OSDN Git Service

/cp
[pf3gnuchains/gcc-fork.git] / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU C++.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009, 2010, 2011
4    Free Software Foundation, Inc.
5    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
6    Rewritten by Jason Merrill (jason@cygnus.com).
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
14
15 GCC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
24 /* Known bugs or deficiencies include:
25
26      all methods must be provided in header files; can't use a source
27      file that contains only the method templates and "just win".  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "tm.h"
33 #include "tree.h"
34 #include "intl.h"
35 #include "pointer-set.h"
36 #include "flags.h"
37 #include "cp-tree.h"
38 #include "c-family/c-common.h"
39 #include "c-family/c-objc.h"
40 #include "cp-objcp-common.h"
41 #include "tree-inline.h"
42 #include "decl.h"
43 #include "output.h"
44 #include "toplev.h"
45 #include "timevar.h"
46 #include "tree-iterator.h"
47 #include "vecprim.h"
48
49 /* The type of functions taking a tree, and some additional data, and
50    returning an int.  */
51 typedef int (*tree_fn_t) (tree, void*);
52
53 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
54    instantiations have been deferred, either because their definitions
55    were not yet available, or because we were putting off doing the work.  */
56 struct GTY ((chain_next ("%h.next"))) pending_template {
57   struct pending_template *next;
58   struct tinst_level *tinst;
59 };
60
61 static GTY(()) struct pending_template *pending_templates;
62 static GTY(()) struct pending_template *last_pending_template;
63
64 int processing_template_parmlist;
65 static int template_header_count;
66
67 static GTY(()) tree saved_trees;
68 static VEC(int,heap) *inline_parm_levels;
69
70 static GTY(()) struct tinst_level *current_tinst_level;
71
72 static GTY(()) tree saved_access_scope;
73
74 /* Live only within one (recursive) call to tsubst_expr.  We use
75    this to pass the statement expression node from the STMT_EXPR
76    to the EXPR_STMT that is its result.  */
77 static tree cur_stmt_expr;
78
79 /* A map from local variable declarations in the body of the template
80    presently being instantiated to the corresponding instantiated
81    local variables.  */
82 static htab_t local_specializations;
83
84 typedef struct GTY(()) spec_entry
85 {
86   tree tmpl;
87   tree args;
88   tree spec;
89 } spec_entry;
90
91 static GTY ((param_is (spec_entry)))
92   htab_t decl_specializations;
93
94 static GTY ((param_is (spec_entry)))
95   htab_t type_specializations;
96
97 /* Contains canonical template parameter types. The vector is indexed by
98    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
99    TREE_LIST, whose TREE_VALUEs contain the canonical template
100    parameters of various types and levels.  */
101 static GTY(()) VEC(tree,gc) *canonical_template_parms;
102
103 #define UNIFY_ALLOW_NONE 0
104 #define UNIFY_ALLOW_MORE_CV_QUAL 1
105 #define UNIFY_ALLOW_LESS_CV_QUAL 2
106 #define UNIFY_ALLOW_DERIVED 4
107 #define UNIFY_ALLOW_INTEGER 8
108 #define UNIFY_ALLOW_OUTER_LEVEL 16
109 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
110 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
111
112 enum template_base_result {
113   tbr_incomplete_type,
114   tbr_ambiguous_baseclass,
115   tbr_success
116 };
117
118 static void push_access_scope (tree);
119 static void pop_access_scope (tree);
120 static void push_deduction_access_scope (tree);
121 static void pop_deduction_access_scope (tree);
122 static bool resolve_overloaded_unification (tree, tree, tree, tree,
123                                             unification_kind_t, int,
124                                             bool);
125 static int try_one_overload (tree, tree, tree, tree, tree,
126                              unification_kind_t, int, bool, bool);
127 static int unify (tree, tree, tree, tree, int, bool);
128 static void add_pending_template (tree);
129 static tree reopen_tinst_level (struct tinst_level *);
130 static tree tsubst_initializer_list (tree, tree);
131 static tree get_class_bindings (tree, tree, tree);
132 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
133                                    bool, bool);
134 static void tsubst_enum (tree, tree, tree);
135 static tree add_to_template_args (tree, tree);
136 static tree add_outermost_template_args (tree, tree);
137 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
138 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
139                                              tree);
140 static int type_unification_real (tree, tree, tree, const tree *,
141                                   unsigned int, int, unification_kind_t, int,
142                                   bool);
143 static void note_template_header (int);
144 static tree convert_nontype_argument_function (tree, tree);
145 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
146 static tree convert_template_argument (tree, tree, tree,
147                                        tsubst_flags_t, int, tree);
148 static int for_each_template_parm (tree, tree_fn_t, void*,
149                                    struct pointer_set_t*, bool);
150 static tree expand_template_argument_pack (tree);
151 static tree build_template_parm_index (int, int, int, int, tree, tree);
152 static bool inline_needs_template_parms (tree);
153 static void push_inline_template_parms_recursive (tree, int);
154 static tree retrieve_local_specialization (tree);
155 static void register_local_specialization (tree, tree);
156 static hashval_t hash_specialization (const void *p);
157 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
158 static int mark_template_parm (tree, void *);
159 static int template_parm_this_level_p (tree, void *);
160 static tree tsubst_friend_function (tree, tree);
161 static tree tsubst_friend_class (tree, tree);
162 static int can_complete_type_without_circularity (tree);
163 static tree get_bindings (tree, tree, tree, bool);
164 static int template_decl_level (tree);
165 static int check_cv_quals_for_unify (int, tree, tree);
166 static void template_parm_level_and_index (tree, int*, int*);
167 static int unify_pack_expansion (tree, tree, tree,
168                                  tree, unification_kind_t, bool, bool);
169 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
170 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
171 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
172 static void regenerate_decl_from_template (tree, tree);
173 static tree most_specialized_class (tree, tree, tsubst_flags_t);
174 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
175 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
176 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
177 static bool check_specialization_scope (void);
178 static tree process_partial_specialization (tree);
179 static void set_current_access_from_decl (tree);
180 static enum template_base_result get_template_base (tree, tree, tree, tree,
181                                                     bool , tree *);
182 static tree try_class_unification (tree, tree, tree, tree, bool);
183 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
184                                            tree, tree);
185 static bool template_template_parm_bindings_ok_p (tree, tree);
186 static int template_args_equal (tree, tree);
187 static void tsubst_default_arguments (tree);
188 static tree for_each_template_parm_r (tree *, int *, void *);
189 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
190 static void copy_default_args_to_explicit_spec (tree);
191 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
192 static int eq_local_specializations (const void *, const void *);
193 static bool dependent_template_arg_p (tree);
194 static bool any_template_arguments_need_structural_equality_p (tree);
195 static bool dependent_type_p_r (tree);
196 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
197 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
198 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
199 static tree tsubst_decl (tree, tree, tsubst_flags_t);
200 static void perform_typedefs_access_check (tree tmpl, tree targs);
201 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
202                                                         location_t);
203 static tree listify (tree);
204 static tree listify_autos (tree, tree);
205 static tree template_parm_to_arg (tree t);
206 static bool arg_from_parm_pack_p (tree, tree);
207 static tree current_template_args (void);
208 static tree fixup_template_type_parm_type (tree, int);
209 static tree fixup_template_parm_index (tree, tree, int);
210 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
211
212 /* Make the current scope suitable for access checking when we are
213    processing T.  T can be FUNCTION_DECL for instantiated function
214    template, or VAR_DECL for static member variable (need by
215    instantiate_decl).  */
216
217 static void
218 push_access_scope (tree t)
219 {
220   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
221               || TREE_CODE (t) == VAR_DECL);
222
223   if (DECL_FRIEND_CONTEXT (t))
224     push_nested_class (DECL_FRIEND_CONTEXT (t));
225   else if (DECL_CLASS_SCOPE_P (t))
226     push_nested_class (DECL_CONTEXT (t));
227   else
228     push_to_top_level ();
229
230   if (TREE_CODE (t) == FUNCTION_DECL)
231     {
232       saved_access_scope = tree_cons
233         (NULL_TREE, current_function_decl, saved_access_scope);
234       current_function_decl = t;
235     }
236 }
237
238 /* Restore the scope set up by push_access_scope.  T is the node we
239    are processing.  */
240
241 static void
242 pop_access_scope (tree t)
243 {
244   if (TREE_CODE (t) == FUNCTION_DECL)
245     {
246       current_function_decl = TREE_VALUE (saved_access_scope);
247       saved_access_scope = TREE_CHAIN (saved_access_scope);
248     }
249
250   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
251     pop_nested_class ();
252   else
253     pop_from_top_level ();
254 }
255
256 /* Do any processing required when DECL (a member template
257    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
258    to DECL, unless it is a specialization, in which case the DECL
259    itself is returned.  */
260
261 tree
262 finish_member_template_decl (tree decl)
263 {
264   if (decl == error_mark_node)
265     return error_mark_node;
266
267   gcc_assert (DECL_P (decl));
268
269   if (TREE_CODE (decl) == TYPE_DECL)
270     {
271       tree type;
272
273       type = TREE_TYPE (decl);
274       if (type == error_mark_node)
275         return error_mark_node;
276       if (MAYBE_CLASS_TYPE_P (type)
277           && CLASSTYPE_TEMPLATE_INFO (type)
278           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
279         {
280           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
281           check_member_template (tmpl);
282           return tmpl;
283         }
284       return NULL_TREE;
285     }
286   else if (TREE_CODE (decl) == FIELD_DECL)
287     error ("data member %qD cannot be a member template", decl);
288   else if (DECL_TEMPLATE_INFO (decl))
289     {
290       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
291         {
292           check_member_template (DECL_TI_TEMPLATE (decl));
293           return DECL_TI_TEMPLATE (decl);
294         }
295       else
296         return decl;
297     }
298   else
299     error ("invalid member template declaration %qD", decl);
300
301   return error_mark_node;
302 }
303
304 /* Create a template info node.  */
305
306 tree
307 build_template_info (tree template_decl, tree template_args)
308 {
309   tree result = make_node (TEMPLATE_INFO);
310   TI_TEMPLATE (result) = template_decl;
311   TI_ARGS (result) = template_args;
312   return result;
313 }
314
315 /* Return the template info node corresponding to T, whatever T is.  */
316
317 tree
318 get_template_info (const_tree t)
319 {
320   tree tinfo = NULL_TREE;
321
322   if (!t || t == error_mark_node)
323     return NULL;
324
325   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
326     tinfo = DECL_TEMPLATE_INFO (t);
327
328   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
329     t = TREE_TYPE (t);
330
331   if (TAGGED_TYPE_P (t))
332     tinfo = TYPE_TEMPLATE_INFO (t);
333   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
334     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
335
336   return tinfo;
337 }
338
339 /* Returns the template nesting level of the indicated class TYPE.
340
341    For example, in:
342      template <class T>
343      struct A
344      {
345        template <class U>
346        struct B {};
347      };
348
349    A<T>::B<U> has depth two, while A<T> has depth one.
350    Both A<T>::B<int> and A<int>::B<U> have depth one, if
351    they are instantiations, not specializations.
352
353    This function is guaranteed to return 0 if passed NULL_TREE so
354    that, for example, `template_class_depth (current_class_type)' is
355    always safe.  */
356
357 int
358 template_class_depth (tree type)
359 {
360   int depth;
361
362   for (depth = 0;
363        type && TREE_CODE (type) != NAMESPACE_DECL;
364        type = (TREE_CODE (type) == FUNCTION_DECL)
365          ? CP_DECL_CONTEXT (type) : CP_TYPE_CONTEXT (type))
366     {
367       tree tinfo = get_template_info (type);
368
369       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
370           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
371         ++depth;
372     }
373
374   return depth;
375 }
376
377 /* Subroutine of maybe_begin_member_template_processing.
378    Returns true if processing DECL needs us to push template parms.  */
379
380 static bool
381 inline_needs_template_parms (tree decl)
382 {
383   if (! DECL_TEMPLATE_INFO (decl))
384     return false;
385
386   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
387           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
388 }
389
390 /* Subroutine of maybe_begin_member_template_processing.
391    Push the template parms in PARMS, starting from LEVELS steps into the
392    chain, and ending at the beginning, since template parms are listed
393    innermost first.  */
394
395 static void
396 push_inline_template_parms_recursive (tree parmlist, int levels)
397 {
398   tree parms = TREE_VALUE (parmlist);
399   int i;
400
401   if (levels > 1)
402     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
403
404   ++processing_template_decl;
405   current_template_parms
406     = tree_cons (size_int (processing_template_decl),
407                  parms, current_template_parms);
408   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
409
410   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
411                NULL);
412   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
413     {
414       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
415
416       if (parm == error_mark_node)
417         continue;
418
419       gcc_assert (DECL_P (parm));
420
421       switch (TREE_CODE (parm))
422         {
423         case TYPE_DECL:
424         case TEMPLATE_DECL:
425           pushdecl (parm);
426           break;
427
428         case PARM_DECL:
429           {
430             /* Make a CONST_DECL as is done in process_template_parm.
431                It is ugly that we recreate this here; the original
432                version built in process_template_parm is no longer
433                available.  */
434             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
435                                     CONST_DECL, DECL_NAME (parm),
436                                     TREE_TYPE (parm));
437             DECL_ARTIFICIAL (decl) = 1;
438             TREE_CONSTANT (decl) = 1;
439             TREE_READONLY (decl) = 1;
440             DECL_INITIAL (decl) = DECL_INITIAL (parm);
441             SET_DECL_TEMPLATE_PARM_P (decl);
442             pushdecl (decl);
443           }
444           break;
445
446         default:
447           gcc_unreachable ();
448         }
449     }
450 }
451
452 /* Restore the template parameter context for a member template or
453    a friend template defined in a class definition.  */
454
455 void
456 maybe_begin_member_template_processing (tree decl)
457 {
458   tree parms;
459   int levels = 0;
460
461   if (inline_needs_template_parms (decl))
462     {
463       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
464       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
465
466       if (DECL_TEMPLATE_SPECIALIZATION (decl))
467         {
468           --levels;
469           parms = TREE_CHAIN (parms);
470         }
471
472       push_inline_template_parms_recursive (parms, levels);
473     }
474
475   /* Remember how many levels of template parameters we pushed so that
476      we can pop them later.  */
477   VEC_safe_push (int, heap, inline_parm_levels, levels);
478 }
479
480 /* Undo the effects of maybe_begin_member_template_processing.  */
481
482 void
483 maybe_end_member_template_processing (void)
484 {
485   int i;
486   int last;
487
488   if (VEC_length (int, inline_parm_levels) == 0)
489     return;
490
491   last = VEC_pop (int, inline_parm_levels);
492   for (i = 0; i < last; ++i)
493     {
494       --processing_template_decl;
495       current_template_parms = TREE_CHAIN (current_template_parms);
496       poplevel (0, 0, 0);
497     }
498 }
499
500 /* Return a new template argument vector which contains all of ARGS,
501    but has as its innermost set of arguments the EXTRA_ARGS.  */
502
503 static tree
504 add_to_template_args (tree args, tree extra_args)
505 {
506   tree new_args;
507   int extra_depth;
508   int i;
509   int j;
510
511   if (args == NULL_TREE || extra_args == error_mark_node)
512     return extra_args;
513
514   extra_depth = TMPL_ARGS_DEPTH (extra_args);
515   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
516
517   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
518     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
519
520   for (j = 1; j <= extra_depth; ++j, ++i)
521     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
522
523   return new_args;
524 }
525
526 /* Like add_to_template_args, but only the outermost ARGS are added to
527    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
528    (EXTRA_ARGS) levels are added.  This function is used to combine
529    the template arguments from a partial instantiation with the
530    template arguments used to attain the full instantiation from the
531    partial instantiation.  */
532
533 static tree
534 add_outermost_template_args (tree args, tree extra_args)
535 {
536   tree new_args;
537
538   /* If there are more levels of EXTRA_ARGS than there are ARGS,
539      something very fishy is going on.  */
540   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
541
542   /* If *all* the new arguments will be the EXTRA_ARGS, just return
543      them.  */
544   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
545     return extra_args;
546
547   /* For the moment, we make ARGS look like it contains fewer levels.  */
548   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
549
550   new_args = add_to_template_args (args, extra_args);
551
552   /* Now, we restore ARGS to its full dimensions.  */
553   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
554
555   return new_args;
556 }
557
558 /* Return the N levels of innermost template arguments from the ARGS.  */
559
560 tree
561 get_innermost_template_args (tree args, int n)
562 {
563   tree new_args;
564   int extra_levels;
565   int i;
566
567   gcc_assert (n >= 0);
568
569   /* If N is 1, just return the innermost set of template arguments.  */
570   if (n == 1)
571     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
572
573   /* If we're not removing anything, just return the arguments we were
574      given.  */
575   extra_levels = TMPL_ARGS_DEPTH (args) - n;
576   gcc_assert (extra_levels >= 0);
577   if (extra_levels == 0)
578     return args;
579
580   /* Make a new set of arguments, not containing the outer arguments.  */
581   new_args = make_tree_vec (n);
582   for (i = 1; i <= n; ++i)
583     SET_TMPL_ARGS_LEVEL (new_args, i,
584                          TMPL_ARGS_LEVEL (args, i + extra_levels));
585
586   return new_args;
587 }
588
589 /* The inverse of get_innermost_template_args: Return all but the innermost
590    EXTRA_LEVELS levels of template arguments from the ARGS.  */
591
592 static tree
593 strip_innermost_template_args (tree args, int extra_levels)
594 {
595   tree new_args;
596   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
597   int i;
598
599   gcc_assert (n >= 0);
600
601   /* If N is 1, just return the outermost set of template arguments.  */
602   if (n == 1)
603     return TMPL_ARGS_LEVEL (args, 1);
604
605   /* If we're not removing anything, just return the arguments we were
606      given.  */
607   gcc_assert (extra_levels >= 0);
608   if (extra_levels == 0)
609     return args;
610
611   /* Make a new set of arguments, not containing the inner arguments.  */
612   new_args = make_tree_vec (n);
613   for (i = 1; i <= n; ++i)
614     SET_TMPL_ARGS_LEVEL (new_args, i,
615                          TMPL_ARGS_LEVEL (args, i));
616
617   return new_args;
618 }
619
620 /* We've got a template header coming up; push to a new level for storing
621    the parms.  */
622
623 void
624 begin_template_parm_list (void)
625 {
626   /* We use a non-tag-transparent scope here, which causes pushtag to
627      put tags in this scope, rather than in the enclosing class or
628      namespace scope.  This is the right thing, since we want
629      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
630      global template class, push_template_decl handles putting the
631      TEMPLATE_DECL into top-level scope.  For a nested template class,
632      e.g.:
633
634        template <class T> struct S1 {
635          template <class T> struct S2 {};
636        };
637
638      pushtag contains special code to call pushdecl_with_scope on the
639      TEMPLATE_DECL for S2.  */
640   begin_scope (sk_template_parms, NULL);
641   ++processing_template_decl;
642   ++processing_template_parmlist;
643   note_template_header (0);
644 }
645
646 /* This routine is called when a specialization is declared.  If it is
647    invalid to declare a specialization here, an error is reported and
648    false is returned, otherwise this routine will return true.  */
649
650 static bool
651 check_specialization_scope (void)
652 {
653   tree scope = current_scope ();
654
655   /* [temp.expl.spec]
656
657      An explicit specialization shall be declared in the namespace of
658      which the template is a member, or, for member templates, in the
659      namespace of which the enclosing class or enclosing class
660      template is a member.  An explicit specialization of a member
661      function, member class or static data member of a class template
662      shall be declared in the namespace of which the class template
663      is a member.  */
664   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
665     {
666       error ("explicit specialization in non-namespace scope %qD", scope);
667       return false;
668     }
669
670   /* [temp.expl.spec]
671
672      In an explicit specialization declaration for a member of a class
673      template or a member template that appears in namespace scope,
674      the member template and some of its enclosing class templates may
675      remain unspecialized, except that the declaration shall not
676      explicitly specialize a class member template if its enclosing
677      class templates are not explicitly specialized as well.  */
678   if (current_template_parms)
679     {
680       error ("enclosing class templates are not explicitly specialized");
681       return false;
682     }
683
684   return true;
685 }
686
687 /* We've just seen template <>.  */
688
689 bool
690 begin_specialization (void)
691 {
692   begin_scope (sk_template_spec, NULL);
693   note_template_header (1);
694   return check_specialization_scope ();
695 }
696
697 /* Called at then end of processing a declaration preceded by
698    template<>.  */
699
700 void
701 end_specialization (void)
702 {
703   finish_scope ();
704   reset_specialization ();
705 }
706
707 /* Any template <>'s that we have seen thus far are not referring to a
708    function specialization.  */
709
710 void
711 reset_specialization (void)
712 {
713   processing_specialization = 0;
714   template_header_count = 0;
715 }
716
717 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
718    it was of the form template <>.  */
719
720 static void
721 note_template_header (int specialization)
722 {
723   processing_specialization = specialization;
724   template_header_count++;
725 }
726
727 /* We're beginning an explicit instantiation.  */
728
729 void
730 begin_explicit_instantiation (void)
731 {
732   gcc_assert (!processing_explicit_instantiation);
733   processing_explicit_instantiation = true;
734 }
735
736
737 void
738 end_explicit_instantiation (void)
739 {
740   gcc_assert (processing_explicit_instantiation);
741   processing_explicit_instantiation = false;
742 }
743
744 /* An explicit specialization or partial specialization TMPL is being
745    declared.  Check that the namespace in which the specialization is
746    occurring is permissible.  Returns false iff it is invalid to
747    specialize TMPL in the current namespace.  */
748
749 static bool
750 check_specialization_namespace (tree tmpl)
751 {
752   tree tpl_ns = decl_namespace_context (tmpl);
753
754   /* [tmpl.expl.spec]
755
756      An explicit specialization shall be declared in the namespace of
757      which the template is a member, or, for member templates, in the
758      namespace of which the enclosing class or enclosing class
759      template is a member.  An explicit specialization of a member
760      function, member class or static data member of a class template
761      shall be declared in the namespace of which the class template is
762      a member.  */
763   if (current_scope() != DECL_CONTEXT (tmpl)
764       && !at_namespace_scope_p ())
765     {
766       error ("specialization of %qD must appear at namespace scope", tmpl);
767       return false;
768     }
769   if (is_associated_namespace (current_namespace, tpl_ns))
770     /* Same or super-using namespace.  */
771     return true;
772   else
773     {
774       permerror (input_location, "specialization of %qD in different namespace", tmpl);
775       permerror (input_location, "  from definition of %q+#D", tmpl);
776       return false;
777     }
778 }
779
780 /* SPEC is an explicit instantiation.  Check that it is valid to
781    perform this explicit instantiation in the current namespace.  */
782
783 static void
784 check_explicit_instantiation_namespace (tree spec)
785 {
786   tree ns;
787
788   /* DR 275: An explicit instantiation shall appear in an enclosing
789      namespace of its template.  */
790   ns = decl_namespace_context (spec);
791   if (!is_ancestor (current_namespace, ns))
792     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
793                "(which does not enclose namespace %qD)",
794                spec, current_namespace, ns);
795 }
796
797 /* The TYPE is being declared.  If it is a template type, that means it
798    is a partial specialization.  Do appropriate error-checking.  */
799
800 tree
801 maybe_process_partial_specialization (tree type)
802 {
803   tree context;
804
805   if (type == error_mark_node)
806     return error_mark_node;
807
808   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
809     {
810       error ("name of class shadows template template parameter %qD",
811              TYPE_NAME (type));
812       return error_mark_node;
813     }
814
815   context = TYPE_CONTEXT (type);
816
817   if ((CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
818       /* Consider non-class instantiations of alias templates as
819          well.  */
820       || (TYPE_P (type)
821           && TYPE_TEMPLATE_INFO (type)
822           && DECL_LANG_SPECIFIC (TYPE_NAME (type))
823           && DECL_USE_TEMPLATE (TYPE_NAME (type))))
824     {
825       /* This is for ordinary explicit specialization and partial
826          specialization of a template class such as:
827
828            template <> class C<int>;
829
830          or:
831
832            template <class T> class C<T*>;
833
834          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
835
836       if (CLASS_TYPE_P (type)
837           && CLASSTYPE_IMPLICIT_INSTANTIATION (type)
838           && !COMPLETE_TYPE_P (type))
839         {
840           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
841           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
842           if (processing_template_decl)
843             {
844               if (push_template_decl (TYPE_MAIN_DECL (type))
845                   == error_mark_node)
846                 return error_mark_node;
847             }
848         }
849       else if (CLASS_TYPE_P (type)
850                && CLASSTYPE_TEMPLATE_INSTANTIATION (type))
851         error ("specialization of %qT after instantiation", type);
852
853       if (DECL_ALIAS_TEMPLATE_P (TYPE_TI_TEMPLATE (type)))
854         {
855           error ("partial specialization of alias template %qD",
856                  TYPE_TI_TEMPLATE (type));
857           return error_mark_node;
858         }
859     }
860   else if (CLASS_TYPE_P (type)
861            && !CLASSTYPE_USE_TEMPLATE (type)
862            && CLASSTYPE_TEMPLATE_INFO (type)
863            && context && CLASS_TYPE_P (context)
864            && CLASSTYPE_TEMPLATE_INFO (context))
865     {
866       /* This is for an explicit specialization of member class
867          template according to [temp.expl.spec/18]:
868
869            template <> template <class U> class C<int>::D;
870
871          The context `C<int>' must be an implicit instantiation.
872          Otherwise this is just a member class template declared
873          earlier like:
874
875            template <> class C<int> { template <class U> class D; };
876            template <> template <class U> class C<int>::D;
877
878          In the first case, `C<int>::D' is a specialization of `C<T>::D'
879          while in the second case, `C<int>::D' is a primary template
880          and `C<T>::D' may not exist.  */
881
882       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
883           && !COMPLETE_TYPE_P (type))
884         {
885           tree t;
886           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
887
888           if (current_namespace
889               != decl_namespace_context (tmpl))
890             {
891               permerror (input_location, "specializing %q#T in different namespace", type);
892               permerror (input_location, "  from definition of %q+#D", tmpl);
893             }
894
895           /* Check for invalid specialization after instantiation:
896
897                template <> template <> class C<int>::D<int>;
898                template <> template <class U> class C<int>::D;  */
899
900           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
901                t; t = TREE_CHAIN (t))
902             {
903               tree inst = TREE_VALUE (t);
904               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
905                 {
906                   /* We already have a full specialization of this partial
907                      instantiation.  Reassign it to the new member
908                      specialization template.  */
909                   spec_entry elt;
910                   spec_entry *entry;
911                   void **slot;
912
913                   elt.tmpl = most_general_template (tmpl);
914                   elt.args = CLASSTYPE_TI_ARGS (inst);
915                   elt.spec = inst;
916
917                   htab_remove_elt (type_specializations, &elt);
918
919                   elt.tmpl = tmpl;
920                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
921
922                   slot = htab_find_slot (type_specializations, &elt, INSERT);
923                   entry = ggc_alloc_spec_entry ();
924                   *entry = elt;
925                   *slot = entry;
926                 }
927               else if (COMPLETE_OR_OPEN_TYPE_P (inst))
928                 /* But if we've had an implicit instantiation, that's a
929                    problem ([temp.expl.spec]/6).  */
930                 error ("specialization %qT after instantiation %qT",
931                        type, inst);
932             }
933
934           /* Mark TYPE as a specialization.  And as a result, we only
935              have one level of template argument for the innermost
936              class template.  */
937           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
938           CLASSTYPE_TI_ARGS (type)
939             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
940         }
941     }
942   else if (processing_specialization)
943     {
944        /* Someday C++0x may allow for enum template specialization.  */
945       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
946           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
947         pedwarn (input_location, OPT_pedantic, "template specialization "
948                  "of %qD not allowed by ISO C++", type);
949       else
950         {
951           error ("explicit specialization of non-template %qT", type);
952           return error_mark_node;
953         }
954     }
955
956   return type;
957 }
958
959 /* Returns nonzero if we can optimize the retrieval of specializations
960    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
961    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
962
963 static inline bool
964 optimize_specialization_lookup_p (tree tmpl)
965 {
966   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
967           && DECL_CLASS_SCOPE_P (tmpl)
968           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
969              parameter.  */
970           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
971           /* The optimized lookup depends on the fact that the
972              template arguments for the member function template apply
973              purely to the containing class, which is not true if the
974              containing class is an explicit or partial
975              specialization.  */
976           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
977           && !DECL_MEMBER_TEMPLATE_P (tmpl)
978           && !DECL_CONV_FN_P (tmpl)
979           /* It is possible to have a template that is not a member
980              template and is not a member of a template class:
981
982              template <typename T>
983              struct S { friend A::f(); };
984
985              Here, the friend function is a template, but the context does
986              not have template information.  The optimized lookup relies
987              on having ARGS be the template arguments for both the class
988              and the function template.  */
989           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
990 }
991
992 /* Retrieve the specialization (in the sense of [temp.spec] - a
993    specialization is either an instantiation or an explicit
994    specialization) of TMPL for the given template ARGS.  If there is
995    no such specialization, return NULL_TREE.  The ARGS are a vector of
996    arguments, or a vector of vectors of arguments, in the case of
997    templates with more than one level of parameters.
998
999    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1000    then we search for a partial specialization matching ARGS.  This
1001    parameter is ignored if TMPL is not a class template.  */
1002
1003 static tree
1004 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1005 {
1006   if (args == error_mark_node)
1007     return NULL_TREE;
1008
1009   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1010
1011   /* There should be as many levels of arguments as there are
1012      levels of parameters.  */
1013   gcc_assert (TMPL_ARGS_DEPTH (args)
1014               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
1015
1016   if (optimize_specialization_lookup_p (tmpl))
1017     {
1018       tree class_template;
1019       tree class_specialization;
1020       VEC(tree,gc) *methods;
1021       tree fns;
1022       int idx;
1023
1024       /* The template arguments actually apply to the containing
1025          class.  Find the class specialization with those
1026          arguments.  */
1027       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1028       class_specialization
1029         = retrieve_specialization (class_template, args, 0);
1030       if (!class_specialization)
1031         return NULL_TREE;
1032       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
1033          for the specialization.  */
1034       idx = class_method_index_for_fn (class_specialization, tmpl);
1035       if (idx == -1)
1036         return NULL_TREE;
1037       /* Iterate through the methods with the indicated name, looking
1038          for the one that has an instance of TMPL.  */
1039       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1040       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1041         {
1042           tree fn = OVL_CURRENT (fns);
1043           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1044               /* using-declarations can add base methods to the method vec,
1045                  and we don't want those here.  */
1046               && DECL_CONTEXT (fn) == class_specialization)
1047             return fn;
1048         }
1049       return NULL_TREE;
1050     }
1051   else
1052     {
1053       spec_entry *found;
1054       spec_entry elt;
1055       htab_t specializations;
1056
1057       elt.tmpl = tmpl;
1058       elt.args = args;
1059       elt.spec = NULL_TREE;
1060
1061       if (DECL_CLASS_TEMPLATE_P (tmpl))
1062         specializations = type_specializations;
1063       else
1064         specializations = decl_specializations;
1065
1066       if (hash == 0)
1067         hash = hash_specialization (&elt);
1068       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1069       if (found)
1070         return found->spec;
1071     }
1072
1073   return NULL_TREE;
1074 }
1075
1076 /* Like retrieve_specialization, but for local declarations.  */
1077
1078 static tree
1079 retrieve_local_specialization (tree tmpl)
1080 {
1081   tree spec;
1082
1083   if (local_specializations == NULL)
1084     return NULL_TREE;
1085
1086   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1087                                      htab_hash_pointer (tmpl));
1088   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1089 }
1090
1091 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1092
1093 int
1094 is_specialization_of (tree decl, tree tmpl)
1095 {
1096   tree t;
1097
1098   if (TREE_CODE (decl) == FUNCTION_DECL)
1099     {
1100       for (t = decl;
1101            t != NULL_TREE;
1102            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1103         if (t == tmpl)
1104           return 1;
1105     }
1106   else
1107     {
1108       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1109
1110       for (t = TREE_TYPE (decl);
1111            t != NULL_TREE;
1112            t = CLASSTYPE_USE_TEMPLATE (t)
1113              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1114         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1115           return 1;
1116     }
1117
1118   return 0;
1119 }
1120
1121 /* Returns nonzero iff DECL is a specialization of friend declaration
1122    FRIEND_DECL according to [temp.friend].  */
1123
1124 bool
1125 is_specialization_of_friend (tree decl, tree friend_decl)
1126 {
1127   bool need_template = true;
1128   int template_depth;
1129
1130   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1131               || TREE_CODE (decl) == TYPE_DECL);
1132
1133   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1134      of a template class, we want to check if DECL is a specialization
1135      if this.  */
1136   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1137       && DECL_TEMPLATE_INFO (friend_decl)
1138       && !DECL_USE_TEMPLATE (friend_decl))
1139     {
1140       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1141       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1142       need_template = false;
1143     }
1144   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1145            && !PRIMARY_TEMPLATE_P (friend_decl))
1146     need_template = false;
1147
1148   /* There is nothing to do if this is not a template friend.  */
1149   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1150     return false;
1151
1152   if (is_specialization_of (decl, friend_decl))
1153     return true;
1154
1155   /* [temp.friend/6]
1156      A member of a class template may be declared to be a friend of a
1157      non-template class.  In this case, the corresponding member of
1158      every specialization of the class template is a friend of the
1159      class granting friendship.
1160
1161      For example, given a template friend declaration
1162
1163        template <class T> friend void A<T>::f();
1164
1165      the member function below is considered a friend
1166
1167        template <> struct A<int> {
1168          void f();
1169        };
1170
1171      For this type of template friend, TEMPLATE_DEPTH below will be
1172      nonzero.  To determine if DECL is a friend of FRIEND, we first
1173      check if the enclosing class is a specialization of another.  */
1174
1175   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1176   if (template_depth
1177       && DECL_CLASS_SCOPE_P (decl)
1178       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1179                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1180     {
1181       /* Next, we check the members themselves.  In order to handle
1182          a few tricky cases, such as when FRIEND_DECL's are
1183
1184            template <class T> friend void A<T>::g(T t);
1185            template <class T> template <T t> friend void A<T>::h();
1186
1187          and DECL's are
1188
1189            void A<int>::g(int);
1190            template <int> void A<int>::h();
1191
1192          we need to figure out ARGS, the template arguments from
1193          the context of DECL.  This is required for template substitution
1194          of `T' in the function parameter of `g' and template parameter
1195          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1196
1197       tree context = DECL_CONTEXT (decl);
1198       tree args = NULL_TREE;
1199       int current_depth = 0;
1200
1201       while (current_depth < template_depth)
1202         {
1203           if (CLASSTYPE_TEMPLATE_INFO (context))
1204             {
1205               if (current_depth == 0)
1206                 args = TYPE_TI_ARGS (context);
1207               else
1208                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1209               current_depth++;
1210             }
1211           context = TYPE_CONTEXT (context);
1212         }
1213
1214       if (TREE_CODE (decl) == FUNCTION_DECL)
1215         {
1216           bool is_template;
1217           tree friend_type;
1218           tree decl_type;
1219           tree friend_args_type;
1220           tree decl_args_type;
1221
1222           /* Make sure that both DECL and FRIEND_DECL are templates or
1223              non-templates.  */
1224           is_template = DECL_TEMPLATE_INFO (decl)
1225                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1226           if (need_template ^ is_template)
1227             return false;
1228           else if (is_template)
1229             {
1230               /* If both are templates, check template parameter list.  */
1231               tree friend_parms
1232                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1233                                          args, tf_none);
1234               if (!comp_template_parms
1235                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1236                       friend_parms))
1237                 return false;
1238
1239               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1240             }
1241           else
1242             decl_type = TREE_TYPE (decl);
1243
1244           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1245                                               tf_none, NULL_TREE);
1246           if (friend_type == error_mark_node)
1247             return false;
1248
1249           /* Check if return types match.  */
1250           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1251             return false;
1252
1253           /* Check if function parameter types match, ignoring the
1254              `this' parameter.  */
1255           friend_args_type = TYPE_ARG_TYPES (friend_type);
1256           decl_args_type = TYPE_ARG_TYPES (decl_type);
1257           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1258             friend_args_type = TREE_CHAIN (friend_args_type);
1259           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1260             decl_args_type = TREE_CHAIN (decl_args_type);
1261
1262           return compparms (decl_args_type, friend_args_type);
1263         }
1264       else
1265         {
1266           /* DECL is a TYPE_DECL */
1267           bool is_template;
1268           tree decl_type = TREE_TYPE (decl);
1269
1270           /* Make sure that both DECL and FRIEND_DECL are templates or
1271              non-templates.  */
1272           is_template
1273             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1274               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1275
1276           if (need_template ^ is_template)
1277             return false;
1278           else if (is_template)
1279             {
1280               tree friend_parms;
1281               /* If both are templates, check the name of the two
1282                  TEMPLATE_DECL's first because is_friend didn't.  */
1283               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1284                   != DECL_NAME (friend_decl))
1285                 return false;
1286
1287               /* Now check template parameter list.  */
1288               friend_parms
1289                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1290                                          args, tf_none);
1291               return comp_template_parms
1292                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1293                  friend_parms);
1294             }
1295           else
1296             return (DECL_NAME (decl)
1297                     == DECL_NAME (friend_decl));
1298         }
1299     }
1300   return false;
1301 }
1302
1303 /* Register the specialization SPEC as a specialization of TMPL with
1304    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1305    is actually just a friend declaration.  Returns SPEC, or an
1306    equivalent prior declaration, if available.  */
1307
1308 static tree
1309 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1310                          hashval_t hash)
1311 {
1312   tree fn;
1313   void **slot = NULL;
1314   spec_entry elt;
1315
1316   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1317
1318   if (TREE_CODE (spec) == FUNCTION_DECL
1319       && uses_template_parms (DECL_TI_ARGS (spec)))
1320     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1321        register it; we want the corresponding TEMPLATE_DECL instead.
1322        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1323        the more obvious `uses_template_parms (spec)' to avoid problems
1324        with default function arguments.  In particular, given
1325        something like this:
1326
1327           template <class T> void f(T t1, T t = T())
1328
1329        the default argument expression is not substituted for in an
1330        instantiation unless and until it is actually needed.  */
1331     return spec;
1332
1333   if (optimize_specialization_lookup_p (tmpl))
1334     /* We don't put these specializations in the hash table, but we might
1335        want to give an error about a mismatch.  */
1336     fn = retrieve_specialization (tmpl, args, 0);
1337   else
1338     {
1339       elt.tmpl = tmpl;
1340       elt.args = args;
1341       elt.spec = spec;
1342
1343       if (hash == 0)
1344         hash = hash_specialization (&elt);
1345
1346       slot =
1347         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1348       if (*slot)
1349         fn = ((spec_entry *) *slot)->spec;
1350       else
1351         fn = NULL_TREE;
1352     }
1353
1354   /* We can sometimes try to re-register a specialization that we've
1355      already got.  In particular, regenerate_decl_from_template calls
1356      duplicate_decls which will update the specialization list.  But,
1357      we'll still get called again here anyhow.  It's more convenient
1358      to simply allow this than to try to prevent it.  */
1359   if (fn == spec)
1360     return spec;
1361   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1362     {
1363       if (DECL_TEMPLATE_INSTANTIATION (fn))
1364         {
1365           if (DECL_ODR_USED (fn)
1366               || DECL_EXPLICIT_INSTANTIATION (fn))
1367             {
1368               error ("specialization of %qD after instantiation",
1369                      fn);
1370               return error_mark_node;
1371             }
1372           else
1373             {
1374               tree clone;
1375               /* This situation should occur only if the first
1376                  specialization is an implicit instantiation, the
1377                  second is an explicit specialization, and the
1378                  implicit instantiation has not yet been used.  That
1379                  situation can occur if we have implicitly
1380                  instantiated a member function and then specialized
1381                  it later.
1382
1383                  We can also wind up here if a friend declaration that
1384                  looked like an instantiation turns out to be a
1385                  specialization:
1386
1387                    template <class T> void foo(T);
1388                    class S { friend void foo<>(int) };
1389                    template <> void foo(int);
1390
1391                  We transform the existing DECL in place so that any
1392                  pointers to it become pointers to the updated
1393                  declaration.
1394
1395                  If there was a definition for the template, but not
1396                  for the specialization, we want this to look as if
1397                  there were no definition, and vice versa.  */
1398               DECL_INITIAL (fn) = NULL_TREE;
1399               duplicate_decls (spec, fn, is_friend);
1400               /* The call to duplicate_decls will have applied
1401                  [temp.expl.spec]:
1402
1403                    An explicit specialization of a function template
1404                    is inline only if it is explicitly declared to be,
1405                    and independently of whether its function template
1406                    is.
1407
1408                 to the primary function; now copy the inline bits to
1409                 the various clones.  */
1410               FOR_EACH_CLONE (clone, fn)
1411                 {
1412                   DECL_DECLARED_INLINE_P (clone)
1413                     = DECL_DECLARED_INLINE_P (fn);
1414                   DECL_SOURCE_LOCATION (clone)
1415                     = DECL_SOURCE_LOCATION (fn);
1416                 }
1417               check_specialization_namespace (fn);
1418
1419               return fn;
1420             }
1421         }
1422       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1423         {
1424           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1425             /* Dup decl failed, but this is a new definition. Set the
1426                line number so any errors match this new
1427                definition.  */
1428             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1429
1430           return fn;
1431         }
1432     }
1433   else if (fn)
1434     return duplicate_decls (spec, fn, is_friend);
1435
1436   /* A specialization must be declared in the same namespace as the
1437      template it is specializing.  */
1438   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1439       && !check_specialization_namespace (tmpl))
1440     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1441
1442   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1443     {
1444       spec_entry *entry = ggc_alloc_spec_entry ();
1445       gcc_assert (tmpl && args && spec);
1446       *entry = elt;
1447       *slot = entry;
1448       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1449           && PRIMARY_TEMPLATE_P (tmpl)
1450           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1451         /* TMPL is a forward declaration of a template function; keep a list
1452            of all specializations in case we need to reassign them to a friend
1453            template later in tsubst_friend_function.  */
1454         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1455           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1456     }
1457
1458   return spec;
1459 }
1460
1461 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1462    TMPL and ARGS members, ignores SPEC.  */
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
1470   return (e1->tmpl == e2->tmpl
1471           && comp_template_args (e1->args, e2->args));
1472 }
1473
1474 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1475
1476 static hashval_t
1477 hash_tmpl_and_args (tree tmpl, tree args)
1478 {
1479   hashval_t val = DECL_UID (tmpl);
1480   return iterative_hash_template_arg (args, val);
1481 }
1482
1483 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1484    ignoring SPEC.  */
1485
1486 static hashval_t
1487 hash_specialization (const void *p)
1488 {
1489   const spec_entry *e = (const spec_entry *)p;
1490   return hash_tmpl_and_args (e->tmpl, e->args);
1491 }
1492
1493 /* Recursively calculate a hash value for a template argument ARG, for use
1494    in the hash tables of template specializations.  */
1495
1496 hashval_t
1497 iterative_hash_template_arg (tree arg, hashval_t val)
1498 {
1499   unsigned HOST_WIDE_INT i;
1500   enum tree_code code;
1501   char tclass;
1502
1503   if (arg == NULL_TREE)
1504     return iterative_hash_object (arg, val);
1505
1506   if (!TYPE_P (arg))
1507     STRIP_NOPS (arg);
1508
1509   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1510     /* We can get one of these when re-hashing a previous entry in the middle
1511        of substituting into a pack expansion.  Just look through it.  */
1512     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1513
1514   code = TREE_CODE (arg);
1515   tclass = TREE_CODE_CLASS (code);
1516
1517   val = iterative_hash_object (code, val);
1518
1519   switch (code)
1520     {
1521     case ERROR_MARK:
1522       return val;
1523
1524     case IDENTIFIER_NODE:
1525       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1526
1527     case TREE_VEC:
1528       {
1529         int i, len = TREE_VEC_LENGTH (arg);
1530         for (i = 0; i < len; ++i)
1531           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1532         return val;
1533       }
1534
1535     case TYPE_PACK_EXPANSION:
1536     case EXPR_PACK_EXPANSION:
1537       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1538
1539     case TYPE_ARGUMENT_PACK:
1540     case NONTYPE_ARGUMENT_PACK:
1541       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1542
1543     case TREE_LIST:
1544       for (; arg; arg = TREE_CHAIN (arg))
1545         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1546       return val;
1547
1548     case OVERLOAD:
1549       for (; arg; arg = OVL_NEXT (arg))
1550         val = iterative_hash_template_arg (OVL_CURRENT (arg), val);
1551       return val;
1552
1553     case CONSTRUCTOR:
1554       {
1555         tree field, value;
1556         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1557           {
1558             val = iterative_hash_template_arg (field, val);
1559             val = iterative_hash_template_arg (value, val);
1560           }
1561         return val;
1562       }
1563
1564     case PARM_DECL:
1565       if (!DECL_ARTIFICIAL (arg))
1566         {
1567           val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1568           val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1569         }
1570       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1571
1572     case TARGET_EXPR:
1573       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1574
1575     case PTRMEM_CST:
1576       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1577       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1578
1579     case TEMPLATE_PARM_INDEX:
1580       val = iterative_hash_template_arg
1581         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1582       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1583       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1584
1585     case TRAIT_EXPR:
1586       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1587       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1588       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1589
1590     case BASELINK:
1591       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1592                                          val);
1593       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1594                                           val);
1595
1596     case MODOP_EXPR:
1597       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1598       code = TREE_CODE (TREE_OPERAND (arg, 1));
1599       val = iterative_hash_object (code, val);
1600       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1601
1602     case LAMBDA_EXPR:
1603       /* A lambda can't appear in a template arg, but don't crash on
1604          erroneous input.  */
1605       gcc_assert (seen_error ());
1606       return val;
1607
1608     case CAST_EXPR:
1609     case IMPLICIT_CONV_EXPR:
1610     case STATIC_CAST_EXPR:
1611     case REINTERPRET_CAST_EXPR:
1612     case CONST_CAST_EXPR:
1613     case DYNAMIC_CAST_EXPR:
1614     case NEW_EXPR:
1615       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1616       /* Now hash operands as usual.  */
1617       break;
1618
1619     default:
1620       break;
1621     }
1622
1623   switch (tclass)
1624     {
1625     case tcc_type:
1626       if (TYPE_CANONICAL (arg))
1627         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1628                                       val);
1629       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1630         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1631       /* Otherwise just compare the types during lookup.  */
1632       return val;
1633
1634     case tcc_declaration:
1635     case tcc_constant:
1636       return iterative_hash_expr (arg, val);
1637
1638     default:
1639       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1640       {
1641         unsigned n = cp_tree_operand_length (arg);
1642         for (i = 0; i < n; ++i)
1643           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1644         return val;
1645       }
1646     }
1647   gcc_unreachable ();
1648   return 0;
1649 }
1650
1651 /* Unregister the specialization SPEC as a specialization of TMPL.
1652    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1653    if the SPEC was listed as a specialization of TMPL.
1654
1655    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1656
1657 bool
1658 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1659 {
1660   spec_entry *entry;
1661   spec_entry elt;
1662
1663   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1664   elt.args = TI_ARGS (tinfo);
1665   elt.spec = NULL_TREE;
1666
1667   entry = (spec_entry *) htab_find (decl_specializations, &elt);
1668   if (entry != NULL)
1669     {
1670       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1671       gcc_assert (new_spec != NULL_TREE);
1672       entry->spec = new_spec;
1673       return 1;
1674     }
1675
1676   return 0;
1677 }
1678
1679 /* Compare an entry in the local specializations hash table P1 (which
1680    is really a pointer to a TREE_LIST) with P2 (which is really a
1681    DECL).  */
1682
1683 static int
1684 eq_local_specializations (const void *p1, const void *p2)
1685 {
1686   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1687 }
1688
1689 /* Hash P1, an entry in the local specializations table.  */
1690
1691 static hashval_t
1692 hash_local_specialization (const void* p1)
1693 {
1694   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1695 }
1696
1697 /* Like register_specialization, but for local declarations.  We are
1698    registering SPEC, an instantiation of TMPL.  */
1699
1700 static void
1701 register_local_specialization (tree spec, tree tmpl)
1702 {
1703   void **slot;
1704
1705   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1706                                    htab_hash_pointer (tmpl), INSERT);
1707   *slot = build_tree_list (spec, tmpl);
1708 }
1709
1710 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1711    specialized class.  */
1712
1713 bool
1714 explicit_class_specialization_p (tree type)
1715 {
1716   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1717     return false;
1718   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1719 }
1720
1721 /* Print the list of functions at FNS, going through all the overloads
1722    for each element of the list.  Alternatively, FNS can not be a
1723    TREE_LIST, in which case it will be printed together with all the
1724    overloads.
1725
1726    MORE and *STR should respectively be FALSE and NULL when the function
1727    is called from the outside.  They are used internally on recursive
1728    calls.  print_candidates manages the two parameters and leaves NULL
1729    in *STR when it ends.  */
1730
1731 static void
1732 print_candidates_1 (tree fns, bool more, const char **str)
1733 {
1734   tree fn, fn2;
1735   char *spaces = NULL;
1736
1737   for (fn = fns; fn; fn = OVL_NEXT (fn))
1738     if (TREE_CODE (fn) == TREE_LIST)
1739       {
1740         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1741           print_candidates_1 (TREE_VALUE (fn2),
1742                               TREE_CHAIN (fn2) || more, str);
1743       }
1744     else
1745       {
1746         if (!*str)
1747           {
1748             /* Pick the prefix string.  */
1749             if (!more && !OVL_NEXT (fns))
1750               {
1751                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1752                 continue;
1753               }
1754
1755             *str = _("candidates are:");
1756             spaces = get_spaces (*str);
1757           }
1758         error ("%s %+#D", *str, OVL_CURRENT (fn));
1759         *str = spaces ? spaces : *str;
1760       }
1761
1762   if (!more)
1763     {
1764       free (spaces);
1765       *str = NULL;
1766     }
1767 }
1768
1769 /* Print the list of candidate FNS in an error message.  FNS can also
1770    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1771
1772 void
1773 print_candidates (tree fns)
1774 {
1775   const char *str = NULL;
1776   print_candidates_1 (fns, false, &str);
1777   gcc_assert (str == NULL);
1778 }
1779
1780 /* Returns the template (one of the functions given by TEMPLATE_ID)
1781    which can be specialized to match the indicated DECL with the
1782    explicit template args given in TEMPLATE_ID.  The DECL may be
1783    NULL_TREE if none is available.  In that case, the functions in
1784    TEMPLATE_ID are non-members.
1785
1786    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1787    specialization of a member template.
1788
1789    The TEMPLATE_COUNT is the number of references to qualifying
1790    template classes that appeared in the name of the function. See
1791    check_explicit_specialization for a more accurate description.
1792
1793    TSK indicates what kind of template declaration (if any) is being
1794    declared.  TSK_TEMPLATE indicates that the declaration given by
1795    DECL, though a FUNCTION_DECL, has template parameters, and is
1796    therefore a template function.
1797
1798    The template args (those explicitly specified and those deduced)
1799    are output in a newly created vector *TARGS_OUT.
1800
1801    If it is impossible to determine the result, an error message is
1802    issued.  The error_mark_node is returned to indicate failure.  */
1803
1804 static tree
1805 determine_specialization (tree template_id,
1806                           tree decl,
1807                           tree* targs_out,
1808                           int need_member_template,
1809                           int template_count,
1810                           tmpl_spec_kind tsk)
1811 {
1812   tree fns;
1813   tree targs;
1814   tree explicit_targs;
1815   tree candidates = NULL_TREE;
1816   /* A TREE_LIST of templates of which DECL may be a specialization.
1817      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1818      corresponding TREE_PURPOSE is the set of template arguments that,
1819      when used to instantiate the template, would produce a function
1820      with the signature of DECL.  */
1821   tree templates = NULL_TREE;
1822   int header_count;
1823   cp_binding_level *b;
1824
1825   *targs_out = NULL_TREE;
1826
1827   if (template_id == error_mark_node || decl == error_mark_node)
1828     return error_mark_node;
1829
1830   fns = TREE_OPERAND (template_id, 0);
1831   explicit_targs = TREE_OPERAND (template_id, 1);
1832
1833   if (fns == error_mark_node)
1834     return error_mark_node;
1835
1836   /* Check for baselinks.  */
1837   if (BASELINK_P (fns))
1838     fns = BASELINK_FUNCTIONS (fns);
1839
1840   if (!is_overloaded_fn (fns))
1841     {
1842       error ("%qD is not a function template", fns);
1843       return error_mark_node;
1844     }
1845
1846   /* Count the number of template headers specified for this
1847      specialization.  */
1848   header_count = 0;
1849   for (b = current_binding_level;
1850        b->kind == sk_template_parms;
1851        b = b->level_chain)
1852     ++header_count;
1853
1854   for (; fns; fns = OVL_NEXT (fns))
1855     {
1856       tree fn = OVL_CURRENT (fns);
1857
1858       if (TREE_CODE (fn) == TEMPLATE_DECL)
1859         {
1860           tree decl_arg_types;
1861           tree fn_arg_types;
1862
1863           /* In case of explicit specialization, we need to check if
1864              the number of template headers appearing in the specialization
1865              is correct. This is usually done in check_explicit_specialization,
1866              but the check done there cannot be exhaustive when specializing
1867              member functions. Consider the following code:
1868
1869              template <> void A<int>::f(int);
1870              template <> template <> void A<int>::f(int);
1871
1872              Assuming that A<int> is not itself an explicit specialization
1873              already, the first line specializes "f" which is a non-template
1874              member function, whilst the second line specializes "f" which
1875              is a template member function. So both lines are syntactically
1876              correct, and check_explicit_specialization does not reject
1877              them.
1878
1879              Here, we can do better, as we are matching the specialization
1880              against the declarations. We count the number of template
1881              headers, and we check if they match TEMPLATE_COUNT + 1
1882              (TEMPLATE_COUNT is the number of qualifying template classes,
1883              plus there must be another header for the member template
1884              itself).
1885
1886              Notice that if header_count is zero, this is not a
1887              specialization but rather a template instantiation, so there
1888              is no check we can perform here.  */
1889           if (header_count && header_count != template_count + 1)
1890             continue;
1891
1892           /* Check that the number of template arguments at the
1893              innermost level for DECL is the same as for FN.  */
1894           if (current_binding_level->kind == sk_template_parms
1895               && !current_binding_level->explicit_spec_p
1896               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1897                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1898                                       (current_template_parms))))
1899             continue;
1900
1901           /* DECL might be a specialization of FN.  */
1902           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1903           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1904
1905           /* For a non-static member function, we need to make sure
1906              that the const qualification is the same.  Since
1907              get_bindings does not try to merge the "this" parameter,
1908              we must do the comparison explicitly.  */
1909           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1910               && !same_type_p (TREE_VALUE (fn_arg_types),
1911                                TREE_VALUE (decl_arg_types)))
1912             continue;
1913
1914           /* Skip the "this" parameter and, for constructors of
1915              classes with virtual bases, the VTT parameter.  A
1916              full specialization of a constructor will have a VTT
1917              parameter, but a template never will.  */ 
1918           decl_arg_types 
1919             = skip_artificial_parms_for (decl, decl_arg_types);
1920           fn_arg_types 
1921             = skip_artificial_parms_for (fn, fn_arg_types);
1922
1923           /* Check that the number of function parameters matches.
1924              For example,
1925                template <class T> void f(int i = 0);
1926                template <> void f<int>();
1927              The specialization f<int> is invalid but is not caught
1928              by get_bindings below.  */
1929           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1930             continue;
1931
1932           /* Function templates cannot be specializations; there are
1933              no partial specializations of functions.  Therefore, if
1934              the type of DECL does not match FN, there is no
1935              match.  */
1936           if (tsk == tsk_template)
1937             {
1938               if (compparms (fn_arg_types, decl_arg_types))
1939                 candidates = tree_cons (NULL_TREE, fn, candidates);
1940               continue;
1941             }
1942
1943           /* See whether this function might be a specialization of this
1944              template.  */
1945           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1946
1947           if (!targs)
1948             /* We cannot deduce template arguments that when used to
1949                specialize TMPL will produce DECL.  */
1950             continue;
1951
1952           /* Save this template, and the arguments deduced.  */
1953           templates = tree_cons (targs, fn, templates);
1954         }
1955       else if (need_member_template)
1956         /* FN is an ordinary member function, and we need a
1957            specialization of a member template.  */
1958         ;
1959       else if (TREE_CODE (fn) != FUNCTION_DECL)
1960         /* We can get IDENTIFIER_NODEs here in certain erroneous
1961            cases.  */
1962         ;
1963       else if (!DECL_FUNCTION_MEMBER_P (fn))
1964         /* This is just an ordinary non-member function.  Nothing can
1965            be a specialization of that.  */
1966         ;
1967       else if (DECL_ARTIFICIAL (fn))
1968         /* Cannot specialize functions that are created implicitly.  */
1969         ;
1970       else
1971         {
1972           tree decl_arg_types;
1973
1974           /* This is an ordinary member function.  However, since
1975              we're here, we can assume it's enclosing class is a
1976              template class.  For example,
1977
1978                template <typename T> struct S { void f(); };
1979                template <> void S<int>::f() {}
1980
1981              Here, S<int>::f is a non-template, but S<int> is a
1982              template class.  If FN has the same type as DECL, we
1983              might be in business.  */
1984
1985           if (!DECL_TEMPLATE_INFO (fn))
1986             /* Its enclosing class is an explicit specialization
1987                of a template class.  This is not a candidate.  */
1988             continue;
1989
1990           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1991                             TREE_TYPE (TREE_TYPE (fn))))
1992             /* The return types differ.  */
1993             continue;
1994
1995           /* Adjust the type of DECL in case FN is a static member.  */
1996           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1997           if (DECL_STATIC_FUNCTION_P (fn)
1998               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1999             decl_arg_types = TREE_CHAIN (decl_arg_types);
2000
2001           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2002                          decl_arg_types))
2003             /* They match!  */
2004             candidates = tree_cons (NULL_TREE, fn, candidates);
2005         }
2006     }
2007
2008   if (templates && TREE_CHAIN (templates))
2009     {
2010       /* We have:
2011
2012            [temp.expl.spec]
2013
2014            It is possible for a specialization with a given function
2015            signature to be instantiated from more than one function
2016            template.  In such cases, explicit specification of the
2017            template arguments must be used to uniquely identify the
2018            function template specialization being specialized.
2019
2020          Note that here, there's no suggestion that we're supposed to
2021          determine which of the candidate templates is most
2022          specialized.  However, we, also have:
2023
2024            [temp.func.order]
2025
2026            Partial ordering of overloaded function template
2027            declarations is used in the following contexts to select
2028            the function template to which a function template
2029            specialization refers:
2030
2031            -- when an explicit specialization refers to a function
2032               template.
2033
2034          So, we do use the partial ordering rules, at least for now.
2035          This extension can only serve to make invalid programs valid,
2036          so it's safe.  And, there is strong anecdotal evidence that
2037          the committee intended the partial ordering rules to apply;
2038          the EDG front end has that behavior, and John Spicer claims
2039          that the committee simply forgot to delete the wording in
2040          [temp.expl.spec].  */
2041       tree tmpl = most_specialized_instantiation (templates);
2042       if (tmpl != error_mark_node)
2043         {
2044           templates = tmpl;
2045           TREE_CHAIN (templates) = NULL_TREE;
2046         }
2047     }
2048
2049   if (templates == NULL_TREE && candidates == NULL_TREE)
2050     {
2051       error ("template-id %qD for %q+D does not match any template "
2052              "declaration", template_id, decl);
2053       if (header_count && header_count != template_count + 1)
2054         inform (input_location, "saw %d %<template<>%>, need %d for "
2055                 "specializing a member function template",
2056                 header_count, template_count + 1);
2057       return error_mark_node;
2058     }
2059   else if ((templates && TREE_CHAIN (templates))
2060            || (candidates && TREE_CHAIN (candidates))
2061            || (templates && candidates))
2062     {
2063       error ("ambiguous template specialization %qD for %q+D",
2064              template_id, decl);
2065       candidates = chainon (candidates, templates);
2066       print_candidates (candidates);
2067       return error_mark_node;
2068     }
2069
2070   /* We have one, and exactly one, match.  */
2071   if (candidates)
2072     {
2073       tree fn = TREE_VALUE (candidates);
2074       *targs_out = copy_node (DECL_TI_ARGS (fn));
2075       /* DECL is a re-declaration or partial instantiation of a template
2076          function.  */
2077       if (TREE_CODE (fn) == TEMPLATE_DECL)
2078         return fn;
2079       /* It was a specialization of an ordinary member function in a
2080          template class.  */
2081       return DECL_TI_TEMPLATE (fn);
2082     }
2083
2084   /* It was a specialization of a template.  */
2085   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2086   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2087     {
2088       *targs_out = copy_node (targs);
2089       SET_TMPL_ARGS_LEVEL (*targs_out,
2090                            TMPL_ARGS_DEPTH (*targs_out),
2091                            TREE_PURPOSE (templates));
2092     }
2093   else
2094     *targs_out = TREE_PURPOSE (templates);
2095   return TREE_VALUE (templates);
2096 }
2097
2098 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2099    but with the default argument values filled in from those in the
2100    TMPL_TYPES.  */
2101
2102 static tree
2103 copy_default_args_to_explicit_spec_1 (tree spec_types,
2104                                       tree tmpl_types)
2105 {
2106   tree new_spec_types;
2107
2108   if (!spec_types)
2109     return NULL_TREE;
2110
2111   if (spec_types == void_list_node)
2112     return void_list_node;
2113
2114   /* Substitute into the rest of the list.  */
2115   new_spec_types =
2116     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2117                                           TREE_CHAIN (tmpl_types));
2118
2119   /* Add the default argument for this parameter.  */
2120   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2121                          TREE_VALUE (spec_types),
2122                          new_spec_types);
2123 }
2124
2125 /* DECL is an explicit specialization.  Replicate default arguments
2126    from the template it specializes.  (That way, code like:
2127
2128      template <class T> void f(T = 3);
2129      template <> void f(double);
2130      void g () { f (); }
2131
2132    works, as required.)  An alternative approach would be to look up
2133    the correct default arguments at the call-site, but this approach
2134    is consistent with how implicit instantiations are handled.  */
2135
2136 static void
2137 copy_default_args_to_explicit_spec (tree decl)
2138 {
2139   tree tmpl;
2140   tree spec_types;
2141   tree tmpl_types;
2142   tree new_spec_types;
2143   tree old_type;
2144   tree new_type;
2145   tree t;
2146   tree object_type = NULL_TREE;
2147   tree in_charge = NULL_TREE;
2148   tree vtt = NULL_TREE;
2149
2150   /* See if there's anything we need to do.  */
2151   tmpl = DECL_TI_TEMPLATE (decl);
2152   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2153   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2154     if (TREE_PURPOSE (t))
2155       break;
2156   if (!t)
2157     return;
2158
2159   old_type = TREE_TYPE (decl);
2160   spec_types = TYPE_ARG_TYPES (old_type);
2161
2162   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2163     {
2164       /* Remove the this pointer, but remember the object's type for
2165          CV quals.  */
2166       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2167       spec_types = TREE_CHAIN (spec_types);
2168       tmpl_types = TREE_CHAIN (tmpl_types);
2169
2170       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2171         {
2172           /* DECL may contain more parameters than TMPL due to the extra
2173              in-charge parameter in constructors and destructors.  */
2174           in_charge = spec_types;
2175           spec_types = TREE_CHAIN (spec_types);
2176         }
2177       if (DECL_HAS_VTT_PARM_P (decl))
2178         {
2179           vtt = spec_types;
2180           spec_types = TREE_CHAIN (spec_types);
2181         }
2182     }
2183
2184   /* Compute the merged default arguments.  */
2185   new_spec_types =
2186     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2187
2188   /* Compute the new FUNCTION_TYPE.  */
2189   if (object_type)
2190     {
2191       if (vtt)
2192         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2193                                          TREE_VALUE (vtt),
2194                                          new_spec_types);
2195
2196       if (in_charge)
2197         /* Put the in-charge parameter back.  */
2198         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2199                                          TREE_VALUE (in_charge),
2200                                          new_spec_types);
2201
2202       new_type = build_method_type_directly (object_type,
2203                                              TREE_TYPE (old_type),
2204                                              new_spec_types);
2205     }
2206   else
2207     new_type = build_function_type (TREE_TYPE (old_type),
2208                                     new_spec_types);
2209   new_type = cp_build_type_attribute_variant (new_type,
2210                                               TYPE_ATTRIBUTES (old_type));
2211   new_type = build_exception_variant (new_type,
2212                                       TYPE_RAISES_EXCEPTIONS (old_type));
2213   TREE_TYPE (decl) = new_type;
2214 }
2215
2216 /* Check to see if the function just declared, as indicated in
2217    DECLARATOR, and in DECL, is a specialization of a function
2218    template.  We may also discover that the declaration is an explicit
2219    instantiation at this point.
2220
2221    Returns DECL, or an equivalent declaration that should be used
2222    instead if all goes well.  Issues an error message if something is
2223    amiss.  Returns error_mark_node if the error is not easily
2224    recoverable.
2225
2226    FLAGS is a bitmask consisting of the following flags:
2227
2228    2: The function has a definition.
2229    4: The function is a friend.
2230
2231    The TEMPLATE_COUNT is the number of references to qualifying
2232    template classes that appeared in the name of the function.  For
2233    example, in
2234
2235      template <class T> struct S { void f(); };
2236      void S<int>::f();
2237
2238    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2239    classes are not counted in the TEMPLATE_COUNT, so that in
2240
2241      template <class T> struct S {};
2242      template <> struct S<int> { void f(); }
2243      template <> void S<int>::f();
2244
2245    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2246    invalid; there should be no template <>.)
2247
2248    If the function is a specialization, it is marked as such via
2249    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2250    is set up correctly, and it is added to the list of specializations
2251    for that template.  */
2252
2253 tree
2254 check_explicit_specialization (tree declarator,
2255                                tree decl,
2256                                int template_count,
2257                                int flags)
2258 {
2259   int have_def = flags & 2;
2260   int is_friend = flags & 4;
2261   int specialization = 0;
2262   int explicit_instantiation = 0;
2263   int member_specialization = 0;
2264   tree ctype = DECL_CLASS_CONTEXT (decl);
2265   tree dname = DECL_NAME (decl);
2266   tmpl_spec_kind tsk;
2267
2268   if (is_friend)
2269     {
2270       if (!processing_specialization)
2271         tsk = tsk_none;
2272       else
2273         tsk = tsk_excessive_parms;
2274     }
2275   else
2276     tsk = current_tmpl_spec_kind (template_count);
2277
2278   switch (tsk)
2279     {
2280     case tsk_none:
2281       if (processing_specialization)
2282         {
2283           specialization = 1;
2284           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2285         }
2286       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2287         {
2288           if (is_friend)
2289             /* This could be something like:
2290
2291                template <class T> void f(T);
2292                class S { friend void f<>(int); }  */
2293             specialization = 1;
2294           else
2295             {
2296               /* This case handles bogus declarations like template <>
2297                  template <class T> void f<int>(); */
2298
2299               error ("template-id %qD in declaration of primary template",
2300                      declarator);
2301               return decl;
2302             }
2303         }
2304       break;
2305
2306     case tsk_invalid_member_spec:
2307       /* The error has already been reported in
2308          check_specialization_scope.  */
2309       return error_mark_node;
2310
2311     case tsk_invalid_expl_inst:
2312       error ("template parameter list used in explicit instantiation");
2313
2314       /* Fall through.  */
2315
2316     case tsk_expl_inst:
2317       if (have_def)
2318         error ("definition provided for explicit instantiation");
2319
2320       explicit_instantiation = 1;
2321       break;
2322
2323     case tsk_excessive_parms:
2324     case tsk_insufficient_parms:
2325       if (tsk == tsk_excessive_parms)
2326         error ("too many template parameter lists in declaration of %qD",
2327                decl);
2328       else if (template_header_count)
2329         error("too few template parameter lists in declaration of %qD", decl);
2330       else
2331         error("explicit specialization of %qD must be introduced by "
2332               "%<template <>%>", decl);
2333
2334       /* Fall through.  */
2335     case tsk_expl_spec:
2336       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2337       if (ctype)
2338         member_specialization = 1;
2339       else
2340         specialization = 1;
2341       break;
2342
2343     case tsk_template:
2344       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2345         {
2346           /* This case handles bogus declarations like template <>
2347              template <class T> void f<int>(); */
2348
2349           if (uses_template_parms (declarator))
2350             error ("function template partial specialization %qD "
2351                    "is not allowed", declarator);
2352           else
2353             error ("template-id %qD in declaration of primary template",
2354                    declarator);
2355           return decl;
2356         }
2357
2358       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2359         /* This is a specialization of a member template, without
2360            specialization the containing class.  Something like:
2361
2362              template <class T> struct S {
2363                template <class U> void f (U);
2364              };
2365              template <> template <class U> void S<int>::f(U) {}
2366
2367            That's a specialization -- but of the entire template.  */
2368         specialization = 1;
2369       break;
2370
2371     default:
2372       gcc_unreachable ();
2373     }
2374
2375   if (specialization || member_specialization)
2376     {
2377       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2378       for (; t; t = TREE_CHAIN (t))
2379         if (TREE_PURPOSE (t))
2380           {
2381             permerror (input_location, 
2382                        "default argument specified in explicit specialization");
2383             break;
2384           }
2385     }
2386
2387   if (specialization || member_specialization || explicit_instantiation)
2388     {
2389       tree tmpl = NULL_TREE;
2390       tree targs = NULL_TREE;
2391
2392       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2393       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2394         {
2395           tree fns;
2396
2397           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2398           if (ctype)
2399             fns = dname;
2400           else
2401             {
2402               /* If there is no class context, the explicit instantiation
2403                  must be at namespace scope.  */
2404               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2405
2406               /* Find the namespace binding, using the declaration
2407                  context.  */
2408               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2409                                            false, true);
2410               if (fns == error_mark_node || !is_overloaded_fn (fns))
2411                 {
2412                   error ("%qD is not a template function", dname);
2413                   fns = error_mark_node;
2414                 }
2415               else
2416                 {
2417                   tree fn = OVL_CURRENT (fns);
2418                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2419                                                 CP_DECL_CONTEXT (fn)))
2420                     error ("%qD is not declared in %qD",
2421                            decl, current_namespace);
2422                 }
2423             }
2424
2425           declarator = lookup_template_function (fns, NULL_TREE);
2426         }
2427
2428       if (declarator == error_mark_node)
2429         return error_mark_node;
2430
2431       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2432         {
2433           if (!explicit_instantiation)
2434             /* A specialization in class scope.  This is invalid,
2435                but the error will already have been flagged by
2436                check_specialization_scope.  */
2437             return error_mark_node;
2438           else
2439             {
2440               /* It's not valid to write an explicit instantiation in
2441                  class scope, e.g.:
2442
2443                    class C { template void f(); }
2444
2445                    This case is caught by the parser.  However, on
2446                    something like:
2447
2448                    template class C { void f(); };
2449
2450                    (which is invalid) we can get here.  The error will be
2451                    issued later.  */
2452               ;
2453             }
2454
2455           return decl;
2456         }
2457       else if (ctype != NULL_TREE
2458                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2459                    IDENTIFIER_NODE))
2460         {
2461           /* Find the list of functions in ctype that have the same
2462              name as the declared function.  */
2463           tree name = TREE_OPERAND (declarator, 0);
2464           tree fns = NULL_TREE;
2465           int idx;
2466
2467           if (constructor_name_p (name, ctype))
2468             {
2469               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2470
2471               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2472                   : !CLASSTYPE_DESTRUCTORS (ctype))
2473                 {
2474                   /* From [temp.expl.spec]:
2475
2476                      If such an explicit specialization for the member
2477                      of a class template names an implicitly-declared
2478                      special member function (clause _special_), the
2479                      program is ill-formed.
2480
2481                      Similar language is found in [temp.explicit].  */
2482                   error ("specialization of implicitly-declared special member function");
2483                   return error_mark_node;
2484                 }
2485
2486               name = is_constructor ? ctor_identifier : dtor_identifier;
2487             }
2488
2489           if (!DECL_CONV_FN_P (decl))
2490             {
2491               idx = lookup_fnfields_1 (ctype, name);
2492               if (idx >= 0)
2493                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2494             }
2495           else
2496             {
2497               VEC(tree,gc) *methods;
2498               tree ovl;
2499
2500               /* For a type-conversion operator, we cannot do a
2501                  name-based lookup.  We might be looking for `operator
2502                  int' which will be a specialization of `operator T'.
2503                  So, we find *all* the conversion operators, and then
2504                  select from them.  */
2505               fns = NULL_TREE;
2506
2507               methods = CLASSTYPE_METHOD_VEC (ctype);
2508               if (methods)
2509                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2510                      VEC_iterate (tree, methods, idx, ovl);
2511                      ++idx)
2512                   {
2513                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2514                       /* There are no more conversion functions.  */
2515                       break;
2516
2517                     /* Glue all these conversion functions together
2518                        with those we already have.  */
2519                     for (; ovl; ovl = OVL_NEXT (ovl))
2520                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2521                   }
2522             }
2523
2524           if (fns == NULL_TREE)
2525             {
2526               error ("no member function %qD declared in %qT", name, ctype);
2527               return error_mark_node;
2528             }
2529           else
2530             TREE_OPERAND (declarator, 0) = fns;
2531         }
2532
2533       /* Figure out what exactly is being specialized at this point.
2534          Note that for an explicit instantiation, even one for a
2535          member function, we cannot tell apriori whether the
2536          instantiation is for a member template, or just a member
2537          function of a template class.  Even if a member template is
2538          being instantiated, the member template arguments may be
2539          elided if they can be deduced from the rest of the
2540          declaration.  */
2541       tmpl = determine_specialization (declarator, decl,
2542                                        &targs,
2543                                        member_specialization,
2544                                        template_count,
2545                                        tsk);
2546
2547       if (!tmpl || tmpl == error_mark_node)
2548         /* We couldn't figure out what this declaration was
2549            specializing.  */
2550         return error_mark_node;
2551       else
2552         {
2553           tree gen_tmpl = most_general_template (tmpl);
2554
2555           if (explicit_instantiation)
2556             {
2557               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2558                  is done by do_decl_instantiation later.  */
2559
2560               int arg_depth = TMPL_ARGS_DEPTH (targs);
2561               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2562
2563               if (arg_depth > parm_depth)
2564                 {
2565                   /* If TMPL is not the most general template (for
2566                      example, if TMPL is a friend template that is
2567                      injected into namespace scope), then there will
2568                      be too many levels of TARGS.  Remove some of them
2569                      here.  */
2570                   int i;
2571                   tree new_targs;
2572
2573                   new_targs = make_tree_vec (parm_depth);
2574                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2575                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2576                       = TREE_VEC_ELT (targs, i);
2577                   targs = new_targs;
2578                 }
2579
2580               return instantiate_template (tmpl, targs, tf_error);
2581             }
2582
2583           /* If we thought that the DECL was a member function, but it
2584              turns out to be specializing a static member function,
2585              make DECL a static member function as well.  */
2586           if (DECL_STATIC_FUNCTION_P (tmpl)
2587               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2588             revert_static_member_fn (decl);
2589
2590           /* If this is a specialization of a member template of a
2591              template class, we want to return the TEMPLATE_DECL, not
2592              the specialization of it.  */
2593           if (tsk == tsk_template)
2594             {
2595               tree result = DECL_TEMPLATE_RESULT (tmpl);
2596               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2597               DECL_INITIAL (result) = NULL_TREE;
2598               if (have_def)
2599                 {
2600                   tree parm;
2601                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2602                   DECL_SOURCE_LOCATION (result)
2603                     = DECL_SOURCE_LOCATION (decl);
2604                   /* We want to use the argument list specified in the
2605                      definition, not in the original declaration.  */
2606                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2607                   for (parm = DECL_ARGUMENTS (result); parm;
2608                        parm = DECL_CHAIN (parm))
2609                     DECL_CONTEXT (parm) = result;
2610                 }
2611               return register_specialization (tmpl, gen_tmpl, targs,
2612                                               is_friend, 0);
2613             }
2614
2615           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2616           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2617
2618           /* Inherit default function arguments from the template
2619              DECL is specializing.  */
2620           copy_default_args_to_explicit_spec (decl);
2621
2622           /* This specialization has the same protection as the
2623              template it specializes.  */
2624           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2625           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2626
2627           /* 7.1.1-1 [dcl.stc]
2628
2629              A storage-class-specifier shall not be specified in an
2630              explicit specialization...
2631
2632              The parser rejects these, so unless action is taken here,
2633              explicit function specializations will always appear with
2634              global linkage.
2635
2636              The action recommended by the C++ CWG in response to C++
2637              defect report 605 is to make the storage class and linkage
2638              of the explicit specialization match the templated function:
2639
2640              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2641            */
2642           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2643             {
2644               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2645               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2646
2647               /* This specialization has the same linkage and visibility as
2648                  the function template it specializes.  */
2649               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2650               if (! TREE_PUBLIC (decl))
2651                 {
2652                   DECL_INTERFACE_KNOWN (decl) = 1;
2653                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2654                 }
2655               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2656               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2657                 {
2658                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2659                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2660                 }
2661             }
2662
2663           /* If DECL is a friend declaration, declared using an
2664              unqualified name, the namespace associated with DECL may
2665              have been set incorrectly.  For example, in:
2666
2667                template <typename T> void f(T);
2668                namespace N {
2669                  struct S { friend void f<int>(int); }
2670                }
2671
2672              we will have set the DECL_CONTEXT for the friend
2673              declaration to N, rather than to the global namespace.  */
2674           if (DECL_NAMESPACE_SCOPE_P (decl))
2675             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2676
2677           if (is_friend && !have_def)
2678             /* This is not really a declaration of a specialization.
2679                It's just the name of an instantiation.  But, it's not
2680                a request for an instantiation, either.  */
2681             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2682           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2683             /* This is indeed a specialization.  In case of constructors
2684                and destructors, we need in-charge and not-in-charge
2685                versions in V3 ABI.  */
2686             clone_function_decl (decl, /*update_method_vec_p=*/0);
2687
2688           /* Register this specialization so that we can find it
2689              again.  */
2690           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2691         }
2692     }
2693
2694   return decl;
2695 }
2696
2697 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2698    parameters.  These are represented in the same format used for
2699    DECL_TEMPLATE_PARMS.  */
2700
2701 int
2702 comp_template_parms (const_tree parms1, const_tree parms2)
2703 {
2704   const_tree p1;
2705   const_tree p2;
2706
2707   if (parms1 == parms2)
2708     return 1;
2709
2710   for (p1 = parms1, p2 = parms2;
2711        p1 != NULL_TREE && p2 != NULL_TREE;
2712        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2713     {
2714       tree t1 = TREE_VALUE (p1);
2715       tree t2 = TREE_VALUE (p2);
2716       int i;
2717
2718       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2719       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2720
2721       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2722         return 0;
2723
2724       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2725         {
2726           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2727           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2728
2729           /* If either of the template parameters are invalid, assume
2730              they match for the sake of error recovery. */
2731           if (parm1 == error_mark_node || parm2 == error_mark_node)
2732             return 1;
2733
2734           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2735             return 0;
2736
2737           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2738               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2739                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2740             continue;
2741           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2742             return 0;
2743         }
2744     }
2745
2746   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2747     /* One set of parameters has more parameters lists than the
2748        other.  */
2749     return 0;
2750
2751   return 1;
2752 }
2753
2754 /* Determine whether PARM is a parameter pack.  */
2755
2756 bool 
2757 template_parameter_pack_p (const_tree parm)
2758 {
2759   /* Determine if we have a non-type template parameter pack.  */
2760   if (TREE_CODE (parm) == PARM_DECL)
2761     return (DECL_TEMPLATE_PARM_P (parm) 
2762             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2763   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
2764     return TEMPLATE_PARM_PARAMETER_PACK (parm);
2765
2766   /* If this is a list of template parameters, we could get a
2767      TYPE_DECL or a TEMPLATE_DECL.  */ 
2768   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2769     parm = TREE_TYPE (parm);
2770
2771   /* Otherwise it must be a type template parameter.  */
2772   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2773            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2774           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2775 }
2776
2777 /* Determine if T is a function parameter pack.  */
2778
2779 bool
2780 function_parameter_pack_p (const_tree t)
2781 {
2782   if (t && TREE_CODE (t) == PARM_DECL)
2783     return FUNCTION_PARAMETER_PACK_P (t);
2784   return false;
2785 }
2786
2787 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2788    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2789
2790 tree
2791 get_function_template_decl (const_tree primary_func_tmpl_inst)
2792 {
2793   if (! primary_func_tmpl_inst
2794       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2795       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2796     return NULL;
2797
2798   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2799 }
2800
2801 /* Return true iff the function parameter PARAM_DECL was expanded
2802    from the function parameter pack PACK.  */
2803
2804 bool
2805 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2806 {
2807   if (DECL_ARTIFICIAL (param_decl)
2808       || !function_parameter_pack_p (pack))
2809     return false;
2810
2811   /* The parameter pack and its pack arguments have the same
2812      DECL_PARM_INDEX.  */
2813   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2814 }
2815
2816 /* Determine whether ARGS describes a variadic template args list,
2817    i.e., one that is terminated by a template argument pack.  */
2818
2819 static bool 
2820 template_args_variadic_p (tree args)
2821 {
2822   int nargs;
2823   tree last_parm;
2824
2825   if (args == NULL_TREE)
2826     return false;
2827
2828   args = INNERMOST_TEMPLATE_ARGS (args);
2829   nargs = TREE_VEC_LENGTH (args);
2830
2831   if (nargs == 0)
2832     return false;
2833
2834   last_parm = TREE_VEC_ELT (args, nargs - 1);
2835
2836   return ARGUMENT_PACK_P (last_parm);
2837 }
2838
2839 /* Generate a new name for the parameter pack name NAME (an
2840    IDENTIFIER_NODE) that incorporates its */
2841
2842 static tree
2843 make_ith_pack_parameter_name (tree name, int i)
2844 {
2845   /* Munge the name to include the parameter index.  */
2846 #define NUMBUF_LEN 128
2847   char numbuf[NUMBUF_LEN];
2848   char* newname;
2849   int newname_len;
2850
2851   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2852   newname_len = IDENTIFIER_LENGTH (name)
2853                 + strlen (numbuf) + 2;
2854   newname = (char*)alloca (newname_len);
2855   snprintf (newname, newname_len,
2856             "%s#%i", IDENTIFIER_POINTER (name), i);
2857   return get_identifier (newname);
2858 }
2859
2860 /* Return true if T is a primary function, class or alias template
2861    instantiation.  */
2862
2863 bool
2864 primary_template_instantiation_p (const_tree t)
2865 {
2866   if (!t)
2867     return false;
2868
2869   if (TREE_CODE (t) == FUNCTION_DECL)
2870     return DECL_LANG_SPECIFIC (t)
2871            && DECL_TEMPLATE_INSTANTIATION (t)
2872            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2873   else if (CLASS_TYPE_P (t))
2874     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2875            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2876   else if (TYPE_P (t)
2877            && TYPE_TEMPLATE_INFO (t)
2878            && PRIMARY_TEMPLATE_P (TYPE_TI_TEMPLATE (t))
2879            && DECL_TEMPLATE_INSTANTIATION (TYPE_NAME (t)))
2880     return true;
2881   return false;
2882 }
2883
2884 /* Return true if PARM is a template template parameter.  */
2885
2886 bool
2887 template_template_parameter_p (const_tree parm)
2888 {
2889   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2890 }
2891
2892 /* Return the template parameters of T if T is a
2893    primary template instantiation, NULL otherwise.  */
2894
2895 tree
2896 get_primary_template_innermost_parameters (const_tree t)
2897 {
2898   tree parms = NULL, template_info = NULL;
2899
2900   if ((template_info = get_template_info (t))
2901       && primary_template_instantiation_p (t))
2902     parms = INNERMOST_TEMPLATE_PARMS
2903         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2904
2905   return parms;
2906 }
2907
2908 /* Return the template parameters of the LEVELth level from the full list
2909    of template parameters PARMS.  */
2910
2911 tree
2912 get_template_parms_at_level (tree parms, int level)
2913 {
2914   tree p;
2915   if (!parms
2916       || TREE_CODE (parms) != TREE_LIST
2917       || level > TMPL_PARMS_DEPTH (parms))
2918     return NULL_TREE;
2919
2920   for (p = parms; p; p = TREE_CHAIN (p))
2921     if (TMPL_PARMS_DEPTH (p) == level)
2922       return p;
2923
2924   return NULL_TREE;
2925 }
2926
2927 /* Returns the template arguments of T if T is a template instantiation,
2928    NULL otherwise.  */
2929
2930 tree
2931 get_template_innermost_arguments (const_tree t)
2932 {
2933   tree args = NULL, template_info = NULL;
2934
2935   if ((template_info = get_template_info (t))
2936       && TI_ARGS (template_info))
2937     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2938
2939   return args;
2940 }
2941
2942 /* Return the argument pack elements of T if T is a template argument pack,
2943    NULL otherwise.  */
2944
2945 tree
2946 get_template_argument_pack_elems (const_tree t)
2947 {
2948   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2949       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2950     return NULL;
2951
2952   return ARGUMENT_PACK_ARGS (t);
2953 }
2954
2955 /* Structure used to track the progress of find_parameter_packs_r.  */
2956 struct find_parameter_pack_data 
2957 {
2958   /* TREE_LIST that will contain all of the parameter packs found by
2959      the traversal.  */
2960   tree* parameter_packs;
2961
2962   /* Set of AST nodes that have been visited by the traversal.  */
2963   struct pointer_set_t *visited;
2964 };
2965
2966 /* Identifies all of the argument packs that occur in a template
2967    argument and appends them to the TREE_LIST inside DATA, which is a
2968    find_parameter_pack_data structure. This is a subroutine of
2969    make_pack_expansion and uses_parameter_packs.  */
2970 static tree
2971 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2972 {
2973   tree t = *tp;
2974   struct find_parameter_pack_data* ppd = 
2975     (struct find_parameter_pack_data*)data;
2976   bool parameter_pack_p = false;
2977
2978   /* Identify whether this is a parameter pack or not.  */
2979   switch (TREE_CODE (t))
2980     {
2981     case TEMPLATE_PARM_INDEX:
2982       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2983         parameter_pack_p = true;
2984       break;
2985
2986     case TEMPLATE_TYPE_PARM:
2987       t = TYPE_MAIN_VARIANT (t);
2988     case TEMPLATE_TEMPLATE_PARM:
2989       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2990         parameter_pack_p = true;
2991       break;
2992
2993     case PARM_DECL:
2994       if (FUNCTION_PARAMETER_PACK_P (t))
2995         {
2996           /* We don't want to walk into the type of a PARM_DECL,
2997              because we don't want to see the type parameter pack.  */
2998           *walk_subtrees = 0;
2999           parameter_pack_p = true;
3000         }
3001       break;
3002
3003     case BASES:
3004       parameter_pack_p = true;
3005       break;
3006     default:
3007       /* Not a parameter pack.  */
3008       break;
3009     }
3010
3011   if (parameter_pack_p)
3012     {
3013       /* Add this parameter pack to the list.  */
3014       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3015     }
3016
3017   if (TYPE_P (t))
3018     cp_walk_tree (&TYPE_CONTEXT (t), 
3019                   &find_parameter_packs_r, ppd, ppd->visited);
3020
3021   /* This switch statement will return immediately if we don't find a
3022      parameter pack.  */
3023   switch (TREE_CODE (t)) 
3024     {
3025     case TEMPLATE_PARM_INDEX:
3026       return NULL_TREE;
3027
3028     case BOUND_TEMPLATE_TEMPLATE_PARM:
3029       /* Check the template itself.  */
3030       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
3031                     &find_parameter_packs_r, ppd, ppd->visited);
3032       /* Check the template arguments.  */
3033       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
3034                     ppd->visited);
3035       *walk_subtrees = 0;
3036       return NULL_TREE;
3037
3038     case TEMPLATE_TYPE_PARM:
3039     case TEMPLATE_TEMPLATE_PARM:
3040       return NULL_TREE;
3041
3042     case PARM_DECL:
3043       return NULL_TREE;
3044
3045     case RECORD_TYPE:
3046       if (TYPE_PTRMEMFUNC_P (t))
3047         return NULL_TREE;
3048       /* Fall through.  */
3049
3050     case UNION_TYPE:
3051     case ENUMERAL_TYPE:
3052       if (TYPE_TEMPLATE_INFO (t))
3053         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3054                       &find_parameter_packs_r, ppd, ppd->visited);
3055
3056       *walk_subtrees = 0;
3057       return NULL_TREE;
3058
3059     case CONSTRUCTOR:
3060     case TEMPLATE_DECL:
3061       cp_walk_tree (&TREE_TYPE (t),
3062                     &find_parameter_packs_r, ppd, ppd->visited);
3063       return NULL_TREE;
3064  
3065     case TYPENAME_TYPE:
3066       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3067                    ppd, ppd->visited);
3068       *walk_subtrees = 0;
3069       return NULL_TREE;
3070       
3071     case TYPE_PACK_EXPANSION:
3072     case EXPR_PACK_EXPANSION:
3073       *walk_subtrees = 0;
3074       return NULL_TREE;
3075
3076     case INTEGER_TYPE:
3077       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3078                     ppd, ppd->visited);
3079       *walk_subtrees = 0;
3080       return NULL_TREE;
3081
3082     case IDENTIFIER_NODE:
3083       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3084                     ppd->visited);
3085       *walk_subtrees = 0;
3086       return NULL_TREE;
3087
3088     default:
3089       return NULL_TREE;
3090     }
3091
3092   return NULL_TREE;
3093 }
3094
3095 /* Determines if the expression or type T uses any parameter packs.  */
3096 bool
3097 uses_parameter_packs (tree t)
3098 {
3099   tree parameter_packs = NULL_TREE;
3100   struct find_parameter_pack_data ppd;
3101   ppd.parameter_packs = &parameter_packs;
3102   ppd.visited = pointer_set_create ();
3103   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3104   pointer_set_destroy (ppd.visited);
3105   return parameter_packs != NULL_TREE;
3106 }
3107
3108 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3109    representation a base-class initializer into a parameter pack
3110    expansion. If all goes well, the resulting node will be an
3111    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3112    respectively.  */
3113 tree 
3114 make_pack_expansion (tree arg)
3115 {
3116   tree result;
3117   tree parameter_packs = NULL_TREE;
3118   bool for_types = false;
3119   struct find_parameter_pack_data ppd;
3120
3121   if (!arg || arg == error_mark_node)
3122     return arg;
3123
3124   if (TREE_CODE (arg) == TREE_LIST)
3125     {
3126       /* The only time we will see a TREE_LIST here is for a base
3127          class initializer.  In this case, the TREE_PURPOSE will be a
3128          _TYPE node (representing the base class expansion we're
3129          initializing) and the TREE_VALUE will be a TREE_LIST
3130          containing the initialization arguments. 
3131
3132          The resulting expansion looks somewhat different from most
3133          expansions. Rather than returning just one _EXPANSION, we
3134          return a TREE_LIST whose TREE_PURPOSE is a
3135          TYPE_PACK_EXPANSION containing the bases that will be
3136          initialized.  The TREE_VALUE will be identical to the
3137          original TREE_VALUE, which is a list of arguments that will
3138          be passed to each base.  We do not introduce any new pack
3139          expansion nodes into the TREE_VALUE (although it is possible
3140          that some already exist), because the TREE_PURPOSE and
3141          TREE_VALUE all need to be expanded together with the same
3142          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3143          resulting TREE_PURPOSE will mention the parameter packs in
3144          both the bases and the arguments to the bases.  */
3145       tree purpose;
3146       tree value;
3147       tree parameter_packs = NULL_TREE;
3148
3149       /* Determine which parameter packs will be used by the base
3150          class expansion.  */
3151       ppd.visited = pointer_set_create ();
3152       ppd.parameter_packs = &parameter_packs;
3153       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3154                     &ppd, ppd.visited);
3155
3156       if (parameter_packs == NULL_TREE)
3157         {
3158           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3159           pointer_set_destroy (ppd.visited);
3160           return error_mark_node;
3161         }
3162
3163       if (TREE_VALUE (arg) != void_type_node)
3164         {
3165           /* Collect the sets of parameter packs used in each of the
3166              initialization arguments.  */
3167           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3168             {
3169               /* Determine which parameter packs will be expanded in this
3170                  argument.  */
3171               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3172                             &ppd, ppd.visited);
3173             }
3174         }
3175
3176       pointer_set_destroy (ppd.visited);
3177
3178       /* Create the pack expansion type for the base type.  */
3179       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3180       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3181       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3182
3183       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3184          they will rarely be compared to anything.  */
3185       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3186
3187       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3188     }
3189
3190   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3191     for_types = true;
3192
3193   /* Build the PACK_EXPANSION_* node.  */
3194   result = for_types
3195      ? cxx_make_type (TYPE_PACK_EXPANSION)
3196      : make_node (EXPR_PACK_EXPANSION);
3197   SET_PACK_EXPANSION_PATTERN (result, arg);
3198   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3199     {
3200       /* Propagate type and const-expression information.  */
3201       TREE_TYPE (result) = TREE_TYPE (arg);
3202       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3203     }
3204   else
3205     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3206        they will rarely be compared to anything.  */
3207     SET_TYPE_STRUCTURAL_EQUALITY (result);
3208
3209   /* Determine which parameter packs will be expanded.  */
3210   ppd.parameter_packs = &parameter_packs;
3211   ppd.visited = pointer_set_create ();
3212   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3213   pointer_set_destroy (ppd.visited);
3214
3215   /* Make sure we found some parameter packs.  */
3216   if (parameter_packs == NULL_TREE)
3217     {
3218       if (TYPE_P (arg))
3219         error ("expansion pattern %<%T%> contains no argument packs", arg);
3220       else
3221         error ("expansion pattern %<%E%> contains no argument packs", arg);
3222       return error_mark_node;
3223     }
3224   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3225
3226   return result;
3227 }
3228
3229 /* Checks T for any "bare" parameter packs, which have not yet been
3230    expanded, and issues an error if any are found. This operation can
3231    only be done on full expressions or types (e.g., an expression
3232    statement, "if" condition, etc.), because we could have expressions like:
3233
3234      foo(f(g(h(args)))...)
3235
3236    where "args" is a parameter pack. check_for_bare_parameter_packs
3237    should not be called for the subexpressions args, h(args),
3238    g(h(args)), or f(g(h(args))), because we would produce erroneous
3239    error messages. 
3240
3241    Returns TRUE and emits an error if there were bare parameter packs,
3242    returns FALSE otherwise.  */
3243 bool 
3244 check_for_bare_parameter_packs (tree t)
3245 {
3246   tree parameter_packs = NULL_TREE;
3247   struct find_parameter_pack_data ppd;
3248
3249   if (!processing_template_decl || !t || t == error_mark_node)
3250     return false;
3251
3252   if (TREE_CODE (t) == TYPE_DECL)
3253     t = TREE_TYPE (t);
3254
3255   ppd.parameter_packs = &parameter_packs;
3256   ppd.visited = pointer_set_create ();
3257   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3258   pointer_set_destroy (ppd.visited);
3259
3260   if (parameter_packs) 
3261     {
3262       error ("parameter packs not expanded with %<...%>:");
3263       while (parameter_packs)
3264         {
3265           tree pack = TREE_VALUE (parameter_packs);
3266           tree name = NULL_TREE;
3267
3268           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3269               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3270             name = TYPE_NAME (pack);
3271           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3272             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3273           else
3274             name = DECL_NAME (pack);
3275
3276           if (name)
3277             inform (input_location, "        %qD", name);
3278           else
3279             inform (input_location, "        <anonymous>");
3280
3281           parameter_packs = TREE_CHAIN (parameter_packs);
3282         }
3283
3284       return true;
3285     }
3286
3287   return false;
3288 }
3289
3290 /* Expand any parameter packs that occur in the template arguments in
3291    ARGS.  */
3292 tree
3293 expand_template_argument_pack (tree args)
3294 {
3295   tree result_args = NULL_TREE;
3296   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3297   int num_result_args = -1;
3298   int non_default_args_count = -1;
3299
3300   /* First, determine if we need to expand anything, and the number of
3301      slots we'll need.  */
3302   for (in_arg = 0; in_arg < nargs; ++in_arg)
3303     {
3304       tree arg = TREE_VEC_ELT (args, in_arg);
3305       if (arg == NULL_TREE)
3306         return args;
3307       if (ARGUMENT_PACK_P (arg))
3308         {
3309           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3310           if (num_result_args < 0)
3311             num_result_args = in_arg + num_packed;
3312           else
3313             num_result_args += num_packed;
3314         }
3315       else
3316         {
3317           if (num_result_args >= 0)
3318             num_result_args++;
3319         }
3320     }
3321
3322   /* If no expansion is necessary, we're done.  */
3323   if (num_result_args < 0)
3324     return args;
3325
3326   /* Expand arguments.  */
3327   result_args = make_tree_vec (num_result_args);
3328   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3329     non_default_args_count =
3330       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3331   for (in_arg = 0; in_arg < nargs; ++in_arg)
3332     {
3333       tree arg = TREE_VEC_ELT (args, in_arg);
3334       if (ARGUMENT_PACK_P (arg))
3335         {
3336           tree packed = ARGUMENT_PACK_ARGS (arg);
3337           int i, num_packed = TREE_VEC_LENGTH (packed);
3338           for (i = 0; i < num_packed; ++i, ++out_arg)
3339             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3340           if (non_default_args_count > 0)
3341             non_default_args_count += num_packed;
3342         }
3343       else
3344         {
3345           TREE_VEC_ELT (result_args, out_arg) = arg;
3346           ++out_arg;
3347         }
3348     }
3349   if (non_default_args_count >= 0)
3350     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3351   return result_args;
3352 }
3353
3354 /* Checks if DECL shadows a template parameter.
3355
3356    [temp.local]: A template-parameter shall not be redeclared within its
3357    scope (including nested scopes).
3358
3359    Emits an error and returns TRUE if the DECL shadows a parameter,
3360    returns FALSE otherwise.  */
3361
3362 bool
3363 check_template_shadow (tree decl)
3364 {
3365   tree olddecl;
3366
3367   /* If we're not in a template, we can't possibly shadow a template
3368      parameter.  */
3369   if (!current_template_parms)
3370     return true;
3371
3372   /* Figure out what we're shadowing.  */
3373   if (TREE_CODE (decl) == OVERLOAD)
3374     decl = OVL_CURRENT (decl);
3375   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3376
3377   /* If there's no previous binding for this name, we're not shadowing
3378      anything, let alone a template parameter.  */
3379   if (!olddecl)
3380     return true;
3381
3382   /* If we're not shadowing a template parameter, we're done.  Note
3383      that OLDDECL might be an OVERLOAD (or perhaps even an
3384      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3385      node.  */
3386   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3387     return true;
3388
3389   /* We check for decl != olddecl to avoid bogus errors for using a
3390      name inside a class.  We check TPFI to avoid duplicate errors for
3391      inline member templates.  */
3392   if (decl == olddecl
3393       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3394     return true;
3395
3396   error ("declaration of %q+#D", decl);
3397   error (" shadows template parm %q+#D", olddecl);
3398   return false;
3399 }
3400
3401 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3402    ORIG_LEVEL, DECL, and TYPE.  NUM_SIBLINGS is the total number of
3403    template parameters.  */
3404
3405 static tree
3406 build_template_parm_index (int index,
3407                            int level,
3408                            int orig_level,
3409                            int num_siblings,
3410                            tree decl,
3411                            tree type)
3412 {
3413   tree t = make_node (TEMPLATE_PARM_INDEX);
3414   TEMPLATE_PARM_IDX (t) = index;
3415   TEMPLATE_PARM_LEVEL (t) = level;
3416   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3417   TEMPLATE_PARM_NUM_SIBLINGS (t) = num_siblings;
3418   TEMPLATE_PARM_DECL (t) = decl;
3419   TREE_TYPE (t) = type;
3420   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3421   TREE_READONLY (t) = TREE_READONLY (decl);
3422
3423   return t;
3424 }
3425
3426 /* Find the canonical type parameter for the given template type
3427    parameter.  Returns the canonical type parameter, which may be TYPE
3428    if no such parameter existed.  */
3429
3430 static tree
3431 canonical_type_parameter (tree type)
3432 {
3433   tree list;
3434   int idx = TEMPLATE_TYPE_IDX (type);
3435   if (!canonical_template_parms)
3436     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3437
3438   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3439     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3440
3441   list = VEC_index (tree, canonical_template_parms, idx);
3442   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3443     list = TREE_CHAIN (list);
3444
3445   if (list)
3446     return TREE_VALUE (list);
3447   else
3448     {
3449       VEC_replace(tree, canonical_template_parms, idx,
3450                   tree_cons (NULL_TREE, type, 
3451                              VEC_index (tree, canonical_template_parms, idx)));
3452       return type;
3453     }
3454 }
3455
3456 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3457    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3458    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3459    new one is created.  */
3460
3461 static tree
3462 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3463                             tsubst_flags_t complain)
3464 {
3465   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3466       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3467           != TEMPLATE_PARM_LEVEL (index) - levels)
3468       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3469     {
3470       tree orig_decl = TEMPLATE_PARM_DECL (index);
3471       tree decl, t;
3472
3473       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3474                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3475       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3476       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3477       DECL_ARTIFICIAL (decl) = 1;
3478       SET_DECL_TEMPLATE_PARM_P (decl);
3479
3480       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3481                                      TEMPLATE_PARM_LEVEL (index) - levels,
3482                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3483                                      TEMPLATE_PARM_NUM_SIBLINGS (index),
3484                                      decl, type);
3485       TEMPLATE_PARM_DESCENDANTS (index) = t;
3486       TEMPLATE_PARM_PARAMETER_PACK (t) 
3487         = TEMPLATE_PARM_PARAMETER_PACK (index);
3488
3489         /* Template template parameters need this.  */
3490       if (TREE_CODE (decl) == TEMPLATE_DECL)
3491         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3492           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3493            args, complain);
3494     }
3495
3496   return TEMPLATE_PARM_DESCENDANTS (index);
3497 }
3498
3499 /* Process information from new template parameter PARM and append it
3500    to the LIST being built.  This new parameter is a non-type
3501    parameter iff IS_NON_TYPE is true. This new parameter is a
3502    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3503    is in PARM_LOC. NUM_TEMPLATE_PARMS is the size of the template
3504    parameter list PARM belongs to. This is used used to create a
3505    proper canonical type for the type of PARM that is to be created,
3506    iff PARM is a type.  If the size is not known, this parameter shall
3507    be set to 0.  */
3508
3509 tree
3510 process_template_parm (tree list, location_t parm_loc, tree parm,
3511                        bool is_non_type, bool is_parameter_pack,
3512                        unsigned num_template_parms)
3513 {
3514   tree decl = 0;
3515   tree defval;
3516   tree err_parm_list;
3517   int idx = 0;
3518
3519   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3520   defval = TREE_PURPOSE (parm);
3521
3522   if (list)
3523     {
3524       tree p = tree_last (list);
3525
3526       if (p && TREE_VALUE (p) != error_mark_node)
3527         {
3528           p = TREE_VALUE (p);
3529           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3530             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3531           else
3532             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3533         }
3534
3535       ++idx;
3536     }
3537   else
3538     idx = 0;
3539
3540   if (is_non_type)
3541     {
3542       parm = TREE_VALUE (parm);
3543
3544       SET_DECL_TEMPLATE_PARM_P (parm);
3545
3546       if (TREE_TYPE (parm) == error_mark_node)
3547         {
3548           err_parm_list = build_tree_list (defval, parm);
3549           TREE_VALUE (err_parm_list) = error_mark_node;
3550            return chainon (list, err_parm_list);
3551         }
3552       else
3553       {
3554         /* [temp.param]
3555
3556            The top-level cv-qualifiers on the template-parameter are
3557            ignored when determining its type.  */
3558         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3559         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3560           {
3561             err_parm_list = build_tree_list (defval, parm);
3562             TREE_VALUE (err_parm_list) = error_mark_node;
3563              return chainon (list, err_parm_list);
3564           }
3565
3566         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3567           {
3568             /* This template parameter is not a parameter pack, but it
3569                should be. Complain about "bare" parameter packs.  */
3570             check_for_bare_parameter_packs (TREE_TYPE (parm));
3571             
3572             /* Recover by calling this a parameter pack.  */
3573             is_parameter_pack = true;
3574           }
3575       }
3576
3577       /* A template parameter is not modifiable.  */
3578       TREE_CONSTANT (parm) = 1;
3579       TREE_READONLY (parm) = 1;
3580       decl = build_decl (parm_loc,
3581                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3582       TREE_CONSTANT (decl) = 1;
3583       TREE_READONLY (decl) = 1;
3584       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3585         = build_template_parm_index (idx, processing_template_decl,
3586                                      processing_template_decl,
3587                                      num_template_parms,
3588                                      decl, TREE_TYPE (parm));
3589
3590       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3591         = is_parameter_pack;
3592     }
3593   else
3594     {
3595       tree t;
3596       parm = TREE_VALUE (TREE_VALUE (parm));
3597
3598       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3599         {
3600           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3601           /* This is for distinguishing between real templates and template
3602              template parameters */
3603           TREE_TYPE (parm) = t;
3604           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3605           decl = parm;
3606         }
3607       else
3608         {
3609           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3610           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3611           decl = build_decl (parm_loc,
3612                              TYPE_DECL, parm, t);
3613         }
3614
3615       TYPE_NAME (t) = decl;
3616       TYPE_STUB_DECL (t) = decl;
3617       parm = decl;
3618       TEMPLATE_TYPE_PARM_INDEX (t)
3619         = build_template_parm_index (idx, processing_template_decl,
3620                                      processing_template_decl,
3621                                      num_template_parms,
3622                                      decl, TREE_TYPE (parm));
3623       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3624       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3625     }
3626   DECL_ARTIFICIAL (decl) = 1;
3627   SET_DECL_TEMPLATE_PARM_P (decl);
3628   pushdecl (decl);
3629   parm = build_tree_list (defval, parm);
3630   return chainon (list, parm);
3631 }
3632
3633 /* The end of a template parameter list has been reached.  Process the
3634    tree list into a parameter vector, converting each parameter into a more
3635    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3636    as PARM_DECLs.  */
3637
3638 tree
3639 end_template_parm_list (tree parms)
3640 {
3641   int nparms;
3642   tree parm, next;
3643   tree saved_parmlist = make_tree_vec (list_length (parms));
3644
3645   current_template_parms
3646     = tree_cons (size_int (processing_template_decl),
3647                  saved_parmlist, current_template_parms);
3648
3649   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3650     {
3651       next = TREE_CHAIN (parm);
3652       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3653       TREE_CHAIN (parm) = NULL_TREE;
3654     }
3655
3656   --processing_template_parmlist;
3657
3658   return saved_parmlist;
3659 }
3660
3661 /* Create a new type almost identical to TYPE but which has the
3662    following differences:
3663
3664      1/ T has a new TEMPLATE_PARM_INDEX that carries the new number of
3665      template sibling parameters of T.
3666
3667      2/ T has a new canonical type that matches the new number
3668      of sibling parms.
3669
3670      3/ From now on, T is going to be what lookups referring to the
3671      name of TYPE will return. No lookup should return TYPE anymore.
3672
3673    NUM_PARMS is the new number of sibling parms TYPE belongs to.
3674
3675    This is a subroutine of fixup_template_parms.  */
3676
3677 static tree
3678 fixup_template_type_parm_type (tree type, int num_parms)
3679 {
3680   tree orig_idx = TEMPLATE_TYPE_PARM_INDEX (type), idx;
3681   tree t;
3682   /* This is the decl which name is inserted into the symbol table for
3683      the template parm type. So whenever we lookup the type name, this
3684      is the DECL we get.  */
3685   tree decl;
3686
3687   /* Do not fix up the type twice.  */
3688   if (orig_idx && TEMPLATE_PARM_NUM_SIBLINGS (orig_idx) != 0)
3689     return type;
3690
3691   t = copy_type (type);
3692   decl = TYPE_NAME (t);
3693
3694   TYPE_MAIN_VARIANT (t) = t;
3695   TYPE_NEXT_VARIANT (t)= NULL_TREE;
3696   TYPE_POINTER_TO (t) = 0;
3697   TYPE_REFERENCE_TO (t) = 0;
3698
3699   idx = build_template_parm_index (TEMPLATE_PARM_IDX (orig_idx),
3700                                    TEMPLATE_PARM_LEVEL (orig_idx),
3701                                    TEMPLATE_PARM_ORIG_LEVEL (orig_idx),
3702                                    num_parms,
3703                                    decl, t);
3704   TEMPLATE_PARM_DESCENDANTS (idx) = TEMPLATE_PARM_DESCENDANTS (orig_idx);
3705   TEMPLATE_PARM_PARAMETER_PACK (idx) = TEMPLATE_PARM_PARAMETER_PACK (orig_idx);
3706   TEMPLATE_TYPE_PARM_INDEX (t) = idx;
3707
3708   TYPE_STUB_DECL (t) = decl;
3709   TEMPLATE_TYPE_DECL (t) = decl;
3710   if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
3711     TREE_TYPE (DECL_TEMPLATE_RESULT  (decl)) = t;
3712
3713   /* Update the type associated to the type name stored in the symbol
3714      table. Now, whenever the type name is looked up, the resulting
3715      type is properly fixed up.  */
3716   TREE_TYPE (decl) = t;
3717
3718   TYPE_CANONICAL (t) = canonical_type_parameter (t);
3719
3720   return t;
3721 }
3722
3723 /* Create and return a new TEMPLATE_PARM_INDEX that is almost
3724    identical to I, but that is fixed up as to:
3725
3726    1/ carry the number of sibling parms (NUM_PARMS) of the template
3727    parm represented by I.
3728
3729    2/ replace all references to template parm types declared before I
3730    (in the same template parm list as I) by references to template
3731    parm types contained in ARGS. ARGS should contain the list of
3732    template parms that have been fixed up so far, in a form suitable
3733    to be passed to tsubst.
3734
3735    This is a subroutine of fixup_template_parms.  */
3736
3737 static tree
3738 fixup_template_parm_index (tree i, tree args, int num_parms)
3739 {
3740   tree index, decl, type;
3741
3742   if (i == NULL_TREE
3743       || TREE_CODE (i) != TEMPLATE_PARM_INDEX
3744       /* Do not fix up the index twice.  */
3745       || (TEMPLATE_PARM_NUM_SIBLINGS (i) != 0))
3746     return i;
3747
3748   decl = TEMPLATE_PARM_DECL (i);
3749   type = TREE_TYPE (decl);
3750
3751   index = build_template_parm_index (TEMPLATE_PARM_IDX (i),
3752                                      TEMPLATE_PARM_LEVEL (i),
3753                                      TEMPLATE_PARM_ORIG_LEVEL (i),
3754                                      num_parms,
3755                                      decl, type);
3756
3757   TEMPLATE_PARM_DESCENDANTS (index) = TEMPLATE_PARM_DESCENDANTS (i);
3758   TEMPLATE_PARM_PARAMETER_PACK (index) = TEMPLATE_PARM_PARAMETER_PACK (i);
3759
3760   type = tsubst (type, args, tf_none, NULL_TREE);
3761   
3762   TREE_TYPE (decl) = type;
3763   TREE_TYPE (index) = type;
3764
3765   return index;
3766 }
3767
3768 /* 
3769    This is a subroutine of fixup_template_parms.
3770
3771    It computes the canonical type of the type of the template
3772    parameter PARM_DESC and update all references to that type so that
3773    they use the newly computed canonical type. No access check is
3774    performed during the fixup. PARM_DESC is a TREE_LIST which
3775    TREE_VALUE is the template parameter and its TREE_PURPOSE is the
3776    default argument of the template parm if any. IDX is the index of
3777    the template parameter, starting at 0. NUM_PARMS is the number of
3778    template parameters in the set PARM_DESC belongs to. ARGLIST is a
3779    TREE_VEC containing the full set of template parameters in a form
3780    suitable to be passed to substs functions as their ARGS
3781    argument. This is what current_template_args returns for a given
3782    template. The innermost vector of args in ARGLIST is the set of
3783    template parms that have been fixed up so far. This function adds
3784    the fixed up parameter into that vector.  */
3785
3786 static void
3787 fixup_template_parm (tree parm_desc,
3788                      int idx,
3789                      int num_parms,
3790                      tree arglist)
3791 {
3792   tree parm = TREE_VALUE (parm_desc);
3793   tree fixedup_args = INNERMOST_TEMPLATE_ARGS (arglist);
3794
3795   push_deferring_access_checks (dk_no_check);
3796
3797   if (TREE_CODE (parm) == TYPE_DECL)
3798     {
3799       /* PARM is a template type parameter. Fix up its type, add
3800          the fixed-up template parm to the vector of fixed-up
3801          template parms so far, and substitute the fixed-up
3802          template parms into the default argument of this
3803          parameter.  */
3804       tree t =
3805         fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3806       TREE_TYPE (parm) = t;
3807
3808       TREE_VEC_ELT (fixedup_args, idx) = template_parm_to_arg (parm_desc);
3809     }
3810   else if (TREE_CODE (parm) == TEMPLATE_DECL)
3811     {
3812       /* PARM is a template template parameter. This is going to
3813          be interesting.  */
3814       tree tparms, targs, innermost_args, t;
3815       int j;
3816
3817       /* First, fix up the parms of the template template parm
3818          because the parms are involved in defining the new canonical
3819          type of the template template parm.  */
3820
3821       /* So we need to substitute the template parm types that have
3822          been fixed up so far into the template parms of this template
3823          template parm. E.g, consider this:
3824
3825          template<class T, template<T u> class TT> class S;
3826
3827          In this case we want to substitute T into the
3828          template parameters of TT.
3829
3830          So let's walk the template parms of PARM here, and
3831          tsubst ARGLIST into into each of the template
3832          parms.   */
3833
3834       /* For this substitution we need to build the full set of
3835          template parameters and use that as arguments for the
3836          tsubsting function.  */
3837       tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
3838
3839       /* This will contain the innermost parms of PARM into which
3840          we have substituted so far.  */
3841       innermost_args = make_tree_vec (TREE_VEC_LENGTH (tparms));
3842       targs = add_to_template_args (arglist, innermost_args);
3843       for (j = 0; j < TREE_VEC_LENGTH (tparms); ++j)
3844         {
3845           tree parameter;
3846
3847           parameter = TREE_VEC_ELT (tparms, j);
3848
3849           /* INNERMOST_ARGS needs to have at least the same number
3850              of elements as the index PARAMETER, ortherwise
3851              tsubsting into PARAMETER will result in partially
3852              instantiating it, reducing its tempate parm
3853              level. Let's tactically fill INNERMOST_ARGS for that
3854              purpose.  */
3855           TREE_VEC_ELT (innermost_args, j) =
3856             template_parm_to_arg (parameter);
3857
3858           fixup_template_parm (parameter, j,
3859                                TREE_VEC_LENGTH (tparms),
3860                                targs);
3861         }
3862
3863       /* Now fix up the type of the template template parm.  */
3864
3865       t = fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3866       TREE_TYPE (parm) = t;
3867
3868       TREE_VEC_ELT (fixedup_args, idx) =
3869         template_parm_to_arg (parm_desc);
3870     }
3871   else if (TREE_CODE (parm) == PARM_DECL)
3872     {
3873       /* PARM is a non-type template parameter. We need to:
3874
3875        * Fix up its TEMPLATE_PARM_INDEX to make it carry the
3876        proper number of sibling parameters.
3877
3878        * Make lookups of the template parameter return a reference
3879        to the fixed-up index. No lookup should return references
3880        to the former index anymore.
3881
3882        * Substitute the template parms that got fixed up so far
3883
3884        * into the type of PARM.  */
3885
3886       tree index = DECL_INITIAL (parm);
3887
3888       /* PUSHED_DECL is the decl added to the symbol table with
3889          the name of the parameter. E,g:
3890              
3891          template<class T, T u> //#0
3892          auto my_function(T t) -> decltype(u); //#1
3893
3894          Here, when looking up u at //#1, we get the decl of u
3895          resulting from the declaration in #0. This is what
3896          PUSHED_DECL is. We need to replace the reference to the
3897          old TEMPLATE_PARM_INDEX carried by PUSHED_DECL by the
3898          fixed-up TEMPLATE_PARM_INDEX.  */
3899       tree pushed_decl = TEMPLATE_PARM_DECL (index);
3900
3901       /* Let's fix up the TEMPLATE_PARM_INDEX then. Note that we must
3902          fixup the type of PUSHED_DECL as well and luckily
3903          fixup_template_parm_index does it for us too.  */
3904       tree fixed_up_index =
3905         fixup_template_parm_index (index, arglist, num_parms);
3906
3907       DECL_INITIAL (pushed_decl) = DECL_INITIAL (parm) = fixed_up_index;
3908
3909       /* Add this fixed up PARM to the template parms we've fixed
3910          up so far and use that to substitute the fixed-up
3911          template parms into the type of PARM.  */
3912       TREE_VEC_ELT (fixedup_args, idx) =
3913         template_parm_to_arg (parm_desc);
3914       TREE_TYPE (parm) = tsubst (TREE_TYPE (parm), arglist,
3915                                  tf_none, NULL_TREE);
3916     }
3917
3918   TREE_PURPOSE (parm_desc) =
3919     tsubst_template_arg (TREE_PURPOSE (parm_desc),
3920                          arglist, tf_none, parm);
3921
3922   pop_deferring_access_checks ();
3923 }
3924
3925 /* Walk the current template parms and properly compute the canonical
3926    types of the dependent types created during
3927    cp_parser_template_parameter_list.  */
3928
3929 void
3930 fixup_template_parms (void)
3931 {
3932   tree arglist;
3933   tree parameter_vec;
3934   tree fixedup_args;
3935   int i, num_parms;
3936
3937   parameter_vec = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3938   if (parameter_vec == NULL_TREE)
3939     return;
3940
3941   num_parms = TREE_VEC_LENGTH (parameter_vec);
3942
3943   /* This vector contains the current innermost template parms that
3944      have been fixed up so far.  The form of FIXEDUP_ARGS is suitable
3945      to be passed to tsubst* functions as their ARGS argument.  */
3946   fixedup_args = make_tree_vec (num_parms);
3947
3948   /* This vector contains the full set of template parms in a form
3949      suitable to be passed to substs functions as their ARGS
3950      argument.  */
3951   arglist = current_template_args ();
3952   arglist = add_outermost_template_args (arglist, fixedup_args);
3953
3954   /* Let's do the proper fixup now.  */
3955   for (i = 0; i < num_parms; ++i)
3956     fixup_template_parm (TREE_VEC_ELT (parameter_vec, i),
3957                          i, num_parms, arglist);
3958 }
3959
3960 /* end_template_decl is called after a template declaration is seen.  */
3961
3962 void
3963 end_template_decl (void)
3964 {
3965   reset_specialization ();
3966
3967   if (! processing_template_decl)
3968     return;
3969
3970   /* This matches the pushlevel in begin_template_parm_list.  */
3971   finish_scope ();
3972
3973   --processing_template_decl;
3974   current_template_parms = TREE_CHAIN (current_template_parms);
3975 }
3976
3977 /* Takes a TREE_LIST representing a template parameter and convert it
3978    into an argument suitable to be passed to the type substitution
3979    functions.  Note that If the TREE_LIST contains an error_mark
3980    node, the returned argument is error_mark_node.  */
3981
3982 static tree
3983 template_parm_to_arg (tree t)
3984 {
3985
3986   if (t == NULL_TREE
3987       || TREE_CODE (t) != TREE_LIST)
3988     return t;
3989
3990   if (error_operand_p (TREE_VALUE (t)))
3991     return error_mark_node;
3992
3993   t = TREE_VALUE (t);
3994
3995   if (TREE_CODE (t) == TYPE_DECL
3996       || TREE_CODE (t) == TEMPLATE_DECL)
3997     {
3998       t = TREE_TYPE (t);
3999
4000       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4001         {
4002           /* Turn this argument into a TYPE_ARGUMENT_PACK
4003              with a single element, which expands T.  */
4004           tree vec = make_tree_vec (1);
4005 #ifdef ENABLE_CHECKING
4006           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
4007             (vec, TREE_VEC_LENGTH (vec));
4008 #endif
4009           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4010
4011           t = cxx_make_type (TYPE_ARGUMENT_PACK);
4012           SET_ARGUMENT_PACK_ARGS (t, vec);
4013         }
4014     }
4015   else
4016     {
4017       t = DECL_INITIAL (t);
4018
4019       if (TEMPLATE_PARM_PARAMETER_PACK (t))
4020         {
4021           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4022              with a single element, which expands T.  */
4023           tree vec = make_tree_vec (1);
4024           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
4025 #ifdef ENABLE_CHECKING
4026           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
4027             (vec, TREE_VEC_LENGTH (vec));
4028 #endif
4029           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4030
4031           t  = make_node (NONTYPE_ARGUMENT_PACK);
4032           SET_ARGUMENT_PACK_ARGS (t, vec);
4033           TREE_TYPE (t) = type;
4034         }
4035     }
4036   return t;
4037 }
4038
4039 /* This function returns TRUE if PARM_PACK is a template parameter
4040    pack and if ARG_PACK is what template_parm_to_arg returned when
4041    passed PARM_PACK.  */
4042
4043 static bool
4044 arg_from_parm_pack_p (tree arg_pack, tree parm_pack)
4045 {
4046   /* For clarity in the comments below let's use the representation
4047      argument_pack<elements>' to denote an argument pack and its
4048      elements.
4049
4050      In the 'if' block below, we want to detect cases where
4051      ARG_PACK is argument_pack<PARM_PACK...>.  I.e, we want to
4052      check if ARG_PACK is an argument pack which sole element is
4053      the expansion of PARM_PACK.  That argument pack is typically
4054      created by template_parm_to_arg when passed a parameter
4055      pack.  */
4056
4057   if (arg_pack
4058       && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
4059       && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
4060     {
4061       tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
4062       tree pattern = PACK_EXPANSION_PATTERN (expansion);
4063       /* So we have an argument_pack<P...>.  We want to test if P
4064          is actually PARM_PACK.  We will not use cp_tree_equal to
4065          test P and PARM_PACK because during type fixup (by
4066          fixup_template_parm) P can be a pre-fixup version of a
4067          type and PARM_PACK be its post-fixup version.
4068          cp_tree_equal would consider them as different even
4069          though we would want to consider them compatible for our
4070          precise purpose here.
4071
4072          Thus we are going to consider that P and PARM_PACK are
4073          compatible if they have the same DECL.  */
4074       if ((/* If ARG_PACK is a type parameter pack named by the
4075               same DECL as parm_pack ...  */
4076            (TYPE_P (pattern)
4077             && TYPE_P (parm_pack)
4078             && TYPE_NAME (pattern) == TYPE_NAME (parm_pack))
4079            /* ... or if PARM_PACK is a non-type parameter named by the
4080               same DECL as ARG_PACK.  Note that PARM_PACK being a
4081               non-type parameter means it's either a PARM_DECL or a
4082               TEMPLATE_PARM_INDEX.  */
4083            || (TREE_CODE (pattern) == TEMPLATE_PARM_INDEX
4084                && ((TREE_CODE (parm_pack) == PARM_DECL
4085                     && (TEMPLATE_PARM_DECL (pattern)
4086                         == TEMPLATE_PARM_DECL (DECL_INITIAL (parm_pack))))
4087                    || (TREE_CODE (parm_pack) == TEMPLATE_PARM_INDEX
4088                        && (TEMPLATE_PARM_DECL (pattern)
4089                            == TEMPLATE_PARM_DECL (parm_pack))))))
4090           && template_parameter_pack_p (pattern))
4091         return true;
4092     }
4093   return false;
4094 }
4095
4096 /* Within the declaration of a template, return all levels of template
4097    parameters that apply.  The template parameters are represented as
4098    a TREE_VEC, in the form documented in cp-tree.h for template
4099    arguments.  */
4100
4101 static tree
4102 current_template_args (void)
4103 {
4104   tree header;
4105   tree args = NULL_TREE;
4106   int length = TMPL_PARMS_DEPTH (current_template_parms);
4107   int l = length;
4108
4109   /* If there is only one level of template parameters, we do not
4110      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4111      TREE_VEC containing the arguments.  */
4112   if (length > 1)
4113     args = make_tree_vec (length);
4114
4115   for (header = current_template_parms; header; header = TREE_CHAIN (header))
4116     {
4117       tree a = copy_node (TREE_VALUE (header));
4118       int i;
4119
4120       TREE_TYPE (a) = NULL_TREE;
4121       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4122         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4123
4124 #ifdef ENABLE_CHECKING
4125       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4126 #endif
4127
4128       if (length > 1)
4129         TREE_VEC_ELT (args, --l) = a;
4130       else
4131         args = a;
4132     }
4133
4134     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
4135       /* This can happen for template parms of a template template
4136          parameter, e.g:
4137
4138          template<template<class T, class U> class TT> struct S;
4139
4140          Consider the level of the parms of TT; T and U both have
4141          level 2; TT has no template parm of level 1. So in this case
4142          the first element of full_template_args is NULL_TREE. If we
4143          leave it like this TMPL_ARG_DEPTH on args returns 1 instead
4144          of 2. This will make tsubst wrongly consider that T and U
4145          have level 1. Instead, let's create a dummy vector as the
4146          first element of full_template_args so that TMPL_ARG_DEPTH
4147          returns the correct depth for args.  */
4148       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
4149   return args;
4150 }
4151
4152 /* Update the declared TYPE by doing any lookups which were thought to be
4153    dependent, but are not now that we know the SCOPE of the declarator.  */
4154
4155 tree
4156 maybe_update_decl_type (tree orig_type, tree scope)
4157 {
4158   tree type = orig_type;
4159
4160   if (type == NULL_TREE)
4161     return type;
4162
4163   if (TREE_CODE (orig_type) == TYPE_DECL)
4164     type = TREE_TYPE (type);
4165
4166   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4167       && dependent_type_p (type)
4168       /* Don't bother building up the args in this case.  */
4169       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4170     {
4171       /* tsubst in the args corresponding to the template parameters,
4172          including auto if present.  Most things will be unchanged, but
4173          make_typename_type and tsubst_qualified_id will resolve
4174          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4175       tree args = current_template_args ();
4176       tree auto_node = type_uses_auto (type);
4177       tree pushed;
4178       if (auto_node)
4179         {
4180           tree auto_vec = make_tree_vec (1);
4181           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4182           args = add_to_template_args (args, auto_vec);
4183         }
4184       pushed = push_scope (scope);
4185       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4186       if (pushed)
4187         pop_scope (scope);
4188     }
4189
4190   if (type == error_mark_node)
4191     return orig_type;
4192
4193   if (TREE_CODE (orig_type) == TYPE_DECL)
4194     {
4195       if (same_type_p (type, TREE_TYPE (orig_type)))
4196         type = orig_type;
4197       else
4198         type = TYPE_NAME (type);
4199     }
4200   return type;
4201 }
4202
4203 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4204    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
4205    a member template.  Used by push_template_decl below.  */
4206
4207 static tree
4208 build_template_decl (tree decl, tree parms, bool member_template_p)
4209 {
4210   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4211   DECL_TEMPLATE_PARMS (tmpl) = parms;
4212   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4213   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4214   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4215
4216   return tmpl;
4217 }
4218
4219 struct template_parm_data
4220 {
4221   /* The level of the template parameters we are currently
4222      processing.  */
4223   int level;
4224
4225   /* The index of the specialization argument we are currently
4226      processing.  */
4227   int current_arg;
4228
4229   /* An array whose size is the number of template parameters.  The
4230      elements are nonzero if the parameter has been used in any one
4231      of the arguments processed so far.  */
4232   int* parms;
4233
4234   /* An array whose size is the number of template arguments.  The
4235      elements are nonzero if the argument makes use of template
4236      parameters of this level.  */
4237   int* arg_uses_template_parms;
4238 };
4239
4240 /* Subroutine of push_template_decl used to see if each template
4241    parameter in a partial specialization is used in the explicit
4242    argument list.  If T is of the LEVEL given in DATA (which is
4243    treated as a template_parm_data*), then DATA->PARMS is marked
4244    appropriately.  */
4245
4246 static int
4247 mark_template_parm (tree t, void* data)
4248 {
4249   int level;
4250   int idx;
4251   struct template_parm_data* tpd = (struct template_parm_data*) data;
4252
4253   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4254     {
4255       level = TEMPLATE_PARM_LEVEL (t);
4256       idx = TEMPLATE_PARM_IDX (t);
4257     }
4258   else
4259     {
4260       level = TEMPLATE_TYPE_LEVEL (t);
4261       idx = TEMPLATE_TYPE_IDX (t);
4262     }
4263
4264   if (level == tpd->level)
4265     {
4266       tpd->parms[idx] = 1;
4267       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4268     }
4269
4270   /* Return zero so that for_each_template_parm will continue the
4271      traversal of the tree; we want to mark *every* template parm.  */
4272   return 0;
4273 }
4274
4275 /* Process the partial specialization DECL.  */
4276
4277 static tree
4278 process_partial_specialization (tree decl)
4279 {
4280   tree type = TREE_TYPE (decl);
4281   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
4282   tree specargs = CLASSTYPE_TI_ARGS (type);
4283   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4284   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4285   tree inner_parms;
4286   tree inst;
4287   int nargs = TREE_VEC_LENGTH (inner_args);
4288   int ntparms;
4289   int  i;
4290   bool did_error_intro = false;
4291   struct template_parm_data tpd;
4292   struct template_parm_data tpd2;
4293
4294   gcc_assert (current_template_parms);
4295
4296   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4297   ntparms = TREE_VEC_LENGTH (inner_parms);
4298
4299   /* We check that each of the template parameters given in the
4300      partial specialization is used in the argument list to the
4301      specialization.  For example:
4302
4303        template <class T> struct S;
4304        template <class T> struct S<T*>;
4305
4306      The second declaration is OK because `T*' uses the template
4307      parameter T, whereas
4308
4309        template <class T> struct S<int>;
4310
4311      is no good.  Even trickier is:
4312
4313        template <class T>
4314        struct S1
4315        {
4316           template <class U>
4317           struct S2;
4318           template <class U>
4319           struct S2<T>;
4320        };
4321
4322      The S2<T> declaration is actually invalid; it is a
4323      full-specialization.  Of course,
4324
4325           template <class U>
4326           struct S2<T (*)(U)>;
4327
4328      or some such would have been OK.  */
4329   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4330   tpd.parms = XALLOCAVEC (int, ntparms);
4331   memset (tpd.parms, 0, sizeof (int) * ntparms);
4332
4333   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4334   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4335   for (i = 0; i < nargs; ++i)
4336     {
4337       tpd.current_arg = i;
4338       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4339                               &mark_template_parm,
4340                               &tpd,
4341                               NULL,
4342                               /*include_nondeduced_p=*/false);
4343     }
4344   for (i = 0; i < ntparms; ++i)
4345     if (tpd.parms[i] == 0)
4346       {
4347         /* One of the template parms was not used in the
4348            specialization.  */
4349         if (!did_error_intro)
4350           {
4351             error ("template parameters not used in partial specialization:");
4352             did_error_intro = true;
4353           }
4354
4355         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4356       }
4357
4358   if (did_error_intro)
4359     return error_mark_node;
4360
4361   /* [temp.class.spec]
4362
4363      The argument list of the specialization shall not be identical to
4364      the implicit argument list of the primary template.  */
4365   if (comp_template_args
4366       (inner_args,
4367        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
4368                                                    (maintmpl)))))
4369     error ("partial specialization %qT does not specialize any template arguments", type);
4370
4371   /* [temp.class.spec]
4372
4373      A partially specialized non-type argument expression shall not
4374      involve template parameters of the partial specialization except
4375      when the argument expression is a simple identifier.
4376
4377      The type of a template parameter corresponding to a specialized
4378      non-type argument shall not be dependent on a parameter of the
4379      specialization. 
4380
4381      Also, we verify that pack expansions only occur at the
4382      end of the argument list.  */
4383   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4384   tpd2.parms = 0;
4385   for (i = 0; i < nargs; ++i)
4386     {
4387       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4388       tree arg = TREE_VEC_ELT (inner_args, i);
4389       tree packed_args = NULL_TREE;
4390       int j, len = 1;
4391
4392       if (ARGUMENT_PACK_P (arg))
4393         {
4394           /* Extract the arguments from the argument pack. We'll be
4395              iterating over these in the following loop.  */
4396           packed_args = ARGUMENT_PACK_ARGS (arg);
4397           len = TREE_VEC_LENGTH (packed_args);
4398         }
4399
4400       for (j = 0; j < len; j++)
4401         {
4402           if (packed_args)
4403             /* Get the Jth argument in the parameter pack.  */
4404             arg = TREE_VEC_ELT (packed_args, j);
4405
4406           if (PACK_EXPANSION_P (arg))
4407             {
4408               /* Pack expansions must come at the end of the
4409                  argument list.  */
4410               if ((packed_args && j < len - 1)
4411                   || (!packed_args && i < nargs - 1))
4412                 {
4413                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4414                     error ("parameter pack argument %qE must be at the "
4415                            "end of the template argument list", arg);
4416                   else
4417                     error ("parameter pack argument %qT must be at the "
4418                            "end of the template argument list", arg);
4419                 }
4420             }
4421
4422           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4423             /* We only care about the pattern.  */
4424             arg = PACK_EXPANSION_PATTERN (arg);
4425
4426           if (/* These first two lines are the `non-type' bit.  */
4427               !TYPE_P (arg)
4428               && TREE_CODE (arg) != TEMPLATE_DECL
4429               /* This next line is the `argument expression is not just a
4430                  simple identifier' condition and also the `specialized
4431                  non-type argument' bit.  */
4432               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
4433             {
4434               if ((!packed_args && tpd.arg_uses_template_parms[i])
4435                   || (packed_args && uses_template_parms (arg)))
4436                 error ("template argument %qE involves template parameter(s)",
4437                        arg);
4438               else 
4439                 {
4440                   /* Look at the corresponding template parameter,
4441                      marking which template parameters its type depends
4442                      upon.  */
4443                   tree type = TREE_TYPE (parm);
4444
4445                   if (!tpd2.parms)
4446                     {
4447                       /* We haven't yet initialized TPD2.  Do so now.  */
4448                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4449                       /* The number of parameters here is the number in the
4450                          main template, which, as checked in the assertion
4451                          above, is NARGS.  */
4452                       tpd2.parms = XALLOCAVEC (int, nargs);
4453                       tpd2.level = 
4454                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4455                     }
4456
4457                   /* Mark the template parameters.  But this time, we're
4458                      looking for the template parameters of the main
4459                      template, not in the specialization.  */
4460                   tpd2.current_arg = i;
4461                   tpd2.arg_uses_template_parms[i] = 0;
4462                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4463                   for_each_template_parm (type,
4464                                           &mark_template_parm,
4465                                           &tpd2,
4466                                           NULL,
4467                                           /*include_nondeduced_p=*/false);
4468
4469                   if (tpd2.arg_uses_template_parms [i])
4470                     {
4471                       /* The type depended on some template parameters.
4472                          If they are fully specialized in the
4473                          specialization, that's OK.  */
4474                       int j;
4475                       int count = 0;
4476                       for (j = 0; j < nargs; ++j)
4477                         if (tpd2.parms[j] != 0
4478                             && tpd.arg_uses_template_parms [j])
4479                           ++count;
4480                       if (count != 0)
4481                         error_n (input_location, count,
4482                                  "type %qT of template argument %qE depends "
4483                                  "on a template parameter",
4484                                  "type %qT of template argument %qE depends "
4485                                  "on template parameters",
4486                                  type,
4487                                  arg);
4488                     }
4489                 }
4490             }
4491         }
4492     }
4493
4494   /* We should only get here once.  */
4495   gcc_assert (!COMPLETE_TYPE_P (type));
4496
4497   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4498     = tree_cons (specargs, inner_parms,
4499                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4500   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4501
4502   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4503        inst = TREE_CHAIN (inst))
4504     {
4505       tree inst_type = TREE_VALUE (inst);
4506       if (COMPLETE_TYPE_P (inst_type)
4507           && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4508         {
4509           tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4510           if (spec && TREE_TYPE (spec) == type)
4511             permerror (input_location,
4512                        "partial specialization of %qT after instantiation "
4513                        "of %qT", type, inst_type);
4514         }
4515     }
4516
4517   return decl;
4518 }
4519
4520 /* Check that a template declaration's use of default arguments and
4521    parameter packs is not invalid.  Here, PARMS are the template
4522    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4523    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4524    specialization.
4525    
4526
4527    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4528    declaration (but not a definition); 1 indicates a declaration, 2
4529    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4530    emitted for extraneous default arguments.
4531
4532    Returns TRUE if there were no errors found, FALSE otherwise. */
4533
4534 bool
4535 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4536                          int is_partial, int is_friend_decl)
4537 {
4538   const char *msg;
4539   int last_level_to_check;
4540   tree parm_level;
4541   bool no_errors = true;
4542
4543   /* [temp.param]
4544
4545      A default template-argument shall not be specified in a
4546      function template declaration or a function template definition, nor
4547      in the template-parameter-list of the definition of a member of a
4548      class template.  */
4549
4550   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4551     /* You can't have a function template declaration in a local
4552        scope, nor you can you define a member of a class template in a
4553        local scope.  */
4554     return true;
4555
4556   if (current_class_type
4557       && !TYPE_BEING_DEFINED (current_class_type)
4558       && DECL_LANG_SPECIFIC (decl)
4559       && DECL_DECLARES_FUNCTION_P (decl)
4560       /* If this is either a friend defined in the scope of the class
4561          or a member function.  */
4562       && (DECL_FUNCTION_MEMBER_P (decl)
4563           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4564           : DECL_FRIEND_CONTEXT (decl)
4565           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4566           : false)
4567       /* And, if it was a member function, it really was defined in
4568          the scope of the class.  */
4569       && (!DECL_FUNCTION_MEMBER_P (decl)
4570           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4571     /* We already checked these parameters when the template was
4572        declared, so there's no need to do it again now.  This function
4573        was defined in class scope, but we're processing it's body now
4574        that the class is complete.  */
4575     return true;
4576
4577   /* Core issue 226 (C++0x only): the following only applies to class
4578      templates.  */
4579   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4580     {
4581       /* [temp.param]
4582
4583          If a template-parameter has a default template-argument, all
4584          subsequent template-parameters shall have a default
4585          template-argument supplied.  */
4586       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4587         {
4588           tree inner_parms = TREE_VALUE (parm_level);
4589           int ntparms = TREE_VEC_LENGTH (inner_parms);
4590           int seen_def_arg_p = 0;
4591           int i;
4592
4593           for (i = 0; i < ntparms; ++i)
4594             {
4595               tree parm = TREE_VEC_ELT (inner_parms, i);
4596
4597               if (parm == error_mark_node)
4598                 continue;
4599
4600               if (TREE_PURPOSE (parm))
4601                 seen_def_arg_p = 1;
4602               else if (seen_def_arg_p
4603                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4604                 {
4605                   error ("no default argument for %qD", TREE_VALUE (parm));
4606                   /* For better subsequent error-recovery, we indicate that
4607                      there should have been a default argument.  */
4608                   TREE_PURPOSE (parm) = error_mark_node;
4609                   no_errors = false;
4610                 }
4611               else if (is_primary
4612                        && !is_partial
4613                        && !is_friend_decl
4614                        /* Don't complain about an enclosing partial
4615                           specialization.  */
4616                        && parm_level == parms
4617                        && TREE_CODE (decl) == TYPE_DECL
4618                        && i < ntparms - 1
4619                        && template_parameter_pack_p (TREE_VALUE (parm)))
4620                 {
4621                   /* A primary class template can only have one
4622                      parameter pack, at the end of the template
4623                      parameter list.  */
4624
4625                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4626                     error ("parameter pack %qE must be at the end of the"
4627                            " template parameter list", TREE_VALUE (parm));
4628                   else
4629                     error ("parameter pack %qT must be at the end of the"
4630                            " template parameter list", 
4631                            TREE_TYPE (TREE_VALUE (parm)));
4632
4633                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4634                     = error_mark_node;
4635                   no_errors = false;
4636                 }
4637             }
4638         }
4639     }
4640
4641   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4642       || is_partial 
4643       || !is_primary
4644       || is_friend_decl)
4645     /* For an ordinary class template, default template arguments are
4646        allowed at the innermost level, e.g.:
4647          template <class T = int>
4648          struct S {};
4649        but, in a partial specialization, they're not allowed even
4650        there, as we have in [temp.class.spec]:
4651
4652          The template parameter list of a specialization shall not
4653          contain default template argument values.
4654
4655        So, for a partial specialization, or for a function template
4656        (in C++98/C++03), we look at all of them.  */
4657     ;
4658   else
4659     /* But, for a primary class template that is not a partial
4660        specialization we look at all template parameters except the
4661        innermost ones.  */
4662     parms = TREE_CHAIN (parms);
4663
4664   /* Figure out what error message to issue.  */
4665   if (is_friend_decl == 2)
4666     msg = G_("default template arguments may not be used in function template "
4667              "friend re-declaration");
4668   else if (is_friend_decl)
4669     msg = G_("default template arguments may not be used in function template "
4670              "friend declarations");
4671   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4672     msg = G_("default template arguments may not be used in function templates "
4673              "without -std=c++11 or -std=gnu++11");
4674   else if (is_partial)
4675     msg = G_("default template arguments may not be used in "
4676              "partial specializations");
4677   else
4678     msg = G_("default argument for template parameter for class enclosing %qD");
4679
4680   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4681     /* If we're inside a class definition, there's no need to
4682        examine the parameters to the class itself.  On the one
4683        hand, they will be checked when the class is defined, and,
4684        on the other, default arguments are valid in things like:
4685          template <class T = double>
4686          struct S { template <class U> void f(U); };
4687        Here the default argument for `S' has no bearing on the
4688        declaration of `f'.  */
4689     last_level_to_check = template_class_depth (current_class_type) + 1;
4690   else
4691     /* Check everything.  */
4692     last_level_to_check = 0;
4693
4694   for (parm_level = parms;
4695        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4696        parm_level = TREE_CHAIN (parm_level))
4697     {
4698       tree inner_parms = TREE_VALUE (parm_level);
4699       int i;
4700       int ntparms;
4701
4702       ntparms = TREE_VEC_LENGTH (inner_parms);
4703       for (i = 0; i < ntparms; ++i)
4704         {
4705           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4706             continue;
4707
4708           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4709             {
4710               if (msg)
4711                 {
4712                   no_errors = false;
4713                   if (is_friend_decl == 2)
4714                     return no_errors;
4715
4716                   error (msg, decl);
4717                   msg = 0;
4718                 }
4719
4720               /* Clear out the default argument so that we are not
4721                  confused later.  */
4722               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4723             }
4724         }
4725
4726       /* At this point, if we're still interested in issuing messages,
4727          they must apply to classes surrounding the object declared.  */
4728       if (msg)
4729         msg = G_("default argument for template parameter for class "
4730                  "enclosing %qD");
4731     }
4732
4733   return no_errors;
4734 }
4735
4736 /* Worker for push_template_decl_real, called via
4737    for_each_template_parm.  DATA is really an int, indicating the
4738    level of the parameters we are interested in.  If T is a template
4739    parameter of that level, return nonzero.  */
4740
4741 static int
4742 template_parm_this_level_p (tree t, void* data)
4743 {
4744   int this_level = *(int *)data;
4745   int level;
4746
4747   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4748     level = TEMPLATE_PARM_LEVEL (t);
4749   else
4750     level = TEMPLATE_TYPE_LEVEL (t);
4751   return level == this_level;
4752 }
4753
4754 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4755    parameters given by current_template_args, or reuses a
4756    previously existing one, if appropriate.  Returns the DECL, or an
4757    equivalent one, if it is replaced via a call to duplicate_decls.
4758
4759    If IS_FRIEND is true, DECL is a friend declaration.  */
4760
4761 tree
4762 push_template_decl_real (tree decl, bool is_friend)
4763 {
4764   tree tmpl;
4765   tree args;
4766   tree info;
4767   tree ctx;
4768   int primary;
4769   int is_partial;
4770   int new_template_p = 0;
4771   /* True if the template is a member template, in the sense of
4772      [temp.mem].  */
4773   bool member_template_p = false;
4774
4775   if (decl == error_mark_node || !current_template_parms)
4776     return error_mark_node;
4777
4778   /* See if this is a partial specialization.  */
4779   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4780                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4781                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4782
4783   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4784     is_friend = true;
4785
4786   if (is_friend)
4787     /* For a friend, we want the context of the friend function, not
4788        the type of which it is a friend.  */
4789     ctx = CP_DECL_CONTEXT (decl);
4790   else if (CP_DECL_CONTEXT (decl)
4791            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4792     /* In the case of a virtual function, we want the class in which
4793        it is defined.  */
4794     ctx = CP_DECL_CONTEXT (decl);
4795   else
4796     /* Otherwise, if we're currently defining some class, the DECL
4797        is assumed to be a member of the class.  */
4798     ctx = current_scope ();
4799
4800   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4801     ctx = NULL_TREE;
4802
4803   if (!DECL_CONTEXT (decl))
4804     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4805
4806   /* See if this is a primary template.  */
4807   if (is_friend && ctx)
4808     /* A friend template that specifies a class context, i.e.
4809          template <typename T> friend void A<T>::f();
4810        is not primary.  */
4811     primary = 0;
4812   else
4813     primary = template_parm_scope_p ();
4814
4815   if (primary)
4816     {
4817       if (DECL_CLASS_SCOPE_P (decl))
4818         member_template_p = true;
4819       if (TREE_CODE (decl) == TYPE_DECL
4820           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4821         {
4822           error ("template class without a name");
4823           return error_mark_node;
4824         }
4825       else if (TREE_CODE (decl) == FUNCTION_DECL)
4826         {
4827           if (DECL_DESTRUCTOR_P (decl))
4828             {
4829               /* [temp.mem]
4830
4831                  A destructor shall not be a member template.  */
4832               error ("destructor %qD declared as member template", decl);
4833               return error_mark_node;
4834             }
4835           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4836               && (!prototype_p (TREE_TYPE (decl))
4837                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4838                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4839                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4840                       == void_list_node)))
4841             {
4842               /* [basic.stc.dynamic.allocation]
4843
4844                  An allocation function can be a function
4845                  template. ... Template allocation functions shall
4846                  have two or more parameters.  */
4847               error ("invalid template declaration of %qD", decl);
4848               return error_mark_node;
4849             }
4850         }
4851       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4852                && CLASS_TYPE_P (TREE_TYPE (decl)))
4853         /* OK */;
4854       else if (TREE_CODE (decl) == TYPE_DECL
4855                && TYPE_DECL_ALIAS_P (decl))
4856         /* alias-declaration */
4857         gcc_assert (!DECL_ARTIFICIAL (decl));
4858       else
4859         {
4860           error ("template declaration of %q#D", decl);
4861           return error_mark_node;
4862         }
4863     }
4864
4865   /* Check to see that the rules regarding the use of default
4866      arguments are not being violated.  */
4867   check_default_tmpl_args (decl, current_template_parms,
4868                            primary, is_partial, /*is_friend_decl=*/0);
4869
4870   /* Ensure that there are no parameter packs in the type of this
4871      declaration that have not been expanded.  */
4872   if (TREE_CODE (decl) == FUNCTION_DECL)
4873     {
4874       /* Check each of the arguments individually to see if there are
4875          any bare parameter packs.  */
4876       tree type = TREE_TYPE (decl);
4877       tree arg = DECL_ARGUMENTS (decl);
4878       tree argtype = TYPE_ARG_TYPES (type);
4879
4880       while (arg && argtype)
4881         {
4882           if (!FUNCTION_PARAMETER_PACK_P (arg)
4883               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4884             {
4885             /* This is a PARM_DECL that contains unexpanded parameter
4886                packs. We have already complained about this in the
4887                check_for_bare_parameter_packs call, so just replace
4888                these types with ERROR_MARK_NODE.  */
4889               TREE_TYPE (arg) = error_mark_node;
4890               TREE_VALUE (argtype) = error_mark_node;
4891             }
4892
4893           arg = DECL_CHAIN (arg);
4894           argtype = TREE_CHAIN (argtype);
4895         }
4896
4897       /* Check for bare parameter packs in the return type and the
4898          exception specifiers.  */
4899       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4900         /* Errors were already issued, set return type to int
4901            as the frontend doesn't expect error_mark_node as
4902            the return type.  */
4903         TREE_TYPE (type) = integer_type_node;
4904       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4905         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4906     }
4907   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4908     {
4909       TREE_TYPE (decl) = error_mark_node;
4910       return error_mark_node;
4911     }
4912
4913   if (is_partial)
4914     return process_partial_specialization (decl);
4915
4916   args = current_template_args ();
4917
4918   if (!ctx
4919       || TREE_CODE (ctx) == FUNCTION_DECL
4920       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4921       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4922     {
4923       if (DECL_LANG_SPECIFIC (decl)
4924           && DECL_TEMPLATE_INFO (decl)
4925           && DECL_TI_TEMPLATE (decl))
4926         tmpl = DECL_TI_TEMPLATE (decl);
4927       /* If DECL is a TYPE_DECL for a class-template, then there won't
4928          be DECL_LANG_SPECIFIC.  The information equivalent to
4929          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4930       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4931                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4932                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4933         {
4934           /* Since a template declaration already existed for this
4935              class-type, we must be redeclaring it here.  Make sure
4936              that the redeclaration is valid.  */
4937           redeclare_class_template (TREE_TYPE (decl),
4938                                     current_template_parms);
4939           /* We don't need to create a new TEMPLATE_DECL; just use the
4940              one we already had.  */
4941           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4942         }
4943       else
4944         {
4945           tmpl = build_template_decl (decl, current_template_parms,
4946                                       member_template_p);
4947           new_template_p = 1;
4948
4949           if (DECL_LANG_SPECIFIC (decl)
4950               && DECL_TEMPLATE_SPECIALIZATION (decl))
4951             {
4952               /* A specialization of a member template of a template
4953                  class.  */
4954               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4955               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4956               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4957             }
4958         }
4959     }
4960   else
4961     {
4962       tree a, t, current, parms;
4963       int i;
4964       tree tinfo = get_template_info (decl);
4965
4966       if (!tinfo)
4967         {
4968           error ("template definition of non-template %q#D", decl);
4969           return error_mark_node;
4970         }
4971
4972       tmpl = TI_TEMPLATE (tinfo);
4973
4974       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4975           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4976           && DECL_TEMPLATE_SPECIALIZATION (decl)
4977           && DECL_MEMBER_TEMPLATE_P (tmpl))
4978         {
4979           tree new_tmpl;
4980
4981           /* The declaration is a specialization of a member
4982              template, declared outside the class.  Therefore, the
4983              innermost template arguments will be NULL, so we
4984              replace them with the arguments determined by the
4985              earlier call to check_explicit_specialization.  */
4986           args = DECL_TI_ARGS (decl);
4987
4988           new_tmpl
4989             = build_template_decl (decl, current_template_parms,
4990                                    member_template_p);
4991           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4992           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4993           DECL_TI_TEMPLATE (decl) = new_tmpl;
4994           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4995           DECL_TEMPLATE_INFO (new_tmpl)
4996             = build_template_info (tmpl, args);
4997
4998           register_specialization (new_tmpl,
4999                                    most_general_template (tmpl),
5000                                    args,
5001                                    is_friend, 0);
5002           return decl;
5003         }
5004
5005       /* Make sure the template headers we got make sense.  */
5006
5007       parms = DECL_TEMPLATE_PARMS (tmpl);
5008       i = TMPL_PARMS_DEPTH (parms);
5009       if (TMPL_ARGS_DEPTH (args) != i)
5010         {
5011           error ("expected %d levels of template parms for %q#D, got %d",
5012                  i, decl, TMPL_ARGS_DEPTH (args));
5013         }
5014       else
5015         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
5016           {
5017             a = TMPL_ARGS_LEVEL (args, i);
5018             t = INNERMOST_TEMPLATE_PARMS (parms);
5019
5020             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
5021               {
5022                 if (current == decl)
5023                   error ("got %d template parameters for %q#D",
5024                          TREE_VEC_LENGTH (a), decl);
5025                 else
5026                   error ("got %d template parameters for %q#T",
5027                          TREE_VEC_LENGTH (a), current);
5028                 error ("  but %d required", TREE_VEC_LENGTH (t));
5029                 return error_mark_node;
5030               }
5031
5032             if (current == decl)
5033               current = ctx;
5034             else if (current == NULL_TREE)
5035               /* Can happen in erroneous input.  */
5036               break;
5037             else
5038               current = (TYPE_P (current)
5039                          ? TYPE_CONTEXT (current)
5040                          : DECL_CONTEXT (current));
5041           }
5042
5043       /* Check that the parms are used in the appropriate qualifying scopes
5044          in the declarator.  */
5045       if (!comp_template_args
5046           (TI_ARGS (tinfo),
5047            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5048         {
5049           error ("\
5050 template arguments to %qD do not match original template %qD",
5051                  decl, DECL_TEMPLATE_RESULT (tmpl));
5052           if (!uses_template_parms (TI_ARGS (tinfo)))
5053             inform (input_location, "use template<> for an explicit specialization");
5054           /* Avoid crash in import_export_decl.  */
5055           DECL_INTERFACE_KNOWN (decl) = 1;
5056           return error_mark_node;
5057         }
5058     }
5059
5060   DECL_TEMPLATE_RESULT (tmpl) = decl;
5061   TREE_TYPE (tmpl) = TREE_TYPE (decl);
5062
5063   /* Push template declarations for global functions and types.  Note
5064      that we do not try to push a global template friend declared in a
5065      template class; such a thing may well depend on the template
5066      parameters of the class.  */
5067   if (new_template_p && !ctx
5068       && !(is_friend && template_class_depth (current_class_type) > 0))
5069     {
5070       tmpl = pushdecl_namespace_level (tmpl, is_friend);
5071       if (tmpl == error_mark_node)
5072         return error_mark_node;
5073
5074       /* Hide template friend classes that haven't been declared yet.  */
5075       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
5076         {
5077           DECL_ANTICIPATED (tmpl) = 1;
5078           DECL_FRIEND_P (tmpl) = 1;
5079         }
5080     }
5081
5082   if (primary)
5083     {
5084       tree parms = DECL_TEMPLATE_PARMS (tmpl);
5085       int i;
5086
5087       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5088       if (DECL_CONV_FN_P (tmpl))
5089         {
5090           int depth = TMPL_PARMS_DEPTH (parms);
5091
5092           /* It is a conversion operator. See if the type converted to
5093              depends on innermost template operands.  */
5094
5095           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
5096                                          depth))
5097             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
5098         }
5099
5100       /* Give template template parms a DECL_CONTEXT of the template
5101          for which they are a parameter.  */
5102       parms = INNERMOST_TEMPLATE_PARMS (parms);
5103       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5104         {
5105           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5106           if (TREE_CODE (parm) == TEMPLATE_DECL)
5107             DECL_CONTEXT (parm) = tmpl;
5108         }
5109     }
5110
5111   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5112      back to its most general template.  If TMPL is a specialization,
5113      ARGS may only have the innermost set of arguments.  Add the missing
5114      argument levels if necessary.  */
5115   if (DECL_TEMPLATE_INFO (tmpl))
5116     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5117
5118   info = build_template_info (tmpl, args);
5119
5120   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5121     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5122   else
5123     {
5124       if (primary && !DECL_LANG_SPECIFIC (decl))
5125         retrofit_lang_decl (decl);
5126       if (DECL_LANG_SPECIFIC (decl))
5127         DECL_TEMPLATE_INFO (decl) = info;
5128     }
5129
5130   return DECL_TEMPLATE_RESULT (tmpl);
5131 }
5132
5133 tree
5134 push_template_decl (tree decl)
5135 {
5136   return push_template_decl_real (decl, false);
5137 }
5138
5139 /* Called when a class template TYPE is redeclared with the indicated
5140    template PARMS, e.g.:
5141
5142      template <class T> struct S;
5143      template <class T> struct S {};  */
5144
5145 bool
5146 redeclare_class_template (tree type, tree parms)
5147 {
5148   tree tmpl;
5149   tree tmpl_parms;
5150   int i;
5151
5152   if (!TYPE_TEMPLATE_INFO (type))
5153     {
5154       error ("%qT is not a template type", type);
5155       return false;
5156     }
5157
5158   tmpl = TYPE_TI_TEMPLATE (type);
5159   if (!PRIMARY_TEMPLATE_P (tmpl))
5160     /* The type is nested in some template class.  Nothing to worry
5161        about here; there are no new template parameters for the nested
5162        type.  */
5163     return true;
5164
5165   if (!parms)
5166     {
5167       error ("template specifiers not specified in declaration of %qD",
5168              tmpl);
5169       return false;
5170     }
5171
5172   parms = INNERMOST_TEMPLATE_PARMS (parms);
5173   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5174
5175   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5176     {
5177       error_n (input_location, TREE_VEC_LENGTH (parms),
5178                "redeclared with %d template parameter",
5179                "redeclared with %d template parameters",
5180                TREE_VEC_LENGTH (parms));
5181       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
5182                 "previous declaration %q+D used %d template parameter",
5183                 "previous declaration %q+D used %d template parameters",
5184                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5185       return false;
5186     }
5187
5188   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5189     {
5190       tree tmpl_parm;
5191       tree parm;
5192       tree tmpl_default;
5193       tree parm_default;
5194
5195       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5196           || TREE_VEC_ELT (parms, i) == error_mark_node)
5197         continue;
5198
5199       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5200       if (tmpl_parm == error_mark_node)
5201         return false;
5202
5203       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5204       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5205       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5206
5207       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5208          TEMPLATE_DECL.  */
5209       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5210           || (TREE_CODE (tmpl_parm) != TYPE_DECL
5211               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5212           || (TREE_CODE (tmpl_parm) != PARM_DECL
5213               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5214                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5215           || (TREE_CODE (tmpl_parm) == PARM_DECL
5216               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5217                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5218         {
5219           error ("template parameter %q+#D", tmpl_parm);
5220           error ("redeclared here as %q#D", parm);
5221           return false;
5222         }
5223
5224       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5225         {
5226           /* We have in [temp.param]:
5227
5228              A template-parameter may not be given default arguments
5229              by two different declarations in the same scope.  */
5230           error_at (input_location, "redefinition of default argument for %q#D", parm);
5231           inform (DECL_SOURCE_LOCATION (tmpl_parm),
5232                   "original definition appeared here");
5233           return false;
5234         }
5235
5236       if (parm_default != NULL_TREE)
5237         /* Update the previous template parameters (which are the ones
5238            that will really count) with the new default value.  */
5239         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5240       else if (tmpl_default != NULL_TREE)
5241         /* Update the new parameters, too; they'll be used as the
5242            parameters for any members.  */
5243         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5244     }
5245
5246     return true;
5247 }
5248
5249 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5250    (possibly simplified) expression.  */
5251
5252 static tree
5253 fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5254 {
5255   if (expr == NULL_TREE)
5256     return NULL_TREE;
5257
5258   /* If we're in a template, but EXPR isn't value dependent, simplify
5259      it.  We're supposed to treat:
5260
5261        template <typename T> void f(T[1 + 1]);
5262        template <typename T> void f(T[2]);
5263
5264      as two declarations of the same function, for example.  */
5265   if (processing_template_decl
5266       && !type_dependent_expression_p (expr)
5267       && potential_constant_expression (expr)
5268       && !value_dependent_expression_p (expr))
5269     {
5270       HOST_WIDE_INT saved_processing_template_decl;
5271
5272       saved_processing_template_decl = processing_template_decl;
5273       processing_template_decl = 0;
5274       expr = tsubst_copy_and_build (expr,
5275                                     /*args=*/NULL_TREE,
5276                                     complain,
5277                                     /*in_decl=*/NULL_TREE,
5278                                     /*function_p=*/false,
5279                                     /*integral_constant_expression_p=*/true);
5280       processing_template_decl = saved_processing_template_decl;
5281     }
5282   return expr;
5283 }
5284
5285 tree
5286 fold_non_dependent_expr (tree expr)
5287 {
5288   return fold_non_dependent_expr_sfinae (expr, tf_error);
5289 }
5290
5291 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
5292    template declaration, or a TYPE_DECL for an alias declaration.  */
5293
5294 bool
5295 alias_type_or_template_p (tree t)
5296 {
5297   if (t == NULL_TREE)
5298     return false;
5299   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
5300           || (TYPE_P (t)
5301               && TYPE_NAME (t)
5302               && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
5303           || DECL_ALIAS_TEMPLATE_P (t));
5304 }
5305
5306 /* Return TRUE iff is a specialization of an alias template.  */
5307
5308 bool
5309 alias_template_specialization_p (tree t)
5310 {
5311   if (t == NULL_TREE)
5312     return false;
5313   return (primary_template_instantiation_p (t)
5314           && DECL_ALIAS_TEMPLATE_P (TYPE_TI_TEMPLATE (t)));
5315 }
5316
5317 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5318    must be a function or a pointer-to-function type, as specified
5319    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5320    and check that the resulting function has external linkage.  */
5321
5322 static tree
5323 convert_nontype_argument_function (tree type, tree expr)
5324 {
5325   tree fns = expr;
5326   tree fn, fn_no_ptr;
5327
5328   fn = instantiate_type (type, fns, tf_none);
5329   if (fn == error_mark_node)
5330     return error_mark_node;
5331
5332   fn_no_ptr = fn;
5333   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5334     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5335   if (BASELINK_P (fn_no_ptr))
5336     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5337  
5338   /* [temp.arg.nontype]/1
5339
5340      A template-argument for a non-type, non-template template-parameter
5341      shall be one of:
5342      [...]
5343      -- the address of an object or function with external linkage.  */
5344   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
5345     {
5346       error ("%qE is not a valid template argument for type %qT "
5347              "because function %qD has not external linkage",
5348              expr, type, fn_no_ptr);
5349       return NULL_TREE;
5350     }
5351
5352   return fn;
5353 }
5354
5355 /* Subroutine of convert_nontype_argument.
5356    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5357    Emit an error otherwise.  */
5358
5359 static bool
5360 check_valid_ptrmem_cst_expr (tree type, tree expr,
5361                              tsubst_flags_t complain)
5362 {
5363   STRIP_NOPS (expr);
5364   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5365     return true;
5366   if (cxx_dialect >= cxx0x && null_member_pointer_value_p (expr))
5367     return true;
5368   if (complain & tf_error)
5369     {
5370       error ("%qE is not a valid template argument for type %qT",
5371              expr, type);
5372       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5373     }
5374   return false;
5375 }
5376
5377 /* Returns TRUE iff the address of OP is value-dependent.
5378
5379    14.6.2.4 [temp.dep.temp]:
5380    A non-integral non-type template-argument is dependent if its type is
5381    dependent or it has either of the following forms
5382      qualified-id
5383      & qualified-id
5384    and contains a nested-name-specifier which specifies a class-name that
5385    names a dependent type.
5386
5387    We generalize this to just say that the address of a member of a
5388    dependent class is value-dependent; the above doesn't cover the
5389    address of a static data member named with an unqualified-id.  */
5390
5391 static bool
5392 has_value_dependent_address (tree op)
5393 {
5394   /* We could use get_inner_reference here, but there's no need;
5395      this is only relevant for template non-type arguments, which
5396      can only be expressed as &id-expression.  */
5397   if (DECL_P (op))
5398     {
5399       tree ctx = CP_DECL_CONTEXT (op);
5400       if (TYPE_P (ctx) && dependent_type_p (ctx))
5401         return true;
5402     }
5403
5404   return false;
5405 }
5406
5407 /* The next set of functions are used for providing helpful explanatory
5408    diagnostics for failed overload resolution.  Their messages should be
5409    indented by two spaces for consistency with the messages in
5410    call.c  */
5411
5412 static int
5413 unify_success (bool explain_p ATTRIBUTE_UNUSED)
5414 {
5415   return 0;
5416 }
5417
5418 static int
5419 unify_parameter_deduction_failure (bool explain_p, tree parm)
5420 {
5421   if (explain_p)
5422     inform (input_location,
5423             "  couldn't deduce template parameter %qD", parm);
5424   return 1;
5425 }
5426
5427 static int
5428 unify_invalid (bool explain_p ATTRIBUTE_UNUSED)
5429 {
5430   return 1;
5431 }
5432
5433 static int
5434 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
5435 {
5436   if (explain_p)
5437     inform (input_location,
5438             "  types %qT and %qT have incompatible cv-qualifiers",
5439             parm, arg);
5440   return 1;
5441 }
5442
5443 static int
5444 unify_type_mismatch (bool explain_p, tree parm, tree arg)
5445 {
5446   if (explain_p)
5447     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
5448   return 1;
5449 }
5450
5451 static int
5452 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
5453 {
5454   if (explain_p)
5455     inform (input_location,
5456             "  template parameter %qD is not a parameter pack, but "
5457             "argument %qD is",
5458             parm, arg);
5459   return 1;
5460 }
5461
5462 static int
5463 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
5464 {
5465   if (explain_p)
5466     inform (input_location,
5467             "  template argument %qE does not match "
5468             "pointer-to-member constant %qE",
5469             arg, parm);
5470   return 1;
5471 }
5472
5473 static int
5474 unify_expression_unequal (bool explain_p, tree parm, tree arg)
5475 {
5476   if (explain_p)
5477     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
5478   return 1;
5479 }
5480
5481 static int
5482 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
5483 {
5484   if (explain_p)
5485     inform (input_location,
5486             "  inconsistent parameter pack deduction with %qT and %qT",
5487             old_arg, new_arg);
5488   return 1;
5489 }
5490
5491 static int
5492 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
5493 {
5494   if (explain_p)
5495     inform (input_location,
5496             "  deduced conflicting types for parameter %qT (%qT and %qT)",
5497             parm, first, second);
5498   return 1;
5499 }
5500
5501 static int
5502 unify_vla_arg (bool explain_p, tree arg)
5503 {
5504   if (explain_p)
5505     inform (input_location,
5506             "  variable-sized array type %qT is not "
5507             "a valid template argument",
5508             arg);
5509   return 1;
5510 }
5511
5512 static int
5513 unify_method_type_error (bool explain_p, tree arg)
5514 {
5515   if (explain_p)
5516     inform (input_location,
5517             "  member function type %qT is not a valid template argument",
5518             arg);
5519   return 1;
5520 }
5521
5522 static int
5523 unify_arity (bool explain_p, int have, int wanted)
5524 {
5525   if (explain_p)
5526     inform_n (input_location, wanted,
5527               "  candidate expects %d argument, %d provided",
5528               "  candidate expects %d arguments, %d provided",
5529               wanted, have);
5530   return 1;
5531 }
5532
5533 static int
5534 unify_too_many_arguments (bool explain_p, int have, int wanted)
5535 {
5536   return unify_arity (explain_p, have, wanted);
5537 }
5538
5539 static int
5540 unify_too_few_arguments (bool explain_p, int have, int wanted)
5541 {
5542   return unify_arity (explain_p, have, wanted);
5543 }
5544
5545 static int
5546 unify_arg_conversion (bool explain_p, tree to_type,
5547                       tree from_type, tree arg)
5548 {
5549   if (explain_p)
5550     inform (input_location, "  cannot convert %qE (type %qT) to type %qT",
5551             arg, from_type, to_type);
5552   return 1;
5553 }
5554
5555 static int
5556 unify_no_common_base (bool explain_p, enum template_base_result r,
5557                       tree parm, tree arg)
5558 {
5559   if (explain_p)
5560     switch (r)
5561       {
5562       case tbr_ambiguous_baseclass:
5563         inform (input_location, "  %qT is an ambiguous base class of %qT",
5564                 arg, parm);
5565         break;
5566       default:
5567         inform (input_location, "  %qT is not derived from %qT", arg, parm);
5568         break;
5569       }
5570   return 1;
5571 }
5572
5573 static int
5574 unify_inconsistent_template_template_parameters (bool explain_p)
5575 {
5576   if (explain_p)
5577     inform (input_location,
5578             "  template parameters of a template template argument are "
5579             "inconsistent with other deduced template arguments");
5580   return 1;
5581 }
5582
5583 static int
5584 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
5585 {
5586   if (explain_p)
5587     inform (input_location,
5588             "  can't deduce a template for %qT from non-template type %qT",
5589             parm, arg);
5590   return 1;
5591 }
5592
5593 static int
5594 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
5595 {
5596   if (explain_p)
5597     inform (input_location,
5598             "  template argument %qE does not match %qD", arg, parm);
5599   return 1;
5600 }
5601
5602 static int
5603 unify_overload_resolution_failure (bool explain_p, tree arg)
5604 {
5605   if (explain_p)
5606     inform (input_location,
5607             "  could not resolve address from overloaded function %qE",
5608             arg);
5609   return 1;
5610 }
5611
5612 /* Attempt to convert the non-type template parameter EXPR to the
5613    indicated TYPE.  If the conversion is successful, return the
5614    converted value.  If the conversion is unsuccessful, return
5615    NULL_TREE if we issued an error message, or error_mark_node if we
5616    did not.  We issue error messages for out-and-out bad template
5617    parameters, but not simply because the conversion failed, since we
5618    might be just trying to do argument deduction.  Both TYPE and EXPR
5619    must be non-dependent.
5620
5621    The conversion follows the special rules described in
5622    [temp.arg.nontype], and it is much more strict than an implicit
5623    conversion.
5624
5625    This function is called twice for each template argument (see
5626    lookup_template_class for a more accurate description of this
5627    problem). This means that we need to handle expressions which
5628    are not valid in a C++ source, but can be created from the
5629    first call (for instance, casts to perform conversions). These
5630    hacks can go away after we fix the double coercion problem.  */
5631
5632 static tree
5633 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5634 {
5635   tree expr_type;
5636
5637   /* Detect immediately string literals as invalid non-type argument.
5638      This special-case is not needed for correctness (we would easily
5639      catch this later), but only to provide better diagnostic for this
5640      common user mistake. As suggested by DR 100, we do not mention
5641      linkage issues in the diagnostic as this is not the point.  */
5642   /* FIXME we're making this OK.  */
5643   if (TREE_CODE (expr) == STRING_CST)
5644     {
5645       if (complain & tf_error)
5646         error ("%qE is not a valid template argument for type %qT "
5647                "because string literals can never be used in this context",
5648                expr, type);
5649       return NULL_TREE;
5650     }
5651
5652   /* Add the ADDR_EXPR now for the benefit of
5653      value_dependent_expression_p.  */
5654   if (TYPE_PTROBV_P (type)
5655       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
5656     expr = decay_conversion (expr);
5657
5658   /* If we are in a template, EXPR may be non-dependent, but still
5659      have a syntactic, rather than semantic, form.  For example, EXPR
5660      might be a SCOPE_REF, rather than the VAR_DECL to which the
5661      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5662      so that access checking can be performed when the template is
5663      instantiated -- but here we need the resolved form so that we can
5664      convert the argument.  */
5665   if (TYPE_REF_OBJ_P (type)
5666       && has_value_dependent_address (expr))
5667     /* If we want the address and it's value-dependent, don't fold.  */;
5668   else if (!type_unknown_p (expr))
5669     expr = fold_non_dependent_expr_sfinae (expr, complain);
5670   if (error_operand_p (expr))
5671     return error_mark_node;
5672   expr_type = TREE_TYPE (expr);
5673   if (TREE_CODE (type) == REFERENCE_TYPE)
5674     expr = mark_lvalue_use (expr);
5675   else
5676     expr = mark_rvalue_use (expr);
5677
5678   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
5679      to a non-type argument of "nullptr".  */
5680   if (expr == nullptr_node
5681       && (TYPE_PTR_P (type) || TYPE_PTR_TO_MEMBER_P (type)))
5682     expr = convert (type, expr);
5683
5684   /* In C++11, integral or enumeration non-type template arguments can be
5685      arbitrary constant expressions.  Pointer and pointer to
5686      member arguments can be general constant expressions that evaluate
5687      to a null value, but otherwise still need to be of a specific form.  */
5688   if (cxx_dialect >= cxx0x)
5689     {
5690       if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5691         expr = maybe_constant_value (expr);
5692       else if (TYPE_PTR_P (type)
5693                || (TYPE_PTR_TO_MEMBER_P (type)
5694                    && TREE_CODE (expr) != PTRMEM_CST))
5695         {
5696           tree folded = maybe_constant_value (expr);
5697           if (TYPE_PTR_P (type) ? integer_zerop (folded)
5698               : null_member_pointer_value_p (folded))
5699             expr = folded;
5700         }
5701     }
5702
5703   /* HACK: Due to double coercion, we can get a
5704      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5705      which is the tree that we built on the first call (see
5706      below when coercing to reference to object or to reference to
5707      function). We just strip everything and get to the arg.
5708      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5709      for examples.  */
5710   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5711     {
5712       tree probe_type, probe = expr;
5713       if (REFERENCE_REF_P (probe))
5714         probe = TREE_OPERAND (probe, 0);
5715       probe_type = TREE_TYPE (probe);
5716       if (TREE_CODE (probe) == NOP_EXPR)
5717         {
5718           /* ??? Maybe we could use convert_from_reference here, but we
5719              would need to relax its constraints because the NOP_EXPR
5720              could actually change the type to something more cv-qualified,
5721              and this is not folded by convert_from_reference.  */
5722           tree addr = TREE_OPERAND (probe, 0);
5723           gcc_assert (TREE_CODE (probe_type) == REFERENCE_TYPE);
5724           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
5725           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
5726           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5727                       (TREE_TYPE (probe_type),
5728                        TREE_TYPE (TREE_TYPE (addr))));
5729
5730           expr = TREE_OPERAND (addr, 0);
5731           expr_type = TREE_TYPE (expr);
5732         }
5733     }
5734
5735   /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5736      parameter is a pointer to object, through decay and
5737      qualification conversion. Let's strip everything.  */
5738   else if (TREE_CODE (expr) == NOP_EXPR && TYPE_PTROBV_P (type))
5739     {
5740       STRIP_NOPS (expr);
5741       gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5742       gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5743       /* Skip the ADDR_EXPR only if it is part of the decay for
5744          an array. Otherwise, it is part of the original argument
5745          in the source code.  */
5746       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5747         expr = TREE_OPERAND (expr, 0);
5748       expr_type = TREE_TYPE (expr);
5749     }
5750
5751   /* [temp.arg.nontype]/5, bullet 1
5752
5753      For a non-type template-parameter of integral or enumeration type,
5754      integral promotions (_conv.prom_) and integral conversions
5755      (_conv.integral_) are applied.  */
5756   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5757     {
5758       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5759       t = maybe_constant_value (t);
5760       if (t != error_mark_node)
5761         expr = t;
5762
5763       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5764         return error_mark_node;
5765
5766       /* Notice that there are constant expressions like '4 % 0' which
5767          do not fold into integer constants.  */
5768       if (TREE_CODE (expr) != INTEGER_CST)
5769         {
5770           if (complain & tf_error)
5771             {
5772               int errs = errorcount, warns = warningcount;
5773               expr = cxx_constant_value (expr);
5774               if (errorcount > errs || warningcount > warns)
5775                 inform (EXPR_LOC_OR_HERE (expr),
5776                         "in template argument for type %qT ", type);
5777               if (expr == error_mark_node)
5778                 return NULL_TREE;
5779               /* else cxx_constant_value complained but gave us
5780                  a real constant, so go ahead.  */
5781               gcc_assert (TREE_CODE (expr) == INTEGER_CST);
5782             }
5783           else
5784             return NULL_TREE;
5785         }
5786     }
5787   /* [temp.arg.nontype]/5, bullet 2
5788
5789      For a non-type template-parameter of type pointer to object,
5790      qualification conversions (_conv.qual_) and the array-to-pointer
5791      conversion (_conv.array_) are applied.  */
5792   else if (TYPE_PTROBV_P (type))
5793     {
5794       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5795
5796          A template-argument for a non-type, non-template template-parameter
5797          shall be one of: [...]
5798
5799          -- the name of a non-type template-parameter;
5800          -- the address of an object or function with external linkage, [...]
5801             expressed as "& id-expression" where the & is optional if the name
5802             refers to a function or array, or if the corresponding
5803             template-parameter is a reference.
5804
5805         Here, we do not care about functions, as they are invalid anyway
5806         for a parameter of type pointer-to-object.  */
5807
5808       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5809         /* Non-type template parameters are OK.  */
5810         ;
5811       else if (cxx_dialect >= cxx0x && integer_zerop (expr))
5812         /* Null pointer values are OK in C++11.  */;
5813       else if (TREE_CODE (expr) != ADDR_EXPR
5814                && TREE_CODE (expr_type) != ARRAY_TYPE)
5815         {
5816           if (TREE_CODE (expr) == VAR_DECL)
5817             {
5818               error ("%qD is not a valid template argument "
5819                      "because %qD is a variable, not the address of "
5820                      "a variable",
5821                      expr, expr);
5822               return NULL_TREE;
5823             }
5824           /* Other values, like integer constants, might be valid
5825              non-type arguments of some other type.  */
5826           return error_mark_node;
5827         }
5828       else
5829         {
5830           tree decl;
5831
5832           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5833                   ? TREE_OPERAND (expr, 0) : expr);
5834           if (TREE_CODE (decl) != VAR_DECL)
5835             {
5836               error ("%qE is not a valid template argument of type %qT "
5837                      "because %qE is not a variable",
5838                      expr, type, decl);
5839               return NULL_TREE;
5840             }
5841           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5842             {
5843               error ("%qE is not a valid template argument of type %qT "
5844                      "because %qD does not have external linkage",
5845                      expr, type, decl);
5846               return NULL_TREE;
5847             }
5848         }
5849
5850       expr = decay_conversion (expr);
5851       if (expr == error_mark_node)
5852         return error_mark_node;
5853
5854       expr = perform_qualification_conversions (type, expr);
5855       if (expr == error_mark_node)
5856         return error_mark_node;
5857     }
5858   /* [temp.arg.nontype]/5, bullet 3
5859
5860      For a non-type template-parameter of type reference to object, no
5861      conversions apply. The type referred to by the reference may be more
5862      cv-qualified than the (otherwise identical) type of the
5863      template-argument. The template-parameter is bound directly to the
5864      template-argument, which must be an lvalue.  */
5865   else if (TYPE_REF_OBJ_P (type))
5866     {
5867       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5868                                                       expr_type))
5869         return error_mark_node;
5870
5871       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5872         {
5873           error ("%qE is not a valid template argument for type %qT "
5874                  "because of conflicts in cv-qualification", expr, type);
5875           return NULL_TREE;
5876         }
5877
5878       if (!real_lvalue_p (expr))
5879         {
5880           error ("%qE is not a valid template argument for type %qT "
5881                  "because it is not an lvalue", expr, type);
5882           return NULL_TREE;
5883         }
5884
5885       /* [temp.arg.nontype]/1
5886
5887          A template-argument for a non-type, non-template template-parameter
5888          shall be one of: [...]
5889
5890          -- the address of an object or function with external linkage.  */
5891       if (TREE_CODE (expr) == INDIRECT_REF
5892           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5893         {
5894           expr = TREE_OPERAND (expr, 0);
5895           if (DECL_P (expr))
5896             {
5897               error ("%q#D is not a valid template argument for type %qT "
5898                      "because a reference variable does not have a constant "
5899                      "address", expr, type);
5900               return NULL_TREE;
5901             }
5902         }
5903
5904       if (!DECL_P (expr))
5905         {
5906           error ("%qE is not a valid template argument for type %qT "
5907                  "because it is not an object with external linkage",
5908                  expr, type);
5909           return NULL_TREE;
5910         }
5911
5912       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5913         {
5914           error ("%qE is not a valid template argument for type %qT "
5915                  "because object %qD has not external linkage",
5916                  expr, type, expr);
5917           return NULL_TREE;
5918         }
5919
5920       expr = build_nop (type, build_address (expr));
5921     }
5922   /* [temp.arg.nontype]/5, bullet 4
5923
5924      For a non-type template-parameter of type pointer to function, only
5925      the function-to-pointer conversion (_conv.func_) is applied. If the
5926      template-argument represents a set of overloaded functions (or a
5927      pointer to such), the matching function is selected from the set
5928      (_over.over_).  */
5929   else if (TYPE_PTRFN_P (type))
5930     {
5931       /* If the argument is a template-id, we might not have enough
5932          context information to decay the pointer.  */
5933       if (!type_unknown_p (expr_type))
5934         {
5935           expr = decay_conversion (expr);
5936           if (expr == error_mark_node)
5937             return error_mark_node;
5938         }
5939
5940       if (cxx_dialect >= cxx0x && integer_zerop (expr))
5941         /* Null pointer values are OK in C++11.  */
5942         return perform_qualification_conversions (type, expr);
5943
5944       expr = convert_nontype_argument_function (type, expr);
5945       if (!expr || expr == error_mark_node)
5946         return expr;
5947
5948       if (TREE_CODE (expr) != ADDR_EXPR)
5949         {
5950           error ("%qE is not a valid template argument for type %qT", expr, type);
5951           error ("it must be the address of a function with external linkage");
5952           return NULL_TREE;
5953         }
5954     }
5955   /* [temp.arg.nontype]/5, bullet 5
5956
5957      For a non-type template-parameter of type reference to function, no
5958      conversions apply. If the template-argument represents a set of
5959      overloaded functions, the matching function is selected from the set
5960      (_over.over_).  */
5961   else if (TYPE_REFFN_P (type))
5962     {
5963       if (TREE_CODE (expr) == ADDR_EXPR)
5964         {
5965           error ("%qE is not a valid template argument for type %qT "
5966                  "because it is a pointer", expr, type);
5967           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5968           return NULL_TREE;
5969         }
5970
5971       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5972       if (!expr || expr == error_mark_node)
5973         return expr;
5974
5975       expr = build_nop (type, build_address (expr));
5976     }
5977   /* [temp.arg.nontype]/5, bullet 6
5978
5979      For a non-type template-parameter of type pointer to member function,
5980      no conversions apply. If the template-argument represents a set of
5981      overloaded member functions, the matching member function is selected
5982      from the set (_over.over_).  */
5983   else if (TYPE_PTRMEMFUNC_P (type))
5984     {
5985       expr = instantiate_type (type, expr, tf_none);
5986       if (expr == error_mark_node)
5987         return error_mark_node;
5988
5989       /* [temp.arg.nontype] bullet 1 says the pointer to member
5990          expression must be a pointer-to-member constant.  */
5991       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5992         return error_mark_node;
5993
5994       /* There is no way to disable standard conversions in
5995          resolve_address_of_overloaded_function (called by
5996          instantiate_type). It is possible that the call succeeded by
5997          converting &B::I to &D::I (where B is a base of D), so we need
5998          to reject this conversion here.
5999
6000          Actually, even if there was a way to disable standard conversions,
6001          it would still be better to reject them here so that we can
6002          provide a superior diagnostic.  */
6003       if (!same_type_p (TREE_TYPE (expr), type))
6004         {
6005           error ("%qE is not a valid template argument for type %qT "
6006                  "because it is of type %qT", expr, type,
6007                  TREE_TYPE (expr));
6008           /* If we are just one standard conversion off, explain.  */
6009           if (can_convert (type, TREE_TYPE (expr)))
6010             inform (input_location,
6011                     "standard conversions are not allowed in this context");
6012           return NULL_TREE;
6013         }
6014     }
6015   /* [temp.arg.nontype]/5, bullet 7
6016
6017      For a non-type template-parameter of type pointer to data member,
6018      qualification conversions (_conv.qual_) are applied.  */
6019   else if (TYPE_PTRMEM_P (type))
6020     {
6021       /* [temp.arg.nontype] bullet 1 says the pointer to member
6022          expression must be a pointer-to-member constant.  */
6023       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
6024         return error_mark_node;
6025
6026       expr = perform_qualification_conversions (type, expr);
6027       if (expr == error_mark_node)
6028         return expr;
6029     }
6030   else if (NULLPTR_TYPE_P (type))
6031     {
6032       if (expr != nullptr_node)
6033         {
6034           error ("%qE is not a valid template argument for type %qT "
6035                  "because it is of type %qT", expr, type, TREE_TYPE (expr));
6036           return NULL_TREE;
6037         }
6038       return expr;
6039     }
6040   /* A template non-type parameter must be one of the above.  */
6041   else
6042     gcc_unreachable ();
6043
6044   /* Sanity check: did we actually convert the argument to the
6045      right type?  */
6046   gcc_assert (same_type_ignoring_top_level_qualifiers_p
6047               (type, TREE_TYPE (expr)));
6048   return expr;
6049 }
6050
6051 /* Subroutine of coerce_template_template_parms, which returns 1 if
6052    PARM_PARM and ARG_PARM match using the rule for the template
6053    parameters of template template parameters. Both PARM and ARG are
6054    template parameters; the rest of the arguments are the same as for
6055    coerce_template_template_parms.
6056  */
6057 static int
6058 coerce_template_template_parm (tree parm,
6059                               tree arg,
6060                               tsubst_flags_t complain,
6061                               tree in_decl,
6062                               tree outer_args)
6063 {
6064   if (arg == NULL_TREE || arg == error_mark_node
6065       || parm == NULL_TREE || parm == error_mark_node)
6066     return 0;
6067   
6068   if (TREE_CODE (arg) != TREE_CODE (parm))
6069     return 0;
6070   
6071   switch (TREE_CODE (parm))
6072     {
6073     case TEMPLATE_DECL:
6074       /* We encounter instantiations of templates like
6075          template <template <template <class> class> class TT>
6076          class C;  */
6077       {
6078         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6079         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6080         
6081         if (!coerce_template_template_parms
6082             (parmparm, argparm, complain, in_decl, outer_args))
6083           return 0;
6084       }
6085       /* Fall through.  */
6086       
6087     case TYPE_DECL:
6088       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
6089           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6090         /* Argument is a parameter pack but parameter is not.  */
6091         return 0;
6092       break;
6093       
6094     case PARM_DECL:
6095       /* The tsubst call is used to handle cases such as
6096          
6097            template <int> class C {};
6098            template <class T, template <T> class TT> class D {};
6099            D<int, C> d;
6100
6101          i.e. the parameter list of TT depends on earlier parameters.  */
6102       if (!uses_template_parms (TREE_TYPE (arg))
6103           && !same_type_p
6104                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
6105                  TREE_TYPE (arg)))
6106         return 0;
6107       
6108       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
6109           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6110         /* Argument is a parameter pack but parameter is not.  */
6111         return 0;
6112       
6113       break;
6114
6115     default:
6116       gcc_unreachable ();
6117     }
6118
6119   return 1;
6120 }
6121
6122
6123 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
6124    template template parameters.  Both PARM_PARMS and ARG_PARMS are
6125    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
6126    or PARM_DECL.
6127
6128    Consider the example:
6129      template <class T> class A;
6130      template<template <class U> class TT> class B;
6131
6132    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
6133    the parameters to A, and OUTER_ARGS contains A.  */
6134
6135 static int
6136 coerce_template_template_parms (tree parm_parms,
6137                                 tree arg_parms,
6138                                 tsubst_flags_t complain,
6139                                 tree in_decl,
6140                                 tree outer_args)
6141 {
6142   int nparms, nargs, i;
6143   tree parm, arg;
6144   int variadic_p = 0;
6145
6146   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
6147   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
6148
6149   nparms = TREE_VEC_LENGTH (parm_parms);
6150   nargs = TREE_VEC_LENGTH (arg_parms);
6151
6152   /* Determine whether we have a parameter pack at the end of the
6153      template template parameter's template parameter list.  */
6154   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
6155     {
6156       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
6157       
6158       if (parm == error_mark_node)
6159         return 0;
6160
6161       switch (TREE_CODE (parm))
6162         {
6163         case TEMPLATE_DECL:
6164         case TYPE_DECL:
6165           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6166             variadic_p = 1;
6167           break;
6168           
6169         case PARM_DECL:
6170           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6171             variadic_p = 1;
6172           break;
6173           
6174         default:
6175           gcc_unreachable ();
6176         }
6177     }
6178  
6179   if (nargs != nparms
6180       && !(variadic_p && nargs >= nparms - 1))
6181     return 0;
6182
6183   /* Check all of the template parameters except the parameter pack at
6184      the end (if any).  */
6185   for (i = 0; i < nparms - variadic_p; ++i)
6186     {
6187       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
6188           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6189         continue;
6190
6191       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6192       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6193
6194       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6195                                           outer_args))
6196         return 0;
6197
6198     }
6199
6200   if (variadic_p)
6201     {
6202       /* Check each of the template parameters in the template
6203          argument against the template parameter pack at the end of
6204          the template template parameter.  */
6205       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
6206         return 0;
6207
6208       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6209
6210       for (; i < nargs; ++i)
6211         {
6212           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6213             continue;
6214  
6215           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6216  
6217           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6218                                               outer_args))
6219             return 0;
6220         }
6221     }
6222
6223   return 1;
6224 }
6225
6226 /* Verifies that the deduced template arguments (in TARGS) for the
6227    template template parameters (in TPARMS) represent valid bindings,
6228    by comparing the template parameter list of each template argument
6229    to the template parameter list of its corresponding template
6230    template parameter, in accordance with DR150. This
6231    routine can only be called after all template arguments have been
6232    deduced. It will return TRUE if all of the template template
6233    parameter bindings are okay, FALSE otherwise.  */
6234 bool 
6235 template_template_parm_bindings_ok_p (tree tparms, tree targs)
6236 {
6237   int i, ntparms = TREE_VEC_LENGTH (tparms);
6238   bool ret = true;
6239
6240   /* We're dealing with template parms in this process.  */
6241   ++processing_template_decl;
6242
6243   targs = INNERMOST_TEMPLATE_ARGS (targs);
6244
6245   for (i = 0; i < ntparms; ++i)
6246     {
6247       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
6248       tree targ = TREE_VEC_ELT (targs, i);
6249
6250       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
6251         {
6252           tree packed_args = NULL_TREE;
6253           int idx, len = 1;
6254
6255           if (ARGUMENT_PACK_P (targ))
6256             {
6257               /* Look inside the argument pack.  */
6258               packed_args = ARGUMENT_PACK_ARGS (targ);
6259               len = TREE_VEC_LENGTH (packed_args);
6260             }
6261
6262           for (idx = 0; idx < len; ++idx)
6263             {
6264               tree targ_parms = NULL_TREE;
6265
6266               if (packed_args)
6267                 /* Extract the next argument from the argument
6268                    pack.  */
6269                 targ = TREE_VEC_ELT (packed_args, idx);
6270
6271               if (PACK_EXPANSION_P (targ))
6272                 /* Look at the pattern of the pack expansion.  */
6273                 targ = PACK_EXPANSION_PATTERN (targ);
6274
6275               /* Extract the template parameters from the template
6276                  argument.  */
6277               if (TREE_CODE (targ) == TEMPLATE_DECL)
6278                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
6279               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
6280                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
6281
6282               /* Verify that we can coerce the template template
6283                  parameters from the template argument to the template
6284                  parameter.  This requires an exact match.  */
6285               if (targ_parms
6286                   && !coerce_template_template_parms
6287                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
6288                         targ_parms,
6289                         tf_none,
6290                         tparm,
6291                         targs))
6292                 {
6293                   ret = false;
6294                   goto out;
6295                 }
6296             }
6297         }
6298     }
6299
6300  out:
6301
6302   --processing_template_decl;
6303   return ret;
6304 }
6305
6306 /* Since type attributes aren't mangled, we need to strip them from
6307    template type arguments.  */
6308
6309 static tree
6310 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
6311 {
6312   tree mv;
6313   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
6314     return arg;
6315   mv = TYPE_MAIN_VARIANT (arg);
6316   arg = strip_typedefs (arg);
6317   if (TYPE_ALIGN (arg) != TYPE_ALIGN (mv)
6318       || TYPE_ATTRIBUTES (arg) != TYPE_ATTRIBUTES (mv))
6319     {
6320       if (complain & tf_warning)
6321         warning (0, "ignoring attributes on template argument %qT", arg);
6322       arg = build_aligned_type (arg, TYPE_ALIGN (mv));
6323       arg = cp_build_type_attribute_variant (arg, TYPE_ATTRIBUTES (mv));
6324     }
6325   return arg;
6326 }
6327
6328 /* Convert the indicated template ARG as necessary to match the
6329    indicated template PARM.  Returns the converted ARG, or
6330    error_mark_node if the conversion was unsuccessful.  Error and
6331    warning messages are issued under control of COMPLAIN.  This
6332    conversion is for the Ith parameter in the parameter list.  ARGS is
6333    the full set of template arguments deduced so far.  */
6334
6335 static tree
6336 convert_template_argument (tree parm,
6337                            tree arg,
6338                            tree args,
6339                            tsubst_flags_t complain,
6340                            int i,
6341                            tree in_decl)
6342 {
6343   tree orig_arg;
6344   tree val;
6345   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
6346
6347   if (TREE_CODE (arg) == TREE_LIST
6348       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
6349     {
6350       /* The template argument was the name of some
6351          member function.  That's usually
6352          invalid, but static members are OK.  In any
6353          case, grab the underlying fields/functions
6354          and issue an error later if required.  */
6355       orig_arg = TREE_VALUE (arg);
6356       TREE_TYPE (arg) = unknown_type_node;
6357     }
6358
6359   orig_arg = arg;
6360
6361   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
6362   requires_type = (TREE_CODE (parm) == TYPE_DECL
6363                    || requires_tmpl_type);
6364
6365   /* When determining whether an argument pack expansion is a template,
6366      look at the pattern.  */
6367   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
6368     arg = PACK_EXPANSION_PATTERN (arg);
6369
6370   /* Deal with an injected-class-name used as a template template arg.  */
6371   if (requires_tmpl_type && CLASS_TYPE_P (arg))
6372     {
6373       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
6374       if (TREE_CODE (t) == TEMPLATE_DECL)
6375         {
6376           if (cxx_dialect >= cxx0x)
6377             /* OK under DR 1004.  */;
6378           else if (complain & tf_warning_or_error)
6379             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
6380                      " used as template template argument", TYPE_NAME (arg));
6381           else if (flag_pedantic_errors)
6382             t = arg;
6383
6384           arg = t;
6385         }
6386     }
6387
6388   is_tmpl_type = 
6389     ((TREE_CODE (arg) == TEMPLATE_DECL
6390       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
6391      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6392      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
6393
6394   if (is_tmpl_type
6395       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6396           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
6397     arg = TYPE_STUB_DECL (arg);
6398
6399   is_type = TYPE_P (arg) || is_tmpl_type;
6400
6401   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
6402       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
6403     {
6404       permerror (input_location, "to refer to a type member of a template parameter, "
6405                  "use %<typename %E%>", orig_arg);
6406
6407       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
6408                                      TREE_OPERAND (arg, 1),
6409                                      typename_type,
6410                                      complain & tf_error);
6411       arg = orig_arg;
6412       is_type = 1;
6413     }
6414   if (is_type != requires_type)
6415     {
6416       if (in_decl)
6417         {
6418           if (complain & tf_error)
6419             {
6420               error ("type/value mismatch at argument %d in template "
6421                      "parameter list for %qD",
6422                      i + 1, in_decl);
6423               if (is_type)
6424                 error ("  expected a constant of type %qT, got %qT",
6425                        TREE_TYPE (parm),
6426                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6427               else if (requires_tmpl_type)
6428                 error ("  expected a class template, got %qE", orig_arg);
6429               else
6430                 error ("  expected a type, got %qE", orig_arg);
6431             }
6432         }
6433       return error_mark_node;
6434     }
6435   if (is_tmpl_type ^ requires_tmpl_type)
6436     {
6437       if (in_decl && (complain & tf_error))
6438         {
6439           error ("type/value mismatch at argument %d in template "
6440                  "parameter list for %qD",
6441                  i + 1, in_decl);
6442           if (is_tmpl_type)
6443             error ("  expected a type, got %qT", DECL_NAME (arg));
6444           else
6445             error ("  expected a class template, got %qT", orig_arg);
6446         }
6447       return error_mark_node;
6448     }
6449
6450   if (is_type)
6451     {
6452       if (requires_tmpl_type)
6453         {
6454           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6455             /* The number of argument required is not known yet.
6456                Just accept it for now.  */
6457             val = TREE_TYPE (arg);
6458           else
6459             {
6460               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6461               tree argparm;
6462
6463               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6464
6465               if (coerce_template_template_parms (parmparm, argparm,
6466                                                   complain, in_decl,
6467                                                   args))
6468                 {
6469                   val = arg;
6470
6471                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
6472                      TEMPLATE_DECL.  */
6473                   if (val != error_mark_node)
6474                     {
6475                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6476                         val = TREE_TYPE (val);
6477                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6478                         val = make_pack_expansion (val);
6479                     }
6480                 }
6481               else
6482                 {
6483                   if (in_decl && (complain & tf_error))
6484                     {
6485                       error ("type/value mismatch at argument %d in "
6486                              "template parameter list for %qD",
6487                              i + 1, in_decl);
6488                       error ("  expected a template of type %qD, got %qT",
6489                              parm, orig_arg);
6490                     }
6491
6492                   val = error_mark_node;
6493                 }
6494             }
6495         }
6496       else
6497         val = orig_arg;
6498       /* We only form one instance of each template specialization.
6499          Therefore, if we use a non-canonical variant (i.e., a
6500          typedef), any future messages referring to the type will use
6501          the typedef, which is confusing if those future uses do not
6502          themselves also use the typedef.  */
6503       if (TYPE_P (val))
6504         val = canonicalize_type_argument (val, complain);
6505     }
6506   else
6507     {
6508       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6509
6510       if (invalid_nontype_parm_type_p (t, complain))
6511         return error_mark_node;
6512
6513       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6514         {
6515           if (same_type_p (t, TREE_TYPE (orig_arg)))
6516             val = orig_arg;
6517           else
6518             {
6519               /* Not sure if this is reachable, but it doesn't hurt
6520                  to be robust.  */
6521               error ("type mismatch in nontype parameter pack");
6522               val = error_mark_node;
6523             }
6524         }
6525       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
6526         /* We used to call digest_init here.  However, digest_init
6527            will report errors, which we don't want when complain
6528            is zero.  More importantly, digest_init will try too
6529            hard to convert things: for example, `0' should not be
6530            converted to pointer type at this point according to
6531            the standard.  Accepting this is not merely an
6532            extension, since deciding whether or not these
6533            conversions can occur is part of determining which
6534            function template to call, or whether a given explicit
6535            argument specification is valid.  */
6536         val = convert_nontype_argument (t, orig_arg, complain);
6537       else
6538         val = orig_arg;
6539
6540       if (val == NULL_TREE)
6541         val = error_mark_node;
6542       else if (val == error_mark_node && (complain & tf_error))
6543         error ("could not convert template argument %qE to %qT",  orig_arg, t);
6544
6545       if (TREE_CODE (val) == SCOPE_REF)
6546         {
6547           /* Strip typedefs from the SCOPE_REF.  */
6548           tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
6549           tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
6550                                                    complain);
6551           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6552                                       QUALIFIED_NAME_IS_TEMPLATE (val));
6553         }
6554     }
6555
6556   return val;
6557 }
6558
6559 /* Coerces the remaining template arguments in INNER_ARGS (from
6560    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6561    Returns the coerced argument pack. PARM_IDX is the position of this
6562    parameter in the template parameter list. ARGS is the original
6563    template argument list.  */
6564 static tree
6565 coerce_template_parameter_pack (tree parms,
6566                                 int parm_idx,
6567                                 tree args,
6568                                 tree inner_args,
6569                                 int arg_idx,
6570                                 tree new_args,
6571                                 int* lost,
6572                                 tree in_decl,
6573                                 tsubst_flags_t complain)
6574 {
6575   tree parm = TREE_VEC_ELT (parms, parm_idx);
6576   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6577   tree packed_args;
6578   tree argument_pack;
6579   tree packed_types = NULL_TREE;
6580
6581   if (arg_idx > nargs)
6582     arg_idx = nargs;
6583
6584   packed_args = make_tree_vec (nargs - arg_idx);
6585
6586   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
6587       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
6588     {
6589       /* When the template parameter is a non-type template
6590          parameter pack whose type uses parameter packs, we need
6591          to look at each of the template arguments
6592          separately. Build a vector of the types for these
6593          non-type template parameters in PACKED_TYPES.  */
6594       tree expansion 
6595         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
6596       packed_types = tsubst_pack_expansion (expansion, args,
6597                                             complain, in_decl);
6598
6599       if (packed_types == error_mark_node)
6600         return error_mark_node;
6601
6602       /* Check that we have the right number of arguments.  */
6603       if (arg_idx < nargs
6604           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
6605           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
6606         {
6607           int needed_parms 
6608             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
6609           error ("wrong number of template arguments (%d, should be %d)",
6610                  nargs, needed_parms);
6611           return error_mark_node;
6612         }
6613
6614       /* If we aren't able to check the actual arguments now
6615          (because they haven't been expanded yet), we can at least
6616          verify that all of the types used for the non-type
6617          template parameter pack are, in fact, valid for non-type
6618          template parameters.  */
6619       if (arg_idx < nargs 
6620           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6621         {
6622           int j, len = TREE_VEC_LENGTH (packed_types);
6623           for (j = 0; j < len; ++j)
6624             {
6625               tree t = TREE_VEC_ELT (packed_types, j);
6626               if (invalid_nontype_parm_type_p (t, complain))
6627                 return error_mark_node;
6628             }
6629         }
6630     }
6631
6632   /* Convert the remaining arguments, which will be a part of the
6633      parameter pack "parm".  */
6634   for (; arg_idx < nargs; ++arg_idx)
6635     {
6636       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6637       tree actual_parm = TREE_VALUE (parm);
6638
6639       if (packed_types && !PACK_EXPANSION_P (arg))
6640         {
6641           /* When we have a vector of types (corresponding to the
6642              non-type template parameter pack that uses parameter
6643              packs in its type, as mention above), and the
6644              argument is not an expansion (which expands to a
6645              currently unknown number of arguments), clone the
6646              parm and give it the next type in PACKED_TYPES.  */
6647           actual_parm = copy_node (actual_parm);
6648           TREE_TYPE (actual_parm) = 
6649             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
6650         }
6651
6652       if (arg != error_mark_node)
6653         arg = convert_template_argument (actual_parm, 
6654                                          arg, new_args, complain, parm_idx,
6655                                          in_decl);
6656       if (arg == error_mark_node)
6657         (*lost)++;
6658       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
6659     }
6660
6661   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6662       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6663     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6664   else
6665     {
6666       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6667       TREE_TYPE (argument_pack) 
6668         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6669       TREE_CONSTANT (argument_pack) = 1;
6670     }
6671
6672   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6673 #ifdef ENABLE_CHECKING
6674   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6675                                        TREE_VEC_LENGTH (packed_args));
6676 #endif
6677   return argument_pack;
6678 }
6679
6680 /* Convert all template arguments to their appropriate types, and
6681    return a vector containing the innermost resulting template
6682    arguments.  If any error occurs, return error_mark_node. Error and
6683    warning messages are issued under control of COMPLAIN.
6684
6685    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6686    for arguments not specified in ARGS.  Otherwise, if
6687    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6688    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6689    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6690    ARGS.  */
6691
6692 static tree
6693 coerce_template_parms (tree parms,
6694                        tree args,
6695                        tree in_decl,
6696                        tsubst_flags_t complain,
6697                        bool require_all_args,
6698                        bool use_default_args)
6699 {
6700   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6701   tree inner_args;
6702   tree new_args;
6703   tree new_inner_args;
6704   int saved_unevaluated_operand;
6705   int saved_inhibit_evaluation_warnings;
6706
6707   /* When used as a boolean value, indicates whether this is a
6708      variadic template parameter list. Since it's an int, we can also
6709      subtract it from nparms to get the number of non-variadic
6710      parameters.  */
6711   int variadic_p = 0;
6712   int post_variadic_parms = 0;
6713
6714   if (args == error_mark_node)
6715     return error_mark_node;
6716
6717   nparms = TREE_VEC_LENGTH (parms);
6718
6719   /* Determine if there are any parameter packs.  */
6720   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
6721     {
6722       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
6723       if (variadic_p)
6724         ++post_variadic_parms;
6725       if (template_parameter_pack_p (tparm))
6726         ++variadic_p;
6727     }
6728
6729   inner_args = INNERMOST_TEMPLATE_ARGS (args);
6730   /* If there are no parameters that follow a parameter pack, we need to
6731      expand any argument packs so that we can deduce a parameter pack from
6732      some non-packed args followed by an argument pack, as in variadic85.C.
6733      If there are such parameters, we need to leave argument packs intact
6734      so the arguments are assigned properly.  This can happen when dealing
6735      with a nested class inside a partial specialization of a class
6736      template, as in variadic92.C, or when deducing a template parameter pack
6737      from a sub-declarator, as in variadic114.C.  */
6738   if (!post_variadic_parms)
6739     inner_args = expand_template_argument_pack (inner_args);
6740
6741   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6742   if ((nargs > nparms && !variadic_p)
6743       || (nargs < nparms - variadic_p
6744           && require_all_args
6745           && (!use_default_args
6746               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6747                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6748     {
6749       if (complain & tf_error)
6750         {
6751           if (variadic_p)
6752             {
6753               nparms -= variadic_p;
6754               error ("wrong number of template arguments "
6755                      "(%d, should be %d or more)", nargs, nparms);
6756             }
6757           else
6758              error ("wrong number of template arguments "
6759                     "(%d, should be %d)", nargs, nparms);
6760
6761           if (in_decl)
6762             error ("provided for %q+D", in_decl);
6763         }
6764
6765       return error_mark_node;
6766     }
6767
6768   /* We need to evaluate the template arguments, even though this
6769      template-id may be nested within a "sizeof".  */
6770   saved_unevaluated_operand = cp_unevaluated_operand;
6771   cp_unevaluated_operand = 0;
6772   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6773   c_inhibit_evaluation_warnings = 0;
6774   new_inner_args = make_tree_vec (nparms);
6775   new_args = add_outermost_template_args (args, new_inner_args);
6776   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6777     {
6778       tree arg;
6779       tree parm;
6780
6781       /* Get the Ith template parameter.  */
6782       parm = TREE_VEC_ELT (parms, parm_idx);
6783  
6784       if (parm == error_mark_node)
6785       {
6786         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6787         continue;
6788       }
6789
6790       /* Calculate the next argument.  */
6791       if (arg_idx < nargs)
6792         arg = TREE_VEC_ELT (inner_args, arg_idx);
6793       else
6794         arg = NULL_TREE;
6795
6796       if (template_parameter_pack_p (TREE_VALUE (parm))
6797           && !(arg && ARGUMENT_PACK_P (arg)))
6798         {
6799           /* All remaining arguments will be placed in the
6800              template parameter pack PARM.  */
6801           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6802                                                 inner_args, arg_idx,
6803                                                 new_args, &lost,
6804                                                 in_decl, complain);
6805
6806           /* Store this argument.  */
6807           if (arg == error_mark_node)
6808             lost++;
6809           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6810
6811           /* We are done with all of the arguments.  */
6812           arg_idx = nargs;
6813           
6814           continue;
6815         }
6816       else if (arg)
6817         {
6818           if (PACK_EXPANSION_P (arg))
6819             {
6820               /* We don't know how many args we have yet, just
6821                  use the unconverted ones for now.  */
6822               new_inner_args = args;
6823               break;
6824             }
6825         }
6826       else if (require_all_args)
6827         {
6828           /* There must be a default arg in this case.  */
6829           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6830                                      complain, in_decl);
6831           /* The position of the first default template argument,
6832              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6833              Record that.  */
6834           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6835             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6836         }
6837       else
6838         break;
6839
6840       if (arg == error_mark_node)
6841         {
6842           if (complain & tf_error)
6843             error ("template argument %d is invalid", arg_idx + 1);
6844         }
6845       else if (!arg)
6846         /* This only occurs if there was an error in the template
6847            parameter list itself (which we would already have
6848            reported) that we are trying to recover from, e.g., a class
6849            template with a parameter list such as
6850            template<typename..., typename>.  */
6851         ++lost;
6852       else
6853         arg = convert_template_argument (TREE_VALUE (parm),
6854                                          arg, new_args, complain, 
6855                                          parm_idx, in_decl);
6856
6857       if (arg == error_mark_node)
6858         lost++;
6859       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6860     }
6861   cp_unevaluated_operand = saved_unevaluated_operand;
6862   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6863
6864   if (lost)
6865     return error_mark_node;
6866
6867 #ifdef ENABLE_CHECKING
6868   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6869     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6870                                          TREE_VEC_LENGTH (new_inner_args));
6871 #endif
6872
6873   return new_inner_args;
6874 }
6875
6876 /* Returns 1 if template args OT and NT are equivalent.  */
6877
6878 static int
6879 template_args_equal (tree ot, tree nt)
6880 {
6881   if (nt == ot)
6882     return 1;
6883   if (nt == NULL_TREE || ot == NULL_TREE)
6884     return false;
6885
6886   if (TREE_CODE (nt) == TREE_VEC)
6887     /* For member templates */
6888     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6889   else if (PACK_EXPANSION_P (ot))
6890     return PACK_EXPANSION_P (nt) 
6891       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6892                               PACK_EXPANSION_PATTERN (nt));
6893   else if (ARGUMENT_PACK_P (ot))
6894     {
6895       int i, len;
6896       tree opack, npack;
6897
6898       if (!ARGUMENT_PACK_P (nt))
6899         return 0;
6900
6901       opack = ARGUMENT_PACK_ARGS (ot);
6902       npack = ARGUMENT_PACK_ARGS (nt);
6903       len = TREE_VEC_LENGTH (opack);
6904       if (TREE_VEC_LENGTH (npack) != len)
6905         return 0;
6906       for (i = 0; i < len; ++i)
6907         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6908                                   TREE_VEC_ELT (npack, i)))
6909           return 0;
6910       return 1;
6911     }
6912   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6913     {
6914       /* We get here probably because we are in the middle of substituting
6915          into the pattern of a pack expansion. In that case the
6916          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6917          interested in. So we want to use the initial pack argument for
6918          the comparison.  */
6919       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6920       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6921         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6922       return template_args_equal (ot, nt);
6923     }
6924   else if (TYPE_P (nt))
6925     return TYPE_P (ot) && same_type_p (ot, nt);
6926   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6927     return 0;
6928   else
6929     return cp_tree_equal (ot, nt);
6930 }
6931
6932 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
6933    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
6934    NEWARG_PTR with the offending arguments if they are non-NULL.  */
6935
6936 static int
6937 comp_template_args_with_info (tree oldargs, tree newargs,
6938                               tree *oldarg_ptr, tree *newarg_ptr)
6939 {
6940   int i;
6941
6942   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6943     return 0;
6944
6945   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6946     {
6947       tree nt = TREE_VEC_ELT (newargs, i);
6948       tree ot = TREE_VEC_ELT (oldargs, i);
6949
6950       if (! template_args_equal (ot, nt))
6951         {
6952           if (oldarg_ptr != NULL)
6953             *oldarg_ptr = ot;
6954           if (newarg_ptr != NULL)
6955             *newarg_ptr = nt;
6956           return 0;
6957         }
6958     }
6959   return 1;
6960 }
6961
6962 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6963    of template arguments.  Returns 0 otherwise.  */
6964
6965 int
6966 comp_template_args (tree oldargs, tree newargs)
6967 {
6968   return comp_template_args_with_info (oldargs, newargs, NULL, NULL);
6969 }
6970
6971 static void
6972 add_pending_template (tree d)
6973 {
6974   tree ti = (TYPE_P (d)
6975              ? CLASSTYPE_TEMPLATE_INFO (d)
6976              : DECL_TEMPLATE_INFO (d));
6977   struct pending_template *pt;
6978   int level;
6979
6980   if (TI_PENDING_TEMPLATE_FLAG (ti))
6981     return;
6982
6983   /* We are called both from instantiate_decl, where we've already had a
6984      tinst_level pushed, and instantiate_template, where we haven't.
6985      Compensate.  */
6986   level = !current_tinst_level || current_tinst_level->decl != d;
6987
6988   if (level)
6989     push_tinst_level (d);
6990
6991   pt = ggc_alloc_pending_template ();
6992   pt->next = NULL;
6993   pt->tinst = current_tinst_level;
6994   if (last_pending_template)
6995     last_pending_template->next = pt;
6996   else
6997     pending_templates = pt;
6998
6999   last_pending_template = pt;
7000
7001   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
7002
7003   if (level)
7004     pop_tinst_level ();
7005 }
7006
7007
7008 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
7009    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
7010    documentation for TEMPLATE_ID_EXPR.  */
7011
7012 tree
7013 lookup_template_function (tree fns, tree arglist)
7014 {
7015   tree type;
7016
7017   if (fns == error_mark_node || arglist == error_mark_node)
7018     return error_mark_node;
7019
7020   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
7021
7022   if (!is_overloaded_fn (fns) && TREE_CODE (fns) != IDENTIFIER_NODE)
7023     {
7024       error ("%q#D is not a function template", fns);
7025       return error_mark_node;
7026     }
7027
7028   if (BASELINK_P (fns))
7029     {
7030       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
7031                                          unknown_type_node,
7032                                          BASELINK_FUNCTIONS (fns),
7033                                          arglist);
7034       return fns;
7035     }
7036
7037   type = TREE_TYPE (fns);
7038   if (TREE_CODE (fns) == OVERLOAD || !type)
7039     type = unknown_type_node;
7040
7041   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
7042 }
7043
7044 /* Within the scope of a template class S<T>, the name S gets bound
7045    (in build_self_reference) to a TYPE_DECL for the class, not a
7046    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
7047    or one of its enclosing classes, and that type is a template,
7048    return the associated TEMPLATE_DECL.  Otherwise, the original
7049    DECL is returned.
7050
7051    Also handle the case when DECL is a TREE_LIST of ambiguous
7052    injected-class-names from different bases.  */
7053
7054 tree
7055 maybe_get_template_decl_from_type_decl (tree decl)
7056 {
7057   if (decl == NULL_TREE)
7058     return decl;
7059
7060   /* DR 176: A lookup that finds an injected-class-name (10.2
7061      [class.member.lookup]) can result in an ambiguity in certain cases
7062      (for example, if it is found in more than one base class). If all of
7063      the injected-class-names that are found refer to specializations of
7064      the same class template, and if the name is followed by a
7065      template-argument-list, the reference refers to the class template
7066      itself and not a specialization thereof, and is not ambiguous.  */
7067   if (TREE_CODE (decl) == TREE_LIST)
7068     {
7069       tree t, tmpl = NULL_TREE;
7070       for (t = decl; t; t = TREE_CHAIN (t))
7071         {
7072           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
7073           if (!tmpl)
7074             tmpl = elt;
7075           else if (tmpl != elt)
7076             break;
7077         }
7078       if (tmpl && t == NULL_TREE)
7079         return tmpl;
7080       else
7081         return decl;
7082     }
7083
7084   return (decl != NULL_TREE
7085           && DECL_SELF_REFERENCE_P (decl)
7086           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
7087     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
7088 }
7089
7090 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
7091    parameters, find the desired type.
7092
7093    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
7094
7095    IN_DECL, if non-NULL, is the template declaration we are trying to
7096    instantiate.
7097
7098    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
7099    the class we are looking up.
7100
7101    Issue error and warning messages under control of COMPLAIN.
7102
7103    If the template class is really a local class in a template
7104    function, then the FUNCTION_CONTEXT is the function in which it is
7105    being instantiated.
7106
7107    ??? Note that this function is currently called *twice* for each
7108    template-id: the first time from the parser, while creating the
7109    incomplete type (finish_template_type), and the second type during the
7110    real instantiation (instantiate_template_class). This is surely something
7111    that we want to avoid. It also causes some problems with argument
7112    coercion (see convert_nontype_argument for more information on this).  */
7113
7114 static tree
7115 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
7116                          int entering_scope, tsubst_flags_t complain)
7117 {
7118   tree templ = NULL_TREE, parmlist;
7119   tree t;
7120   void **slot;
7121   spec_entry *entry;
7122   spec_entry elt;
7123   hashval_t hash;
7124
7125   if (TREE_CODE (d1) == IDENTIFIER_NODE)
7126     {
7127       tree value = innermost_non_namespace_value (d1);
7128       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
7129         templ = value;
7130       else
7131         {
7132           if (context)
7133             push_decl_namespace (context);
7134           templ = lookup_name (d1);
7135           templ = maybe_get_template_decl_from_type_decl (templ);
7136           if (context)
7137             pop_decl_namespace ();
7138         }
7139       if (templ)
7140         context = DECL_CONTEXT (templ);
7141     }
7142   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
7143     {
7144       tree type = TREE_TYPE (d1);
7145
7146       /* If we are declaring a constructor, say A<T>::A<T>, we will get
7147          an implicit typename for the second A.  Deal with it.  */
7148       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
7149         type = TREE_TYPE (type);
7150
7151       if (CLASSTYPE_TEMPLATE_INFO (type))
7152         {
7153           templ = CLASSTYPE_TI_TEMPLATE (type);
7154           d1 = DECL_NAME (templ);
7155         }
7156     }
7157   else if (TREE_CODE (d1) == ENUMERAL_TYPE
7158            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
7159     {
7160       templ = TYPE_TI_TEMPLATE (d1);
7161       d1 = DECL_NAME (templ);
7162     }
7163   else if (TREE_CODE (d1) == TEMPLATE_DECL
7164            && DECL_TEMPLATE_RESULT (d1)
7165            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
7166     {
7167       templ = d1;
7168       d1 = DECL_NAME (templ);
7169       context = DECL_CONTEXT (templ);
7170     }
7171
7172   /* Issue an error message if we didn't find a template.  */
7173   if (! templ)
7174     {
7175       if (complain & tf_error)
7176         error ("%qT is not a template", d1);
7177       return error_mark_node;
7178     }
7179
7180   if (TREE_CODE (templ) != TEMPLATE_DECL
7181          /* Make sure it's a user visible template, if it was named by
7182             the user.  */
7183       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
7184           && !PRIMARY_TEMPLATE_P (templ)))
7185     {
7186       if (complain & tf_error)
7187         {
7188           error ("non-template type %qT used as a template", d1);
7189           if (in_decl)
7190             error ("for template declaration %q+D", in_decl);
7191         }
7192       return error_mark_node;
7193     }
7194
7195   complain &= ~tf_user;
7196
7197   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
7198     {
7199       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
7200          template arguments */
7201
7202       tree parm;
7203       tree arglist2;
7204       tree outer;
7205
7206       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7207
7208       /* Consider an example where a template template parameter declared as
7209
7210            template <class T, class U = std::allocator<T> > class TT
7211
7212          The template parameter level of T and U are one level larger than
7213          of TT.  To proper process the default argument of U, say when an
7214          instantiation `TT<int>' is seen, we need to build the full
7215          arguments containing {int} as the innermost level.  Outer levels,
7216          available when not appearing as default template argument, can be
7217          obtained from the arguments of the enclosing template.
7218
7219          Suppose that TT is later substituted with std::vector.  The above
7220          instantiation is `TT<int, std::allocator<T> >' with TT at
7221          level 1, and T at level 2, while the template arguments at level 1
7222          becomes {std::vector} and the inner level 2 is {int}.  */
7223
7224       outer = DECL_CONTEXT (templ);
7225       if (outer)
7226         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
7227       else if (current_template_parms)
7228         /* This is an argument of the current template, so we haven't set
7229            DECL_CONTEXT yet.  */
7230         outer = current_template_args ();
7231
7232       if (outer)
7233         arglist = add_to_template_args (outer, arglist);
7234
7235       arglist2 = coerce_template_parms (parmlist, arglist, templ,
7236                                         complain,
7237                                         /*require_all_args=*/true,
7238                                         /*use_default_args=*/true);
7239       if (arglist2 == error_mark_node
7240           || (!uses_template_parms (arglist2)
7241               && check_instantiated_args (templ, arglist2, complain)))
7242         return error_mark_node;
7243
7244       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
7245       return parm;
7246     }
7247   else
7248     {
7249       tree template_type = TREE_TYPE (templ);
7250       tree gen_tmpl;
7251       tree type_decl;
7252       tree found = NULL_TREE;
7253       int arg_depth;
7254       int parm_depth;
7255       int is_dependent_type;
7256       int use_partial_inst_tmpl = false;
7257
7258       gen_tmpl = most_general_template (templ);
7259       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
7260       parm_depth = TMPL_PARMS_DEPTH (parmlist);
7261       arg_depth = TMPL_ARGS_DEPTH (arglist);
7262
7263       if (arg_depth == 1 && parm_depth > 1)
7264         {
7265           /* We've been given an incomplete set of template arguments.
7266              For example, given:
7267
7268                template <class T> struct S1 {
7269                  template <class U> struct S2 {};
7270                  template <class U> struct S2<U*> {};
7271                 };
7272
7273              we will be called with an ARGLIST of `U*', but the
7274              TEMPLATE will be `template <class T> template
7275              <class U> struct S1<T>::S2'.  We must fill in the missing
7276              arguments.  */
7277           arglist
7278             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
7279                                            arglist);
7280           arg_depth = TMPL_ARGS_DEPTH (arglist);
7281         }
7282
7283       /* Now we should have enough arguments.  */
7284       gcc_assert (parm_depth == arg_depth);
7285
7286       /* From here on, we're only interested in the most general
7287          template.  */
7288
7289       /* Calculate the BOUND_ARGS.  These will be the args that are
7290          actually tsubst'd into the definition to create the
7291          instantiation.  */
7292       if (parm_depth > 1)
7293         {
7294           /* We have multiple levels of arguments to coerce, at once.  */
7295           int i;
7296           int saved_depth = TMPL_ARGS_DEPTH (arglist);
7297
7298           tree bound_args = make_tree_vec (parm_depth);
7299
7300           for (i = saved_depth,
7301                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
7302                i > 0 && t != NULL_TREE;
7303                --i, t = TREE_CHAIN (t))
7304             {
7305               tree a;
7306               if (i == saved_depth)
7307                 a = coerce_template_parms (TREE_VALUE (t),
7308                                            arglist, gen_tmpl,
7309                                            complain,
7310                                            /*require_all_args=*/true,
7311                                            /*use_default_args=*/true);
7312               else
7313                 /* Outer levels should have already been coerced.  */
7314                 a = TMPL_ARGS_LEVEL (arglist, i);
7315
7316               /* Don't process further if one of the levels fails.  */
7317               if (a == error_mark_node)
7318                 {
7319                   /* Restore the ARGLIST to its full size.  */
7320                   TREE_VEC_LENGTH (arglist) = saved_depth;
7321                   return error_mark_node;
7322                 }
7323
7324               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
7325
7326               /* We temporarily reduce the length of the ARGLIST so
7327                  that coerce_template_parms will see only the arguments
7328                  corresponding to the template parameters it is
7329                  examining.  */
7330               TREE_VEC_LENGTH (arglist)--;
7331             }
7332
7333           /* Restore the ARGLIST to its full size.  */
7334           TREE_VEC_LENGTH (arglist) = saved_depth;
7335
7336           arglist = bound_args;
7337         }
7338       else
7339         arglist
7340           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
7341                                    INNERMOST_TEMPLATE_ARGS (arglist),
7342                                    gen_tmpl,
7343                                    complain,
7344                                    /*require_all_args=*/true,
7345                                    /*use_default_args=*/true);
7346
7347       if (arglist == error_mark_node)
7348         /* We were unable to bind the arguments.  */
7349         return error_mark_node;
7350
7351       /* In the scope of a template class, explicit references to the
7352          template class refer to the type of the template, not any
7353          instantiation of it.  For example, in:
7354
7355            template <class T> class C { void f(C<T>); }
7356
7357          the `C<T>' is just the same as `C'.  Outside of the
7358          class, however, such a reference is an instantiation.  */
7359       if ((entering_scope
7360            || !PRIMARY_TEMPLATE_P (gen_tmpl)
7361            || currently_open_class (template_type))
7362           /* comp_template_args is expensive, check it last.  */
7363           && comp_template_args (TYPE_TI_ARGS (template_type),
7364                                  arglist))
7365         return template_type;
7366
7367       /* If we already have this specialization, return it.  */
7368       elt.tmpl = gen_tmpl;
7369       elt.args = arglist;
7370       hash = hash_specialization (&elt);
7371       entry = (spec_entry *) htab_find_with_hash (type_specializations,
7372                                                   &elt, hash);
7373
7374       if (entry)
7375         return entry->spec;
7376
7377       is_dependent_type = uses_template_parms (arglist);
7378
7379       /* If the deduced arguments are invalid, then the binding
7380          failed.  */
7381       if (!is_dependent_type
7382           && check_instantiated_args (gen_tmpl,
7383                                       INNERMOST_TEMPLATE_ARGS (arglist),
7384                                       complain))
7385         return error_mark_node;
7386
7387       if (!is_dependent_type
7388           && !PRIMARY_TEMPLATE_P (gen_tmpl)
7389           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
7390           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
7391         {
7392           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
7393                                       DECL_NAME (gen_tmpl),
7394                                       /*tag_scope=*/ts_global);
7395           return found;
7396         }
7397
7398       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
7399                         complain, in_decl);
7400       if (!context)
7401         context = global_namespace;
7402
7403       /* Create the type.  */
7404       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
7405         {
7406           if (!is_dependent_type)
7407             {
7408               set_current_access_from_decl (TYPE_NAME (template_type));
7409               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
7410                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
7411                                       arglist, complain, in_decl),
7412                               SCOPED_ENUM_P (template_type), NULL);
7413             }
7414           else
7415             {
7416               /* We don't want to call start_enum for this type, since
7417                  the values for the enumeration constants may involve
7418                  template parameters.  And, no one should be interested
7419                  in the enumeration constants for such a type.  */
7420               t = cxx_make_type (ENUMERAL_TYPE);
7421               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
7422             }
7423           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
7424           ENUM_FIXED_UNDERLYING_TYPE_P (t)
7425             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
7426         }
7427       else if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
7428         {
7429           /* The user referred to a specialization of an alias
7430             template represented by GEN_TMPL.
7431
7432             [temp.alias]/2 says:
7433
7434                 When a template-id refers to the specialization of an
7435                 alias template, it is equivalent to the associated
7436                 type obtained by substitution of its
7437                 template-arguments for the template-parameters in the
7438                 type-id of the alias template.  */
7439
7440           t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
7441           /* Note that the call above (by indirectly calling
7442              register_specialization in tsubst_decl) registers the
7443              TYPE_DECL representing the specialization of the alias
7444              template.  So next time someone substitutes ARGLIST for
7445              the template parms into the alias template (GEN_TMPL),
7446              she'll get that TYPE_DECL back.  */
7447
7448           if (t == error_mark_node)
7449             return t;
7450         }
7451       else if (CLASS_TYPE_P (template_type))
7452         {
7453           t = make_class_type (TREE_CODE (template_type));
7454           CLASSTYPE_DECLARED_CLASS (t)
7455             = CLASSTYPE_DECLARED_CLASS (template_type);
7456           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7457           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7458
7459           /* A local class.  Make sure the decl gets registered properly.  */
7460           if (context == current_function_decl)
7461             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
7462
7463           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7464             /* This instantiation is another name for the primary
7465                template type. Set the TYPE_CANONICAL field
7466                appropriately. */
7467             TYPE_CANONICAL (t) = template_type;
7468           else if (any_template_arguments_need_structural_equality_p (arglist))
7469             /* Some of the template arguments require structural
7470                equality testing, so this template class requires
7471                structural equality testing. */
7472             SET_TYPE_STRUCTURAL_EQUALITY (t);
7473         }
7474       else
7475         gcc_unreachable ();
7476
7477       /* If we called start_enum or pushtag above, this information
7478          will already be set up.  */
7479       if (!TYPE_NAME (t))
7480         {
7481           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7482
7483           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7484           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7485           DECL_SOURCE_LOCATION (type_decl)
7486             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7487         }
7488       else
7489         type_decl = TYPE_NAME (t);
7490
7491       if (CLASS_TYPE_P (template_type))
7492         {
7493           TREE_PRIVATE (type_decl)
7494             = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
7495           TREE_PROTECTED (type_decl)
7496             = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
7497           if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7498             {
7499               DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7500               DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7501             }
7502         }
7503
7504       /* Let's consider the explicit specialization of a member
7505          of a class template specialization that is implicitely instantiated,
7506          e.g.:
7507              template<class T>
7508              struct S
7509              {
7510                template<class U> struct M {}; //#0
7511              };
7512
7513              template<>
7514              template<>
7515              struct S<int>::M<char> //#1
7516              {
7517                int i;
7518              };
7519         [temp.expl.spec]/4 says this is valid.
7520
7521         In this case, when we write:
7522         S<int>::M<char> m;
7523
7524         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
7525         the one of #0.
7526
7527         When we encounter #1, we want to store the partial instantiation
7528         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
7529
7530         For all cases other than this "explicit specialization of member of a
7531         class template", we just want to store the most general template into
7532         the CLASSTYPE_TI_TEMPLATE of M.
7533
7534         This case of "explicit specialization of member of a class template"
7535         only happens when:
7536         1/ the enclosing class is an instantiation of, and therefore not
7537         the same as, the context of the most general template, and
7538         2/ we aren't looking at the partial instantiation itself, i.e.
7539         the innermost arguments are not the same as the innermost parms of
7540         the most general template.
7541
7542         So it's only when 1/ and 2/ happens that we want to use the partial
7543         instantiation of the member template in lieu of its most general
7544         template.  */
7545
7546       if (PRIMARY_TEMPLATE_P (gen_tmpl)
7547           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
7548           /* the enclosing class must be an instantiation...  */
7549           && CLASS_TYPE_P (context)
7550           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
7551         {
7552           tree partial_inst_args;
7553           TREE_VEC_LENGTH (arglist)--;
7554           ++processing_template_decl;
7555           partial_inst_args =
7556             tsubst (INNERMOST_TEMPLATE_ARGS
7557                         (TYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
7558                     arglist, complain, NULL_TREE);
7559           --processing_template_decl;
7560           TREE_VEC_LENGTH (arglist)++;
7561           use_partial_inst_tmpl =
7562             /*...and we must not be looking at the partial instantiation
7563              itself. */
7564             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
7565                                  partial_inst_args);
7566         }
7567
7568       if (!use_partial_inst_tmpl)
7569         /* This case is easy; there are no member templates involved.  */
7570         found = gen_tmpl;
7571       else
7572         {
7573           /* This is a full instantiation of a member template.  Find
7574              the partial instantiation of which this is an instance.  */
7575
7576           /* Temporarily reduce by one the number of levels in the ARGLIST
7577              so as to avoid comparing the last set of arguments.  */
7578           TREE_VEC_LENGTH (arglist)--;
7579           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
7580           TREE_VEC_LENGTH (arglist)++;
7581           /* FOUND is either a proper class type, or an alias
7582              template specialization.  In the later case, it's a
7583              TYPE_DECL, resulting from the substituting of arguments
7584              for parameters in the TYPE_DECL of the alias template
7585              done earlier.  So be careful while getting the template
7586              of FOUND.  */
7587           found = TREE_CODE (found) == TYPE_DECL
7588             ? TYPE_TI_TEMPLATE (TREE_TYPE (found))
7589             : CLASSTYPE_TI_TEMPLATE (found);
7590         }
7591
7592       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
7593
7594       elt.spec = t;
7595       slot = htab_find_slot_with_hash (type_specializations,
7596                                        &elt, hash, INSERT);
7597       entry = ggc_alloc_spec_entry ();
7598       *entry = elt;
7599       *slot = entry;
7600
7601       /* Note this use of the partial instantiation so we can check it
7602          later in maybe_process_partial_specialization.  */
7603       DECL_TEMPLATE_INSTANTIATIONS (templ)
7604         = tree_cons (arglist, t,
7605                      DECL_TEMPLATE_INSTANTIATIONS (templ));
7606
7607       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
7608         /* Now that the type has been registered on the instantiations
7609            list, we set up the enumerators.  Because the enumeration
7610            constants may involve the enumeration type itself, we make
7611            sure to register the type first, and then create the
7612            constants.  That way, doing tsubst_expr for the enumeration
7613            constants won't result in recursive calls here; we'll find
7614            the instantiation and exit above.  */
7615         tsubst_enum (template_type, t, arglist);
7616
7617       if (CLASS_TYPE_P (template_type) && is_dependent_type)
7618         /* If the type makes use of template parameters, the
7619            code that generates debugging information will crash.  */
7620         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
7621
7622       /* Possibly limit visibility based on template args.  */
7623       TREE_PUBLIC (type_decl) = 1;
7624       determine_visibility (type_decl);
7625
7626       return t;
7627     }
7628 }
7629
7630 /* Wrapper for lookup_template_class_1.  */
7631
7632 tree
7633 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
7634                        int entering_scope, tsubst_flags_t complain)
7635 {
7636   tree ret;
7637   timevar_push (TV_TEMPLATE_INST);
7638   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
7639                                  entering_scope, complain);
7640   timevar_pop (TV_TEMPLATE_INST);
7641   return ret;
7642 }
7643 \f
7644 struct pair_fn_data
7645 {
7646   tree_fn_t fn;
7647   void *data;
7648   /* True when we should also visit template parameters that occur in
7649      non-deduced contexts.  */
7650   bool include_nondeduced_p;
7651   struct pointer_set_t *visited;
7652 };
7653
7654 /* Called from for_each_template_parm via walk_tree.  */
7655
7656 static tree
7657 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
7658 {
7659   tree t = *tp;
7660   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
7661   tree_fn_t fn = pfd->fn;
7662   void *data = pfd->data;
7663
7664   if (TYPE_P (t)
7665       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
7666       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
7667                                  pfd->include_nondeduced_p))
7668     return error_mark_node;
7669
7670   switch (TREE_CODE (t))
7671     {
7672     case RECORD_TYPE:
7673       if (TYPE_PTRMEMFUNC_P (t))
7674         break;
7675       /* Fall through.  */
7676
7677     case UNION_TYPE:
7678     case ENUMERAL_TYPE:
7679       if (!TYPE_TEMPLATE_INFO (t))
7680         *walk_subtrees = 0;
7681       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
7682                                        fn, data, pfd->visited, 
7683                                        pfd->include_nondeduced_p))
7684         return error_mark_node;
7685       break;
7686
7687     case INTEGER_TYPE:
7688       if (for_each_template_parm (TYPE_MIN_VALUE (t),
7689                                   fn, data, pfd->visited, 
7690                                   pfd->include_nondeduced_p)
7691           || for_each_template_parm (TYPE_MAX_VALUE (t),
7692                                      fn, data, pfd->visited,
7693                                      pfd->include_nondeduced_p))
7694         return error_mark_node;
7695       break;
7696
7697     case METHOD_TYPE:
7698       /* Since we're not going to walk subtrees, we have to do this
7699          explicitly here.  */
7700       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
7701                                   pfd->visited, pfd->include_nondeduced_p))
7702         return error_mark_node;
7703       /* Fall through.  */
7704
7705     case FUNCTION_TYPE:
7706       /* Check the return type.  */
7707       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7708                                   pfd->include_nondeduced_p))
7709         return error_mark_node;
7710
7711       /* Check the parameter types.  Since default arguments are not
7712          instantiated until they are needed, the TYPE_ARG_TYPES may
7713          contain expressions that involve template parameters.  But,
7714          no-one should be looking at them yet.  And, once they're
7715          instantiated, they don't contain template parameters, so
7716          there's no point in looking at them then, either.  */
7717       {
7718         tree parm;
7719
7720         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
7721           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
7722                                       pfd->visited, pfd->include_nondeduced_p))
7723             return error_mark_node;
7724
7725         /* Since we've already handled the TYPE_ARG_TYPES, we don't
7726            want walk_tree walking into them itself.  */
7727         *walk_subtrees = 0;
7728       }
7729       break;
7730
7731     case TYPEOF_TYPE:
7732     case UNDERLYING_TYPE:
7733       if (pfd->include_nondeduced_p
7734           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
7735                                      pfd->visited, 
7736                                      pfd->include_nondeduced_p))
7737         return error_mark_node;
7738       break;
7739
7740     case FUNCTION_DECL:
7741     case VAR_DECL:
7742       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
7743           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
7744                                      pfd->visited, pfd->include_nondeduced_p))
7745         return error_mark_node;
7746       /* Fall through.  */
7747
7748     case PARM_DECL:
7749     case CONST_DECL:
7750       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
7751           && for_each_template_parm (DECL_INITIAL (t), fn, data,
7752                                      pfd->visited, pfd->include_nondeduced_p))
7753         return error_mark_node;
7754       if (DECL_CONTEXT (t)
7755           && pfd->include_nondeduced_p
7756           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
7757                                      pfd->visited, pfd->include_nondeduced_p))
7758         return error_mark_node;
7759       break;
7760
7761     case BOUND_TEMPLATE_TEMPLATE_PARM:
7762       /* Record template parameters such as `T' inside `TT<T>'.  */
7763       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
7764                                   pfd->include_nondeduced_p))
7765         return error_mark_node;
7766       /* Fall through.  */
7767
7768     case TEMPLATE_TEMPLATE_PARM:
7769     case TEMPLATE_TYPE_PARM:
7770     case TEMPLATE_PARM_INDEX:
7771       if (fn && (*fn)(t, data))
7772         return error_mark_node;
7773       else if (!fn)
7774         return error_mark_node;
7775       break;
7776
7777     case TEMPLATE_DECL:
7778       /* A template template parameter is encountered.  */
7779       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
7780           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7781                                      pfd->include_nondeduced_p))
7782         return error_mark_node;
7783
7784       /* Already substituted template template parameter */
7785       *walk_subtrees = 0;
7786       break;
7787
7788     case TYPENAME_TYPE:
7789       if (!fn
7790           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
7791                                      data, pfd->visited, 
7792                                      pfd->include_nondeduced_p))
7793         return error_mark_node;
7794       break;
7795
7796     case CONSTRUCTOR:
7797       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
7798           && pfd->include_nondeduced_p
7799           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
7800                                      (TREE_TYPE (t)), fn, data,
7801                                      pfd->visited, pfd->include_nondeduced_p))
7802         return error_mark_node;
7803       break;
7804
7805     case INDIRECT_REF:
7806     case COMPONENT_REF:
7807       /* If there's no type, then this thing must be some expression
7808          involving template parameters.  */
7809       if (!fn && !TREE_TYPE (t))
7810         return error_mark_node;
7811       break;
7812
7813     case MODOP_EXPR:
7814     case CAST_EXPR:
7815     case IMPLICIT_CONV_EXPR:
7816     case REINTERPRET_CAST_EXPR:
7817     case CONST_CAST_EXPR:
7818     case STATIC_CAST_EXPR:
7819     case DYNAMIC_CAST_EXPR:
7820     case ARROW_EXPR:
7821     case DOTSTAR_EXPR:
7822     case TYPEID_EXPR:
7823     case PSEUDO_DTOR_EXPR:
7824       if (!fn)
7825         return error_mark_node;
7826       break;
7827
7828     default:
7829       break;
7830     }
7831
7832   /* We didn't find any template parameters we liked.  */
7833   return NULL_TREE;
7834 }
7835
7836 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7837    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7838    call FN with the parameter and the DATA.
7839    If FN returns nonzero, the iteration is terminated, and
7840    for_each_template_parm returns 1.  Otherwise, the iteration
7841    continues.  If FN never returns a nonzero value, the value
7842    returned by for_each_template_parm is 0.  If FN is NULL, it is
7843    considered to be the function which always returns 1.
7844
7845    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7846    parameters that occur in non-deduced contexts.  When false, only
7847    visits those template parameters that can be deduced.  */
7848
7849 static int
7850 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7851                         struct pointer_set_t *visited,
7852                         bool include_nondeduced_p)
7853 {
7854   struct pair_fn_data pfd;
7855   int result;
7856
7857   /* Set up.  */
7858   pfd.fn = fn;
7859   pfd.data = data;
7860   pfd.include_nondeduced_p = include_nondeduced_p;
7861
7862   /* Walk the tree.  (Conceptually, we would like to walk without
7863      duplicates, but for_each_template_parm_r recursively calls
7864      for_each_template_parm, so we would need to reorganize a fair
7865      bit to use walk_tree_without_duplicates, so we keep our own
7866      visited list.)  */
7867   if (visited)
7868     pfd.visited = visited;
7869   else
7870     pfd.visited = pointer_set_create ();
7871   result = cp_walk_tree (&t,
7872                          for_each_template_parm_r,
7873                          &pfd,
7874                          pfd.visited) != NULL_TREE;
7875
7876   /* Clean up.  */
7877   if (!visited)
7878     {
7879       pointer_set_destroy (pfd.visited);
7880       pfd.visited = 0;
7881     }
7882
7883   return result;
7884 }
7885
7886 /* Returns true if T depends on any template parameter.  */
7887
7888 int
7889 uses_template_parms (tree t)
7890 {
7891   bool dependent_p;
7892   int saved_processing_template_decl;
7893
7894   saved_processing_template_decl = processing_template_decl;
7895   if (!saved_processing_template_decl)
7896     processing_template_decl = 1;
7897   if (TYPE_P (t))
7898     dependent_p = dependent_type_p (t);
7899   else if (TREE_CODE (t) == TREE_VEC)
7900     dependent_p = any_dependent_template_arguments_p (t);
7901   else if (TREE_CODE (t) == TREE_LIST)
7902     dependent_p = (uses_template_parms (TREE_VALUE (t))
7903                    || uses_template_parms (TREE_CHAIN (t)));
7904   else if (TREE_CODE (t) == TYPE_DECL)
7905     dependent_p = dependent_type_p (TREE_TYPE (t));
7906   else if (DECL_P (t)
7907            || EXPR_P (t)
7908            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7909            || TREE_CODE (t) == OVERLOAD
7910            || BASELINK_P (t)
7911            || TREE_CODE (t) == IDENTIFIER_NODE
7912            || TREE_CODE (t) == TRAIT_EXPR
7913            || TREE_CODE (t) == CONSTRUCTOR
7914            || CONSTANT_CLASS_P (t))
7915     dependent_p = (type_dependent_expression_p (t)
7916                    || value_dependent_expression_p (t));
7917   else
7918     {
7919       gcc_assert (t == error_mark_node);
7920       dependent_p = false;
7921     }
7922
7923   processing_template_decl = saved_processing_template_decl;
7924
7925   return dependent_p;
7926 }
7927
7928 /* Returns true if T depends on any template parameter with level LEVEL.  */
7929
7930 int
7931 uses_template_parms_level (tree t, int level)
7932 {
7933   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7934                                  /*include_nondeduced_p=*/true);
7935 }
7936
7937 /* Returns TRUE iff INST is an instantiation we don't need to do in an
7938    ill-formed translation unit, i.e. a variable or function that isn't
7939    usable in a constant expression.  */
7940
7941 static inline bool
7942 neglectable_inst_p (tree d)
7943 {
7944   return (DECL_P (d)
7945           && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
7946                : decl_maybe_constant_var_p (d)));
7947 }
7948
7949 /* Returns TRUE iff we should refuse to instantiate DECL because it's
7950    neglectable and instantiated from within an erroneous instantiation.  */
7951
7952 static bool
7953 limit_bad_template_recursion (tree decl)
7954 {
7955   struct tinst_level *lev = current_tinst_level;
7956   int errs = errorcount + sorrycount;
7957   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
7958     return false;
7959
7960   for (; lev; lev = lev->next)
7961     if (neglectable_inst_p (lev->decl))
7962       break;
7963
7964   return (lev && errs > lev->errors);
7965 }
7966
7967 static int tinst_depth;
7968 extern int max_tinst_depth;
7969 #ifdef GATHER_STATISTICS
7970 int depth_reached;
7971 #endif
7972 static GTY(()) struct tinst_level *last_error_tinst_level;
7973
7974 /* We're starting to instantiate D; record the template instantiation context
7975    for diagnostics and to restore it later.  */
7976
7977 int
7978 push_tinst_level (tree d)
7979 {
7980   struct tinst_level *new_level;
7981
7982   if (tinst_depth >= max_tinst_depth)
7983     {
7984       last_error_tinst_level = current_tinst_level;
7985       if (TREE_CODE (d) == TREE_LIST)
7986         error ("template instantiation depth exceeds maximum of %d (use "
7987                "-ftemplate-depth= to increase the maximum) substituting %qS",
7988                max_tinst_depth, d);
7989       else
7990         error ("template instantiation depth exceeds maximum of %d (use "
7991                "-ftemplate-depth= to increase the maximum) instantiating %qD",
7992                max_tinst_depth, d);
7993
7994       print_instantiation_context ();
7995
7996       return 0;
7997     }
7998
7999   /* If the current instantiation caused problems, don't let it instantiate
8000      anything else.  Do allow deduction substitution and decls usable in
8001      constant expressions.  */
8002   if (limit_bad_template_recursion (d))
8003     return 0;
8004
8005   new_level = ggc_alloc_tinst_level ();
8006   new_level->decl = d;
8007   new_level->locus = input_location;
8008   new_level->errors = errorcount+sorrycount;
8009   new_level->in_system_header_p = in_system_header;
8010   new_level->next = current_tinst_level;
8011   current_tinst_level = new_level;
8012
8013   ++tinst_depth;
8014 #ifdef GATHER_STATISTICS
8015   if (tinst_depth > depth_reached)
8016     depth_reached = tinst_depth;
8017 #endif
8018
8019   return 1;
8020 }
8021
8022 /* We're done instantiating this template; return to the instantiation
8023    context.  */
8024
8025 void
8026 pop_tinst_level (void)
8027 {
8028   /* Restore the filename and line number stashed away when we started
8029      this instantiation.  */
8030   input_location = current_tinst_level->locus;
8031   current_tinst_level = current_tinst_level->next;
8032   --tinst_depth;
8033 }
8034
8035 /* We're instantiating a deferred template; restore the template
8036    instantiation context in which the instantiation was requested, which
8037    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
8038
8039 static tree
8040 reopen_tinst_level (struct tinst_level *level)
8041 {
8042   struct tinst_level *t;
8043
8044   tinst_depth = 0;
8045   for (t = level; t; t = t->next)
8046     ++tinst_depth;
8047
8048   current_tinst_level = level;
8049   pop_tinst_level ();
8050   if (current_tinst_level)
8051     current_tinst_level->errors = errorcount+sorrycount;
8052   return level->decl;
8053 }
8054
8055 /* Returns the TINST_LEVEL which gives the original instantiation
8056    context.  */
8057
8058 struct tinst_level *
8059 outermost_tinst_level (void)
8060 {
8061   struct tinst_level *level = current_tinst_level;
8062   if (level)
8063     while (level->next)
8064       level = level->next;
8065   return level;
8066 }
8067
8068 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
8069
8070 bool
8071 parameter_of_template_p (tree parm, tree templ)
8072 {
8073   tree parms;
8074   int i;
8075
8076   if (!parm || !templ)
8077     return false;
8078
8079   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
8080   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
8081
8082   parms = DECL_TEMPLATE_PARMS (templ);
8083   parms = INNERMOST_TEMPLATE_PARMS (parms);
8084
8085   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
8086     {
8087       tree p = TREE_VALUE (TREE_VEC_ELT (parms, i));
8088       if (parm == p
8089           || (DECL_INITIAL (parm)
8090               && DECL_INITIAL (parm) == DECL_INITIAL (p)))
8091         return true;
8092     }
8093
8094   return false;
8095 }
8096
8097 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
8098    vector of template arguments, as for tsubst.
8099
8100    Returns an appropriate tsubst'd friend declaration.  */
8101
8102 static tree
8103 tsubst_friend_function (tree decl, tree args)
8104 {
8105   tree new_friend;
8106
8107   if (TREE_CODE (decl) == FUNCTION_DECL
8108       && DECL_TEMPLATE_INSTANTIATION (decl)
8109       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
8110     /* This was a friend declared with an explicit template
8111        argument list, e.g.:
8112
8113        friend void f<>(T);
8114
8115        to indicate that f was a template instantiation, not a new
8116        function declaration.  Now, we have to figure out what
8117        instantiation of what template.  */
8118     {
8119       tree template_id, arglist, fns;
8120       tree new_args;
8121       tree tmpl;
8122       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
8123
8124       /* Friend functions are looked up in the containing namespace scope.
8125          We must enter that scope, to avoid finding member functions of the
8126          current class with same name.  */
8127       push_nested_namespace (ns);
8128       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
8129                          tf_warning_or_error, NULL_TREE,
8130                          /*integral_constant_expression_p=*/false);
8131       pop_nested_namespace (ns);
8132       arglist = tsubst (DECL_TI_ARGS (decl), args,
8133                         tf_warning_or_error, NULL_TREE);
8134       template_id = lookup_template_function (fns, arglist);
8135
8136       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
8137       tmpl = determine_specialization (template_id, new_friend,
8138                                        &new_args,
8139                                        /*need_member_template=*/0,
8140                                        TREE_VEC_LENGTH (args),
8141                                        tsk_none);
8142       return instantiate_template (tmpl, new_args, tf_error);
8143     }
8144
8145   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
8146
8147   /* The NEW_FRIEND will look like an instantiation, to the
8148      compiler, but is not an instantiation from the point of view of
8149      the language.  For example, we might have had:
8150
8151      template <class T> struct S {
8152        template <class U> friend void f(T, U);
8153      };
8154
8155      Then, in S<int>, template <class U> void f(int, U) is not an
8156      instantiation of anything.  */
8157   if (new_friend == error_mark_node)
8158     return error_mark_node;
8159
8160   DECL_USE_TEMPLATE (new_friend) = 0;
8161   if (TREE_CODE (decl) == TEMPLATE_DECL)
8162     {
8163       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
8164       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
8165         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
8166     }
8167
8168   /* The mangled name for the NEW_FRIEND is incorrect.  The function
8169      is not a template instantiation and should not be mangled like
8170      one.  Therefore, we forget the mangling here; we'll recompute it
8171      later if we need it.  */
8172   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
8173     {
8174       SET_DECL_RTL (new_friend, NULL);
8175       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
8176     }
8177
8178   if (DECL_NAMESPACE_SCOPE_P (new_friend))
8179     {
8180       tree old_decl;
8181       tree new_friend_template_info;
8182       tree new_friend_result_template_info;
8183       tree ns;
8184       int  new_friend_is_defn;
8185
8186       /* We must save some information from NEW_FRIEND before calling
8187          duplicate decls since that function will free NEW_FRIEND if
8188          possible.  */
8189       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
8190       new_friend_is_defn =
8191             (DECL_INITIAL (DECL_TEMPLATE_RESULT
8192                            (template_for_substitution (new_friend)))
8193              != NULL_TREE);
8194       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
8195         {
8196           /* This declaration is a `primary' template.  */
8197           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
8198
8199           new_friend_result_template_info
8200             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
8201         }
8202       else
8203         new_friend_result_template_info = NULL_TREE;
8204
8205       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
8206       if (new_friend_is_defn)
8207         DECL_INITIAL (new_friend) = error_mark_node;
8208
8209       /* Inside pushdecl_namespace_level, we will push into the
8210          current namespace. However, the friend function should go
8211          into the namespace of the template.  */
8212       ns = decl_namespace_context (new_friend);
8213       push_nested_namespace (ns);
8214       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
8215       pop_nested_namespace (ns);
8216
8217       if (old_decl == error_mark_node)
8218         return error_mark_node;
8219
8220       if (old_decl != new_friend)
8221         {
8222           /* This new friend declaration matched an existing
8223              declaration.  For example, given:
8224
8225                template <class T> void f(T);
8226                template <class U> class C {
8227                  template <class T> friend void f(T) {}
8228                };
8229
8230              the friend declaration actually provides the definition
8231              of `f', once C has been instantiated for some type.  So,
8232              old_decl will be the out-of-class template declaration,
8233              while new_friend is the in-class definition.
8234
8235              But, if `f' was called before this point, the
8236              instantiation of `f' will have DECL_TI_ARGS corresponding
8237              to `T' but not to `U', references to which might appear
8238              in the definition of `f'.  Previously, the most general
8239              template for an instantiation of `f' was the out-of-class
8240              version; now it is the in-class version.  Therefore, we
8241              run through all specialization of `f', adding to their
8242              DECL_TI_ARGS appropriately.  In particular, they need a
8243              new set of outer arguments, corresponding to the
8244              arguments for this class instantiation.
8245
8246              The same situation can arise with something like this:
8247
8248                friend void f(int);
8249                template <class T> class C {
8250                  friend void f(T) {}
8251                };
8252
8253              when `C<int>' is instantiated.  Now, `f(int)' is defined
8254              in the class.  */
8255
8256           if (!new_friend_is_defn)
8257             /* On the other hand, if the in-class declaration does
8258                *not* provide a definition, then we don't want to alter
8259                existing definitions.  We can just leave everything
8260                alone.  */
8261             ;
8262           else
8263             {
8264               tree new_template = TI_TEMPLATE (new_friend_template_info);
8265               tree new_args = TI_ARGS (new_friend_template_info);
8266
8267               /* Overwrite whatever template info was there before, if
8268                  any, with the new template information pertaining to
8269                  the declaration.  */
8270               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
8271
8272               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
8273                 {
8274                   /* We should have called reregister_specialization in
8275                      duplicate_decls.  */
8276                   gcc_assert (retrieve_specialization (new_template,
8277                                                        new_args, 0)
8278                               == old_decl);
8279
8280                   /* Instantiate it if the global has already been used.  */
8281                   if (DECL_ODR_USED (old_decl))
8282                     instantiate_decl (old_decl, /*defer_ok=*/true,
8283                                       /*expl_inst_class_mem_p=*/false);
8284                 }
8285               else
8286                 {
8287                   tree t;
8288
8289                   /* Indicate that the old function template is a partial
8290                      instantiation.  */
8291                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
8292                     = new_friend_result_template_info;
8293
8294                   gcc_assert (new_template
8295                               == most_general_template (new_template));
8296                   gcc_assert (new_template != old_decl);
8297
8298                   /* Reassign any specializations already in the hash table
8299                      to the new more general template, and add the
8300                      additional template args.  */
8301                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
8302                        t != NULL_TREE;
8303                        t = TREE_CHAIN (t))
8304                     {
8305                       tree spec = TREE_VALUE (t);
8306                       spec_entry elt;
8307
8308                       elt.tmpl = old_decl;
8309                       elt.args = DECL_TI_ARGS (spec);
8310                       elt.spec = NULL_TREE;
8311
8312                       htab_remove_elt (decl_specializations, &elt);
8313
8314                       DECL_TI_ARGS (spec)
8315                         = add_outermost_template_args (new_args,
8316                                                        DECL_TI_ARGS (spec));
8317
8318                       register_specialization
8319                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
8320
8321                     }
8322                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
8323                 }
8324             }
8325
8326           /* The information from NEW_FRIEND has been merged into OLD_DECL
8327              by duplicate_decls.  */
8328           new_friend = old_decl;
8329         }
8330     }
8331   else
8332     {
8333       tree context = DECL_CONTEXT (new_friend);
8334       bool dependent_p;
8335
8336       /* In the code
8337            template <class T> class C {
8338              template <class U> friend void C1<U>::f (); // case 1
8339              friend void C2<T>::f ();                    // case 2
8340            };
8341          we only need to make sure CONTEXT is a complete type for
8342          case 2.  To distinguish between the two cases, we note that
8343          CONTEXT of case 1 remains dependent type after tsubst while
8344          this isn't true for case 2.  */
8345       ++processing_template_decl;
8346       dependent_p = dependent_type_p (context);
8347       --processing_template_decl;
8348
8349       if (!dependent_p
8350           && !complete_type_or_else (context, NULL_TREE))
8351         return error_mark_node;
8352
8353       if (COMPLETE_TYPE_P (context))
8354         {
8355           /* Check to see that the declaration is really present, and,
8356              possibly obtain an improved declaration.  */
8357           tree fn = check_classfn (context,
8358                                    new_friend, NULL_TREE);
8359
8360           if (fn)
8361             new_friend = fn;
8362         }
8363     }
8364
8365   return new_friend;
8366 }
8367
8368 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
8369    template arguments, as for tsubst.
8370
8371    Returns an appropriate tsubst'd friend type or error_mark_node on
8372    failure.  */
8373
8374 static tree
8375 tsubst_friend_class (tree friend_tmpl, tree args)
8376 {
8377   tree friend_type;
8378   tree tmpl;
8379   tree context;
8380
8381   context = CP_DECL_CONTEXT (friend_tmpl);
8382
8383   if (context != global_namespace)
8384     {
8385       if (TREE_CODE (context) == NAMESPACE_DECL)
8386         push_nested_namespace (context);
8387       else
8388         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
8389     }
8390
8391   /* Look for a class template declaration.  We look for hidden names
8392      because two friend declarations of the same template are the
8393      same.  For example, in:
8394
8395        struct A { 
8396          template <typename> friend class F;
8397        };
8398        template <typename> struct B { 
8399          template <typename> friend class F;
8400        };
8401
8402      both F templates are the same.  */
8403   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
8404                            /*block_p=*/true, 0, 
8405                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
8406
8407   /* But, if we don't find one, it might be because we're in a
8408      situation like this:
8409
8410        template <class T>
8411        struct S {
8412          template <class U>
8413          friend struct S;
8414        };
8415
8416      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
8417      for `S<int>', not the TEMPLATE_DECL.  */
8418   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
8419     {
8420       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
8421       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
8422     }
8423
8424   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
8425     {
8426       /* The friend template has already been declared.  Just
8427          check to see that the declarations match, and install any new
8428          default parameters.  We must tsubst the default parameters,
8429          of course.  We only need the innermost template parameters
8430          because that is all that redeclare_class_template will look
8431          at.  */
8432       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
8433           > TMPL_ARGS_DEPTH (args))
8434         {
8435           tree parms;
8436           location_t saved_input_location;
8437           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
8438                                          args, tf_warning_or_error);
8439
8440           saved_input_location = input_location;
8441           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
8442           redeclare_class_template (TREE_TYPE (tmpl), parms);
8443           input_location = saved_input_location;
8444           
8445         }
8446
8447       friend_type = TREE_TYPE (tmpl);
8448     }
8449   else
8450     {
8451       /* The friend template has not already been declared.  In this
8452          case, the instantiation of the template class will cause the
8453          injection of this template into the global scope.  */
8454       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
8455       if (tmpl == error_mark_node)
8456         return error_mark_node;
8457
8458       /* The new TMPL is not an instantiation of anything, so we
8459          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
8460          the new type because that is supposed to be the corresponding
8461          template decl, i.e., TMPL.  */
8462       DECL_USE_TEMPLATE (tmpl) = 0;
8463       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
8464       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
8465       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
8466         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
8467
8468       /* Inject this template into the global scope.  */
8469       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
8470     }
8471
8472   if (context != global_namespace)
8473     {
8474       if (TREE_CODE (context) == NAMESPACE_DECL)
8475         pop_nested_namespace (context);
8476       else
8477         pop_nested_class ();
8478     }
8479
8480   return friend_type;
8481 }
8482
8483 /* Returns zero if TYPE cannot be completed later due to circularity.
8484    Otherwise returns one.  */
8485
8486 static int
8487 can_complete_type_without_circularity (tree type)
8488 {
8489   if (type == NULL_TREE || type == error_mark_node)
8490     return 0;
8491   else if (COMPLETE_TYPE_P (type))
8492     return 1;
8493   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
8494     return can_complete_type_without_circularity (TREE_TYPE (type));
8495   else if (CLASS_TYPE_P (type)
8496            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
8497     return 0;
8498   else
8499     return 1;
8500 }
8501
8502 /* Apply any attributes which had to be deferred until instantiation
8503    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
8504    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
8505
8506 static void
8507 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
8508                                 tree args, tsubst_flags_t complain, tree in_decl)
8509 {
8510   tree last_dep = NULL_TREE;
8511   tree t;
8512   tree *p;
8513
8514   for (t = attributes; t; t = TREE_CHAIN (t))
8515     if (ATTR_IS_DEPENDENT (t))
8516       {
8517         last_dep = t;
8518         attributes = copy_list (attributes);
8519         break;
8520       }
8521
8522   if (DECL_P (*decl_p))
8523     {
8524       if (TREE_TYPE (*decl_p) == error_mark_node)
8525         return;
8526       p = &DECL_ATTRIBUTES (*decl_p);
8527     }
8528   else
8529     p = &TYPE_ATTRIBUTES (*decl_p);
8530
8531   if (last_dep)
8532     {
8533       tree late_attrs = NULL_TREE;
8534       tree *q = &late_attrs;
8535
8536       for (*p = attributes; *p; )
8537         {
8538           t = *p;
8539           if (ATTR_IS_DEPENDENT (t))
8540             {
8541               *p = TREE_CHAIN (t);
8542               TREE_CHAIN (t) = NULL_TREE;
8543               /* If the first attribute argument is an identifier, don't
8544                  pass it through tsubst.  Attributes like mode, format,
8545                  cleanup and several target specific attributes expect it
8546                  unmodified.  */
8547               if (TREE_VALUE (t)
8548                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
8549                   && TREE_VALUE (TREE_VALUE (t))
8550                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
8551                       == IDENTIFIER_NODE))
8552                 {
8553                   tree chain
8554                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
8555                                    in_decl,
8556                                    /*integral_constant_expression_p=*/false);
8557                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
8558                     TREE_VALUE (t)
8559                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
8560                                    chain);
8561                 }
8562               else
8563                 TREE_VALUE (t)
8564                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
8565                                  /*integral_constant_expression_p=*/false);
8566               *q = t;
8567               q = &TREE_CHAIN (t);
8568             }
8569           else
8570             p = &TREE_CHAIN (t);
8571         }
8572
8573       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
8574     }
8575 }
8576
8577 /* Perform (or defer) access check for typedefs that were referenced
8578    from within the template TMPL code.
8579    This is a subroutine of instantiate_template and instantiate_class_template.
8580    TMPL is the template to consider and TARGS is the list of arguments of
8581    that template.  */
8582
8583 static void
8584 perform_typedefs_access_check (tree tmpl, tree targs)
8585 {
8586   location_t saved_location;
8587   int i;
8588   qualified_typedef_usage_t *iter;
8589
8590   if (!tmpl
8591       || (!CLASS_TYPE_P (tmpl)
8592           && TREE_CODE (tmpl) != FUNCTION_DECL))
8593     return;
8594
8595   saved_location = input_location;
8596   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
8597                     get_types_needing_access_check (tmpl),
8598                     i, iter)
8599     {
8600       tree type_decl = iter->typedef_decl;
8601       tree type_scope = iter->context;
8602
8603       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
8604         continue;
8605
8606       if (uses_template_parms (type_decl))
8607         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
8608       if (uses_template_parms (type_scope))
8609         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
8610
8611       /* Make access check error messages point to the location
8612          of the use of the typedef.  */
8613       input_location = iter->locus;
8614       perform_or_defer_access_check (TYPE_BINFO (type_scope),
8615                                      type_decl, type_decl);
8616     }
8617     input_location = saved_location;
8618 }
8619
8620 static tree
8621 instantiate_class_template_1 (tree type)
8622 {
8623   tree templ, args, pattern, t, member;
8624   tree typedecl;
8625   tree pbinfo;
8626   tree base_list;
8627   unsigned int saved_maximum_field_alignment;
8628
8629   if (type == error_mark_node)
8630     return error_mark_node;
8631
8632   if (COMPLETE_OR_OPEN_TYPE_P (type)
8633       || uses_template_parms (type))
8634     return type;
8635
8636   /* Figure out which template is being instantiated.  */
8637   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
8638   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
8639
8640   /* Determine what specialization of the original template to
8641      instantiate.  */
8642   t = most_specialized_class (type, templ, tf_warning_or_error);
8643   if (t == error_mark_node)
8644     {
8645       TYPE_BEING_DEFINED (type) = 1;
8646       return error_mark_node;
8647     }
8648   else if (t)
8649     {
8650       /* This TYPE is actually an instantiation of a partial
8651          specialization.  We replace the innermost set of ARGS with
8652          the arguments appropriate for substitution.  For example,
8653          given:
8654
8655            template <class T> struct S {};
8656            template <class T> struct S<T*> {};
8657
8658          and supposing that we are instantiating S<int*>, ARGS will
8659          presently be {int*} -- but we need {int}.  */
8660       pattern = TREE_TYPE (t);
8661       args = TREE_PURPOSE (t);
8662     }
8663   else
8664     {
8665       pattern = TREE_TYPE (templ);
8666       args = CLASSTYPE_TI_ARGS (type);
8667     }
8668
8669   /* If the template we're instantiating is incomplete, then clearly
8670      there's nothing we can do.  */
8671   if (!COMPLETE_TYPE_P (pattern))
8672     return type;
8673
8674   /* If we've recursively instantiated too many templates, stop.  */
8675   if (! push_tinst_level (type))
8676     return type;
8677
8678   /* Now we're really doing the instantiation.  Mark the type as in
8679      the process of being defined.  */
8680   TYPE_BEING_DEFINED (type) = 1;
8681
8682   /* We may be in the middle of deferred access check.  Disable
8683      it now.  */
8684   push_deferring_access_checks (dk_no_deferred);
8685
8686   push_to_top_level ();
8687   /* Use #pragma pack from the template context.  */
8688   saved_maximum_field_alignment = maximum_field_alignment;
8689   maximum_field_alignment = TYPE_PRECISION (pattern);
8690
8691   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
8692
8693   /* Set the input location to the most specialized template definition.
8694      This is needed if tsubsting causes an error.  */
8695   typedecl = TYPE_MAIN_DECL (pattern);
8696   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
8697     DECL_SOURCE_LOCATION (typedecl);
8698
8699   TYPE_PACKED (type) = TYPE_PACKED (pattern);
8700   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
8701   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
8702   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
8703   if (ANON_AGGR_TYPE_P (pattern))
8704     SET_ANON_AGGR_TYPE_P (type);
8705   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
8706     {
8707       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
8708       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
8709       /* Adjust visibility for template arguments.  */
8710       determine_visibility (TYPE_MAIN_DECL (type));
8711     }
8712   CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
8713
8714   pbinfo = TYPE_BINFO (pattern);
8715
8716   /* We should never instantiate a nested class before its enclosing
8717      class; we need to look up the nested class by name before we can
8718      instantiate it, and that lookup should instantiate the enclosing
8719      class.  */
8720   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
8721               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
8722
8723   base_list = NULL_TREE;
8724   if (BINFO_N_BASE_BINFOS (pbinfo))
8725     {
8726       tree pbase_binfo;
8727       tree pushed_scope;
8728       int i;
8729
8730       /* We must enter the scope containing the type, as that is where
8731          the accessibility of types named in dependent bases are
8732          looked up from.  */
8733       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
8734
8735       /* Substitute into each of the bases to determine the actual
8736          basetypes.  */
8737       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
8738         {
8739           tree base;
8740           tree access = BINFO_BASE_ACCESS (pbinfo, i);
8741           tree expanded_bases = NULL_TREE;
8742           int idx, len = 1;
8743
8744           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
8745             {
8746               expanded_bases = 
8747                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
8748                                        args, tf_error, NULL_TREE);
8749               if (expanded_bases == error_mark_node)
8750                 continue;
8751
8752               len = TREE_VEC_LENGTH (expanded_bases);
8753             }
8754
8755           for (idx = 0; idx < len; idx++)
8756             {
8757               if (expanded_bases)
8758                 /* Extract the already-expanded base class.  */
8759                 base = TREE_VEC_ELT (expanded_bases, idx);
8760               else
8761                 /* Substitute to figure out the base class.  */
8762                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
8763                                NULL_TREE);
8764
8765               if (base == error_mark_node)
8766                 continue;
8767
8768               base_list = tree_cons (access, base, base_list);
8769               if (BINFO_VIRTUAL_P (pbase_binfo))
8770                 TREE_TYPE (base_list) = integer_type_node;
8771             }
8772         }
8773
8774       /* The list is now in reverse order; correct that.  */
8775       base_list = nreverse (base_list);
8776
8777       if (pushed_scope)
8778         pop_scope (pushed_scope);
8779     }
8780   /* Now call xref_basetypes to set up all the base-class
8781      information.  */
8782   xref_basetypes (type, base_list);
8783
8784   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
8785                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
8786                                   args, tf_error, NULL_TREE);
8787   fixup_attribute_variants (type);
8788
8789   /* Now that our base classes are set up, enter the scope of the
8790      class, so that name lookups into base classes, etc. will work
8791      correctly.  This is precisely analogous to what we do in
8792      begin_class_definition when defining an ordinary non-template
8793      class, except we also need to push the enclosing classes.  */
8794   push_nested_class (type);
8795
8796   /* Now members are processed in the order of declaration.  */
8797   for (member = CLASSTYPE_DECL_LIST (pattern);
8798        member; member = TREE_CHAIN (member))
8799     {
8800       tree t = TREE_VALUE (member);
8801
8802       if (TREE_PURPOSE (member))
8803         {
8804           if (TYPE_P (t))
8805             {
8806               /* Build new CLASSTYPE_NESTED_UTDS.  */
8807
8808               tree newtag;
8809               bool class_template_p;
8810
8811               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
8812                                   && TYPE_LANG_SPECIFIC (t)
8813                                   && CLASSTYPE_IS_TEMPLATE (t));
8814               /* If the member is a class template, then -- even after
8815                  substitution -- there may be dependent types in the
8816                  template argument list for the class.  We increment
8817                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
8818                  that function will assume that no types are dependent
8819                  when outside of a template.  */
8820               if (class_template_p)
8821                 ++processing_template_decl;
8822               newtag = tsubst (t, args, tf_error, NULL_TREE);
8823               if (class_template_p)
8824                 --processing_template_decl;
8825               if (newtag == error_mark_node)
8826                 continue;
8827
8828               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8829                 {
8830                   tree name = TYPE_IDENTIFIER (t);
8831
8832                   if (class_template_p)
8833                     /* Unfortunately, lookup_template_class sets
8834                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8835                        instantiation (i.e., for the type of a member
8836                        template class nested within a template class.)
8837                        This behavior is required for
8838                        maybe_process_partial_specialization to work
8839                        correctly, but is not accurate in this case;
8840                        the TAG is not an instantiation of anything.
8841                        (The corresponding TEMPLATE_DECL is an
8842                        instantiation, but the TYPE is not.) */
8843                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8844
8845                   /* Now, we call pushtag to put this NEWTAG into the scope of
8846                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8847                      pushtag calling push_template_decl.  We don't have to do
8848                      this for enums because it will already have been done in
8849                      tsubst_enum.  */
8850                   if (name)
8851                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8852                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8853                 }
8854             }
8855           else if (TREE_CODE (t) == FUNCTION_DECL
8856                    || DECL_FUNCTION_TEMPLATE_P (t))
8857             {
8858               /* Build new TYPE_METHODS.  */
8859               tree r;
8860
8861               if (TREE_CODE (t) == TEMPLATE_DECL)
8862                 ++processing_template_decl;
8863               r = tsubst (t, args, tf_error, NULL_TREE);
8864               if (TREE_CODE (t) == TEMPLATE_DECL)
8865                 --processing_template_decl;
8866               set_current_access_from_decl (r);
8867               finish_member_declaration (r);
8868               /* Instantiate members marked with attribute used.  */
8869               if (r != error_mark_node && DECL_PRESERVE_P (r))
8870                 mark_used (r);
8871             }
8872           else
8873             {
8874               /* Build new TYPE_FIELDS.  */
8875               if (TREE_CODE (t) == STATIC_ASSERT)
8876                 {
8877                   tree condition = 
8878                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8879                                  tf_warning_or_error, NULL_TREE,
8880                                  /*integral_constant_expression_p=*/true);
8881                   finish_static_assert (condition,
8882                                         STATIC_ASSERT_MESSAGE (t), 
8883                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8884                                         /*member_p=*/true);
8885                 }
8886               else if (TREE_CODE (t) != CONST_DECL)
8887                 {
8888                   tree r;
8889
8890                   /* The file and line for this declaration, to
8891                      assist in error message reporting.  Since we
8892                      called push_tinst_level above, we don't need to
8893                      restore these.  */
8894                   input_location = DECL_SOURCE_LOCATION (t);
8895
8896                   if (TREE_CODE (t) == TEMPLATE_DECL)
8897                     ++processing_template_decl;
8898                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8899                   if (TREE_CODE (t) == TEMPLATE_DECL)
8900                     --processing_template_decl;
8901                   if (TREE_CODE (r) == VAR_DECL)
8902                     {
8903                       /* In [temp.inst]:
8904
8905                            [t]he initialization (and any associated
8906                            side-effects) of a static data member does
8907                            not occur unless the static data member is
8908                            itself used in a way that requires the
8909                            definition of the static data member to
8910                            exist.
8911
8912                          Therefore, we do not substitute into the
8913                          initialized for the static data member here.  */
8914                       finish_static_data_member_decl
8915                         (r,
8916                          /*init=*/NULL_TREE,
8917                          /*init_const_expr_p=*/false,
8918                          /*asmspec_tree=*/NULL_TREE,
8919                          /*flags=*/0);
8920                       /* Instantiate members marked with attribute used.  */
8921                       if (r != error_mark_node && DECL_PRESERVE_P (r))
8922                         mark_used (r);
8923                     }
8924                   else if (TREE_CODE (r) == FIELD_DECL)
8925                     {
8926                       /* Determine whether R has a valid type and can be
8927                          completed later.  If R is invalid, then it is
8928                          replaced by error_mark_node so that it will not be
8929                          added to TYPE_FIELDS.  */
8930                       tree rtype = TREE_TYPE (r);
8931                       if (can_complete_type_without_circularity (rtype))
8932                         complete_type (rtype);
8933
8934                       if (!COMPLETE_TYPE_P (rtype))
8935                         {
8936                           cxx_incomplete_type_error (r, rtype);
8937                           r = error_mark_node;
8938                         }
8939                     }
8940
8941                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8942                      such a thing will already have been added to the field
8943                      list by tsubst_enum in finish_member_declaration in the
8944                      CLASSTYPE_NESTED_UTDS case above.  */
8945                   if (!(TREE_CODE (r) == TYPE_DECL
8946                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8947                         && DECL_ARTIFICIAL (r)))
8948                     {
8949                       set_current_access_from_decl (r);
8950                       finish_member_declaration (r);
8951                     }
8952                 }
8953             }
8954         }
8955       else
8956         {
8957           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8958             {
8959               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8960
8961               tree friend_type = t;
8962               bool adjust_processing_template_decl = false;
8963
8964               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8965                 {
8966                   /* template <class T> friend class C;  */
8967                   friend_type = tsubst_friend_class (friend_type, args);
8968                   adjust_processing_template_decl = true;
8969                 }
8970               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8971                 {
8972                   /* template <class T> friend class C::D;  */
8973                   friend_type = tsubst (friend_type, args,
8974                                         tf_warning_or_error, NULL_TREE);
8975                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8976                     friend_type = TREE_TYPE (friend_type);
8977                   adjust_processing_template_decl = true;
8978                 }
8979               else if (TREE_CODE (friend_type) == TYPENAME_TYPE
8980                        || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
8981                 {
8982                   /* This could be either
8983
8984                        friend class T::C;
8985
8986                      when dependent_type_p is false or
8987
8988                        template <class U> friend class T::C;
8989
8990                      otherwise.  */
8991                   friend_type = tsubst (friend_type, args,
8992                                         tf_warning_or_error, NULL_TREE);
8993                   /* Bump processing_template_decl for correct
8994                      dependent_type_p calculation.  */
8995                   ++processing_template_decl;
8996                   if (dependent_type_p (friend_type))
8997                     adjust_processing_template_decl = true;
8998                   --processing_template_decl;
8999                 }
9000               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
9001                        && hidden_name_p (TYPE_NAME (friend_type)))
9002                 {
9003                   /* friend class C;
9004
9005                      where C hasn't been declared yet.  Let's lookup name
9006                      from namespace scope directly, bypassing any name that
9007                      come from dependent base class.  */
9008                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
9009
9010                   /* The call to xref_tag_from_type does injection for friend
9011                      classes.  */
9012                   push_nested_namespace (ns);
9013                   friend_type =
9014                     xref_tag_from_type (friend_type, NULL_TREE,
9015                                         /*tag_scope=*/ts_current);
9016                   pop_nested_namespace (ns);
9017                 }
9018               else if (uses_template_parms (friend_type))
9019                 /* friend class C<T>;  */
9020                 friend_type = tsubst (friend_type, args,
9021                                       tf_warning_or_error, NULL_TREE);
9022               /* Otherwise it's
9023
9024                    friend class C;
9025
9026                  where C is already declared or
9027
9028                    friend class C<int>;
9029
9030                  We don't have to do anything in these cases.  */
9031
9032               if (adjust_processing_template_decl)
9033                 /* Trick make_friend_class into realizing that the friend
9034                    we're adding is a template, not an ordinary class.  It's
9035                    important that we use make_friend_class since it will
9036                    perform some error-checking and output cross-reference
9037                    information.  */
9038                 ++processing_template_decl;
9039
9040               if (friend_type != error_mark_node)
9041                 make_friend_class (type, friend_type, /*complain=*/false);
9042
9043               if (adjust_processing_template_decl)
9044                 --processing_template_decl;
9045             }
9046           else
9047             {
9048               /* Build new DECL_FRIENDLIST.  */
9049               tree r;
9050
9051               /* The file and line for this declaration, to
9052                  assist in error message reporting.  Since we
9053                  called push_tinst_level above, we don't need to
9054                  restore these.  */
9055               input_location = DECL_SOURCE_LOCATION (t);
9056
9057               if (TREE_CODE (t) == TEMPLATE_DECL)
9058                 {
9059                   ++processing_template_decl;
9060                   push_deferring_access_checks (dk_no_check);
9061                 }
9062
9063               r = tsubst_friend_function (t, args);
9064               add_friend (type, r, /*complain=*/false);
9065               if (TREE_CODE (t) == TEMPLATE_DECL)
9066                 {
9067                   pop_deferring_access_checks ();
9068                   --processing_template_decl;
9069                 }
9070             }
9071         }
9072     }
9073
9074   if (CLASSTYPE_LAMBDA_EXPR (type))
9075     {
9076       tree lambda = CLASSTYPE_LAMBDA_EXPR (type);
9077       if (LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (lambda))
9078         {
9079           apply_lambda_return_type (lambda, void_type_node);
9080           LAMBDA_EXPR_RETURN_TYPE (lambda) = NULL_TREE;
9081         }
9082       instantiate_decl (lambda_function (type), false, false);
9083       maybe_add_lambda_conv_op (type);
9084     }
9085
9086   /* Set the file and line number information to whatever is given for
9087      the class itself.  This puts error messages involving generated
9088      implicit functions at a predictable point, and the same point
9089      that would be used for non-template classes.  */
9090   input_location = DECL_SOURCE_LOCATION (typedecl);
9091
9092   unreverse_member_declarations (type);
9093   finish_struct_1 (type);
9094   TYPE_BEING_DEFINED (type) = 0;
9095
9096   /* We don't instantiate default arguments for member functions.  14.7.1:
9097
9098      The implicit instantiation of a class template specialization causes
9099      the implicit instantiation of the declarations, but not of the
9100      definitions or default arguments, of the class member functions,
9101      member classes, static data members and member templates....  */
9102
9103   /* Some typedefs referenced from within the template code need to be access
9104      checked at template instantiation time, i.e now. These types were
9105      added to the template at parsing time. Let's get those and perform
9106      the access checks then.  */
9107   perform_typedefs_access_check (pattern, args);
9108   perform_deferred_access_checks ();
9109   pop_nested_class ();
9110   maximum_field_alignment = saved_maximum_field_alignment;
9111   pop_from_top_level ();
9112   pop_deferring_access_checks ();
9113   pop_tinst_level ();
9114
9115   /* The vtable for a template class can be emitted in any translation
9116      unit in which the class is instantiated.  When there is no key
9117      method, however, finish_struct_1 will already have added TYPE to
9118      the keyed_classes list.  */
9119   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
9120     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
9121
9122   return type;
9123 }
9124
9125 /* Wrapper for instantiate_class_template_1.  */
9126
9127 tree
9128 instantiate_class_template (tree type)
9129 {
9130   tree ret;
9131   timevar_push (TV_TEMPLATE_INST);
9132   ret = instantiate_class_template_1 (type);
9133   timevar_pop (TV_TEMPLATE_INST);
9134   return ret;
9135 }
9136
9137 static tree
9138 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9139 {
9140   tree r;
9141
9142   if (!t)
9143     r = t;
9144   else if (TYPE_P (t))
9145     r = tsubst (t, args, complain, in_decl);
9146   else
9147     {
9148       if (!(complain & tf_warning))
9149         ++c_inhibit_evaluation_warnings;
9150       r = tsubst_expr (t, args, complain, in_decl,
9151                        /*integral_constant_expression_p=*/true);
9152       if (!(complain & tf_warning))
9153         --c_inhibit_evaluation_warnings;
9154       /* Preserve the raw-reference nature of T.  */
9155       if (TREE_TYPE (t) && TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE
9156           && REFERENCE_REF_P (r))
9157         r = TREE_OPERAND (r, 0);
9158     }
9159   return r;
9160 }
9161
9162 /* Given a function parameter pack TMPL_PARM and some function parameters
9163    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
9164    and set *SPEC_P to point at the next point in the list.  */
9165
9166 static tree
9167 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
9168 {
9169   /* Collect all of the extra "packed" parameters into an
9170      argument pack.  */
9171   tree parmvec;
9172   tree parmtypevec;
9173   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
9174   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
9175   tree spec_parm = *spec_p;
9176   int i, len;
9177
9178   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
9179     if (tmpl_parm
9180         && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
9181       break;
9182
9183   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
9184   parmvec = make_tree_vec (len);
9185   parmtypevec = make_tree_vec (len);
9186   spec_parm = *spec_p;
9187   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
9188     {
9189       TREE_VEC_ELT (parmvec, i) = spec_parm;
9190       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
9191     }
9192
9193   /* Build the argument packs.  */
9194   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
9195   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
9196   TREE_TYPE (argpack) = argtypepack;
9197   *spec_p = spec_parm;
9198
9199   return argpack;
9200 }
9201
9202 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
9203    NONTYPE_ARGUMENT_PACK.  */
9204
9205 static tree
9206 make_fnparm_pack (tree spec_parm)
9207 {
9208   return extract_fnparm_pack (NULL_TREE, &spec_parm);
9209 }
9210
9211 /* Substitute ARGS into T, which is an pack expansion
9212    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
9213    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
9214    (if only a partial substitution could be performed) or
9215    ERROR_MARK_NODE if there was an error.  */
9216 tree
9217 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
9218                        tree in_decl)
9219 {
9220   tree pattern;
9221   tree pack, packs = NULL_TREE;
9222   bool unsubstituted_packs = false;
9223   int i, len = -1;
9224   tree result;
9225   htab_t saved_local_specializations = NULL;
9226
9227   gcc_assert (PACK_EXPANSION_P (t));
9228   pattern = PACK_EXPANSION_PATTERN (t);
9229
9230   /* Determine the argument packs that will instantiate the parameter
9231      packs used in the expansion expression. While we're at it,
9232      compute the number of arguments to be expanded and make sure it
9233      is consistent.  */
9234   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
9235        pack = TREE_CHAIN (pack))
9236     {
9237       tree parm_pack = TREE_VALUE (pack);
9238       tree arg_pack = NULL_TREE;
9239       tree orig_arg = NULL_TREE;
9240
9241       if (TREE_CODE (parm_pack) == BASES)
9242        {
9243          if (BASES_DIRECT (parm_pack))
9244            return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
9245                                                         args, complain, in_decl, false));
9246          else
9247            return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
9248                                                  args, complain, in_decl, false));
9249        }
9250       if (TREE_CODE (parm_pack) == PARM_DECL)
9251         {
9252           if (!cp_unevaluated_operand)
9253             arg_pack = retrieve_local_specialization (parm_pack);
9254           else
9255             {
9256               /* We can't rely on local_specializations for a parameter
9257                  name used later in a function declaration (such as in a
9258                  late-specified return type).  Even if it exists, it might
9259                  have the wrong value for a recursive call.  Just make a
9260                  dummy decl, since it's only used for its type.  */
9261               arg_pack = tsubst_decl (parm_pack, args, complain);
9262               if (arg_pack && FUNCTION_PARAMETER_PACK_P (arg_pack))
9263                 /* Partial instantiation of the parm_pack, we can't build
9264                    up an argument pack yet.  */
9265                 arg_pack = NULL_TREE;
9266               else
9267                 arg_pack = make_fnparm_pack (arg_pack);
9268             }
9269         }
9270       else
9271         {
9272           int level, idx, levels;
9273           template_parm_level_and_index (parm_pack, &level, &idx);
9274
9275           levels = TMPL_ARGS_DEPTH (args);
9276           if (level <= levels)
9277             arg_pack = TMPL_ARG (args, level, idx);
9278         }
9279
9280       orig_arg = arg_pack;
9281       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
9282         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
9283       
9284       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
9285         /* This can only happen if we forget to expand an argument
9286            pack somewhere else. Just return an error, silently.  */
9287         {
9288           result = make_tree_vec (1);
9289           TREE_VEC_ELT (result, 0) = error_mark_node;
9290           return result;
9291         }
9292
9293       if (arg_from_parm_pack_p (arg_pack, parm_pack))
9294         /* The argument pack that the parameter maps to is just an
9295            expansion of the parameter itself, such as one would find
9296            in the implicit typedef of a class inside the class itself.
9297            Consider this parameter "unsubstituted", so that we will
9298            maintain the outer pack expansion.  */
9299         arg_pack = NULL_TREE;
9300           
9301       if (arg_pack)
9302         {
9303           int my_len = 
9304             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
9305
9306           /* Don't bother trying to do a partial substitution with
9307              incomplete packs; we'll try again after deduction.  */
9308           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
9309             return t;
9310
9311           if (len < 0)
9312             len = my_len;
9313           else if (len != my_len)
9314             {
9315               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
9316                 error ("mismatched argument pack lengths while expanding "
9317                        "%<%T%>",
9318                        pattern);
9319               else
9320                 error ("mismatched argument pack lengths while expanding "
9321                        "%<%E%>",
9322                        pattern);
9323               return error_mark_node;
9324             }
9325
9326           /* Keep track of the parameter packs and their corresponding
9327              argument packs.  */
9328           packs = tree_cons (parm_pack, arg_pack, packs);
9329           TREE_TYPE (packs) = orig_arg;
9330         }
9331       else
9332         {
9333           /* We can't substitute for this parameter pack.  */
9334           unsubstituted_packs = true;
9335           break;
9336         }
9337     }
9338
9339   /* We cannot expand this expansion expression, because we don't have
9340      all of the argument packs we need. Substitute into the pattern
9341      and return a PACK_EXPANSION_*. The caller will need to deal with
9342      that.  */
9343   if (unsubstituted_packs)
9344     {
9345       tree new_pat;
9346       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9347         new_pat = tsubst_expr (pattern, args, complain, in_decl,
9348                                /*integral_constant_expression_p=*/false);
9349       else
9350         new_pat = tsubst (pattern, args, complain, in_decl);
9351       return make_pack_expansion (new_pat);
9352     }
9353
9354   /* We could not find any argument packs that work.  */
9355   if (len < 0)
9356     return error_mark_node;
9357
9358   if (cp_unevaluated_operand)
9359     {
9360       /* We're in a late-specified return type, so create our own local
9361          specializations table; the current table is either NULL or (in the
9362          case of recursive unification) might have bindings that we don't
9363          want to use or alter.  */
9364       saved_local_specializations = local_specializations;
9365       local_specializations = htab_create (37,
9366                                            hash_local_specialization,
9367                                            eq_local_specializations,
9368                                            NULL);
9369     }
9370
9371   /* For each argument in each argument pack, substitute into the
9372      pattern.  */
9373   result = make_tree_vec (len);
9374   for (i = 0; i < len; ++i)
9375     {
9376       /* For parameter pack, change the substitution of the parameter
9377          pack to the ith argument in its argument pack, then expand
9378          the pattern.  */
9379       for (pack = packs; pack; pack = TREE_CHAIN (pack))
9380         {
9381           tree parm = TREE_PURPOSE (pack);
9382           tree arg;
9383
9384           /* Select the Ith argument from the pack.  */
9385           if (TREE_CODE (parm) == PARM_DECL)
9386             {
9387               if (i == 0)
9388                 {
9389                   arg = make_node (ARGUMENT_PACK_SELECT);
9390                   ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
9391                   mark_used (parm);
9392                   register_local_specialization (arg, parm);
9393                 }
9394               else
9395                 arg = retrieve_local_specialization (parm);
9396             }
9397           else
9398             {
9399               int idx, level;
9400               template_parm_level_and_index (parm, &level, &idx);
9401
9402               if (i == 0)
9403                 {
9404                   arg = make_node (ARGUMENT_PACK_SELECT);
9405                   ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
9406                   /* Update the corresponding argument.  */
9407                   TMPL_ARG (args, level, idx) = arg;
9408                 }
9409               else
9410                 /* Re-use the ARGUMENT_PACK_SELECT.  */
9411                 arg = TMPL_ARG (args, level, idx);
9412             }
9413           ARGUMENT_PACK_SELECT_INDEX (arg) = i;
9414         }
9415
9416       /* Substitute into the PATTERN with the altered arguments.  */
9417       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9418         TREE_VEC_ELT (result, i) = 
9419           tsubst_expr (pattern, args, complain, in_decl,
9420                        /*integral_constant_expression_p=*/false);
9421       else
9422         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
9423
9424       if (TREE_VEC_ELT (result, i) == error_mark_node)
9425         {
9426           result = error_mark_node;
9427           break;
9428         }
9429     }
9430
9431   /* Update ARGS to restore the substitution from parameter packs to
9432      their argument packs.  */
9433   for (pack = packs; pack; pack = TREE_CHAIN (pack))
9434     {
9435       tree parm = TREE_PURPOSE (pack);
9436
9437       if (TREE_CODE (parm) == PARM_DECL)
9438         register_local_specialization (TREE_TYPE (pack), parm);
9439       else
9440         {
9441           int idx, level;
9442           template_parm_level_and_index (parm, &level, &idx);
9443           
9444           /* Update the corresponding argument.  */
9445           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
9446             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
9447               TREE_TYPE (pack);
9448           else
9449             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
9450         }
9451     }
9452
9453   if (saved_local_specializations)
9454     {
9455       htab_delete (local_specializations);
9456       local_specializations = saved_local_specializations;
9457     }
9458   
9459   return result;
9460 }
9461
9462 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
9463    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
9464    parameter packs; all parms generated from a function parameter pack will
9465    have the same DECL_PARM_INDEX.  */
9466
9467 tree
9468 get_pattern_parm (tree parm, tree tmpl)
9469 {
9470   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
9471   tree patparm;
9472
9473   if (DECL_ARTIFICIAL (parm))
9474     {
9475       for (patparm = DECL_ARGUMENTS (pattern);
9476            patparm; patparm = DECL_CHAIN (patparm))
9477         if (DECL_ARTIFICIAL (patparm)
9478             && DECL_NAME (parm) == DECL_NAME (patparm))
9479           break;
9480     }
9481   else
9482     {
9483       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
9484       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
9485       gcc_assert (DECL_PARM_INDEX (patparm)
9486                   == DECL_PARM_INDEX (parm));
9487     }
9488
9489   return patparm;
9490 }
9491
9492 /* Substitute ARGS into the vector or list of template arguments T.  */
9493
9494 static tree
9495 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9496 {
9497   tree orig_t = t;
9498   int len, need_new = 0, i, expanded_len_adjust = 0, out;
9499   tree *elts;
9500
9501   if (t == error_mark_node)
9502     return error_mark_node;
9503
9504   len = TREE_VEC_LENGTH (t);
9505   elts = XALLOCAVEC (tree, len);
9506
9507   for (i = 0; i < len; i++)
9508     {
9509       tree orig_arg = TREE_VEC_ELT (t, i);
9510       tree new_arg;
9511
9512       if (TREE_CODE (orig_arg) == TREE_VEC)
9513         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
9514       else if (PACK_EXPANSION_P (orig_arg))
9515         {
9516           /* Substitute into an expansion expression.  */
9517           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
9518
9519           if (TREE_CODE (new_arg) == TREE_VEC)
9520             /* Add to the expanded length adjustment the number of
9521                expanded arguments. We subtract one from this
9522                measurement, because the argument pack expression
9523                itself is already counted as 1 in
9524                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
9525                the argument pack is empty.  */
9526             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
9527         }
9528       else if (ARGUMENT_PACK_P (orig_arg))
9529         {
9530           /* Substitute into each of the arguments.  */
9531           new_arg = TYPE_P (orig_arg)
9532             ? cxx_make_type (TREE_CODE (orig_arg))
9533             : make_node (TREE_CODE (orig_arg));
9534           
9535           SET_ARGUMENT_PACK_ARGS (
9536             new_arg,
9537             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
9538                                   args, complain, in_decl));
9539
9540           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
9541             new_arg = error_mark_node;
9542
9543           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
9544             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
9545                                           complain, in_decl);
9546             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
9547
9548             if (TREE_TYPE (new_arg) == error_mark_node)
9549               new_arg = error_mark_node;
9550           }
9551         }
9552       else
9553         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
9554
9555       if (new_arg == error_mark_node)
9556         return error_mark_node;
9557
9558       elts[i] = new_arg;
9559       if (new_arg != orig_arg)
9560         need_new = 1;
9561     }
9562
9563   if (!need_new)
9564     return t;
9565
9566   /* Make space for the expanded arguments coming from template
9567      argument packs.  */
9568   t = make_tree_vec (len + expanded_len_adjust);
9569   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
9570      arguments for a member template.
9571      In that case each TREE_VEC in ORIG_T represents a level of template
9572      arguments, and ORIG_T won't carry any non defaulted argument count.
9573      It will rather be the nested TREE_VECs that will carry one.
9574      In other words, ORIG_T carries a non defaulted argument count only
9575      if it doesn't contain any nested TREE_VEC.  */
9576   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
9577     {
9578       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
9579       count += expanded_len_adjust;
9580       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
9581     }
9582   for (i = 0, out = 0; i < len; i++)
9583     {
9584       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
9585            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
9586           && TREE_CODE (elts[i]) == TREE_VEC)
9587         {
9588           int idx;
9589
9590           /* Now expand the template argument pack "in place".  */
9591           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
9592             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
9593         }
9594       else
9595         {
9596           TREE_VEC_ELT (t, out) = elts[i];
9597           out++;
9598         }
9599     }
9600
9601   return t;
9602 }
9603
9604 /* Return the result of substituting ARGS into the template parameters
9605    given by PARMS.  If there are m levels of ARGS and m + n levels of
9606    PARMS, then the result will contain n levels of PARMS.  For
9607    example, if PARMS is `template <class T> template <class U>
9608    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
9609    result will be `template <int*, double, class V>'.  */
9610
9611 static tree
9612 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
9613 {
9614   tree r = NULL_TREE;
9615   tree* new_parms;
9616
9617   /* When substituting into a template, we must set
9618      PROCESSING_TEMPLATE_DECL as the template parameters may be
9619      dependent if they are based on one-another, and the dependency
9620      predicates are short-circuit outside of templates.  */
9621   ++processing_template_decl;
9622
9623   for (new_parms = &r;
9624        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
9625        new_parms = &(TREE_CHAIN (*new_parms)),
9626          parms = TREE_CHAIN (parms))
9627     {
9628       tree new_vec =
9629         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
9630       int i;
9631
9632       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
9633         {
9634           tree tuple;
9635
9636           if (parms == error_mark_node)
9637             continue;
9638
9639           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
9640
9641           if (tuple == error_mark_node)
9642             continue;
9643
9644           TREE_VEC_ELT (new_vec, i) =
9645             tsubst_template_parm (tuple, args, complain);
9646         }
9647
9648       *new_parms =
9649         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
9650                              - TMPL_ARGS_DEPTH (args)),
9651                    new_vec, NULL_TREE);
9652     }
9653
9654   --processing_template_decl;
9655
9656   return r;
9657 }
9658
9659 /* Return the result of substituting ARGS into one template parameter
9660    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
9661    parameter and which TREE_PURPOSE is the default argument of the
9662    template parameter.  */
9663
9664 static tree
9665 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
9666 {
9667   tree default_value, parm_decl;
9668
9669   if (args == NULL_TREE
9670       || t == NULL_TREE
9671       || t == error_mark_node)
9672     return t;
9673
9674   gcc_assert (TREE_CODE (t) == TREE_LIST);
9675
9676   default_value = TREE_PURPOSE (t);
9677   parm_decl = TREE_VALUE (t);
9678
9679   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
9680   if (TREE_CODE (parm_decl) == PARM_DECL
9681       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
9682     parm_decl = error_mark_node;
9683   default_value = tsubst_template_arg (default_value, args,
9684                                        complain, NULL_TREE);
9685
9686   return build_tree_list (default_value, parm_decl);
9687 }
9688
9689 /* Substitute the ARGS into the indicated aggregate (or enumeration)
9690    type T.  If T is not an aggregate or enumeration type, it is
9691    handled as if by tsubst.  IN_DECL is as for tsubst.  If
9692    ENTERING_SCOPE is nonzero, T is the context for a template which
9693    we are presently tsubst'ing.  Return the substituted value.  */
9694
9695 static tree
9696 tsubst_aggr_type (tree t,
9697                   tree args,
9698                   tsubst_flags_t complain,
9699                   tree in_decl,
9700                   int entering_scope)
9701 {
9702   if (t == NULL_TREE)
9703     return NULL_TREE;
9704
9705   switch (TREE_CODE (t))
9706     {
9707     case RECORD_TYPE:
9708       if (TYPE_PTRMEMFUNC_P (t))
9709         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
9710
9711       /* Else fall through.  */
9712     case ENUMERAL_TYPE:
9713     case UNION_TYPE:
9714       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
9715         {
9716           tree argvec;
9717           tree context;
9718           tree r;
9719           int saved_unevaluated_operand;
9720           int saved_inhibit_evaluation_warnings;
9721
9722           /* In "sizeof(X<I>)" we need to evaluate "I".  */
9723           saved_unevaluated_operand = cp_unevaluated_operand;
9724           cp_unevaluated_operand = 0;
9725           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9726           c_inhibit_evaluation_warnings = 0;
9727
9728           /* First, determine the context for the type we are looking
9729              up.  */
9730           context = TYPE_CONTEXT (t);
9731           if (context && TYPE_P (context))
9732             {
9733               context = tsubst_aggr_type (context, args, complain,
9734                                           in_decl, /*entering_scope=*/1);
9735               /* If context is a nested class inside a class template,
9736                  it may still need to be instantiated (c++/33959).  */
9737               context = complete_type (context);
9738             }
9739
9740           /* Then, figure out what arguments are appropriate for the
9741              type we are trying to find.  For example, given:
9742
9743                template <class T> struct S;
9744                template <class T, class U> void f(T, U) { S<U> su; }
9745
9746              and supposing that we are instantiating f<int, double>,
9747              then our ARGS will be {int, double}, but, when looking up
9748              S we only want {double}.  */
9749           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
9750                                          complain, in_decl);
9751           if (argvec == error_mark_node)
9752             r = error_mark_node;
9753           else
9754             {
9755               r = lookup_template_class (t, argvec, in_decl, context,
9756                                          entering_scope, complain);
9757               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
9758             }
9759
9760           cp_unevaluated_operand = saved_unevaluated_operand;
9761           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9762
9763           return r;
9764         }
9765       else
9766         /* This is not a template type, so there's nothing to do.  */
9767         return t;
9768
9769     default:
9770       return tsubst (t, args, complain, in_decl);
9771     }
9772 }
9773
9774 /* Substitute into the default argument ARG (a default argument for
9775    FN), which has the indicated TYPE.  */
9776
9777 tree
9778 tsubst_default_argument (tree fn, tree type, tree arg)
9779 {
9780   tree saved_class_ptr = NULL_TREE;
9781   tree saved_class_ref = NULL_TREE;
9782
9783   /* This can happen in invalid code.  */
9784   if (TREE_CODE (arg) == DEFAULT_ARG)
9785     return arg;
9786
9787   /* This default argument came from a template.  Instantiate the
9788      default argument here, not in tsubst.  In the case of
9789      something like:
9790
9791        template <class T>
9792        struct S {
9793          static T t();
9794          void f(T = t());
9795        };
9796
9797      we must be careful to do name lookup in the scope of S<T>,
9798      rather than in the current class.  */
9799   push_access_scope (fn);
9800   /* The "this" pointer is not valid in a default argument.  */
9801   if (cfun)
9802     {
9803       saved_class_ptr = current_class_ptr;
9804       cp_function_chain->x_current_class_ptr = NULL_TREE;
9805       saved_class_ref = current_class_ref;
9806       cp_function_chain->x_current_class_ref = NULL_TREE;
9807     }
9808
9809   push_deferring_access_checks(dk_no_deferred);
9810   /* The default argument expression may cause implicitly defined
9811      member functions to be synthesized, which will result in garbage
9812      collection.  We must treat this situation as if we were within
9813      the body of function so as to avoid collecting live data on the
9814      stack.  */
9815   ++function_depth;
9816   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
9817                      tf_warning_or_error, NULL_TREE,
9818                      /*integral_constant_expression_p=*/false);
9819   --function_depth;
9820   pop_deferring_access_checks();
9821
9822   /* Restore the "this" pointer.  */
9823   if (cfun)
9824     {
9825       cp_function_chain->x_current_class_ptr = saved_class_ptr;
9826       cp_function_chain->x_current_class_ref = saved_class_ref;
9827     }
9828
9829   /* Make sure the default argument is reasonable.  */
9830   arg = check_default_argument (type, arg);
9831
9832   pop_access_scope (fn);
9833
9834   return arg;
9835 }
9836
9837 /* Substitute into all the default arguments for FN.  */
9838
9839 static void
9840 tsubst_default_arguments (tree fn)
9841 {
9842   tree arg;
9843   tree tmpl_args;
9844
9845   tmpl_args = DECL_TI_ARGS (fn);
9846
9847   /* If this function is not yet instantiated, we certainly don't need
9848      its default arguments.  */
9849   if (uses_template_parms (tmpl_args))
9850     return;
9851   /* Don't do this again for clones.  */
9852   if (DECL_CLONED_FUNCTION_P (fn))
9853     return;
9854
9855   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
9856        arg;
9857        arg = TREE_CHAIN (arg))
9858     if (TREE_PURPOSE (arg))
9859       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
9860                                                     TREE_VALUE (arg),
9861                                                     TREE_PURPOSE (arg));
9862 }
9863
9864 /* Substitute the ARGS into the T, which is a _DECL.  Return the
9865    result of the substitution.  Issue error and warning messages under
9866    control of COMPLAIN.  */
9867
9868 static tree
9869 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
9870 {
9871 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
9872   location_t saved_loc;
9873   tree r = NULL_TREE;
9874   tree in_decl = t;
9875   hashval_t hash = 0;
9876
9877   /* Set the filename and linenumber to improve error-reporting.  */
9878   saved_loc = input_location;
9879   input_location = DECL_SOURCE_LOCATION (t);
9880
9881   switch (TREE_CODE (t))
9882     {
9883     case TEMPLATE_DECL:
9884       {
9885         /* We can get here when processing a member function template,
9886            member class template, or template template parameter.  */
9887         tree decl = DECL_TEMPLATE_RESULT (t);
9888         tree spec;
9889         tree tmpl_args;
9890         tree full_args;
9891
9892         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9893           {
9894             /* Template template parameter is treated here.  */
9895             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9896             if (new_type == error_mark_node)
9897               RETURN (error_mark_node);
9898
9899             r = copy_decl (t);
9900             DECL_CHAIN (r) = NULL_TREE;
9901             TREE_TYPE (r) = new_type;
9902             DECL_TEMPLATE_RESULT (r)
9903               = build_decl (DECL_SOURCE_LOCATION (decl),
9904                             TYPE_DECL, DECL_NAME (decl), new_type);
9905             DECL_TEMPLATE_PARMS (r)
9906               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9907                                        complain);
9908             TYPE_NAME (new_type) = r;
9909             break;
9910           }
9911
9912         /* We might already have an instance of this template.
9913            The ARGS are for the surrounding class type, so the
9914            full args contain the tsubst'd args for the context,
9915            plus the innermost args from the template decl.  */
9916         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
9917           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
9918           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
9919         /* Because this is a template, the arguments will still be
9920            dependent, even after substitution.  If
9921            PROCESSING_TEMPLATE_DECL is not set, the dependency
9922            predicates will short-circuit.  */
9923         ++processing_template_decl;
9924         full_args = tsubst_template_args (tmpl_args, args,
9925                                           complain, in_decl);
9926         --processing_template_decl;
9927         if (full_args == error_mark_node)
9928           RETURN (error_mark_node);
9929
9930         /* If this is a default template template argument,
9931            tsubst might not have changed anything.  */
9932         if (full_args == tmpl_args)
9933           RETURN (t);
9934
9935         hash = hash_tmpl_and_args (t, full_args);
9936         spec = retrieve_specialization (t, full_args, hash);
9937         if (spec != NULL_TREE)
9938           {
9939             r = spec;
9940             break;
9941           }
9942
9943         /* Make a new template decl.  It will be similar to the
9944            original, but will record the current template arguments.
9945            We also create a new function declaration, which is just
9946            like the old one, but points to this new template, rather
9947            than the old one.  */
9948         r = copy_decl (t);
9949         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9950         DECL_CHAIN (r) = NULL_TREE;
9951
9952         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9953
9954         if (TREE_CODE (decl) == TYPE_DECL
9955             && !TYPE_DECL_ALIAS_P (decl))
9956           {
9957             tree new_type;
9958             ++processing_template_decl;
9959             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9960             --processing_template_decl;
9961             if (new_type == error_mark_node)
9962               RETURN (error_mark_node);
9963
9964             TREE_TYPE (r) = new_type;
9965             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9966             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9967             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9968             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9969           }
9970         else
9971           {
9972             tree new_decl;
9973             ++processing_template_decl;
9974             new_decl = tsubst (decl, args, complain, in_decl);
9975             --processing_template_decl;
9976             if (new_decl == error_mark_node)
9977               RETURN (error_mark_node);
9978
9979             DECL_TEMPLATE_RESULT (r) = new_decl;
9980             DECL_TI_TEMPLATE (new_decl) = r;
9981             TREE_TYPE (r) = TREE_TYPE (new_decl);
9982             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9983             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9984           }
9985
9986         SET_DECL_IMPLICIT_INSTANTIATION (r);
9987         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9988         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9989
9990         /* The template parameters for this new template are all the
9991            template parameters for the old template, except the
9992            outermost level of parameters.  */
9993         DECL_TEMPLATE_PARMS (r)
9994           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9995                                    complain);
9996
9997         if (PRIMARY_TEMPLATE_P (t))
9998           DECL_PRIMARY_TEMPLATE (r) = r;
9999
10000         if (TREE_CODE (decl) != TYPE_DECL)
10001           /* Record this non-type partial instantiation.  */
10002           register_specialization (r, t,
10003                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
10004                                    false, hash);
10005       }
10006       break;
10007
10008     case FUNCTION_DECL:
10009       {
10010         tree ctx;
10011         tree argvec = NULL_TREE;
10012         tree *friends;
10013         tree gen_tmpl;
10014         tree type;
10015         int member;
10016         int args_depth;
10017         int parms_depth;
10018
10019         /* Nobody should be tsubst'ing into non-template functions.  */
10020         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
10021
10022         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
10023           {
10024             tree spec;
10025             bool dependent_p;
10026
10027             /* If T is not dependent, just return it.  We have to
10028                increment PROCESSING_TEMPLATE_DECL because
10029                value_dependent_expression_p assumes that nothing is
10030                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
10031             ++processing_template_decl;
10032             dependent_p = value_dependent_expression_p (t);
10033             --processing_template_decl;
10034             if (!dependent_p)
10035               RETURN (t);
10036
10037             /* Calculate the most general template of which R is a
10038                specialization, and the complete set of arguments used to
10039                specialize R.  */
10040             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
10041             argvec = tsubst_template_args (DECL_TI_ARGS
10042                                           (DECL_TEMPLATE_RESULT
10043                                                  (DECL_TI_TEMPLATE (t))),
10044                                            args, complain, in_decl);
10045             if (argvec == error_mark_node)
10046               RETURN (error_mark_node);
10047
10048             /* Check to see if we already have this specialization.  */
10049             hash = hash_tmpl_and_args (gen_tmpl, argvec);
10050             spec = retrieve_specialization (gen_tmpl, argvec, hash);
10051
10052             if (spec)
10053               {
10054                 r = spec;
10055                 break;
10056               }
10057
10058             /* We can see more levels of arguments than parameters if
10059                there was a specialization of a member template, like
10060                this:
10061
10062                  template <class T> struct S { template <class U> void f(); }
10063                  template <> template <class U> void S<int>::f(U);
10064
10065                Here, we'll be substituting into the specialization,
10066                because that's where we can find the code we actually
10067                want to generate, but we'll have enough arguments for
10068                the most general template.
10069
10070                We also deal with the peculiar case:
10071
10072                  template <class T> struct S {
10073                    template <class U> friend void f();
10074                  };
10075                  template <class U> void f() {}
10076                  template S<int>;
10077                  template void f<double>();
10078
10079                Here, the ARGS for the instantiation of will be {int,
10080                double}.  But, we only need as many ARGS as there are
10081                levels of template parameters in CODE_PATTERN.  We are
10082                careful not to get fooled into reducing the ARGS in
10083                situations like:
10084
10085                  template <class T> struct S { template <class U> void f(U); }
10086                  template <class T> template <> void S<T>::f(int) {}
10087
10088                which we can spot because the pattern will be a
10089                specialization in this case.  */
10090             args_depth = TMPL_ARGS_DEPTH (args);
10091             parms_depth =
10092               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
10093             if (args_depth > parms_depth
10094                 && !DECL_TEMPLATE_SPECIALIZATION (t))
10095               args = get_innermost_template_args (args, parms_depth);
10096           }
10097         else
10098           {
10099             /* This special case arises when we have something like this:
10100
10101                  template <class T> struct S {
10102                    friend void f<int>(int, double);
10103                  };
10104
10105                Here, the DECL_TI_TEMPLATE for the friend declaration
10106                will be an IDENTIFIER_NODE.  We are being called from
10107                tsubst_friend_function, and we want only to create a
10108                new decl (R) with appropriate types so that we can call
10109                determine_specialization.  */
10110             gen_tmpl = NULL_TREE;
10111           }
10112
10113         if (DECL_CLASS_SCOPE_P (t))
10114           {
10115             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
10116               member = 2;
10117             else
10118               member = 1;
10119             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
10120                                     complain, t, /*entering_scope=*/1);
10121           }
10122         else
10123           {
10124             member = 0;
10125             ctx = DECL_CONTEXT (t);
10126           }
10127         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10128         if (type == error_mark_node)
10129           RETURN (error_mark_node);
10130
10131         /* We do NOT check for matching decls pushed separately at this
10132            point, as they may not represent instantiations of this
10133            template, and in any case are considered separate under the
10134            discrete model.  */
10135         r = copy_decl (t);
10136         DECL_USE_TEMPLATE (r) = 0;
10137         TREE_TYPE (r) = type;
10138         /* Clear out the mangled name and RTL for the instantiation.  */
10139         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10140         SET_DECL_RTL (r, NULL);
10141         /* Leave DECL_INITIAL set on deleted instantiations.  */
10142         if (!DECL_DELETED_FN (r))
10143           DECL_INITIAL (r) = NULL_TREE;
10144         DECL_CONTEXT (r) = ctx;
10145
10146         if (member && DECL_CONV_FN_P (r))
10147           /* Type-conversion operator.  Reconstruct the name, in
10148              case it's the name of one of the template's parameters.  */
10149           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
10150
10151         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
10152                                      complain, t);
10153         DECL_RESULT (r) = NULL_TREE;
10154
10155         TREE_STATIC (r) = 0;
10156         TREE_PUBLIC (r) = TREE_PUBLIC (t);
10157         DECL_EXTERNAL (r) = 1;
10158         /* If this is an instantiation of a function with internal
10159            linkage, we already know what object file linkage will be
10160            assigned to the instantiation.  */
10161         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
10162         DECL_DEFER_OUTPUT (r) = 0;
10163         DECL_CHAIN (r) = NULL_TREE;
10164         DECL_PENDING_INLINE_INFO (r) = 0;
10165         DECL_PENDING_INLINE_P (r) = 0;
10166         DECL_SAVED_TREE (r) = NULL_TREE;
10167         DECL_STRUCT_FUNCTION (r) = NULL;
10168         TREE_USED (r) = 0;
10169         /* We'll re-clone as appropriate in instantiate_template.  */
10170         DECL_CLONED_FUNCTION (r) = NULL_TREE;
10171
10172         /* If we aren't complaining now, return on error before we register
10173            the specialization so that we'll complain eventually.  */
10174         if ((complain & tf_error) == 0
10175             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10176             && !grok_op_properties (r, /*complain=*/false))
10177           RETURN (error_mark_node);
10178
10179         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
10180            this in the special friend case mentioned above where
10181            GEN_TMPL is NULL.  */
10182         if (gen_tmpl)
10183           {
10184             DECL_TEMPLATE_INFO (r)
10185               = build_template_info (gen_tmpl, argvec);
10186             SET_DECL_IMPLICIT_INSTANTIATION (r);
10187             register_specialization (r, gen_tmpl, argvec, false, hash);
10188
10189             /* We're not supposed to instantiate default arguments
10190                until they are called, for a template.  But, for a
10191                declaration like:
10192
10193                  template <class T> void f ()
10194                  { extern void g(int i = T()); }
10195
10196                we should do the substitution when the template is
10197                instantiated.  We handle the member function case in
10198                instantiate_class_template since the default arguments
10199                might refer to other members of the class.  */
10200             if (!member
10201                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10202                 && !uses_template_parms (argvec))
10203               tsubst_default_arguments (r);
10204           }
10205         else
10206           DECL_TEMPLATE_INFO (r) = NULL_TREE;
10207
10208         /* Copy the list of befriending classes.  */
10209         for (friends = &DECL_BEFRIENDING_CLASSES (r);
10210              *friends;
10211              friends = &TREE_CHAIN (*friends))
10212           {
10213             *friends = copy_node (*friends);
10214             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
10215                                             args, complain,
10216                                             in_decl);
10217           }
10218
10219         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
10220           {
10221             maybe_retrofit_in_chrg (r);
10222             if (DECL_CONSTRUCTOR_P (r))
10223               grok_ctor_properties (ctx, r);
10224             /* If this is an instantiation of a member template, clone it.
10225                If it isn't, that'll be handled by
10226                clone_constructors_and_destructors.  */
10227             if (PRIMARY_TEMPLATE_P (gen_tmpl))
10228               clone_function_decl (r, /*update_method_vec_p=*/0);
10229           }
10230         else if ((complain & tf_error) != 0
10231                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10232                  && !grok_op_properties (r, /*complain=*/true))
10233           RETURN (error_mark_node);
10234
10235         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
10236           SET_DECL_FRIEND_CONTEXT (r,
10237                                    tsubst (DECL_FRIEND_CONTEXT (t),
10238                                             args, complain, in_decl));
10239
10240         /* Possibly limit visibility based on template args.  */
10241         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10242         if (DECL_VISIBILITY_SPECIFIED (t))
10243           {
10244             DECL_VISIBILITY_SPECIFIED (r) = 0;
10245             DECL_ATTRIBUTES (r)
10246               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10247           }
10248         determine_visibility (r);
10249         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
10250             && !processing_template_decl)
10251           defaulted_late_check (r);
10252
10253         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10254                                         args, complain, in_decl);
10255       }
10256       break;
10257
10258     case PARM_DECL:
10259       {
10260         tree type = NULL_TREE;
10261         int i, len = 1;
10262         tree expanded_types = NULL_TREE;
10263         tree prev_r = NULL_TREE;
10264         tree first_r = NULL_TREE;
10265
10266         if (FUNCTION_PARAMETER_PACK_P (t))
10267           {
10268             /* If there is a local specialization that isn't a
10269                parameter pack, it means that we're doing a "simple"
10270                substitution from inside tsubst_pack_expansion. Just
10271                return the local specialization (which will be a single
10272                parm).  */
10273             tree spec = retrieve_local_specialization (t);
10274             if (spec 
10275                 && TREE_CODE (spec) == PARM_DECL
10276                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
10277               RETURN (spec);
10278
10279             /* Expand the TYPE_PACK_EXPANSION that provides the types for
10280                the parameters in this function parameter pack.  */
10281             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
10282                                                     complain, in_decl);
10283             if (TREE_CODE (expanded_types) == TREE_VEC)
10284               {
10285                 len = TREE_VEC_LENGTH (expanded_types);
10286
10287                 /* Zero-length parameter packs are boring. Just substitute
10288                    into the chain.  */
10289                 if (len == 0)
10290                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
10291                                   TREE_CHAIN (t)));
10292               }
10293             else
10294               {
10295                 /* All we did was update the type. Make a note of that.  */
10296                 type = expanded_types;
10297                 expanded_types = NULL_TREE;
10298               }
10299           }
10300
10301         /* Loop through all of the parameter's we'll build. When T is
10302            a function parameter pack, LEN is the number of expanded
10303            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
10304         r = NULL_TREE;
10305         for (i = 0; i < len; ++i)
10306           {
10307             prev_r = r;
10308             r = copy_node (t);
10309             if (DECL_TEMPLATE_PARM_P (t))
10310               SET_DECL_TEMPLATE_PARM_P (r);
10311
10312             if (expanded_types)
10313               /* We're on the Ith parameter of the function parameter
10314                  pack.  */
10315               {
10316                 /* An argument of a function parameter pack is not a parameter
10317                    pack.  */
10318                 FUNCTION_PARAMETER_PACK_P (r) = false;
10319
10320                 /* Get the Ith type.  */
10321                 type = TREE_VEC_ELT (expanded_types, i);
10322
10323                 if (DECL_NAME (r))
10324                   /* Rename the parameter to include the index.  */
10325                   DECL_NAME (r) =
10326                     make_ith_pack_parameter_name (DECL_NAME (r), i);
10327               }
10328             else if (!type)
10329               /* We're dealing with a normal parameter.  */
10330               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10331
10332             type = type_decays_to (type);
10333             TREE_TYPE (r) = type;
10334             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10335
10336             if (DECL_INITIAL (r))
10337               {
10338                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
10339                   DECL_INITIAL (r) = TREE_TYPE (r);
10340                 else
10341                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
10342                                              complain, in_decl);
10343               }
10344
10345             DECL_CONTEXT (r) = NULL_TREE;
10346
10347             if (!DECL_TEMPLATE_PARM_P (r))
10348               DECL_ARG_TYPE (r) = type_passed_as (type);
10349
10350             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10351                                             args, complain, in_decl);
10352
10353             /* Keep track of the first new parameter we
10354                generate. That's what will be returned to the
10355                caller.  */
10356             if (!first_r)
10357               first_r = r;
10358
10359             /* Build a proper chain of parameters when substituting
10360                into a function parameter pack.  */
10361             if (prev_r)
10362               DECL_CHAIN (prev_r) = r;
10363           }
10364
10365         if (DECL_CHAIN (t))
10366           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
10367                                    complain, DECL_CHAIN (t));
10368
10369         /* FIRST_R contains the start of the chain we've built.  */
10370         r = first_r;
10371       }
10372       break;
10373
10374     case FIELD_DECL:
10375       {
10376         tree type;
10377
10378         r = copy_decl (t);
10379         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10380         if (type == error_mark_node)
10381           RETURN (error_mark_node);
10382         TREE_TYPE (r) = type;
10383         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10384
10385         if (DECL_C_BIT_FIELD (r))
10386           /* For bit-fields, DECL_INITIAL gives the number of bits.  For
10387              non-bit-fields DECL_INITIAL is a non-static data member
10388              initializer, which gets deferred instantiation.  */
10389           DECL_INITIAL (r)
10390             = tsubst_expr (DECL_INITIAL (t), args,
10391                            complain, in_decl,
10392                            /*integral_constant_expression_p=*/true);
10393         else if (DECL_INITIAL (t))
10394           {
10395             /* Set up DECL_TEMPLATE_INFO so that we can get at the
10396                NSDMI in perform_member_init.  Still set DECL_INITIAL
10397                so that we know there is one.  */
10398             DECL_INITIAL (r) = void_zero_node;
10399             gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
10400             retrofit_lang_decl (r);
10401             DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
10402           }
10403         /* We don't have to set DECL_CONTEXT here; it is set by
10404            finish_member_declaration.  */
10405         DECL_CHAIN (r) = NULL_TREE;
10406         if (VOID_TYPE_P (type))
10407           error ("instantiation of %q+D as type %qT", r, type);
10408
10409         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10410                                         args, complain, in_decl);
10411       }
10412       break;
10413
10414     case USING_DECL:
10415       /* We reach here only for member using decls.  */
10416       if (DECL_DEPENDENT_P (t))
10417         {
10418           r = do_class_using_decl
10419             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
10420              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
10421           if (!r)
10422             r = error_mark_node;
10423           else
10424             {
10425               TREE_PROTECTED (r) = TREE_PROTECTED (t);
10426               TREE_PRIVATE (r) = TREE_PRIVATE (t);
10427             }
10428         }
10429       else
10430         {
10431           r = copy_node (t);
10432           DECL_CHAIN (r) = NULL_TREE;
10433         }
10434       break;
10435
10436     case TYPE_DECL:
10437     case VAR_DECL:
10438       {
10439         tree argvec = NULL_TREE;
10440         tree gen_tmpl = NULL_TREE;
10441         tree spec;
10442         tree tmpl = NULL_TREE;
10443         tree ctx;
10444         tree type = NULL_TREE;
10445         bool local_p;
10446
10447         if (TREE_CODE (t) == TYPE_DECL
10448             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
10449           {
10450             /* If this is the canonical decl, we don't have to
10451                mess with instantiations, and often we can't (for
10452                typename, template type parms and such).  Note that
10453                TYPE_NAME is not correct for the above test if
10454                we've copied the type for a typedef.  */
10455             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10456             if (type == error_mark_node)
10457               RETURN (error_mark_node);
10458             r = TYPE_NAME (type);
10459             break;
10460           }
10461
10462         /* Check to see if we already have the specialization we
10463            need.  */
10464         spec = NULL_TREE;
10465         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
10466           {
10467             /* T is a static data member or namespace-scope entity.
10468                We have to substitute into namespace-scope variables
10469                (even though such entities are never templates) because
10470                of cases like:
10471                
10472                  template <class T> void f() { extern T t; }
10473
10474                where the entity referenced is not known until
10475                instantiation time.  */
10476             local_p = false;
10477             ctx = DECL_CONTEXT (t);
10478             if (DECL_CLASS_SCOPE_P (t))
10479               {
10480                 ctx = tsubst_aggr_type (ctx, args,
10481                                         complain,
10482                                         in_decl, /*entering_scope=*/1);
10483                 /* If CTX is unchanged, then T is in fact the
10484                    specialization we want.  That situation occurs when
10485                    referencing a static data member within in its own
10486                    class.  We can use pointer equality, rather than
10487                    same_type_p, because DECL_CONTEXT is always
10488                    canonical...  */
10489                 if (ctx == DECL_CONTEXT (t)
10490                     && (TREE_CODE (t) != TYPE_DECL
10491                         /* ... unless T is a member template; in which
10492                            case our caller can be willing to create a
10493                            specialization of that template represented
10494                            by T.  */
10495                         || !(DECL_TI_TEMPLATE (t)
10496                              && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t)))))
10497                   spec = t;
10498               }
10499
10500             if (!spec)
10501               {
10502                 tmpl = DECL_TI_TEMPLATE (t);
10503                 gen_tmpl = most_general_template (tmpl);
10504                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
10505                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
10506                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
10507               }
10508           }
10509         else
10510           {
10511             /* A local variable.  */
10512             local_p = true;
10513             /* Subsequent calls to pushdecl will fill this in.  */
10514             ctx = NULL_TREE;
10515             spec = retrieve_local_specialization (t);
10516           }
10517         /* If we already have the specialization we need, there is
10518            nothing more to do.  */ 
10519         if (spec)
10520           {
10521             r = spec;
10522             break;
10523           }
10524
10525         /* Create a new node for the specialization we need.  */
10526         r = copy_decl (t);
10527         if (type == NULL_TREE)
10528           {
10529             if (is_typedef_decl (t))
10530               type = DECL_ORIGINAL_TYPE (t);
10531             else
10532               type = TREE_TYPE (t);
10533             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
10534               type = strip_array_domain (type);
10535             type = tsubst (type, args, complain, in_decl);
10536           }
10537         if (TREE_CODE (r) == VAR_DECL)
10538           {
10539             /* Even if the original location is out of scope, the
10540                newly substituted one is not.  */
10541             DECL_DEAD_FOR_LOCAL (r) = 0;
10542             DECL_INITIALIZED_P (r) = 0;
10543             DECL_TEMPLATE_INSTANTIATED (r) = 0;
10544             if (type == error_mark_node)
10545               RETURN (error_mark_node);
10546             if (TREE_CODE (type) == FUNCTION_TYPE)
10547               {
10548                 /* It may seem that this case cannot occur, since:
10549
10550                      typedef void f();
10551                      void g() { f x; }
10552
10553                    declares a function, not a variable.  However:
10554       
10555                      typedef void f();
10556                      template <typename T> void g() { T t; }
10557                      template void g<f>();
10558
10559                    is an attempt to declare a variable with function
10560                    type.  */
10561                 error ("variable %qD has function type",
10562                        /* R is not yet sufficiently initialized, so we
10563                           just use its name.  */
10564                        DECL_NAME (r));
10565                 RETURN (error_mark_node);
10566               }
10567             type = complete_type (type);
10568             /* Wait until cp_finish_decl to set this again, to handle
10569                circular dependency (template/instantiate6.C). */
10570             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
10571             type = check_var_type (DECL_NAME (r), type);
10572
10573             if (DECL_HAS_VALUE_EXPR_P (t))
10574               {
10575                 tree ve = DECL_VALUE_EXPR (t);
10576                 ve = tsubst_expr (ve, args, complain, in_decl,
10577                                   /*constant_expression_p=*/false);
10578                 if (REFERENCE_REF_P (ve))
10579                   {
10580                     gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
10581                     ve = TREE_OPERAND (ve, 0);
10582                   }
10583                 SET_DECL_VALUE_EXPR (r, ve);
10584               }
10585           }
10586         else if (DECL_SELF_REFERENCE_P (t))
10587           SET_DECL_SELF_REFERENCE_P (r);
10588         TREE_TYPE (r) = type;
10589         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10590         DECL_CONTEXT (r) = ctx;
10591         /* Clear out the mangled name and RTL for the instantiation.  */
10592         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10593         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10594           SET_DECL_RTL (r, NULL);
10595         /* The initializer must not be expanded until it is required;
10596            see [temp.inst].  */
10597         DECL_INITIAL (r) = NULL_TREE;
10598         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10599           SET_DECL_RTL (r, NULL);
10600         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
10601         if (TREE_CODE (r) == VAR_DECL)
10602           {
10603             /* Possibly limit visibility based on template args.  */
10604             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10605             if (DECL_VISIBILITY_SPECIFIED (t))
10606               {
10607                 DECL_VISIBILITY_SPECIFIED (r) = 0;
10608                 DECL_ATTRIBUTES (r)
10609                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10610               }
10611             determine_visibility (r);
10612           }
10613
10614         if (!local_p)
10615           {
10616             /* A static data member declaration is always marked
10617                external when it is declared in-class, even if an
10618                initializer is present.  We mimic the non-template
10619                processing here.  */
10620             DECL_EXTERNAL (r) = 1;
10621
10622             register_specialization (r, gen_tmpl, argvec, false, hash);
10623             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
10624             SET_DECL_IMPLICIT_INSTANTIATION (r);
10625           }
10626         else if (cp_unevaluated_operand)
10627           {
10628             /* We're substituting this var in a decltype outside of its
10629                scope, such as for a lambda return type.  Don't add it to
10630                local_specializations, do perform auto deduction.  */
10631             tree auto_node = type_uses_auto (type);
10632             if (auto_node)
10633               {
10634                 tree init
10635                   = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
10636                                  /*constant_expression_p=*/false);
10637                 init = resolve_nondeduced_context (init);
10638                 TREE_TYPE (r) = type
10639                   = do_auto_deduction (type, init, auto_node);
10640               }
10641           }
10642         else
10643           register_local_specialization (r, t);
10644
10645         DECL_CHAIN (r) = NULL_TREE;
10646
10647         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
10648                                         /*flags=*/0,
10649                                         args, complain, in_decl);
10650
10651         /* Preserve a typedef that names a type.  */
10652         if (is_typedef_decl (r))
10653           {
10654             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
10655             set_underlying_type (r);
10656           }
10657
10658         layout_decl (r, 0);
10659       }
10660       break;
10661
10662     default:
10663       gcc_unreachable ();
10664     }
10665 #undef RETURN
10666
10667  out:
10668   /* Restore the file and line information.  */
10669   input_location = saved_loc;
10670
10671   return r;
10672 }
10673
10674 /* Substitute into the ARG_TYPES of a function type.  */
10675
10676 static tree
10677 tsubst_arg_types (tree arg_types,
10678                   tree args,
10679                   tsubst_flags_t complain,
10680                   tree in_decl)
10681 {
10682   tree remaining_arg_types;
10683   tree type = NULL_TREE;
10684   int i = 1;
10685   tree expanded_args = NULL_TREE;
10686   tree default_arg;
10687
10688   if (!arg_types || arg_types == void_list_node)
10689     return arg_types;
10690
10691   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
10692                                           args, complain, in_decl);
10693   if (remaining_arg_types == error_mark_node)
10694     return error_mark_node;
10695
10696   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
10697     {
10698       /* For a pack expansion, perform substitution on the
10699          entire expression. Later on, we'll handle the arguments
10700          one-by-one.  */
10701       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
10702                                             args, complain, in_decl);
10703
10704       if (TREE_CODE (expanded_args) == TREE_VEC)
10705         /* So that we'll spin through the parameters, one by one.  */
10706         i = TREE_VEC_LENGTH (expanded_args);
10707       else
10708         {
10709           /* We only partially substituted into the parameter
10710              pack. Our type is TYPE_PACK_EXPANSION.  */
10711           type = expanded_args;
10712           expanded_args = NULL_TREE;
10713         }
10714     }
10715
10716   while (i > 0) {
10717     --i;
10718     
10719     if (expanded_args)
10720       type = TREE_VEC_ELT (expanded_args, i);
10721     else if (!type)
10722       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
10723
10724     if (type == error_mark_node)
10725       return error_mark_node;
10726     if (VOID_TYPE_P (type))
10727       {
10728         if (complain & tf_error)
10729           {
10730             error ("invalid parameter type %qT", type);
10731             if (in_decl)
10732               error ("in declaration %q+D", in_decl);
10733           }
10734         return error_mark_node;
10735     }
10736     
10737     /* Do array-to-pointer, function-to-pointer conversion, and ignore
10738        top-level qualifiers as required.  */
10739     type = cv_unqualified (type_decays_to (type));
10740
10741     /* We do not substitute into default arguments here.  The standard
10742        mandates that they be instantiated only when needed, which is
10743        done in build_over_call.  */
10744     default_arg = TREE_PURPOSE (arg_types);
10745
10746     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
10747       {
10748         /* We've instantiated a template before its default arguments
10749            have been parsed.  This can happen for a nested template
10750            class, and is not an error unless we require the default
10751            argument in a call of this function.  */
10752         remaining_arg_types = 
10753           tree_cons (default_arg, type, remaining_arg_types);
10754         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
10755                        remaining_arg_types);
10756       }
10757     else
10758       remaining_arg_types = 
10759         hash_tree_cons (default_arg, type, remaining_arg_types);
10760   }
10761         
10762   return remaining_arg_types;
10763 }
10764
10765 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
10766    *not* handle the exception-specification for FNTYPE, because the
10767    initial substitution of explicitly provided template parameters
10768    during argument deduction forbids substitution into the
10769    exception-specification:
10770
10771      [temp.deduct]
10772
10773      All references in the function type of the function template to  the
10774      corresponding template parameters are replaced by the specified tem-
10775      plate argument values.  If a substitution in a template parameter or
10776      in  the function type of the function template results in an invalid
10777      type, type deduction fails.  [Note: The equivalent  substitution  in
10778      exception specifications is done only when the function is instanti-
10779      ated, at which point a program is  ill-formed  if  the  substitution
10780      results in an invalid type.]  */
10781
10782 static tree
10783 tsubst_function_type (tree t,
10784                       tree args,
10785                       tsubst_flags_t complain,
10786                       tree in_decl)
10787 {
10788   tree return_type;
10789   tree arg_types;
10790   tree fntype;
10791
10792   /* The TYPE_CONTEXT is not used for function/method types.  */
10793   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
10794
10795   /* Substitute the return type.  */
10796   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10797   if (return_type == error_mark_node)
10798     return error_mark_node;
10799   /* The standard does not presently indicate that creation of a
10800      function type with an invalid return type is a deduction failure.
10801      However, that is clearly analogous to creating an array of "void"
10802      or a reference to a reference.  This is core issue #486.  */
10803   if (TREE_CODE (return_type) == ARRAY_TYPE
10804       || TREE_CODE (return_type) == FUNCTION_TYPE)
10805     {
10806       if (complain & tf_error)
10807         {
10808           if (TREE_CODE (return_type) == ARRAY_TYPE)
10809             error ("function returning an array");
10810           else
10811             error ("function returning a function");
10812         }
10813       return error_mark_node;
10814     }
10815
10816   /* Substitute the argument types.  */
10817   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
10818                                 complain, in_decl);
10819   if (arg_types == error_mark_node)
10820     return error_mark_node;
10821
10822   /* Construct a new type node and return it.  */
10823   if (TREE_CODE (t) == FUNCTION_TYPE)
10824     {
10825       fntype = build_function_type (return_type, arg_types);
10826       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
10827     }
10828   else
10829     {
10830       tree r = TREE_TYPE (TREE_VALUE (arg_types));
10831       if (! MAYBE_CLASS_TYPE_P (r))
10832         {
10833           /* [temp.deduct]
10834
10835              Type deduction may fail for any of the following
10836              reasons:
10837
10838              -- Attempting to create "pointer to member of T" when T
10839              is not a class type.  */
10840           if (complain & tf_error)
10841             error ("creating pointer to member function of non-class type %qT",
10842                       r);
10843           return error_mark_node;
10844         }
10845
10846       fntype = build_method_type_directly (r, return_type,
10847                                            TREE_CHAIN (arg_types));
10848     }
10849   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
10850
10851   return fntype;
10852 }
10853
10854 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
10855    ARGS into that specification, and return the substituted
10856    specification.  If there is no specification, return NULL_TREE.  */
10857
10858 static tree
10859 tsubst_exception_specification (tree fntype,
10860                                 tree args,
10861                                 tsubst_flags_t complain,
10862                                 tree in_decl,
10863                                 bool defer_ok)
10864 {
10865   tree specs;
10866   tree new_specs;
10867
10868   specs = TYPE_RAISES_EXCEPTIONS (fntype);
10869   new_specs = NULL_TREE;
10870   if (specs && TREE_PURPOSE (specs))
10871     {
10872       /* A noexcept-specifier.  */
10873       tree expr = TREE_PURPOSE (specs);
10874       if (expr == boolean_true_node || expr == boolean_false_node)
10875         new_specs = expr;
10876       else if (defer_ok)
10877         {
10878           /* Defer instantiation of noexcept-specifiers to avoid
10879              excessive instantiations (c++/49107).  */
10880           new_specs = make_node (DEFERRED_NOEXCEPT);
10881           if (DEFERRED_NOEXCEPT_SPEC_P (specs))
10882             {
10883               /* We already partially instantiated this member template,
10884                  so combine the new args with the old.  */
10885               DEFERRED_NOEXCEPT_PATTERN (new_specs)
10886                 = DEFERRED_NOEXCEPT_PATTERN (expr);
10887               DEFERRED_NOEXCEPT_ARGS (new_specs)
10888                 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
10889             }
10890           else
10891             {
10892               DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
10893               DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
10894             }
10895         }
10896       else
10897         new_specs = tsubst_copy_and_build
10898           (expr, args, complain, in_decl, /*function_p=*/false,
10899            /*integral_constant_expression_p=*/true);
10900       new_specs = build_noexcept_spec (new_specs, complain);
10901     }
10902   else if (specs)
10903     {
10904       if (! TREE_VALUE (specs))
10905         new_specs = specs;
10906       else
10907         while (specs)
10908           {
10909             tree spec;
10910             int i, len = 1;
10911             tree expanded_specs = NULL_TREE;
10912
10913             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
10914               {
10915                 /* Expand the pack expansion type.  */
10916                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
10917                                                        args, complain,
10918                                                        in_decl);
10919
10920                 if (expanded_specs == error_mark_node)
10921                   return error_mark_node;
10922                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
10923                   len = TREE_VEC_LENGTH (expanded_specs);
10924                 else
10925                   {
10926                     /* We're substituting into a member template, so
10927                        we got a TYPE_PACK_EXPANSION back.  Add that
10928                        expansion and move on.  */
10929                     gcc_assert (TREE_CODE (expanded_specs) 
10930                                 == TYPE_PACK_EXPANSION);
10931                     new_specs = add_exception_specifier (new_specs,
10932                                                          expanded_specs,
10933                                                          complain);
10934                     specs = TREE_CHAIN (specs);
10935                     continue;
10936                   }
10937               }
10938
10939             for (i = 0; i < len; ++i)
10940               {
10941                 if (expanded_specs)
10942                   spec = TREE_VEC_ELT (expanded_specs, i);
10943                 else
10944                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
10945                 if (spec == error_mark_node)
10946                   return spec;
10947                 new_specs = add_exception_specifier (new_specs, spec, 
10948                                                      complain);
10949               }
10950
10951             specs = TREE_CHAIN (specs);
10952           }
10953     }
10954   return new_specs;
10955 }
10956
10957 /* Take the tree structure T and replace template parameters used
10958    therein with the argument vector ARGS.  IN_DECL is an associated
10959    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
10960    Issue error and warning messages under control of COMPLAIN.  Note
10961    that we must be relatively non-tolerant of extensions here, in
10962    order to preserve conformance; if we allow substitutions that
10963    should not be allowed, we may allow argument deductions that should
10964    not succeed, and therefore report ambiguous overload situations
10965    where there are none.  In theory, we could allow the substitution,
10966    but indicate that it should have failed, and allow our caller to
10967    make sure that the right thing happens, but we don't try to do this
10968    yet.
10969
10970    This function is used for dealing with types, decls and the like;
10971    for expressions, use tsubst_expr or tsubst_copy.  */
10972
10973 tree
10974 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10975 {
10976   enum tree_code code;
10977   tree type, r = NULL_TREE;
10978
10979   if (t == NULL_TREE || t == error_mark_node
10980       || t == integer_type_node
10981       || t == void_type_node
10982       || t == char_type_node
10983       || t == unknown_type_node
10984       || TREE_CODE (t) == NAMESPACE_DECL
10985       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
10986     return t;
10987
10988   if (DECL_P (t))
10989     return tsubst_decl (t, args, complain);
10990
10991   if (args == NULL_TREE)
10992     return t;
10993
10994   code = TREE_CODE (t);
10995
10996   if (code == IDENTIFIER_NODE)
10997     type = IDENTIFIER_TYPE_VALUE (t);
10998   else
10999     type = TREE_TYPE (t);
11000
11001   gcc_assert (type != unknown_type_node);
11002
11003   /* Reuse typedefs.  We need to do this to handle dependent attributes,
11004      such as attribute aligned.  */
11005   if (TYPE_P (t)
11006       && typedef_variant_p (t))
11007     {
11008       tree decl = TYPE_NAME (t);
11009
11010       if (TYPE_DECL_ALIAS_P (decl)
11011           && DECL_LANG_SPECIFIC (decl)
11012           && DECL_TEMPLATE_INFO (decl)
11013           && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
11014         {
11015           /* DECL represents an alias template and we want to
11016              instantiate it.  Let's substitute our arguments for the
11017              template parameters into the declaration and get the
11018              resulting type.  */
11019           r = tsubst (decl, args, complain, decl);
11020         }
11021       else if (DECL_CLASS_SCOPE_P (decl)
11022                && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
11023                && uses_template_parms (DECL_CONTEXT (decl)))
11024         {
11025           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
11026           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
11027           r = retrieve_specialization (tmpl, gen_args, 0);
11028         }
11029       else if (DECL_FUNCTION_SCOPE_P (decl)
11030                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
11031                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
11032         r = retrieve_local_specialization (decl);
11033       else
11034         /* The typedef is from a non-template context.  */
11035         return t;
11036
11037       if (r)
11038         {
11039           r = TREE_TYPE (r);
11040           r = cp_build_qualified_type_real
11041             (r, cp_type_quals (t) | cp_type_quals (r),
11042              complain | tf_ignore_bad_quals);
11043           return r;
11044         }
11045       /* Else we must be instantiating the typedef, so fall through.  */
11046     }
11047
11048   if (type
11049       && code != TYPENAME_TYPE
11050       && code != TEMPLATE_TYPE_PARM
11051       && code != IDENTIFIER_NODE
11052       && code != FUNCTION_TYPE
11053       && code != METHOD_TYPE)
11054     type = tsubst (type, args, complain, in_decl);
11055   if (type == error_mark_node)
11056     return error_mark_node;
11057
11058   switch (code)
11059     {
11060     case RECORD_TYPE:
11061     case UNION_TYPE:
11062     case ENUMERAL_TYPE:
11063       return tsubst_aggr_type (t, args, complain, in_decl,
11064                                /*entering_scope=*/0);
11065
11066     case ERROR_MARK:
11067     case IDENTIFIER_NODE:
11068     case VOID_TYPE:
11069     case REAL_TYPE:
11070     case COMPLEX_TYPE:
11071     case VECTOR_TYPE:
11072     case BOOLEAN_TYPE:
11073     case NULLPTR_TYPE:
11074     case LANG_TYPE:
11075       return t;
11076
11077     case INTEGER_TYPE:
11078       if (t == integer_type_node)
11079         return t;
11080
11081       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
11082           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
11083         return t;
11084
11085       {
11086         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
11087
11088         max = tsubst_expr (omax, args, complain, in_decl,
11089                            /*integral_constant_expression_p=*/false);
11090
11091         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
11092            needed.  */
11093         if (TREE_CODE (max) == NOP_EXPR
11094             && TREE_SIDE_EFFECTS (omax)
11095             && !TREE_TYPE (max))
11096           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
11097
11098         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
11099            with TREE_SIDE_EFFECTS that indicates this is not an integral
11100            constant expression.  */
11101         if (processing_template_decl
11102             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
11103           {
11104             gcc_assert (TREE_CODE (max) == NOP_EXPR);
11105             TREE_SIDE_EFFECTS (max) = 1;
11106           }
11107
11108         return compute_array_index_type (NULL_TREE, max, complain);
11109       }
11110
11111     case TEMPLATE_TYPE_PARM:
11112     case TEMPLATE_TEMPLATE_PARM:
11113     case BOUND_TEMPLATE_TEMPLATE_PARM:
11114     case TEMPLATE_PARM_INDEX:
11115       {
11116         int idx;
11117         int level;
11118         int levels;
11119         tree arg = NULL_TREE;
11120
11121         r = NULL_TREE;
11122
11123         gcc_assert (TREE_VEC_LENGTH (args) > 0);
11124         template_parm_level_and_index (t, &level, &idx); 
11125
11126         levels = TMPL_ARGS_DEPTH (args);
11127         if (level <= levels)
11128           {
11129             arg = TMPL_ARG (args, level, idx);
11130
11131             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
11132               /* See through ARGUMENT_PACK_SELECT arguments. */
11133               arg = ARGUMENT_PACK_SELECT_ARG (arg);
11134           }
11135
11136         if (arg == error_mark_node)
11137           return error_mark_node;
11138         else if (arg != NULL_TREE)
11139           {
11140             if (ARGUMENT_PACK_P (arg))
11141               /* If ARG is an argument pack, we don't actually want to
11142                  perform a substitution here, because substitutions
11143                  for argument packs are only done
11144                  element-by-element. We can get to this point when
11145                  substituting the type of a non-type template
11146                  parameter pack, when that type actually contains
11147                  template parameter packs from an outer template, e.g.,
11148
11149                  template<typename... Types> struct A {
11150                    template<Types... Values> struct B { };
11151                  };  */
11152               return t;
11153
11154             if (code == TEMPLATE_TYPE_PARM)
11155               {
11156                 int quals;
11157                 gcc_assert (TYPE_P (arg));
11158
11159                 quals = cp_type_quals (arg) | cp_type_quals (t);
11160                   
11161                 return cp_build_qualified_type_real
11162                   (arg, quals, complain | tf_ignore_bad_quals);
11163               }
11164             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11165               {
11166                 /* We are processing a type constructed from a
11167                    template template parameter.  */
11168                 tree argvec = tsubst (TYPE_TI_ARGS (t),
11169                                       args, complain, in_decl);
11170                 if (argvec == error_mark_node)
11171                   return error_mark_node;
11172
11173                 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
11174                             || TREE_CODE (arg) == TEMPLATE_DECL
11175                             || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
11176
11177                 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
11178                   /* Consider this code:
11179
11180                         template <template <class> class Template>
11181                         struct Internal {
11182                         template <class Arg> using Bind = Template<Arg>;
11183                         };
11184
11185                         template <template <class> class Template, class Arg>
11186                         using Instantiate = Template<Arg>; //#0
11187
11188                         template <template <class> class Template,
11189                                   class Argument>
11190                         using Bind =
11191                           Instantiate<Internal<Template>::template Bind,
11192                                       Argument>; //#1
11193
11194                      When #1 is parsed, the
11195                      BOUND_TEMPLATE_TEMPLATE_PARM representing the
11196                      parameter `Template' in #0 matches the
11197                      UNBOUND_CLASS_TEMPLATE representing the argument
11198                      `Internal<Template>::template Bind'; We then want
11199                      to assemble the type `Bind<Argument>' that can't
11200                      be fully created right now, because
11201                      `Internal<Template>' not being complete, the Bind
11202                      template cannot be looked up in that context.  So
11203                      we need to "store" `Bind<Argument>' for later
11204                      when the context of Bind becomes complete.  Let's
11205                      store that in a TYPENAME_TYPE.  */
11206                   return make_typename_type (TYPE_CONTEXT (arg),
11207                                              build_nt (TEMPLATE_ID_EXPR,
11208                                                        TYPE_IDENTIFIER (arg),
11209                                                        argvec),
11210                                              typename_type,
11211                                              complain);
11212
11213                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
11214                    are resolving nested-types in the signature of a
11215                    member function templates.  Otherwise ARG is a
11216                    TEMPLATE_DECL and is the real template to be
11217                    instantiated.  */
11218                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
11219                   arg = TYPE_NAME (arg);
11220
11221                 r = lookup_template_class (arg,
11222                                            argvec, in_decl,
11223                                            DECL_CONTEXT (arg),
11224                                             /*entering_scope=*/0,
11225                                            complain);
11226                 return cp_build_qualified_type_real
11227                   (r, cp_type_quals (t), complain);
11228               }
11229             else
11230               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
11231               return convert_from_reference (unshare_expr (arg));
11232           }
11233
11234         if (level == 1)
11235           /* This can happen during the attempted tsubst'ing in
11236              unify.  This means that we don't yet have any information
11237              about the template parameter in question.  */
11238           return t;
11239
11240         /* If we get here, we must have been looking at a parm for a
11241            more deeply nested template.  Make a new version of this
11242            template parameter, but with a lower level.  */
11243         switch (code)
11244           {
11245           case TEMPLATE_TYPE_PARM:
11246           case TEMPLATE_TEMPLATE_PARM:
11247           case BOUND_TEMPLATE_TEMPLATE_PARM:
11248             if (cp_type_quals (t))
11249               {
11250                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
11251                 r = cp_build_qualified_type_real
11252                   (r, cp_type_quals (t),
11253                    complain | (code == TEMPLATE_TYPE_PARM
11254                                ? tf_ignore_bad_quals : 0));
11255               }
11256             else
11257               {
11258                 r = copy_type (t);
11259                 TEMPLATE_TYPE_PARM_INDEX (r)
11260                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
11261                                                 r, levels, args, complain);
11262                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
11263                 TYPE_MAIN_VARIANT (r) = r;
11264                 TYPE_POINTER_TO (r) = NULL_TREE;
11265                 TYPE_REFERENCE_TO (r) = NULL_TREE;
11266
11267                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
11268                   /* We have reduced the level of the template
11269                      template parameter, but not the levels of its
11270                      template parameters, so canonical_type_parameter
11271                      will not be able to find the canonical template
11272                      template parameter for this level. Thus, we
11273                      require structural equality checking to compare
11274                      TEMPLATE_TEMPLATE_PARMs. */
11275                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11276                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
11277                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11278                 else
11279                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
11280
11281                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11282                   {
11283                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
11284                                           complain, in_decl);
11285                     if (argvec == error_mark_node)
11286                       return error_mark_node;
11287
11288                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
11289                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
11290                   }
11291               }
11292             break;
11293
11294           case TEMPLATE_PARM_INDEX:
11295             r = reduce_template_parm_level (t, type, levels, args, complain);
11296             break;
11297
11298           default:
11299             gcc_unreachable ();
11300           }
11301
11302         return r;
11303       }
11304
11305     case TREE_LIST:
11306       {
11307         tree purpose, value, chain;
11308
11309         if (t == void_list_node)
11310           return t;
11311
11312         purpose = TREE_PURPOSE (t);
11313         if (purpose)
11314           {
11315             purpose = tsubst (purpose, args, complain, in_decl);
11316             if (purpose == error_mark_node)
11317               return error_mark_node;
11318           }
11319         value = TREE_VALUE (t);
11320         if (value)
11321           {
11322             value = tsubst (value, args, complain, in_decl);
11323             if (value == error_mark_node)
11324               return error_mark_node;
11325           }
11326         chain = TREE_CHAIN (t);
11327         if (chain && chain != void_type_node)
11328           {
11329             chain = tsubst (chain, args, complain, in_decl);
11330             if (chain == error_mark_node)
11331               return error_mark_node;
11332           }
11333         if (purpose == TREE_PURPOSE (t)
11334             && value == TREE_VALUE (t)
11335             && chain == TREE_CHAIN (t))
11336           return t;
11337         return hash_tree_cons (purpose, value, chain);
11338       }
11339
11340     case TREE_BINFO:
11341       /* We should never be tsubsting a binfo.  */
11342       gcc_unreachable ();
11343
11344     case TREE_VEC:
11345       /* A vector of template arguments.  */
11346       gcc_assert (!type);
11347       return tsubst_template_args (t, args, complain, in_decl);
11348
11349     case POINTER_TYPE:
11350     case REFERENCE_TYPE:
11351       {
11352         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
11353           return t;
11354
11355         /* [temp.deduct]
11356
11357            Type deduction may fail for any of the following
11358            reasons:
11359
11360            -- Attempting to create a pointer to reference type.
11361            -- Attempting to create a reference to a reference type or
11362               a reference to void.
11363
11364           Core issue 106 says that creating a reference to a reference
11365           during instantiation is no longer a cause for failure. We
11366           only enforce this check in strict C++98 mode.  */
11367         if ((TREE_CODE (type) == REFERENCE_TYPE
11368              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
11369             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
11370           {
11371             static location_t last_loc;
11372
11373             /* We keep track of the last time we issued this error
11374                message to avoid spewing a ton of messages during a
11375                single bad template instantiation.  */
11376             if (complain & tf_error
11377                 && last_loc != input_location)
11378               {
11379                 if (TREE_CODE (type) == VOID_TYPE)
11380                   error ("forming reference to void");
11381                else if (code == POINTER_TYPE)
11382                  error ("forming pointer to reference type %qT", type);
11383                else
11384                   error ("forming reference to reference type %qT", type);
11385                 last_loc = input_location;
11386               }
11387
11388             return error_mark_node;
11389           }
11390         else if (code == POINTER_TYPE)
11391           {
11392             r = build_pointer_type (type);
11393             if (TREE_CODE (type) == METHOD_TYPE)
11394               r = build_ptrmemfunc_type (r);
11395           }
11396         else if (TREE_CODE (type) == REFERENCE_TYPE)
11397           /* In C++0x, during template argument substitution, when there is an
11398              attempt to create a reference to a reference type, reference
11399              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
11400
11401              "If a template-argument for a template-parameter T names a type
11402              that is a reference to a type A, an attempt to create the type
11403              'lvalue reference to cv T' creates the type 'lvalue reference to
11404              A,' while an attempt to create the type type rvalue reference to
11405              cv T' creates the type T"
11406           */
11407           r = cp_build_reference_type
11408               (TREE_TYPE (type),
11409                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
11410         else
11411           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
11412         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
11413
11414         if (r != error_mark_node)
11415           /* Will this ever be needed for TYPE_..._TO values?  */
11416           layout_type (r);
11417
11418         return r;
11419       }
11420     case OFFSET_TYPE:
11421       {
11422         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
11423         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
11424           {
11425             /* [temp.deduct]
11426
11427                Type deduction may fail for any of the following
11428                reasons:
11429
11430                -- Attempting to create "pointer to member of T" when T
11431                   is not a class type.  */
11432             if (complain & tf_error)
11433               error ("creating pointer to member of non-class type %qT", r);
11434             return error_mark_node;
11435           }
11436         if (TREE_CODE (type) == REFERENCE_TYPE)
11437           {
11438             if (complain & tf_error)
11439               error ("creating pointer to member reference type %qT", type);
11440             return error_mark_node;
11441           }
11442         if (TREE_CODE (type) == VOID_TYPE)
11443           {
11444             if (complain & tf_error)
11445               error ("creating pointer to member of type void");
11446             return error_mark_node;
11447           }
11448         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
11449         if (TREE_CODE (type) == FUNCTION_TYPE)
11450           {
11451             /* The type of the implicit object parameter gets its
11452                cv-qualifiers from the FUNCTION_TYPE. */
11453             tree memptr;
11454             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
11455             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
11456             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
11457                                                  complain);
11458           }
11459         else
11460           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
11461                                                cp_type_quals (t),
11462                                                complain);
11463       }
11464     case FUNCTION_TYPE:
11465     case METHOD_TYPE:
11466       {
11467         tree fntype;
11468         tree specs;
11469         fntype = tsubst_function_type (t, args, complain, in_decl);
11470         if (fntype == error_mark_node)
11471           return error_mark_node;
11472
11473         /* Substitute the exception specification.  */
11474         specs = tsubst_exception_specification (t, args, complain,
11475                                                 in_decl, /*defer_ok*/true);
11476         if (specs == error_mark_node)
11477           return error_mark_node;
11478         if (specs)
11479           fntype = build_exception_variant (fntype, specs);
11480         return fntype;
11481       }
11482     case ARRAY_TYPE:
11483       {
11484         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
11485         if (domain == error_mark_node)
11486           return error_mark_node;
11487
11488         /* As an optimization, we avoid regenerating the array type if
11489            it will obviously be the same as T.  */
11490         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
11491           return t;
11492
11493         /* These checks should match the ones in grokdeclarator.
11494
11495            [temp.deduct]
11496
11497            The deduction may fail for any of the following reasons:
11498
11499            -- Attempting to create an array with an element type that
11500               is void, a function type, or a reference type, or [DR337]
11501               an abstract class type.  */
11502         if (TREE_CODE (type) == VOID_TYPE
11503             || TREE_CODE (type) == FUNCTION_TYPE
11504             || TREE_CODE (type) == REFERENCE_TYPE)
11505           {
11506             if (complain & tf_error)
11507               error ("creating array of %qT", type);
11508             return error_mark_node;
11509           }
11510         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
11511           {
11512             if (complain & tf_error)
11513               error ("creating array of %qT, which is an abstract class type",
11514                      type);
11515             return error_mark_node;
11516           }
11517
11518         r = build_cplus_array_type (type, domain);
11519
11520         if (TYPE_USER_ALIGN (t))
11521           {
11522             TYPE_ALIGN (r) = TYPE_ALIGN (t);
11523             TYPE_USER_ALIGN (r) = 1;
11524           }
11525
11526         return r;
11527       }
11528
11529     case TYPENAME_TYPE:
11530       {
11531         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11532                                      in_decl, /*entering_scope=*/1);
11533         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
11534                               complain, in_decl);
11535
11536         if (ctx == error_mark_node || f == error_mark_node)
11537           return error_mark_node;
11538
11539         if (!MAYBE_CLASS_TYPE_P (ctx))
11540           {
11541             if (complain & tf_error)
11542               error ("%qT is not a class, struct, or union type", ctx);
11543             return error_mark_node;
11544           }
11545         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
11546           {
11547             /* Normally, make_typename_type does not require that the CTX
11548                have complete type in order to allow things like:
11549
11550                  template <class T> struct S { typename S<T>::X Y; };
11551
11552                But, such constructs have already been resolved by this
11553                point, so here CTX really should have complete type, unless
11554                it's a partial instantiation.  */
11555             ctx = complete_type (ctx);
11556             if (!COMPLETE_TYPE_P (ctx))
11557               {
11558                 if (complain & tf_error)
11559                   cxx_incomplete_type_error (NULL_TREE, ctx);
11560                 return error_mark_node;
11561               }
11562           }
11563
11564         f = make_typename_type (ctx, f, typename_type,
11565                                 (complain & tf_error) | tf_keep_type_decl);
11566         if (f == error_mark_node)
11567           return f;
11568         if (TREE_CODE (f) == TYPE_DECL)
11569           {
11570             complain |= tf_ignore_bad_quals;
11571             f = TREE_TYPE (f);
11572           }
11573
11574         if (TREE_CODE (f) != TYPENAME_TYPE)
11575           {
11576             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
11577               {
11578                 if (complain & tf_error)
11579                   error ("%qT resolves to %qT, which is not an enumeration type",
11580                          t, f);
11581                 else
11582                   return error_mark_node;
11583               }
11584             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
11585               {
11586                 if (complain & tf_error)
11587                   error ("%qT resolves to %qT, which is is not a class type",
11588                          t, f);
11589                 else
11590                   return error_mark_node;
11591               }
11592           }
11593
11594         return cp_build_qualified_type_real
11595           (f, cp_type_quals (f) | cp_type_quals (t), complain);
11596       }
11597
11598     case UNBOUND_CLASS_TEMPLATE:
11599       {
11600         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11601                                      in_decl, /*entering_scope=*/1);
11602         tree name = TYPE_IDENTIFIER (t);
11603         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
11604
11605         if (ctx == error_mark_node || name == error_mark_node)
11606           return error_mark_node;
11607
11608         if (parm_list)
11609           parm_list = tsubst_template_parms (parm_list, args, complain);
11610         return make_unbound_class_template (ctx, name, parm_list, complain);
11611       }
11612
11613     case TYPEOF_TYPE:
11614       {
11615         tree type;
11616
11617         ++cp_unevaluated_operand;
11618         ++c_inhibit_evaluation_warnings;
11619
11620         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
11621                             complain, in_decl,
11622                             /*integral_constant_expression_p=*/false);
11623
11624         --cp_unevaluated_operand;
11625         --c_inhibit_evaluation_warnings;
11626
11627         type = finish_typeof (type);
11628         return cp_build_qualified_type_real (type,
11629                                              cp_type_quals (t)
11630                                              | cp_type_quals (type),
11631                                              complain);
11632       }
11633
11634     case DECLTYPE_TYPE:
11635       {
11636         tree type;
11637
11638         ++cp_unevaluated_operand;
11639         ++c_inhibit_evaluation_warnings;
11640
11641         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
11642                             complain, in_decl,
11643                             /*integral_constant_expression_p=*/false);
11644
11645         --cp_unevaluated_operand;
11646         --c_inhibit_evaluation_warnings;
11647
11648         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
11649           type = lambda_capture_field_type (type);
11650         else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
11651           type = lambda_proxy_type (type);
11652         else
11653           type = finish_decltype_type
11654             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t), complain);
11655         return cp_build_qualified_type_real (type,
11656                                              cp_type_quals (t)
11657                                              | cp_type_quals (type),
11658                                              complain);
11659       }
11660
11661     case UNDERLYING_TYPE:
11662       {
11663         tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
11664                             complain, in_decl);
11665         return finish_underlying_type (type);
11666       }
11667
11668     case TYPE_ARGUMENT_PACK:
11669     case NONTYPE_ARGUMENT_PACK:
11670       {
11671         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
11672         tree packed_out = 
11673           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
11674                                 args,
11675                                 complain,
11676                                 in_decl);
11677         SET_ARGUMENT_PACK_ARGS (r, packed_out);
11678
11679         /* For template nontype argument packs, also substitute into
11680            the type.  */
11681         if (code == NONTYPE_ARGUMENT_PACK)
11682           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
11683
11684         return r;
11685       }
11686       break;
11687
11688     case INTEGER_CST:
11689     case REAL_CST:
11690     case STRING_CST:
11691     case PLUS_EXPR:
11692     case MINUS_EXPR:
11693     case NEGATE_EXPR:
11694     case NOP_EXPR:
11695     case INDIRECT_REF:
11696     case ADDR_EXPR:
11697     case CALL_EXPR:
11698     case ARRAY_REF:
11699     case SCOPE_REF:
11700       /* We should use one of the expression tsubsts for these codes.  */
11701       gcc_unreachable ();
11702
11703     default:
11704       sorry ("use of %qs in template", tree_code_name [(int) code]);
11705       return error_mark_node;
11706     }
11707 }
11708
11709 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
11710    type of the expression on the left-hand side of the "." or "->"
11711    operator.  */
11712
11713 static tree
11714 tsubst_baselink (tree baselink, tree object_type,
11715                  tree args, tsubst_flags_t complain, tree in_decl)
11716 {
11717     tree name;
11718     tree qualifying_scope;
11719     tree fns;
11720     tree optype;
11721     tree template_args = 0;
11722     bool template_id_p = false;
11723
11724     /* A baselink indicates a function from a base class.  Both the
11725        BASELINK_ACCESS_BINFO and the base class referenced may
11726        indicate bases of the template class, rather than the
11727        instantiated class.  In addition, lookups that were not
11728        ambiguous before may be ambiguous now.  Therefore, we perform
11729        the lookup again.  */
11730     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
11731     qualifying_scope = tsubst (qualifying_scope, args,
11732                                complain, in_decl);
11733     fns = BASELINK_FUNCTIONS (baselink);
11734     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
11735     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11736       {
11737         template_id_p = true;
11738         template_args = TREE_OPERAND (fns, 1);
11739         fns = TREE_OPERAND (fns, 0);
11740         if (template_args)
11741           template_args = tsubst_template_args (template_args, args,
11742                                                 complain, in_decl);
11743       }
11744     name = DECL_NAME (get_first_fn (fns));
11745     if (IDENTIFIER_TYPENAME_P (name))
11746       name = mangle_conv_op_name_for_type (optype);
11747     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
11748     if (!baselink)
11749       return error_mark_node;
11750
11751     /* If lookup found a single function, mark it as used at this
11752        point.  (If it lookup found multiple functions the one selected
11753        later by overload resolution will be marked as used at that
11754        point.)  */
11755     if (BASELINK_P (baselink))
11756       fns = BASELINK_FUNCTIONS (baselink);
11757     if (!template_id_p && !really_overloaded_fn (fns))
11758       mark_used (OVL_CURRENT (fns));
11759
11760     /* Add back the template arguments, if present.  */
11761     if (BASELINK_P (baselink) && template_id_p)
11762       BASELINK_FUNCTIONS (baselink)
11763         = build_nt (TEMPLATE_ID_EXPR,
11764                     BASELINK_FUNCTIONS (baselink),
11765                     template_args);
11766     /* Update the conversion operator type.  */
11767     BASELINK_OPTYPE (baselink) = optype;
11768
11769     if (!object_type)
11770       object_type = current_class_type;
11771     return adjust_result_of_qualified_name_lookup (baselink,
11772                                                    qualifying_scope,
11773                                                    object_type);
11774 }
11775
11776 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
11777    true if the qualified-id will be a postfix-expression in-and-of
11778    itself; false if more of the postfix-expression follows the
11779    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
11780    of "&".  */
11781
11782 static tree
11783 tsubst_qualified_id (tree qualified_id, tree args,
11784                      tsubst_flags_t complain, tree in_decl,
11785                      bool done, bool address_p)
11786 {
11787   tree expr;
11788   tree scope;
11789   tree name;
11790   bool is_template;
11791   tree template_args;
11792
11793   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
11794
11795   /* Figure out what name to look up.  */
11796   name = TREE_OPERAND (qualified_id, 1);
11797   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
11798     {
11799       is_template = true;
11800       template_args = TREE_OPERAND (name, 1);
11801       if (template_args)
11802         template_args = tsubst_template_args (template_args, args,
11803                                               complain, in_decl);
11804       name = TREE_OPERAND (name, 0);
11805     }
11806   else
11807     {
11808       is_template = false;
11809       template_args = NULL_TREE;
11810     }
11811
11812   /* Substitute into the qualifying scope.  When there are no ARGS, we
11813      are just trying to simplify a non-dependent expression.  In that
11814      case the qualifying scope may be dependent, and, in any case,
11815      substituting will not help.  */
11816   scope = TREE_OPERAND (qualified_id, 0);
11817   if (args)
11818     {
11819       scope = tsubst (scope, args, complain, in_decl);
11820       expr = tsubst_copy (name, args, complain, in_decl);
11821     }
11822   else
11823     expr = name;
11824
11825   if (dependent_scope_p (scope))
11826     {
11827       if (is_template)
11828         expr = build_min_nt (TEMPLATE_ID_EXPR, expr, template_args);
11829       return build_qualified_name (NULL_TREE, scope, expr,
11830                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
11831     }
11832
11833   if (!BASELINK_P (name) && !DECL_P (expr))
11834     {
11835       if (TREE_CODE (expr) == BIT_NOT_EXPR)
11836         {
11837           /* A BIT_NOT_EXPR is used to represent a destructor.  */
11838           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
11839             {
11840               error ("qualifying type %qT does not match destructor name ~%qT",
11841                      scope, TREE_OPERAND (expr, 0));
11842               expr = error_mark_node;
11843             }
11844           else
11845             expr = lookup_qualified_name (scope, complete_dtor_identifier,
11846                                           /*is_type_p=*/0, false);
11847         }
11848       else
11849         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
11850       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
11851                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
11852         {
11853           if (complain & tf_error)
11854             {
11855               error ("dependent-name %qE is parsed as a non-type, but "
11856                      "instantiation yields a type", qualified_id);
11857               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
11858             }
11859           return error_mark_node;
11860         }
11861     }
11862
11863   if (DECL_P (expr))
11864     {
11865       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
11866                                            scope);
11867       /* Remember that there was a reference to this entity.  */
11868       mark_used (expr);
11869     }
11870
11871   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
11872     {
11873       if (complain & tf_error)
11874         qualified_name_lookup_error (scope,
11875                                      TREE_OPERAND (qualified_id, 1),
11876                                      expr, input_location);
11877       return error_mark_node;
11878     }
11879
11880   if (is_template)
11881     expr = lookup_template_function (expr, template_args);
11882
11883   if (expr == error_mark_node && complain & tf_error)
11884     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
11885                                  expr, input_location);
11886   else if (TYPE_P (scope))
11887     {
11888       expr = (adjust_result_of_qualified_name_lookup
11889               (expr, scope, current_class_type));
11890       expr = (finish_qualified_id_expr
11891               (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
11892                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
11893                /*template_arg_p=*/false));
11894     }
11895
11896   /* Expressions do not generally have reference type.  */
11897   if (TREE_CODE (expr) != SCOPE_REF
11898       /* However, if we're about to form a pointer-to-member, we just
11899          want the referenced member referenced.  */
11900       && TREE_CODE (expr) != OFFSET_REF)
11901     expr = convert_from_reference (expr);
11902
11903   return expr;
11904 }
11905
11906 /* Like tsubst, but deals with expressions.  This function just replaces
11907    template parms; to finish processing the resultant expression, use
11908    tsubst_copy_and_build or tsubst_expr.  */
11909
11910 static tree
11911 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11912 {
11913   enum tree_code code;
11914   tree r;
11915
11916   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
11917     return t;
11918
11919   code = TREE_CODE (t);
11920
11921   switch (code)
11922     {
11923     case PARM_DECL:
11924       r = retrieve_local_specialization (t);
11925
11926       if (r == NULL)
11927         {
11928           tree c;
11929
11930           /* We get here for a use of 'this' in an NSDMI.  */
11931           if (DECL_NAME (t) == this_identifier
11932               && at_function_scope_p ()
11933               && DECL_CONSTRUCTOR_P (current_function_decl))
11934             return current_class_ptr;
11935
11936           /* This can happen for a parameter name used later in a function
11937              declaration (such as in a late-specified return type).  Just
11938              make a dummy decl, since it's only used for its type.  */
11939           gcc_assert (cp_unevaluated_operand != 0);
11940           /* We copy T because want to tsubst the PARM_DECL only,
11941              not the following PARM_DECLs that are chained to T.  */
11942           c = copy_node (t);
11943           r = tsubst_decl (c, args, complain);
11944           /* Give it the template pattern as its context; its true context
11945              hasn't been instantiated yet and this is good enough for
11946              mangling.  */
11947           DECL_CONTEXT (r) = DECL_CONTEXT (t);
11948         }
11949       
11950       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
11951         r = ARGUMENT_PACK_SELECT_ARG (r);
11952       mark_used (r);
11953       return r;
11954
11955     case CONST_DECL:
11956       {
11957         tree enum_type;
11958         tree v;
11959
11960         if (DECL_TEMPLATE_PARM_P (t))
11961           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
11962         /* There is no need to substitute into namespace-scope
11963            enumerators.  */
11964         if (DECL_NAMESPACE_SCOPE_P (t))
11965           return t;
11966         /* If ARGS is NULL, then T is known to be non-dependent.  */
11967         if (args == NULL_TREE)
11968           return integral_constant_value (t);
11969
11970         /* Unfortunately, we cannot just call lookup_name here.
11971            Consider:
11972
11973              template <int I> int f() {
11974              enum E { a = I };
11975              struct S { void g() { E e = a; } };
11976              };
11977
11978            When we instantiate f<7>::S::g(), say, lookup_name is not
11979            clever enough to find f<7>::a.  */
11980         enum_type
11981           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
11982                               /*entering_scope=*/0);
11983
11984         for (v = TYPE_VALUES (enum_type);
11985              v != NULL_TREE;
11986              v = TREE_CHAIN (v))
11987           if (TREE_PURPOSE (v) == DECL_NAME (t))
11988             return TREE_VALUE (v);
11989
11990           /* We didn't find the name.  That should never happen; if
11991              name-lookup found it during preliminary parsing, we
11992              should find it again here during instantiation.  */
11993         gcc_unreachable ();
11994       }
11995       return t;
11996
11997     case FIELD_DECL:
11998       if (DECL_CONTEXT (t))
11999         {
12000           tree ctx;
12001
12002           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
12003                                   /*entering_scope=*/1);
12004           if (ctx != DECL_CONTEXT (t))
12005             {
12006               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
12007               if (!r)
12008                 {
12009                   if (complain & tf_error)
12010                     error ("using invalid field %qD", t);
12011                   return error_mark_node;
12012                 }
12013               return r;
12014             }
12015         }
12016
12017       return t;
12018
12019     case VAR_DECL:
12020     case FUNCTION_DECL:
12021       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
12022           || local_variable_p (t))
12023         t = tsubst (t, args, complain, in_decl);
12024       mark_used (t);
12025       return t;
12026
12027     case NAMESPACE_DECL:
12028       return t;
12029
12030     case OVERLOAD:
12031       /* An OVERLOAD will always be a non-dependent overload set; an
12032          overload set from function scope will just be represented with an
12033          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
12034       gcc_assert (!uses_template_parms (t));
12035       return t;
12036
12037     case BASELINK:
12038       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
12039
12040     case TEMPLATE_DECL:
12041       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12042         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
12043                        args, complain, in_decl);
12044       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
12045         return tsubst (t, args, complain, in_decl);
12046       else if (DECL_CLASS_SCOPE_P (t)
12047                && uses_template_parms (DECL_CONTEXT (t)))
12048         {
12049           /* Template template argument like the following example need
12050              special treatment:
12051
12052                template <template <class> class TT> struct C {};
12053                template <class T> struct D {
12054                  template <class U> struct E {};
12055                  C<E> c;                                // #1
12056                };
12057                D<int> d;                                // #2
12058
12059              We are processing the template argument `E' in #1 for
12060              the template instantiation #2.  Originally, `E' is a
12061              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
12062              have to substitute this with one having context `D<int>'.  */
12063
12064           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
12065           return lookup_field (context, DECL_NAME(t), 0, false);
12066         }
12067       else
12068         /* Ordinary template template argument.  */
12069         return t;
12070
12071     case CAST_EXPR:
12072     case REINTERPRET_CAST_EXPR:
12073     case CONST_CAST_EXPR:
12074     case STATIC_CAST_EXPR:
12075     case DYNAMIC_CAST_EXPR:
12076     case IMPLICIT_CONV_EXPR:
12077     case CONVERT_EXPR:
12078     case NOP_EXPR:
12079       return build1
12080         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
12081          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
12082
12083     case SIZEOF_EXPR:
12084       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12085         {
12086
12087           tree expanded;
12088           int len = 0;
12089
12090           ++cp_unevaluated_operand;
12091           ++c_inhibit_evaluation_warnings;
12092           /* We only want to compute the number of arguments.  */
12093           expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
12094                                             complain, in_decl);
12095           --cp_unevaluated_operand;
12096           --c_inhibit_evaluation_warnings;
12097
12098           if (TREE_CODE (expanded) == TREE_VEC)
12099             len = TREE_VEC_LENGTH (expanded);
12100
12101           if (expanded == error_mark_node)
12102             return error_mark_node;
12103           else if (PACK_EXPANSION_P (expanded)
12104                    || (TREE_CODE (expanded) == TREE_VEC
12105                        && len > 0
12106                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
12107             {
12108               if (TREE_CODE (expanded) == TREE_VEC)
12109                 expanded = TREE_VEC_ELT (expanded, len - 1);
12110
12111               if (TYPE_P (expanded))
12112                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
12113                                                    complain & tf_error);
12114               else
12115                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
12116                                                    complain & tf_error);
12117             }
12118           else
12119             return build_int_cst (size_type_node, len);
12120         }
12121       /* Fall through */
12122
12123     case INDIRECT_REF:
12124     case NEGATE_EXPR:
12125     case TRUTH_NOT_EXPR:
12126     case BIT_NOT_EXPR:
12127     case ADDR_EXPR:
12128     case UNARY_PLUS_EXPR:      /* Unary + */
12129     case ALIGNOF_EXPR:
12130     case AT_ENCODE_EXPR:
12131     case ARROW_EXPR:
12132     case THROW_EXPR:
12133     case TYPEID_EXPR:
12134     case REALPART_EXPR:
12135     case IMAGPART_EXPR:
12136       return build1
12137         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
12138          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
12139
12140     case COMPONENT_REF:
12141       {
12142         tree object;
12143         tree name;
12144
12145         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
12146         name = TREE_OPERAND (t, 1);
12147         if (TREE_CODE (name) == BIT_NOT_EXPR)
12148           {
12149             name = tsubst_copy (TREE_OPERAND (name, 0), args,
12150                                 complain, in_decl);
12151             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
12152           }
12153         else if (TREE_CODE (name) == SCOPE_REF
12154                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
12155           {
12156             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
12157                                      complain, in_decl);
12158             name = TREE_OPERAND (name, 1);
12159             name = tsubst_copy (TREE_OPERAND (name, 0), args,
12160                                 complain, in_decl);
12161             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
12162             name = build_qualified_name (/*type=*/NULL_TREE,
12163                                          base, name,
12164                                          /*template_p=*/false);
12165           }
12166         else if (BASELINK_P (name))
12167           name = tsubst_baselink (name,
12168                                   non_reference (TREE_TYPE (object)),
12169                                   args, complain,
12170                                   in_decl);
12171         else
12172           name = tsubst_copy (name, args, complain, in_decl);
12173         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
12174       }
12175
12176     case PLUS_EXPR:
12177     case MINUS_EXPR:
12178     case MULT_EXPR:
12179     case TRUNC_DIV_EXPR:
12180     case CEIL_DIV_EXPR:
12181     case FLOOR_DIV_EXPR:
12182     case ROUND_DIV_EXPR:
12183     case EXACT_DIV_EXPR:
12184     case BIT_AND_EXPR:
12185     case BIT_IOR_EXPR:
12186     case BIT_XOR_EXPR:
12187     case TRUNC_MOD_EXPR:
12188     case FLOOR_MOD_EXPR:
12189     case TRUTH_ANDIF_EXPR:
12190     case TRUTH_ORIF_EXPR:
12191     case TRUTH_AND_EXPR:
12192     case TRUTH_OR_EXPR:
12193     case RSHIFT_EXPR:
12194     case LSHIFT_EXPR:
12195     case RROTATE_EXPR:
12196     case LROTATE_EXPR:
12197     case EQ_EXPR:
12198     case NE_EXPR:
12199     case MAX_EXPR:
12200     case MIN_EXPR:
12201     case LE_EXPR:
12202     case GE_EXPR:
12203     case LT_EXPR:
12204     case GT_EXPR:
12205     case COMPOUND_EXPR:
12206     case DOTSTAR_EXPR:
12207     case MEMBER_REF:
12208     case PREDECREMENT_EXPR:
12209     case PREINCREMENT_EXPR:
12210     case POSTDECREMENT_EXPR:
12211     case POSTINCREMENT_EXPR:
12212       return build_nt
12213         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12214          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12215
12216     case SCOPE_REF:
12217       return build_qualified_name (/*type=*/NULL_TREE,
12218                                    tsubst_copy (TREE_OPERAND (t, 0),
12219                                                 args, complain, in_decl),
12220                                    tsubst_copy (TREE_OPERAND (t, 1),
12221                                                 args, complain, in_decl),
12222                                    QUALIFIED_NAME_IS_TEMPLATE (t));
12223
12224     case ARRAY_REF:
12225       return build_nt
12226         (ARRAY_REF,
12227          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12228          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12229          NULL_TREE, NULL_TREE);
12230
12231     case CALL_EXPR:
12232       {
12233         int n = VL_EXP_OPERAND_LENGTH (t);
12234         tree result = build_vl_exp (CALL_EXPR, n);
12235         int i;
12236         for (i = 0; i < n; i++)
12237           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
12238                                              complain, in_decl);
12239         return result;
12240       }
12241
12242     case COND_EXPR:
12243     case MODOP_EXPR:
12244     case PSEUDO_DTOR_EXPR:
12245       {
12246         r = build_nt
12247           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12248            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12249            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12250         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12251         return r;
12252       }
12253
12254     case NEW_EXPR:
12255       {
12256         r = build_nt
12257         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12258          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12259          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12260         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
12261         return r;
12262       }
12263
12264     case DELETE_EXPR:
12265       {
12266         r = build_nt
12267         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12268          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12269         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
12270         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
12271         return r;
12272       }
12273
12274     case TEMPLATE_ID_EXPR:
12275       {
12276         /* Substituted template arguments */
12277         tree fn = TREE_OPERAND (t, 0);
12278         tree targs = TREE_OPERAND (t, 1);
12279
12280         fn = tsubst_copy (fn, args, complain, in_decl);
12281         if (targs)
12282           targs = tsubst_template_args (targs, args, complain, in_decl);
12283
12284         return lookup_template_function (fn, targs);
12285       }
12286
12287     case TREE_LIST:
12288       {
12289         tree purpose, value, chain;
12290
12291         if (t == void_list_node)
12292           return t;
12293
12294         purpose = TREE_PURPOSE (t);
12295         if (purpose)
12296           purpose = tsubst_copy (purpose, args, complain, in_decl);
12297         value = TREE_VALUE (t);
12298         if (value)
12299           value = tsubst_copy (value, args, complain, in_decl);
12300         chain = TREE_CHAIN (t);
12301         if (chain && chain != void_type_node)
12302           chain = tsubst_copy (chain, args, complain, in_decl);
12303         if (purpose == TREE_PURPOSE (t)
12304             && value == TREE_VALUE (t)
12305             && chain == TREE_CHAIN (t))
12306           return t;
12307         return tree_cons (purpose, value, chain);
12308       }
12309
12310     case RECORD_TYPE:
12311     case UNION_TYPE:
12312     case ENUMERAL_TYPE:
12313     case INTEGER_TYPE:
12314     case TEMPLATE_TYPE_PARM:
12315     case TEMPLATE_TEMPLATE_PARM:
12316     case BOUND_TEMPLATE_TEMPLATE_PARM:
12317     case TEMPLATE_PARM_INDEX:
12318     case POINTER_TYPE:
12319     case REFERENCE_TYPE:
12320     case OFFSET_TYPE:
12321     case FUNCTION_TYPE:
12322     case METHOD_TYPE:
12323     case ARRAY_TYPE:
12324     case TYPENAME_TYPE:
12325     case UNBOUND_CLASS_TEMPLATE:
12326     case TYPEOF_TYPE:
12327     case DECLTYPE_TYPE:
12328     case TYPE_DECL:
12329       return tsubst (t, args, complain, in_decl);
12330
12331     case IDENTIFIER_NODE:
12332       if (IDENTIFIER_TYPENAME_P (t))
12333         {
12334           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12335           return mangle_conv_op_name_for_type (new_type);
12336         }
12337       else
12338         return t;
12339
12340     case CONSTRUCTOR:
12341       /* This is handled by tsubst_copy_and_build.  */
12342       gcc_unreachable ();
12343
12344     case VA_ARG_EXPR:
12345       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
12346                                           in_decl),
12347                              tsubst (TREE_TYPE (t), args, complain, in_decl));
12348
12349     case CLEANUP_POINT_EXPR:
12350       /* We shouldn't have built any of these during initial template
12351          generation.  Instead, they should be built during instantiation
12352          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
12353       gcc_unreachable ();
12354
12355     case OFFSET_REF:
12356       r = build2
12357         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
12358          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12359          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12360       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
12361       mark_used (TREE_OPERAND (r, 1));
12362       return r;
12363
12364     case EXPR_PACK_EXPANSION:
12365       error ("invalid use of pack expansion expression");
12366       return error_mark_node;
12367
12368     case NONTYPE_ARGUMENT_PACK:
12369       error ("use %<...%> to expand argument pack");
12370       return error_mark_node;
12371
12372     case INTEGER_CST:
12373     case REAL_CST:
12374     case STRING_CST:
12375     case COMPLEX_CST:
12376       {
12377         /* Instantiate any typedefs in the type.  */
12378         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12379         r = fold_convert (type, t);
12380         gcc_assert (TREE_CODE (r) == code);
12381         return r;
12382       }
12383
12384     case PTRMEM_CST:
12385       /* These can sometimes show up in a partial instantiation, but never
12386          involve template parms.  */
12387       gcc_assert (!uses_template_parms (t));
12388       return t;
12389
12390     default:
12391       /* We shouldn't get here, but keep going if !ENABLE_CHECKING.  */
12392       gcc_checking_assert (false);
12393       return t;
12394     }
12395 }
12396
12397 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
12398
12399 static tree
12400 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
12401                     tree in_decl)
12402 {
12403   tree new_clauses = NULL, nc, oc;
12404
12405   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
12406     {
12407       nc = copy_node (oc);
12408       OMP_CLAUSE_CHAIN (nc) = new_clauses;
12409       new_clauses = nc;
12410
12411       switch (OMP_CLAUSE_CODE (nc))
12412         {
12413         case OMP_CLAUSE_LASTPRIVATE:
12414           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
12415             {
12416               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
12417               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
12418                            in_decl, /*integral_constant_expression_p=*/false);
12419               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
12420                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
12421             }
12422           /* FALLTHRU */
12423         case OMP_CLAUSE_PRIVATE:
12424         case OMP_CLAUSE_SHARED:
12425         case OMP_CLAUSE_FIRSTPRIVATE:
12426         case OMP_CLAUSE_REDUCTION:
12427         case OMP_CLAUSE_COPYIN:
12428         case OMP_CLAUSE_COPYPRIVATE:
12429         case OMP_CLAUSE_IF:
12430         case OMP_CLAUSE_NUM_THREADS:
12431         case OMP_CLAUSE_SCHEDULE:
12432         case OMP_CLAUSE_COLLAPSE:
12433         case OMP_CLAUSE_FINAL:
12434           OMP_CLAUSE_OPERAND (nc, 0)
12435             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
12436                            in_decl, /*integral_constant_expression_p=*/false);
12437           break;
12438         case OMP_CLAUSE_NOWAIT:
12439         case OMP_CLAUSE_ORDERED:
12440         case OMP_CLAUSE_DEFAULT:
12441         case OMP_CLAUSE_UNTIED:
12442         case OMP_CLAUSE_MERGEABLE:
12443           break;
12444         default:
12445           gcc_unreachable ();
12446         }
12447     }
12448
12449   return finish_omp_clauses (nreverse (new_clauses));
12450 }
12451
12452 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
12453
12454 static tree
12455 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
12456                           tree in_decl)
12457 {
12458 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
12459
12460   tree purpose, value, chain;
12461
12462   if (t == NULL)
12463     return t;
12464
12465   if (TREE_CODE (t) != TREE_LIST)
12466     return tsubst_copy_and_build (t, args, complain, in_decl,
12467                                   /*function_p=*/false,
12468                                   /*integral_constant_expression_p=*/false);
12469
12470   if (t == void_list_node)
12471     return t;
12472
12473   purpose = TREE_PURPOSE (t);
12474   if (purpose)
12475     purpose = RECUR (purpose);
12476   value = TREE_VALUE (t);
12477   if (value && TREE_CODE (value) != LABEL_DECL)
12478     value = RECUR (value);
12479   chain = TREE_CHAIN (t);
12480   if (chain && chain != void_type_node)
12481     chain = RECUR (chain);
12482   return tree_cons (purpose, value, chain);
12483 #undef RECUR
12484 }
12485
12486 /* Substitute one OMP_FOR iterator.  */
12487
12488 static void
12489 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
12490                          tree condv, tree incrv, tree *clauses,
12491                          tree args, tsubst_flags_t complain, tree in_decl,
12492                          bool integral_constant_expression_p)
12493 {
12494 #define RECUR(NODE)                             \
12495   tsubst_expr ((NODE), args, complain, in_decl, \
12496                integral_constant_expression_p)
12497   tree decl, init, cond, incr, auto_node;
12498
12499   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
12500   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
12501   decl = RECUR (TREE_OPERAND (init, 0));
12502   init = TREE_OPERAND (init, 1);
12503   auto_node = type_uses_auto (TREE_TYPE (decl));
12504   if (auto_node && init)
12505     {
12506       tree init_expr = init;
12507       if (TREE_CODE (init_expr) == DECL_EXPR)
12508         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
12509       init_expr = RECUR (init_expr);
12510       TREE_TYPE (decl)
12511         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
12512     }
12513   gcc_assert (!type_dependent_expression_p (decl));
12514
12515   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
12516     {
12517       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
12518       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12519       if (TREE_CODE (incr) == MODIFY_EXPR)
12520         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
12521                                     RECUR (TREE_OPERAND (incr, 1)),
12522                                     complain);
12523       else
12524         incr = RECUR (incr);
12525       TREE_VEC_ELT (declv, i) = decl;
12526       TREE_VEC_ELT (initv, i) = init;
12527       TREE_VEC_ELT (condv, i) = cond;
12528       TREE_VEC_ELT (incrv, i) = incr;
12529       return;
12530     }
12531
12532   if (init && TREE_CODE (init) != DECL_EXPR)
12533     {
12534       tree c;
12535       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
12536         {
12537           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
12538                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
12539               && OMP_CLAUSE_DECL (c) == decl)
12540             break;
12541           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
12542                    && OMP_CLAUSE_DECL (c) == decl)
12543             error ("iteration variable %qD should not be firstprivate", decl);
12544           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
12545                    && OMP_CLAUSE_DECL (c) == decl)
12546             error ("iteration variable %qD should not be reduction", decl);
12547         }
12548       if (c == NULL)
12549         {
12550           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
12551           OMP_CLAUSE_DECL (c) = decl;
12552           c = finish_omp_clauses (c);
12553           if (c)
12554             {
12555               OMP_CLAUSE_CHAIN (c) = *clauses;
12556               *clauses = c;
12557             }
12558         }
12559     }
12560   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
12561   if (COMPARISON_CLASS_P (cond))
12562     cond = build2 (TREE_CODE (cond), boolean_type_node,
12563                    RECUR (TREE_OPERAND (cond, 0)),
12564                    RECUR (TREE_OPERAND (cond, 1)));
12565   else
12566     cond = RECUR (cond);
12567   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12568   switch (TREE_CODE (incr))
12569     {
12570     case PREINCREMENT_EXPR:
12571     case PREDECREMENT_EXPR:
12572     case POSTINCREMENT_EXPR:
12573     case POSTDECREMENT_EXPR:
12574       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
12575                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
12576       break;
12577     case MODIFY_EXPR:
12578       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12579           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12580         {
12581           tree rhs = TREE_OPERAND (incr, 1);
12582           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12583                          RECUR (TREE_OPERAND (incr, 0)),
12584                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12585                                  RECUR (TREE_OPERAND (rhs, 0)),
12586                                  RECUR (TREE_OPERAND (rhs, 1))));
12587         }
12588       else
12589         incr = RECUR (incr);
12590       break;
12591     case MODOP_EXPR:
12592       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12593           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12594         {
12595           tree lhs = RECUR (TREE_OPERAND (incr, 0));
12596           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
12597                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
12598                                  TREE_TYPE (decl), lhs,
12599                                  RECUR (TREE_OPERAND (incr, 2))));
12600         }
12601       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
12602                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
12603                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
12604         {
12605           tree rhs = TREE_OPERAND (incr, 2);
12606           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12607                          RECUR (TREE_OPERAND (incr, 0)),
12608                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12609                                  RECUR (TREE_OPERAND (rhs, 0)),
12610                                  RECUR (TREE_OPERAND (rhs, 1))));
12611         }
12612       else
12613         incr = RECUR (incr);
12614       break;
12615     default:
12616       incr = RECUR (incr);
12617       break;
12618     }
12619
12620   TREE_VEC_ELT (declv, i) = decl;
12621   TREE_VEC_ELT (initv, i) = init;
12622   TREE_VEC_ELT (condv, i) = cond;
12623   TREE_VEC_ELT (incrv, i) = incr;
12624 #undef RECUR
12625 }
12626
12627 /* Like tsubst_copy for expressions, etc. but also does semantic
12628    processing.  */
12629
12630 static tree
12631 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
12632              bool integral_constant_expression_p)
12633 {
12634 #define RECUR(NODE)                             \
12635   tsubst_expr ((NODE), args, complain, in_decl, \
12636                integral_constant_expression_p)
12637
12638   tree stmt, tmp;
12639
12640   if (t == NULL_TREE || t == error_mark_node)
12641     return t;
12642
12643   if (EXPR_HAS_LOCATION (t))
12644     input_location = EXPR_LOCATION (t);
12645   if (STATEMENT_CODE_P (TREE_CODE (t)))
12646     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
12647
12648   switch (TREE_CODE (t))
12649     {
12650     case STATEMENT_LIST:
12651       {
12652         tree_stmt_iterator i;
12653         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
12654           RECUR (tsi_stmt (i));
12655         break;
12656       }
12657
12658     case CTOR_INITIALIZER:
12659       finish_mem_initializers (tsubst_initializer_list
12660                                (TREE_OPERAND (t, 0), args));
12661       break;
12662
12663     case RETURN_EXPR:
12664       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
12665       break;
12666
12667     case EXPR_STMT:
12668       tmp = RECUR (EXPR_STMT_EXPR (t));
12669       if (EXPR_STMT_STMT_EXPR_RESULT (t))
12670         finish_stmt_expr_expr (tmp, cur_stmt_expr);
12671       else
12672         finish_expr_stmt (tmp);
12673       break;
12674
12675     case USING_STMT:
12676       do_using_directive (USING_STMT_NAMESPACE (t));
12677       break;
12678
12679     case DECL_EXPR:
12680       {
12681         tree decl, pattern_decl;
12682         tree init;
12683
12684         pattern_decl = decl = DECL_EXPR_DECL (t);
12685         if (TREE_CODE (decl) == LABEL_DECL)
12686           finish_label_decl (DECL_NAME (decl));
12687         else if (TREE_CODE (decl) == USING_DECL)
12688           {
12689             tree scope = USING_DECL_SCOPE (decl);
12690             tree name = DECL_NAME (decl);
12691             tree decl;
12692
12693             scope = tsubst (scope, args, complain, in_decl);
12694             decl = lookup_qualified_name (scope, name,
12695                                           /*is_type_p=*/false,
12696                                           /*complain=*/false);
12697             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
12698               qualified_name_lookup_error (scope, name, decl, input_location);
12699             else
12700               do_local_using_decl (decl, scope, name);
12701           }
12702         else
12703           {
12704             init = DECL_INITIAL (decl);
12705             decl = tsubst (decl, args, complain, in_decl);
12706             if (decl != error_mark_node)
12707               {
12708                 /* By marking the declaration as instantiated, we avoid
12709                    trying to instantiate it.  Since instantiate_decl can't
12710                    handle local variables, and since we've already done
12711                    all that needs to be done, that's the right thing to
12712                    do.  */
12713                 if (TREE_CODE (decl) == VAR_DECL)
12714                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12715                 if (TREE_CODE (decl) == VAR_DECL
12716                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12717                   /* Anonymous aggregates are a special case.  */
12718                   finish_anon_union (decl);
12719                 else
12720                   {
12721                     int const_init = false;
12722                     maybe_push_decl (decl);
12723                     if (TREE_CODE (decl) == VAR_DECL
12724                         && DECL_PRETTY_FUNCTION_P (decl))
12725                       {
12726                         /* For __PRETTY_FUNCTION__ we have to adjust the
12727                            initializer.  */
12728                         const char *const name
12729                           = cxx_printable_name (current_function_decl, 2);
12730                         init = cp_fname_init (name, &TREE_TYPE (decl));
12731                       }
12732                     else
12733                       {
12734                         tree t = RECUR (init);
12735
12736                         if (init && !t)
12737                           {
12738                             /* If we had an initializer but it
12739                                instantiated to nothing,
12740                                value-initialize the object.  This will
12741                                only occur when the initializer was a
12742                                pack expansion where the parameter packs
12743                                used in that expansion were of length
12744                                zero.  */
12745                             init = build_value_init (TREE_TYPE (decl),
12746                                                      complain);
12747                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
12748                               init = get_target_expr_sfinae (init, complain);
12749                           }
12750                         else
12751                           init = t;
12752                       }
12753
12754                     if (TREE_CODE (decl) == VAR_DECL)
12755                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
12756                                     (pattern_decl));
12757                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
12758                   }
12759               }
12760           }
12761
12762         /* A DECL_EXPR can also be used as an expression, in the condition
12763            clause of an if/for/while construct.  */
12764         return decl;
12765       }
12766
12767     case FOR_STMT:
12768       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12769       RECUR (FOR_INIT_STMT (t));
12770       finish_for_init_stmt (stmt);
12771       tmp = RECUR (FOR_COND (t));
12772       finish_for_cond (tmp, stmt);
12773       tmp = RECUR (FOR_EXPR (t));
12774       finish_for_expr (tmp, stmt);
12775       RECUR (FOR_BODY (t));
12776       finish_for_stmt (stmt);
12777       break;
12778
12779     case RANGE_FOR_STMT:
12780       {
12781         tree decl, expr;
12782         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12783         decl = RANGE_FOR_DECL (t);
12784         decl = tsubst (decl, args, complain, in_decl);
12785         maybe_push_decl (decl);
12786         expr = RECUR (RANGE_FOR_EXPR (t));
12787         stmt = cp_convert_range_for (stmt, decl, expr);
12788         RECUR (RANGE_FOR_BODY (t));
12789         finish_for_stmt (stmt);
12790       }
12791       break;
12792
12793     case WHILE_STMT:
12794       stmt = begin_while_stmt ();
12795       tmp = RECUR (WHILE_COND (t));
12796       finish_while_stmt_cond (tmp, stmt);
12797       RECUR (WHILE_BODY (t));
12798       finish_while_stmt (stmt);
12799       break;
12800
12801     case DO_STMT:
12802       stmt = begin_do_stmt ();
12803       RECUR (DO_BODY (t));
12804       finish_do_body (stmt);
12805       tmp = RECUR (DO_COND (t));
12806       finish_do_stmt (tmp, stmt);
12807       break;
12808
12809     case IF_STMT:
12810       stmt = begin_if_stmt ();
12811       tmp = RECUR (IF_COND (t));
12812       finish_if_stmt_cond (tmp, stmt);
12813       RECUR (THEN_CLAUSE (t));
12814       finish_then_clause (stmt);
12815
12816       if (ELSE_CLAUSE (t))
12817         {
12818           begin_else_clause (stmt);
12819           RECUR (ELSE_CLAUSE (t));
12820           finish_else_clause (stmt);
12821         }
12822
12823       finish_if_stmt (stmt);
12824       break;
12825
12826     case BIND_EXPR:
12827       if (BIND_EXPR_BODY_BLOCK (t))
12828         stmt = begin_function_body ();
12829       else
12830         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
12831                                     ? BCS_TRY_BLOCK : 0);
12832
12833       RECUR (BIND_EXPR_BODY (t));
12834
12835       if (BIND_EXPR_BODY_BLOCK (t))
12836         finish_function_body (stmt);
12837       else
12838         finish_compound_stmt (stmt);
12839       break;
12840
12841     case BREAK_STMT:
12842       finish_break_stmt ();
12843       break;
12844
12845     case CONTINUE_STMT:
12846       finish_continue_stmt ();
12847       break;
12848
12849     case SWITCH_STMT:
12850       stmt = begin_switch_stmt ();
12851       tmp = RECUR (SWITCH_STMT_COND (t));
12852       finish_switch_cond (tmp, stmt);
12853       RECUR (SWITCH_STMT_BODY (t));
12854       finish_switch_stmt (stmt);
12855       break;
12856
12857     case CASE_LABEL_EXPR:
12858       finish_case_label (EXPR_LOCATION (t),
12859                          RECUR (CASE_LOW (t)),
12860                          RECUR (CASE_HIGH (t)));
12861       break;
12862
12863     case LABEL_EXPR:
12864       {
12865         tree decl = LABEL_EXPR_LABEL (t);
12866         tree label;
12867
12868         label = finish_label_stmt (DECL_NAME (decl));
12869         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
12870           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
12871       }
12872       break;
12873
12874     case GOTO_EXPR:
12875       tmp = GOTO_DESTINATION (t);
12876       if (TREE_CODE (tmp) != LABEL_DECL)
12877         /* Computed goto's must be tsubst'd into.  On the other hand,
12878            non-computed gotos must not be; the identifier in question
12879            will have no binding.  */
12880         tmp = RECUR (tmp);
12881       else
12882         tmp = DECL_NAME (tmp);
12883       finish_goto_stmt (tmp);
12884       break;
12885
12886     case ASM_EXPR:
12887       tmp = finish_asm_stmt
12888         (ASM_VOLATILE_P (t),
12889          RECUR (ASM_STRING (t)),
12890          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
12891          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
12892          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
12893          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
12894       {
12895         tree asm_expr = tmp;
12896         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
12897           asm_expr = TREE_OPERAND (asm_expr, 0);
12898         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
12899       }
12900       break;
12901
12902     case TRY_BLOCK:
12903       if (CLEANUP_P (t))
12904         {
12905           stmt = begin_try_block ();
12906           RECUR (TRY_STMTS (t));
12907           finish_cleanup_try_block (stmt);
12908           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
12909         }
12910       else
12911         {
12912           tree compound_stmt = NULL_TREE;
12913
12914           if (FN_TRY_BLOCK_P (t))
12915             stmt = begin_function_try_block (&compound_stmt);
12916           else
12917             stmt = begin_try_block ();
12918
12919           RECUR (TRY_STMTS (t));
12920
12921           if (FN_TRY_BLOCK_P (t))
12922             finish_function_try_block (stmt);
12923           else
12924             finish_try_block (stmt);
12925
12926           RECUR (TRY_HANDLERS (t));
12927           if (FN_TRY_BLOCK_P (t))
12928             finish_function_handler_sequence (stmt, compound_stmt);
12929           else
12930             finish_handler_sequence (stmt);
12931         }
12932       break;
12933
12934     case HANDLER:
12935       {
12936         tree decl = HANDLER_PARMS (t);
12937
12938         if (decl)
12939           {
12940             decl = tsubst (decl, args, complain, in_decl);
12941             /* Prevent instantiate_decl from trying to instantiate
12942                this variable.  We've already done all that needs to be
12943                done.  */
12944             if (decl != error_mark_node)
12945               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12946           }
12947         stmt = begin_handler ();
12948         finish_handler_parms (decl, stmt);
12949         RECUR (HANDLER_BODY (t));
12950         finish_handler (stmt);
12951       }
12952       break;
12953
12954     case TAG_DEFN:
12955       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12956       break;
12957
12958     case STATIC_ASSERT:
12959       {
12960         tree condition = 
12961           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
12962                        args,
12963                        complain, in_decl,
12964                        /*integral_constant_expression_p=*/true);
12965         finish_static_assert (condition,
12966                               STATIC_ASSERT_MESSAGE (t),
12967                               STATIC_ASSERT_SOURCE_LOCATION (t),
12968                               /*member_p=*/false);
12969       }
12970       break;
12971
12972     case OMP_PARALLEL:
12973       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
12974                                 args, complain, in_decl);
12975       stmt = begin_omp_parallel ();
12976       RECUR (OMP_PARALLEL_BODY (t));
12977       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
12978         = OMP_PARALLEL_COMBINED (t);
12979       break;
12980
12981     case OMP_TASK:
12982       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
12983                                 args, complain, in_decl);
12984       stmt = begin_omp_task ();
12985       RECUR (OMP_TASK_BODY (t));
12986       finish_omp_task (tmp, stmt);
12987       break;
12988
12989     case OMP_FOR:
12990       {
12991         tree clauses, body, pre_body;
12992         tree declv, initv, condv, incrv;
12993         int i;
12994
12995         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
12996                                       args, complain, in_decl);
12997         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12998         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12999         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
13000         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
13001
13002         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
13003           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
13004                                    &clauses, args, complain, in_decl,
13005                                    integral_constant_expression_p);
13006
13007         stmt = begin_omp_structured_block ();
13008
13009         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
13010           if (TREE_VEC_ELT (initv, i) == NULL
13011               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
13012             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
13013           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
13014             {
13015               tree init = RECUR (TREE_VEC_ELT (initv, i));
13016               gcc_assert (init == TREE_VEC_ELT (declv, i));
13017               TREE_VEC_ELT (initv, i) = NULL_TREE;
13018             }
13019           else
13020             {
13021               tree decl_expr = TREE_VEC_ELT (initv, i);
13022               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
13023               gcc_assert (init != NULL);
13024               TREE_VEC_ELT (initv, i) = RECUR (init);
13025               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
13026               RECUR (decl_expr);
13027               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
13028             }
13029
13030         pre_body = push_stmt_list ();
13031         RECUR (OMP_FOR_PRE_BODY (t));
13032         pre_body = pop_stmt_list (pre_body);
13033
13034         body = push_stmt_list ();
13035         RECUR (OMP_FOR_BODY (t));
13036         body = pop_stmt_list (body);
13037
13038         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
13039                             body, pre_body, clauses);
13040
13041         add_stmt (finish_omp_structured_block (stmt));
13042       }
13043       break;
13044
13045     case OMP_SECTIONS:
13046     case OMP_SINGLE:
13047       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
13048       stmt = push_stmt_list ();
13049       RECUR (OMP_BODY (t));
13050       stmt = pop_stmt_list (stmt);
13051
13052       t = copy_node (t);
13053       OMP_BODY (t) = stmt;
13054       OMP_CLAUSES (t) = tmp;
13055       add_stmt (t);
13056       break;
13057
13058     case OMP_SECTION:
13059     case OMP_CRITICAL:
13060     case OMP_MASTER:
13061     case OMP_ORDERED:
13062       stmt = push_stmt_list ();
13063       RECUR (OMP_BODY (t));
13064       stmt = pop_stmt_list (stmt);
13065
13066       t = copy_node (t);
13067       OMP_BODY (t) = stmt;
13068       add_stmt (t);
13069       break;
13070
13071     case OMP_ATOMIC:
13072       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
13073       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
13074         {
13075           tree op1 = TREE_OPERAND (t, 1);
13076           tree rhs1 = NULL_TREE;
13077           tree lhs, rhs;
13078           if (TREE_CODE (op1) == COMPOUND_EXPR)
13079             {
13080               rhs1 = RECUR (TREE_OPERAND (op1, 0));
13081               op1 = TREE_OPERAND (op1, 1);
13082             }
13083           lhs = RECUR (TREE_OPERAND (op1, 0));
13084           rhs = RECUR (TREE_OPERAND (op1, 1));
13085           finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
13086                              NULL_TREE, NULL_TREE, rhs1);
13087         }
13088       else
13089         {
13090           tree op1 = TREE_OPERAND (t, 1);
13091           tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
13092           tree rhs1 = NULL_TREE;
13093           enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
13094           enum tree_code opcode = NOP_EXPR;
13095           if (code == OMP_ATOMIC_READ)
13096             {
13097               v = RECUR (TREE_OPERAND (op1, 0));
13098               lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
13099             }
13100           else if (code == OMP_ATOMIC_CAPTURE_OLD
13101                    || code == OMP_ATOMIC_CAPTURE_NEW)
13102             {
13103               tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
13104               v = RECUR (TREE_OPERAND (op1, 0));
13105               lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
13106               if (TREE_CODE (op11) == COMPOUND_EXPR)
13107                 {
13108                   rhs1 = RECUR (TREE_OPERAND (op11, 0));
13109                   op11 = TREE_OPERAND (op11, 1);
13110                 }
13111               lhs = RECUR (TREE_OPERAND (op11, 0));
13112               rhs = RECUR (TREE_OPERAND (op11, 1));
13113               opcode = TREE_CODE (op11);
13114             }
13115           else
13116             {
13117               code = OMP_ATOMIC;
13118               lhs = RECUR (TREE_OPERAND (op1, 0));
13119               rhs = RECUR (TREE_OPERAND (op1, 1));
13120             }
13121           finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1);
13122         }
13123       break;
13124
13125     case TRANSACTION_EXPR:
13126       {
13127         int flags = 0;
13128         flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
13129         flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
13130
13131         if (TRANSACTION_EXPR_IS_STMT (t))
13132           {
13133             stmt = begin_transaction_stmt (input_location, NULL, flags);
13134             RECUR (TRANSACTION_EXPR_BODY (t));
13135             finish_transaction_stmt (stmt, NULL, flags);
13136           }
13137         else
13138           {
13139             stmt = build_transaction_expr (EXPR_LOCATION (t),
13140                                            RECUR (TRANSACTION_EXPR_BODY (t)),
13141                                            flags);
13142             return stmt;
13143           }
13144       }
13145       break;
13146
13147     case EXPR_PACK_EXPANSION:
13148       error ("invalid use of pack expansion expression");
13149       return error_mark_node;
13150
13151     case NONTYPE_ARGUMENT_PACK:
13152       error ("use %<...%> to expand argument pack");
13153       return error_mark_node;
13154
13155     default:
13156       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
13157
13158       return tsubst_copy_and_build (t, args, complain, in_decl,
13159                                     /*function_p=*/false,
13160                                     integral_constant_expression_p);
13161     }
13162
13163   return NULL_TREE;
13164 #undef RECUR
13165 }
13166
13167 /* T is a postfix-expression that is not being used in a function
13168    call.  Return the substituted version of T.  */
13169
13170 static tree
13171 tsubst_non_call_postfix_expression (tree t, tree args,
13172                                     tsubst_flags_t complain,
13173                                     tree in_decl)
13174 {
13175   if (TREE_CODE (t) == SCOPE_REF)
13176     t = tsubst_qualified_id (t, args, complain, in_decl,
13177                              /*done=*/false, /*address_p=*/false);
13178   else
13179     t = tsubst_copy_and_build (t, args, complain, in_decl,
13180                                /*function_p=*/false,
13181                                /*integral_constant_expression_p=*/false);
13182
13183   return t;
13184 }
13185
13186 /* Like tsubst but deals with expressions and performs semantic
13187    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
13188
13189 tree
13190 tsubst_copy_and_build (tree t,
13191                        tree args,
13192                        tsubst_flags_t complain,
13193                        tree in_decl,
13194                        bool function_p,
13195                        bool integral_constant_expression_p)
13196 {
13197 #define RECUR(NODE)                                             \
13198   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
13199                          /*function_p=*/false,                  \
13200                          integral_constant_expression_p)
13201
13202   tree op1;
13203
13204   if (t == NULL_TREE || t == error_mark_node)
13205     return t;
13206
13207   switch (TREE_CODE (t))
13208     {
13209     case USING_DECL:
13210       t = DECL_NAME (t);
13211       /* Fall through.  */
13212     case IDENTIFIER_NODE:
13213       {
13214         tree decl;
13215         cp_id_kind idk;
13216         bool non_integral_constant_expression_p;
13217         const char *error_msg;
13218
13219         if (IDENTIFIER_TYPENAME_P (t))
13220           {
13221             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13222             t = mangle_conv_op_name_for_type (new_type);
13223           }
13224
13225         /* Look up the name.  */
13226         decl = lookup_name (t);
13227
13228         /* By convention, expressions use ERROR_MARK_NODE to indicate
13229            failure, not NULL_TREE.  */
13230         if (decl == NULL_TREE)
13231           decl = error_mark_node;
13232
13233         decl = finish_id_expression (t, decl, NULL_TREE,
13234                                      &idk,
13235                                      integral_constant_expression_p,
13236           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx0x),
13237                                      &non_integral_constant_expression_p,
13238                                      /*template_p=*/false,
13239                                      /*done=*/true,
13240                                      /*address_p=*/false,
13241                                      /*template_arg_p=*/false,
13242                                      &error_msg,
13243                                      input_location);
13244         if (error_msg)
13245           error (error_msg);
13246         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
13247           {
13248             if (complain & tf_error)
13249               unqualified_name_lookup_error (decl);
13250             decl = error_mark_node;
13251           }
13252         return decl;
13253       }
13254
13255     case TEMPLATE_ID_EXPR:
13256       {
13257         tree object;
13258         tree templ = RECUR (TREE_OPERAND (t, 0));
13259         tree targs = TREE_OPERAND (t, 1);
13260
13261         if (targs)
13262           targs = tsubst_template_args (targs, args, complain, in_decl);
13263
13264         if (TREE_CODE (templ) == COMPONENT_REF)
13265           {
13266             object = TREE_OPERAND (templ, 0);
13267             templ = TREE_OPERAND (templ, 1);
13268           }
13269         else
13270           object = NULL_TREE;
13271         templ = lookup_template_function (templ, targs);
13272
13273         if (object)
13274           return build3 (COMPONENT_REF, TREE_TYPE (templ),
13275                          object, templ, NULL_TREE);
13276         else
13277           return baselink_for_fns (templ);
13278       }
13279
13280     case INDIRECT_REF:
13281       {
13282         tree r = RECUR (TREE_OPERAND (t, 0));
13283
13284         if (REFERENCE_REF_P (t))
13285           {
13286             /* A type conversion to reference type will be enclosed in
13287                such an indirect ref, but the substitution of the cast
13288                will have also added such an indirect ref.  */
13289             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
13290               r = convert_from_reference (r);
13291           }
13292         else
13293           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
13294         return r;
13295       }
13296
13297     case NOP_EXPR:
13298       return build_nop
13299         (tsubst (TREE_TYPE (t), args, complain, in_decl),
13300          RECUR (TREE_OPERAND (t, 0)));
13301
13302     case IMPLICIT_CONV_EXPR:
13303       {
13304         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13305         tree expr = RECUR (TREE_OPERAND (t, 0));
13306         int flags = LOOKUP_IMPLICIT;
13307         if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
13308           flags = LOOKUP_NORMAL;
13309         return perform_implicit_conversion_flags (type, expr, complain,
13310                                                   flags);
13311       }
13312
13313     case CONVERT_EXPR:
13314       return build1
13315         (CONVERT_EXPR,
13316          tsubst (TREE_TYPE (t), args, complain, in_decl),
13317          RECUR (TREE_OPERAND (t, 0)));
13318
13319     case CAST_EXPR:
13320     case REINTERPRET_CAST_EXPR:
13321     case CONST_CAST_EXPR:
13322     case DYNAMIC_CAST_EXPR:
13323     case STATIC_CAST_EXPR:
13324       {
13325         tree type;
13326         tree op;
13327
13328         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13329         if (integral_constant_expression_p
13330             && !cast_valid_in_integral_constant_expression_p (type))
13331           {
13332             if (complain & tf_error)
13333               error ("a cast to a type other than an integral or "
13334                      "enumeration type cannot appear in a constant-expression");
13335             return error_mark_node; 
13336           }
13337
13338         op = RECUR (TREE_OPERAND (t, 0));
13339
13340         switch (TREE_CODE (t))
13341           {
13342           case CAST_EXPR:
13343             return build_functional_cast (type, op, complain);
13344           case REINTERPRET_CAST_EXPR:
13345             return build_reinterpret_cast (type, op, complain);
13346           case CONST_CAST_EXPR:
13347             return build_const_cast (type, op, complain);
13348           case DYNAMIC_CAST_EXPR:
13349             return build_dynamic_cast (type, op, complain);
13350           case STATIC_CAST_EXPR:
13351             return build_static_cast (type, op, complain);
13352           default:
13353             gcc_unreachable ();
13354           }
13355       }
13356
13357     case POSTDECREMENT_EXPR:
13358     case POSTINCREMENT_EXPR:
13359       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13360                                                 args, complain, in_decl);
13361       return build_x_unary_op (TREE_CODE (t), op1, complain);
13362
13363     case PREDECREMENT_EXPR:
13364     case PREINCREMENT_EXPR:
13365     case NEGATE_EXPR:
13366     case BIT_NOT_EXPR:
13367     case ABS_EXPR:
13368     case TRUTH_NOT_EXPR:
13369     case UNARY_PLUS_EXPR:  /* Unary + */
13370     case REALPART_EXPR:
13371     case IMAGPART_EXPR:
13372       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
13373                                complain);
13374
13375     case ADDR_EXPR:
13376       op1 = TREE_OPERAND (t, 0);
13377       if (TREE_CODE (op1) == LABEL_DECL)
13378         return finish_label_address_expr (DECL_NAME (op1),
13379                                           EXPR_LOCATION (op1));
13380       if (TREE_CODE (op1) == SCOPE_REF)
13381         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
13382                                    /*done=*/true, /*address_p=*/true);
13383       else
13384         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
13385                                                   in_decl);
13386       return build_x_unary_op (ADDR_EXPR, op1, complain);
13387
13388     case PLUS_EXPR:
13389     case MINUS_EXPR:
13390     case MULT_EXPR:
13391     case TRUNC_DIV_EXPR:
13392     case CEIL_DIV_EXPR:
13393     case FLOOR_DIV_EXPR:
13394     case ROUND_DIV_EXPR:
13395     case EXACT_DIV_EXPR:
13396     case BIT_AND_EXPR:
13397     case BIT_IOR_EXPR:
13398     case BIT_XOR_EXPR:
13399     case TRUNC_MOD_EXPR:
13400     case FLOOR_MOD_EXPR:
13401     case TRUTH_ANDIF_EXPR:
13402     case TRUTH_ORIF_EXPR:
13403     case TRUTH_AND_EXPR:
13404     case TRUTH_OR_EXPR:
13405     case RSHIFT_EXPR:
13406     case LSHIFT_EXPR:
13407     case RROTATE_EXPR:
13408     case LROTATE_EXPR:
13409     case EQ_EXPR:
13410     case NE_EXPR:
13411     case MAX_EXPR:
13412     case MIN_EXPR:
13413     case LE_EXPR:
13414     case GE_EXPR:
13415     case LT_EXPR:
13416     case GT_EXPR:
13417     case MEMBER_REF:
13418     case DOTSTAR_EXPR:
13419       return build_x_binary_op
13420         (TREE_CODE (t),
13421          RECUR (TREE_OPERAND (t, 0)),
13422          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
13423           ? ERROR_MARK
13424           : TREE_CODE (TREE_OPERAND (t, 0))),
13425          RECUR (TREE_OPERAND (t, 1)),
13426          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
13427           ? ERROR_MARK
13428           : TREE_CODE (TREE_OPERAND (t, 1))),
13429          /*overload=*/NULL,
13430          complain);
13431
13432     case SCOPE_REF:
13433       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
13434                                   /*address_p=*/false);
13435     case ARRAY_REF:
13436       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13437                                                 args, complain, in_decl);
13438       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
13439
13440     case SIZEOF_EXPR:
13441       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
13442         return tsubst_copy (t, args, complain, in_decl);
13443       /* Fall through */
13444       
13445     case ALIGNOF_EXPR:
13446       op1 = TREE_OPERAND (t, 0);
13447       if (!args)
13448         {
13449           /* When there are no ARGS, we are trying to evaluate a
13450              non-dependent expression from the parser.  Trying to do
13451              the substitutions may not work.  */
13452           if (!TYPE_P (op1))
13453             op1 = TREE_TYPE (op1);
13454         }
13455       else
13456         {
13457           ++cp_unevaluated_operand;
13458           ++c_inhibit_evaluation_warnings;
13459           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13460                                        /*function_p=*/false,
13461                                        /*integral_constant_expression_p=*/false);
13462           --cp_unevaluated_operand;
13463           --c_inhibit_evaluation_warnings;
13464         }
13465       if (TYPE_P (op1))
13466         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
13467                                            complain & tf_error);
13468       else
13469         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
13470                                            complain & tf_error);
13471
13472     case AT_ENCODE_EXPR:
13473       {
13474         op1 = TREE_OPERAND (t, 0);
13475         ++cp_unevaluated_operand;
13476         ++c_inhibit_evaluation_warnings;
13477         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13478                                      /*function_p=*/false,
13479                                      /*integral_constant_expression_p=*/false);
13480         --cp_unevaluated_operand;
13481         --c_inhibit_evaluation_warnings;
13482         return objc_build_encode_expr (op1);
13483       }
13484
13485     case NOEXCEPT_EXPR:
13486       op1 = TREE_OPERAND (t, 0);
13487       ++cp_unevaluated_operand;
13488       ++c_inhibit_evaluation_warnings;
13489       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13490                                    /*function_p=*/false,
13491                                    /*integral_constant_expression_p=*/false);
13492       --cp_unevaluated_operand;
13493       --c_inhibit_evaluation_warnings;
13494       return finish_noexcept_expr (op1, complain);
13495
13496     case MODOP_EXPR:
13497       {
13498         tree r = build_x_modify_expr
13499           (RECUR (TREE_OPERAND (t, 0)),
13500            TREE_CODE (TREE_OPERAND (t, 1)),
13501            RECUR (TREE_OPERAND (t, 2)),
13502            complain);
13503         /* TREE_NO_WARNING must be set if either the expression was
13504            parenthesized or it uses an operator such as >>= rather
13505            than plain assignment.  In the former case, it was already
13506            set and must be copied.  In the latter case,
13507            build_x_modify_expr sets it and it must not be reset
13508            here.  */
13509         if (TREE_NO_WARNING (t))
13510           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
13511         return r;
13512       }
13513
13514     case ARROW_EXPR:
13515       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13516                                                 args, complain, in_decl);
13517       /* Remember that there was a reference to this entity.  */
13518       if (DECL_P (op1))
13519         mark_used (op1);
13520       return build_x_arrow (op1);
13521
13522     case NEW_EXPR:
13523       {
13524         tree placement = RECUR (TREE_OPERAND (t, 0));
13525         tree init = RECUR (TREE_OPERAND (t, 3));
13526         VEC(tree,gc) *placement_vec;
13527         VEC(tree,gc) *init_vec;
13528         tree ret;
13529
13530         if (placement == NULL_TREE)
13531           placement_vec = NULL;
13532         else
13533           {
13534             placement_vec = make_tree_vector ();
13535             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
13536               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
13537           }
13538
13539         /* If there was an initializer in the original tree, but it
13540            instantiated to an empty list, then we should pass a
13541            non-NULL empty vector to tell build_new that it was an
13542            empty initializer() rather than no initializer.  This can
13543            only happen when the initializer is a pack expansion whose
13544            parameter packs are of length zero.  */
13545         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
13546           init_vec = NULL;
13547         else
13548           {
13549             init_vec = make_tree_vector ();
13550             if (init == void_zero_node)
13551               gcc_assert (init_vec != NULL);
13552             else
13553               {
13554                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
13555                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
13556               }
13557           }
13558
13559         ret = build_new (&placement_vec,
13560                          tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
13561                          RECUR (TREE_OPERAND (t, 2)),
13562                          &init_vec,
13563                          NEW_EXPR_USE_GLOBAL (t),
13564                          complain);
13565
13566         if (placement_vec != NULL)
13567           release_tree_vector (placement_vec);
13568         if (init_vec != NULL)
13569           release_tree_vector (init_vec);
13570
13571         return ret;
13572       }
13573
13574     case DELETE_EXPR:
13575      return delete_sanity
13576        (RECUR (TREE_OPERAND (t, 0)),
13577         RECUR (TREE_OPERAND (t, 1)),
13578         DELETE_EXPR_USE_VEC (t),
13579         DELETE_EXPR_USE_GLOBAL (t),
13580         complain);
13581
13582     case COMPOUND_EXPR:
13583       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
13584                                     RECUR (TREE_OPERAND (t, 1)),
13585                                     complain);
13586
13587     case CALL_EXPR:
13588       {
13589         tree function;
13590         VEC(tree,gc) *call_args;
13591         unsigned int nargs, i;
13592         bool qualified_p;
13593         bool koenig_p;
13594         tree ret;
13595
13596         function = CALL_EXPR_FN (t);
13597         /* When we parsed the expression,  we determined whether or
13598            not Koenig lookup should be performed.  */
13599         koenig_p = KOENIG_LOOKUP_P (t);
13600         if (TREE_CODE (function) == SCOPE_REF)
13601           {
13602             qualified_p = true;
13603             function = tsubst_qualified_id (function, args, complain, in_decl,
13604                                             /*done=*/false,
13605                                             /*address_p=*/false);
13606           }
13607         else if (koenig_p && TREE_CODE (function) == IDENTIFIER_NODE)
13608           {
13609             /* Do nothing; calling tsubst_copy_and_build on an identifier
13610                would incorrectly perform unqualified lookup again.
13611
13612                Note that we can also have an IDENTIFIER_NODE if the earlier
13613                unqualified lookup found a member function; in that case
13614                koenig_p will be false and we do want to do the lookup
13615                again to find the instantiated member function.
13616
13617                FIXME but doing that causes c++/15272, so we need to stop
13618                using IDENTIFIER_NODE in that situation.  */
13619             qualified_p = false;
13620           }
13621         else
13622           {
13623             if (TREE_CODE (function) == COMPONENT_REF)
13624               {
13625                 tree op = TREE_OPERAND (function, 1);
13626
13627                 qualified_p = (TREE_CODE (op) == SCOPE_REF
13628                                || (BASELINK_P (op)
13629                                    && BASELINK_QUALIFIED_P (op)));
13630               }
13631             else
13632               qualified_p = false;
13633
13634             function = tsubst_copy_and_build (function, args, complain,
13635                                               in_decl,
13636                                               !qualified_p,
13637                                               integral_constant_expression_p);
13638
13639             if (BASELINK_P (function))
13640               qualified_p = true;
13641           }
13642
13643         nargs = call_expr_nargs (t);
13644         call_args = make_tree_vector ();
13645         for (i = 0; i < nargs; ++i)
13646           {
13647             tree arg = CALL_EXPR_ARG (t, i);
13648
13649             if (!PACK_EXPANSION_P (arg))
13650               VEC_safe_push (tree, gc, call_args,
13651                              RECUR (CALL_EXPR_ARG (t, i)));
13652             else
13653               {
13654                 /* Expand the pack expansion and push each entry onto
13655                    CALL_ARGS.  */
13656                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
13657                 if (TREE_CODE (arg) == TREE_VEC)
13658                   {
13659                     unsigned int len, j;
13660
13661                     len = TREE_VEC_LENGTH (arg);
13662                     for (j = 0; j < len; ++j)
13663                       {
13664                         tree value = TREE_VEC_ELT (arg, j);
13665                         if (value != NULL_TREE)
13666                           value = convert_from_reference (value);
13667                         VEC_safe_push (tree, gc, call_args, value);
13668                       }
13669                   }
13670                 else
13671                   {
13672                     /* A partial substitution.  Add one entry.  */
13673                     VEC_safe_push (tree, gc, call_args, arg);
13674                   }
13675               }
13676           }
13677
13678         /* We do not perform argument-dependent lookup if normal
13679            lookup finds a non-function, in accordance with the
13680            expected resolution of DR 218.  */
13681         if (koenig_p
13682             && ((is_overloaded_fn (function)
13683                  /* If lookup found a member function, the Koenig lookup is
13684                     not appropriate, even if an unqualified-name was used
13685                     to denote the function.  */
13686                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
13687                 || TREE_CODE (function) == IDENTIFIER_NODE)
13688             /* Only do this when substitution turns a dependent call
13689                into a non-dependent call.  */
13690             && type_dependent_expression_p_push (t)
13691             && !any_type_dependent_arguments_p (call_args))
13692           function = perform_koenig_lookup (function, call_args, false,
13693                                             tf_none);
13694
13695         if (TREE_CODE (function) == IDENTIFIER_NODE
13696             && !any_type_dependent_arguments_p (call_args))
13697           {
13698             if (koenig_p && (complain & tf_warning_or_error))
13699               {
13700                 /* For backwards compatibility and good diagnostics, try
13701                    the unqualified lookup again if we aren't in SFINAE
13702                    context.  */
13703                 tree unq = (tsubst_copy_and_build
13704                             (function, args, complain, in_decl, true,
13705                              integral_constant_expression_p));
13706                 if (unq == error_mark_node)
13707                   return error_mark_node;
13708
13709                 if (unq != function)
13710                   {
13711                     tree fn = unq;
13712                     if (TREE_CODE (fn) == INDIRECT_REF)
13713                       fn = TREE_OPERAND (fn, 0);
13714                     if (TREE_CODE (fn) == COMPONENT_REF)
13715                       fn = TREE_OPERAND (fn, 1);
13716                     if (is_overloaded_fn (fn))
13717                       fn = get_first_fn (fn);
13718                     permerror (EXPR_LOC_OR_HERE (t),
13719                                "%qD was not declared in this scope, "
13720                                "and no declarations were found by "
13721                                "argument-dependent lookup at the point "
13722                                "of instantiation", function);
13723                     if (!DECL_P (fn))
13724                       /* Can't say anything more.  */;
13725                     else if (DECL_CLASS_SCOPE_P (fn))
13726                       {
13727                         inform (EXPR_LOC_OR_HERE (t),
13728                                 "declarations in dependent base %qT are "
13729                                 "not found by unqualified lookup",
13730                                 DECL_CLASS_CONTEXT (fn));
13731                         if (current_class_ptr)
13732                           inform (EXPR_LOC_OR_HERE (t),
13733                                   "use %<this->%D%> instead", function);
13734                         else
13735                           inform (EXPR_LOC_OR_HERE (t),
13736                                   "use %<%T::%D%> instead",
13737                                   current_class_name, function);
13738                       }
13739                     else
13740                       inform (0, "%q+D declared here, later in the "
13741                                 "translation unit", fn);
13742                     function = unq;
13743                   }
13744               }
13745             if (TREE_CODE (function) == IDENTIFIER_NODE)
13746               {
13747                 unqualified_name_lookup_error (function);
13748                 release_tree_vector (call_args);
13749                 return error_mark_node;
13750               }
13751           }
13752
13753         /* Remember that there was a reference to this entity.  */
13754         if (DECL_P (function))
13755           mark_used (function);
13756
13757         if (TREE_CODE (function) == OFFSET_REF)
13758           ret = build_offset_ref_call_from_tree (function, &call_args);
13759         else if (TREE_CODE (function) == COMPONENT_REF)
13760           {
13761             tree instance = TREE_OPERAND (function, 0);
13762             tree fn = TREE_OPERAND (function, 1);
13763
13764             if (processing_template_decl
13765                 && (type_dependent_expression_p (instance)
13766                     || (!BASELINK_P (fn)
13767                         && TREE_CODE (fn) != FIELD_DECL)
13768                     || type_dependent_expression_p (fn)
13769                     || any_type_dependent_arguments_p (call_args)))
13770               ret = build_nt_call_vec (function, call_args);
13771             else if (!BASELINK_P (fn))
13772               ret = finish_call_expr (function, &call_args,
13773                                        /*disallow_virtual=*/false,
13774                                        /*koenig_p=*/false,
13775                                        complain);
13776             else
13777               ret = (build_new_method_call
13778                       (instance, fn,
13779                        &call_args, NULL_TREE,
13780                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
13781                        /*fn_p=*/NULL,
13782                        complain));
13783           }
13784         else
13785           ret = finish_call_expr (function, &call_args,
13786                                   /*disallow_virtual=*/qualified_p,
13787                                   koenig_p,
13788                                   complain);
13789
13790         release_tree_vector (call_args);
13791
13792         return ret;
13793       }
13794
13795     case COND_EXPR:
13796       return build_x_conditional_expr
13797         (RECUR (TREE_OPERAND (t, 0)),
13798          RECUR (TREE_OPERAND (t, 1)),
13799          RECUR (TREE_OPERAND (t, 2)),
13800          complain);
13801
13802     case PSEUDO_DTOR_EXPR:
13803       return finish_pseudo_destructor_expr
13804         (RECUR (TREE_OPERAND (t, 0)),
13805          RECUR (TREE_OPERAND (t, 1)),
13806          tsubst (TREE_OPERAND (t, 2), args, complain, in_decl));
13807
13808     case TREE_LIST:
13809       {
13810         tree purpose, value, chain;
13811
13812         if (t == void_list_node)
13813           return t;
13814
13815         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
13816             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
13817           {
13818             /* We have pack expansions, so expand those and
13819                create a new list out of it.  */
13820             tree purposevec = NULL_TREE;
13821             tree valuevec = NULL_TREE;
13822             tree chain;
13823             int i, len = -1;
13824
13825             /* Expand the argument expressions.  */
13826             if (TREE_PURPOSE (t))
13827               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
13828                                                  complain, in_decl);
13829             if (TREE_VALUE (t))
13830               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
13831                                                complain, in_decl);
13832
13833             /* Build the rest of the list.  */
13834             chain = TREE_CHAIN (t);
13835             if (chain && chain != void_type_node)
13836               chain = RECUR (chain);
13837
13838             /* Determine the number of arguments.  */
13839             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
13840               {
13841                 len = TREE_VEC_LENGTH (purposevec);
13842                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
13843               }
13844             else if (TREE_CODE (valuevec) == TREE_VEC)
13845               len = TREE_VEC_LENGTH (valuevec);
13846             else
13847               {
13848                 /* Since we only performed a partial substitution into
13849                    the argument pack, we only return a single list
13850                    node.  */
13851                 if (purposevec == TREE_PURPOSE (t)
13852                     && valuevec == TREE_VALUE (t)
13853                     && chain == TREE_CHAIN (t))
13854                   return t;
13855
13856                 return tree_cons (purposevec, valuevec, chain);
13857               }
13858             
13859             /* Convert the argument vectors into a TREE_LIST */
13860             i = len;
13861             while (i > 0)
13862               {
13863                 /* Grab the Ith values.  */
13864                 i--;
13865                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
13866                                      : NULL_TREE;
13867                 value 
13868                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
13869                              : NULL_TREE;
13870
13871                 /* Build the list (backwards).  */
13872                 chain = tree_cons (purpose, value, chain);
13873               }
13874
13875             return chain;
13876           }
13877
13878         purpose = TREE_PURPOSE (t);
13879         if (purpose)
13880           purpose = RECUR (purpose);
13881         value = TREE_VALUE (t);
13882         if (value)
13883           value = RECUR (value);
13884         chain = TREE_CHAIN (t);
13885         if (chain && chain != void_type_node)
13886           chain = RECUR (chain);
13887         if (purpose == TREE_PURPOSE (t)
13888             && value == TREE_VALUE (t)
13889             && chain == TREE_CHAIN (t))
13890           return t;
13891         return tree_cons (purpose, value, chain);
13892       }
13893
13894     case COMPONENT_REF:
13895       {
13896         tree object;
13897         tree object_type;
13898         tree member;
13899
13900         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13901                                                      args, complain, in_decl);
13902         /* Remember that there was a reference to this entity.  */
13903         if (DECL_P (object))
13904           mark_used (object);
13905         object_type = TREE_TYPE (object);
13906
13907         member = TREE_OPERAND (t, 1);
13908         if (BASELINK_P (member))
13909           member = tsubst_baselink (member,
13910                                     non_reference (TREE_TYPE (object)),
13911                                     args, complain, in_decl);
13912         else
13913           member = tsubst_copy (member, args, complain, in_decl);
13914         if (member == error_mark_node)
13915           return error_mark_node;
13916
13917         if (type_dependent_expression_p (object))
13918           /* We can't do much here.  */;
13919         else if (!CLASS_TYPE_P (object_type))
13920           {
13921             if (SCALAR_TYPE_P (object_type))
13922               {
13923                 tree s = NULL_TREE;
13924                 tree dtor = member;
13925
13926                 if (TREE_CODE (dtor) == SCOPE_REF)
13927                   {
13928                     s = TREE_OPERAND (dtor, 0);
13929                     dtor = TREE_OPERAND (dtor, 1);
13930                   }
13931                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
13932                   {
13933                     dtor = TREE_OPERAND (dtor, 0);
13934                     if (TYPE_P (dtor))
13935                       return finish_pseudo_destructor_expr (object, s, dtor);
13936                   }
13937               }
13938           }
13939         else if (TREE_CODE (member) == SCOPE_REF
13940                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
13941           {
13942             /* Lookup the template functions now that we know what the
13943                scope is.  */
13944             tree scope = TREE_OPERAND (member, 0);
13945             tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
13946             tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
13947             member = lookup_qualified_name (scope, tmpl,
13948                                             /*is_type_p=*/false,
13949                                             /*complain=*/false);
13950             if (BASELINK_P (member))
13951               {
13952                 BASELINK_FUNCTIONS (member)
13953                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
13954                               args);
13955                 member = (adjust_result_of_qualified_name_lookup
13956                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
13957                            object_type));
13958               }
13959             else
13960               {
13961                 qualified_name_lookup_error (scope, tmpl, member,
13962                                              input_location);
13963                 return error_mark_node;
13964               }
13965           }
13966         else if (TREE_CODE (member) == SCOPE_REF
13967                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
13968                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
13969           {
13970             if (complain & tf_error)
13971               {
13972                 if (TYPE_P (TREE_OPERAND (member, 0)))
13973                   error ("%qT is not a class or namespace",
13974                          TREE_OPERAND (member, 0));
13975                 else
13976                   error ("%qD is not a class or namespace",
13977                          TREE_OPERAND (member, 0));
13978               }
13979             return error_mark_node;
13980           }
13981         else if (TREE_CODE (member) == FIELD_DECL)
13982           return finish_non_static_data_member (member, object, NULL_TREE);
13983
13984         return finish_class_member_access_expr (object, member,
13985                                                 /*template_p=*/false,
13986                                                 complain);
13987       }
13988
13989     case THROW_EXPR:
13990       return build_throw
13991         (RECUR (TREE_OPERAND (t, 0)));
13992
13993     case CONSTRUCTOR:
13994       {
13995         VEC(constructor_elt,gc) *n;
13996         constructor_elt *ce;
13997         unsigned HOST_WIDE_INT idx;
13998         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13999         bool process_index_p;
14000         int newlen;
14001         bool need_copy_p = false;
14002         tree r;
14003
14004         if (type == error_mark_node)
14005           return error_mark_node;
14006
14007         /* digest_init will do the wrong thing if we let it.  */
14008         if (type && TYPE_PTRMEMFUNC_P (type))
14009           return t;
14010
14011         /* We do not want to process the index of aggregate
14012            initializers as they are identifier nodes which will be
14013            looked up by digest_init.  */
14014         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
14015
14016         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
14017         newlen = VEC_length (constructor_elt, n);
14018         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
14019           {
14020             if (ce->index && process_index_p)
14021               ce->index = RECUR (ce->index);
14022
14023             if (PACK_EXPANSION_P (ce->value))
14024               {
14025                 /* Substitute into the pack expansion.  */
14026                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
14027                                                   in_decl);
14028
14029                 if (ce->value == error_mark_node
14030                     || PACK_EXPANSION_P (ce->value))
14031                   ;
14032                 else if (TREE_VEC_LENGTH (ce->value) == 1)
14033                   /* Just move the argument into place.  */
14034                   ce->value = TREE_VEC_ELT (ce->value, 0);
14035                 else
14036                   {
14037                     /* Update the length of the final CONSTRUCTOR
14038                        arguments vector, and note that we will need to
14039                        copy.*/
14040                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
14041                     need_copy_p = true;
14042                   }
14043               }
14044             else
14045               ce->value = RECUR (ce->value);
14046           }
14047
14048         if (need_copy_p)
14049           {
14050             VEC(constructor_elt,gc) *old_n = n;
14051
14052             n = VEC_alloc (constructor_elt, gc, newlen);
14053             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
14054               {
14055                 if (TREE_CODE (ce->value) == TREE_VEC)
14056                   {
14057                     int i, len = TREE_VEC_LENGTH (ce->value);
14058                     for (i = 0; i < len; ++i)
14059                       CONSTRUCTOR_APPEND_ELT (n, 0,
14060                                               TREE_VEC_ELT (ce->value, i));
14061                   }
14062                 else
14063                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
14064               }
14065           }
14066
14067         r = build_constructor (init_list_type_node, n);
14068         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
14069
14070         if (TREE_HAS_CONSTRUCTOR (t))
14071           return finish_compound_literal (type, r, complain);
14072
14073         TREE_TYPE (r) = type;
14074         return r;
14075       }
14076
14077     case TYPEID_EXPR:
14078       {
14079         tree operand_0 = TREE_OPERAND (t, 0);
14080         if (TYPE_P (operand_0))
14081           {
14082             operand_0 = tsubst (operand_0, args, complain, in_decl);
14083             return get_typeid (operand_0);
14084           }
14085         else
14086           {
14087             operand_0 = RECUR (operand_0);
14088             return build_typeid (operand_0);
14089           }
14090       }
14091
14092     case VAR_DECL:
14093       if (!args)
14094         return t;
14095       /* Fall through */
14096
14097     case PARM_DECL:
14098       {
14099         tree r = tsubst_copy (t, args, complain, in_decl);
14100
14101         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
14102           /* If the original type was a reference, we'll be wrapped in
14103              the appropriate INDIRECT_REF.  */
14104           r = convert_from_reference (r);
14105         return r;
14106       }
14107
14108     case VA_ARG_EXPR:
14109       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
14110                              tsubst (TREE_TYPE (t), args, complain, in_decl));
14111
14112     case OFFSETOF_EXPR:
14113       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
14114
14115     case TRAIT_EXPR:
14116       {
14117         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
14118                                   complain, in_decl);
14119
14120         tree type2 = TRAIT_EXPR_TYPE2 (t);
14121         if (type2)
14122           type2 = tsubst_copy (type2, args, complain, in_decl);
14123         
14124         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
14125       }
14126
14127     case STMT_EXPR:
14128       {
14129         tree old_stmt_expr = cur_stmt_expr;
14130         tree stmt_expr = begin_stmt_expr ();
14131
14132         cur_stmt_expr = stmt_expr;
14133         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
14134                      integral_constant_expression_p);
14135         stmt_expr = finish_stmt_expr (stmt_expr, false);
14136         cur_stmt_expr = old_stmt_expr;
14137
14138         /* If the resulting list of expression statement is empty,
14139            fold it further into void_zero_node.  */
14140         if (empty_expr_stmt_p (stmt_expr))
14141           stmt_expr = void_zero_node;
14142
14143         return stmt_expr;
14144       }
14145
14146     case CONST_DECL:
14147       t = tsubst_copy (t, args, complain, in_decl);
14148       /* As in finish_id_expression, we resolve enumeration constants
14149          to their underlying values.  */
14150       if (TREE_CODE (t) == CONST_DECL && !processing_template_decl)
14151         {
14152           used_types_insert (TREE_TYPE (t));
14153           return DECL_INITIAL (t);
14154         }
14155       return t;
14156
14157     case LAMBDA_EXPR:
14158       {
14159         tree r = build_lambda_expr ();
14160
14161         tree type = tsubst (LAMBDA_EXPR_CLOSURE (t), args, complain, NULL_TREE);
14162         LAMBDA_EXPR_CLOSURE (r) = type;
14163         CLASSTYPE_LAMBDA_EXPR (type) = r;
14164
14165         LAMBDA_EXPR_LOCATION (r)
14166           = LAMBDA_EXPR_LOCATION (t);
14167         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
14168           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
14169         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
14170         LAMBDA_EXPR_DISCRIMINATOR (r)
14171           = (LAMBDA_EXPR_DISCRIMINATOR (t));
14172         LAMBDA_EXPR_EXTRA_SCOPE (r)
14173           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
14174         if (LAMBDA_EXPR_RETURN_TYPE (t) == dependent_lambda_return_type_node)
14175           {
14176             LAMBDA_EXPR_RETURN_TYPE (r) = dependent_lambda_return_type_node;
14177             LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (r) = true;
14178           }
14179         else
14180           LAMBDA_EXPR_RETURN_TYPE (r)
14181             = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
14182
14183         gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
14184                     && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
14185
14186         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
14187         determine_visibility (TYPE_NAME (type));
14188         /* Now that we know visibility, instantiate the type so we have a
14189            declaration of the op() for later calls to lambda_function.  */
14190         complete_type (type);
14191
14192         /* The capture list refers to closure members, so this needs to
14193            wait until after we finish instantiating the type.  */
14194         LAMBDA_EXPR_CAPTURE_LIST (r)
14195           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
14196
14197         return build_lambda_object (r);
14198       }
14199
14200     case TARGET_EXPR:
14201       /* We can get here for a constant initializer of non-dependent type.
14202          FIXME stop folding in cp_parser_initializer_clause.  */
14203       gcc_assert (TREE_CONSTANT (t));
14204       {
14205         tree r = get_target_expr (RECUR (TARGET_EXPR_INITIAL (t)));
14206         TREE_CONSTANT (r) = true;
14207         return r;
14208       }
14209
14210     default:
14211       /* Handle Objective-C++ constructs, if appropriate.  */
14212       {
14213         tree subst
14214           = objcp_tsubst_copy_and_build (t, args, complain,
14215                                          in_decl, /*function_p=*/false);
14216         if (subst)
14217           return subst;
14218       }
14219       return tsubst_copy (t, args, complain, in_decl);
14220     }
14221
14222 #undef RECUR
14223 }
14224
14225 /* Verify that the instantiated ARGS are valid. For type arguments,
14226    make sure that the type's linkage is ok. For non-type arguments,
14227    make sure they are constants if they are integral or enumerations.
14228    Emit an error under control of COMPLAIN, and return TRUE on error.  */
14229
14230 static bool
14231 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
14232 {
14233   if (ARGUMENT_PACK_P (t))
14234     {
14235       tree vec = ARGUMENT_PACK_ARGS (t);
14236       int len = TREE_VEC_LENGTH (vec);
14237       bool result = false;
14238       int i;
14239
14240       for (i = 0; i < len; ++i)
14241         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
14242           result = true;
14243       return result;
14244     }
14245   else if (TYPE_P (t))
14246     {
14247       /* [basic.link]: A name with no linkage (notably, the name
14248          of a class or enumeration declared in a local scope)
14249          shall not be used to declare an entity with linkage.
14250          This implies that names with no linkage cannot be used as
14251          template arguments
14252
14253          DR 757 relaxes this restriction for C++0x.  */
14254       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
14255                  : no_linkage_check (t, /*relaxed_p=*/false));
14256
14257       if (nt)
14258         {
14259           /* DR 488 makes use of a type with no linkage cause
14260              type deduction to fail.  */
14261           if (complain & tf_error)
14262             {
14263               if (TYPE_ANONYMOUS_P (nt))
14264                 error ("%qT is/uses anonymous type", t);
14265               else
14266                 error ("template argument for %qD uses local type %qT",
14267                        tmpl, t);
14268             }
14269           return true;
14270         }
14271       /* In order to avoid all sorts of complications, we do not
14272          allow variably-modified types as template arguments.  */
14273       else if (variably_modified_type_p (t, NULL_TREE))
14274         {
14275           if (complain & tf_error)
14276             error ("%qT is a variably modified type", t);
14277           return true;
14278         }
14279     }
14280   /* A non-type argument of integral or enumerated type must be a
14281      constant.  */
14282   else if (TREE_TYPE (t)
14283            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
14284            && !TREE_CONSTANT (t))
14285     {
14286       if (complain & tf_error)
14287         error ("integral expression %qE is not constant", t);
14288       return true;
14289     }
14290   return false;
14291 }
14292
14293 static bool
14294 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
14295 {
14296   int ix, len = DECL_NTPARMS (tmpl);
14297   bool result = false;
14298
14299   for (ix = 0; ix != len; ix++)
14300     {
14301       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
14302         result = true;
14303     }
14304   if (result && (complain & tf_error))
14305     error ("  trying to instantiate %qD", tmpl);
14306   return result;
14307 }
14308
14309 /* In C++0x, it's possible to have a function template whose type depends
14310    on itself recursively.  This is most obvious with decltype, but can also
14311    occur with enumeration scope (c++/48969).  So we need to catch infinite
14312    recursion and reject the substitution at deduction time; this function
14313    will return error_mark_node for any repeated substitution.
14314
14315    This also catches excessive recursion such as when f<N> depends on
14316    f<N-1> across all integers, and returns error_mark_node for all the
14317    substitutions back up to the initial one.
14318
14319    This is, of course, not reentrant.  */
14320
14321 static tree
14322 deduction_tsubst_fntype (tree fn, tree targs, tsubst_flags_t complain)
14323 {
14324   static bool excessive_deduction_depth;
14325   static int deduction_depth;
14326   struct pending_template *old_last_pend = last_pending_template;
14327   struct tinst_level *old_error_tinst = last_error_tinst_level;
14328
14329   tree fntype = TREE_TYPE (fn);
14330   tree tinst;
14331   tree r;
14332
14333   if (excessive_deduction_depth)
14334     return error_mark_node;
14335
14336   tinst = build_tree_list (fn, targs);
14337   if (!push_tinst_level (tinst))
14338     {
14339       excessive_deduction_depth = true;
14340       ggc_free (tinst);
14341       return error_mark_node;
14342     }
14343
14344   input_location = DECL_SOURCE_LOCATION (fn);
14345   ++deduction_depth;
14346   push_deduction_access_scope (fn);
14347   r = tsubst (fntype, targs, complain, NULL_TREE);
14348   pop_deduction_access_scope (fn);
14349   --deduction_depth;
14350
14351   if (excessive_deduction_depth)
14352     {
14353       r = error_mark_node;
14354       if (deduction_depth == 0)
14355         /* Reset once we're all the way out.  */
14356         excessive_deduction_depth = false;
14357     }
14358
14359   pop_tinst_level ();
14360   /* We can't free this if a pending_template entry or last_error_tinst_level
14361      is pointing at it.  */
14362   if (last_pending_template == old_last_pend
14363       && last_error_tinst_level == old_error_tinst)
14364     ggc_free (tinst);
14365   return r;
14366 }
14367
14368 /* Instantiate the indicated variable or function template TMPL with
14369    the template arguments in TARG_PTR.  */
14370
14371 static tree
14372 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
14373 {
14374   tree targ_ptr = orig_args;
14375   tree fndecl;
14376   tree gen_tmpl;
14377   tree spec;
14378   HOST_WIDE_INT saved_processing_template_decl;
14379
14380   if (tmpl == error_mark_node)
14381     return error_mark_node;
14382
14383   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
14384
14385   /* If this function is a clone, handle it specially.  */
14386   if (DECL_CLONED_FUNCTION_P (tmpl))
14387     {
14388       tree spec;
14389       tree clone;
14390
14391       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
14392          DECL_CLONED_FUNCTION.  */
14393       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
14394                                    targ_ptr, complain);
14395       if (spec == error_mark_node)
14396         return error_mark_node;
14397
14398       /* Look for the clone.  */
14399       FOR_EACH_CLONE (clone, spec)
14400         if (DECL_NAME (clone) == DECL_NAME (tmpl))
14401           return clone;
14402       /* We should always have found the clone by now.  */
14403       gcc_unreachable ();
14404       return NULL_TREE;
14405     }
14406
14407   /* Check to see if we already have this specialization.  */
14408   gen_tmpl = most_general_template (tmpl);
14409   if (tmpl != gen_tmpl)
14410     /* The TMPL is a partial instantiation.  To get a full set of
14411        arguments we must add the arguments used to perform the
14412        partial instantiation.  */
14413     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
14414                                             targ_ptr);
14415
14416   /* It would be nice to avoid hashing here and then again in tsubst_decl,
14417      but it doesn't seem to be on the hot path.  */
14418   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
14419
14420   gcc_assert (tmpl == gen_tmpl
14421               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
14422                   == spec)
14423               || fndecl == NULL_TREE);
14424
14425   if (spec != NULL_TREE)
14426     return spec;
14427
14428   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
14429                                complain))
14430     return error_mark_node;
14431
14432   /* We are building a FUNCTION_DECL, during which the access of its
14433      parameters and return types have to be checked.  However this
14434      FUNCTION_DECL which is the desired context for access checking
14435      is not built yet.  We solve this chicken-and-egg problem by
14436      deferring all checks until we have the FUNCTION_DECL.  */
14437   push_deferring_access_checks (dk_deferred);
14438
14439   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
14440      (because, for example, we have encountered a non-dependent
14441      function call in the body of a template function and must now
14442      determine which of several overloaded functions will be called),
14443      within the instantiation itself we are not processing a
14444      template.  */  
14445   saved_processing_template_decl = processing_template_decl;
14446   processing_template_decl = 0;
14447   /* Substitute template parameters to obtain the specialization.  */
14448   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
14449                    targ_ptr, complain, gen_tmpl);
14450   processing_template_decl = saved_processing_template_decl;
14451   if (fndecl == error_mark_node)
14452     return error_mark_node;
14453
14454   /* Now we know the specialization, compute access previously
14455      deferred.  */
14456   push_access_scope (fndecl);
14457
14458   /* Some typedefs referenced from within the template code need to be access
14459      checked at template instantiation time, i.e now. These types were
14460      added to the template at parsing time. Let's get those and perfom
14461      the acces checks then.  */
14462   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
14463   perform_deferred_access_checks ();
14464   pop_access_scope (fndecl);
14465   pop_deferring_access_checks ();
14466
14467   /* The DECL_TI_TEMPLATE should always be the immediate parent
14468      template, not the most general template.  */
14469   DECL_TI_TEMPLATE (fndecl) = tmpl;
14470
14471   /* If we've just instantiated the main entry point for a function,
14472      instantiate all the alternate entry points as well.  We do this
14473      by cloning the instantiation of the main entry point, not by
14474      instantiating the template clones.  */
14475   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
14476     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
14477
14478   return fndecl;
14479 }
14480
14481 /* Wrapper for instantiate_template_1.  */
14482
14483 tree
14484 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
14485 {
14486   tree ret;
14487   timevar_push (TV_TEMPLATE_INST);
14488   ret = instantiate_template_1 (tmpl, orig_args,  complain);
14489   timevar_pop (TV_TEMPLATE_INST);
14490   return ret;
14491 }
14492
14493 /* We're going to do deduction substitution on the type of TMPL, a function
14494    template.  In C++11 mode, push into that access scope.  In C++03 mode,
14495    disable access checking.  */
14496
14497 static void
14498 push_deduction_access_scope (tree tmpl)
14499 {
14500   if (cxx_dialect >= cxx0x)
14501     {
14502       int ptd = processing_template_decl;
14503       push_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14504       /* Preserve processing_template_decl across push_to_top_level.  */
14505       if (ptd && !processing_template_decl)
14506         ++processing_template_decl;
14507     }
14508   else
14509     push_deferring_access_checks (dk_no_check);
14510 }
14511
14512 /* And pop back out.  */
14513
14514 static void
14515 pop_deduction_access_scope (tree tmpl)
14516 {
14517   if (cxx_dialect >= cxx0x)
14518     pop_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14519   else
14520     pop_deferring_access_checks ();
14521 }
14522
14523 /* PARM is a template parameter pack for FN.  Returns true iff
14524    PARM is used in a deducible way in the argument list of FN.  */
14525
14526 static bool
14527 pack_deducible_p (tree parm, tree fn)
14528 {
14529   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
14530   for (; t; t = TREE_CHAIN (t))
14531     {
14532       tree type = TREE_VALUE (t);
14533       tree packs;
14534       if (!PACK_EXPANSION_P (type))
14535         continue;
14536       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
14537            packs; packs = TREE_CHAIN (packs))
14538         if (TREE_VALUE (packs) == parm)
14539           {
14540             /* The template parameter pack is used in a function parameter
14541                pack.  If this is the end of the parameter list, the
14542                template parameter pack is deducible.  */
14543             if (TREE_CHAIN (t) == void_list_node)
14544               return true;
14545             else
14546               /* Otherwise, not.  Well, it could be deduced from
14547                  a non-pack parameter, but doing so would end up with
14548                  a deduction mismatch, so don't bother.  */
14549               return false;
14550           }
14551     }
14552   /* The template parameter pack isn't used in any function parameter
14553      packs, but it might be used deeper, e.g. tuple<Args...>.  */
14554   return true;
14555 }
14556
14557 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
14558    NARGS elements of the arguments that are being used when calling
14559    it.  TARGS is a vector into which the deduced template arguments
14560    are placed.
14561
14562    Return zero for success, 2 for an incomplete match that doesn't resolve
14563    all the types, and 1 for complete failure.  An error message will be
14564    printed only for an incomplete match.
14565
14566    If FN is a conversion operator, or we are trying to produce a specific
14567    specialization, RETURN_TYPE is the return type desired.
14568
14569    The EXPLICIT_TARGS are explicit template arguments provided via a
14570    template-id.
14571
14572    The parameter STRICT is one of:
14573
14574    DEDUCE_CALL:
14575      We are deducing arguments for a function call, as in
14576      [temp.deduct.call].
14577
14578    DEDUCE_CONV:
14579      We are deducing arguments for a conversion function, as in
14580      [temp.deduct.conv].
14581
14582    DEDUCE_EXACT:
14583      We are deducing arguments when doing an explicit instantiation
14584      as in [temp.explicit], when determining an explicit specialization
14585      as in [temp.expl.spec], or when taking the address of a function
14586      template, as in [temp.deduct.funcaddr].  */
14587
14588 int
14589 fn_type_unification (tree fn,
14590                      tree explicit_targs,
14591                      tree targs,
14592                      const tree *args,
14593                      unsigned int nargs,
14594                      tree return_type,
14595                      unification_kind_t strict,
14596                      int flags,
14597                      bool explain_p)
14598 {
14599   tree parms;
14600   tree fntype;
14601   int result;
14602
14603   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
14604
14605   fntype = TREE_TYPE (fn);
14606   if (explicit_targs)
14607     {
14608       /* [temp.deduct]
14609
14610          The specified template arguments must match the template
14611          parameters in kind (i.e., type, nontype, template), and there
14612          must not be more arguments than there are parameters;
14613          otherwise type deduction fails.
14614
14615          Nontype arguments must match the types of the corresponding
14616          nontype template parameters, or must be convertible to the
14617          types of the corresponding nontype parameters as specified in
14618          _temp.arg.nontype_, otherwise type deduction fails.
14619
14620          All references in the function type of the function template
14621          to the corresponding template parameters are replaced by the
14622          specified template argument values.  If a substitution in a
14623          template parameter or in the function type of the function
14624          template results in an invalid type, type deduction fails.  */
14625       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
14626       int i, len = TREE_VEC_LENGTH (tparms);
14627       tree converted_args;
14628       bool incomplete = false;
14629
14630       if (explicit_targs == error_mark_node)
14631         return unify_invalid (explain_p);
14632
14633       converted_args
14634         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
14635                                   (explain_p
14636                                    ? tf_warning_or_error
14637                                    : tf_none),
14638                                    /*require_all_args=*/false,
14639                                    /*use_default_args=*/false));
14640       if (converted_args == error_mark_node)
14641         return 1;
14642
14643       /* Substitute the explicit args into the function type.  This is
14644          necessary so that, for instance, explicitly declared function
14645          arguments can match null pointed constants.  If we were given
14646          an incomplete set of explicit args, we must not do semantic
14647          processing during substitution as we could create partial
14648          instantiations.  */
14649       for (i = 0; i < len; i++)
14650         {
14651           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14652           bool parameter_pack = false;
14653           tree targ = TREE_VEC_ELT (converted_args, i);
14654
14655           /* Dig out the actual parm.  */
14656           if (TREE_CODE (parm) == TYPE_DECL
14657               || TREE_CODE (parm) == TEMPLATE_DECL)
14658             {
14659               parm = TREE_TYPE (parm);
14660               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
14661             }
14662           else if (TREE_CODE (parm) == PARM_DECL)
14663             {
14664               parm = DECL_INITIAL (parm);
14665               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
14666             }
14667
14668           if (!parameter_pack && targ == NULL_TREE)
14669             /* No explicit argument for this template parameter.  */
14670             incomplete = true;
14671
14672           if (parameter_pack && pack_deducible_p (parm, fn))
14673             {
14674               /* Mark the argument pack as "incomplete". We could
14675                  still deduce more arguments during unification.
14676                  We remove this mark in type_unification_real.  */
14677               if (targ)
14678                 {
14679                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
14680                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
14681                     = ARGUMENT_PACK_ARGS (targ);
14682                 }
14683
14684               /* We have some incomplete argument packs.  */
14685               incomplete = true;
14686             }
14687         }
14688
14689       processing_template_decl += incomplete;
14690       fntype = deduction_tsubst_fntype (fn, converted_args,
14691                                         (explain_p
14692                                          ? tf_warning_or_error
14693                                          : tf_none));
14694       processing_template_decl -= incomplete;
14695
14696       if (fntype == error_mark_node)
14697         return 1;
14698
14699       /* Place the explicitly specified arguments in TARGS.  */
14700       for (i = NUM_TMPL_ARGS (converted_args); i--;)
14701         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
14702     }
14703
14704   /* Never do unification on the 'this' parameter.  */
14705   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
14706
14707   if (return_type)
14708     {
14709       tree *new_args;
14710
14711       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
14712       new_args = XALLOCAVEC (tree, nargs + 1);
14713       new_args[0] = return_type;
14714       memcpy (new_args + 1, args, nargs * sizeof (tree));
14715       args = new_args;
14716       ++nargs;
14717     }
14718
14719   /* We allow incomplete unification without an error message here
14720      because the standard doesn't seem to explicitly prohibit it.  Our
14721      callers must be ready to deal with unification failures in any
14722      event.  */
14723   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
14724                                   targs, parms, args, nargs, /*subr=*/0,
14725                                   strict, flags, explain_p);
14726
14727   /* Now that we have bindings for all of the template arguments,
14728      ensure that the arguments deduced for the template template
14729      parameters have compatible template parameter lists.  We cannot
14730      check this property before we have deduced all template
14731      arguments, because the template parameter types of a template
14732      template parameter might depend on prior template parameters
14733      deduced after the template template parameter.  The following
14734      ill-formed example illustrates this issue:
14735
14736        template<typename T, template<T> class C> void f(C<5>, T);
14737
14738        template<int N> struct X {};
14739
14740        void g() {
14741          f(X<5>(), 5l); // error: template argument deduction fails
14742        }
14743
14744      The template parameter list of 'C' depends on the template type
14745      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
14746      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
14747      time that we deduce 'C'.  */
14748   if (result == 0
14749       && !template_template_parm_bindings_ok_p 
14750            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
14751     return unify_inconsistent_template_template_parameters (explain_p);
14752
14753   if (result == 0)
14754     /* All is well so far.  Now, check:
14755
14756        [temp.deduct]
14757
14758        When all template arguments have been deduced, all uses of
14759        template parameters in nondeduced contexts are replaced with
14760        the corresponding deduced argument values.  If the
14761        substitution results in an invalid type, as described above,
14762        type deduction fails.  */
14763     {
14764       tree substed = deduction_tsubst_fntype (fn, targs,
14765                                               (explain_p
14766                                                ? tf_warning_or_error
14767                                                : tf_none));
14768       if (substed == error_mark_node)
14769         return 1;
14770
14771       /* If we're looking for an exact match, check that what we got
14772          is indeed an exact match.  It might not be if some template
14773          parameters are used in non-deduced contexts.  */
14774       if (strict == DEDUCE_EXACT)
14775         {
14776           unsigned int i;
14777
14778           tree sarg
14779             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
14780           if (return_type)
14781             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
14782           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
14783             if (!same_type_p (args[i], TREE_VALUE (sarg)))
14784               return unify_type_mismatch (explain_p, args[i],
14785                                           TREE_VALUE (sarg));
14786         }
14787     }
14788
14789   return result;
14790 }
14791
14792 /* Adjust types before performing type deduction, as described in
14793    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
14794    sections are symmetric.  PARM is the type of a function parameter
14795    or the return type of the conversion function.  ARG is the type of
14796    the argument passed to the call, or the type of the value
14797    initialized with the result of the conversion function.
14798    ARG_EXPR is the original argument expression, which may be null.  */
14799
14800 static int
14801 maybe_adjust_types_for_deduction (unification_kind_t strict,
14802                                   tree* parm,
14803                                   tree* arg,
14804                                   tree arg_expr)
14805 {
14806   int result = 0;
14807
14808   switch (strict)
14809     {
14810     case DEDUCE_CALL:
14811       break;
14812
14813     case DEDUCE_CONV:
14814       {
14815         /* Swap PARM and ARG throughout the remainder of this
14816            function; the handling is precisely symmetric since PARM
14817            will initialize ARG rather than vice versa.  */
14818         tree* temp = parm;
14819         parm = arg;
14820         arg = temp;
14821         break;
14822       }
14823
14824     case DEDUCE_EXACT:
14825       /* Core issue #873: Do the DR606 thing (see below) for these cases,
14826          too, but here handle it by stripping the reference from PARM
14827          rather than by adding it to ARG.  */
14828       if (TREE_CODE (*parm) == REFERENCE_TYPE
14829           && TYPE_REF_IS_RVALUE (*parm)
14830           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14831           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14832           && TREE_CODE (*arg) == REFERENCE_TYPE
14833           && !TYPE_REF_IS_RVALUE (*arg))
14834         *parm = TREE_TYPE (*parm);
14835       /* Nothing else to do in this case.  */
14836       return 0;
14837
14838     default:
14839       gcc_unreachable ();
14840     }
14841
14842   if (TREE_CODE (*parm) != REFERENCE_TYPE)
14843     {
14844       /* [temp.deduct.call]
14845
14846          If P is not a reference type:
14847
14848          --If A is an array type, the pointer type produced by the
14849          array-to-pointer standard conversion (_conv.array_) is
14850          used in place of A for type deduction; otherwise,
14851
14852          --If A is a function type, the pointer type produced by
14853          the function-to-pointer standard conversion
14854          (_conv.func_) is used in place of A for type deduction;
14855          otherwise,
14856
14857          --If A is a cv-qualified type, the top level
14858          cv-qualifiers of A's type are ignored for type
14859          deduction.  */
14860       if (TREE_CODE (*arg) == ARRAY_TYPE)
14861         *arg = build_pointer_type (TREE_TYPE (*arg));
14862       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
14863         *arg = build_pointer_type (*arg);
14864       else
14865         *arg = TYPE_MAIN_VARIANT (*arg);
14866     }
14867
14868   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
14869      of the form T&&, where T is a template parameter, and the argument
14870      is an lvalue, T is deduced as A& */
14871   if (TREE_CODE (*parm) == REFERENCE_TYPE
14872       && TYPE_REF_IS_RVALUE (*parm)
14873       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14874       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14875       && (arg_expr ? real_lvalue_p (arg_expr)
14876           /* try_one_overload doesn't provide an arg_expr, but
14877              functions are always lvalues.  */
14878           : TREE_CODE (*arg) == FUNCTION_TYPE))
14879     *arg = build_reference_type (*arg);
14880
14881   /* [temp.deduct.call]
14882
14883      If P is a cv-qualified type, the top level cv-qualifiers
14884      of P's type are ignored for type deduction.  If P is a
14885      reference type, the type referred to by P is used for
14886      type deduction.  */
14887   *parm = TYPE_MAIN_VARIANT (*parm);
14888   if (TREE_CODE (*parm) == REFERENCE_TYPE)
14889     {
14890       *parm = TREE_TYPE (*parm);
14891       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14892     }
14893
14894   /* DR 322. For conversion deduction, remove a reference type on parm
14895      too (which has been swapped into ARG).  */
14896   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
14897     *arg = TREE_TYPE (*arg);
14898
14899   return result;
14900 }
14901
14902 /* Subroutine of unify_one_argument.  PARM is a function parameter of a
14903    template which does contain any deducible template parameters; check if
14904    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
14905    unify_one_argument.  */
14906
14907 static int
14908 check_non_deducible_conversion (tree parm, tree arg, int strict,
14909                                 int flags, bool explain_p)
14910 {
14911   tree type;
14912
14913   if (!TYPE_P (arg))
14914     type = TREE_TYPE (arg);
14915   else
14916     type = arg;
14917
14918   if (same_type_p (parm, type))
14919     return unify_success (explain_p);
14920
14921   if (strict == DEDUCE_CONV)
14922     {
14923       if (can_convert_arg (type, parm, NULL_TREE, flags))
14924         return unify_success (explain_p);
14925     }
14926   else if (strict != DEDUCE_EXACT)
14927     {
14928       if (can_convert_arg (parm, type,
14929                            TYPE_P (arg) ? NULL_TREE : arg,
14930                            flags))
14931         return unify_success (explain_p);
14932     }
14933
14934   if (strict == DEDUCE_EXACT)
14935     return unify_type_mismatch (explain_p, parm, arg);
14936   else
14937     return unify_arg_conversion (explain_p, parm, type, arg);
14938 }
14939
14940 /* Subroutine of type_unification_real and unify_pack_expansion to
14941    handle unification of a single P/A pair.  Parameters are as
14942    for those functions.  */
14943
14944 static int
14945 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
14946                     int subr, unification_kind_t strict, int flags,
14947                     bool explain_p)
14948 {
14949   tree arg_expr = NULL_TREE;
14950   int arg_strict;
14951
14952   if (arg == error_mark_node || parm == error_mark_node)
14953     return unify_invalid (explain_p);
14954   if (arg == unknown_type_node)
14955     /* We can't deduce anything from this, but we might get all the
14956        template args from other function args.  */
14957     return unify_success (explain_p);
14958
14959   /* FIXME uses_deducible_template_parms */
14960   if (TYPE_P (parm) && !uses_template_parms (parm))
14961     return check_non_deducible_conversion (parm, arg, strict, flags,
14962                                            explain_p);
14963
14964   switch (strict)
14965     {
14966     case DEDUCE_CALL:
14967       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
14968                     | UNIFY_ALLOW_MORE_CV_QUAL
14969                     | UNIFY_ALLOW_DERIVED);
14970       break;
14971
14972     case DEDUCE_CONV:
14973       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14974       break;
14975
14976     case DEDUCE_EXACT:
14977       arg_strict = UNIFY_ALLOW_NONE;
14978       break;
14979
14980     default:
14981       gcc_unreachable ();
14982     }
14983
14984   /* We only do these transformations if this is the top-level
14985      parameter_type_list in a call or declaration matching; in other
14986      situations (nested function declarators, template argument lists) we
14987      won't be comparing a type to an expression, and we don't do any type
14988      adjustments.  */
14989   if (!subr)
14990     {
14991       if (!TYPE_P (arg))
14992         {
14993           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14994           if (type_unknown_p (arg))
14995             {
14996               /* [temp.deduct.type] A template-argument can be
14997                  deduced from a pointer to function or pointer
14998                  to member function argument if the set of
14999                  overloaded functions does not contain function
15000                  templates and at most one of a set of
15001                  overloaded functions provides a unique
15002                  match.  */
15003
15004               if (resolve_overloaded_unification
15005                   (tparms, targs, parm, arg, strict,
15006                    arg_strict, explain_p))
15007                 return unify_success (explain_p);
15008               return unify_overload_resolution_failure (explain_p, arg);
15009             }
15010
15011           arg_expr = arg;
15012           arg = unlowered_expr_type (arg);
15013           if (arg == error_mark_node)
15014             return unify_invalid (explain_p);
15015         }
15016
15017       arg_strict |=
15018         maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
15019     }
15020   else
15021     gcc_assert ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
15022                 == (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL));
15023
15024   /* For deduction from an init-list we need the actual list.  */
15025   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
15026     arg = arg_expr;
15027   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
15028 }
15029
15030 /* Most parms like fn_type_unification.
15031
15032    If SUBR is 1, we're being called recursively (to unify the
15033    arguments of a function or method parameter of a function
15034    template). */
15035
15036 static int
15037 type_unification_real (tree tparms,
15038                        tree targs,
15039                        tree xparms,
15040                        const tree *xargs,
15041                        unsigned int xnargs,
15042                        int subr,
15043                        unification_kind_t strict,
15044                        int flags,
15045                        bool explain_p)
15046 {
15047   tree parm, arg;
15048   int i;
15049   int ntparms = TREE_VEC_LENGTH (tparms);
15050   int saw_undeduced = 0;
15051   tree parms;
15052   const tree *args;
15053   unsigned int nargs;
15054   unsigned int ia;
15055
15056   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
15057   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
15058   gcc_assert (ntparms > 0);
15059
15060   /* Reset the number of non-defaulted template arguments contained
15061      in TARGS.  */
15062   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
15063
15064  again:
15065   parms = xparms;
15066   args = xargs;
15067   nargs = xnargs;
15068
15069   ia = 0;
15070   while (parms && parms != void_list_node
15071          && ia < nargs)
15072     {
15073       parm = TREE_VALUE (parms);
15074
15075       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
15076           && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
15077         /* For a function parameter pack that occurs at the end of the
15078            parameter-declaration-list, the type A of each remaining
15079            argument of the call is compared with the type P of the
15080            declarator-id of the function parameter pack.  */
15081         break;
15082
15083       parms = TREE_CHAIN (parms);
15084
15085       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
15086         /* For a function parameter pack that does not occur at the
15087            end of the parameter-declaration-list, the type of the
15088            parameter pack is a non-deduced context.  */
15089         continue;
15090
15091       arg = args[ia];
15092       ++ia;
15093
15094       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
15095                               flags, explain_p))
15096         return 1;
15097     }
15098
15099   if (parms 
15100       && parms != void_list_node
15101       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
15102     {
15103       /* Unify the remaining arguments with the pack expansion type.  */
15104       tree argvec;
15105       tree parmvec = make_tree_vec (1);
15106
15107       /* Allocate a TREE_VEC and copy in all of the arguments */ 
15108       argvec = make_tree_vec (nargs - ia);
15109       for (i = 0; ia < nargs; ++ia, ++i)
15110         TREE_VEC_ELT (argvec, i) = args[ia];
15111
15112       /* Copy the parameter into parmvec.  */
15113       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
15114       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
15115                                 /*subr=*/subr, explain_p))
15116         return 1;
15117
15118       /* Advance to the end of the list of parameters.  */
15119       parms = TREE_CHAIN (parms);
15120     }
15121
15122   /* Fail if we've reached the end of the parm list, and more args
15123      are present, and the parm list isn't variadic.  */
15124   if (ia < nargs && parms == void_list_node)
15125     return unify_too_many_arguments (explain_p, nargs, ia);
15126   /* Fail if parms are left and they don't have default values.  */
15127   if (parms && parms != void_list_node
15128       && TREE_PURPOSE (parms) == NULL_TREE)
15129     {
15130       unsigned int count = nargs;
15131       tree p = parms;
15132       while (p && p != void_list_node)
15133         {
15134           count++;
15135           p = TREE_CHAIN (p);
15136         }
15137       return unify_too_few_arguments (explain_p, ia, count);
15138     }
15139
15140   if (!subr)
15141     {
15142       tsubst_flags_t complain = (explain_p
15143                                  ? tf_warning_or_error
15144                                  : tf_none);
15145
15146       /* Check to see if we need another pass before we start clearing
15147          ARGUMENT_PACK_INCOMPLETE_P.  */
15148       for (i = 0; i < ntparms; i++)
15149         {
15150           tree targ = TREE_VEC_ELT (targs, i);
15151           tree tparm = TREE_VEC_ELT (tparms, i);
15152
15153           if (targ || tparm == error_mark_node)
15154             continue;
15155           tparm = TREE_VALUE (tparm);
15156
15157           /* If this is an undeduced nontype parameter that depends on
15158              a type parameter, try another pass; its type may have been
15159              deduced from a later argument than the one from which
15160              this parameter can be deduced.  */
15161           if (TREE_CODE (tparm) == PARM_DECL
15162               && uses_template_parms (TREE_TYPE (tparm))
15163               && !saw_undeduced++)
15164             goto again;
15165         }
15166
15167       for (i = 0; i < ntparms; i++)
15168         {
15169           tree targ = TREE_VEC_ELT (targs, i);
15170           tree tparm = TREE_VEC_ELT (tparms, i);
15171
15172           /* Clear the "incomplete" flags on all argument packs now so that
15173              substituting them into later default arguments works.  */
15174           if (targ && ARGUMENT_PACK_P (targ))
15175             {
15176               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
15177               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
15178             }
15179
15180           if (targ || tparm == error_mark_node)
15181             continue;
15182           tparm = TREE_VALUE (tparm);
15183
15184           /* Core issue #226 (C++0x) [temp.deduct]:
15185
15186              If a template argument has not been deduced, its
15187              default template argument, if any, is used. 
15188
15189              When we are in C++98 mode, TREE_PURPOSE will either
15190              be NULL_TREE or ERROR_MARK_NODE, so we do not need
15191              to explicitly check cxx_dialect here.  */
15192           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
15193             {
15194               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
15195               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
15196               arg = tsubst_template_arg (arg, targs, complain, NULL_TREE);
15197               arg = convert_template_argument (parm, arg, targs, complain,
15198                                                i, NULL_TREE);
15199               if (arg == error_mark_node)
15200                 return 1;
15201               else
15202                 {
15203                   TREE_VEC_ELT (targs, i) = arg;
15204                   /* The position of the first default template argument,
15205                      is also the number of non-defaulted arguments in TARGS.
15206                      Record that.  */
15207                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
15208                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
15209                   continue;
15210                 }
15211             }
15212
15213           /* If the type parameter is a parameter pack, then it will
15214              be deduced to an empty parameter pack.  */
15215           if (template_parameter_pack_p (tparm))
15216             {
15217               tree arg;
15218
15219               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
15220                 {
15221                   arg = make_node (NONTYPE_ARGUMENT_PACK);
15222                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
15223                   TREE_CONSTANT (arg) = 1;
15224                 }
15225               else
15226                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
15227
15228               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
15229
15230               TREE_VEC_ELT (targs, i) = arg;
15231               continue;
15232             }
15233
15234           return unify_parameter_deduction_failure (explain_p, tparm);
15235         }
15236     }
15237 #ifdef ENABLE_CHECKING
15238   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
15239     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
15240 #endif
15241
15242   return unify_success (explain_p);
15243 }
15244
15245 /* Subroutine of type_unification_real.  Args are like the variables
15246    at the call site.  ARG is an overloaded function (or template-id);
15247    we try deducing template args from each of the overloads, and if
15248    only one succeeds, we go with that.  Modifies TARGS and returns
15249    true on success.  */
15250
15251 static bool
15252 resolve_overloaded_unification (tree tparms,
15253                                 tree targs,
15254                                 tree parm,
15255                                 tree arg,
15256                                 unification_kind_t strict,
15257                                 int sub_strict,
15258                                 bool explain_p)
15259 {
15260   tree tempargs = copy_node (targs);
15261   int good = 0;
15262   tree goodfn = NULL_TREE;
15263   bool addr_p;
15264
15265   if (TREE_CODE (arg) == ADDR_EXPR)
15266     {
15267       arg = TREE_OPERAND (arg, 0);
15268       addr_p = true;
15269     }
15270   else
15271     addr_p = false;
15272
15273   if (TREE_CODE (arg) == COMPONENT_REF)
15274     /* Handle `&x' where `x' is some static or non-static member
15275        function name.  */
15276     arg = TREE_OPERAND (arg, 1);
15277
15278   if (TREE_CODE (arg) == OFFSET_REF)
15279     arg = TREE_OPERAND (arg, 1);
15280
15281   /* Strip baselink information.  */
15282   if (BASELINK_P (arg))
15283     arg = BASELINK_FUNCTIONS (arg);
15284
15285   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
15286     {
15287       /* If we got some explicit template args, we need to plug them into
15288          the affected templates before we try to unify, in case the
15289          explicit args will completely resolve the templates in question.  */
15290
15291       int ok = 0;
15292       tree expl_subargs = TREE_OPERAND (arg, 1);
15293       arg = TREE_OPERAND (arg, 0);
15294
15295       for (; arg; arg = OVL_NEXT (arg))
15296         {
15297           tree fn = OVL_CURRENT (arg);
15298           tree subargs, elem;
15299
15300           if (TREE_CODE (fn) != TEMPLATE_DECL)
15301             continue;
15302
15303           ++processing_template_decl;
15304           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
15305                                   expl_subargs, /*check_ret=*/false);
15306           if (subargs && !any_dependent_template_arguments_p (subargs))
15307             {
15308               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
15309               if (try_one_overload (tparms, targs, tempargs, parm,
15310                                     elem, strict, sub_strict, addr_p, explain_p)
15311                   && (!goodfn || !decls_match (goodfn, elem)))
15312                 {
15313                   goodfn = elem;
15314                   ++good;
15315                 }
15316             }
15317           else if (subargs)
15318             ++ok;
15319           --processing_template_decl;
15320         }
15321       /* If no templates (or more than one) are fully resolved by the
15322          explicit arguments, this template-id is a non-deduced context; it
15323          could still be OK if we deduce all template arguments for the
15324          enclosing call through other arguments.  */
15325       if (good != 1)
15326         good = ok;
15327     }
15328   else if (TREE_CODE (arg) != OVERLOAD
15329            && TREE_CODE (arg) != FUNCTION_DECL)
15330     /* If ARG is, for example, "(0, &f)" then its type will be unknown
15331        -- but the deduction does not succeed because the expression is
15332        not just the function on its own.  */
15333     return false;
15334   else
15335     for (; arg; arg = OVL_NEXT (arg))
15336       if (try_one_overload (tparms, targs, tempargs, parm,
15337                             TREE_TYPE (OVL_CURRENT (arg)),
15338                             strict, sub_strict, addr_p, explain_p)
15339           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
15340         {
15341           goodfn = OVL_CURRENT (arg);
15342           ++good;
15343         }
15344
15345   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15346      to function or pointer to member function argument if the set of
15347      overloaded functions does not contain function templates and at most
15348      one of a set of overloaded functions provides a unique match.
15349
15350      So if we found multiple possibilities, we return success but don't
15351      deduce anything.  */
15352
15353   if (good == 1)
15354     {
15355       int i = TREE_VEC_LENGTH (targs);
15356       for (; i--; )
15357         if (TREE_VEC_ELT (tempargs, i))
15358           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
15359     }
15360   if (good)
15361     return true;
15362
15363   return false;
15364 }
15365
15366 /* Core DR 115: In contexts where deduction is done and fails, or in
15367    contexts where deduction is not done, if a template argument list is
15368    specified and it, along with any default template arguments, identifies
15369    a single function template specialization, then the template-id is an
15370    lvalue for the function template specialization.  */
15371
15372 tree
15373 resolve_nondeduced_context (tree orig_expr)
15374 {
15375   tree expr, offset, baselink;
15376   bool addr;
15377
15378   if (!type_unknown_p (orig_expr))
15379     return orig_expr;
15380
15381   expr = orig_expr;
15382   addr = false;
15383   offset = NULL_TREE;
15384   baselink = NULL_TREE;
15385
15386   if (TREE_CODE (expr) == ADDR_EXPR)
15387     {
15388       expr = TREE_OPERAND (expr, 0);
15389       addr = true;
15390     }
15391   if (TREE_CODE (expr) == OFFSET_REF)
15392     {
15393       offset = expr;
15394       expr = TREE_OPERAND (expr, 1);
15395     }
15396   if (BASELINK_P (expr))
15397     {
15398       baselink = expr;
15399       expr = BASELINK_FUNCTIONS (expr);
15400     }
15401
15402   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
15403     {
15404       int good = 0;
15405       tree goodfn = NULL_TREE;
15406
15407       /* If we got some explicit template args, we need to plug them into
15408          the affected templates before we try to unify, in case the
15409          explicit args will completely resolve the templates in question.  */
15410
15411       tree expl_subargs = TREE_OPERAND (expr, 1);
15412       tree arg = TREE_OPERAND (expr, 0);
15413       tree badfn = NULL_TREE;
15414       tree badargs = NULL_TREE;
15415
15416       for (; arg; arg = OVL_NEXT (arg))
15417         {
15418           tree fn = OVL_CURRENT (arg);
15419           tree subargs, elem;
15420
15421           if (TREE_CODE (fn) != TEMPLATE_DECL)
15422             continue;
15423
15424           ++processing_template_decl;
15425           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
15426                                   expl_subargs, /*check_ret=*/false);
15427           if (subargs && !any_dependent_template_arguments_p (subargs))
15428             {
15429               elem = instantiate_template (fn, subargs, tf_none);
15430               if (elem == error_mark_node)
15431                 {
15432                   badfn = fn;
15433                   badargs = subargs;
15434                 }
15435               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
15436                 {
15437                   goodfn = elem;
15438                   ++good;
15439                 }
15440             }
15441           --processing_template_decl;
15442         }
15443       if (good == 1)
15444         {
15445           mark_used (goodfn);
15446           expr = goodfn;
15447           if (baselink)
15448             expr = build_baselink (BASELINK_BINFO (baselink),
15449                                    BASELINK_ACCESS_BINFO (baselink),
15450                                    expr, BASELINK_OPTYPE (baselink));
15451           if (offset)
15452             {
15453               tree base
15454                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
15455               expr = build_offset_ref (base, expr, addr);
15456             }
15457           if (addr)
15458             expr = cp_build_addr_expr (expr, tf_warning_or_error);
15459           return expr;
15460         }
15461       else if (good == 0 && badargs)
15462         /* There were no good options and at least one bad one, so let the
15463            user know what the problem is.  */
15464         instantiate_template (badfn, badargs, tf_warning_or_error);
15465     }
15466   return orig_expr;
15467 }
15468
15469 /* Subroutine of resolve_overloaded_unification; does deduction for a single
15470    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
15471    different overloads deduce different arguments for a given parm.
15472    ADDR_P is true if the expression for which deduction is being
15473    performed was of the form "& fn" rather than simply "fn".
15474
15475    Returns 1 on success.  */
15476
15477 static int
15478 try_one_overload (tree tparms,
15479                   tree orig_targs,
15480                   tree targs,
15481                   tree parm,
15482                   tree arg,
15483                   unification_kind_t strict,
15484                   int sub_strict,
15485                   bool addr_p,
15486                   bool explain_p)
15487 {
15488   int nargs;
15489   tree tempargs;
15490   int i;
15491
15492   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15493      to function or pointer to member function argument if the set of
15494      overloaded functions does not contain function templates and at most
15495      one of a set of overloaded functions provides a unique match.
15496
15497      So if this is a template, just return success.  */
15498
15499   if (uses_template_parms (arg))
15500     return 1;
15501
15502   if (TREE_CODE (arg) == METHOD_TYPE)
15503     arg = build_ptrmemfunc_type (build_pointer_type (arg));
15504   else if (addr_p)
15505     arg = build_pointer_type (arg);
15506
15507   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
15508
15509   /* We don't copy orig_targs for this because if we have already deduced
15510      some template args from previous args, unify would complain when we
15511      try to deduce a template parameter for the same argument, even though
15512      there isn't really a conflict.  */
15513   nargs = TREE_VEC_LENGTH (targs);
15514   tempargs = make_tree_vec (nargs);
15515
15516   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
15517     return 0;
15518
15519   /* First make sure we didn't deduce anything that conflicts with
15520      explicitly specified args.  */
15521   for (i = nargs; i--; )
15522     {
15523       tree elt = TREE_VEC_ELT (tempargs, i);
15524       tree oldelt = TREE_VEC_ELT (orig_targs, i);
15525
15526       if (!elt)
15527         /*NOP*/;
15528       else if (uses_template_parms (elt))
15529         /* Since we're unifying against ourselves, we will fill in
15530            template args used in the function parm list with our own
15531            template parms.  Discard them.  */
15532         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
15533       else if (oldelt && !template_args_equal (oldelt, elt))
15534         return 0;
15535     }
15536
15537   for (i = nargs; i--; )
15538     {
15539       tree elt = TREE_VEC_ELT (tempargs, i);
15540
15541       if (elt)
15542         TREE_VEC_ELT (targs, i) = elt;
15543     }
15544
15545   return 1;
15546 }
15547
15548 /* PARM is a template class (perhaps with unbound template
15549    parameters).  ARG is a fully instantiated type.  If ARG can be
15550    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
15551    TARGS are as for unify.  */
15552
15553 static tree
15554 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
15555                        bool explain_p)
15556 {
15557   tree copy_of_targs;
15558
15559   if (!CLASSTYPE_TEMPLATE_INFO (arg)
15560       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
15561           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
15562     return NULL_TREE;
15563
15564   /* We need to make a new template argument vector for the call to
15565      unify.  If we used TARGS, we'd clutter it up with the result of
15566      the attempted unification, even if this class didn't work out.
15567      We also don't want to commit ourselves to all the unifications
15568      we've already done, since unification is supposed to be done on
15569      an argument-by-argument basis.  In other words, consider the
15570      following pathological case:
15571
15572        template <int I, int J, int K>
15573        struct S {};
15574
15575        template <int I, int J>
15576        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
15577
15578        template <int I, int J, int K>
15579        void f(S<I, J, K>, S<I, I, I>);
15580
15581        void g() {
15582          S<0, 0, 0> s0;
15583          S<0, 1, 2> s2;
15584
15585          f(s0, s2);
15586        }
15587
15588      Now, by the time we consider the unification involving `s2', we
15589      already know that we must have `f<0, 0, 0>'.  But, even though
15590      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
15591      because there are two ways to unify base classes of S<0, 1, 2>
15592      with S<I, I, I>.  If we kept the already deduced knowledge, we
15593      would reject the possibility I=1.  */
15594   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
15595
15596   /* If unification failed, we're done.  */
15597   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
15598              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
15599     return NULL_TREE;
15600
15601   return arg;
15602 }
15603
15604 /* Given a template type PARM and a class type ARG, find the unique
15605    base type in ARG that is an instance of PARM.  We do not examine
15606    ARG itself; only its base-classes.  If there is not exactly one
15607    appropriate base class, return NULL_TREE.  PARM may be the type of
15608    a partial specialization, as well as a plain template type.  Used
15609    by unify.  */
15610
15611 static enum template_base_result
15612 get_template_base (tree tparms, tree targs, tree parm, tree arg,
15613                    bool explain_p, tree *result)
15614 {
15615   tree rval = NULL_TREE;
15616   tree binfo;
15617
15618   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
15619
15620   binfo = TYPE_BINFO (complete_type (arg));
15621   if (!binfo)
15622     {
15623       /* The type could not be completed.  */
15624       *result = NULL_TREE;
15625       return tbr_incomplete_type;
15626     }
15627
15628   /* Walk in inheritance graph order.  The search order is not
15629      important, and this avoids multiple walks of virtual bases.  */
15630   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
15631     {
15632       tree r = try_class_unification (tparms, targs, parm,
15633                                       BINFO_TYPE (binfo), explain_p);
15634
15635       if (r)
15636         {
15637           /* If there is more than one satisfactory baseclass, then:
15638
15639                [temp.deduct.call]
15640
15641               If they yield more than one possible deduced A, the type
15642               deduction fails.
15643
15644              applies.  */
15645           if (rval && !same_type_p (r, rval))
15646             {
15647               *result = NULL_TREE;
15648               return tbr_ambiguous_baseclass;
15649             }
15650
15651           rval = r;
15652         }
15653     }
15654
15655   *result = rval;
15656   return tbr_success;
15657 }
15658
15659 /* Returns the level of DECL, which declares a template parameter.  */
15660
15661 static int
15662 template_decl_level (tree decl)
15663 {
15664   switch (TREE_CODE (decl))
15665     {
15666     case TYPE_DECL:
15667     case TEMPLATE_DECL:
15668       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
15669
15670     case PARM_DECL:
15671       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
15672
15673     default:
15674       gcc_unreachable ();
15675     }
15676   return 0;
15677 }
15678
15679 /* Decide whether ARG can be unified with PARM, considering only the
15680    cv-qualifiers of each type, given STRICT as documented for unify.
15681    Returns nonzero iff the unification is OK on that basis.  */
15682
15683 static int
15684 check_cv_quals_for_unify (int strict, tree arg, tree parm)
15685 {
15686   int arg_quals = cp_type_quals (arg);
15687   int parm_quals = cp_type_quals (parm);
15688
15689   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15690       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15691     {
15692       /*  Although a CVR qualifier is ignored when being applied to a
15693           substituted template parameter ([8.3.2]/1 for example), that
15694           does not allow us to unify "const T" with "int&" because both
15695           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
15696           It is ok when we're allowing additional CV qualifiers
15697           at the outer level [14.8.2.1]/3,1st bullet.  */
15698       if ((TREE_CODE (arg) == REFERENCE_TYPE
15699            || TREE_CODE (arg) == FUNCTION_TYPE
15700            || TREE_CODE (arg) == METHOD_TYPE)
15701           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
15702         return 0;
15703
15704       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
15705           && (parm_quals & TYPE_QUAL_RESTRICT))
15706         return 0;
15707     }
15708
15709   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15710       && (arg_quals & parm_quals) != parm_quals)
15711     return 0;
15712
15713   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
15714       && (parm_quals & arg_quals) != arg_quals)
15715     return 0;
15716
15717   return 1;
15718 }
15719
15720 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
15721 void 
15722 template_parm_level_and_index (tree parm, int* level, int* index)
15723 {
15724   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15725       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15726       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15727     {
15728       *index = TEMPLATE_TYPE_IDX (parm);
15729       *level = TEMPLATE_TYPE_LEVEL (parm);
15730     }
15731   else
15732     {
15733       *index = TEMPLATE_PARM_IDX (parm);
15734       *level = TEMPLATE_PARM_LEVEL (parm);
15735     }
15736 }
15737
15738 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)                    \
15739   do {                                                                  \
15740     if (unify (TP, TA, P, A, S, EP))                                    \
15741       return 1;                                                         \
15742   } while (0);
15743
15744 /* Unifies the remaining arguments in PACKED_ARGS with the pack
15745    expansion at the end of PACKED_PARMS. Returns 0 if the type
15746    deduction succeeds, 1 otherwise. STRICT is the same as in
15747    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
15748    call argument list. We'll need to adjust the arguments to make them
15749    types. SUBR tells us if this is from a recursive call to
15750    type_unification_real, or for comparing two template argument
15751    lists. */
15752
15753 static int
15754 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
15755                       tree packed_args, unification_kind_t strict,
15756                       bool subr, bool explain_p)
15757 {
15758   tree parm 
15759     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
15760   tree pattern = PACK_EXPANSION_PATTERN (parm);
15761   tree pack, packs = NULL_TREE;
15762   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
15763   int len = TREE_VEC_LENGTH (packed_args);
15764
15765   /* Determine the parameter packs we will be deducing from the
15766      pattern, and record their current deductions.  */
15767   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
15768        pack; pack = TREE_CHAIN (pack))
15769     {
15770       tree parm_pack = TREE_VALUE (pack);
15771       int idx, level;
15772
15773       /* Determine the index and level of this parameter pack.  */
15774       template_parm_level_and_index (parm_pack, &level, &idx);
15775
15776       /* Keep track of the parameter packs and their corresponding
15777          argument packs.  */
15778       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
15779       TREE_TYPE (packs) = make_tree_vec (len - start);
15780     }
15781   
15782   /* Loop through all of the arguments that have not yet been
15783      unified and unify each with the pattern.  */
15784   for (i = start; i < len; i++)
15785     {
15786       tree parm;
15787       bool any_explicit = false;
15788       tree arg = TREE_VEC_ELT (packed_args, i);
15789
15790       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
15791          or the element of its argument pack at the current index if
15792          this argument was explicitly specified.  */
15793       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15794         {
15795           int idx, level;
15796           tree arg, pargs;
15797           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15798
15799           arg = NULL_TREE;
15800           if (TREE_VALUE (pack)
15801               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
15802               && (i < TREE_VEC_LENGTH (pargs)))
15803             {
15804               any_explicit = true;
15805               arg = TREE_VEC_ELT (pargs, i);
15806             }
15807           TMPL_ARG (targs, level, idx) = arg;
15808         }
15809
15810       /* If we had explicit template arguments, substitute them into the
15811          pattern before deduction.  */
15812       if (any_explicit)
15813         {
15814           /* Some arguments might still be unspecified or dependent.  */
15815           bool dependent;
15816           ++processing_template_decl;
15817           dependent = any_dependent_template_arguments_p (targs);
15818           if (!dependent)
15819             --processing_template_decl;
15820           parm = tsubst (pattern, targs,
15821                          explain_p ? tf_warning_or_error : tf_none,
15822                          NULL_TREE);
15823           if (dependent)
15824             --processing_template_decl;
15825           if (parm == error_mark_node)
15826             return 1;
15827         }
15828       else
15829         parm = pattern;
15830
15831       /* Unify the pattern with the current argument.  */
15832       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
15833                               LOOKUP_IMPLICIT, explain_p))
15834         return 1;
15835
15836       /* For each parameter pack, collect the deduced value.  */
15837       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15838         {
15839           int idx, level;
15840           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15841
15842           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
15843             TMPL_ARG (targs, level, idx);
15844         }
15845     }
15846
15847   /* Verify that the results of unification with the parameter packs
15848      produce results consistent with what we've seen before, and make
15849      the deduced argument packs available.  */
15850   for (pack = packs; pack; pack = TREE_CHAIN (pack))
15851     {
15852       tree old_pack = TREE_VALUE (pack);
15853       tree new_args = TREE_TYPE (pack);
15854       int i, len = TREE_VEC_LENGTH (new_args);
15855       int idx, level;
15856       bool nondeduced_p = false;
15857
15858       /* By default keep the original deduced argument pack.
15859          If necessary, more specific code is going to update the
15860          resulting deduced argument later down in this function.  */
15861       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15862       TMPL_ARG (targs, level, idx) = old_pack;
15863
15864       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
15865          actually deduce anything.  */
15866       for (i = 0; i < len && !nondeduced_p; ++i)
15867         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
15868           nondeduced_p = true;
15869       if (nondeduced_p)
15870         continue;
15871
15872       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
15873         {
15874           /* If we had fewer function args than explicit template args,
15875              just use the explicits.  */
15876           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15877           int explicit_len = TREE_VEC_LENGTH (explicit_args);
15878           if (len < explicit_len)
15879             new_args = explicit_args;
15880         }
15881
15882       if (!old_pack)
15883         {
15884           tree result;
15885           /* Build the deduced *_ARGUMENT_PACK.  */
15886           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
15887             {
15888               result = make_node (NONTYPE_ARGUMENT_PACK);
15889               TREE_TYPE (result) = 
15890                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
15891               TREE_CONSTANT (result) = 1;
15892             }
15893           else
15894             result = cxx_make_type (TYPE_ARGUMENT_PACK);
15895
15896           SET_ARGUMENT_PACK_ARGS (result, new_args);
15897
15898           /* Note the deduced argument packs for this parameter
15899              pack.  */
15900           TMPL_ARG (targs, level, idx) = result;
15901         }
15902       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
15903                && (ARGUMENT_PACK_ARGS (old_pack) 
15904                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
15905         {
15906           /* We only had the explicitly-provided arguments before, but
15907              now we have a complete set of arguments.  */
15908           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15909
15910           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
15911           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
15912           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
15913         }
15914       else
15915         {
15916           tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
15917           tree old_args = ARGUMENT_PACK_ARGS (old_pack);
15918
15919           if (!comp_template_args_with_info (old_args, new_args,
15920                                              &bad_old_arg, &bad_new_arg))
15921             /* Inconsistent unification of this parameter pack.  */
15922             return unify_parameter_pack_inconsistent (explain_p,
15923                                                       bad_old_arg,
15924                                                       bad_new_arg);
15925         }
15926     }
15927
15928   return unify_success (explain_p);
15929 }
15930
15931 /* Deduce the value of template parameters.  TPARMS is the (innermost)
15932    set of template parameters to a template.  TARGS is the bindings
15933    for those template parameters, as determined thus far; TARGS may
15934    include template arguments for outer levels of template parameters
15935    as well.  PARM is a parameter to a template function, or a
15936    subcomponent of that parameter; ARG is the corresponding argument.
15937    This function attempts to match PARM with ARG in a manner
15938    consistent with the existing assignments in TARGS.  If more values
15939    are deduced, then TARGS is updated.
15940
15941    Returns 0 if the type deduction succeeds, 1 otherwise.  The
15942    parameter STRICT is a bitwise or of the following flags:
15943
15944      UNIFY_ALLOW_NONE:
15945        Require an exact match between PARM and ARG.
15946      UNIFY_ALLOW_MORE_CV_QUAL:
15947        Allow the deduced ARG to be more cv-qualified (by qualification
15948        conversion) than ARG.
15949      UNIFY_ALLOW_LESS_CV_QUAL:
15950        Allow the deduced ARG to be less cv-qualified than ARG.
15951      UNIFY_ALLOW_DERIVED:
15952        Allow the deduced ARG to be a template base class of ARG,
15953        or a pointer to a template base class of the type pointed to by
15954        ARG.
15955      UNIFY_ALLOW_INTEGER:
15956        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
15957        case for more information.
15958      UNIFY_ALLOW_OUTER_LEVEL:
15959        This is the outermost level of a deduction. Used to determine validity
15960        of qualification conversions. A valid qualification conversion must
15961        have const qualified pointers leading up to the inner type which
15962        requires additional CV quals, except at the outer level, where const
15963        is not required [conv.qual]. It would be normal to set this flag in
15964        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
15965      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
15966        This is the outermost level of a deduction, and PARM can be more CV
15967        qualified at this point.
15968      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
15969        This is the outermost level of a deduction, and PARM can be less CV
15970        qualified at this point.  */
15971
15972 static int
15973 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
15974        bool explain_p)
15975 {
15976   int idx;
15977   tree targ;
15978   tree tparm;
15979   int strict_in = strict;
15980
15981   /* I don't think this will do the right thing with respect to types.
15982      But the only case I've seen it in so far has been array bounds, where
15983      signedness is the only information lost, and I think that will be
15984      okay.  */
15985   while (TREE_CODE (parm) == NOP_EXPR)
15986     parm = TREE_OPERAND (parm, 0);
15987
15988   if (arg == error_mark_node)
15989     return unify_invalid (explain_p);
15990   if (arg == unknown_type_node
15991       || arg == init_list_type_node)
15992     /* We can't deduce anything from this, but we might get all the
15993        template args from other function args.  */
15994     return unify_success (explain_p);
15995
15996   /* If PARM uses template parameters, then we can't bail out here,
15997      even if ARG == PARM, since we won't record unifications for the
15998      template parameters.  We might need them if we're trying to
15999      figure out which of two things is more specialized.  */
16000   if (arg == parm && !uses_template_parms (parm))
16001     return unify_success (explain_p);
16002
16003   /* Handle init lists early, so the rest of the function can assume
16004      we're dealing with a type. */
16005   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
16006     {
16007       tree elt, elttype;
16008       unsigned i;
16009       tree orig_parm = parm;
16010
16011       /* Replace T with std::initializer_list<T> for deduction.  */
16012       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
16013           && flag_deduce_init_list)
16014         parm = listify (parm);
16015
16016       if (!is_std_init_list (parm))
16017         /* We can only deduce from an initializer list argument if the
16018            parameter is std::initializer_list; otherwise this is a
16019            non-deduced context. */
16020         return unify_success (explain_p);
16021
16022       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
16023
16024       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
16025         {
16026           int elt_strict = strict;
16027
16028           if (elt == error_mark_node)
16029             return unify_invalid (explain_p);
16030
16031           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
16032             {
16033               tree type = TREE_TYPE (elt);
16034               /* It should only be possible to get here for a call.  */
16035               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
16036               elt_strict |= maybe_adjust_types_for_deduction
16037                 (DEDUCE_CALL, &elttype, &type, elt);
16038               elt = type;
16039             }
16040
16041           RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
16042                                    explain_p);
16043         }
16044
16045       /* If the std::initializer_list<T> deduction worked, replace the
16046          deduced A with std::initializer_list<A>.  */
16047       if (orig_parm != parm)
16048         {
16049           idx = TEMPLATE_TYPE_IDX (orig_parm);
16050           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
16051           targ = listify (targ);
16052           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
16053         }
16054       return unify_success (explain_p);
16055     }
16056
16057   /* Immediately reject some pairs that won't unify because of
16058      cv-qualification mismatches.  */
16059   if (TREE_CODE (arg) == TREE_CODE (parm)
16060       && TYPE_P (arg)
16061       /* It is the elements of the array which hold the cv quals of an array
16062          type, and the elements might be template type parms. We'll check
16063          when we recurse.  */
16064       && TREE_CODE (arg) != ARRAY_TYPE
16065       /* We check the cv-qualifiers when unifying with template type
16066          parameters below.  We want to allow ARG `const T' to unify with
16067          PARM `T' for example, when computing which of two templates
16068          is more specialized, for example.  */
16069       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
16070       && !check_cv_quals_for_unify (strict_in, arg, parm))
16071     return unify_cv_qual_mismatch (explain_p, parm, arg);
16072
16073   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
16074       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
16075     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
16076   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
16077   strict &= ~UNIFY_ALLOW_DERIVED;
16078   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
16079   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
16080
16081   switch (TREE_CODE (parm))
16082     {
16083     case TYPENAME_TYPE:
16084     case SCOPE_REF:
16085     case UNBOUND_CLASS_TEMPLATE:
16086       /* In a type which contains a nested-name-specifier, template
16087          argument values cannot be deduced for template parameters used
16088          within the nested-name-specifier.  */
16089       return unify_success (explain_p);
16090
16091     case TEMPLATE_TYPE_PARM:
16092     case TEMPLATE_TEMPLATE_PARM:
16093     case BOUND_TEMPLATE_TEMPLATE_PARM:
16094       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
16095       if (tparm == error_mark_node)
16096         return unify_invalid (explain_p);
16097
16098       if (TEMPLATE_TYPE_LEVEL (parm)
16099           != template_decl_level (tparm))
16100         /* The PARM is not one we're trying to unify.  Just check
16101            to see if it matches ARG.  */
16102         {
16103           if (TREE_CODE (arg) == TREE_CODE (parm)
16104               && same_type_p (parm, arg))
16105             return unify_success (explain_p);
16106           else
16107             return unify_type_mismatch (explain_p, parm, arg);
16108         }
16109       idx = TEMPLATE_TYPE_IDX (parm);
16110       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
16111       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
16112
16113       /* Check for mixed types and values.  */
16114       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
16115            && TREE_CODE (tparm) != TYPE_DECL)
16116           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
16117               && TREE_CODE (tparm) != TEMPLATE_DECL))
16118         gcc_unreachable ();
16119
16120       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
16121         {
16122           /* ARG must be constructed from a template class or a template
16123              template parameter.  */
16124           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
16125               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
16126             return unify_template_deduction_failure (explain_p, parm, arg);
16127
16128           {
16129             tree parmvec = TYPE_TI_ARGS (parm);
16130             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
16131             tree full_argvec = add_to_template_args (targs, argvec);
16132             tree parm_parms 
16133               = DECL_INNERMOST_TEMPLATE_PARMS
16134                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
16135             int i, len;
16136             int parm_variadic_p = 0;
16137
16138             /* The resolution to DR150 makes clear that default
16139                arguments for an N-argument may not be used to bind T
16140                to a template template parameter with fewer than N
16141                parameters.  It is not safe to permit the binding of
16142                default arguments as an extension, as that may change
16143                the meaning of a conforming program.  Consider:
16144
16145                   struct Dense { static const unsigned int dim = 1; };
16146
16147                   template <template <typename> class View,
16148                             typename Block>
16149                   void operator+(float, View<Block> const&);
16150
16151                   template <typename Block,
16152                             unsigned int Dim = Block::dim>
16153                   struct Lvalue_proxy { operator float() const; };
16154
16155                   void
16156                   test_1d (void) {
16157                     Lvalue_proxy<Dense> p;
16158                     float b;
16159                     b + p;
16160                   }
16161
16162               Here, if Lvalue_proxy is permitted to bind to View, then
16163               the global operator+ will be used; if they are not, the
16164               Lvalue_proxy will be converted to float.  */
16165             if (coerce_template_parms (parm_parms,
16166                                        full_argvec,
16167                                        TYPE_TI_TEMPLATE (parm),
16168                                        (explain_p
16169                                         ? tf_warning_or_error
16170                                         : tf_none),
16171                                        /*require_all_args=*/true,
16172                                        /*use_default_args=*/false)
16173                 == error_mark_node)
16174               return 1;
16175
16176             /* Deduce arguments T, i from TT<T> or TT<i>.
16177                We check each element of PARMVEC and ARGVEC individually
16178                rather than the whole TREE_VEC since they can have
16179                different number of elements.  */
16180
16181             parmvec = expand_template_argument_pack (parmvec);
16182             argvec = expand_template_argument_pack (argvec);
16183
16184             len = TREE_VEC_LENGTH (parmvec);
16185
16186             /* Check if the parameters end in a pack, making them
16187                variadic.  */
16188             if (len > 0
16189                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
16190               parm_variadic_p = 1;
16191             
16192             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
16193               return unify_too_few_arguments (explain_p,
16194                                               TREE_VEC_LENGTH (argvec), len);
16195
16196              for (i = 0; i < len - parm_variadic_p; ++i)
16197               {
16198                 RECUR_AND_CHECK_FAILURE (tparms, targs,
16199                                          TREE_VEC_ELT (parmvec, i),
16200                                          TREE_VEC_ELT (argvec, i),
16201                                          UNIFY_ALLOW_NONE, explain_p);
16202               }
16203
16204             if (parm_variadic_p
16205                 && unify_pack_expansion (tparms, targs,
16206                                          parmvec, argvec,
16207                                          DEDUCE_EXACT,
16208                                          /*subr=*/true, explain_p))
16209               return 1;
16210           }
16211           arg = TYPE_TI_TEMPLATE (arg);
16212
16213           /* Fall through to deduce template name.  */
16214         }
16215
16216       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
16217           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
16218         {
16219           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
16220
16221           /* Simple cases: Value already set, does match or doesn't.  */
16222           if (targ != NULL_TREE && template_args_equal (targ, arg))
16223             return unify_success (explain_p);
16224           else if (targ)
16225             return unify_inconsistency (explain_p, parm, targ, arg);
16226         }
16227       else
16228         {
16229           /* If PARM is `const T' and ARG is only `int', we don't have
16230              a match unless we are allowing additional qualification.
16231              If ARG is `const int' and PARM is just `T' that's OK;
16232              that binds `const int' to `T'.  */
16233           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
16234                                          arg, parm))
16235             return unify_cv_qual_mismatch (explain_p, parm, arg);
16236
16237           /* Consider the case where ARG is `const volatile int' and
16238              PARM is `const T'.  Then, T should be `volatile int'.  */
16239           arg = cp_build_qualified_type_real
16240             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
16241           if (arg == error_mark_node)
16242             return unify_invalid (explain_p);
16243
16244           /* Simple cases: Value already set, does match or doesn't.  */
16245           if (targ != NULL_TREE && same_type_p (targ, arg))
16246             return unify_success (explain_p);
16247           else if (targ)
16248             return unify_inconsistency (explain_p, parm, targ, arg);
16249
16250           /* Make sure that ARG is not a variable-sized array.  (Note
16251              that were talking about variable-sized arrays (like
16252              `int[n]'), rather than arrays of unknown size (like
16253              `int[]').)  We'll get very confused by such a type since
16254              the bound of the array is not constant, and therefore
16255              not mangleable.  Besides, such types are not allowed in
16256              ISO C++, so we can do as we please here.  We do allow
16257              them for 'auto' deduction, since that isn't ABI-exposed.  */
16258           if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
16259             return unify_vla_arg (explain_p, arg);
16260
16261           /* Strip typedefs as in convert_template_argument.  */
16262           arg = canonicalize_type_argument (arg, tf_none);
16263         }
16264
16265       /* If ARG is a parameter pack or an expansion, we cannot unify
16266          against it unless PARM is also a parameter pack.  */
16267       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16268           && !template_parameter_pack_p (parm))
16269         return unify_parameter_pack_mismatch (explain_p, parm, arg);
16270
16271       /* If the argument deduction results is a METHOD_TYPE,
16272          then there is a problem.
16273          METHOD_TYPE doesn't map to any real C++ type the result of
16274          the deduction can not be of that type.  */
16275       if (TREE_CODE (arg) == METHOD_TYPE)
16276         return unify_method_type_error (explain_p, arg);
16277
16278       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16279       return unify_success (explain_p);
16280
16281     case TEMPLATE_PARM_INDEX:
16282       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
16283       if (tparm == error_mark_node)
16284         return unify_invalid (explain_p);
16285
16286       if (TEMPLATE_PARM_LEVEL (parm)
16287           != template_decl_level (tparm))
16288         {
16289           /* The PARM is not one we're trying to unify.  Just check
16290              to see if it matches ARG.  */
16291           int result = !(TREE_CODE (arg) == TREE_CODE (parm)
16292                          && cp_tree_equal (parm, arg));
16293           if (result)
16294             unify_expression_unequal (explain_p, parm, arg);
16295           return result;
16296         }
16297
16298       idx = TEMPLATE_PARM_IDX (parm);
16299       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
16300
16301       if (targ)
16302         {
16303           int x = !cp_tree_equal (targ, arg);
16304           if (x)
16305             unify_inconsistency (explain_p, parm, targ, arg);
16306           return x;
16307         }
16308
16309       /* [temp.deduct.type] If, in the declaration of a function template
16310          with a non-type template-parameter, the non-type
16311          template-parameter is used in an expression in the function
16312          parameter-list and, if the corresponding template-argument is
16313          deduced, the template-argument type shall match the type of the
16314          template-parameter exactly, except that a template-argument
16315          deduced from an array bound may be of any integral type.
16316          The non-type parameter might use already deduced type parameters.  */
16317       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
16318       if (!TREE_TYPE (arg))
16319         /* Template-parameter dependent expression.  Just accept it for now.
16320            It will later be processed in convert_template_argument.  */
16321         ;
16322       else if (same_type_p (TREE_TYPE (arg), tparm))
16323         /* OK */;
16324       else if ((strict & UNIFY_ALLOW_INTEGER)
16325                && (TREE_CODE (tparm) == INTEGER_TYPE
16326                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
16327         /* Convert the ARG to the type of PARM; the deduced non-type
16328            template argument must exactly match the types of the
16329            corresponding parameter.  */
16330         arg = fold (build_nop (tparm, arg));
16331       else if (uses_template_parms (tparm))
16332         /* We haven't deduced the type of this parameter yet.  Try again
16333            later.  */
16334         return unify_success (explain_p);
16335       else
16336         return unify_type_mismatch (explain_p, tparm, arg);
16337
16338       /* If ARG is a parameter pack or an expansion, we cannot unify
16339          against it unless PARM is also a parameter pack.  */
16340       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16341           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
16342         return unify_parameter_pack_mismatch (explain_p, parm, arg);
16343
16344       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16345       return unify_success (explain_p);
16346
16347     case PTRMEM_CST:
16348      {
16349         /* A pointer-to-member constant can be unified only with
16350          another constant.  */
16351       if (TREE_CODE (arg) != PTRMEM_CST)
16352         return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
16353
16354       /* Just unify the class member. It would be useless (and possibly
16355          wrong, depending on the strict flags) to unify also
16356          PTRMEM_CST_CLASS, because we want to be sure that both parm and
16357          arg refer to the same variable, even if through different
16358          classes. For instance:
16359
16360          struct A { int x; };
16361          struct B : A { };
16362
16363          Unification of &A::x and &B::x must succeed.  */
16364       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
16365                     PTRMEM_CST_MEMBER (arg), strict, explain_p);
16366      }
16367
16368     case POINTER_TYPE:
16369       {
16370         if (TREE_CODE (arg) != POINTER_TYPE)
16371           return unify_type_mismatch (explain_p, parm, arg);
16372
16373         /* [temp.deduct.call]
16374
16375            A can be another pointer or pointer to member type that can
16376            be converted to the deduced A via a qualification
16377            conversion (_conv.qual_).
16378
16379            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
16380            This will allow for additional cv-qualification of the
16381            pointed-to types if appropriate.  */
16382
16383         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
16384           /* The derived-to-base conversion only persists through one
16385              level of pointers.  */
16386           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
16387
16388         return unify (tparms, targs, TREE_TYPE (parm),
16389                       TREE_TYPE (arg), strict, explain_p);
16390       }
16391
16392     case REFERENCE_TYPE:
16393       if (TREE_CODE (arg) != REFERENCE_TYPE)
16394         return unify_type_mismatch (explain_p, parm, arg);
16395       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16396                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16397
16398     case ARRAY_TYPE:
16399       if (TREE_CODE (arg) != ARRAY_TYPE)
16400         return unify_type_mismatch (explain_p, parm, arg);
16401       if ((TYPE_DOMAIN (parm) == NULL_TREE)
16402           != (TYPE_DOMAIN (arg) == NULL_TREE))
16403         return unify_type_mismatch (explain_p, parm, arg);
16404       if (TYPE_DOMAIN (parm) != NULL_TREE)
16405         {
16406           tree parm_max;
16407           tree arg_max;
16408           bool parm_cst;
16409           bool arg_cst;
16410
16411           /* Our representation of array types uses "N - 1" as the
16412              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
16413              not an integer constant.  We cannot unify arbitrarily
16414              complex expressions, so we eliminate the MINUS_EXPRs
16415              here.  */
16416           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
16417           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
16418           if (!parm_cst)
16419             {
16420               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
16421               parm_max = TREE_OPERAND (parm_max, 0);
16422             }
16423           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
16424           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
16425           if (!arg_cst)
16426             {
16427               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
16428                  trying to unify the type of a variable with the type
16429                  of a template parameter.  For example:
16430
16431                    template <unsigned int N>
16432                    void f (char (&) [N]);
16433                    int g(); 
16434                    void h(int i) {
16435                      char a[g(i)];
16436                      f(a); 
16437                    }
16438
16439                 Here, the type of the ARG will be "int [g(i)]", and
16440                 may be a SAVE_EXPR, etc.  */
16441               if (TREE_CODE (arg_max) != MINUS_EXPR)
16442                 return unify_vla_arg (explain_p, arg);
16443               arg_max = TREE_OPERAND (arg_max, 0);
16444             }
16445
16446           /* If only one of the bounds used a MINUS_EXPR, compensate
16447              by adding one to the other bound.  */
16448           if (parm_cst && !arg_cst)
16449             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
16450                                     integer_type_node,
16451                                     parm_max,
16452                                     integer_one_node);
16453           else if (arg_cst && !parm_cst)
16454             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
16455                                    integer_type_node,
16456                                    arg_max,
16457                                    integer_one_node);
16458
16459           RECUR_AND_CHECK_FAILURE (tparms, targs, parm_max, arg_max,
16460                                    UNIFY_ALLOW_INTEGER, explain_p);
16461         }
16462       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16463                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16464
16465     case REAL_TYPE:
16466     case COMPLEX_TYPE:
16467     case VECTOR_TYPE:
16468     case INTEGER_TYPE:
16469     case BOOLEAN_TYPE:
16470     case ENUMERAL_TYPE:
16471     case VOID_TYPE:
16472       if (TREE_CODE (arg) != TREE_CODE (parm))
16473         return unify_type_mismatch (explain_p, parm, arg);
16474
16475       /* We have already checked cv-qualification at the top of the
16476          function.  */
16477       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
16478         return unify_type_mismatch (explain_p, parm, arg);
16479
16480       /* As far as unification is concerned, this wins.  Later checks
16481          will invalidate it if necessary.  */
16482       return unify_success (explain_p);
16483
16484       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
16485       /* Type INTEGER_CST can come from ordinary constant template args.  */
16486     case INTEGER_CST:
16487       while (TREE_CODE (arg) == NOP_EXPR)
16488         arg = TREE_OPERAND (arg, 0);
16489
16490       if (TREE_CODE (arg) != INTEGER_CST)
16491         return unify_template_argument_mismatch (explain_p, parm, arg);
16492       return (tree_int_cst_equal (parm, arg)
16493               ? unify_success (explain_p)
16494               : unify_template_argument_mismatch (explain_p, parm, arg));
16495
16496     case TREE_VEC:
16497       {
16498         int i, len, argslen;
16499         int parm_variadic_p = 0;
16500
16501         if (TREE_CODE (arg) != TREE_VEC)
16502           return unify_template_argument_mismatch (explain_p, parm, arg);
16503
16504         len = TREE_VEC_LENGTH (parm);
16505         argslen = TREE_VEC_LENGTH (arg);
16506
16507         /* Check for pack expansions in the parameters.  */
16508         for (i = 0; i < len; ++i)
16509           {
16510             if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
16511               {
16512                 if (i == len - 1)
16513                   /* We can unify against something with a trailing
16514                      parameter pack.  */
16515                   parm_variadic_p = 1;
16516                 else
16517                   /* [temp.deduct.type]/9: If the template argument list of
16518                      P contains a pack expansion that is not the last
16519                      template argument, the entire template argument list
16520                      is a non-deduced context.  */
16521                   return unify_success (explain_p);
16522               }
16523           }
16524
16525         /* If we don't have enough arguments to satisfy the parameters
16526            (not counting the pack expression at the end), or we have
16527            too many arguments for a parameter list that doesn't end in
16528            a pack expression, we can't unify.  */
16529         if (parm_variadic_p
16530             ? argslen < len - parm_variadic_p
16531             : argslen != len)
16532           return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
16533
16534         /* Unify all of the parameters that precede the (optional)
16535            pack expression.  */
16536         for (i = 0; i < len - parm_variadic_p; ++i)
16537           {
16538             RECUR_AND_CHECK_FAILURE (tparms, targs,
16539                                      TREE_VEC_ELT (parm, i),
16540                                      TREE_VEC_ELT (arg, i),
16541                                      UNIFY_ALLOW_NONE, explain_p);
16542           }
16543         if (parm_variadic_p)
16544           return unify_pack_expansion (tparms, targs, parm, arg,
16545                                        DEDUCE_EXACT,
16546                                        /*subr=*/true, explain_p);
16547         return unify_success (explain_p);
16548       }
16549
16550     case RECORD_TYPE:
16551     case UNION_TYPE:
16552       if (TREE_CODE (arg) != TREE_CODE (parm))
16553         return unify_type_mismatch (explain_p, parm, arg);
16554
16555       if (TYPE_PTRMEMFUNC_P (parm))
16556         {
16557           if (!TYPE_PTRMEMFUNC_P (arg))
16558             return unify_type_mismatch (explain_p, parm, arg);
16559
16560           return unify (tparms, targs,
16561                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
16562                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
16563                         strict, explain_p);
16564         }
16565
16566       if (CLASSTYPE_TEMPLATE_INFO (parm))
16567         {
16568           tree t = NULL_TREE;
16569
16570           if (strict_in & UNIFY_ALLOW_DERIVED)
16571             {
16572               /* First, we try to unify the PARM and ARG directly.  */
16573               t = try_class_unification (tparms, targs,
16574                                          parm, arg, explain_p);
16575
16576               if (!t)
16577                 {
16578                   /* Fallback to the special case allowed in
16579                      [temp.deduct.call]:
16580
16581                        If P is a class, and P has the form
16582                        template-id, then A can be a derived class of
16583                        the deduced A.  Likewise, if P is a pointer to
16584                        a class of the form template-id, A can be a
16585                        pointer to a derived class pointed to by the
16586                        deduced A.  */
16587                   enum template_base_result r;
16588                   r = get_template_base (tparms, targs, parm, arg,
16589                                          explain_p, &t);
16590
16591                   if (!t)
16592                     return unify_no_common_base (explain_p, r, parm, arg);
16593                 }
16594             }
16595           else if (CLASSTYPE_TEMPLATE_INFO (arg)
16596                    && (CLASSTYPE_TI_TEMPLATE (parm)
16597                        == CLASSTYPE_TI_TEMPLATE (arg)))
16598             /* Perhaps PARM is something like S<U> and ARG is S<int>.
16599                Then, we should unify `int' and `U'.  */
16600             t = arg;
16601           else
16602             /* There's no chance of unification succeeding.  */
16603             return unify_type_mismatch (explain_p, parm, arg);
16604
16605           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
16606                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
16607         }
16608       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
16609         return unify_type_mismatch (explain_p, parm, arg);
16610       return unify_success (explain_p);
16611
16612     case METHOD_TYPE:
16613     case FUNCTION_TYPE:
16614       {
16615         unsigned int nargs;
16616         tree *args;
16617         tree a;
16618         unsigned int i;
16619
16620         if (TREE_CODE (arg) != TREE_CODE (parm))
16621           return unify_type_mismatch (explain_p, parm, arg);
16622
16623         /* CV qualifications for methods can never be deduced, they must
16624            match exactly.  We need to check them explicitly here,
16625            because type_unification_real treats them as any other
16626            cv-qualified parameter.  */
16627         if (TREE_CODE (parm) == METHOD_TYPE
16628             && (!check_cv_quals_for_unify
16629                 (UNIFY_ALLOW_NONE,
16630                  class_of_this_parm (arg),
16631                  class_of_this_parm (parm))))
16632           return unify_cv_qual_mismatch (explain_p, parm, arg);
16633
16634         RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
16635                                  TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
16636
16637         nargs = list_length (TYPE_ARG_TYPES (arg));
16638         args = XALLOCAVEC (tree, nargs);
16639         for (a = TYPE_ARG_TYPES (arg), i = 0;
16640              a != NULL_TREE && a != void_list_node;
16641              a = TREE_CHAIN (a), ++i)
16642           args[i] = TREE_VALUE (a);
16643         nargs = i;
16644
16645         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
16646                                       args, nargs, 1, DEDUCE_EXACT,
16647                                       LOOKUP_NORMAL, explain_p);
16648       }
16649
16650     case OFFSET_TYPE:
16651       /* Unify a pointer to member with a pointer to member function, which
16652          deduces the type of the member as a function type. */
16653       if (TYPE_PTRMEMFUNC_P (arg))
16654         {
16655           tree method_type;
16656           tree fntype;
16657
16658           /* Check top-level cv qualifiers */
16659           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
16660             return unify_cv_qual_mismatch (explain_p, parm, arg);
16661
16662           RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16663                                    TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
16664                                    UNIFY_ALLOW_NONE, explain_p);
16665
16666           /* Determine the type of the function we are unifying against. */
16667           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
16668           fntype =
16669             build_function_type (TREE_TYPE (method_type),
16670                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
16671
16672           /* Extract the cv-qualifiers of the member function from the
16673              implicit object parameter and place them on the function
16674              type to be restored later. */
16675           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
16676           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
16677         }
16678
16679       if (TREE_CODE (arg) != OFFSET_TYPE)
16680         return unify_type_mismatch (explain_p, parm, arg);
16681       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16682                                TYPE_OFFSET_BASETYPE (arg),
16683                                UNIFY_ALLOW_NONE, explain_p);
16684       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16685                     strict, explain_p);
16686
16687     case CONST_DECL:
16688       if (DECL_TEMPLATE_PARM_P (parm))
16689         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
16690       if (arg != integral_constant_value (parm))
16691         return unify_template_argument_mismatch (explain_p, parm, arg);
16692       return unify_success (explain_p);
16693
16694     case FIELD_DECL:
16695     case TEMPLATE_DECL:
16696       /* Matched cases are handled by the ARG == PARM test above.  */
16697       return unify_template_argument_mismatch (explain_p, parm, arg);
16698
16699     case VAR_DECL:
16700       /* A non-type template parameter that is a variable should be a
16701          an integral constant, in which case, it whould have been
16702          folded into its (constant) value. So we should not be getting
16703          a variable here.  */
16704       gcc_unreachable ();
16705
16706     case TYPE_ARGUMENT_PACK:
16707     case NONTYPE_ARGUMENT_PACK:
16708       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
16709                     ARGUMENT_PACK_ARGS (arg), strict, explain_p);
16710
16711     case TYPEOF_TYPE:
16712     case DECLTYPE_TYPE:
16713     case UNDERLYING_TYPE:
16714       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
16715          or UNDERLYING_TYPE nodes.  */
16716       return unify_success (explain_p);
16717
16718     case ERROR_MARK:
16719       /* Unification fails if we hit an error node.  */
16720       return unify_invalid (explain_p);
16721
16722     default:
16723       /* An unresolved overload is a nondeduced context.  */
16724       if (type_unknown_p (parm))
16725         return unify_success (explain_p);
16726       gcc_assert (EXPR_P (parm));
16727
16728       /* We must be looking at an expression.  This can happen with
16729          something like:
16730
16731            template <int I>
16732            void foo(S<I>, S<I + 2>);
16733
16734          This is a "nondeduced context":
16735
16736            [deduct.type]
16737
16738            The nondeduced contexts are:
16739
16740            --A type that is a template-id in which one or more of
16741              the template-arguments is an expression that references
16742              a template-parameter.
16743
16744          In these cases, we assume deduction succeeded, but don't
16745          actually infer any unifications.  */
16746
16747       if (!uses_template_parms (parm)
16748           && !template_args_equal (parm, arg))
16749         return unify_expression_unequal (explain_p, parm, arg);
16750       else
16751         return unify_success (explain_p);
16752     }
16753 }
16754 #undef RECUR_AND_CHECK_FAILURE
16755 \f
16756 /* Note that DECL can be defined in this translation unit, if
16757    required.  */
16758
16759 static void
16760 mark_definable (tree decl)
16761 {
16762   tree clone;
16763   DECL_NOT_REALLY_EXTERN (decl) = 1;
16764   FOR_EACH_CLONE (clone, decl)
16765     DECL_NOT_REALLY_EXTERN (clone) = 1;
16766 }
16767
16768 /* Called if RESULT is explicitly instantiated, or is a member of an
16769    explicitly instantiated class.  */
16770
16771 void
16772 mark_decl_instantiated (tree result, int extern_p)
16773 {
16774   SET_DECL_EXPLICIT_INSTANTIATION (result);
16775
16776   /* If this entity has already been written out, it's too late to
16777      make any modifications.  */
16778   if (TREE_ASM_WRITTEN (result))
16779     return;
16780
16781   if (TREE_CODE (result) != FUNCTION_DECL)
16782     /* The TREE_PUBLIC flag for function declarations will have been
16783        set correctly by tsubst.  */
16784     TREE_PUBLIC (result) = 1;
16785
16786   /* This might have been set by an earlier implicit instantiation.  */
16787   DECL_COMDAT (result) = 0;
16788
16789   if (extern_p)
16790     DECL_NOT_REALLY_EXTERN (result) = 0;
16791   else
16792     {
16793       mark_definable (result);
16794       /* Always make artificials weak.  */
16795       if (DECL_ARTIFICIAL (result) && flag_weak)
16796         comdat_linkage (result);
16797       /* For WIN32 we also want to put explicit instantiations in
16798          linkonce sections.  */
16799       else if (TREE_PUBLIC (result))
16800         maybe_make_one_only (result);
16801     }
16802
16803   /* If EXTERN_P, then this function will not be emitted -- unless
16804      followed by an explicit instantiation, at which point its linkage
16805      will be adjusted.  If !EXTERN_P, then this function will be
16806      emitted here.  In neither circumstance do we want
16807      import_export_decl to adjust the linkage.  */
16808   DECL_INTERFACE_KNOWN (result) = 1;
16809 }
16810
16811 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
16812    important template arguments.  If any are missing, we check whether
16813    they're important by using error_mark_node for substituting into any
16814    args that were used for partial ordering (the ones between ARGS and END)
16815    and seeing if it bubbles up.  */
16816
16817 static bool
16818 check_undeduced_parms (tree targs, tree args, tree end)
16819 {
16820   bool found = false;
16821   int i;
16822   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
16823     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
16824       {
16825         found = true;
16826         TREE_VEC_ELT (targs, i) = error_mark_node;
16827       }
16828   if (found)
16829     {
16830       for (; args != end; args = TREE_CHAIN (args))
16831         {
16832           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
16833           if (substed == error_mark_node)
16834             return true;
16835         }
16836     }
16837   return false;
16838 }
16839
16840 /* Given two function templates PAT1 and PAT2, return:
16841
16842    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
16843    -1 if PAT2 is more specialized than PAT1.
16844    0 if neither is more specialized.
16845
16846    LEN indicates the number of parameters we should consider
16847    (defaulted parameters should not be considered).
16848
16849    The 1998 std underspecified function template partial ordering, and
16850    DR214 addresses the issue.  We take pairs of arguments, one from
16851    each of the templates, and deduce them against each other.  One of
16852    the templates will be more specialized if all the *other*
16853    template's arguments deduce against its arguments and at least one
16854    of its arguments *does* *not* deduce against the other template's
16855    corresponding argument.  Deduction is done as for class templates.
16856    The arguments used in deduction have reference and top level cv
16857    qualifiers removed.  Iff both arguments were originally reference
16858    types *and* deduction succeeds in both directions, the template
16859    with the more cv-qualified argument wins for that pairing (if
16860    neither is more cv-qualified, they both are equal).  Unlike regular
16861    deduction, after all the arguments have been deduced in this way,
16862    we do *not* verify the deduced template argument values can be
16863    substituted into non-deduced contexts.
16864
16865    The logic can be a bit confusing here, because we look at deduce1 and
16866    targs1 to see if pat2 is at least as specialized, and vice versa; if we
16867    can find template arguments for pat1 to make arg1 look like arg2, that
16868    means that arg2 is at least as specialized as arg1.  */
16869
16870 int
16871 more_specialized_fn (tree pat1, tree pat2, int len)
16872 {
16873   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
16874   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
16875   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
16876   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
16877   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
16878   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
16879   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
16880   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
16881   tree origs1, origs2;
16882   bool lose1 = false;
16883   bool lose2 = false;
16884
16885   /* Remove the this parameter from non-static member functions.  If
16886      one is a non-static member function and the other is not a static
16887      member function, remove the first parameter from that function
16888      also.  This situation occurs for operator functions where we
16889      locate both a member function (with this pointer) and non-member
16890      operator (with explicit first operand).  */
16891   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
16892     {
16893       len--; /* LEN is the number of significant arguments for DECL1 */
16894       args1 = TREE_CHAIN (args1);
16895       if (!DECL_STATIC_FUNCTION_P (decl2))
16896         args2 = TREE_CHAIN (args2);
16897     }
16898   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
16899     {
16900       args2 = TREE_CHAIN (args2);
16901       if (!DECL_STATIC_FUNCTION_P (decl1))
16902         {
16903           len--;
16904           args1 = TREE_CHAIN (args1);
16905         }
16906     }
16907
16908   /* If only one is a conversion operator, they are unordered.  */
16909   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
16910     return 0;
16911
16912   /* Consider the return type for a conversion function */
16913   if (DECL_CONV_FN_P (decl1))
16914     {
16915       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
16916       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
16917       len++;
16918     }
16919
16920   processing_template_decl++;
16921
16922   origs1 = args1;
16923   origs2 = args2;
16924
16925   while (len--
16926          /* Stop when an ellipsis is seen.  */
16927          && args1 != NULL_TREE && args2 != NULL_TREE)
16928     {
16929       tree arg1 = TREE_VALUE (args1);
16930       tree arg2 = TREE_VALUE (args2);
16931       int deduce1, deduce2;
16932       int quals1 = -1;
16933       int quals2 = -1;
16934
16935       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16936           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16937         {
16938           /* When both arguments are pack expansions, we need only
16939              unify the patterns themselves.  */
16940           arg1 = PACK_EXPANSION_PATTERN (arg1);
16941           arg2 = PACK_EXPANSION_PATTERN (arg2);
16942
16943           /* This is the last comparison we need to do.  */
16944           len = 0;
16945         }
16946
16947       if (TREE_CODE (arg1) == REFERENCE_TYPE)
16948         {
16949           arg1 = TREE_TYPE (arg1);
16950           quals1 = cp_type_quals (arg1);
16951         }
16952
16953       if (TREE_CODE (arg2) == REFERENCE_TYPE)
16954         {
16955           arg2 = TREE_TYPE (arg2);
16956           quals2 = cp_type_quals (arg2);
16957         }
16958
16959       if ((quals1 < 0) != (quals2 < 0))
16960         {
16961           /* Only of the args is a reference, see if we should apply
16962              array/function pointer decay to it.  This is not part of
16963              DR214, but is, IMHO, consistent with the deduction rules
16964              for the function call itself, and with our earlier
16965              implementation of the underspecified partial ordering
16966              rules.  (nathan).  */
16967           if (quals1 >= 0)
16968             {
16969               switch (TREE_CODE (arg1))
16970                 {
16971                 case ARRAY_TYPE:
16972                   arg1 = TREE_TYPE (arg1);
16973                   /* FALLTHROUGH. */
16974                 case FUNCTION_TYPE:
16975                   arg1 = build_pointer_type (arg1);
16976                   break;
16977
16978                 default:
16979                   break;
16980                 }
16981             }
16982           else
16983             {
16984               switch (TREE_CODE (arg2))
16985                 {
16986                 case ARRAY_TYPE:
16987                   arg2 = TREE_TYPE (arg2);
16988                   /* FALLTHROUGH. */
16989                 case FUNCTION_TYPE:
16990                   arg2 = build_pointer_type (arg2);
16991                   break;
16992
16993                 default:
16994                   break;
16995                 }
16996             }
16997         }
16998
16999       arg1 = TYPE_MAIN_VARIANT (arg1);
17000       arg2 = TYPE_MAIN_VARIANT (arg2);
17001
17002       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
17003         {
17004           int i, len2 = list_length (args2);
17005           tree parmvec = make_tree_vec (1);
17006           tree argvec = make_tree_vec (len2);
17007           tree ta = args2;
17008
17009           /* Setup the parameter vector, which contains only ARG1.  */
17010           TREE_VEC_ELT (parmvec, 0) = arg1;
17011
17012           /* Setup the argument vector, which contains the remaining
17013              arguments.  */
17014           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
17015             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
17016
17017           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
17018                                            argvec, DEDUCE_EXACT,
17019                                            /*subr=*/true, /*explain_p=*/false)
17020                      == 0);
17021
17022           /* We cannot deduce in the other direction, because ARG1 is
17023              a pack expansion but ARG2 is not.  */
17024           deduce2 = 0;
17025         }
17026       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
17027         {
17028           int i, len1 = list_length (args1);
17029           tree parmvec = make_tree_vec (1);
17030           tree argvec = make_tree_vec (len1);
17031           tree ta = args1;
17032
17033           /* Setup the parameter vector, which contains only ARG1.  */
17034           TREE_VEC_ELT (parmvec, 0) = arg2;
17035
17036           /* Setup the argument vector, which contains the remaining
17037              arguments.  */
17038           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
17039             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
17040
17041           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
17042                                            argvec, DEDUCE_EXACT,
17043                                            /*subr=*/true, /*explain_p=*/false)
17044                      == 0);
17045
17046           /* We cannot deduce in the other direction, because ARG2 is
17047              a pack expansion but ARG1 is not.*/
17048           deduce1 = 0;
17049         }
17050
17051       else
17052         {
17053           /* The normal case, where neither argument is a pack
17054              expansion.  */
17055           deduce1 = (unify (tparms1, targs1, arg1, arg2,
17056                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
17057                      == 0);
17058           deduce2 = (unify (tparms2, targs2, arg2, arg1,
17059                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
17060                      == 0);
17061         }
17062
17063       /* If we couldn't deduce arguments for tparms1 to make arg1 match
17064          arg2, then arg2 is not as specialized as arg1.  */
17065       if (!deduce1)
17066         lose2 = true;
17067       if (!deduce2)
17068         lose1 = true;
17069
17070       /* "If, for a given type, deduction succeeds in both directions
17071          (i.e., the types are identical after the transformations above)
17072          and if the type from the argument template is more cv-qualified
17073          than the type from the parameter template (as described above)
17074          that type is considered to be more specialized than the other. If
17075          neither type is more cv-qualified than the other then neither type
17076          is more specialized than the other."  */
17077
17078       if (deduce1 && deduce2
17079           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
17080         {
17081           if ((quals1 & quals2) == quals2)
17082             lose2 = true;
17083           if ((quals1 & quals2) == quals1)
17084             lose1 = true;
17085         }
17086
17087       if (lose1 && lose2)
17088         /* We've failed to deduce something in either direction.
17089            These must be unordered.  */
17090         break;
17091
17092       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
17093           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
17094         /* We have already processed all of the arguments in our
17095            handing of the pack expansion type.  */
17096         len = 0;
17097
17098       args1 = TREE_CHAIN (args1);
17099       args2 = TREE_CHAIN (args2);
17100     }
17101
17102   /* "In most cases, all template parameters must have values in order for
17103      deduction to succeed, but for partial ordering purposes a template
17104      parameter may remain without a value provided it is not used in the
17105      types being used for partial ordering."
17106
17107      Thus, if we are missing any of the targs1 we need to substitute into
17108      origs1, then pat2 is not as specialized as pat1.  This can happen when
17109      there is a nondeduced context.  */
17110   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
17111     lose2 = true;
17112   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
17113     lose1 = true;
17114
17115   processing_template_decl--;
17116
17117   /* All things being equal, if the next argument is a pack expansion
17118      for one function but not for the other, prefer the
17119      non-variadic function.  FIXME this is bogus; see c++/41958.  */
17120   if (lose1 == lose2
17121       && args1 && TREE_VALUE (args1)
17122       && args2 && TREE_VALUE (args2))
17123     {
17124       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
17125       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
17126     }
17127
17128   if (lose1 == lose2)
17129     return 0;
17130   else if (!lose1)
17131     return 1;
17132   else
17133     return -1;
17134 }
17135
17136 /* Determine which of two partial specializations is more specialized.
17137
17138    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
17139    to the first partial specialization.  The TREE_VALUE is the
17140    innermost set of template parameters for the partial
17141    specialization.  PAT2 is similar, but for the second template.
17142
17143    Return 1 if the first partial specialization is more specialized;
17144    -1 if the second is more specialized; 0 if neither is more
17145    specialized.
17146
17147    See [temp.class.order] for information about determining which of
17148    two templates is more specialized.  */
17149
17150 static int
17151 more_specialized_class (tree pat1, tree pat2)
17152 {
17153   tree targs;
17154   tree tmpl1, tmpl2;
17155   int winner = 0;
17156   bool any_deductions = false;
17157
17158   tmpl1 = TREE_TYPE (pat1);
17159   tmpl2 = TREE_TYPE (pat2);
17160
17161   /* Just like what happens for functions, if we are ordering between
17162      different class template specializations, we may encounter dependent
17163      types in the arguments, and we need our dependency check functions
17164      to behave correctly.  */
17165   ++processing_template_decl;
17166   targs = get_class_bindings (TREE_VALUE (pat1),
17167                               CLASSTYPE_TI_ARGS (tmpl1),
17168                               CLASSTYPE_TI_ARGS (tmpl2));
17169   if (targs)
17170     {
17171       --winner;
17172       any_deductions = true;
17173     }
17174
17175   targs = get_class_bindings (TREE_VALUE (pat2),
17176                               CLASSTYPE_TI_ARGS (tmpl2),
17177                               CLASSTYPE_TI_ARGS (tmpl1));
17178   if (targs)
17179     {
17180       ++winner;
17181       any_deductions = true;
17182     }
17183   --processing_template_decl;
17184
17185   /* In the case of a tie where at least one of the class templates
17186      has a parameter pack at the end, the template with the most
17187      non-packed parameters wins.  */
17188   if (winner == 0
17189       && any_deductions
17190       && (template_args_variadic_p (TREE_PURPOSE (pat1))
17191           || template_args_variadic_p (TREE_PURPOSE (pat2))))
17192     {
17193       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
17194       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
17195       int len1 = TREE_VEC_LENGTH (args1);
17196       int len2 = TREE_VEC_LENGTH (args2);
17197
17198       /* We don't count the pack expansion at the end.  */
17199       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
17200         --len1;
17201       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
17202         --len2;
17203
17204       if (len1 > len2)
17205         return 1;
17206       else if (len1 < len2)
17207         return -1;
17208     }
17209
17210   return winner;
17211 }
17212
17213 /* Return the template arguments that will produce the function signature
17214    DECL from the function template FN, with the explicit template
17215    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
17216    also match.  Return NULL_TREE if no satisfactory arguments could be
17217    found.  */
17218
17219 static tree
17220 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
17221 {
17222   int ntparms = DECL_NTPARMS (fn);
17223   tree targs = make_tree_vec (ntparms);
17224   tree decl_type;
17225   tree decl_arg_types;
17226   tree *args;
17227   unsigned int nargs, ix;
17228   tree arg;
17229
17230   /* Substitute the explicit template arguments into the type of DECL.
17231      The call to fn_type_unification will handle substitution into the
17232      FN.  */
17233   decl_type = TREE_TYPE (decl);
17234   if (explicit_args && uses_template_parms (decl_type))
17235     {
17236       tree tmpl;
17237       tree converted_args;
17238
17239       if (DECL_TEMPLATE_INFO (decl))
17240         tmpl = DECL_TI_TEMPLATE (decl);
17241       else
17242         /* We can get here for some invalid specializations.  */
17243         return NULL_TREE;
17244
17245       converted_args
17246         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17247                                  explicit_args, NULL_TREE,
17248                                  tf_none,
17249                                  /*require_all_args=*/false,
17250                                  /*use_default_args=*/false);
17251       if (converted_args == error_mark_node)
17252         return NULL_TREE;
17253
17254       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
17255       if (decl_type == error_mark_node)
17256         return NULL_TREE;
17257     }
17258
17259   /* Never do unification on the 'this' parameter.  */
17260   decl_arg_types = skip_artificial_parms_for (decl, 
17261                                               TYPE_ARG_TYPES (decl_type));
17262
17263   nargs = list_length (decl_arg_types);
17264   args = XALLOCAVEC (tree, nargs);
17265   for (arg = decl_arg_types, ix = 0;
17266        arg != NULL_TREE && arg != void_list_node;
17267        arg = TREE_CHAIN (arg), ++ix)
17268     args[ix] = TREE_VALUE (arg);
17269
17270   if (fn_type_unification (fn, explicit_args, targs,
17271                            args, ix,
17272                            (check_rettype || DECL_CONV_FN_P (fn)
17273                             ? TREE_TYPE (decl_type) : NULL_TREE),
17274                            DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false))
17275     return NULL_TREE;
17276
17277   return targs;
17278 }
17279
17280 /* Return the innermost template arguments that, when applied to a
17281    template specialization whose innermost template parameters are
17282    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
17283    ARGS.
17284
17285    For example, suppose we have:
17286
17287      template <class T, class U> struct S {};
17288      template <class T> struct S<T*, int> {};
17289
17290    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
17291    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
17292    int}.  The resulting vector will be {double}, indicating that `T'
17293    is bound to `double'.  */
17294
17295 static tree
17296 get_class_bindings (tree tparms, tree spec_args, tree args)
17297 {
17298   int i, ntparms = TREE_VEC_LENGTH (tparms);
17299   tree deduced_args;
17300   tree innermost_deduced_args;
17301
17302   innermost_deduced_args = make_tree_vec (ntparms);
17303   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17304     {
17305       deduced_args = copy_node (args);
17306       SET_TMPL_ARGS_LEVEL (deduced_args,
17307                            TMPL_ARGS_DEPTH (deduced_args),
17308                            innermost_deduced_args);
17309     }
17310   else
17311     deduced_args = innermost_deduced_args;
17312
17313   if (unify (tparms, deduced_args,
17314              INNERMOST_TEMPLATE_ARGS (spec_args),
17315              INNERMOST_TEMPLATE_ARGS (args),
17316              UNIFY_ALLOW_NONE, /*explain_p=*/false))
17317     return NULL_TREE;
17318
17319   for (i =  0; i < ntparms; ++i)
17320     if (! TREE_VEC_ELT (innermost_deduced_args, i))
17321       return NULL_TREE;
17322
17323   /* Verify that nondeduced template arguments agree with the type
17324      obtained from argument deduction.
17325
17326      For example:
17327
17328        struct A { typedef int X; };
17329        template <class T, class U> struct C {};
17330        template <class T> struct C<T, typename T::X> {};
17331
17332      Then with the instantiation `C<A, int>', we can deduce that
17333      `T' is `A' but unify () does not check whether `typename T::X'
17334      is `int'.  */
17335   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
17336   if (spec_args == error_mark_node
17337       /* We only need to check the innermost arguments; the other
17338          arguments will always agree.  */
17339       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
17340                               INNERMOST_TEMPLATE_ARGS (args)))
17341     return NULL_TREE;
17342
17343   /* Now that we have bindings for all of the template arguments,
17344      ensure that the arguments deduced for the template template
17345      parameters have compatible template parameter lists.  See the use
17346      of template_template_parm_bindings_ok_p in fn_type_unification
17347      for more information.  */
17348   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
17349     return NULL_TREE;
17350
17351   return deduced_args;
17352 }
17353
17354 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
17355    Return the TREE_LIST node with the most specialized template, if
17356    any.  If there is no most specialized template, the error_mark_node
17357    is returned.
17358
17359    Note that this function does not look at, or modify, the
17360    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
17361    returned is one of the elements of INSTANTIATIONS, callers may
17362    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
17363    and retrieve it from the value returned.  */
17364
17365 tree
17366 most_specialized_instantiation (tree templates)
17367 {
17368   tree fn, champ;
17369
17370   ++processing_template_decl;
17371
17372   champ = templates;
17373   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
17374     {
17375       int fate = 0;
17376
17377       if (get_bindings (TREE_VALUE (champ),
17378                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17379                         NULL_TREE, /*check_ret=*/true))
17380         fate--;
17381
17382       if (get_bindings (TREE_VALUE (fn),
17383                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17384                         NULL_TREE, /*check_ret=*/true))
17385         fate++;
17386
17387       if (fate == -1)
17388         champ = fn;
17389       else if (!fate)
17390         {
17391           /* Equally specialized, move to next function.  If there
17392              is no next function, nothing's most specialized.  */
17393           fn = TREE_CHAIN (fn);
17394           champ = fn;
17395           if (!fn)
17396             break;
17397         }
17398     }
17399
17400   if (champ)
17401     /* Now verify that champ is better than everything earlier in the
17402        instantiation list.  */
17403     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
17404       if (get_bindings (TREE_VALUE (champ),
17405                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17406                         NULL_TREE, /*check_ret=*/true)
17407           || !get_bindings (TREE_VALUE (fn),
17408                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17409                             NULL_TREE, /*check_ret=*/true))
17410         {
17411           champ = NULL_TREE;
17412           break;
17413         }
17414
17415   processing_template_decl--;
17416
17417   if (!champ)
17418     return error_mark_node;
17419
17420   return champ;
17421 }
17422
17423 /* If DECL is a specialization of some template, return the most
17424    general such template.  Otherwise, returns NULL_TREE.
17425
17426    For example, given:
17427
17428      template <class T> struct S { template <class U> void f(U); };
17429
17430    if TMPL is `template <class U> void S<int>::f(U)' this will return
17431    the full template.  This function will not trace past partial
17432    specializations, however.  For example, given in addition:
17433
17434      template <class T> struct S<T*> { template <class U> void f(U); };
17435
17436    if TMPL is `template <class U> void S<int*>::f(U)' this will return
17437    `template <class T> template <class U> S<T*>::f(U)'.  */
17438
17439 tree
17440 most_general_template (tree decl)
17441 {
17442   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
17443      an immediate specialization.  */
17444   if (TREE_CODE (decl) == FUNCTION_DECL)
17445     {
17446       if (DECL_TEMPLATE_INFO (decl)) {
17447         decl = DECL_TI_TEMPLATE (decl);
17448
17449         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
17450            template friend.  */
17451         if (TREE_CODE (decl) != TEMPLATE_DECL)
17452           return NULL_TREE;
17453       } else
17454         return NULL_TREE;
17455     }
17456
17457   /* Look for more and more general templates.  */
17458   while (DECL_TEMPLATE_INFO (decl))
17459     {
17460       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
17461          (See cp-tree.h for details.)  */
17462       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
17463         break;
17464
17465       if (CLASS_TYPE_P (TREE_TYPE (decl))
17466           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
17467         break;
17468
17469       /* Stop if we run into an explicitly specialized class template.  */
17470       if (!DECL_NAMESPACE_SCOPE_P (decl)
17471           && DECL_CONTEXT (decl)
17472           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
17473         break;
17474
17475       decl = DECL_TI_TEMPLATE (decl);
17476     }
17477
17478   return decl;
17479 }
17480
17481 /* Return the most specialized of the class template partial
17482    specializations of TMPL which can produce TYPE, a specialization of
17483    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
17484    a _TYPE node corresponding to the partial specialization, while the
17485    TREE_PURPOSE is the set of template arguments that must be
17486    substituted into the TREE_TYPE in order to generate TYPE.
17487
17488    If the choice of partial specialization is ambiguous, a diagnostic
17489    is issued, and the error_mark_node is returned.  If there are no
17490    partial specializations of TMPL matching TYPE, then NULL_TREE is
17491    returned.  */
17492
17493 static tree
17494 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
17495 {
17496   tree list = NULL_TREE;
17497   tree t;
17498   tree champ;
17499   int fate;
17500   bool ambiguous_p;
17501   tree args;
17502   tree outer_args = NULL_TREE;
17503
17504   tmpl = most_general_template (tmpl);
17505   args = CLASSTYPE_TI_ARGS (type);
17506
17507   /* For determining which partial specialization to use, only the
17508      innermost args are interesting.  */
17509   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17510     {
17511       outer_args = strip_innermost_template_args (args, 1);
17512       args = INNERMOST_TEMPLATE_ARGS (args);
17513     }
17514
17515   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
17516     {
17517       tree partial_spec_args;
17518       tree spec_args;
17519       tree parms = TREE_VALUE (t);
17520
17521       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
17522
17523       ++processing_template_decl;
17524
17525       if (outer_args)
17526         {
17527           int i;
17528
17529           /* Discard the outer levels of args, and then substitute in the
17530              template args from the enclosing class.  */
17531           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
17532           partial_spec_args = tsubst_template_args
17533             (partial_spec_args, outer_args, tf_none, NULL_TREE);
17534
17535           /* PARMS already refers to just the innermost parms, but the
17536              template parms in partial_spec_args had their levels lowered
17537              by tsubst, so we need to do the same for the parm list.  We
17538              can't just tsubst the TREE_VEC itself, as tsubst wants to
17539              treat a TREE_VEC as an argument vector.  */
17540           parms = copy_node (parms);
17541           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
17542             TREE_VEC_ELT (parms, i) =
17543               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
17544
17545         }
17546
17547       partial_spec_args =
17548           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17549                                  add_to_template_args (outer_args,
17550                                                        partial_spec_args),
17551                                  tmpl, tf_none,
17552                                  /*require_all_args=*/true,
17553                                  /*use_default_args=*/true);
17554
17555       --processing_template_decl;
17556
17557       if (partial_spec_args == error_mark_node)
17558         return error_mark_node;
17559
17560       spec_args = get_class_bindings (parms,
17561                                       partial_spec_args,
17562                                       args);
17563       if (spec_args)
17564         {
17565           if (outer_args)
17566             spec_args = add_to_template_args (outer_args, spec_args);
17567           list = tree_cons (spec_args, TREE_VALUE (t), list);
17568           TREE_TYPE (list) = TREE_TYPE (t);
17569         }
17570     }
17571
17572   if (! list)
17573     return NULL_TREE;
17574
17575   ambiguous_p = false;
17576   t = list;
17577   champ = t;
17578   t = TREE_CHAIN (t);
17579   for (; t; t = TREE_CHAIN (t))
17580     {
17581       fate = more_specialized_class (champ, t);
17582       if (fate == 1)
17583         ;
17584       else
17585         {
17586           if (fate == 0)
17587             {
17588               t = TREE_CHAIN (t);
17589               if (! t)
17590                 {
17591                   ambiguous_p = true;
17592                   break;
17593                 }
17594             }
17595           champ = t;
17596         }
17597     }
17598
17599   if (!ambiguous_p)
17600     for (t = list; t && t != champ; t = TREE_CHAIN (t))
17601       {
17602         fate = more_specialized_class (champ, t);
17603         if (fate != 1)
17604           {
17605             ambiguous_p = true;
17606             break;
17607           }
17608       }
17609
17610   if (ambiguous_p)
17611     {
17612       const char *str;
17613       char *spaces = NULL;
17614       if (!(complain & tf_error))
17615         return error_mark_node;
17616       error ("ambiguous class template instantiation for %q#T", type);
17617       str = ngettext ("candidate is:", "candidates are:", list_length (list));
17618       for (t = list; t; t = TREE_CHAIN (t))
17619         {
17620           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
17621           spaces = spaces ? spaces : get_spaces (str);
17622         }
17623       free (spaces);
17624       return error_mark_node;
17625     }
17626
17627   return champ;
17628 }
17629
17630 /* Explicitly instantiate DECL.  */
17631
17632 void
17633 do_decl_instantiation (tree decl, tree storage)
17634 {
17635   tree result = NULL_TREE;
17636   int extern_p = 0;
17637
17638   if (!decl || decl == error_mark_node)
17639     /* An error occurred, for which grokdeclarator has already issued
17640        an appropriate message.  */
17641     return;
17642   else if (! DECL_LANG_SPECIFIC (decl))
17643     {
17644       error ("explicit instantiation of non-template %q#D", decl);
17645       return;
17646     }
17647   else if (TREE_CODE (decl) == VAR_DECL)
17648     {
17649       /* There is an asymmetry here in the way VAR_DECLs and
17650          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
17651          the latter, the DECL we get back will be marked as a
17652          template instantiation, and the appropriate
17653          DECL_TEMPLATE_INFO will be set up.  This does not happen for
17654          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
17655          should handle VAR_DECLs as it currently handles
17656          FUNCTION_DECLs.  */
17657       if (!DECL_CLASS_SCOPE_P (decl))
17658         {
17659           error ("%qD is not a static data member of a class template", decl);
17660           return;
17661         }
17662       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
17663       if (!result || TREE_CODE (result) != VAR_DECL)
17664         {
17665           error ("no matching template for %qD found", decl);
17666           return;
17667         }
17668       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
17669         {
17670           error ("type %qT for explicit instantiation %qD does not match "
17671                  "declared type %qT", TREE_TYPE (result), decl,
17672                  TREE_TYPE (decl));
17673           return;
17674         }
17675     }
17676   else if (TREE_CODE (decl) != FUNCTION_DECL)
17677     {
17678       error ("explicit instantiation of %q#D", decl);
17679       return;
17680     }
17681   else
17682     result = decl;
17683
17684   /* Check for various error cases.  Note that if the explicit
17685      instantiation is valid the RESULT will currently be marked as an
17686      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
17687      until we get here.  */
17688
17689   if (DECL_TEMPLATE_SPECIALIZATION (result))
17690     {
17691       /* DR 259 [temp.spec].
17692
17693          Both an explicit instantiation and a declaration of an explicit
17694          specialization shall not appear in a program unless the explicit
17695          instantiation follows a declaration of the explicit specialization.
17696
17697          For a given set of template parameters, if an explicit
17698          instantiation of a template appears after a declaration of an
17699          explicit specialization for that template, the explicit
17700          instantiation has no effect.  */
17701       return;
17702     }
17703   else if (DECL_EXPLICIT_INSTANTIATION (result))
17704     {
17705       /* [temp.spec]
17706
17707          No program shall explicitly instantiate any template more
17708          than once.
17709
17710          We check DECL_NOT_REALLY_EXTERN so as not to complain when
17711          the first instantiation was `extern' and the second is not,
17712          and EXTERN_P for the opposite case.  */
17713       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
17714         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
17715       /* If an "extern" explicit instantiation follows an ordinary
17716          explicit instantiation, the template is instantiated.  */
17717       if (extern_p)
17718         return;
17719     }
17720   else if (!DECL_IMPLICIT_INSTANTIATION (result))
17721     {
17722       error ("no matching template for %qD found", result);
17723       return;
17724     }
17725   else if (!DECL_TEMPLATE_INFO (result))
17726     {
17727       permerror (input_location, "explicit instantiation of non-template %q#D", result);
17728       return;
17729     }
17730
17731   if (storage == NULL_TREE)
17732     ;
17733   else if (storage == ridpointers[(int) RID_EXTERN])
17734     {
17735       if (!in_system_header && (cxx_dialect == cxx98))
17736         pedwarn (input_location, OPT_pedantic, 
17737                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
17738                  "instantiations");
17739       extern_p = 1;
17740     }
17741   else
17742     error ("storage class %qD applied to template instantiation", storage);
17743
17744   check_explicit_instantiation_namespace (result);
17745   mark_decl_instantiated (result, extern_p);
17746   if (! extern_p)
17747     instantiate_decl (result, /*defer_ok=*/1,
17748                       /*expl_inst_class_mem_p=*/false);
17749 }
17750
17751 static void
17752 mark_class_instantiated (tree t, int extern_p)
17753 {
17754   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
17755   SET_CLASSTYPE_INTERFACE_KNOWN (t);
17756   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
17757   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
17758   if (! extern_p)
17759     {
17760       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
17761       rest_of_type_compilation (t, 1);
17762     }
17763 }
17764
17765 /* Called from do_type_instantiation through binding_table_foreach to
17766    do recursive instantiation for the type bound in ENTRY.  */
17767 static void
17768 bt_instantiate_type_proc (binding_entry entry, void *data)
17769 {
17770   tree storage = *(tree *) data;
17771
17772   if (MAYBE_CLASS_TYPE_P (entry->type)
17773       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
17774     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
17775 }
17776
17777 /* Called from do_type_instantiation to instantiate a member
17778    (a member function or a static member variable) of an
17779    explicitly instantiated class template.  */
17780 static void
17781 instantiate_class_member (tree decl, int extern_p)
17782 {
17783   mark_decl_instantiated (decl, extern_p);
17784   if (! extern_p)
17785     instantiate_decl (decl, /*defer_ok=*/1,
17786                       /*expl_inst_class_mem_p=*/true);
17787 }
17788
17789 /* Perform an explicit instantiation of template class T.  STORAGE, if
17790    non-null, is the RID for extern, inline or static.  COMPLAIN is
17791    nonzero if this is called from the parser, zero if called recursively,
17792    since the standard is unclear (as detailed below).  */
17793
17794 void
17795 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
17796 {
17797   int extern_p = 0;
17798   int nomem_p = 0;
17799   int static_p = 0;
17800   int previous_instantiation_extern_p = 0;
17801
17802   if (TREE_CODE (t) == TYPE_DECL)
17803     t = TREE_TYPE (t);
17804
17805   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
17806     {
17807       tree tmpl =
17808         (TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
17809       if (tmpl)
17810         error ("explicit instantiation of non-class template %qD", tmpl);
17811       else
17812         error ("explicit instantiation of non-template type %qT", t);
17813       return;
17814     }
17815
17816   complete_type (t);
17817
17818   if (!COMPLETE_TYPE_P (t))
17819     {
17820       if (complain & tf_error)
17821         error ("explicit instantiation of %q#T before definition of template",
17822                t);
17823       return;
17824     }
17825
17826   if (storage != NULL_TREE)
17827     {
17828       if (!in_system_header)
17829         {
17830           if (storage == ridpointers[(int) RID_EXTERN])
17831             {
17832               if (cxx_dialect == cxx98)
17833                 pedwarn (input_location, OPT_pedantic, 
17834                          "ISO C++ 1998 forbids the use of %<extern%> on "
17835                          "explicit instantiations");
17836             }
17837           else
17838             pedwarn (input_location, OPT_pedantic, 
17839                      "ISO C++ forbids the use of %qE"
17840                      " on explicit instantiations", storage);
17841         }
17842
17843       if (storage == ridpointers[(int) RID_INLINE])
17844         nomem_p = 1;
17845       else if (storage == ridpointers[(int) RID_EXTERN])
17846         extern_p = 1;
17847       else if (storage == ridpointers[(int) RID_STATIC])
17848         static_p = 1;
17849       else
17850         {
17851           error ("storage class %qD applied to template instantiation",
17852                  storage);
17853           extern_p = 0;
17854         }
17855     }
17856
17857   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
17858     {
17859       /* DR 259 [temp.spec].
17860
17861          Both an explicit instantiation and a declaration of an explicit
17862          specialization shall not appear in a program unless the explicit
17863          instantiation follows a declaration of the explicit specialization.
17864
17865          For a given set of template parameters, if an explicit
17866          instantiation of a template appears after a declaration of an
17867          explicit specialization for that template, the explicit
17868          instantiation has no effect.  */
17869       return;
17870     }
17871   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
17872     {
17873       /* [temp.spec]
17874
17875          No program shall explicitly instantiate any template more
17876          than once.
17877
17878          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
17879          instantiation was `extern'.  If EXTERN_P then the second is.
17880          These cases are OK.  */
17881       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
17882
17883       if (!previous_instantiation_extern_p && !extern_p
17884           && (complain & tf_error))
17885         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
17886
17887       /* If we've already instantiated the template, just return now.  */
17888       if (!CLASSTYPE_INTERFACE_ONLY (t))
17889         return;
17890     }
17891
17892   check_explicit_instantiation_namespace (TYPE_NAME (t));
17893   mark_class_instantiated (t, extern_p);
17894
17895   if (nomem_p)
17896     return;
17897
17898   {
17899     tree tmp;
17900
17901     /* In contrast to implicit instantiation, where only the
17902        declarations, and not the definitions, of members are
17903        instantiated, we have here:
17904
17905          [temp.explicit]
17906
17907          The explicit instantiation of a class template specialization
17908          implies the instantiation of all of its members not
17909          previously explicitly specialized in the translation unit
17910          containing the explicit instantiation.
17911
17912        Of course, we can't instantiate member template classes, since
17913        we don't have any arguments for them.  Note that the standard
17914        is unclear on whether the instantiation of the members are
17915        *explicit* instantiations or not.  However, the most natural
17916        interpretation is that it should be an explicit instantiation.  */
17917
17918     if (! static_p)
17919       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
17920         if (TREE_CODE (tmp) == FUNCTION_DECL
17921             && DECL_TEMPLATE_INSTANTIATION (tmp))
17922           instantiate_class_member (tmp, extern_p);
17923
17924     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
17925       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
17926         instantiate_class_member (tmp, extern_p);
17927
17928     if (CLASSTYPE_NESTED_UTDS (t))
17929       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
17930                              bt_instantiate_type_proc, &storage);
17931   }
17932 }
17933
17934 /* Given a function DECL, which is a specialization of TMPL, modify
17935    DECL to be a re-instantiation of TMPL with the same template
17936    arguments.  TMPL should be the template into which tsubst'ing
17937    should occur for DECL, not the most general template.
17938
17939    One reason for doing this is a scenario like this:
17940
17941      template <class T>
17942      void f(const T&, int i);
17943
17944      void g() { f(3, 7); }
17945
17946      template <class T>
17947      void f(const T& t, const int i) { }
17948
17949    Note that when the template is first instantiated, with
17950    instantiate_template, the resulting DECL will have no name for the
17951    first parameter, and the wrong type for the second.  So, when we go
17952    to instantiate the DECL, we regenerate it.  */
17953
17954 static void
17955 regenerate_decl_from_template (tree decl, tree tmpl)
17956 {
17957   /* The arguments used to instantiate DECL, from the most general
17958      template.  */
17959   tree args;
17960   tree code_pattern;
17961
17962   args = DECL_TI_ARGS (decl);
17963   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
17964
17965   /* Make sure that we can see identifiers, and compute access
17966      correctly.  */
17967   push_access_scope (decl);
17968
17969   if (TREE_CODE (decl) == FUNCTION_DECL)
17970     {
17971       tree decl_parm;
17972       tree pattern_parm;
17973       tree specs;
17974       int args_depth;
17975       int parms_depth;
17976
17977       args_depth = TMPL_ARGS_DEPTH (args);
17978       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
17979       if (args_depth > parms_depth)
17980         args = get_innermost_template_args (args, parms_depth);
17981
17982       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
17983                                               args, tf_error, NULL_TREE,
17984                                               /*defer_ok*/false);
17985       if (specs && specs != error_mark_node)
17986         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
17987                                                     specs);
17988
17989       /* Merge parameter declarations.  */
17990       decl_parm = skip_artificial_parms_for (decl,
17991                                              DECL_ARGUMENTS (decl));
17992       pattern_parm
17993         = skip_artificial_parms_for (code_pattern,
17994                                      DECL_ARGUMENTS (code_pattern));
17995       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
17996         {
17997           tree parm_type;
17998           tree attributes;
17999           
18000           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
18001             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
18002           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
18003                               NULL_TREE);
18004           parm_type = type_decays_to (parm_type);
18005           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
18006             TREE_TYPE (decl_parm) = parm_type;
18007           attributes = DECL_ATTRIBUTES (pattern_parm);
18008           if (DECL_ATTRIBUTES (decl_parm) != attributes)
18009             {
18010               DECL_ATTRIBUTES (decl_parm) = attributes;
18011               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
18012             }
18013           decl_parm = DECL_CHAIN (decl_parm);
18014           pattern_parm = DECL_CHAIN (pattern_parm);
18015         }
18016       /* Merge any parameters that match with the function parameter
18017          pack.  */
18018       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
18019         {
18020           int i, len;
18021           tree expanded_types;
18022           /* Expand the TYPE_PACK_EXPANSION that provides the types for
18023              the parameters in this function parameter pack.  */
18024           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
18025                                                  args, tf_error, NULL_TREE);
18026           len = TREE_VEC_LENGTH (expanded_types);
18027           for (i = 0; i < len; i++)
18028             {
18029               tree parm_type;
18030               tree attributes;
18031           
18032               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
18033                 /* Rename the parameter to include the index.  */
18034                 DECL_NAME (decl_parm) = 
18035                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
18036               parm_type = TREE_VEC_ELT (expanded_types, i);
18037               parm_type = type_decays_to (parm_type);
18038               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
18039                 TREE_TYPE (decl_parm) = parm_type;
18040               attributes = DECL_ATTRIBUTES (pattern_parm);
18041               if (DECL_ATTRIBUTES (decl_parm) != attributes)
18042                 {
18043                   DECL_ATTRIBUTES (decl_parm) = attributes;
18044                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
18045                 }
18046               decl_parm = DECL_CHAIN (decl_parm);
18047             }
18048         }
18049       /* Merge additional specifiers from the CODE_PATTERN.  */
18050       if (DECL_DECLARED_INLINE_P (code_pattern)
18051           && !DECL_DECLARED_INLINE_P (decl))
18052         DECL_DECLARED_INLINE_P (decl) = 1;
18053     }
18054   else if (TREE_CODE (decl) == VAR_DECL)
18055     {
18056       DECL_INITIAL (decl) =
18057         tsubst_expr (DECL_INITIAL (code_pattern), args,
18058                      tf_error, DECL_TI_TEMPLATE (decl),
18059                      /*integral_constant_expression_p=*/false);
18060       if (VAR_HAD_UNKNOWN_BOUND (decl))
18061         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
18062                                    tf_error, DECL_TI_TEMPLATE (decl));
18063     }
18064   else
18065     gcc_unreachable ();
18066
18067   pop_access_scope (decl);
18068 }
18069
18070 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
18071    substituted to get DECL.  */
18072
18073 tree
18074 template_for_substitution (tree decl)
18075 {
18076   tree tmpl = DECL_TI_TEMPLATE (decl);
18077
18078   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
18079      for the instantiation.  This is not always the most general
18080      template.  Consider, for example:
18081
18082         template <class T>
18083         struct S { template <class U> void f();
18084                    template <> void f<int>(); };
18085
18086      and an instantiation of S<double>::f<int>.  We want TD to be the
18087      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
18088   while (/* An instantiation cannot have a definition, so we need a
18089             more general template.  */
18090          DECL_TEMPLATE_INSTANTIATION (tmpl)
18091            /* We must also deal with friend templates.  Given:
18092
18093                 template <class T> struct S {
18094                   template <class U> friend void f() {};
18095                 };
18096
18097               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
18098               so far as the language is concerned, but that's still
18099               where we get the pattern for the instantiation from.  On
18100               other hand, if the definition comes outside the class, say:
18101
18102                 template <class T> struct S {
18103                   template <class U> friend void f();
18104                 };
18105                 template <class U> friend void f() {}
18106
18107               we don't need to look any further.  That's what the check for
18108               DECL_INITIAL is for.  */
18109           || (TREE_CODE (decl) == FUNCTION_DECL
18110               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
18111               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
18112     {
18113       /* The present template, TD, should not be a definition.  If it
18114          were a definition, we should be using it!  Note that we
18115          cannot restructure the loop to just keep going until we find
18116          a template with a definition, since that might go too far if
18117          a specialization was declared, but not defined.  */
18118       gcc_assert (TREE_CODE (decl) != VAR_DECL
18119                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
18120
18121       /* Fetch the more general template.  */
18122       tmpl = DECL_TI_TEMPLATE (tmpl);
18123     }
18124
18125   return tmpl;
18126 }
18127
18128 /* Returns true if we need to instantiate this template instance even if we
18129    know we aren't going to emit it..  */
18130
18131 bool
18132 always_instantiate_p (tree decl)
18133 {
18134   /* We always instantiate inline functions so that we can inline them.  An
18135      explicit instantiation declaration prohibits implicit instantiation of
18136      non-inline functions.  With high levels of optimization, we would
18137      normally inline non-inline functions -- but we're not allowed to do
18138      that for "extern template" functions.  Therefore, we check
18139      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
18140   return ((TREE_CODE (decl) == FUNCTION_DECL
18141            && DECL_DECLARED_INLINE_P (decl))
18142           /* And we need to instantiate static data members so that
18143              their initializers are available in integral constant
18144              expressions.  */
18145           || (TREE_CODE (decl) == VAR_DECL
18146               && decl_maybe_constant_var_p (decl)));
18147 }
18148
18149 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
18150    instantiate it now, modifying TREE_TYPE (fn).  */
18151
18152 void
18153 maybe_instantiate_noexcept (tree fn)
18154 {
18155   tree fntype, spec, noex, clone;
18156
18157   if (DECL_CLONED_FUNCTION_P (fn))
18158     fn = DECL_CLONED_FUNCTION (fn);
18159   fntype = TREE_TYPE (fn);
18160   spec = TYPE_RAISES_EXCEPTIONS (fntype);
18161
18162   if (!DEFERRED_NOEXCEPT_SPEC_P (spec))
18163     return;
18164
18165   noex = TREE_PURPOSE (spec);
18166
18167   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
18168     {
18169       if (push_tinst_level (fn))
18170         {
18171           push_access_scope (fn);
18172           input_location = DECL_SOURCE_LOCATION (fn);
18173           noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
18174                                         DEFERRED_NOEXCEPT_ARGS (noex),
18175                                         tf_warning_or_error, fn,
18176                                         /*function_p=*/false,
18177                                         /*integral_constant_expression_p=*/true);
18178           pop_access_scope (fn);
18179           pop_tinst_level ();
18180           spec = build_noexcept_spec (noex, tf_warning_or_error);
18181           if (spec == error_mark_node)
18182             spec = noexcept_false_spec;
18183         }
18184       else
18185         spec = noexcept_false_spec;
18186     }
18187   else
18188     {
18189       /* This is an implicitly declared function, so NOEX is a list of
18190          other functions to evaluate and merge.  */
18191       tree elt;
18192       spec = noexcept_true_spec;
18193       for (elt = noex; elt; elt = OVL_NEXT (elt))
18194         {
18195           tree fn = OVL_CURRENT (elt);
18196           tree subspec;
18197           maybe_instantiate_noexcept (fn);
18198           subspec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn));
18199           spec = merge_exception_specifiers (spec, subspec, NULL_TREE);
18200         }
18201     }
18202
18203   TREE_TYPE (fn) = build_exception_variant (fntype, spec);
18204
18205   FOR_EACH_CLONE (clone, fn)
18206     {
18207       if (TREE_TYPE (clone) == fntype)
18208         TREE_TYPE (clone) = TREE_TYPE (fn);
18209       else
18210         TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
18211     }
18212 }
18213
18214 /* Produce the definition of D, a _DECL generated from a template.  If
18215    DEFER_OK is nonzero, then we don't have to actually do the
18216    instantiation now; we just have to do it sometime.  Normally it is
18217    an error if this is an explicit instantiation but D is undefined.
18218    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
18219    explicitly instantiated class template.  */
18220
18221 tree
18222 instantiate_decl (tree d, int defer_ok,
18223                   bool expl_inst_class_mem_p)
18224 {
18225   tree tmpl = DECL_TI_TEMPLATE (d);
18226   tree gen_args;
18227   tree args;
18228   tree td;
18229   tree code_pattern;
18230   tree spec;
18231   tree gen_tmpl;
18232   bool pattern_defined;
18233   int need_push;
18234   location_t saved_loc = input_location;
18235   bool external_p;
18236
18237   /* This function should only be used to instantiate templates for
18238      functions and static member variables.  */
18239   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
18240               || TREE_CODE (d) == VAR_DECL);
18241
18242   /* Variables are never deferred; if instantiation is required, they
18243      are instantiated right away.  That allows for better code in the
18244      case that an expression refers to the value of the variable --
18245      if the variable has a constant value the referring expression can
18246      take advantage of that fact.  */
18247   if (TREE_CODE (d) == VAR_DECL
18248       || DECL_DECLARED_CONSTEXPR_P (d))
18249     defer_ok = 0;
18250
18251   /* Don't instantiate cloned functions.  Instead, instantiate the
18252      functions they cloned.  */
18253   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
18254     d = DECL_CLONED_FUNCTION (d);
18255
18256   if (DECL_TEMPLATE_INSTANTIATED (d)
18257       || (TREE_CODE (d) == FUNCTION_DECL
18258           && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
18259       || DECL_TEMPLATE_SPECIALIZATION (d))
18260     /* D has already been instantiated or explicitly specialized, so
18261        there's nothing for us to do here.
18262
18263        It might seem reasonable to check whether or not D is an explicit
18264        instantiation, and, if so, stop here.  But when an explicit
18265        instantiation is deferred until the end of the compilation,
18266        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
18267        the instantiation.  */
18268     return d;
18269
18270   /* Check to see whether we know that this template will be
18271      instantiated in some other file, as with "extern template"
18272      extension.  */
18273   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
18274
18275   /* In general, we do not instantiate such templates.  */
18276   if (external_p && !always_instantiate_p (d))
18277     return d;
18278
18279   gen_tmpl = most_general_template (tmpl);
18280   gen_args = DECL_TI_ARGS (d);
18281
18282   if (tmpl != gen_tmpl)
18283     /* We should already have the extra args.  */
18284     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
18285                 == TMPL_ARGS_DEPTH (gen_args));
18286   /* And what's in the hash table should match D.  */
18287   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
18288               || spec == NULL_TREE);
18289
18290   /* This needs to happen before any tsubsting.  */
18291   if (! push_tinst_level (d))
18292     return d;
18293
18294   timevar_push (TV_TEMPLATE_INST);
18295
18296   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
18297      for the instantiation.  */
18298   td = template_for_substitution (d);
18299   code_pattern = DECL_TEMPLATE_RESULT (td);
18300
18301   /* We should never be trying to instantiate a member of a class
18302      template or partial specialization.  */
18303   gcc_assert (d != code_pattern);
18304
18305   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
18306       || DECL_TEMPLATE_SPECIALIZATION (td))
18307     /* In the case of a friend template whose definition is provided
18308        outside the class, we may have too many arguments.  Drop the
18309        ones we don't need.  The same is true for specializations.  */
18310     args = get_innermost_template_args
18311       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
18312   else
18313     args = gen_args;
18314
18315   if (TREE_CODE (d) == FUNCTION_DECL)
18316     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE
18317                        || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern));
18318   else
18319     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
18320
18321   /* We may be in the middle of deferred access check.  Disable it now.  */
18322   push_deferring_access_checks (dk_no_deferred);
18323
18324   /* Unless an explicit instantiation directive has already determined
18325      the linkage of D, remember that a definition is available for
18326      this entity.  */
18327   if (pattern_defined
18328       && !DECL_INTERFACE_KNOWN (d)
18329       && !DECL_NOT_REALLY_EXTERN (d))
18330     mark_definable (d);
18331
18332   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
18333   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
18334   input_location = DECL_SOURCE_LOCATION (d);
18335
18336   /* If D is a member of an explicitly instantiated class template,
18337      and no definition is available, treat it like an implicit
18338      instantiation.  */
18339   if (!pattern_defined && expl_inst_class_mem_p
18340       && DECL_EXPLICIT_INSTANTIATION (d))
18341     {
18342       /* Leave linkage flags alone on instantiations with anonymous
18343          visibility.  */
18344       if (TREE_PUBLIC (d))
18345         {
18346           DECL_NOT_REALLY_EXTERN (d) = 0;
18347           DECL_INTERFACE_KNOWN (d) = 0;
18348         }
18349       SET_DECL_IMPLICIT_INSTANTIATION (d);
18350     }
18351
18352   if (TREE_CODE (d) == FUNCTION_DECL)
18353     maybe_instantiate_noexcept (d);
18354
18355   /* Recheck the substitutions to obtain any warning messages
18356      about ignoring cv qualifiers.  Don't do this for artificial decls,
18357      as it breaks the context-sensitive substitution for lambda op(). */
18358   if (!defer_ok && !DECL_ARTIFICIAL (d))
18359     {
18360       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
18361       tree type = TREE_TYPE (gen);
18362
18363       /* Make sure that we can see identifiers, and compute access
18364          correctly.  D is already the target FUNCTION_DECL with the
18365          right context.  */
18366       push_access_scope (d);
18367
18368       if (TREE_CODE (gen) == FUNCTION_DECL)
18369         {
18370           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
18371           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
18372                                           d, /*defer_ok*/true);
18373           /* Don't simply tsubst the function type, as that will give
18374              duplicate warnings about poor parameter qualifications.
18375              The function arguments are the same as the decl_arguments
18376              without the top level cv qualifiers.  */
18377           type = TREE_TYPE (type);
18378         }
18379       tsubst (type, gen_args, tf_warning_or_error, d);
18380
18381       pop_access_scope (d);
18382     }
18383
18384   /* Defer all other templates, unless we have been explicitly
18385      forbidden from doing so.  */
18386   if (/* If there is no definition, we cannot instantiate the
18387          template.  */
18388       ! pattern_defined
18389       /* If it's OK to postpone instantiation, do so.  */
18390       || defer_ok
18391       /* If this is a static data member that will be defined
18392          elsewhere, we don't want to instantiate the entire data
18393          member, but we do want to instantiate the initializer so that
18394          we can substitute that elsewhere.  */
18395       || (external_p && TREE_CODE (d) == VAR_DECL))
18396     {
18397       /* The definition of the static data member is now required so
18398          we must substitute the initializer.  */
18399       if (TREE_CODE (d) == VAR_DECL
18400           && !DECL_INITIAL (d)
18401           && DECL_INITIAL (code_pattern))
18402         {
18403           tree ns;
18404           tree init;
18405           bool const_init = false;
18406
18407           ns = decl_namespace_context (d);
18408           push_nested_namespace (ns);
18409           push_nested_class (DECL_CONTEXT (d));
18410           init = tsubst_expr (DECL_INITIAL (code_pattern),
18411                               args,
18412                               tf_warning_or_error, NULL_TREE,
18413                               /*integral_constant_expression_p=*/false);
18414           /* Make sure the initializer is still constant, in case of
18415              circular dependency (template/instantiate6.C). */
18416           const_init
18417             = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18418           cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
18419                           /*asmspec_tree=*/NULL_TREE,
18420                           LOOKUP_ONLYCONVERTING);
18421           pop_nested_class ();
18422           pop_nested_namespace (ns);
18423         }
18424
18425       /* We restore the source position here because it's used by
18426          add_pending_template.  */
18427       input_location = saved_loc;
18428
18429       if (at_eof && !pattern_defined
18430           && DECL_EXPLICIT_INSTANTIATION (d)
18431           && DECL_NOT_REALLY_EXTERN (d))
18432         /* [temp.explicit]
18433
18434            The definition of a non-exported function template, a
18435            non-exported member function template, or a non-exported
18436            member function or static data member of a class template
18437            shall be present in every translation unit in which it is
18438            explicitly instantiated.  */
18439         permerror (input_location,  "explicit instantiation of %qD "
18440                    "but no definition available", d);
18441
18442       /* If we're in unevaluated context, we just wanted to get the
18443          constant value; this isn't an odr use, so don't queue
18444          a full instantiation.  */
18445       if (cp_unevaluated_operand != 0)
18446         goto out;
18447       /* ??? Historically, we have instantiated inline functions, even
18448          when marked as "extern template".  */
18449       if (!(external_p && TREE_CODE (d) == VAR_DECL))
18450         add_pending_template (d);
18451       goto out;
18452     }
18453   /* Tell the repository that D is available in this translation unit
18454      -- and see if it is supposed to be instantiated here.  */
18455   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
18456     {
18457       /* In a PCH file, despite the fact that the repository hasn't
18458          requested instantiation in the PCH it is still possible that
18459          an instantiation will be required in a file that includes the
18460          PCH.  */
18461       if (pch_file)
18462         add_pending_template (d);
18463       /* Instantiate inline functions so that the inliner can do its
18464          job, even though we'll not be emitting a copy of this
18465          function.  */
18466       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
18467         goto out;
18468     }
18469
18470   need_push = !cfun || !global_bindings_p ();
18471   if (need_push)
18472     push_to_top_level ();
18473
18474   /* Mark D as instantiated so that recursive calls to
18475      instantiate_decl do not try to instantiate it again.  */
18476   DECL_TEMPLATE_INSTANTIATED (d) = 1;
18477
18478   /* Regenerate the declaration in case the template has been modified
18479      by a subsequent redeclaration.  */
18480   regenerate_decl_from_template (d, td);
18481
18482   /* We already set the file and line above.  Reset them now in case
18483      they changed as a result of calling regenerate_decl_from_template.  */
18484   input_location = DECL_SOURCE_LOCATION (d);
18485
18486   if (TREE_CODE (d) == VAR_DECL)
18487     {
18488       tree init;
18489       bool const_init = false;
18490
18491       /* Clear out DECL_RTL; whatever was there before may not be right
18492          since we've reset the type of the declaration.  */
18493       SET_DECL_RTL (d, NULL);
18494       DECL_IN_AGGR_P (d) = 0;
18495
18496       /* The initializer is placed in DECL_INITIAL by
18497          regenerate_decl_from_template so we don't need to
18498          push/pop_access_scope again here.  Pull it out so that
18499          cp_finish_decl can process it.  */
18500       init = DECL_INITIAL (d);
18501       DECL_INITIAL (d) = NULL_TREE;
18502       DECL_INITIALIZED_P (d) = 0;
18503
18504       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
18505          initializer.  That function will defer actual emission until
18506          we have a chance to determine linkage.  */
18507       DECL_EXTERNAL (d) = 0;
18508
18509       /* Enter the scope of D so that access-checking works correctly.  */
18510       push_nested_class (DECL_CONTEXT (d));
18511       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18512       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
18513       pop_nested_class ();
18514     }
18515   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
18516     synthesize_method (d);
18517   else if (TREE_CODE (d) == FUNCTION_DECL)
18518     {
18519       htab_t saved_local_specializations;
18520       tree subst_decl;
18521       tree tmpl_parm;
18522       tree spec_parm;
18523
18524       /* Save away the current list, in case we are instantiating one
18525          template from within the body of another.  */
18526       saved_local_specializations = local_specializations;
18527
18528       /* Set up the list of local specializations.  */
18529       local_specializations = htab_create (37,
18530                                            hash_local_specialization,
18531                                            eq_local_specializations,
18532                                            NULL);
18533
18534       /* Set up context.  */
18535       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
18536
18537       /* Create substitution entries for the parameters.  */
18538       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
18539       tmpl_parm = DECL_ARGUMENTS (subst_decl);
18540       spec_parm = DECL_ARGUMENTS (d);
18541       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
18542         {
18543           register_local_specialization (spec_parm, tmpl_parm);
18544           spec_parm = skip_artificial_parms_for (d, spec_parm);
18545           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
18546         }
18547       for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
18548         {
18549           if (!FUNCTION_PARAMETER_PACK_P (tmpl_parm))
18550             {
18551               register_local_specialization (spec_parm, tmpl_parm);
18552               spec_parm = DECL_CHAIN (spec_parm);
18553             }
18554           else
18555             {
18556               /* Register the (value) argument pack as a specialization of
18557                  TMPL_PARM, then move on.  */
18558               tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
18559               register_local_specialization (argpack, tmpl_parm);
18560             }
18561         }
18562       gcc_assert (!spec_parm);
18563
18564       /* Substitute into the body of the function.  */
18565       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
18566                    tf_warning_or_error, tmpl,
18567                    /*integral_constant_expression_p=*/false);
18568
18569       /* Set the current input_location to the end of the function
18570          so that finish_function knows where we are.  */
18571       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
18572
18573       /* We don't need the local specializations any more.  */
18574       htab_delete (local_specializations);
18575       local_specializations = saved_local_specializations;
18576
18577       /* Finish the function.  */
18578       d = finish_function (0);
18579       expand_or_defer_fn (d);
18580     }
18581
18582   /* We're not deferring instantiation any more.  */
18583   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
18584
18585   if (need_push)
18586     pop_from_top_level ();
18587
18588 out:
18589   input_location = saved_loc;
18590   pop_deferring_access_checks ();
18591   pop_tinst_level ();
18592
18593   timevar_pop (TV_TEMPLATE_INST);
18594
18595   return d;
18596 }
18597
18598 /* Run through the list of templates that we wish we could
18599    instantiate, and instantiate any we can.  RETRIES is the
18600    number of times we retry pending template instantiation.  */
18601
18602 void
18603 instantiate_pending_templates (int retries)
18604 {
18605   int reconsider;
18606   location_t saved_loc = input_location;
18607
18608   /* Instantiating templates may trigger vtable generation.  This in turn
18609      may require further template instantiations.  We place a limit here
18610      to avoid infinite loop.  */
18611   if (pending_templates && retries >= max_tinst_depth)
18612     {
18613       tree decl = pending_templates->tinst->decl;
18614
18615       error ("template instantiation depth exceeds maximum of %d"
18616              " instantiating %q+D, possibly from virtual table generation"
18617              " (use -ftemplate-depth= to increase the maximum)",
18618              max_tinst_depth, decl);
18619       if (TREE_CODE (decl) == FUNCTION_DECL)
18620         /* Pretend that we defined it.  */
18621         DECL_INITIAL (decl) = error_mark_node;
18622       return;
18623     }
18624
18625   do
18626     {
18627       struct pending_template **t = &pending_templates;
18628       struct pending_template *last = NULL;
18629       reconsider = 0;
18630       while (*t)
18631         {
18632           tree instantiation = reopen_tinst_level ((*t)->tinst);
18633           bool complete = false;
18634
18635           if (TYPE_P (instantiation))
18636             {
18637               tree fn;
18638
18639               if (!COMPLETE_TYPE_P (instantiation))
18640                 {
18641                   instantiate_class_template (instantiation);
18642                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
18643                     for (fn = TYPE_METHODS (instantiation);
18644                          fn;
18645                          fn = TREE_CHAIN (fn))
18646                       if (! DECL_ARTIFICIAL (fn))
18647                         instantiate_decl (fn,
18648                                           /*defer_ok=*/0,
18649                                           /*expl_inst_class_mem_p=*/false);
18650                   if (COMPLETE_TYPE_P (instantiation))
18651                     reconsider = 1;
18652                 }
18653
18654               complete = COMPLETE_TYPE_P (instantiation);
18655             }
18656           else
18657             {
18658               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
18659                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
18660                 {
18661                   instantiation
18662                     = instantiate_decl (instantiation,
18663                                         /*defer_ok=*/0,
18664                                         /*expl_inst_class_mem_p=*/false);
18665                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
18666                     reconsider = 1;
18667                 }
18668
18669               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
18670                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
18671             }
18672
18673           if (complete)
18674             /* If INSTANTIATION has been instantiated, then we don't
18675                need to consider it again in the future.  */
18676             *t = (*t)->next;
18677           else
18678             {
18679               last = *t;
18680               t = &(*t)->next;
18681             }
18682           tinst_depth = 0;
18683           current_tinst_level = NULL;
18684         }
18685       last_pending_template = last;
18686     }
18687   while (reconsider);
18688
18689   input_location = saved_loc;
18690 }
18691
18692 /* Substitute ARGVEC into T, which is a list of initializers for
18693    either base class or a non-static data member.  The TREE_PURPOSEs
18694    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
18695    instantiate_decl.  */
18696
18697 static tree
18698 tsubst_initializer_list (tree t, tree argvec)
18699 {
18700   tree inits = NULL_TREE;
18701
18702   for (; t; t = TREE_CHAIN (t))
18703     {
18704       tree decl;
18705       tree init;
18706       tree expanded_bases = NULL_TREE;
18707       tree expanded_arguments = NULL_TREE;
18708       int i, len = 1;
18709
18710       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
18711         {
18712           tree expr;
18713           tree arg;
18714
18715           /* Expand the base class expansion type into separate base
18716              classes.  */
18717           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
18718                                                  tf_warning_or_error,
18719                                                  NULL_TREE);
18720           if (expanded_bases == error_mark_node)
18721             continue;
18722           
18723           /* We'll be building separate TREE_LISTs of arguments for
18724              each base.  */
18725           len = TREE_VEC_LENGTH (expanded_bases);
18726           expanded_arguments = make_tree_vec (len);
18727           for (i = 0; i < len; i++)
18728             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
18729
18730           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
18731              expand each argument in the TREE_VALUE of t.  */
18732           expr = make_node (EXPR_PACK_EXPANSION);
18733           PACK_EXPANSION_PARAMETER_PACKS (expr) =
18734             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
18735
18736           if (TREE_VALUE (t) == void_type_node)
18737             /* VOID_TYPE_NODE is used to indicate
18738                value-initialization.  */
18739             {
18740               for (i = 0; i < len; i++)
18741                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
18742             }
18743           else
18744             {
18745               /* Substitute parameter packs into each argument in the
18746                  TREE_LIST.  */
18747               in_base_initializer = 1;
18748               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
18749                 {
18750                   tree expanded_exprs;
18751
18752                   /* Expand the argument.  */
18753                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
18754                   expanded_exprs 
18755                     = tsubst_pack_expansion (expr, argvec,
18756                                              tf_warning_or_error,
18757                                              NULL_TREE);
18758                   if (expanded_exprs == error_mark_node)
18759                     continue;
18760
18761                   /* Prepend each of the expanded expressions to the
18762                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
18763                   for (i = 0; i < len; i++)
18764                     {
18765                       TREE_VEC_ELT (expanded_arguments, i) = 
18766                         tree_cons (NULL_TREE, 
18767                                    TREE_VEC_ELT (expanded_exprs, i),
18768                                    TREE_VEC_ELT (expanded_arguments, i));
18769                     }
18770                 }
18771               in_base_initializer = 0;
18772
18773               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
18774                  since we built them backwards.  */
18775               for (i = 0; i < len; i++)
18776                 {
18777                   TREE_VEC_ELT (expanded_arguments, i) = 
18778                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
18779                 }
18780             }
18781         }
18782
18783       for (i = 0; i < len; ++i)
18784         {
18785           if (expanded_bases)
18786             {
18787               decl = TREE_VEC_ELT (expanded_bases, i);
18788               decl = expand_member_init (decl);
18789               init = TREE_VEC_ELT (expanded_arguments, i);
18790             }
18791           else
18792             {
18793               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
18794                                   tf_warning_or_error, NULL_TREE);
18795
18796               decl = expand_member_init (decl);
18797               if (decl && !DECL_P (decl))
18798                 in_base_initializer = 1;
18799
18800               init = TREE_VALUE (t);
18801               if (init != void_type_node)
18802                 init = tsubst_expr (init, argvec,
18803                                     tf_warning_or_error, NULL_TREE,
18804                                     /*integral_constant_expression_p=*/false);
18805               in_base_initializer = 0;
18806             }
18807
18808           if (decl)
18809             {
18810               init = build_tree_list (decl, init);
18811               TREE_CHAIN (init) = inits;
18812               inits = init;
18813             }
18814         }
18815     }
18816   return inits;
18817 }
18818
18819 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
18820
18821 static void
18822 set_current_access_from_decl (tree decl)
18823 {
18824   if (TREE_PRIVATE (decl))
18825     current_access_specifier = access_private_node;
18826   else if (TREE_PROTECTED (decl))
18827     current_access_specifier = access_protected_node;
18828   else
18829     current_access_specifier = access_public_node;
18830 }
18831
18832 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
18833    is the instantiation (which should have been created with
18834    start_enum) and ARGS are the template arguments to use.  */
18835
18836 static void
18837 tsubst_enum (tree tag, tree newtag, tree args)
18838 {
18839   tree e;
18840
18841   if (SCOPED_ENUM_P (newtag))
18842     begin_scope (sk_scoped_enum, newtag);
18843
18844   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
18845     {
18846       tree value;
18847       tree decl;
18848
18849       decl = TREE_VALUE (e);
18850       /* Note that in a template enum, the TREE_VALUE is the
18851          CONST_DECL, not the corresponding INTEGER_CST.  */
18852       value = tsubst_expr (DECL_INITIAL (decl),
18853                            args, tf_warning_or_error, NULL_TREE,
18854                            /*integral_constant_expression_p=*/true);
18855
18856       /* Give this enumeration constant the correct access.  */
18857       set_current_access_from_decl (decl);
18858
18859       /* Actually build the enumerator itself.  */
18860       build_enumerator
18861         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
18862     }
18863
18864   if (SCOPED_ENUM_P (newtag))
18865     finish_scope ();
18866
18867   finish_enum_value_list (newtag);
18868   finish_enum (newtag);
18869
18870   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
18871     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
18872 }
18873
18874 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
18875    its type -- but without substituting the innermost set of template
18876    arguments.  So, innermost set of template parameters will appear in
18877    the type.  */
18878
18879 tree
18880 get_mostly_instantiated_function_type (tree decl)
18881 {
18882   tree fn_type;
18883   tree tmpl;
18884   tree targs;
18885   tree tparms;
18886   int parm_depth;
18887
18888   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
18889   targs = DECL_TI_ARGS (decl);
18890   tparms = DECL_TEMPLATE_PARMS (tmpl);
18891   parm_depth = TMPL_PARMS_DEPTH (tparms);
18892
18893   /* There should be as many levels of arguments as there are levels
18894      of parameters.  */
18895   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
18896
18897   fn_type = TREE_TYPE (tmpl);
18898
18899   if (parm_depth == 1)
18900     /* No substitution is necessary.  */
18901     ;
18902   else
18903     {
18904       int i;
18905       tree partial_args;
18906
18907       /* Replace the innermost level of the TARGS with NULL_TREEs to
18908          let tsubst know not to substitute for those parameters.  */
18909       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
18910       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
18911         SET_TMPL_ARGS_LEVEL (partial_args, i,
18912                              TMPL_ARGS_LEVEL (targs, i));
18913       SET_TMPL_ARGS_LEVEL (partial_args,
18914                            TMPL_ARGS_DEPTH (targs),
18915                            make_tree_vec (DECL_NTPARMS (tmpl)));
18916
18917       /* Make sure that we can see identifiers, and compute access
18918          correctly.  */
18919       push_access_scope (decl);
18920
18921       ++processing_template_decl;
18922       /* Now, do the (partial) substitution to figure out the
18923          appropriate function type.  */
18924       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
18925       --processing_template_decl;
18926
18927       /* Substitute into the template parameters to obtain the real
18928          innermost set of parameters.  This step is important if the
18929          innermost set of template parameters contains value
18930          parameters whose types depend on outer template parameters.  */
18931       TREE_VEC_LENGTH (partial_args)--;
18932       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
18933
18934       pop_access_scope (decl);
18935     }
18936
18937   return fn_type;
18938 }
18939
18940 /* Return truthvalue if we're processing a template different from
18941    the last one involved in diagnostics.  */
18942 int
18943 problematic_instantiation_changed (void)
18944 {
18945   return current_tinst_level != last_error_tinst_level;
18946 }
18947
18948 /* Remember current template involved in diagnostics.  */
18949 void
18950 record_last_problematic_instantiation (void)
18951 {
18952   last_error_tinst_level = current_tinst_level;
18953 }
18954
18955 struct tinst_level *
18956 current_instantiation (void)
18957 {
18958   return current_tinst_level;
18959 }
18960
18961 /* [temp.param] Check that template non-type parm TYPE is of an allowable
18962    type. Return zero for ok, nonzero for disallowed. Issue error and
18963    warning messages under control of COMPLAIN.  */
18964
18965 static int
18966 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
18967 {
18968   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
18969     return 0;
18970   else if (POINTER_TYPE_P (type))
18971     return 0;
18972   else if (TYPE_PTR_TO_MEMBER_P (type))
18973     return 0;
18974   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
18975     return 0;
18976   else if (TREE_CODE (type) == TYPENAME_TYPE)
18977     return 0;
18978   else if (TREE_CODE (type) == DECLTYPE_TYPE)
18979     return 0;
18980   else if (TREE_CODE (type) == NULLPTR_TYPE)
18981     return 0;
18982
18983   if (complain & tf_error)
18984     {
18985       if (type == error_mark_node)
18986         inform (input_location, "invalid template non-type parameter");
18987       else
18988         error ("%q#T is not a valid type for a template non-type parameter",
18989                type);
18990     }
18991   return 1;
18992 }
18993
18994 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
18995    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
18996
18997 static bool
18998 dependent_type_p_r (tree type)
18999 {
19000   tree scope;
19001
19002   /* [temp.dep.type]
19003
19004      A type is dependent if it is:
19005
19006      -- a template parameter. Template template parameters are types
19007         for us (since TYPE_P holds true for them) so we handle
19008         them here.  */
19009   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
19010       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
19011     return true;
19012   /* -- a qualified-id with a nested-name-specifier which contains a
19013         class-name that names a dependent type or whose unqualified-id
19014         names a dependent type.  */
19015   if (TREE_CODE (type) == TYPENAME_TYPE)
19016     return true;
19017   /* -- a cv-qualified type where the cv-unqualified type is
19018         dependent.  */
19019   type = TYPE_MAIN_VARIANT (type);
19020   /* -- a compound type constructed from any dependent type.  */
19021   if (TYPE_PTR_TO_MEMBER_P (type))
19022     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
19023             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
19024                                            (type)));
19025   else if (TREE_CODE (type) == POINTER_TYPE
19026            || TREE_CODE (type) == REFERENCE_TYPE)
19027     return dependent_type_p (TREE_TYPE (type));
19028   else if (TREE_CODE (type) == FUNCTION_TYPE
19029            || TREE_CODE (type) == METHOD_TYPE)
19030     {
19031       tree arg_type;
19032
19033       if (dependent_type_p (TREE_TYPE (type)))
19034         return true;
19035       for (arg_type = TYPE_ARG_TYPES (type);
19036            arg_type;
19037            arg_type = TREE_CHAIN (arg_type))
19038         if (dependent_type_p (TREE_VALUE (arg_type)))
19039           return true;
19040       return false;
19041     }
19042   /* -- an array type constructed from any dependent type or whose
19043         size is specified by a constant expression that is
19044         value-dependent.
19045
19046         We checked for type- and value-dependence of the bounds in
19047         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
19048   if (TREE_CODE (type) == ARRAY_TYPE)
19049     {
19050       if (TYPE_DOMAIN (type)
19051           && dependent_type_p (TYPE_DOMAIN (type)))
19052         return true;
19053       return dependent_type_p (TREE_TYPE (type));
19054     }
19055
19056   /* -- a template-id in which either the template name is a template
19057      parameter ...  */
19058   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
19059     return true;
19060   /* ... or any of the template arguments is a dependent type or
19061         an expression that is type-dependent or value-dependent.  */
19062   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
19063            && (any_dependent_template_arguments_p
19064                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
19065     return true;
19066
19067   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
19068      dependent; if the argument of the `typeof' expression is not
19069      type-dependent, then it should already been have resolved.  */
19070   if (TREE_CODE (type) == TYPEOF_TYPE
19071       || TREE_CODE (type) == DECLTYPE_TYPE
19072       || TREE_CODE (type) == UNDERLYING_TYPE)
19073     return true;
19074
19075   /* A template argument pack is dependent if any of its packed
19076      arguments are.  */
19077   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
19078     {
19079       tree args = ARGUMENT_PACK_ARGS (type);
19080       int i, len = TREE_VEC_LENGTH (args);
19081       for (i = 0; i < len; ++i)
19082         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
19083           return true;
19084     }
19085
19086   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
19087      be template parameters.  */
19088   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
19089     return true;
19090
19091   /* The standard does not specifically mention types that are local
19092      to template functions or local classes, but they should be
19093      considered dependent too.  For example:
19094
19095        template <int I> void f() {
19096          enum E { a = I };
19097          S<sizeof (E)> s;
19098        }
19099
19100      The size of `E' cannot be known until the value of `I' has been
19101      determined.  Therefore, `E' must be considered dependent.  */
19102   scope = TYPE_CONTEXT (type);
19103   if (scope && TYPE_P (scope))
19104     return dependent_type_p (scope);
19105   /* Don't use type_dependent_expression_p here, as it can lead
19106      to infinite recursion trying to determine whether a lambda
19107      nested in a lambda is dependent (c++/47687).  */
19108   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
19109            && DECL_LANG_SPECIFIC (scope)
19110            && DECL_TEMPLATE_INFO (scope)
19111            && (any_dependent_template_arguments_p
19112                (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
19113     return true;
19114
19115   /* Other types are non-dependent.  */
19116   return false;
19117 }
19118
19119 /* Returns TRUE if TYPE is dependent, in the sense of
19120    [temp.dep.type].  Note that a NULL type is considered dependent.  */
19121
19122 bool
19123 dependent_type_p (tree type)
19124 {
19125   /* If there are no template parameters in scope, then there can't be
19126      any dependent types.  */
19127   if (!processing_template_decl)
19128     {
19129       /* If we are not processing a template, then nobody should be
19130          providing us with a dependent type.  */
19131       gcc_assert (type);
19132       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
19133       return false;
19134     }
19135
19136   /* If the type is NULL, we have not computed a type for the entity
19137      in question; in that case, the type is dependent.  */
19138   if (!type)
19139     return true;
19140
19141   /* Erroneous types can be considered non-dependent.  */
19142   if (type == error_mark_node)
19143     return false;
19144
19145   /* If we have not already computed the appropriate value for TYPE,
19146      do so now.  */
19147   if (!TYPE_DEPENDENT_P_VALID (type))
19148     {
19149       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
19150       TYPE_DEPENDENT_P_VALID (type) = 1;
19151     }
19152
19153   return TYPE_DEPENDENT_P (type);
19154 }
19155
19156 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
19157    lookup.  In other words, a dependent type that is not the current
19158    instantiation.  */
19159
19160 bool
19161 dependent_scope_p (tree scope)
19162 {
19163   return (scope && TYPE_P (scope) && dependent_type_p (scope)
19164           && !currently_open_class (scope));
19165 }
19166
19167 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
19168    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
19169    expression.  */
19170
19171 /* Note that this predicate is not appropriate for general expressions;
19172    only constant expressions (that satisfy potential_constant_expression)
19173    can be tested for value dependence.
19174
19175    We should really also have a predicate for "instantiation-dependent".
19176
19177    fold_non_dependent_expr: fold if constant and not type-dependent and not value-dependent.
19178      (what about instantiation-dependent constant-expressions?)
19179    is_late_template_attribute: defer if instantiation-dependent.
19180    compute_array_index_type: proceed if constant and not t- or v-dependent
19181      if instantiation-dependent, need to remember full expression
19182    uses_template_parms: FIXME - need to audit callers
19183    tsubst_decl [function_decl]: Why is this using value_dependent_expression_p?
19184    dependent_type_p [array_type]: dependent if index type is dependent
19185      (or non-constant?)
19186    static_assert - instantiation-dependent */
19187
19188 bool
19189 value_dependent_expression_p (tree expression)
19190 {
19191   if (!processing_template_decl)
19192     return false;
19193
19194   /* A name declared with a dependent type.  */
19195   if (DECL_P (expression) && type_dependent_expression_p (expression))
19196     return true;
19197
19198   switch (TREE_CODE (expression))
19199     {
19200     case IDENTIFIER_NODE:
19201       /* A name that has not been looked up -- must be dependent.  */
19202       return true;
19203
19204     case TEMPLATE_PARM_INDEX:
19205       /* A non-type template parm.  */
19206       return true;
19207
19208     case CONST_DECL:
19209       /* A non-type template parm.  */
19210       if (DECL_TEMPLATE_PARM_P (expression))
19211         return true;
19212       return value_dependent_expression_p (DECL_INITIAL (expression));
19213
19214     case VAR_DECL:
19215        /* A constant with literal type and is initialized
19216           with an expression that is value-dependent.  */
19217       if (DECL_INITIAL (expression)
19218           && decl_constant_var_p (expression)
19219           && value_dependent_expression_p (DECL_INITIAL (expression)))
19220         return true;
19221       return false;
19222
19223     case DYNAMIC_CAST_EXPR:
19224     case STATIC_CAST_EXPR:
19225     case CONST_CAST_EXPR:
19226     case REINTERPRET_CAST_EXPR:
19227     case CAST_EXPR:
19228       /* These expressions are value-dependent if the type to which
19229          the cast occurs is dependent or the expression being casted
19230          is value-dependent.  */
19231       {
19232         tree type = TREE_TYPE (expression);
19233
19234         if (dependent_type_p (type))
19235           return true;
19236
19237         /* A functional cast has a list of operands.  */
19238         expression = TREE_OPERAND (expression, 0);
19239         if (!expression)
19240           {
19241             /* If there are no operands, it must be an expression such
19242                as "int()". This should not happen for aggregate types
19243                because it would form non-constant expressions.  */
19244             gcc_assert (cxx_dialect >= cxx0x
19245                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
19246
19247             return false;
19248           }
19249
19250         if (TREE_CODE (expression) == TREE_LIST)
19251           return any_value_dependent_elements_p (expression);
19252
19253         return value_dependent_expression_p (expression);
19254       }
19255
19256     case SIZEOF_EXPR:
19257     case ALIGNOF_EXPR:
19258     case TYPEID_EXPR:
19259       /* A `sizeof' expression is value-dependent if the operand is
19260          type-dependent or is a pack expansion.  */
19261       expression = TREE_OPERAND (expression, 0);
19262       if (PACK_EXPANSION_P (expression))
19263         return true;
19264       else if (TYPE_P (expression))
19265         return dependent_type_p (expression);
19266       return type_dependent_expression_p (expression);
19267
19268     case AT_ENCODE_EXPR:
19269       /* An 'encode' expression is value-dependent if the operand is
19270          type-dependent.  */
19271       expression = TREE_OPERAND (expression, 0);
19272       return dependent_type_p (expression);
19273
19274     case NOEXCEPT_EXPR:
19275       expression = TREE_OPERAND (expression, 0);
19276       return type_dependent_expression_p (expression);
19277
19278     case SCOPE_REF:
19279       {
19280         tree name = TREE_OPERAND (expression, 1);
19281         return value_dependent_expression_p (name);
19282       }
19283
19284     case COMPONENT_REF:
19285       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
19286               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
19287
19288     case NONTYPE_ARGUMENT_PACK:
19289       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
19290          is value-dependent.  */
19291       {
19292         tree values = ARGUMENT_PACK_ARGS (expression);
19293         int i, len = TREE_VEC_LENGTH (values);
19294         
19295         for (i = 0; i < len; ++i)
19296           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
19297             return true;
19298         
19299         return false;
19300       }
19301
19302     case TRAIT_EXPR:
19303       {
19304         tree type2 = TRAIT_EXPR_TYPE2 (expression);
19305         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
19306                 || (type2 ? dependent_type_p (type2) : false));
19307       }
19308
19309     case MODOP_EXPR:
19310       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19311               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
19312
19313     case ARRAY_REF:
19314       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19315               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
19316
19317     case ADDR_EXPR:
19318       {
19319         tree op = TREE_OPERAND (expression, 0);
19320         return (value_dependent_expression_p (op)
19321                 || has_value_dependent_address (op));
19322       }
19323
19324     case CALL_EXPR:
19325       {
19326         tree fn = get_callee_fndecl (expression);
19327         int i, nargs;
19328         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
19329           return true;
19330         nargs = call_expr_nargs (expression);
19331         for (i = 0; i < nargs; ++i)
19332           {
19333             tree op = CALL_EXPR_ARG (expression, i);
19334             /* In a call to a constexpr member function, look through the
19335                implicit ADDR_EXPR on the object argument so that it doesn't
19336                cause the call to be considered value-dependent.  We also
19337                look through it in potential_constant_expression.  */
19338             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
19339                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
19340                 && TREE_CODE (op) == ADDR_EXPR)
19341               op = TREE_OPERAND (op, 0);
19342             if (value_dependent_expression_p (op))
19343               return true;
19344           }
19345         return false;
19346       }
19347
19348     case TEMPLATE_ID_EXPR:
19349       /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
19350          type-dependent.  */
19351       return type_dependent_expression_p (expression);
19352
19353     case CONSTRUCTOR:
19354       {
19355         unsigned ix;
19356         tree val;
19357         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
19358           if (value_dependent_expression_p (val))
19359             return true;
19360         return false;
19361       }
19362
19363     default:
19364       /* A constant expression is value-dependent if any subexpression is
19365          value-dependent.  */
19366       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
19367         {
19368         case tcc_reference:
19369         case tcc_unary:
19370         case tcc_comparison:
19371         case tcc_binary:
19372         case tcc_expression:
19373         case tcc_vl_exp:
19374           {
19375             int i, len = cp_tree_operand_length (expression);
19376
19377             for (i = 0; i < len; i++)
19378               {
19379                 tree t = TREE_OPERAND (expression, i);
19380
19381                 /* In some cases, some of the operands may be missing.l
19382                    (For example, in the case of PREDECREMENT_EXPR, the
19383                    amount to increment by may be missing.)  That doesn't
19384                    make the expression dependent.  */
19385                 if (t && value_dependent_expression_p (t))
19386                   return true;
19387               }
19388           }
19389           break;
19390         default:
19391           break;
19392         }
19393       break;
19394     }
19395
19396   /* The expression is not value-dependent.  */
19397   return false;
19398 }
19399
19400 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
19401    [temp.dep.expr].  Note that an expression with no type is
19402    considered dependent.  Other parts of the compiler arrange for an
19403    expression with type-dependent subexpressions to have no type, so
19404    this function doesn't have to be fully recursive.  */
19405
19406 bool
19407 type_dependent_expression_p (tree expression)
19408 {
19409   if (!processing_template_decl)
19410     return false;
19411
19412   if (expression == error_mark_node)
19413     return false;
19414
19415   /* An unresolved name is always dependent.  */
19416   if (TREE_CODE (expression) == IDENTIFIER_NODE
19417       || TREE_CODE (expression) == USING_DECL)
19418     return true;
19419
19420   /* Some expression forms are never type-dependent.  */
19421   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
19422       || TREE_CODE (expression) == SIZEOF_EXPR
19423       || TREE_CODE (expression) == ALIGNOF_EXPR
19424       || TREE_CODE (expression) == AT_ENCODE_EXPR
19425       || TREE_CODE (expression) == NOEXCEPT_EXPR
19426       || TREE_CODE (expression) == TRAIT_EXPR
19427       || TREE_CODE (expression) == TYPEID_EXPR
19428       || TREE_CODE (expression) == DELETE_EXPR
19429       || TREE_CODE (expression) == VEC_DELETE_EXPR
19430       || TREE_CODE (expression) == THROW_EXPR)
19431     return false;
19432
19433   /* The types of these expressions depends only on the type to which
19434      the cast occurs.  */
19435   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
19436       || TREE_CODE (expression) == STATIC_CAST_EXPR
19437       || TREE_CODE (expression) == CONST_CAST_EXPR
19438       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
19439       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
19440       || TREE_CODE (expression) == CAST_EXPR)
19441     return dependent_type_p (TREE_TYPE (expression));
19442
19443   /* The types of these expressions depends only on the type created
19444      by the expression.  */
19445   if (TREE_CODE (expression) == NEW_EXPR
19446       || TREE_CODE (expression) == VEC_NEW_EXPR)
19447     {
19448       /* For NEW_EXPR tree nodes created inside a template, either
19449          the object type itself or a TREE_LIST may appear as the
19450          operand 1.  */
19451       tree type = TREE_OPERAND (expression, 1);
19452       if (TREE_CODE (type) == TREE_LIST)
19453         /* This is an array type.  We need to check array dimensions
19454            as well.  */
19455         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
19456                || value_dependent_expression_p
19457                     (TREE_OPERAND (TREE_VALUE (type), 1));
19458       else
19459         return dependent_type_p (type);
19460     }
19461
19462   if (TREE_CODE (expression) == SCOPE_REF)
19463     {
19464       tree scope = TREE_OPERAND (expression, 0);
19465       tree name = TREE_OPERAND (expression, 1);
19466
19467       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
19468          contains an identifier associated by name lookup with one or more
19469          declarations declared with a dependent type, or...a
19470          nested-name-specifier or qualified-id that names a member of an
19471          unknown specialization.  */
19472       return (type_dependent_expression_p (name)
19473               || dependent_scope_p (scope));
19474     }
19475
19476   if (TREE_CODE (expression) == FUNCTION_DECL
19477       && DECL_LANG_SPECIFIC (expression)
19478       && DECL_TEMPLATE_INFO (expression)
19479       && (any_dependent_template_arguments_p
19480           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
19481     return true;
19482
19483   if (TREE_CODE (expression) == TEMPLATE_DECL
19484       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
19485     return false;
19486
19487   if (TREE_CODE (expression) == STMT_EXPR)
19488     expression = stmt_expr_value_expr (expression);
19489
19490   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
19491     {
19492       tree elt;
19493       unsigned i;
19494
19495       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
19496         {
19497           if (type_dependent_expression_p (elt))
19498             return true;
19499         }
19500       return false;
19501     }
19502
19503   /* A static data member of the current instantiation with incomplete
19504      array type is type-dependent, as the definition and specializations
19505      can have different bounds.  */
19506   if (TREE_CODE (expression) == VAR_DECL
19507       && DECL_CLASS_SCOPE_P (expression)
19508       && dependent_type_p (DECL_CONTEXT (expression))
19509       && VAR_HAD_UNKNOWN_BOUND (expression))
19510     return true;
19511
19512   if (TREE_TYPE (expression) == unknown_type_node)
19513     {
19514       if (TREE_CODE (expression) == ADDR_EXPR)
19515         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
19516       if (TREE_CODE (expression) == COMPONENT_REF
19517           || TREE_CODE (expression) == OFFSET_REF)
19518         {
19519           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
19520             return true;
19521           expression = TREE_OPERAND (expression, 1);
19522           if (TREE_CODE (expression) == IDENTIFIER_NODE)
19523             return false;
19524         }
19525       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
19526       if (TREE_CODE (expression) == SCOPE_REF)
19527         return false;
19528
19529       if (BASELINK_P (expression))
19530         expression = BASELINK_FUNCTIONS (expression);
19531
19532       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
19533         {
19534           if (any_dependent_template_arguments_p
19535               (TREE_OPERAND (expression, 1)))
19536             return true;
19537           expression = TREE_OPERAND (expression, 0);
19538         }
19539       gcc_assert (TREE_CODE (expression) == OVERLOAD
19540                   || TREE_CODE (expression) == FUNCTION_DECL);
19541
19542       while (expression)
19543         {
19544           if (type_dependent_expression_p (OVL_CURRENT (expression)))
19545             return true;
19546           expression = OVL_NEXT (expression);
19547         }
19548       return false;
19549     }
19550
19551   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
19552
19553   return (dependent_type_p (TREE_TYPE (expression)));
19554 }
19555
19556 /* Like type_dependent_expression_p, but it also works while not processing
19557    a template definition, i.e. during substitution or mangling.  */
19558
19559 bool
19560 type_dependent_expression_p_push (tree expr)
19561 {
19562   bool b;
19563   ++processing_template_decl;
19564   b = type_dependent_expression_p (expr);
19565   --processing_template_decl;
19566   return b;
19567 }
19568
19569 /* Returns TRUE if ARGS contains a type-dependent expression.  */
19570
19571 bool
19572 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
19573 {
19574   unsigned int i;
19575   tree arg;
19576
19577   FOR_EACH_VEC_ELT (tree, args, i, arg)
19578     {
19579       if (type_dependent_expression_p (arg))
19580         return true;
19581     }
19582   return false;
19583 }
19584
19585 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19586    expressions) contains any type-dependent expressions.  */
19587
19588 bool
19589 any_type_dependent_elements_p (const_tree list)
19590 {
19591   for (; list; list = TREE_CHAIN (list))
19592     if (value_dependent_expression_p (TREE_VALUE (list)))
19593       return true;
19594
19595   return false;
19596 }
19597
19598 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19599    expressions) contains any value-dependent expressions.  */
19600
19601 bool
19602 any_value_dependent_elements_p (const_tree list)
19603 {
19604   for (; list; list = TREE_CHAIN (list))
19605     if (value_dependent_expression_p (TREE_VALUE (list)))
19606       return true;
19607
19608   return false;
19609 }
19610
19611 /* Returns TRUE if the ARG (a template argument) is dependent.  */
19612
19613 bool
19614 dependent_template_arg_p (tree arg)
19615 {
19616   if (!processing_template_decl)
19617     return false;
19618
19619   /* Assume a template argument that was wrongly written by the user
19620      is dependent. This is consistent with what
19621      any_dependent_template_arguments_p [that calls this function]
19622      does.  */
19623   if (!arg || arg == error_mark_node)
19624     return true;
19625
19626   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
19627     arg = ARGUMENT_PACK_SELECT_ARG (arg);
19628
19629   if (TREE_CODE (arg) == TEMPLATE_DECL
19630       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19631     return dependent_template_p (arg);
19632   else if (ARGUMENT_PACK_P (arg))
19633     {
19634       tree args = ARGUMENT_PACK_ARGS (arg);
19635       int i, len = TREE_VEC_LENGTH (args);
19636       for (i = 0; i < len; ++i)
19637         {
19638           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
19639             return true;
19640         }
19641
19642       return false;
19643     }
19644   else if (TYPE_P (arg))
19645     return dependent_type_p (arg);
19646   else
19647     return (type_dependent_expression_p (arg)
19648             || value_dependent_expression_p (arg));
19649 }
19650
19651 /* Returns true if ARGS (a collection of template arguments) contains
19652    any types that require structural equality testing.  */
19653
19654 bool
19655 any_template_arguments_need_structural_equality_p (tree args)
19656 {
19657   int i;
19658   int j;
19659
19660   if (!args)
19661     return false;
19662   if (args == error_mark_node)
19663     return true;
19664
19665   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19666     {
19667       tree level = TMPL_ARGS_LEVEL (args, i + 1);
19668       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19669         {
19670           tree arg = TREE_VEC_ELT (level, j);
19671           tree packed_args = NULL_TREE;
19672           int k, len = 1;
19673
19674           if (ARGUMENT_PACK_P (arg))
19675             {
19676               /* Look inside the argument pack.  */
19677               packed_args = ARGUMENT_PACK_ARGS (arg);
19678               len = TREE_VEC_LENGTH (packed_args);
19679             }
19680
19681           for (k = 0; k < len; ++k)
19682             {
19683               if (packed_args)
19684                 arg = TREE_VEC_ELT (packed_args, k);
19685
19686               if (error_operand_p (arg))
19687                 return true;
19688               else if (TREE_CODE (arg) == TEMPLATE_DECL
19689                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19690                 continue;
19691               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
19692                 return true;
19693               else if (!TYPE_P (arg) && TREE_TYPE (arg)
19694                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
19695                 return true;
19696             }
19697         }
19698     }
19699
19700   return false;
19701 }
19702
19703 /* Returns true if ARGS (a collection of template arguments) contains
19704    any dependent arguments.  */
19705
19706 bool
19707 any_dependent_template_arguments_p (const_tree args)
19708 {
19709   int i;
19710   int j;
19711
19712   if (!args)
19713     return false;
19714   if (args == error_mark_node)
19715     return true;
19716
19717   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19718     {
19719       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
19720       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19721         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
19722           return true;
19723     }
19724
19725   return false;
19726 }
19727
19728 /* Returns TRUE if the template TMPL is dependent.  */
19729
19730 bool
19731 dependent_template_p (tree tmpl)
19732 {
19733   if (TREE_CODE (tmpl) == OVERLOAD)
19734     {
19735       while (tmpl)
19736         {
19737           if (dependent_template_p (OVL_CURRENT (tmpl)))
19738             return true;
19739           tmpl = OVL_NEXT (tmpl);
19740         }
19741       return false;
19742     }
19743
19744   /* Template template parameters are dependent.  */
19745   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
19746       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
19747     return true;
19748   /* So are names that have not been looked up.  */
19749   if (TREE_CODE (tmpl) == SCOPE_REF
19750       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
19751     return true;
19752   /* So are member templates of dependent classes.  */
19753   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
19754     return dependent_type_p (DECL_CONTEXT (tmpl));
19755   return false;
19756 }
19757
19758 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
19759
19760 bool
19761 dependent_template_id_p (tree tmpl, tree args)
19762 {
19763   return (dependent_template_p (tmpl)
19764           || any_dependent_template_arguments_p (args));
19765 }
19766
19767 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
19768    is dependent.  */
19769
19770 bool
19771 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
19772 {
19773   int i;
19774
19775   if (!processing_template_decl)
19776     return false;
19777
19778   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
19779     {
19780       tree decl = TREE_VEC_ELT (declv, i);
19781       tree init = TREE_VEC_ELT (initv, i);
19782       tree cond = TREE_VEC_ELT (condv, i);
19783       tree incr = TREE_VEC_ELT (incrv, i);
19784
19785       if (type_dependent_expression_p (decl))
19786         return true;
19787
19788       if (init && type_dependent_expression_p (init))
19789         return true;
19790
19791       if (type_dependent_expression_p (cond))
19792         return true;
19793
19794       if (COMPARISON_CLASS_P (cond)
19795           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
19796               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
19797         return true;
19798
19799       if (TREE_CODE (incr) == MODOP_EXPR)
19800         {
19801           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
19802               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
19803             return true;
19804         }
19805       else if (type_dependent_expression_p (incr))
19806         return true;
19807       else if (TREE_CODE (incr) == MODIFY_EXPR)
19808         {
19809           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
19810             return true;
19811           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
19812             {
19813               tree t = TREE_OPERAND (incr, 1);
19814               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
19815                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
19816                 return true;
19817             }
19818         }
19819     }
19820
19821   return false;
19822 }
19823
19824 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
19825    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
19826    no such TYPE can be found.  Note that this function peers inside
19827    uninstantiated templates and therefore should be used only in
19828    extremely limited situations.  ONLY_CURRENT_P restricts this
19829    peering to the currently open classes hierarchy (which is required
19830    when comparing types).  */
19831
19832 tree
19833 resolve_typename_type (tree type, bool only_current_p)
19834 {
19835   tree scope;
19836   tree name;
19837   tree decl;
19838   int quals;
19839   tree pushed_scope;
19840   tree result;
19841
19842   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
19843
19844   scope = TYPE_CONTEXT (type);
19845   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
19846      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
19847      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
19848      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
19849      identifier  of the TYPENAME_TYPE anymore.
19850      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
19851      TYPENAME_TYPE instead, we avoid messing up with a possible
19852      typedef variant case.  */
19853   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
19854
19855   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
19856      it first before we can figure out what NAME refers to.  */
19857   if (TREE_CODE (scope) == TYPENAME_TYPE)
19858     scope = resolve_typename_type (scope, only_current_p);
19859   /* If we don't know what SCOPE refers to, then we cannot resolve the
19860      TYPENAME_TYPE.  */
19861   if (TREE_CODE (scope) == TYPENAME_TYPE)
19862     return type;
19863   /* If the SCOPE is a template type parameter, we have no way of
19864      resolving the name.  */
19865   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
19866     return type;
19867   /* If the SCOPE is not the current instantiation, there's no reason
19868      to look inside it.  */
19869   if (only_current_p && !currently_open_class (scope))
19870     return type;
19871   /* If this is a typedef, we don't want to look inside (c++/11987).  */
19872   if (typedef_variant_p (type))
19873     return type;
19874   /* If SCOPE isn't the template itself, it will not have a valid
19875      TYPE_FIELDS list.  */
19876   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
19877     /* scope is either the template itself or a compatible instantiation
19878        like X<T>, so look up the name in the original template.  */
19879     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
19880   else
19881     /* scope is a partial instantiation, so we can't do the lookup or we
19882        will lose the template arguments.  */
19883     return type;
19884   /* Enter the SCOPE so that name lookup will be resolved as if we
19885      were in the class definition.  In particular, SCOPE will no
19886      longer be considered a dependent type.  */
19887   pushed_scope = push_scope (scope);
19888   /* Look up the declaration.  */
19889   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
19890                         tf_warning_or_error);
19891
19892   result = NULL_TREE;
19893   
19894   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
19895      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
19896   if (!decl)
19897     /*nop*/;
19898   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
19899            && TREE_CODE (decl) == TYPE_DECL)
19900     {
19901       result = TREE_TYPE (decl);
19902       if (result == error_mark_node)
19903         result = NULL_TREE;
19904     }
19905   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
19906            && DECL_CLASS_TEMPLATE_P (decl))
19907     {
19908       tree tmpl;
19909       tree args;
19910       /* Obtain the template and the arguments.  */
19911       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
19912       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
19913       /* Instantiate the template.  */
19914       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
19915                                       /*entering_scope=*/0,
19916                                       tf_error | tf_user);
19917       if (result == error_mark_node)
19918         result = NULL_TREE;
19919     }
19920   
19921   /* Leave the SCOPE.  */
19922   if (pushed_scope)
19923     pop_scope (pushed_scope);
19924
19925   /* If we failed to resolve it, return the original typename.  */
19926   if (!result)
19927     return type;
19928   
19929   /* If lookup found a typename type, resolve that too.  */
19930   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
19931     {
19932       /* Ill-formed programs can cause infinite recursion here, so we
19933          must catch that.  */
19934       TYPENAME_IS_RESOLVING_P (type) = 1;
19935       result = resolve_typename_type (result, only_current_p);
19936       TYPENAME_IS_RESOLVING_P (type) = 0;
19937     }
19938   
19939   /* Qualify the resulting type.  */
19940   quals = cp_type_quals (type);
19941   if (quals)
19942     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
19943
19944   return result;
19945 }
19946
19947 /* EXPR is an expression which is not type-dependent.  Return a proxy
19948    for EXPR that can be used to compute the types of larger
19949    expressions containing EXPR.  */
19950
19951 tree
19952 build_non_dependent_expr (tree expr)
19953 {
19954   tree inner_expr;
19955
19956 #ifdef ENABLE_CHECKING
19957   /* Try to get a constant value for all non-type-dependent expressions in
19958       order to expose bugs in *_dependent_expression_p and constexpr.  */
19959   if (cxx_dialect >= cxx0x)
19960     maybe_constant_value (fold_non_dependent_expr_sfinae (expr, tf_none));
19961 #endif
19962
19963   /* Preserve OVERLOADs; the functions must be available to resolve
19964      types.  */
19965   inner_expr = expr;
19966   if (TREE_CODE (inner_expr) == STMT_EXPR)
19967     inner_expr = stmt_expr_value_expr (inner_expr);
19968   if (TREE_CODE (inner_expr) == ADDR_EXPR)
19969     inner_expr = TREE_OPERAND (inner_expr, 0);
19970   if (TREE_CODE (inner_expr) == COMPONENT_REF)
19971     inner_expr = TREE_OPERAND (inner_expr, 1);
19972   if (is_overloaded_fn (inner_expr)
19973       || TREE_CODE (inner_expr) == OFFSET_REF)
19974     return expr;
19975   /* There is no need to return a proxy for a variable.  */
19976   if (TREE_CODE (expr) == VAR_DECL)
19977     return expr;
19978   /* Preserve string constants; conversions from string constants to
19979      "char *" are allowed, even though normally a "const char *"
19980      cannot be used to initialize a "char *".  */
19981   if (TREE_CODE (expr) == STRING_CST)
19982     return expr;
19983   /* Preserve arithmetic constants, as an optimization -- there is no
19984      reason to create a new node.  */
19985   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
19986     return expr;
19987   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
19988      There is at least one place where we want to know that a
19989      particular expression is a throw-expression: when checking a ?:
19990      expression, there are special rules if the second or third
19991      argument is a throw-expression.  */
19992   if (TREE_CODE (expr) == THROW_EXPR)
19993     return expr;
19994
19995   /* Don't wrap an initializer list, we need to be able to look inside.  */
19996   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
19997     return expr;
19998
19999   if (TREE_CODE (expr) == COND_EXPR)
20000     return build3 (COND_EXPR,
20001                    TREE_TYPE (expr),
20002                    TREE_OPERAND (expr, 0),
20003                    (TREE_OPERAND (expr, 1)
20004                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
20005                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
20006                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
20007   if (TREE_CODE (expr) == COMPOUND_EXPR
20008       && !COMPOUND_EXPR_OVERLOADED (expr))
20009     return build2 (COMPOUND_EXPR,
20010                    TREE_TYPE (expr),
20011                    TREE_OPERAND (expr, 0),
20012                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
20013
20014   /* If the type is unknown, it can't really be non-dependent */
20015   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
20016
20017   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
20018   return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
20019 }
20020
20021 /* ARGS is a vector of expressions as arguments to a function call.
20022    Replace the arguments with equivalent non-dependent expressions.
20023    This modifies ARGS in place.  */
20024
20025 void
20026 make_args_non_dependent (VEC(tree,gc) *args)
20027 {
20028   unsigned int ix;
20029   tree arg;
20030
20031   FOR_EACH_VEC_ELT (tree, args, ix, arg)
20032     {
20033       tree newarg = build_non_dependent_expr (arg);
20034       if (newarg != arg)
20035         VEC_replace (tree, args, ix, newarg);
20036     }
20037 }
20038
20039 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
20040    with a level one deeper than the actual template parms.  */
20041
20042 tree
20043 make_auto (void)
20044 {
20045   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
20046   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
20047                                TYPE_DECL, get_identifier ("auto"), au);
20048   TYPE_STUB_DECL (au) = TYPE_NAME (au);
20049   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
20050     (0, processing_template_decl + 1, processing_template_decl + 1,
20051      0, TYPE_NAME (au), NULL_TREE);
20052   TYPE_CANONICAL (au) = canonical_type_parameter (au);
20053   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
20054   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
20055
20056   return au;
20057 }
20058
20059 /* Given type ARG, return std::initializer_list<ARG>.  */
20060
20061 static tree
20062 listify (tree arg)
20063 {
20064   tree std_init_list = namespace_binding
20065     (get_identifier ("initializer_list"), std_node);
20066   tree argvec;
20067   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
20068     {    
20069       error ("deducing from brace-enclosed initializer list requires "
20070              "#include <initializer_list>");
20071       return error_mark_node;
20072     }
20073   argvec = make_tree_vec (1);
20074   TREE_VEC_ELT (argvec, 0) = arg;
20075   return lookup_template_class (std_init_list, argvec, NULL_TREE,
20076                                 NULL_TREE, 0, tf_warning_or_error);
20077 }
20078
20079 /* Replace auto in TYPE with std::initializer_list<auto>.  */
20080
20081 static tree
20082 listify_autos (tree type, tree auto_node)
20083 {
20084   tree init_auto = listify (auto_node);
20085   tree argvec = make_tree_vec (1);
20086   TREE_VEC_ELT (argvec, 0) = init_auto;
20087   if (processing_template_decl)
20088     argvec = add_to_template_args (current_template_args (), argvec);
20089   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
20090 }
20091
20092 /* walk_tree helper for do_auto_deduction.  */
20093
20094 static tree
20095 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
20096                  void *type)
20097 {
20098   /* Is this a variable with the type we're looking for?  */
20099   if (DECL_P (*tp)
20100       && TREE_TYPE (*tp) == type)
20101     return *tp;
20102   else
20103     return NULL_TREE;
20104 }
20105
20106 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
20107    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
20108
20109 tree
20110 do_auto_deduction (tree type, tree init, tree auto_node)
20111 {
20112   tree parms, tparms, targs;
20113   tree args[1];
20114   tree decl;
20115   int val;
20116
20117   if (processing_template_decl
20118       && (TREE_TYPE (init) == NULL_TREE
20119           || BRACE_ENCLOSED_INITIALIZER_P (init)))
20120     /* Not enough information to try this yet.  */
20121     return type;
20122
20123   /* The name of the object being declared shall not appear in the
20124      initializer expression.  */
20125   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
20126   if (decl)
20127     {
20128       error ("variable %q#D with %<auto%> type used in its own "
20129              "initializer", decl);
20130       return error_mark_node;
20131     }
20132
20133   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
20134      with either a new invented type template parameter U or, if the
20135      initializer is a braced-init-list (8.5.4), with
20136      std::initializer_list<U>.  */
20137   if (BRACE_ENCLOSED_INITIALIZER_P (init))
20138     type = listify_autos (type, auto_node);
20139
20140   init = resolve_nondeduced_context (init);
20141
20142   parms = build_tree_list (NULL_TREE, type);
20143   args[0] = init;
20144   tparms = make_tree_vec (1);
20145   targs = make_tree_vec (1);
20146   TREE_VEC_ELT (tparms, 0)
20147     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
20148   val = type_unification_real (tparms, targs, parms, args, 1, 0,
20149                                DEDUCE_CALL, LOOKUP_NORMAL,
20150                                /*explain_p=*/false);
20151   if (val > 0)
20152     {
20153       if (processing_template_decl)
20154         /* Try again at instantiation time.  */
20155         return type;
20156       if (type && type != error_mark_node)
20157         /* If type is error_mark_node a diagnostic must have been
20158            emitted by now.  Also, having a mention to '<type error>'
20159            in the diagnostic is not really useful to the user.  */
20160         error ("unable to deduce %qT from %qE", type, init);
20161       return error_mark_node;
20162     }
20163
20164   /* If the list of declarators contains more than one declarator, the type
20165      of each declared variable is determined as described above. If the
20166      type deduced for the template parameter U is not the same in each
20167      deduction, the program is ill-formed.  */
20168   if (TREE_TYPE (auto_node)
20169       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
20170     {
20171       error ("inconsistent deduction for %qT: %qT and then %qT",
20172              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
20173       return error_mark_node;
20174     }
20175   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
20176
20177   if (processing_template_decl)
20178     targs = add_to_template_args (current_template_args (), targs);
20179   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
20180 }
20181
20182 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
20183    result.  */
20184
20185 tree
20186 splice_late_return_type (tree type, tree late_return_type)
20187 {
20188   tree argvec;
20189
20190   if (late_return_type == NULL_TREE)
20191     return type;
20192   argvec = make_tree_vec (1);
20193   TREE_VEC_ELT (argvec, 0) = late_return_type;
20194   if (processing_template_parmlist)
20195     /* For a late-specified return type in a template type-parameter, we
20196        need to add a dummy argument level for its parmlist.  */
20197     argvec = add_to_template_args
20198       (make_tree_vec (processing_template_parmlist), argvec);
20199   if (current_template_parms)
20200     argvec = add_to_template_args (current_template_args (), argvec);
20201   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
20202 }
20203
20204 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
20205
20206 bool
20207 is_auto (const_tree type)
20208 {
20209   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
20210       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
20211     return true;
20212   else
20213     return false;
20214 }
20215
20216 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
20217    appear as a type-specifier for the declaration in question, we don't
20218    have to look through the whole type.  */
20219
20220 tree
20221 type_uses_auto (tree type)
20222 {
20223   enum tree_code code;
20224   if (is_auto (type))
20225     return type;
20226
20227   code = TREE_CODE (type);
20228
20229   if (code == POINTER_TYPE || code == REFERENCE_TYPE
20230       || code == OFFSET_TYPE || code == FUNCTION_TYPE
20231       || code == METHOD_TYPE || code == ARRAY_TYPE)
20232     return type_uses_auto (TREE_TYPE (type));
20233
20234   if (TYPE_PTRMEMFUNC_P (type))
20235     return type_uses_auto (TREE_TYPE (TREE_TYPE
20236                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
20237
20238   return NULL_TREE;
20239 }
20240
20241 /* For a given template T, return the vector of typedefs referenced
20242    in T for which access check is needed at T instantiation time.
20243    T is either  a FUNCTION_DECL or a RECORD_TYPE.
20244    Those typedefs were added to T by the function
20245    append_type_to_template_for_access_check.  */
20246
20247 VEC(qualified_typedef_usage_t,gc)*
20248 get_types_needing_access_check (tree t)
20249 {
20250   tree ti;
20251   VEC(qualified_typedef_usage_t,gc) *result = NULL;
20252
20253   if (!t || t == error_mark_node)
20254     return NULL;
20255
20256   if (!(ti = get_template_info (t)))
20257     return NULL;
20258
20259   if (CLASS_TYPE_P (t)
20260       || TREE_CODE (t) == FUNCTION_DECL)
20261     {
20262       if (!TI_TEMPLATE (ti))
20263         return NULL;
20264
20265       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
20266     }
20267
20268   return result;
20269 }
20270
20271 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
20272    tied to T. That list of typedefs will be access checked at
20273    T instantiation time.
20274    T is either a FUNCTION_DECL or a RECORD_TYPE.
20275    TYPE_DECL is a TYPE_DECL node representing a typedef.
20276    SCOPE is the scope through which TYPE_DECL is accessed.
20277    LOCATION is the location of the usage point of TYPE_DECL.
20278
20279    This function is a subroutine of
20280    append_type_to_template_for_access_check.  */
20281
20282 static void
20283 append_type_to_template_for_access_check_1 (tree t,
20284                                             tree type_decl,
20285                                             tree scope,
20286                                             location_t location)
20287 {
20288   qualified_typedef_usage_t typedef_usage;
20289   tree ti;
20290
20291   if (!t || t == error_mark_node)
20292     return;
20293
20294   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
20295                || CLASS_TYPE_P (t))
20296               && type_decl
20297               && TREE_CODE (type_decl) == TYPE_DECL
20298               && scope);
20299
20300   if (!(ti = get_template_info (t)))
20301     return;
20302
20303   gcc_assert (TI_TEMPLATE (ti));
20304
20305   typedef_usage.typedef_decl = type_decl;
20306   typedef_usage.context = scope;
20307   typedef_usage.locus = location;
20308
20309   VEC_safe_push (qualified_typedef_usage_t, gc,
20310                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
20311                  &typedef_usage);
20312 }
20313
20314 /* Append TYPE_DECL to the template TEMPL.
20315    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
20316    At TEMPL instanciation time, TYPE_DECL will be checked to see
20317    if it can be accessed through SCOPE.
20318    LOCATION is the location of the usage point of TYPE_DECL.
20319
20320    e.g. consider the following code snippet:
20321
20322      class C
20323      {
20324        typedef int myint;
20325      };
20326
20327      template<class U> struct S
20328      {
20329        C::myint mi; // <-- usage point of the typedef C::myint
20330      };
20331
20332      S<char> s;
20333
20334    At S<char> instantiation time, we need to check the access of C::myint
20335    In other words, we need to check the access of the myint typedef through
20336    the C scope. For that purpose, this function will add the myint typedef
20337    and the scope C through which its being accessed to a list of typedefs
20338    tied to the template S. That list will be walked at template instantiation
20339    time and access check performed on each typedefs it contains.
20340    Note that this particular code snippet should yield an error because
20341    myint is private to C.  */
20342
20343 void
20344 append_type_to_template_for_access_check (tree templ,
20345                                           tree type_decl,
20346                                           tree scope,
20347                                           location_t location)
20348 {
20349   qualified_typedef_usage_t *iter;
20350   int i;
20351
20352   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
20353
20354   /* Make sure we don't append the type to the template twice.  */
20355   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
20356                     get_types_needing_access_check (templ),
20357                     i, iter)
20358     if (iter->typedef_decl == type_decl && scope == iter->context)
20359       return;
20360
20361   append_type_to_template_for_access_check_1 (templ, type_decl,
20362                                               scope, location);
20363 }
20364
20365 /* Set up the hash tables for template instantiations.  */
20366
20367 void
20368 init_template_processing (void)
20369 {
20370   decl_specializations = htab_create_ggc (37,
20371                                           hash_specialization,
20372                                           eq_specializations,
20373                                           ggc_free);
20374   type_specializations = htab_create_ggc (37,
20375                                           hash_specialization,
20376                                           eq_specializations,
20377                                           ggc_free);
20378 }
20379
20380 /* Print stats about the template hash tables for -fstats.  */
20381
20382 void
20383 print_template_statistics (void)
20384 {
20385   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
20386            "%f collisions\n", (long) htab_size (decl_specializations),
20387            (long) htab_elements (decl_specializations),
20388            htab_collisions (decl_specializations));
20389   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
20390            "%f collisions\n", (long) htab_size (type_specializations),
20391            (long) htab_elements (type_specializations),
20392            htab_collisions (type_specializations));
20393 }
20394
20395 #include "gt-cp-pt.h"