OSDN Git Service

f150d8f61308f303651b64734dbb9cd26e0ab9de
[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
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 "cp-objcp-common.h"
40 #include "tree-inline.h"
41 #include "decl.h"
42 #include "output.h"
43 #include "toplev.h"
44 #include "timevar.h"
45 #include "tree-iterator.h"
46 #include "vecprim.h"
47
48 /* The type of functions taking a tree, and some additional data, and
49    returning an int.  */
50 typedef int (*tree_fn_t) (tree, void*);
51
52 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
53    instantiations have been deferred, either because their definitions
54    were not yet available, or because we were putting off doing the work.  */
55 struct GTY (()) pending_template {
56   struct pending_template *next;
57   struct tinst_level *tinst;
58 };
59
60 static GTY(()) struct pending_template *pending_templates;
61 static GTY(()) struct pending_template *last_pending_template;
62
63 int processing_template_parmlist;
64 static int template_header_count;
65
66 static GTY(()) tree saved_trees;
67 static VEC(int,heap) *inline_parm_levels;
68
69 static GTY(()) struct tinst_level *current_tinst_level;
70
71 static GTY(()) tree saved_access_scope;
72
73 /* Live only within one (recursive) call to tsubst_expr.  We use
74    this to pass the statement expression node from the STMT_EXPR
75    to the EXPR_STMT that is its result.  */
76 static tree cur_stmt_expr;
77
78 /* A map from local variable declarations in the body of the template
79    presently being instantiated to the corresponding instantiated
80    local variables.  */
81 static htab_t local_specializations;
82
83 typedef struct GTY(()) spec_entry
84 {
85   tree tmpl;
86   tree args;
87   tree spec;
88 } spec_entry;
89
90 static GTY ((param_is (spec_entry)))
91   htab_t decl_specializations;
92
93 static GTY ((param_is (spec_entry)))
94   htab_t type_specializations;
95
96 /* Contains canonical template parameter types. The vector is indexed by
97    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
98    TREE_LIST, whose TREE_VALUEs contain the canonical template
99    parameters of various types and levels.  */
100 static GTY(()) VEC(tree,gc) *canonical_template_parms;
101
102 #define UNIFY_ALLOW_NONE 0
103 #define UNIFY_ALLOW_MORE_CV_QUAL 1
104 #define UNIFY_ALLOW_LESS_CV_QUAL 2
105 #define UNIFY_ALLOW_DERIVED 4
106 #define UNIFY_ALLOW_INTEGER 8
107 #define UNIFY_ALLOW_OUTER_LEVEL 16
108 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
109 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
110
111 static void push_access_scope (tree);
112 static void pop_access_scope (tree);
113 static bool resolve_overloaded_unification (tree, tree, tree, tree,
114                                             unification_kind_t, int);
115 static int try_one_overload (tree, tree, tree, tree, tree,
116                              unification_kind_t, int, bool);
117 static int unify (tree, tree, tree, tree, int);
118 static void add_pending_template (tree);
119 static tree reopen_tinst_level (struct tinst_level *);
120 static tree tsubst_initializer_list (tree, tree);
121 static tree get_class_bindings (tree, tree, tree);
122 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
123                                    bool, bool);
124 static void tsubst_enum (tree, tree, tree);
125 static tree add_to_template_args (tree, tree);
126 static tree add_outermost_template_args (tree, tree);
127 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
128 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
129                                              tree);
130 static int type_unification_real (tree, tree, tree, const tree *,
131                                   unsigned int, int, unification_kind_t, int);
132 static void note_template_header (int);
133 static tree convert_nontype_argument_function (tree, tree);
134 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
135 static tree convert_template_argument (tree, tree, tree,
136                                        tsubst_flags_t, int, tree);
137 static int for_each_template_parm (tree, tree_fn_t, void*,
138                                    struct pointer_set_t*, bool);
139 static tree expand_template_argument_pack (tree);
140 static tree build_template_parm_index (int, int, int, tree, tree);
141 static bool inline_needs_template_parms (tree);
142 static void push_inline_template_parms_recursive (tree, int);
143 static tree retrieve_local_specialization (tree);
144 static void register_local_specialization (tree, tree);
145 static hashval_t hash_specialization (const void *p);
146 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
147 static int mark_template_parm (tree, void *);
148 static int template_parm_this_level_p (tree, void *);
149 static tree tsubst_friend_function (tree, tree);
150 static tree tsubst_friend_class (tree, tree);
151 static int can_complete_type_without_circularity (tree);
152 static tree get_bindings (tree, tree, tree, bool);
153 static int template_decl_level (tree);
154 static int check_cv_quals_for_unify (int, tree, tree);
155 static void template_parm_level_and_index (tree, int*, int*);
156 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
157 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
158 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
159 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
160 static void regenerate_decl_from_template (tree, tree);
161 static tree most_specialized_class (tree, tree, tsubst_flags_t);
162 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
163 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
164 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
165 static bool check_specialization_scope (void);
166 static tree process_partial_specialization (tree);
167 static void set_current_access_from_decl (tree);
168 static tree get_template_base (tree, tree, tree, tree);
169 static tree try_class_unification (tree, tree, tree, tree);
170 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
171                                            tree, tree);
172 static bool template_template_parm_bindings_ok_p (tree, tree);
173 static int template_args_equal (tree, tree);
174 static void tsubst_default_arguments (tree);
175 static tree for_each_template_parm_r (tree *, int *, void *);
176 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
177 static void copy_default_args_to_explicit_spec (tree);
178 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
179 static int eq_local_specializations (const void *, const void *);
180 static bool dependent_template_arg_p (tree);
181 static bool any_template_arguments_need_structural_equality_p (tree);
182 static bool dependent_type_p_r (tree);
183 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
184 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
185 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
186 static tree tsubst_decl (tree, tree, tsubst_flags_t);
187 static void perform_typedefs_access_check (tree tmpl, tree targs);
188 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
189                                                         location_t);
190 static hashval_t iterative_hash_template_arg (tree arg, hashval_t val);
191 static tree listify (tree);
192 static tree listify_autos (tree, tree);
193
194 /* Make the current scope suitable for access checking when we are
195    processing T.  T can be FUNCTION_DECL for instantiated function
196    template, or VAR_DECL for static member variable (need by
197    instantiate_decl).  */
198
199 static void
200 push_access_scope (tree t)
201 {
202   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
203               || TREE_CODE (t) == VAR_DECL);
204
205   if (DECL_FRIEND_CONTEXT (t))
206     push_nested_class (DECL_FRIEND_CONTEXT (t));
207   else if (DECL_CLASS_SCOPE_P (t))
208     push_nested_class (DECL_CONTEXT (t));
209   else
210     push_to_top_level ();
211
212   if (TREE_CODE (t) == FUNCTION_DECL)
213     {
214       saved_access_scope = tree_cons
215         (NULL_TREE, current_function_decl, saved_access_scope);
216       current_function_decl = t;
217     }
218 }
219
220 /* Restore the scope set up by push_access_scope.  T is the node we
221    are processing.  */
222
223 static void
224 pop_access_scope (tree t)
225 {
226   if (TREE_CODE (t) == FUNCTION_DECL)
227     {
228       current_function_decl = TREE_VALUE (saved_access_scope);
229       saved_access_scope = TREE_CHAIN (saved_access_scope);
230     }
231
232   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
233     pop_nested_class ();
234   else
235     pop_from_top_level ();
236 }
237
238 /* Do any processing required when DECL (a member template
239    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
240    to DECL, unless it is a specialization, in which case the DECL
241    itself is returned.  */
242
243 tree
244 finish_member_template_decl (tree decl)
245 {
246   if (decl == error_mark_node)
247     return error_mark_node;
248
249   gcc_assert (DECL_P (decl));
250
251   if (TREE_CODE (decl) == TYPE_DECL)
252     {
253       tree type;
254
255       type = TREE_TYPE (decl);
256       if (type == error_mark_node)
257         return error_mark_node;
258       if (MAYBE_CLASS_TYPE_P (type)
259           && CLASSTYPE_TEMPLATE_INFO (type)
260           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
261         {
262           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
263           check_member_template (tmpl);
264           return tmpl;
265         }
266       return NULL_TREE;
267     }
268   else if (TREE_CODE (decl) == FIELD_DECL)
269     error ("data member %qD cannot be a member template", decl);
270   else if (DECL_TEMPLATE_INFO (decl))
271     {
272       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
273         {
274           check_member_template (DECL_TI_TEMPLATE (decl));
275           return DECL_TI_TEMPLATE (decl);
276         }
277       else
278         return decl;
279     }
280   else
281     error ("invalid member template declaration %qD", decl);
282
283   return error_mark_node;
284 }
285
286 /* Create a template info node.  */
287
288 tree
289 build_template_info (tree template_decl, tree template_args)
290 {
291   tree result = make_node (TEMPLATE_INFO);
292   TI_TEMPLATE (result) = template_decl;
293   TI_ARGS (result) = template_args;
294   return result;
295 }
296
297 /* Return the template info node corresponding to T, whatever T is.  */
298
299 tree
300 get_template_info (const_tree t)
301 {
302   tree tinfo = NULL_TREE;
303
304   if (!t || t == error_mark_node)
305     return NULL;
306
307   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
308     tinfo = DECL_TEMPLATE_INFO (t);
309
310   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
311     t = TREE_TYPE (t);
312
313   if (TAGGED_TYPE_P (t))
314     tinfo = TYPE_TEMPLATE_INFO (t);
315   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
316     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
317
318   return tinfo;
319 }
320
321 /* Returns the template nesting level of the indicated class TYPE.
322
323    For example, in:
324      template <class T>
325      struct A
326      {
327        template <class U>
328        struct B {};
329      };
330
331    A<T>::B<U> has depth two, while A<T> has depth one.
332    Both A<T>::B<int> and A<int>::B<U> have depth one, if
333    they are instantiations, not specializations.
334
335    This function is guaranteed to return 0 if passed NULL_TREE so
336    that, for example, `template_class_depth (current_class_type)' is
337    always safe.  */
338
339 int
340 template_class_depth (tree type)
341 {
342   int depth;
343
344   for (depth = 0;
345        type && TREE_CODE (type) != NAMESPACE_DECL;
346        type = (TREE_CODE (type) == FUNCTION_DECL)
347          ? CP_DECL_CONTEXT (type) : CP_TYPE_CONTEXT (type))
348     {
349       tree tinfo = get_template_info (type);
350
351       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
352           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
353         ++depth;
354     }
355
356   return depth;
357 }
358
359 /* Subroutine of maybe_begin_member_template_processing.
360    Returns true if processing DECL needs us to push template parms.  */
361
362 static bool
363 inline_needs_template_parms (tree decl)
364 {
365   if (! DECL_TEMPLATE_INFO (decl))
366     return false;
367
368   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
369           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
370 }
371
372 /* Subroutine of maybe_begin_member_template_processing.
373    Push the template parms in PARMS, starting from LEVELS steps into the
374    chain, and ending at the beginning, since template parms are listed
375    innermost first.  */
376
377 static void
378 push_inline_template_parms_recursive (tree parmlist, int levels)
379 {
380   tree parms = TREE_VALUE (parmlist);
381   int i;
382
383   if (levels > 1)
384     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
385
386   ++processing_template_decl;
387   current_template_parms
388     = tree_cons (size_int (processing_template_decl),
389                  parms, current_template_parms);
390   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
391
392   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
393                NULL);
394   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
395     {
396       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
397
398       if (parm == error_mark_node)
399         continue;
400
401       gcc_assert (DECL_P (parm));
402
403       switch (TREE_CODE (parm))
404         {
405         case TYPE_DECL:
406         case TEMPLATE_DECL:
407           pushdecl (parm);
408           break;
409
410         case PARM_DECL:
411           {
412             /* Make a CONST_DECL as is done in process_template_parm.
413                It is ugly that we recreate this here; the original
414                version built in process_template_parm is no longer
415                available.  */
416             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
417                                     CONST_DECL, DECL_NAME (parm),
418                                     TREE_TYPE (parm));
419             DECL_ARTIFICIAL (decl) = 1;
420             TREE_CONSTANT (decl) = 1;
421             TREE_READONLY (decl) = 1;
422             DECL_INITIAL (decl) = DECL_INITIAL (parm);
423             SET_DECL_TEMPLATE_PARM_P (decl);
424             pushdecl (decl);
425           }
426           break;
427
428         default:
429           gcc_unreachable ();
430         }
431     }
432 }
433
434 /* Restore the template parameter context for a member template or
435    a friend template defined in a class definition.  */
436
437 void
438 maybe_begin_member_template_processing (tree decl)
439 {
440   tree parms;
441   int levels = 0;
442
443   if (inline_needs_template_parms (decl))
444     {
445       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
446       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
447
448       if (DECL_TEMPLATE_SPECIALIZATION (decl))
449         {
450           --levels;
451           parms = TREE_CHAIN (parms);
452         }
453
454       push_inline_template_parms_recursive (parms, levels);
455     }
456
457   /* Remember how many levels of template parameters we pushed so that
458      we can pop them later.  */
459   VEC_safe_push (int, heap, inline_parm_levels, levels);
460 }
461
462 /* Undo the effects of maybe_begin_member_template_processing.  */
463
464 void
465 maybe_end_member_template_processing (void)
466 {
467   int i;
468   int last;
469
470   if (VEC_length (int, inline_parm_levels) == 0)
471     return;
472
473   last = VEC_pop (int, inline_parm_levels);
474   for (i = 0; i < last; ++i)
475     {
476       --processing_template_decl;
477       current_template_parms = TREE_CHAIN (current_template_parms);
478       poplevel (0, 0, 0);
479     }
480 }
481
482 /* Return a new template argument vector which contains all of ARGS,
483    but has as its innermost set of arguments the EXTRA_ARGS.  */
484
485 static tree
486 add_to_template_args (tree args, tree extra_args)
487 {
488   tree new_args;
489   int extra_depth;
490   int i;
491   int j;
492
493   if (args == NULL_TREE || extra_args == error_mark_node)
494     return extra_args;
495
496   extra_depth = TMPL_ARGS_DEPTH (extra_args);
497   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
498
499   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
500     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
501
502   for (j = 1; j <= extra_depth; ++j, ++i)
503     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
504
505   return new_args;
506 }
507
508 /* Like add_to_template_args, but only the outermost ARGS are added to
509    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
510    (EXTRA_ARGS) levels are added.  This function is used to combine
511    the template arguments from a partial instantiation with the
512    template arguments used to attain the full instantiation from the
513    partial instantiation.  */
514
515 static tree
516 add_outermost_template_args (tree args, tree extra_args)
517 {
518   tree new_args;
519
520   /* If there are more levels of EXTRA_ARGS than there are ARGS,
521      something very fishy is going on.  */
522   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
523
524   /* If *all* the new arguments will be the EXTRA_ARGS, just return
525      them.  */
526   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
527     return extra_args;
528
529   /* For the moment, we make ARGS look like it contains fewer levels.  */
530   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
531
532   new_args = add_to_template_args (args, extra_args);
533
534   /* Now, we restore ARGS to its full dimensions.  */
535   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
536
537   return new_args;
538 }
539
540 /* Return the N levels of innermost template arguments from the ARGS.  */
541
542 tree
543 get_innermost_template_args (tree args, int n)
544 {
545   tree new_args;
546   int extra_levels;
547   int i;
548
549   gcc_assert (n >= 0);
550
551   /* If N is 1, just return the innermost set of template arguments.  */
552   if (n == 1)
553     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
554
555   /* If we're not removing anything, just return the arguments we were
556      given.  */
557   extra_levels = TMPL_ARGS_DEPTH (args) - n;
558   gcc_assert (extra_levels >= 0);
559   if (extra_levels == 0)
560     return args;
561
562   /* Make a new set of arguments, not containing the outer arguments.  */
563   new_args = make_tree_vec (n);
564   for (i = 1; i <= n; ++i)
565     SET_TMPL_ARGS_LEVEL (new_args, i,
566                          TMPL_ARGS_LEVEL (args, i + extra_levels));
567
568   return new_args;
569 }
570
571 /* The inverse of get_innermost_template_args: Return all but the innermost
572    EXTRA_LEVELS levels of template arguments from the ARGS.  */
573
574 static tree
575 strip_innermost_template_args (tree args, int extra_levels)
576 {
577   tree new_args;
578   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
579   int i;
580
581   gcc_assert (n >= 0);
582
583   /* If N is 1, just return the outermost set of template arguments.  */
584   if (n == 1)
585     return TMPL_ARGS_LEVEL (args, 1);
586
587   /* If we're not removing anything, just return the arguments we were
588      given.  */
589   gcc_assert (extra_levels >= 0);
590   if (extra_levels == 0)
591     return args;
592
593   /* Make a new set of arguments, not containing the inner arguments.  */
594   new_args = make_tree_vec (n);
595   for (i = 1; i <= n; ++i)
596     SET_TMPL_ARGS_LEVEL (new_args, i,
597                          TMPL_ARGS_LEVEL (args, i));
598
599   return new_args;
600 }
601
602 /* We've got a template header coming up; push to a new level for storing
603    the parms.  */
604
605 void
606 begin_template_parm_list (void)
607 {
608   /* We use a non-tag-transparent scope here, which causes pushtag to
609      put tags in this scope, rather than in the enclosing class or
610      namespace scope.  This is the right thing, since we want
611      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
612      global template class, push_template_decl handles putting the
613      TEMPLATE_DECL into top-level scope.  For a nested template class,
614      e.g.:
615
616        template <class T> struct S1 {
617          template <class T> struct S2 {};
618        };
619
620      pushtag contains special code to call pushdecl_with_scope on the
621      TEMPLATE_DECL for S2.  */
622   begin_scope (sk_template_parms, NULL);
623   ++processing_template_decl;
624   ++processing_template_parmlist;
625   note_template_header (0);
626 }
627
628 /* This routine is called when a specialization is declared.  If it is
629    invalid to declare a specialization here, an error is reported and
630    false is returned, otherwise this routine will return true.  */
631
632 static bool
633 check_specialization_scope (void)
634 {
635   tree scope = current_scope ();
636
637   /* [temp.expl.spec]
638
639      An explicit specialization shall be declared in the namespace of
640      which the template is a member, or, for member templates, in the
641      namespace of which the enclosing class or enclosing class
642      template is a member.  An explicit specialization of a member
643      function, member class or static data member of a class template
644      shall be declared in the namespace of which the class template
645      is a member.  */
646   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
647     {
648       error ("explicit specialization in non-namespace scope %qD", scope);
649       return false;
650     }
651
652   /* [temp.expl.spec]
653
654      In an explicit specialization declaration for a member of a class
655      template or a member template that appears in namespace scope,
656      the member template and some of its enclosing class templates may
657      remain unspecialized, except that the declaration shall not
658      explicitly specialize a class member template if its enclosing
659      class templates are not explicitly specialized as well.  */
660   if (current_template_parms)
661     {
662       error ("enclosing class templates are not explicitly specialized");
663       return false;
664     }
665
666   return true;
667 }
668
669 /* We've just seen template <>.  */
670
671 bool
672 begin_specialization (void)
673 {
674   begin_scope (sk_template_spec, NULL);
675   note_template_header (1);
676   return check_specialization_scope ();
677 }
678
679 /* Called at then end of processing a declaration preceded by
680    template<>.  */
681
682 void
683 end_specialization (void)
684 {
685   finish_scope ();
686   reset_specialization ();
687 }
688
689 /* Any template <>'s that we have seen thus far are not referring to a
690    function specialization.  */
691
692 void
693 reset_specialization (void)
694 {
695   processing_specialization = 0;
696   template_header_count = 0;
697 }
698
699 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
700    it was of the form template <>.  */
701
702 static void
703 note_template_header (int specialization)
704 {
705   processing_specialization = specialization;
706   template_header_count++;
707 }
708
709 /* We're beginning an explicit instantiation.  */
710
711 void
712 begin_explicit_instantiation (void)
713 {
714   gcc_assert (!processing_explicit_instantiation);
715   processing_explicit_instantiation = true;
716 }
717
718
719 void
720 end_explicit_instantiation (void)
721 {
722   gcc_assert (processing_explicit_instantiation);
723   processing_explicit_instantiation = false;
724 }
725
726 /* An explicit specialization or partial specialization TMPL is being
727    declared.  Check that the namespace in which the specialization is
728    occurring is permissible.  Returns false iff it is invalid to
729    specialize TMPL in the current namespace.  */
730
731 static bool
732 check_specialization_namespace (tree tmpl)
733 {
734   tree tpl_ns = decl_namespace_context (tmpl);
735
736   /* [tmpl.expl.spec]
737
738      An explicit specialization shall be declared in the namespace of
739      which the template is a member, or, for member templates, in the
740      namespace of which the enclosing class or enclosing class
741      template is a member.  An explicit specialization of a member
742      function, member class or static data member of a class template
743      shall be declared in the namespace of which the class template is
744      a member.  */
745   if (current_scope() != DECL_CONTEXT (tmpl)
746       && !at_namespace_scope_p ())
747     {
748       error ("specialization of %qD must appear at namespace scope", tmpl);
749       return false;
750     }
751   if (is_associated_namespace (current_namespace, tpl_ns))
752     /* Same or super-using namespace.  */
753     return true;
754   else
755     {
756       permerror (input_location, "specialization of %qD in different namespace", tmpl);
757       permerror (input_location, "  from definition of %q+#D", tmpl);
758       return false;
759     }
760 }
761
762 /* SPEC is an explicit instantiation.  Check that it is valid to
763    perform this explicit instantiation in the current namespace.  */
764
765 static void
766 check_explicit_instantiation_namespace (tree spec)
767 {
768   tree ns;
769
770   /* DR 275: An explicit instantiation shall appear in an enclosing
771      namespace of its template.  */
772   ns = decl_namespace_context (spec);
773   if (!is_ancestor (current_namespace, ns))
774     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
775                "(which does not enclose namespace %qD)",
776                spec, current_namespace, ns);
777 }
778
779 /* The TYPE is being declared.  If it is a template type, that means it
780    is a partial specialization.  Do appropriate error-checking.  */
781
782 tree
783 maybe_process_partial_specialization (tree type)
784 {
785   tree context;
786
787   if (type == error_mark_node)
788     return error_mark_node;
789
790   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
791     {
792       error ("name of class shadows template template parameter %qD",
793              TYPE_NAME (type));
794       return error_mark_node;
795     }
796
797   context = TYPE_CONTEXT (type);
798
799   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
800     {
801       /* This is for ordinary explicit specialization and partial
802          specialization of a template class such as:
803
804            template <> class C<int>;
805
806          or:
807
808            template <class T> class C<T*>;
809
810          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
811
812       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
813           && !COMPLETE_TYPE_P (type))
814         {
815           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
816           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
817           if (processing_template_decl)
818             {
819               if (push_template_decl (TYPE_MAIN_DECL (type))
820                   == error_mark_node)
821                 return error_mark_node;
822             }
823         }
824       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
825         error ("specialization of %qT after instantiation", type);
826     }
827   else if (CLASS_TYPE_P (type)
828            && !CLASSTYPE_USE_TEMPLATE (type)
829            && CLASSTYPE_TEMPLATE_INFO (type)
830            && context && CLASS_TYPE_P (context)
831            && CLASSTYPE_TEMPLATE_INFO (context))
832     {
833       /* This is for an explicit specialization of member class
834          template according to [temp.expl.spec/18]:
835
836            template <> template <class U> class C<int>::D;
837
838          The context `C<int>' must be an implicit instantiation.
839          Otherwise this is just a member class template declared
840          earlier like:
841
842            template <> class C<int> { template <class U> class D; };
843            template <> template <class U> class C<int>::D;
844
845          In the first case, `C<int>::D' is a specialization of `C<T>::D'
846          while in the second case, `C<int>::D' is a primary template
847          and `C<T>::D' may not exist.  */
848
849       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
850           && !COMPLETE_TYPE_P (type))
851         {
852           tree t;
853           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
854
855           if (current_namespace
856               != decl_namespace_context (tmpl))
857             {
858               permerror (input_location, "specializing %q#T in different namespace", type);
859               permerror (input_location, "  from definition of %q+#D", tmpl);
860             }
861
862           /* Check for invalid specialization after instantiation:
863
864                template <> template <> class C<int>::D<int>;
865                template <> template <class U> class C<int>::D;  */
866
867           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
868                t; t = TREE_CHAIN (t))
869             {
870               tree inst = TREE_VALUE (t);
871               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
872                 {
873                   /* We already have a full specialization of this partial
874                      instantiation.  Reassign it to the new member
875                      specialization template.  */
876                   spec_entry elt;
877                   spec_entry **slot;
878
879                   elt.tmpl = most_general_template (tmpl);
880                   elt.args = CLASSTYPE_TI_ARGS (inst);
881                   elt.spec = inst;
882
883                   htab_remove_elt (type_specializations, &elt);
884
885                   elt.tmpl = tmpl;
886                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
887
888                   slot = (spec_entry **)
889                     htab_find_slot (type_specializations, &elt, INSERT);
890                   *slot = ggc_alloc_spec_entry ();
891                   **slot = elt;
892                 }
893               else if (COMPLETE_OR_OPEN_TYPE_P (inst))
894                 /* But if we've had an implicit instantiation, that's a
895                    problem ([temp.expl.spec]/6).  */
896                 error ("specialization %qT after instantiation %qT",
897                        type, inst);
898             }
899
900           /* Mark TYPE as a specialization.  And as a result, we only
901              have one level of template argument for the innermost
902              class template.  */
903           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
904           CLASSTYPE_TI_ARGS (type)
905             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
906         }
907     }
908   else if (processing_specialization)
909     {
910        /* Someday C++0x may allow for enum template specialization.  */
911       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
912           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
913         pedwarn (input_location, OPT_pedantic, "template specialization "
914                  "of %qD not allowed by ISO C++", type);
915       else
916         {
917           error ("explicit specialization of non-template %qT", type);
918           return error_mark_node;
919         }
920     }
921
922   return type;
923 }
924
925 /* Returns nonzero if we can optimize the retrieval of specializations
926    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
927    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
928
929 static inline bool
930 optimize_specialization_lookup_p (tree tmpl)
931 {
932   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
933           && DECL_CLASS_SCOPE_P (tmpl)
934           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
935              parameter.  */
936           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
937           /* The optimized lookup depends on the fact that the
938              template arguments for the member function template apply
939              purely to the containing class, which is not true if the
940              containing class is an explicit or partial
941              specialization.  */
942           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
943           && !DECL_MEMBER_TEMPLATE_P (tmpl)
944           && !DECL_CONV_FN_P (tmpl)
945           /* It is possible to have a template that is not a member
946              template and is not a member of a template class:
947
948              template <typename T>
949              struct S { friend A::f(); };
950
951              Here, the friend function is a template, but the context does
952              not have template information.  The optimized lookup relies
953              on having ARGS be the template arguments for both the class
954              and the function template.  */
955           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
956 }
957
958 /* Retrieve the specialization (in the sense of [temp.spec] - a
959    specialization is either an instantiation or an explicit
960    specialization) of TMPL for the given template ARGS.  If there is
961    no such specialization, return NULL_TREE.  The ARGS are a vector of
962    arguments, or a vector of vectors of arguments, in the case of
963    templates with more than one level of parameters.
964
965    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
966    then we search for a partial specialization matching ARGS.  This
967    parameter is ignored if TMPL is not a class template.  */
968
969 static tree
970 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
971 {
972   if (args == error_mark_node)
973     return NULL_TREE;
974
975   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
976
977   /* There should be as many levels of arguments as there are
978      levels of parameters.  */
979   gcc_assert (TMPL_ARGS_DEPTH (args)
980               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
981
982   if (optimize_specialization_lookup_p (tmpl))
983     {
984       tree class_template;
985       tree class_specialization;
986       VEC(tree,gc) *methods;
987       tree fns;
988       int idx;
989
990       /* The template arguments actually apply to the containing
991          class.  Find the class specialization with those
992          arguments.  */
993       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
994       class_specialization
995         = retrieve_specialization (class_template, args, 0);
996       if (!class_specialization)
997         return NULL_TREE;
998       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
999          for the specialization.  */
1000       idx = class_method_index_for_fn (class_specialization, tmpl);
1001       if (idx == -1)
1002         return NULL_TREE;
1003       /* Iterate through the methods with the indicated name, looking
1004          for the one that has an instance of TMPL.  */
1005       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1006       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1007         {
1008           tree fn = OVL_CURRENT (fns);
1009           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1010               /* using-declarations can add base methods to the method vec,
1011                  and we don't want those here.  */
1012               && DECL_CONTEXT (fn) == class_specialization)
1013             return fn;
1014         }
1015       return NULL_TREE;
1016     }
1017   else
1018     {
1019       spec_entry *found;
1020       spec_entry elt;
1021       htab_t specializations;
1022
1023       elt.tmpl = tmpl;
1024       elt.args = args;
1025       elt.spec = NULL_TREE;
1026
1027       if (DECL_CLASS_TEMPLATE_P (tmpl))
1028         specializations = type_specializations;
1029       else
1030         specializations = decl_specializations;
1031
1032       if (hash == 0)
1033         hash = hash_specialization (&elt);
1034       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1035       if (found)
1036         return found->spec;
1037     }
1038
1039   return NULL_TREE;
1040 }
1041
1042 /* Like retrieve_specialization, but for local declarations.  */
1043
1044 static tree
1045 retrieve_local_specialization (tree tmpl)
1046 {
1047   tree spec;
1048
1049   if (local_specializations == NULL)
1050     return NULL_TREE;
1051
1052   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1053                                      htab_hash_pointer (tmpl));
1054   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1055 }
1056
1057 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1058
1059 int
1060 is_specialization_of (tree decl, tree tmpl)
1061 {
1062   tree t;
1063
1064   if (TREE_CODE (decl) == FUNCTION_DECL)
1065     {
1066       for (t = decl;
1067            t != NULL_TREE;
1068            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1069         if (t == tmpl)
1070           return 1;
1071     }
1072   else
1073     {
1074       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1075
1076       for (t = TREE_TYPE (decl);
1077            t != NULL_TREE;
1078            t = CLASSTYPE_USE_TEMPLATE (t)
1079              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1080         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1081           return 1;
1082     }
1083
1084   return 0;
1085 }
1086
1087 /* Returns nonzero iff DECL is a specialization of friend declaration
1088    FRIEND_DECL according to [temp.friend].  */
1089
1090 bool
1091 is_specialization_of_friend (tree decl, tree friend_decl)
1092 {
1093   bool need_template = true;
1094   int template_depth;
1095
1096   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1097               || TREE_CODE (decl) == TYPE_DECL);
1098
1099   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1100      of a template class, we want to check if DECL is a specialization
1101      if this.  */
1102   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1103       && DECL_TEMPLATE_INFO (friend_decl)
1104       && !DECL_USE_TEMPLATE (friend_decl))
1105     {
1106       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1107       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1108       need_template = false;
1109     }
1110   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1111            && !PRIMARY_TEMPLATE_P (friend_decl))
1112     need_template = false;
1113
1114   /* There is nothing to do if this is not a template friend.  */
1115   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1116     return false;
1117
1118   if (is_specialization_of (decl, friend_decl))
1119     return true;
1120
1121   /* [temp.friend/6]
1122      A member of a class template may be declared to be a friend of a
1123      non-template class.  In this case, the corresponding member of
1124      every specialization of the class template is a friend of the
1125      class granting friendship.
1126
1127      For example, given a template friend declaration
1128
1129        template <class T> friend void A<T>::f();
1130
1131      the member function below is considered a friend
1132
1133        template <> struct A<int> {
1134          void f();
1135        };
1136
1137      For this type of template friend, TEMPLATE_DEPTH below will be
1138      nonzero.  To determine if DECL is a friend of FRIEND, we first
1139      check if the enclosing class is a specialization of another.  */
1140
1141   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1142   if (template_depth
1143       && DECL_CLASS_SCOPE_P (decl)
1144       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1145                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1146     {
1147       /* Next, we check the members themselves.  In order to handle
1148          a few tricky cases, such as when FRIEND_DECL's are
1149
1150            template <class T> friend void A<T>::g(T t);
1151            template <class T> template <T t> friend void A<T>::h();
1152
1153          and DECL's are
1154
1155            void A<int>::g(int);
1156            template <int> void A<int>::h();
1157
1158          we need to figure out ARGS, the template arguments from
1159          the context of DECL.  This is required for template substitution
1160          of `T' in the function parameter of `g' and template parameter
1161          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1162
1163       tree context = DECL_CONTEXT (decl);
1164       tree args = NULL_TREE;
1165       int current_depth = 0;
1166
1167       while (current_depth < template_depth)
1168         {
1169           if (CLASSTYPE_TEMPLATE_INFO (context))
1170             {
1171               if (current_depth == 0)
1172                 args = TYPE_TI_ARGS (context);
1173               else
1174                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1175               current_depth++;
1176             }
1177           context = TYPE_CONTEXT (context);
1178         }
1179
1180       if (TREE_CODE (decl) == FUNCTION_DECL)
1181         {
1182           bool is_template;
1183           tree friend_type;
1184           tree decl_type;
1185           tree friend_args_type;
1186           tree decl_args_type;
1187
1188           /* Make sure that both DECL and FRIEND_DECL are templates or
1189              non-templates.  */
1190           is_template = DECL_TEMPLATE_INFO (decl)
1191                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1192           if (need_template ^ is_template)
1193             return false;
1194           else if (is_template)
1195             {
1196               /* If both are templates, check template parameter list.  */
1197               tree friend_parms
1198                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1199                                          args, tf_none);
1200               if (!comp_template_parms
1201                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1202                       friend_parms))
1203                 return false;
1204
1205               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1206             }
1207           else
1208             decl_type = TREE_TYPE (decl);
1209
1210           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1211                                               tf_none, NULL_TREE);
1212           if (friend_type == error_mark_node)
1213             return false;
1214
1215           /* Check if return types match.  */
1216           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1217             return false;
1218
1219           /* Check if function parameter types match, ignoring the
1220              `this' parameter.  */
1221           friend_args_type = TYPE_ARG_TYPES (friend_type);
1222           decl_args_type = TYPE_ARG_TYPES (decl_type);
1223           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1224             friend_args_type = TREE_CHAIN (friend_args_type);
1225           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1226             decl_args_type = TREE_CHAIN (decl_args_type);
1227
1228           return compparms (decl_args_type, friend_args_type);
1229         }
1230       else
1231         {
1232           /* DECL is a TYPE_DECL */
1233           bool is_template;
1234           tree decl_type = TREE_TYPE (decl);
1235
1236           /* Make sure that both DECL and FRIEND_DECL are templates or
1237              non-templates.  */
1238           is_template
1239             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1240               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1241
1242           if (need_template ^ is_template)
1243             return false;
1244           else if (is_template)
1245             {
1246               tree friend_parms;
1247               /* If both are templates, check the name of the two
1248                  TEMPLATE_DECL's first because is_friend didn't.  */
1249               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1250                   != DECL_NAME (friend_decl))
1251                 return false;
1252
1253               /* Now check template parameter list.  */
1254               friend_parms
1255                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1256                                          args, tf_none);
1257               return comp_template_parms
1258                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1259                  friend_parms);
1260             }
1261           else
1262             return (DECL_NAME (decl)
1263                     == DECL_NAME (friend_decl));
1264         }
1265     }
1266   return false;
1267 }
1268
1269 /* Register the specialization SPEC as a specialization of TMPL with
1270    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1271    is actually just a friend declaration.  Returns SPEC, or an
1272    equivalent prior declaration, if available.  */
1273
1274 static tree
1275 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1276                          hashval_t hash)
1277 {
1278   tree fn;
1279   spec_entry **slot = NULL;
1280   spec_entry elt;
1281
1282   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1283
1284   if (TREE_CODE (spec) == FUNCTION_DECL
1285       && uses_template_parms (DECL_TI_ARGS (spec)))
1286     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1287        register it; we want the corresponding TEMPLATE_DECL instead.
1288        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1289        the more obvious `uses_template_parms (spec)' to avoid problems
1290        with default function arguments.  In particular, given
1291        something like this:
1292
1293           template <class T> void f(T t1, T t = T())
1294
1295        the default argument expression is not substituted for in an
1296        instantiation unless and until it is actually needed.  */
1297     return spec;
1298
1299   if (optimize_specialization_lookup_p (tmpl))
1300     /* We don't put these specializations in the hash table, but we might
1301        want to give an error about a mismatch.  */
1302     fn = retrieve_specialization (tmpl, args, 0);
1303   else
1304     {
1305       elt.tmpl = tmpl;
1306       elt.args = args;
1307       elt.spec = spec;
1308
1309       if (hash == 0)
1310         hash = hash_specialization (&elt);
1311
1312       slot = (spec_entry **)
1313         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1314       if (*slot)
1315         fn = (*slot)->spec;
1316       else
1317         fn = NULL_TREE;
1318     }
1319
1320   /* We can sometimes try to re-register a specialization that we've
1321      already got.  In particular, regenerate_decl_from_template calls
1322      duplicate_decls which will update the specialization list.  But,
1323      we'll still get called again here anyhow.  It's more convenient
1324      to simply allow this than to try to prevent it.  */
1325   if (fn == spec)
1326     return spec;
1327   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1328     {
1329       if (DECL_TEMPLATE_INSTANTIATION (fn))
1330         {
1331           if (DECL_ODR_USED (fn)
1332               || DECL_EXPLICIT_INSTANTIATION (fn))
1333             {
1334               error ("specialization of %qD after instantiation",
1335                      fn);
1336               return error_mark_node;
1337             }
1338           else
1339             {
1340               tree clone;
1341               /* This situation should occur only if the first
1342                  specialization is an implicit instantiation, the
1343                  second is an explicit specialization, and the
1344                  implicit instantiation has not yet been used.  That
1345                  situation can occur if we have implicitly
1346                  instantiated a member function and then specialized
1347                  it later.
1348
1349                  We can also wind up here if a friend declaration that
1350                  looked like an instantiation turns out to be a
1351                  specialization:
1352
1353                    template <class T> void foo(T);
1354                    class S { friend void foo<>(int) };
1355                    template <> void foo(int);
1356
1357                  We transform the existing DECL in place so that any
1358                  pointers to it become pointers to the updated
1359                  declaration.
1360
1361                  If there was a definition for the template, but not
1362                  for the specialization, we want this to look as if
1363                  there were no definition, and vice versa.  */
1364               DECL_INITIAL (fn) = NULL_TREE;
1365               duplicate_decls (spec, fn, is_friend);
1366               /* The call to duplicate_decls will have applied
1367                  [temp.expl.spec]:
1368
1369                    An explicit specialization of a function template
1370                    is inline only if it is explicitly declared to be,
1371                    and independently of whether its function template
1372                    is.
1373
1374                 to the primary function; now copy the inline bits to
1375                 the various clones.  */
1376               FOR_EACH_CLONE (clone, fn)
1377                 {
1378                   DECL_DECLARED_INLINE_P (clone)
1379                     = DECL_DECLARED_INLINE_P (fn);
1380                   DECL_SOURCE_LOCATION (clone)
1381                     = DECL_SOURCE_LOCATION (fn);
1382                 }
1383               check_specialization_namespace (fn);
1384
1385               return fn;
1386             }
1387         }
1388       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1389         {
1390           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1391             /* Dup decl failed, but this is a new definition. Set the
1392                line number so any errors match this new
1393                definition.  */
1394             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1395
1396           return fn;
1397         }
1398     }
1399   else if (fn)
1400     return duplicate_decls (spec, fn, is_friend);
1401
1402   /* A specialization must be declared in the same namespace as the
1403      template it is specializing.  */
1404   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1405       && !check_specialization_namespace (tmpl))
1406     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1407
1408   if (!optimize_specialization_lookup_p (tmpl))
1409     {
1410       gcc_assert (tmpl && args && spec);
1411       *slot = ggc_alloc_spec_entry ();
1412       **slot = elt;
1413       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1414           && PRIMARY_TEMPLATE_P (tmpl)
1415           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1416         /* TMPL is a forward declaration of a template function; keep a list
1417            of all specializations in case we need to reassign them to a friend
1418            template later in tsubst_friend_function.  */
1419         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1420           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1421     }
1422
1423   return spec;
1424 }
1425
1426 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1427    TMPL and ARGS members, ignores SPEC.  */
1428
1429 static int
1430 eq_specializations (const void *p1, const void *p2)
1431 {
1432   const spec_entry *e1 = (const spec_entry *)p1;
1433   const spec_entry *e2 = (const spec_entry *)p2;
1434
1435   return (e1->tmpl == e2->tmpl
1436           && comp_template_args (e1->args, e2->args));
1437 }
1438
1439 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1440
1441 static hashval_t
1442 hash_tmpl_and_args (tree tmpl, tree args)
1443 {
1444   hashval_t val = DECL_UID (tmpl);
1445   return iterative_hash_template_arg (args, val);
1446 }
1447
1448 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1449    ignoring SPEC.  */
1450
1451 static hashval_t
1452 hash_specialization (const void *p)
1453 {
1454   const spec_entry *e = (const spec_entry *)p;
1455   return hash_tmpl_and_args (e->tmpl, e->args);
1456 }
1457
1458 /* Recursively calculate a hash value for a template argument ARG, for use
1459    in the hash tables of template specializations.  */
1460
1461 static hashval_t
1462 iterative_hash_template_arg (tree arg, hashval_t val)
1463 {
1464   unsigned HOST_WIDE_INT i;
1465   enum tree_code code;
1466   char tclass;
1467
1468   if (arg == NULL_TREE)
1469     return iterative_hash_object (arg, val);
1470
1471   if (!TYPE_P (arg))
1472     STRIP_NOPS (arg);
1473
1474   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1475     /* We can get one of these when re-hashing a previous entry in the middle
1476        of substituting into a pack expansion.  Just look through it.  */
1477     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1478
1479   code = TREE_CODE (arg);
1480   tclass = TREE_CODE_CLASS (code);
1481
1482   val = iterative_hash_object (code, val);
1483
1484   switch (code)
1485     {
1486     case ERROR_MARK:
1487       return val;
1488
1489     case IDENTIFIER_NODE:
1490       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1491
1492     case TREE_VEC:
1493       {
1494         int i, len = TREE_VEC_LENGTH (arg);
1495         for (i = 0; i < len; ++i)
1496           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1497         return val;
1498       }
1499
1500     case TYPE_PACK_EXPANSION:
1501     case EXPR_PACK_EXPANSION:
1502       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1503
1504     case TYPE_ARGUMENT_PACK:
1505     case NONTYPE_ARGUMENT_PACK:
1506       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1507
1508     case TREE_LIST:
1509       for (; arg; arg = TREE_CHAIN (arg))
1510         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1511       return val;
1512
1513     case OVERLOAD:
1514       for (; arg; arg = OVL_CHAIN (arg))
1515         val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1516       return val;
1517
1518     case CONSTRUCTOR:
1519       {
1520         tree field, value;
1521         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1522           {
1523             val = iterative_hash_template_arg (field, val);
1524             val = iterative_hash_template_arg (value, val);
1525           }
1526         return val;
1527       }
1528
1529     case PARM_DECL:
1530       if (!DECL_ARTIFICIAL (arg))
1531         val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1532       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1533
1534     case TARGET_EXPR:
1535       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1536
1537     case PTRMEM_CST:
1538       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1539       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1540
1541     case TEMPLATE_PARM_INDEX:
1542       val = iterative_hash_template_arg
1543         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1544       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1545       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1546
1547     case TRAIT_EXPR:
1548       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1549       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1550       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1551
1552     case BASELINK:
1553       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1554                                          val);
1555       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1556                                           val);
1557
1558     case MODOP_EXPR:
1559       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1560       code = TREE_CODE (TREE_OPERAND (arg, 1));
1561       val = iterative_hash_object (code, val);
1562       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1563
1564     case ARRAY_TYPE:
1565       /* layout_type sets structural equality for arrays of
1566          incomplete type, so we can't rely on the canonical type
1567          for hashing.  */
1568       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1569       return iterative_hash_template_arg (TYPE_DOMAIN (arg), val);
1570
1571     case LAMBDA_EXPR:
1572       /* A lambda can't appear in a template arg, but don't crash on
1573          erroneous input.  */
1574       gcc_assert (seen_error ());
1575       return val;
1576
1577     case CAST_EXPR:
1578     case STATIC_CAST_EXPR:
1579     case REINTERPRET_CAST_EXPR:
1580     case CONST_CAST_EXPR:
1581     case DYNAMIC_CAST_EXPR:
1582     case NEW_EXPR:
1583       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1584       /* Now hash operands as usual.  */
1585       break;
1586
1587     default:
1588       break;
1589     }
1590
1591   switch (tclass)
1592     {
1593     case tcc_type:
1594       if (TYPE_CANONICAL (arg))
1595         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1596                                       val);
1597       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1598         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1599       /* Otherwise just compare the types during lookup.  */
1600       return val;
1601
1602     case tcc_declaration:
1603     case tcc_constant:
1604       return iterative_hash_expr (arg, val);
1605
1606     default:
1607       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1608       {
1609         unsigned n = TREE_OPERAND_LENGTH (arg);
1610         for (i = 0; i < n; ++i)
1611           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1612         return val;
1613       }
1614     }
1615   gcc_unreachable ();
1616   return 0;
1617 }
1618
1619 /* Unregister the specialization SPEC as a specialization of TMPL.
1620    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1621    if the SPEC was listed as a specialization of TMPL.
1622
1623    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1624
1625 bool
1626 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1627 {
1628   spec_entry **slot;
1629   spec_entry elt;
1630
1631   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1632   elt.args = TI_ARGS (tinfo);
1633   elt.spec = NULL_TREE;
1634
1635   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1636   if (*slot)
1637     {
1638       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1639       gcc_assert (new_spec != NULL_TREE);
1640       (*slot)->spec = new_spec;
1641       return 1;
1642     }
1643
1644   return 0;
1645 }
1646
1647 /* Compare an entry in the local specializations hash table P1 (which
1648    is really a pointer to a TREE_LIST) with P2 (which is really a
1649    DECL).  */
1650
1651 static int
1652 eq_local_specializations (const void *p1, const void *p2)
1653 {
1654   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1655 }
1656
1657 /* Hash P1, an entry in the local specializations table.  */
1658
1659 static hashval_t
1660 hash_local_specialization (const void* p1)
1661 {
1662   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1663 }
1664
1665 /* Like register_specialization, but for local declarations.  We are
1666    registering SPEC, an instantiation of TMPL.  */
1667
1668 static void
1669 register_local_specialization (tree spec, tree tmpl)
1670 {
1671   void **slot;
1672
1673   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1674                                    htab_hash_pointer (tmpl), INSERT);
1675   *slot = build_tree_list (spec, tmpl);
1676 }
1677
1678 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1679    specialized class.  */
1680
1681 bool
1682 explicit_class_specialization_p (tree type)
1683 {
1684   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1685     return false;
1686   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1687 }
1688
1689 /* Print the list of functions at FNS, going through all the overloads
1690    for each element of the list.  Alternatively, FNS can not be a
1691    TREE_LIST, in which case it will be printed together with all the
1692    overloads.
1693
1694    MORE and *STR should respectively be FALSE and NULL when the function
1695    is called from the outside.  They are used internally on recursive
1696    calls.  print_candidates manages the two parameters and leaves NULL
1697    in *STR when it ends.  */
1698
1699 static void
1700 print_candidates_1 (tree fns, bool more, const char **str)
1701 {
1702   tree fn, fn2;
1703   char *spaces = NULL;
1704
1705   for (fn = fns; fn; fn = OVL_NEXT (fn))
1706     if (TREE_CODE (fn) == TREE_LIST)
1707       {
1708         gcc_assert (!OVL_NEXT (fn) && !is_overloaded_fn (fn));
1709         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1710           print_candidates_1 (TREE_VALUE (fn2),
1711                               TREE_CHAIN (fn2) || more, str);
1712       }
1713     else
1714       {
1715         if (!*str)
1716           {
1717             /* Pick the prefix string.  */
1718             if (!more && !OVL_NEXT (fns))
1719               {
1720                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1721                 continue;
1722               }
1723
1724             *str = _("candidates are:");
1725             spaces = get_spaces (*str);
1726           }
1727         error ("%s %+#D", *str, OVL_CURRENT (fn));
1728         *str = spaces ? spaces : *str;
1729       }
1730
1731   if (!more)
1732     {
1733       free (spaces);
1734       *str = NULL;
1735     }
1736 }
1737
1738 /* Print the list of candidate FNS in an error message.  */
1739
1740 void
1741 print_candidates (tree fns)
1742 {
1743   const char *str = NULL;
1744   print_candidates_1 (fns, false, &str);
1745   gcc_assert (str == NULL);
1746 }
1747
1748 /* Returns the template (one of the functions given by TEMPLATE_ID)
1749    which can be specialized to match the indicated DECL with the
1750    explicit template args given in TEMPLATE_ID.  The DECL may be
1751    NULL_TREE if none is available.  In that case, the functions in
1752    TEMPLATE_ID are non-members.
1753
1754    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1755    specialization of a member template.
1756
1757    The TEMPLATE_COUNT is the number of references to qualifying
1758    template classes that appeared in the name of the function. See
1759    check_explicit_specialization for a more accurate description.
1760
1761    TSK indicates what kind of template declaration (if any) is being
1762    declared.  TSK_TEMPLATE indicates that the declaration given by
1763    DECL, though a FUNCTION_DECL, has template parameters, and is
1764    therefore a template function.
1765
1766    The template args (those explicitly specified and those deduced)
1767    are output in a newly created vector *TARGS_OUT.
1768
1769    If it is impossible to determine the result, an error message is
1770    issued.  The error_mark_node is returned to indicate failure.  */
1771
1772 static tree
1773 determine_specialization (tree template_id,
1774                           tree decl,
1775                           tree* targs_out,
1776                           int need_member_template,
1777                           int template_count,
1778                           tmpl_spec_kind tsk)
1779 {
1780   tree fns;
1781   tree targs;
1782   tree explicit_targs;
1783   tree candidates = NULL_TREE;
1784   /* A TREE_LIST of templates of which DECL may be a specialization.
1785      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1786      corresponding TREE_PURPOSE is the set of template arguments that,
1787      when used to instantiate the template, would produce a function
1788      with the signature of DECL.  */
1789   tree templates = NULL_TREE;
1790   int header_count;
1791   struct cp_binding_level *b;
1792
1793   *targs_out = NULL_TREE;
1794
1795   if (template_id == error_mark_node || decl == error_mark_node)
1796     return error_mark_node;
1797
1798   fns = TREE_OPERAND (template_id, 0);
1799   explicit_targs = TREE_OPERAND (template_id, 1);
1800
1801   if (fns == error_mark_node)
1802     return error_mark_node;
1803
1804   /* Check for baselinks.  */
1805   if (BASELINK_P (fns))
1806     fns = BASELINK_FUNCTIONS (fns);
1807
1808   if (!is_overloaded_fn (fns))
1809     {
1810       error ("%qD is not a function template", fns);
1811       return error_mark_node;
1812     }
1813
1814   /* Count the number of template headers specified for this
1815      specialization.  */
1816   header_count = 0;
1817   for (b = current_binding_level;
1818        b->kind == sk_template_parms;
1819        b = b->level_chain)
1820     ++header_count;
1821
1822   for (; fns; fns = OVL_NEXT (fns))
1823     {
1824       tree fn = OVL_CURRENT (fns);
1825
1826       if (TREE_CODE (fn) == TEMPLATE_DECL)
1827         {
1828           tree decl_arg_types;
1829           tree fn_arg_types;
1830
1831           /* In case of explicit specialization, we need to check if
1832              the number of template headers appearing in the specialization
1833              is correct. This is usually done in check_explicit_specialization,
1834              but the check done there cannot be exhaustive when specializing
1835              member functions. Consider the following code:
1836
1837              template <> void A<int>::f(int);
1838              template <> template <> void A<int>::f(int);
1839
1840              Assuming that A<int> is not itself an explicit specialization
1841              already, the first line specializes "f" which is a non-template
1842              member function, whilst the second line specializes "f" which
1843              is a template member function. So both lines are syntactically
1844              correct, and check_explicit_specialization does not reject
1845              them.
1846
1847              Here, we can do better, as we are matching the specialization
1848              against the declarations. We count the number of template
1849              headers, and we check if they match TEMPLATE_COUNT + 1
1850              (TEMPLATE_COUNT is the number of qualifying template classes,
1851              plus there must be another header for the member template
1852              itself).
1853
1854              Notice that if header_count is zero, this is not a
1855              specialization but rather a template instantiation, so there
1856              is no check we can perform here.  */
1857           if (header_count && header_count != template_count + 1)
1858             continue;
1859
1860           /* Check that the number of template arguments at the
1861              innermost level for DECL is the same as for FN.  */
1862           if (current_binding_level->kind == sk_template_parms
1863               && !current_binding_level->explicit_spec_p
1864               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1865                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1866                                       (current_template_parms))))
1867             continue;
1868
1869           /* DECL might be a specialization of FN.  */
1870           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1871           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1872
1873           /* For a non-static member function, we need to make sure
1874              that the const qualification is the same.  Since
1875              get_bindings does not try to merge the "this" parameter,
1876              we must do the comparison explicitly.  */
1877           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1878               && !same_type_p (TREE_VALUE (fn_arg_types),
1879                                TREE_VALUE (decl_arg_types)))
1880             continue;
1881
1882           /* Skip the "this" parameter and, for constructors of
1883              classes with virtual bases, the VTT parameter.  A
1884              full specialization of a constructor will have a VTT
1885              parameter, but a template never will.  */ 
1886           decl_arg_types 
1887             = skip_artificial_parms_for (decl, decl_arg_types);
1888           fn_arg_types 
1889             = skip_artificial_parms_for (fn, fn_arg_types);
1890
1891           /* Check that the number of function parameters matches.
1892              For example,
1893                template <class T> void f(int i = 0);
1894                template <> void f<int>();
1895              The specialization f<int> is invalid but is not caught
1896              by get_bindings below.  */
1897           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1898             continue;
1899
1900           /* Function templates cannot be specializations; there are
1901              no partial specializations of functions.  Therefore, if
1902              the type of DECL does not match FN, there is no
1903              match.  */
1904           if (tsk == tsk_template)
1905             {
1906               if (compparms (fn_arg_types, decl_arg_types))
1907                 candidates = tree_cons (NULL_TREE, fn, candidates);
1908               continue;
1909             }
1910
1911           /* See whether this function might be a specialization of this
1912              template.  */
1913           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1914
1915           if (!targs)
1916             /* We cannot deduce template arguments that when used to
1917                specialize TMPL will produce DECL.  */
1918             continue;
1919
1920           /* Save this template, and the arguments deduced.  */
1921           templates = tree_cons (targs, fn, templates);
1922         }
1923       else if (need_member_template)
1924         /* FN is an ordinary member function, and we need a
1925            specialization of a member template.  */
1926         ;
1927       else if (TREE_CODE (fn) != FUNCTION_DECL)
1928         /* We can get IDENTIFIER_NODEs here in certain erroneous
1929            cases.  */
1930         ;
1931       else if (!DECL_FUNCTION_MEMBER_P (fn))
1932         /* This is just an ordinary non-member function.  Nothing can
1933            be a specialization of that.  */
1934         ;
1935       else if (DECL_ARTIFICIAL (fn))
1936         /* Cannot specialize functions that are created implicitly.  */
1937         ;
1938       else
1939         {
1940           tree decl_arg_types;
1941
1942           /* This is an ordinary member function.  However, since
1943              we're here, we can assume it's enclosing class is a
1944              template class.  For example,
1945
1946                template <typename T> struct S { void f(); };
1947                template <> void S<int>::f() {}
1948
1949              Here, S<int>::f is a non-template, but S<int> is a
1950              template class.  If FN has the same type as DECL, we
1951              might be in business.  */
1952
1953           if (!DECL_TEMPLATE_INFO (fn))
1954             /* Its enclosing class is an explicit specialization
1955                of a template class.  This is not a candidate.  */
1956             continue;
1957
1958           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1959                             TREE_TYPE (TREE_TYPE (fn))))
1960             /* The return types differ.  */
1961             continue;
1962
1963           /* Adjust the type of DECL in case FN is a static member.  */
1964           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1965           if (DECL_STATIC_FUNCTION_P (fn)
1966               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1967             decl_arg_types = TREE_CHAIN (decl_arg_types);
1968
1969           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1970                          decl_arg_types))
1971             /* They match!  */
1972             candidates = tree_cons (NULL_TREE, fn, candidates);
1973         }
1974     }
1975
1976   if (templates && TREE_CHAIN (templates))
1977     {
1978       /* We have:
1979
1980            [temp.expl.spec]
1981
1982            It is possible for a specialization with a given function
1983            signature to be instantiated from more than one function
1984            template.  In such cases, explicit specification of the
1985            template arguments must be used to uniquely identify the
1986            function template specialization being specialized.
1987
1988          Note that here, there's no suggestion that we're supposed to
1989          determine which of the candidate templates is most
1990          specialized.  However, we, also have:
1991
1992            [temp.func.order]
1993
1994            Partial ordering of overloaded function template
1995            declarations is used in the following contexts to select
1996            the function template to which a function template
1997            specialization refers:
1998
1999            -- when an explicit specialization refers to a function
2000               template.
2001
2002          So, we do use the partial ordering rules, at least for now.
2003          This extension can only serve to make invalid programs valid,
2004          so it's safe.  And, there is strong anecdotal evidence that
2005          the committee intended the partial ordering rules to apply;
2006          the EDG front end has that behavior, and John Spicer claims
2007          that the committee simply forgot to delete the wording in
2008          [temp.expl.spec].  */
2009       tree tmpl = most_specialized_instantiation (templates);
2010       if (tmpl != error_mark_node)
2011         {
2012           templates = tmpl;
2013           TREE_CHAIN (templates) = NULL_TREE;
2014         }
2015     }
2016
2017   if (templates == NULL_TREE && candidates == NULL_TREE)
2018     {
2019       error ("template-id %qD for %q+D does not match any template "
2020              "declaration", template_id, decl);
2021       if (header_count && header_count != template_count + 1)
2022         inform (input_location, "saw %d %<template<>%>, need %d for "
2023                 "specializing a member function template",
2024                 header_count, template_count + 1);
2025       return error_mark_node;
2026     }
2027   else if ((templates && TREE_CHAIN (templates))
2028            || (candidates && TREE_CHAIN (candidates))
2029            || (templates && candidates))
2030     {
2031       error ("ambiguous template specialization %qD for %q+D",
2032              template_id, decl);
2033       candidates = chainon (candidates, templates);
2034       print_candidates (candidates);
2035       return error_mark_node;
2036     }
2037
2038   /* We have one, and exactly one, match.  */
2039   if (candidates)
2040     {
2041       tree fn = TREE_VALUE (candidates);
2042       *targs_out = copy_node (DECL_TI_ARGS (fn));
2043       /* DECL is a re-declaration or partial instantiation of a template
2044          function.  */
2045       if (TREE_CODE (fn) == TEMPLATE_DECL)
2046         return fn;
2047       /* It was a specialization of an ordinary member function in a
2048          template class.  */
2049       return DECL_TI_TEMPLATE (fn);
2050     }
2051
2052   /* It was a specialization of a template.  */
2053   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2054   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2055     {
2056       *targs_out = copy_node (targs);
2057       SET_TMPL_ARGS_LEVEL (*targs_out,
2058                            TMPL_ARGS_DEPTH (*targs_out),
2059                            TREE_PURPOSE (templates));
2060     }
2061   else
2062     *targs_out = TREE_PURPOSE (templates);
2063   return TREE_VALUE (templates);
2064 }
2065
2066 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2067    but with the default argument values filled in from those in the
2068    TMPL_TYPES.  */
2069
2070 static tree
2071 copy_default_args_to_explicit_spec_1 (tree spec_types,
2072                                       tree tmpl_types)
2073 {
2074   tree new_spec_types;
2075
2076   if (!spec_types)
2077     return NULL_TREE;
2078
2079   if (spec_types == void_list_node)
2080     return void_list_node;
2081
2082   /* Substitute into the rest of the list.  */
2083   new_spec_types =
2084     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2085                                           TREE_CHAIN (tmpl_types));
2086
2087   /* Add the default argument for this parameter.  */
2088   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2089                          TREE_VALUE (spec_types),
2090                          new_spec_types);
2091 }
2092
2093 /* DECL is an explicit specialization.  Replicate default arguments
2094    from the template it specializes.  (That way, code like:
2095
2096      template <class T> void f(T = 3);
2097      template <> void f(double);
2098      void g () { f (); }
2099
2100    works, as required.)  An alternative approach would be to look up
2101    the correct default arguments at the call-site, but this approach
2102    is consistent with how implicit instantiations are handled.  */
2103
2104 static void
2105 copy_default_args_to_explicit_spec (tree decl)
2106 {
2107   tree tmpl;
2108   tree spec_types;
2109   tree tmpl_types;
2110   tree new_spec_types;
2111   tree old_type;
2112   tree new_type;
2113   tree t;
2114   tree object_type = NULL_TREE;
2115   tree in_charge = NULL_TREE;
2116   tree vtt = NULL_TREE;
2117
2118   /* See if there's anything we need to do.  */
2119   tmpl = DECL_TI_TEMPLATE (decl);
2120   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2121   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2122     if (TREE_PURPOSE (t))
2123       break;
2124   if (!t)
2125     return;
2126
2127   old_type = TREE_TYPE (decl);
2128   spec_types = TYPE_ARG_TYPES (old_type);
2129
2130   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2131     {
2132       /* Remove the this pointer, but remember the object's type for
2133          CV quals.  */
2134       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2135       spec_types = TREE_CHAIN (spec_types);
2136       tmpl_types = TREE_CHAIN (tmpl_types);
2137
2138       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2139         {
2140           /* DECL may contain more parameters than TMPL due to the extra
2141              in-charge parameter in constructors and destructors.  */
2142           in_charge = spec_types;
2143           spec_types = TREE_CHAIN (spec_types);
2144         }
2145       if (DECL_HAS_VTT_PARM_P (decl))
2146         {
2147           vtt = spec_types;
2148           spec_types = TREE_CHAIN (spec_types);
2149         }
2150     }
2151
2152   /* Compute the merged default arguments.  */
2153   new_spec_types =
2154     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2155
2156   /* Compute the new FUNCTION_TYPE.  */
2157   if (object_type)
2158     {
2159       if (vtt)
2160         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2161                                          TREE_VALUE (vtt),
2162                                          new_spec_types);
2163
2164       if (in_charge)
2165         /* Put the in-charge parameter back.  */
2166         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2167                                          TREE_VALUE (in_charge),
2168                                          new_spec_types);
2169
2170       new_type = build_method_type_directly (object_type,
2171                                              TREE_TYPE (old_type),
2172                                              new_spec_types);
2173     }
2174   else
2175     new_type = build_function_type (TREE_TYPE (old_type),
2176                                     new_spec_types);
2177   new_type = cp_build_type_attribute_variant (new_type,
2178                                               TYPE_ATTRIBUTES (old_type));
2179   new_type = build_exception_variant (new_type,
2180                                       TYPE_RAISES_EXCEPTIONS (old_type));
2181   TREE_TYPE (decl) = new_type;
2182 }
2183
2184 /* Check to see if the function just declared, as indicated in
2185    DECLARATOR, and in DECL, is a specialization of a function
2186    template.  We may also discover that the declaration is an explicit
2187    instantiation at this point.
2188
2189    Returns DECL, or an equivalent declaration that should be used
2190    instead if all goes well.  Issues an error message if something is
2191    amiss.  Returns error_mark_node if the error is not easily
2192    recoverable.
2193
2194    FLAGS is a bitmask consisting of the following flags:
2195
2196    2: The function has a definition.
2197    4: The function is a friend.
2198
2199    The TEMPLATE_COUNT is the number of references to qualifying
2200    template classes that appeared in the name of the function.  For
2201    example, in
2202
2203      template <class T> struct S { void f(); };
2204      void S<int>::f();
2205
2206    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2207    classes are not counted in the TEMPLATE_COUNT, so that in
2208
2209      template <class T> struct S {};
2210      template <> struct S<int> { void f(); }
2211      template <> void S<int>::f();
2212
2213    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2214    invalid; there should be no template <>.)
2215
2216    If the function is a specialization, it is marked as such via
2217    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2218    is set up correctly, and it is added to the list of specializations
2219    for that template.  */
2220
2221 tree
2222 check_explicit_specialization (tree declarator,
2223                                tree decl,
2224                                int template_count,
2225                                int flags)
2226 {
2227   int have_def = flags & 2;
2228   int is_friend = flags & 4;
2229   int specialization = 0;
2230   int explicit_instantiation = 0;
2231   int member_specialization = 0;
2232   tree ctype = DECL_CLASS_CONTEXT (decl);
2233   tree dname = DECL_NAME (decl);
2234   tmpl_spec_kind tsk;
2235
2236   if (is_friend)
2237     {
2238       if (!processing_specialization)
2239         tsk = tsk_none;
2240       else
2241         tsk = tsk_excessive_parms;
2242     }
2243   else
2244     tsk = current_tmpl_spec_kind (template_count);
2245
2246   switch (tsk)
2247     {
2248     case tsk_none:
2249       if (processing_specialization)
2250         {
2251           specialization = 1;
2252           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2253         }
2254       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2255         {
2256           if (is_friend)
2257             /* This could be something like:
2258
2259                template <class T> void f(T);
2260                class S { friend void f<>(int); }  */
2261             specialization = 1;
2262           else
2263             {
2264               /* This case handles bogus declarations like template <>
2265                  template <class T> void f<int>(); */
2266
2267               error ("template-id %qD in declaration of primary template",
2268                      declarator);
2269               return decl;
2270             }
2271         }
2272       break;
2273
2274     case tsk_invalid_member_spec:
2275       /* The error has already been reported in
2276          check_specialization_scope.  */
2277       return error_mark_node;
2278
2279     case tsk_invalid_expl_inst:
2280       error ("template parameter list used in explicit instantiation");
2281
2282       /* Fall through.  */
2283
2284     case tsk_expl_inst:
2285       if (have_def)
2286         error ("definition provided for explicit instantiation");
2287
2288       explicit_instantiation = 1;
2289       break;
2290
2291     case tsk_excessive_parms:
2292     case tsk_insufficient_parms:
2293       if (tsk == tsk_excessive_parms)
2294         error ("too many template parameter lists in declaration of %qD",
2295                decl);
2296       else if (template_header_count)
2297         error("too few template parameter lists in declaration of %qD", decl);
2298       else
2299         error("explicit specialization of %qD must be introduced by "
2300               "%<template <>%>", decl);
2301
2302       /* Fall through.  */
2303     case tsk_expl_spec:
2304       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2305       if (ctype)
2306         member_specialization = 1;
2307       else
2308         specialization = 1;
2309       break;
2310
2311     case tsk_template:
2312       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2313         {
2314           /* This case handles bogus declarations like template <>
2315              template <class T> void f<int>(); */
2316
2317           if (uses_template_parms (declarator))
2318             error ("function template partial specialization %qD "
2319                    "is not allowed", declarator);
2320           else
2321             error ("template-id %qD in declaration of primary template",
2322                    declarator);
2323           return decl;
2324         }
2325
2326       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2327         /* This is a specialization of a member template, without
2328            specialization the containing class.  Something like:
2329
2330              template <class T> struct S {
2331                template <class U> void f (U);
2332              };
2333              template <> template <class U> void S<int>::f(U) {}
2334
2335            That's a specialization -- but of the entire template.  */
2336         specialization = 1;
2337       break;
2338
2339     default:
2340       gcc_unreachable ();
2341     }
2342
2343   if (specialization || member_specialization)
2344     {
2345       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2346       for (; t; t = TREE_CHAIN (t))
2347         if (TREE_PURPOSE (t))
2348           {
2349             permerror (input_location, 
2350                        "default argument specified in explicit specialization");
2351             break;
2352           }
2353     }
2354
2355   if (specialization || member_specialization || explicit_instantiation)
2356     {
2357       tree tmpl = NULL_TREE;
2358       tree targs = NULL_TREE;
2359
2360       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2361       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2362         {
2363           tree fns;
2364
2365           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2366           if (ctype)
2367             fns = dname;
2368           else
2369             {
2370               /* If there is no class context, the explicit instantiation
2371                  must be at namespace scope.  */
2372               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2373
2374               /* Find the namespace binding, using the declaration
2375                  context.  */
2376               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2377                                            false, true);
2378               if (fns == error_mark_node || !is_overloaded_fn (fns))
2379                 {
2380                   error ("%qD is not a template function", dname);
2381                   fns = error_mark_node;
2382                 }
2383               else
2384                 {
2385                   tree fn = OVL_CURRENT (fns);
2386                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2387                                                 CP_DECL_CONTEXT (fn)))
2388                     error ("%qD is not declared in %qD",
2389                            decl, current_namespace);
2390                 }
2391             }
2392
2393           declarator = lookup_template_function (fns, NULL_TREE);
2394         }
2395
2396       if (declarator == error_mark_node)
2397         return error_mark_node;
2398
2399       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2400         {
2401           if (!explicit_instantiation)
2402             /* A specialization in class scope.  This is invalid,
2403                but the error will already have been flagged by
2404                check_specialization_scope.  */
2405             return error_mark_node;
2406           else
2407             {
2408               /* It's not valid to write an explicit instantiation in
2409                  class scope, e.g.:
2410
2411                    class C { template void f(); }
2412
2413                    This case is caught by the parser.  However, on
2414                    something like:
2415
2416                    template class C { void f(); };
2417
2418                    (which is invalid) we can get here.  The error will be
2419                    issued later.  */
2420               ;
2421             }
2422
2423           return decl;
2424         }
2425       else if (ctype != NULL_TREE
2426                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2427                    IDENTIFIER_NODE))
2428         {
2429           /* Find the list of functions in ctype that have the same
2430              name as the declared function.  */
2431           tree name = TREE_OPERAND (declarator, 0);
2432           tree fns = NULL_TREE;
2433           int idx;
2434
2435           if (constructor_name_p (name, ctype))
2436             {
2437               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2438
2439               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2440                   : !CLASSTYPE_DESTRUCTORS (ctype))
2441                 {
2442                   /* From [temp.expl.spec]:
2443
2444                      If such an explicit specialization for the member
2445                      of a class template names an implicitly-declared
2446                      special member function (clause _special_), the
2447                      program is ill-formed.
2448
2449                      Similar language is found in [temp.explicit].  */
2450                   error ("specialization of implicitly-declared special member function");
2451                   return error_mark_node;
2452                 }
2453
2454               name = is_constructor ? ctor_identifier : dtor_identifier;
2455             }
2456
2457           if (!DECL_CONV_FN_P (decl))
2458             {
2459               idx = lookup_fnfields_1 (ctype, name);
2460               if (idx >= 0)
2461                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2462             }
2463           else
2464             {
2465               VEC(tree,gc) *methods;
2466               tree ovl;
2467
2468               /* For a type-conversion operator, we cannot do a
2469                  name-based lookup.  We might be looking for `operator
2470                  int' which will be a specialization of `operator T'.
2471                  So, we find *all* the conversion operators, and then
2472                  select from them.  */
2473               fns = NULL_TREE;
2474
2475               methods = CLASSTYPE_METHOD_VEC (ctype);
2476               if (methods)
2477                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2478                      VEC_iterate (tree, methods, idx, ovl);
2479                      ++idx)
2480                   {
2481                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2482                       /* There are no more conversion functions.  */
2483                       break;
2484
2485                     /* Glue all these conversion functions together
2486                        with those we already have.  */
2487                     for (; ovl; ovl = OVL_NEXT (ovl))
2488                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2489                   }
2490             }
2491
2492           if (fns == NULL_TREE)
2493             {
2494               error ("no member function %qD declared in %qT", name, ctype);
2495               return error_mark_node;
2496             }
2497           else
2498             TREE_OPERAND (declarator, 0) = fns;
2499         }
2500
2501       /* Figure out what exactly is being specialized at this point.
2502          Note that for an explicit instantiation, even one for a
2503          member function, we cannot tell apriori whether the
2504          instantiation is for a member template, or just a member
2505          function of a template class.  Even if a member template is
2506          being instantiated, the member template arguments may be
2507          elided if they can be deduced from the rest of the
2508          declaration.  */
2509       tmpl = determine_specialization (declarator, decl,
2510                                        &targs,
2511                                        member_specialization,
2512                                        template_count,
2513                                        tsk);
2514
2515       if (!tmpl || tmpl == error_mark_node)
2516         /* We couldn't figure out what this declaration was
2517            specializing.  */
2518         return error_mark_node;
2519       else
2520         {
2521           tree gen_tmpl = most_general_template (tmpl);
2522
2523           if (explicit_instantiation)
2524             {
2525               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2526                  is done by do_decl_instantiation later.  */
2527
2528               int arg_depth = TMPL_ARGS_DEPTH (targs);
2529               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2530
2531               if (arg_depth > parm_depth)
2532                 {
2533                   /* If TMPL is not the most general template (for
2534                      example, if TMPL is a friend template that is
2535                      injected into namespace scope), then there will
2536                      be too many levels of TARGS.  Remove some of them
2537                      here.  */
2538                   int i;
2539                   tree new_targs;
2540
2541                   new_targs = make_tree_vec (parm_depth);
2542                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2543                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2544                       = TREE_VEC_ELT (targs, i);
2545                   targs = new_targs;
2546                 }
2547
2548               return instantiate_template (tmpl, targs, tf_error);
2549             }
2550
2551           /* If we thought that the DECL was a member function, but it
2552              turns out to be specializing a static member function,
2553              make DECL a static member function as well.  */
2554           if (DECL_STATIC_FUNCTION_P (tmpl)
2555               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2556             revert_static_member_fn (decl);
2557
2558           /* If this is a specialization of a member template of a
2559              template class, we want to return the TEMPLATE_DECL, not
2560              the specialization of it.  */
2561           if (tsk == tsk_template)
2562             {
2563               tree result = DECL_TEMPLATE_RESULT (tmpl);
2564               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2565               DECL_INITIAL (result) = NULL_TREE;
2566               if (have_def)
2567                 {
2568                   tree parm;
2569                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2570                   DECL_SOURCE_LOCATION (result)
2571                     = DECL_SOURCE_LOCATION (decl);
2572                   /* We want to use the argument list specified in the
2573                      definition, not in the original declaration.  */
2574                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2575                   for (parm = DECL_ARGUMENTS (result); parm;
2576                        parm = DECL_CHAIN (parm))
2577                     DECL_CONTEXT (parm) = result;
2578                 }
2579               return register_specialization (tmpl, gen_tmpl, targs,
2580                                               is_friend, 0);
2581             }
2582
2583           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2584           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2585
2586           /* Inherit default function arguments from the template
2587              DECL is specializing.  */
2588           copy_default_args_to_explicit_spec (decl);
2589
2590           /* This specialization has the same protection as the
2591              template it specializes.  */
2592           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2593           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2594
2595           /* 7.1.1-1 [dcl.stc]
2596
2597              A storage-class-specifier shall not be specified in an
2598              explicit specialization...
2599
2600              The parser rejects these, so unless action is taken here,
2601              explicit function specializations will always appear with
2602              global linkage.
2603
2604              The action recommended by the C++ CWG in response to C++
2605              defect report 605 is to make the storage class and linkage
2606              of the explicit specialization match the templated function:
2607
2608              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2609            */
2610           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2611             {
2612               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2613               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2614
2615               /* This specialization has the same linkage and visibility as
2616                  the function template it specializes.  */
2617               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2618               if (! TREE_PUBLIC (decl))
2619                 {
2620                   DECL_INTERFACE_KNOWN (decl) = 1;
2621                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2622                 }
2623               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2624               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2625                 {
2626                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2627                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2628                 }
2629             }
2630
2631           /* If DECL is a friend declaration, declared using an
2632              unqualified name, the namespace associated with DECL may
2633              have been set incorrectly.  For example, in:
2634
2635                template <typename T> void f(T);
2636                namespace N {
2637                  struct S { friend void f<int>(int); }
2638                }
2639
2640              we will have set the DECL_CONTEXT for the friend
2641              declaration to N, rather than to the global namespace.  */
2642           if (DECL_NAMESPACE_SCOPE_P (decl))
2643             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2644
2645           if (is_friend && !have_def)
2646             /* This is not really a declaration of a specialization.
2647                It's just the name of an instantiation.  But, it's not
2648                a request for an instantiation, either.  */
2649             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2650           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2651             /* This is indeed a specialization.  In case of constructors
2652                and destructors, we need in-charge and not-in-charge
2653                versions in V3 ABI.  */
2654             clone_function_decl (decl, /*update_method_vec_p=*/0);
2655
2656           /* Register this specialization so that we can find it
2657              again.  */
2658           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2659         }
2660     }
2661
2662   return decl;
2663 }
2664
2665 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2666    parameters.  These are represented in the same format used for
2667    DECL_TEMPLATE_PARMS.  */
2668
2669 int
2670 comp_template_parms (const_tree parms1, const_tree parms2)
2671 {
2672   const_tree p1;
2673   const_tree p2;
2674
2675   if (parms1 == parms2)
2676     return 1;
2677
2678   for (p1 = parms1, p2 = parms2;
2679        p1 != NULL_TREE && p2 != NULL_TREE;
2680        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2681     {
2682       tree t1 = TREE_VALUE (p1);
2683       tree t2 = TREE_VALUE (p2);
2684       int i;
2685
2686       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2687       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2688
2689       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2690         return 0;
2691
2692       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2693         {
2694           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2695           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2696
2697           /* If either of the template parameters are invalid, assume
2698              they match for the sake of error recovery. */
2699           if (parm1 == error_mark_node || parm2 == error_mark_node)
2700             return 1;
2701
2702           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2703             return 0;
2704
2705           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2706               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2707                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2708             continue;
2709           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2710             return 0;
2711         }
2712     }
2713
2714   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2715     /* One set of parameters has more parameters lists than the
2716        other.  */
2717     return 0;
2718
2719   return 1;
2720 }
2721
2722 /* Determine whether PARM is a parameter pack.  */
2723
2724 bool 
2725 template_parameter_pack_p (const_tree parm)
2726 {
2727   /* Determine if we have a non-type template parameter pack.  */
2728   if (TREE_CODE (parm) == PARM_DECL)
2729     return (DECL_TEMPLATE_PARM_P (parm) 
2730             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2731
2732   /* If this is a list of template parameters, we could get a
2733      TYPE_DECL or a TEMPLATE_DECL.  */ 
2734   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2735     parm = TREE_TYPE (parm);
2736
2737   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2738            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2739           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2740 }
2741
2742 /* Determine if T is a function parameter pack.  */
2743
2744 bool
2745 function_parameter_pack_p (const_tree t)
2746 {
2747   if (t && TREE_CODE (t) == PARM_DECL)
2748     return FUNCTION_PARAMETER_PACK_P (t);
2749   return false;
2750 }
2751
2752 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2753    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2754
2755 tree
2756 get_function_template_decl (const_tree primary_func_tmpl_inst)
2757 {
2758   if (! primary_func_tmpl_inst
2759       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2760       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2761     return NULL;
2762
2763   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2764 }
2765
2766 /* Return true iff the function parameter PARAM_DECL was expanded
2767    from the function parameter pack PACK.  */
2768
2769 bool
2770 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2771 {
2772   if (DECL_ARTIFICIAL (param_decl)
2773       || !function_parameter_pack_p (pack))
2774     return false;
2775
2776   /* The parameter pack and its pack arguments have the same
2777      DECL_PARM_INDEX.  */
2778   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2779 }
2780
2781 /* Determine whether ARGS describes a variadic template args list,
2782    i.e., one that is terminated by a template argument pack.  */
2783
2784 static bool 
2785 template_args_variadic_p (tree args)
2786 {
2787   int nargs;
2788   tree last_parm;
2789
2790   if (args == NULL_TREE)
2791     return false;
2792
2793   args = INNERMOST_TEMPLATE_ARGS (args);
2794   nargs = TREE_VEC_LENGTH (args);
2795
2796   if (nargs == 0)
2797     return false;
2798
2799   last_parm = TREE_VEC_ELT (args, nargs - 1);
2800
2801   return ARGUMENT_PACK_P (last_parm);
2802 }
2803
2804 /* Generate a new name for the parameter pack name NAME (an
2805    IDENTIFIER_NODE) that incorporates its */
2806
2807 static tree
2808 make_ith_pack_parameter_name (tree name, int i)
2809 {
2810   /* Munge the name to include the parameter index.  */
2811 #define NUMBUF_LEN 128
2812   char numbuf[NUMBUF_LEN];
2813   char* newname;
2814   int newname_len;
2815
2816   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2817   newname_len = IDENTIFIER_LENGTH (name)
2818                 + strlen (numbuf) + 2;
2819   newname = (char*)alloca (newname_len);
2820   snprintf (newname, newname_len,
2821             "%s#%i", IDENTIFIER_POINTER (name), i);
2822   return get_identifier (newname);
2823 }
2824
2825 /* Return true if T is a primary function
2826    or class template instantiation.  */
2827
2828 bool
2829 primary_template_instantiation_p (const_tree t)
2830 {
2831   if (!t)
2832     return false;
2833
2834   if (TREE_CODE (t) == FUNCTION_DECL)
2835     return DECL_LANG_SPECIFIC (t)
2836            && DECL_TEMPLATE_INSTANTIATION (t)
2837            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2838   else if (CLASS_TYPE_P (t))
2839     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2840            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2841   return false;
2842 }
2843
2844 /* Return true if PARM is a template template parameter.  */
2845
2846 bool
2847 template_template_parameter_p (const_tree parm)
2848 {
2849   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2850 }
2851
2852 /* Return the template parameters of T if T is a
2853    primary template instantiation, NULL otherwise.  */
2854
2855 tree
2856 get_primary_template_innermost_parameters (const_tree t)
2857 {
2858   tree parms = NULL, template_info = NULL;
2859
2860   if ((template_info = get_template_info (t))
2861       && primary_template_instantiation_p (t))
2862     parms = INNERMOST_TEMPLATE_PARMS
2863         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2864
2865   return parms;
2866 }
2867
2868 /* Return the template parameters of the LEVELth level from the full list
2869    of template parameters PARMS.  */
2870
2871 tree
2872 get_template_parms_at_level (tree parms, int level)
2873 {
2874   tree p;
2875   if (!parms
2876       || TREE_CODE (parms) != TREE_LIST
2877       || level > TMPL_PARMS_DEPTH (parms))
2878     return NULL_TREE;
2879
2880   for (p = parms; p; p = TREE_CHAIN (p))
2881     if (TMPL_PARMS_DEPTH (p) == level)
2882       return p;
2883
2884   return NULL_TREE;
2885 }
2886
2887 /* Returns the template arguments of T if T is a template instantiation,
2888    NULL otherwise.  */
2889
2890 tree
2891 get_template_innermost_arguments (const_tree t)
2892 {
2893   tree args = NULL, template_info = NULL;
2894
2895   if ((template_info = get_template_info (t))
2896       && TI_ARGS (template_info))
2897     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2898
2899   return args;
2900 }
2901
2902 /* Return the argument pack elements of T if T is a template argument pack,
2903    NULL otherwise.  */
2904
2905 tree
2906 get_template_argument_pack_elems (const_tree t)
2907 {
2908   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2909       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2910     return NULL;
2911
2912   return ARGUMENT_PACK_ARGS (t);
2913 }
2914
2915 /* Structure used to track the progress of find_parameter_packs_r.  */
2916 struct find_parameter_pack_data 
2917 {
2918   /* TREE_LIST that will contain all of the parameter packs found by
2919      the traversal.  */
2920   tree* parameter_packs;
2921
2922   /* Set of AST nodes that have been visited by the traversal.  */
2923   struct pointer_set_t *visited;
2924 };
2925
2926 /* Identifies all of the argument packs that occur in a template
2927    argument and appends them to the TREE_LIST inside DATA, which is a
2928    find_parameter_pack_data structure. This is a subroutine of
2929    make_pack_expansion and uses_parameter_packs.  */
2930 static tree
2931 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2932 {
2933   tree t = *tp;
2934   struct find_parameter_pack_data* ppd = 
2935     (struct find_parameter_pack_data*)data;
2936   bool parameter_pack_p = false;
2937
2938   /* Identify whether this is a parameter pack or not.  */
2939   switch (TREE_CODE (t))
2940     {
2941     case TEMPLATE_PARM_INDEX:
2942       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2943         parameter_pack_p = true;
2944       break;
2945
2946     case TEMPLATE_TYPE_PARM:
2947     case TEMPLATE_TEMPLATE_PARM:
2948       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2949         parameter_pack_p = true;
2950       break;
2951
2952     case PARM_DECL:
2953       if (FUNCTION_PARAMETER_PACK_P (t))
2954         {
2955           /* We don't want to walk into the type of a PARM_DECL,
2956              because we don't want to see the type parameter pack.  */
2957           *walk_subtrees = 0;
2958           parameter_pack_p = true;
2959         }
2960       break;
2961
2962     default:
2963       /* Not a parameter pack.  */
2964       break;
2965     }
2966
2967   if (parameter_pack_p)
2968     {
2969       /* Add this parameter pack to the list.  */
2970       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2971     }
2972
2973   if (TYPE_P (t))
2974     cp_walk_tree (&TYPE_CONTEXT (t), 
2975                   &find_parameter_packs_r, ppd, ppd->visited);
2976
2977   /* This switch statement will return immediately if we don't find a
2978      parameter pack.  */
2979   switch (TREE_CODE (t)) 
2980     {
2981     case TEMPLATE_PARM_INDEX:
2982       return NULL_TREE;
2983
2984     case BOUND_TEMPLATE_TEMPLATE_PARM:
2985       /* Check the template itself.  */
2986       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2987                     &find_parameter_packs_r, ppd, ppd->visited);
2988       /* Check the template arguments.  */
2989       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2990                     ppd->visited);
2991       *walk_subtrees = 0;
2992       return NULL_TREE;
2993
2994     case TEMPLATE_TYPE_PARM:
2995     case TEMPLATE_TEMPLATE_PARM:
2996       return NULL_TREE;
2997
2998     case PARM_DECL:
2999       return NULL_TREE;
3000
3001     case RECORD_TYPE:
3002       if (TYPE_PTRMEMFUNC_P (t))
3003         return NULL_TREE;
3004       /* Fall through.  */
3005
3006     case UNION_TYPE:
3007     case ENUMERAL_TYPE:
3008       if (TYPE_TEMPLATE_INFO (t))
3009         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3010                       &find_parameter_packs_r, ppd, ppd->visited);
3011
3012       *walk_subtrees = 0;
3013       return NULL_TREE;
3014
3015     case TEMPLATE_DECL:
3016       cp_walk_tree (&TREE_TYPE (t),
3017                     &find_parameter_packs_r, ppd, ppd->visited);
3018       return NULL_TREE;
3019  
3020     case TYPENAME_TYPE:
3021       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3022                    ppd, ppd->visited);
3023       *walk_subtrees = 0;
3024       return NULL_TREE;
3025       
3026     case TYPE_PACK_EXPANSION:
3027     case EXPR_PACK_EXPANSION:
3028       *walk_subtrees = 0;
3029       return NULL_TREE;
3030
3031     case INTEGER_TYPE:
3032       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3033                     ppd, ppd->visited);
3034       *walk_subtrees = 0;
3035       return NULL_TREE;
3036
3037     case IDENTIFIER_NODE:
3038       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3039                     ppd->visited);
3040       *walk_subtrees = 0;
3041       return NULL_TREE;
3042
3043     default:
3044       return NULL_TREE;
3045     }
3046
3047   return NULL_TREE;
3048 }
3049
3050 /* Determines if the expression or type T uses any parameter packs.  */
3051 bool
3052 uses_parameter_packs (tree t)
3053 {
3054   tree parameter_packs = NULL_TREE;
3055   struct find_parameter_pack_data ppd;
3056   ppd.parameter_packs = &parameter_packs;
3057   ppd.visited = pointer_set_create ();
3058   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3059   pointer_set_destroy (ppd.visited);
3060   return parameter_packs != NULL_TREE;
3061 }
3062
3063 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3064    representation a base-class initializer into a parameter pack
3065    expansion. If all goes well, the resulting node will be an
3066    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3067    respectively.  */
3068 tree 
3069 make_pack_expansion (tree arg)
3070 {
3071   tree result;
3072   tree parameter_packs = NULL_TREE;
3073   bool for_types = false;
3074   struct find_parameter_pack_data ppd;
3075
3076   if (!arg || arg == error_mark_node)
3077     return arg;
3078
3079   if (TREE_CODE (arg) == TREE_LIST)
3080     {
3081       /* The only time we will see a TREE_LIST here is for a base
3082          class initializer.  In this case, the TREE_PURPOSE will be a
3083          _TYPE node (representing the base class expansion we're
3084          initializing) and the TREE_VALUE will be a TREE_LIST
3085          containing the initialization arguments. 
3086
3087          The resulting expansion looks somewhat different from most
3088          expansions. Rather than returning just one _EXPANSION, we
3089          return a TREE_LIST whose TREE_PURPOSE is a
3090          TYPE_PACK_EXPANSION containing the bases that will be
3091          initialized.  The TREE_VALUE will be identical to the
3092          original TREE_VALUE, which is a list of arguments that will
3093          be passed to each base.  We do not introduce any new pack
3094          expansion nodes into the TREE_VALUE (although it is possible
3095          that some already exist), because the TREE_PURPOSE and
3096          TREE_VALUE all need to be expanded together with the same
3097          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3098          resulting TREE_PURPOSE will mention the parameter packs in
3099          both the bases and the arguments to the bases.  */
3100       tree purpose;
3101       tree value;
3102       tree parameter_packs = NULL_TREE;
3103
3104       /* Determine which parameter packs will be used by the base
3105          class expansion.  */
3106       ppd.visited = pointer_set_create ();
3107       ppd.parameter_packs = &parameter_packs;
3108       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3109                     &ppd, ppd.visited);
3110
3111       if (parameter_packs == NULL_TREE)
3112         {
3113           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3114           pointer_set_destroy (ppd.visited);
3115           return error_mark_node;
3116         }
3117
3118       if (TREE_VALUE (arg) != void_type_node)
3119         {
3120           /* Collect the sets of parameter packs used in each of the
3121              initialization arguments.  */
3122           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3123             {
3124               /* Determine which parameter packs will be expanded in this
3125                  argument.  */
3126               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3127                             &ppd, ppd.visited);
3128             }
3129         }
3130
3131       pointer_set_destroy (ppd.visited);
3132
3133       /* Create the pack expansion type for the base type.  */
3134       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3135       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3136       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3137
3138       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3139          they will rarely be compared to anything.  */
3140       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3141
3142       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3143     }
3144
3145   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3146     for_types = true;
3147
3148   /* Build the PACK_EXPANSION_* node.  */
3149   result = for_types
3150      ? cxx_make_type (TYPE_PACK_EXPANSION)
3151      : make_node (EXPR_PACK_EXPANSION);
3152   SET_PACK_EXPANSION_PATTERN (result, arg);
3153   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3154     {
3155       /* Propagate type and const-expression information.  */
3156       TREE_TYPE (result) = TREE_TYPE (arg);
3157       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3158     }
3159   else
3160     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3161        they will rarely be compared to anything.  */
3162     SET_TYPE_STRUCTURAL_EQUALITY (result);
3163
3164   /* Determine which parameter packs will be expanded.  */
3165   ppd.parameter_packs = &parameter_packs;
3166   ppd.visited = pointer_set_create ();
3167   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3168   pointer_set_destroy (ppd.visited);
3169
3170   /* Make sure we found some parameter packs.  */
3171   if (parameter_packs == NULL_TREE)
3172     {
3173       if (TYPE_P (arg))
3174         error ("expansion pattern %<%T%> contains no argument packs", arg);
3175       else
3176         error ("expansion pattern %<%E%> contains no argument packs", arg);
3177       return error_mark_node;
3178     }
3179   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3180
3181   return result;
3182 }
3183
3184 /* Checks T for any "bare" parameter packs, which have not yet been
3185    expanded, and issues an error if any are found. This operation can
3186    only be done on full expressions or types (e.g., an expression
3187    statement, "if" condition, etc.), because we could have expressions like:
3188
3189      foo(f(g(h(args)))...)
3190
3191    where "args" is a parameter pack. check_for_bare_parameter_packs
3192    should not be called for the subexpressions args, h(args),
3193    g(h(args)), or f(g(h(args))), because we would produce erroneous
3194    error messages. 
3195
3196    Returns TRUE and emits an error if there were bare parameter packs,
3197    returns FALSE otherwise.  */
3198 bool 
3199 check_for_bare_parameter_packs (tree t)
3200 {
3201   tree parameter_packs = NULL_TREE;
3202   struct find_parameter_pack_data ppd;
3203
3204   if (!processing_template_decl || !t || t == error_mark_node)
3205     return false;
3206
3207   if (TREE_CODE (t) == TYPE_DECL)
3208     t = TREE_TYPE (t);
3209
3210   ppd.parameter_packs = &parameter_packs;
3211   ppd.visited = pointer_set_create ();
3212   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3213   pointer_set_destroy (ppd.visited);
3214
3215   if (parameter_packs) 
3216     {
3217       error ("parameter packs not expanded with %<...%>:");
3218       while (parameter_packs)
3219         {
3220           tree pack = TREE_VALUE (parameter_packs);
3221           tree name = NULL_TREE;
3222
3223           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3224               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3225             name = TYPE_NAME (pack);
3226           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3227             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3228           else
3229             name = DECL_NAME (pack);
3230
3231           if (name)
3232             inform (input_location, "        %qD", name);
3233           else
3234             inform (input_location, "        <anonymous>");
3235
3236           parameter_packs = TREE_CHAIN (parameter_packs);
3237         }
3238
3239       return true;
3240     }
3241
3242   return false;
3243 }
3244
3245 /* Expand any parameter packs that occur in the template arguments in
3246    ARGS.  */
3247 tree
3248 expand_template_argument_pack (tree args)
3249 {
3250   tree result_args = NULL_TREE;
3251   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3252   int num_result_args = -1;
3253   int non_default_args_count = -1;
3254
3255   /* First, determine if we need to expand anything, and the number of
3256      slots we'll need.  */
3257   for (in_arg = 0; in_arg < nargs; ++in_arg)
3258     {
3259       tree arg = TREE_VEC_ELT (args, in_arg);
3260       if (arg == NULL_TREE)
3261         return args;
3262       if (ARGUMENT_PACK_P (arg))
3263         {
3264           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3265           if (num_result_args < 0)
3266             num_result_args = in_arg + num_packed;
3267           else
3268             num_result_args += num_packed;
3269         }
3270       else
3271         {
3272           if (num_result_args >= 0)
3273             num_result_args++;
3274         }
3275     }
3276
3277   /* If no expansion is necessary, we're done.  */
3278   if (num_result_args < 0)
3279     return args;
3280
3281   /* Expand arguments.  */
3282   result_args = make_tree_vec (num_result_args);
3283   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3284     non_default_args_count =
3285       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3286   for (in_arg = 0; in_arg < nargs; ++in_arg)
3287     {
3288       tree arg = TREE_VEC_ELT (args, in_arg);
3289       if (ARGUMENT_PACK_P (arg))
3290         {
3291           tree packed = ARGUMENT_PACK_ARGS (arg);
3292           int i, num_packed = TREE_VEC_LENGTH (packed);
3293           for (i = 0; i < num_packed; ++i, ++out_arg)
3294             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3295           if (non_default_args_count > 0)
3296             non_default_args_count += num_packed;
3297         }
3298       else
3299         {
3300           TREE_VEC_ELT (result_args, out_arg) = arg;
3301           ++out_arg;
3302         }
3303     }
3304   if (non_default_args_count >= 0)
3305     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3306   return result_args;
3307 }
3308
3309 /* Checks if DECL shadows a template parameter.
3310
3311    [temp.local]: A template-parameter shall not be redeclared within its
3312    scope (including nested scopes).
3313
3314    Emits an error and returns TRUE if the DECL shadows a parameter,
3315    returns FALSE otherwise.  */
3316
3317 bool
3318 check_template_shadow (tree decl)
3319 {
3320   tree olddecl;
3321
3322   /* If we're not in a template, we can't possibly shadow a template
3323      parameter.  */
3324   if (!current_template_parms)
3325     return true;
3326
3327   /* Figure out what we're shadowing.  */
3328   if (TREE_CODE (decl) == OVERLOAD)
3329     decl = OVL_CURRENT (decl);
3330   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3331
3332   /* If there's no previous binding for this name, we're not shadowing
3333      anything, let alone a template parameter.  */
3334   if (!olddecl)
3335     return true;
3336
3337   /* If we're not shadowing a template parameter, we're done.  Note
3338      that OLDDECL might be an OVERLOAD (or perhaps even an
3339      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3340      node.  */
3341   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3342     return true;
3343
3344   /* We check for decl != olddecl to avoid bogus errors for using a
3345      name inside a class.  We check TPFI to avoid duplicate errors for
3346      inline member templates.  */
3347   if (decl == olddecl
3348       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3349     return true;
3350
3351   error ("declaration of %q+#D", decl);
3352   error (" shadows template parm %q+#D", olddecl);
3353   return false;
3354 }
3355
3356 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3357    ORIG_LEVEL, DECL, and TYPE.  */
3358
3359 static tree
3360 build_template_parm_index (int index,
3361                            int level,
3362                            int orig_level,
3363                            tree decl,
3364                            tree type)
3365 {
3366   tree t = make_node (TEMPLATE_PARM_INDEX);
3367   TEMPLATE_PARM_IDX (t) = index;
3368   TEMPLATE_PARM_LEVEL (t) = level;
3369   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3370   TEMPLATE_PARM_DECL (t) = decl;
3371   TREE_TYPE (t) = type;
3372   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3373   TREE_READONLY (t) = TREE_READONLY (decl);
3374
3375   return t;
3376 }
3377
3378 /* Find the canonical type parameter for the given template type
3379    parameter.  Returns the canonical type parameter, which may be TYPE
3380    if no such parameter existed.  */
3381 static tree
3382 canonical_type_parameter (tree type)
3383 {
3384   tree list;
3385   int idx = TEMPLATE_TYPE_IDX (type);
3386   if (!canonical_template_parms)
3387     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3388
3389   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3390     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3391
3392   list = VEC_index (tree, canonical_template_parms, idx);
3393   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3394     list = TREE_CHAIN (list);
3395
3396   if (list)
3397     return TREE_VALUE (list);
3398   else
3399     {
3400       VEC_replace(tree, canonical_template_parms, idx,
3401                   tree_cons (NULL_TREE, type, 
3402                              VEC_index (tree, canonical_template_parms, idx)));
3403       return type;
3404     }
3405 }
3406
3407 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3408    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3409    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3410    new one is created.  */
3411
3412 static tree
3413 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3414                             tsubst_flags_t complain)
3415 {
3416   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3417       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3418           != TEMPLATE_PARM_LEVEL (index) - levels)
3419       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3420     {
3421       tree orig_decl = TEMPLATE_PARM_DECL (index);
3422       tree decl, t;
3423
3424       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3425                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3426       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3427       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3428       DECL_ARTIFICIAL (decl) = 1;
3429       SET_DECL_TEMPLATE_PARM_P (decl);
3430
3431       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3432                                      TEMPLATE_PARM_LEVEL (index) - levels,
3433                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3434                                      decl, type);
3435       TEMPLATE_PARM_DESCENDANTS (index) = t;
3436       TEMPLATE_PARM_PARAMETER_PACK (t) 
3437         = TEMPLATE_PARM_PARAMETER_PACK (index);
3438
3439         /* Template template parameters need this.  */
3440       if (TREE_CODE (decl) == TEMPLATE_DECL)
3441         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3442           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3443            args, complain);
3444     }
3445
3446   return TEMPLATE_PARM_DESCENDANTS (index);
3447 }
3448
3449 /* Process information from new template parameter PARM and append it to the
3450    LIST being built.  This new parameter is a non-type parameter iff
3451    IS_NON_TYPE is true. This new parameter is a parameter
3452    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3453    PARM_LOC.  */
3454
3455 tree
3456 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3457                        bool is_parameter_pack)
3458 {
3459   tree decl = 0;
3460   tree defval;
3461   tree err_parm_list;
3462   int idx = 0;
3463
3464   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3465   defval = TREE_PURPOSE (parm);
3466
3467   if (list)
3468     {
3469       tree p = tree_last (list);
3470
3471       if (p && TREE_VALUE (p) != error_mark_node)
3472         {
3473           p = TREE_VALUE (p);
3474           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3475             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3476           else
3477             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3478         }
3479
3480       ++idx;
3481     }
3482   else
3483     idx = 0;
3484
3485   if (is_non_type)
3486     {
3487       parm = TREE_VALUE (parm);
3488
3489       SET_DECL_TEMPLATE_PARM_P (parm);
3490
3491       if (TREE_TYPE (parm) == error_mark_node)
3492         {
3493           err_parm_list = build_tree_list (defval, parm);
3494           TREE_VALUE (err_parm_list) = error_mark_node;
3495            return chainon (list, err_parm_list);
3496         }
3497       else
3498       {
3499         /* [temp.param]
3500
3501            The top-level cv-qualifiers on the template-parameter are
3502            ignored when determining its type.  */
3503         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3504         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3505           {
3506             err_parm_list = build_tree_list (defval, parm);
3507             TREE_VALUE (err_parm_list) = error_mark_node;
3508              return chainon (list, err_parm_list);
3509           }
3510
3511         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3512           {
3513             /* This template parameter is not a parameter pack, but it
3514                should be. Complain about "bare" parameter packs.  */
3515             check_for_bare_parameter_packs (TREE_TYPE (parm));
3516             
3517             /* Recover by calling this a parameter pack.  */
3518             is_parameter_pack = true;
3519           }
3520       }
3521
3522       /* A template parameter is not modifiable.  */
3523       TREE_CONSTANT (parm) = 1;
3524       TREE_READONLY (parm) = 1;
3525       decl = build_decl (parm_loc,
3526                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3527       TREE_CONSTANT (decl) = 1;
3528       TREE_READONLY (decl) = 1;
3529       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3530         = build_template_parm_index (idx, processing_template_decl,
3531                                      processing_template_decl,
3532                                      decl, TREE_TYPE (parm));
3533
3534       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3535         = is_parameter_pack;
3536     }
3537   else
3538     {
3539       tree t;
3540       parm = TREE_VALUE (TREE_VALUE (parm));
3541
3542       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3543         {
3544           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3545           /* This is for distinguishing between real templates and template
3546              template parameters */
3547           TREE_TYPE (parm) = t;
3548           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3549           decl = parm;
3550         }
3551       else
3552         {
3553           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3554           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3555           decl = build_decl (parm_loc,
3556                              TYPE_DECL, parm, t);
3557         }
3558
3559       TYPE_NAME (t) = decl;
3560       TYPE_STUB_DECL (t) = decl;
3561       parm = decl;
3562       TEMPLATE_TYPE_PARM_INDEX (t)
3563         = build_template_parm_index (idx, processing_template_decl,
3564                                      processing_template_decl,
3565                                      decl, TREE_TYPE (parm));
3566       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3567       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3568     }
3569   DECL_ARTIFICIAL (decl) = 1;
3570   SET_DECL_TEMPLATE_PARM_P (decl);
3571   pushdecl (decl);
3572   parm = build_tree_list (defval, parm);
3573   return chainon (list, parm);
3574 }
3575
3576 /* The end of a template parameter list has been reached.  Process the
3577    tree list into a parameter vector, converting each parameter into a more
3578    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3579    as PARM_DECLs.  */
3580
3581 tree
3582 end_template_parm_list (tree parms)
3583 {
3584   int nparms;
3585   tree parm, next;
3586   tree saved_parmlist = make_tree_vec (list_length (parms));
3587
3588   current_template_parms
3589     = tree_cons (size_int (processing_template_decl),
3590                  saved_parmlist, current_template_parms);
3591
3592   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3593     {
3594       next = TREE_CHAIN (parm);
3595       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3596       TREE_CHAIN (parm) = NULL_TREE;
3597       if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL)
3598         TEMPLATE_TYPE_PARM_SIBLING_PARMS (TREE_TYPE (TREE_VALUE (parm))) =
3599               current_template_parms;
3600     }
3601
3602   --processing_template_parmlist;
3603
3604   return saved_parmlist;
3605 }
3606
3607 /* end_template_decl is called after a template declaration is seen.  */
3608
3609 void
3610 end_template_decl (void)
3611 {
3612   reset_specialization ();
3613
3614   if (! processing_template_decl)
3615     return;
3616
3617   /* This matches the pushlevel in begin_template_parm_list.  */
3618   finish_scope ();
3619
3620   --processing_template_decl;
3621   current_template_parms = TREE_CHAIN (current_template_parms);
3622 }
3623
3624 /* Within the declaration of a template, return all levels of template
3625    parameters that apply.  The template parameters are represented as
3626    a TREE_VEC, in the form documented in cp-tree.h for template
3627    arguments.  */
3628
3629 static tree
3630 current_template_args (void)
3631 {
3632   tree header;
3633   tree args = NULL_TREE;
3634   int length = TMPL_PARMS_DEPTH (current_template_parms);
3635   int l = length;
3636
3637   /* If there is only one level of template parameters, we do not
3638      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3639      TREE_VEC containing the arguments.  */
3640   if (length > 1)
3641     args = make_tree_vec (length);
3642
3643   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3644     {
3645       tree a = copy_node (TREE_VALUE (header));
3646       int i;
3647
3648       TREE_TYPE (a) = NULL_TREE;
3649       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3650         {
3651           tree t = TREE_VEC_ELT (a, i);
3652
3653           /* T will be a list if we are called from within a
3654              begin/end_template_parm_list pair, but a vector directly
3655              if within a begin/end_member_template_processing pair.  */
3656           if (TREE_CODE (t) == TREE_LIST)
3657             {
3658               t = TREE_VALUE (t);
3659
3660               if (!error_operand_p (t))
3661                 {
3662                   if (TREE_CODE (t) == TYPE_DECL
3663                       || TREE_CODE (t) == TEMPLATE_DECL)
3664                     {
3665                       t = TREE_TYPE (t);
3666                       
3667                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3668                         {
3669                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3670                              with a single element, which expands T.  */
3671                           tree vec = make_tree_vec (1);
3672 #ifdef ENABLE_CHECKING
3673                           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3674                                 (vec, TREE_VEC_LENGTH (vec));
3675 #endif
3676                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3677                           
3678                           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3679                           SET_ARGUMENT_PACK_ARGS (t, vec);
3680                         }
3681                     }
3682                   else
3683                     {
3684                       t = DECL_INITIAL (t);
3685                       
3686                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3687                         {
3688                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3689                              with a single element, which expands T.  */
3690                           tree vec = make_tree_vec (1);
3691                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3692 #ifdef ENABLE_CHECKING
3693                           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3694                                 (vec, TREE_VEC_LENGTH (vec));
3695 #endif
3696                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3697                           
3698                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3699                           SET_ARGUMENT_PACK_ARGS (t, vec);
3700                           TREE_TYPE (t) = type;
3701                         }
3702                     }
3703                   TREE_VEC_ELT (a, i) = t;
3704                 }
3705             }
3706         }
3707
3708 #ifdef ENABLE_CHECKING
3709       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
3710 #endif
3711
3712       if (length > 1)
3713         TREE_VEC_ELT (args, --l) = a;
3714       else
3715         args = a;
3716     }
3717
3718   return args;
3719 }
3720
3721 /* Update the declared TYPE by doing any lookups which were thought to be
3722    dependent, but are not now that we know the SCOPE of the declarator.  */
3723
3724 tree
3725 maybe_update_decl_type (tree orig_type, tree scope)
3726 {
3727   tree type = orig_type;
3728
3729   if (type == NULL_TREE)
3730     return type;
3731
3732   if (TREE_CODE (orig_type) == TYPE_DECL)
3733     type = TREE_TYPE (type);
3734
3735   if (scope && TYPE_P (scope) && dependent_type_p (scope)
3736       && dependent_type_p (type)
3737       /* Don't bother building up the args in this case.  */
3738       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
3739     {
3740       /* tsubst in the args corresponding to the template parameters,
3741          including auto if present.  Most things will be unchanged, but
3742          make_typename_type and tsubst_qualified_id will resolve
3743          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
3744       tree args = current_template_args ();
3745       tree auto_node = type_uses_auto (type);
3746       tree pushed;
3747       if (auto_node)
3748         {
3749           tree auto_vec = make_tree_vec (1);
3750           TREE_VEC_ELT (auto_vec, 0) = auto_node;
3751           args = add_to_template_args (args, auto_vec);
3752         }
3753       pushed = push_scope (scope);
3754       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
3755       if (pushed)
3756         pop_scope (scope);
3757     }
3758
3759   if (type == error_mark_node)
3760     return orig_type;
3761
3762   if (TREE_CODE (orig_type) == TYPE_DECL)
3763     {
3764       if (same_type_p (type, TREE_TYPE (orig_type)))
3765         type = orig_type;
3766       else
3767         type = TYPE_NAME (type);
3768     }
3769   return type;
3770 }
3771
3772 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3773    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3774    a member template.  Used by push_template_decl below.  */
3775
3776 static tree
3777 build_template_decl (tree decl, tree parms, bool member_template_p)
3778 {
3779   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3780   DECL_TEMPLATE_PARMS (tmpl) = parms;
3781   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3782   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3783
3784   return tmpl;
3785 }
3786
3787 struct template_parm_data
3788 {
3789   /* The level of the template parameters we are currently
3790      processing.  */
3791   int level;
3792
3793   /* The index of the specialization argument we are currently
3794      processing.  */
3795   int current_arg;
3796
3797   /* An array whose size is the number of template parameters.  The
3798      elements are nonzero if the parameter has been used in any one
3799      of the arguments processed so far.  */
3800   int* parms;
3801
3802   /* An array whose size is the number of template arguments.  The
3803      elements are nonzero if the argument makes use of template
3804      parameters of this level.  */
3805   int* arg_uses_template_parms;
3806 };
3807
3808 /* Subroutine of push_template_decl used to see if each template
3809    parameter in a partial specialization is used in the explicit
3810    argument list.  If T is of the LEVEL given in DATA (which is
3811    treated as a template_parm_data*), then DATA->PARMS is marked
3812    appropriately.  */
3813
3814 static int
3815 mark_template_parm (tree t, void* data)
3816 {
3817   int level;
3818   int idx;
3819   struct template_parm_data* tpd = (struct template_parm_data*) data;
3820
3821   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3822     {
3823       level = TEMPLATE_PARM_LEVEL (t);
3824       idx = TEMPLATE_PARM_IDX (t);
3825     }
3826   else
3827     {
3828       level = TEMPLATE_TYPE_LEVEL (t);
3829       idx = TEMPLATE_TYPE_IDX (t);
3830     }
3831
3832   if (level == tpd->level)
3833     {
3834       tpd->parms[idx] = 1;
3835       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3836     }
3837
3838   /* Return zero so that for_each_template_parm will continue the
3839      traversal of the tree; we want to mark *every* template parm.  */
3840   return 0;
3841 }
3842
3843 /* Process the partial specialization DECL.  */
3844
3845 static tree
3846 process_partial_specialization (tree decl)
3847 {
3848   tree type = TREE_TYPE (decl);
3849   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3850   tree specargs = CLASSTYPE_TI_ARGS (type);
3851   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3852   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3853   tree inner_parms;
3854   tree inst;
3855   int nargs = TREE_VEC_LENGTH (inner_args);
3856   int ntparms;
3857   int  i;
3858   bool did_error_intro = false;
3859   struct template_parm_data tpd;
3860   struct template_parm_data tpd2;
3861
3862   gcc_assert (current_template_parms);
3863
3864   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3865   ntparms = TREE_VEC_LENGTH (inner_parms);
3866
3867   /* We check that each of the template parameters given in the
3868      partial specialization is used in the argument list to the
3869      specialization.  For example:
3870
3871        template <class T> struct S;
3872        template <class T> struct S<T*>;
3873
3874      The second declaration is OK because `T*' uses the template
3875      parameter T, whereas
3876
3877        template <class T> struct S<int>;
3878
3879      is no good.  Even trickier is:
3880
3881        template <class T>
3882        struct S1
3883        {
3884           template <class U>
3885           struct S2;
3886           template <class U>
3887           struct S2<T>;
3888        };
3889
3890      The S2<T> declaration is actually invalid; it is a
3891      full-specialization.  Of course,
3892
3893           template <class U>
3894           struct S2<T (*)(U)>;
3895
3896      or some such would have been OK.  */
3897   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3898   tpd.parms = XALLOCAVEC (int, ntparms);
3899   memset (tpd.parms, 0, sizeof (int) * ntparms);
3900
3901   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
3902   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3903   for (i = 0; i < nargs; ++i)
3904     {
3905       tpd.current_arg = i;
3906       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3907                               &mark_template_parm,
3908                               &tpd,
3909                               NULL,
3910                               /*include_nondeduced_p=*/false);
3911     }
3912   for (i = 0; i < ntparms; ++i)
3913     if (tpd.parms[i] == 0)
3914       {
3915         /* One of the template parms was not used in the
3916            specialization.  */
3917         if (!did_error_intro)
3918           {
3919             error ("template parameters not used in partial specialization:");
3920             did_error_intro = true;
3921           }
3922
3923         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3924       }
3925
3926   if (did_error_intro)
3927     return error_mark_node;
3928
3929   /* [temp.class.spec]
3930
3931      The argument list of the specialization shall not be identical to
3932      the implicit argument list of the primary template.  */
3933   if (comp_template_args
3934       (inner_args,
3935        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3936                                                    (maintmpl)))))
3937     error ("partial specialization %qT does not specialize any template arguments", type);
3938
3939   /* [temp.class.spec]
3940
3941      A partially specialized non-type argument expression shall not
3942      involve template parameters of the partial specialization except
3943      when the argument expression is a simple identifier.
3944
3945      The type of a template parameter corresponding to a specialized
3946      non-type argument shall not be dependent on a parameter of the
3947      specialization. 
3948
3949      Also, we verify that pack expansions only occur at the
3950      end of the argument list.  */
3951   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3952   tpd2.parms = 0;
3953   for (i = 0; i < nargs; ++i)
3954     {
3955       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3956       tree arg = TREE_VEC_ELT (inner_args, i);
3957       tree packed_args = NULL_TREE;
3958       int j, len = 1;
3959
3960       if (ARGUMENT_PACK_P (arg))
3961         {
3962           /* Extract the arguments from the argument pack. We'll be
3963              iterating over these in the following loop.  */
3964           packed_args = ARGUMENT_PACK_ARGS (arg);
3965           len = TREE_VEC_LENGTH (packed_args);
3966         }
3967
3968       for (j = 0; j < len; j++)
3969         {
3970           if (packed_args)
3971             /* Get the Jth argument in the parameter pack.  */
3972             arg = TREE_VEC_ELT (packed_args, j);
3973
3974           if (PACK_EXPANSION_P (arg))
3975             {
3976               /* Pack expansions must come at the end of the
3977                  argument list.  */
3978               if ((packed_args && j < len - 1)
3979                   || (!packed_args && i < nargs - 1))
3980                 {
3981                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3982                     error ("parameter pack argument %qE must be at the "
3983                            "end of the template argument list", arg);
3984                   else
3985                     error ("parameter pack argument %qT must be at the "
3986                            "end of the template argument list", arg);
3987                 }
3988             }
3989
3990           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3991             /* We only care about the pattern.  */
3992             arg = PACK_EXPANSION_PATTERN (arg);
3993
3994           if (/* These first two lines are the `non-type' bit.  */
3995               !TYPE_P (arg)
3996               && TREE_CODE (arg) != TEMPLATE_DECL
3997               /* This next line is the `argument expression is not just a
3998                  simple identifier' condition and also the `specialized
3999                  non-type argument' bit.  */
4000               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
4001             {
4002               if ((!packed_args && tpd.arg_uses_template_parms[i])
4003                   || (packed_args && uses_template_parms (arg)))
4004                 error ("template argument %qE involves template parameter(s)",
4005                        arg);
4006               else 
4007                 {
4008                   /* Look at the corresponding template parameter,
4009                      marking which template parameters its type depends
4010                      upon.  */
4011                   tree type = TREE_TYPE (parm);
4012
4013                   if (!tpd2.parms)
4014                     {
4015                       /* We haven't yet initialized TPD2.  Do so now.  */
4016                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4017                       /* The number of parameters here is the number in the
4018                          main template, which, as checked in the assertion
4019                          above, is NARGS.  */
4020                       tpd2.parms = XALLOCAVEC (int, nargs);
4021                       tpd2.level = 
4022                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4023                     }
4024
4025                   /* Mark the template parameters.  But this time, we're
4026                      looking for the template parameters of the main
4027                      template, not in the specialization.  */
4028                   tpd2.current_arg = i;
4029                   tpd2.arg_uses_template_parms[i] = 0;
4030                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4031                   for_each_template_parm (type,
4032                                           &mark_template_parm,
4033                                           &tpd2,
4034                                           NULL,
4035                                           /*include_nondeduced_p=*/false);
4036
4037                   if (tpd2.arg_uses_template_parms [i])
4038                     {
4039                       /* The type depended on some template parameters.
4040                          If they are fully specialized in the
4041                          specialization, that's OK.  */
4042                       int j;
4043                       int count = 0;
4044                       for (j = 0; j < nargs; ++j)
4045                         if (tpd2.parms[j] != 0
4046                             && tpd.arg_uses_template_parms [j])
4047                           ++count;
4048                       if (count != 0)
4049                         error_n (input_location, count,
4050                                  "type %qT of template argument %qE depends "
4051                                  "on a template parameter",
4052                                  "type %qT of template argument %qE depends "
4053                                  "on template parameters",
4054                                  type,
4055                                  arg);
4056                     }
4057                 }
4058             }
4059         }
4060     }
4061
4062   /* We should only get here once.  */
4063   gcc_assert (!COMPLETE_TYPE_P (type));
4064
4065   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4066     = tree_cons (specargs, inner_parms,
4067                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4068   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4069
4070   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4071        inst = TREE_CHAIN (inst))
4072     {
4073       tree inst_type = TREE_VALUE (inst);
4074       if (COMPLETE_TYPE_P (inst_type)
4075           && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4076         {
4077           tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4078           if (spec && TREE_TYPE (spec) == type)
4079             permerror (input_location,
4080                        "partial specialization of %qT after instantiation "
4081                        "of %qT", type, inst_type);
4082         }
4083     }
4084
4085   return decl;
4086 }
4087
4088 /* Check that a template declaration's use of default arguments and
4089    parameter packs is not invalid.  Here, PARMS are the template
4090    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4091    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4092    specialization.
4093    
4094
4095    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4096    declaration (but not a definition); 1 indicates a declaration, 2
4097    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4098    emitted for extraneous default arguments.
4099
4100    Returns TRUE if there were no errors found, FALSE otherwise. */
4101
4102 bool
4103 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4104                          int is_partial, int is_friend_decl)
4105 {
4106   const char *msg;
4107   int last_level_to_check;
4108   tree parm_level;
4109   bool no_errors = true;
4110
4111   /* [temp.param]
4112
4113      A default template-argument shall not be specified in a
4114      function template declaration or a function template definition, nor
4115      in the template-parameter-list of the definition of a member of a
4116      class template.  */
4117
4118   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4119     /* You can't have a function template declaration in a local
4120        scope, nor you can you define a member of a class template in a
4121        local scope.  */
4122     return true;
4123
4124   if (current_class_type
4125       && !TYPE_BEING_DEFINED (current_class_type)
4126       && DECL_LANG_SPECIFIC (decl)
4127       && DECL_DECLARES_FUNCTION_P (decl)
4128       /* If this is either a friend defined in the scope of the class
4129          or a member function.  */
4130       && (DECL_FUNCTION_MEMBER_P (decl)
4131           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4132           : DECL_FRIEND_CONTEXT (decl)
4133           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4134           : false)
4135       /* And, if it was a member function, it really was defined in
4136          the scope of the class.  */
4137       && (!DECL_FUNCTION_MEMBER_P (decl)
4138           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4139     /* We already checked these parameters when the template was
4140        declared, so there's no need to do it again now.  This function
4141        was defined in class scope, but we're processing it's body now
4142        that the class is complete.  */
4143     return true;
4144
4145   /* Core issue 226 (C++0x only): the following only applies to class
4146      templates.  */
4147   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4148     {
4149       /* [temp.param]
4150
4151          If a template-parameter has a default template-argument, all
4152          subsequent template-parameters shall have a default
4153          template-argument supplied.  */
4154       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4155         {
4156           tree inner_parms = TREE_VALUE (parm_level);
4157           int ntparms = TREE_VEC_LENGTH (inner_parms);
4158           int seen_def_arg_p = 0;
4159           int i;
4160
4161           for (i = 0; i < ntparms; ++i)
4162             {
4163               tree parm = TREE_VEC_ELT (inner_parms, i);
4164
4165               if (parm == error_mark_node)
4166                 continue;
4167
4168               if (TREE_PURPOSE (parm))
4169                 seen_def_arg_p = 1;
4170               else if (seen_def_arg_p
4171                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4172                 {
4173                   error ("no default argument for %qD", TREE_VALUE (parm));
4174                   /* For better subsequent error-recovery, we indicate that
4175                      there should have been a default argument.  */
4176                   TREE_PURPOSE (parm) = error_mark_node;
4177                   no_errors = false;
4178                 }
4179               else if (is_primary
4180                        && !is_partial
4181                        && !is_friend_decl
4182                        /* Don't complain about an enclosing partial
4183                           specialization.  */
4184                        && parm_level == parms
4185                        && TREE_CODE (decl) == TYPE_DECL
4186                        && i < ntparms - 1
4187                        && template_parameter_pack_p (TREE_VALUE (parm)))
4188                 {
4189                   /* A primary class template can only have one
4190                      parameter pack, at the end of the template
4191                      parameter list.  */
4192
4193                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4194                     error ("parameter pack %qE must be at the end of the"
4195                            " template parameter list", TREE_VALUE (parm));
4196                   else
4197                     error ("parameter pack %qT must be at the end of the"
4198                            " template parameter list", 
4199                            TREE_TYPE (TREE_VALUE (parm)));
4200
4201                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4202                     = error_mark_node;
4203                   no_errors = false;
4204                 }
4205             }
4206         }
4207     }
4208
4209   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4210       || is_partial 
4211       || !is_primary
4212       || is_friend_decl)
4213     /* For an ordinary class template, default template arguments are
4214        allowed at the innermost level, e.g.:
4215          template <class T = int>
4216          struct S {};
4217        but, in a partial specialization, they're not allowed even
4218        there, as we have in [temp.class.spec]:
4219
4220          The template parameter list of a specialization shall not
4221          contain default template argument values.
4222
4223        So, for a partial specialization, or for a function template
4224        (in C++98/C++03), we look at all of them.  */
4225     ;
4226   else
4227     /* But, for a primary class template that is not a partial
4228        specialization we look at all template parameters except the
4229        innermost ones.  */
4230     parms = TREE_CHAIN (parms);
4231
4232   /* Figure out what error message to issue.  */
4233   if (is_friend_decl == 2)
4234     msg = G_("default template arguments may not be used in function template "
4235              "friend re-declaration");
4236   else if (is_friend_decl)
4237     msg = G_("default template arguments may not be used in function template "
4238              "friend declarations");
4239   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4240     msg = G_("default template arguments may not be used in function templates "
4241              "without -std=c++0x or -std=gnu++0x");
4242   else if (is_partial)
4243     msg = G_("default template arguments may not be used in "
4244              "partial specializations");
4245   else
4246     msg = G_("default argument for template parameter for class enclosing %qD");
4247
4248   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4249     /* If we're inside a class definition, there's no need to
4250        examine the parameters to the class itself.  On the one
4251        hand, they will be checked when the class is defined, and,
4252        on the other, default arguments are valid in things like:
4253          template <class T = double>
4254          struct S { template <class U> void f(U); };
4255        Here the default argument for `S' has no bearing on the
4256        declaration of `f'.  */
4257     last_level_to_check = template_class_depth (current_class_type) + 1;
4258   else
4259     /* Check everything.  */
4260     last_level_to_check = 0;
4261
4262   for (parm_level = parms;
4263        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4264        parm_level = TREE_CHAIN (parm_level))
4265     {
4266       tree inner_parms = TREE_VALUE (parm_level);
4267       int i;
4268       int ntparms;
4269
4270       ntparms = TREE_VEC_LENGTH (inner_parms);
4271       for (i = 0; i < ntparms; ++i)
4272         {
4273           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4274             continue;
4275
4276           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4277             {
4278               if (msg)
4279                 {
4280                   no_errors = false;
4281                   if (is_friend_decl == 2)
4282                     return no_errors;
4283
4284                   error (msg, decl);
4285                   msg = 0;
4286                 }
4287
4288               /* Clear out the default argument so that we are not
4289                  confused later.  */
4290               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4291             }
4292         }
4293
4294       /* At this point, if we're still interested in issuing messages,
4295          they must apply to classes surrounding the object declared.  */
4296       if (msg)
4297         msg = G_("default argument for template parameter for class "
4298                  "enclosing %qD");
4299     }
4300
4301   return no_errors;
4302 }
4303
4304 /* Worker for push_template_decl_real, called via
4305    for_each_template_parm.  DATA is really an int, indicating the
4306    level of the parameters we are interested in.  If T is a template
4307    parameter of that level, return nonzero.  */
4308
4309 static int
4310 template_parm_this_level_p (tree t, void* data)
4311 {
4312   int this_level = *(int *)data;
4313   int level;
4314
4315   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4316     level = TEMPLATE_PARM_LEVEL (t);
4317   else
4318     level = TEMPLATE_TYPE_LEVEL (t);
4319   return level == this_level;
4320 }
4321
4322 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4323    parameters given by current_template_args, or reuses a
4324    previously existing one, if appropriate.  Returns the DECL, or an
4325    equivalent one, if it is replaced via a call to duplicate_decls.
4326
4327    If IS_FRIEND is true, DECL is a friend declaration.  */
4328
4329 tree
4330 push_template_decl_real (tree decl, bool is_friend)
4331 {
4332   tree tmpl;
4333   tree args;
4334   tree info;
4335   tree ctx;
4336   int primary;
4337   int is_partial;
4338   int new_template_p = 0;
4339   /* True if the template is a member template, in the sense of
4340      [temp.mem].  */
4341   bool member_template_p = false;
4342
4343   if (decl == error_mark_node || !current_template_parms)
4344     return error_mark_node;
4345
4346   /* See if this is a partial specialization.  */
4347   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4348                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4349                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4350
4351   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4352     is_friend = true;
4353
4354   if (is_friend)
4355     /* For a friend, we want the context of the friend function, not
4356        the type of which it is a friend.  */
4357     ctx = CP_DECL_CONTEXT (decl);
4358   else if (CP_DECL_CONTEXT (decl)
4359            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4360     /* In the case of a virtual function, we want the class in which
4361        it is defined.  */
4362     ctx = CP_DECL_CONTEXT (decl);
4363   else
4364     /* Otherwise, if we're currently defining some class, the DECL
4365        is assumed to be a member of the class.  */
4366     ctx = current_scope ();
4367
4368   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4369     ctx = NULL_TREE;
4370
4371   if (!DECL_CONTEXT (decl))
4372     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4373
4374   /* See if this is a primary template.  */
4375   if (is_friend && ctx)
4376     /* A friend template that specifies a class context, i.e.
4377          template <typename T> friend void A<T>::f();
4378        is not primary.  */
4379     primary = 0;
4380   else
4381     primary = template_parm_scope_p ();
4382
4383   if (primary)
4384     {
4385       if (DECL_CLASS_SCOPE_P (decl))
4386         member_template_p = true;
4387       if (TREE_CODE (decl) == TYPE_DECL
4388           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4389         {
4390           error ("template class without a name");
4391           return error_mark_node;
4392         }
4393       else if (TREE_CODE (decl) == FUNCTION_DECL)
4394         {
4395           if (DECL_DESTRUCTOR_P (decl))
4396             {
4397               /* [temp.mem]
4398
4399                  A destructor shall not be a member template.  */
4400               error ("destructor %qD declared as member template", decl);
4401               return error_mark_node;
4402             }
4403           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4404               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4405                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4406                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4407                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4408                       == void_list_node)))
4409             {
4410               /* [basic.stc.dynamic.allocation]
4411
4412                  An allocation function can be a function
4413                  template. ... Template allocation functions shall
4414                  have two or more parameters.  */
4415               error ("invalid template declaration of %qD", decl);
4416               return error_mark_node;
4417             }
4418         }
4419       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4420                && CLASS_TYPE_P (TREE_TYPE (decl)))
4421         /* OK */;
4422       else
4423         {
4424           error ("template declaration of %q#D", decl);
4425           return error_mark_node;
4426         }
4427     }
4428
4429   /* Check to see that the rules regarding the use of default
4430      arguments are not being violated.  */
4431   check_default_tmpl_args (decl, current_template_parms,
4432                            primary, is_partial, /*is_friend_decl=*/0);
4433
4434   /* Ensure that there are no parameter packs in the type of this
4435      declaration that have not been expanded.  */
4436   if (TREE_CODE (decl) == FUNCTION_DECL)
4437     {
4438       /* Check each of the arguments individually to see if there are
4439          any bare parameter packs.  */
4440       tree type = TREE_TYPE (decl);
4441       tree arg = DECL_ARGUMENTS (decl);
4442       tree argtype = TYPE_ARG_TYPES (type);
4443
4444       while (arg && argtype)
4445         {
4446           if (!FUNCTION_PARAMETER_PACK_P (arg)
4447               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4448             {
4449             /* This is a PARM_DECL that contains unexpanded parameter
4450                packs. We have already complained about this in the
4451                check_for_bare_parameter_packs call, so just replace
4452                these types with ERROR_MARK_NODE.  */
4453               TREE_TYPE (arg) = error_mark_node;
4454               TREE_VALUE (argtype) = error_mark_node;
4455             }
4456
4457           arg = DECL_CHAIN (arg);
4458           argtype = TREE_CHAIN (argtype);
4459         }
4460
4461       /* Check for bare parameter packs in the return type and the
4462          exception specifiers.  */
4463       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4464         /* Errors were already issued, set return type to int
4465            as the frontend doesn't expect error_mark_node as
4466            the return type.  */
4467         TREE_TYPE (type) = integer_type_node;
4468       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4469         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4470     }
4471   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4472     {
4473       TREE_TYPE (decl) = error_mark_node;
4474       return error_mark_node;
4475     }
4476
4477   if (is_partial)
4478     return process_partial_specialization (decl);
4479
4480   args = current_template_args ();
4481
4482   if (!ctx
4483       || TREE_CODE (ctx) == FUNCTION_DECL
4484       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4485       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4486     {
4487       if (DECL_LANG_SPECIFIC (decl)
4488           && DECL_TEMPLATE_INFO (decl)
4489           && DECL_TI_TEMPLATE (decl))
4490         tmpl = DECL_TI_TEMPLATE (decl);
4491       /* If DECL is a TYPE_DECL for a class-template, then there won't
4492          be DECL_LANG_SPECIFIC.  The information equivalent to
4493          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4494       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4495                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4496                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4497         {
4498           /* Since a template declaration already existed for this
4499              class-type, we must be redeclaring it here.  Make sure
4500              that the redeclaration is valid.  */
4501           redeclare_class_template (TREE_TYPE (decl),
4502                                     current_template_parms);
4503           /* We don't need to create a new TEMPLATE_DECL; just use the
4504              one we already had.  */
4505           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4506         }
4507       else
4508         {
4509           tmpl = build_template_decl (decl, current_template_parms,
4510                                       member_template_p);
4511           new_template_p = 1;
4512
4513           if (DECL_LANG_SPECIFIC (decl)
4514               && DECL_TEMPLATE_SPECIALIZATION (decl))
4515             {
4516               /* A specialization of a member template of a template
4517                  class.  */
4518               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4519               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4520               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4521             }
4522         }
4523     }
4524   else
4525     {
4526       tree a, t, current, parms;
4527       int i;
4528       tree tinfo = get_template_info (decl);
4529
4530       if (!tinfo)
4531         {
4532           error ("template definition of non-template %q#D", decl);
4533           return error_mark_node;
4534         }
4535
4536       tmpl = TI_TEMPLATE (tinfo);
4537
4538       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4539           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4540           && DECL_TEMPLATE_SPECIALIZATION (decl)
4541           && DECL_MEMBER_TEMPLATE_P (tmpl))
4542         {
4543           tree new_tmpl;
4544
4545           /* The declaration is a specialization of a member
4546              template, declared outside the class.  Therefore, the
4547              innermost template arguments will be NULL, so we
4548              replace them with the arguments determined by the
4549              earlier call to check_explicit_specialization.  */
4550           args = DECL_TI_ARGS (decl);
4551
4552           new_tmpl
4553             = build_template_decl (decl, current_template_parms,
4554                                    member_template_p);
4555           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4556           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4557           DECL_TI_TEMPLATE (decl) = new_tmpl;
4558           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4559           DECL_TEMPLATE_INFO (new_tmpl)
4560             = build_template_info (tmpl, args);
4561
4562           register_specialization (new_tmpl,
4563                                    most_general_template (tmpl),
4564                                    args,
4565                                    is_friend, 0);
4566           return decl;
4567         }
4568
4569       /* Make sure the template headers we got make sense.  */
4570
4571       parms = DECL_TEMPLATE_PARMS (tmpl);
4572       i = TMPL_PARMS_DEPTH (parms);
4573       if (TMPL_ARGS_DEPTH (args) != i)
4574         {
4575           error ("expected %d levels of template parms for %q#D, got %d",
4576                  i, decl, TMPL_ARGS_DEPTH (args));
4577         }
4578       else
4579         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4580           {
4581             a = TMPL_ARGS_LEVEL (args, i);
4582             t = INNERMOST_TEMPLATE_PARMS (parms);
4583
4584             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4585               {
4586                 if (current == decl)
4587                   error ("got %d template parameters for %q#D",
4588                          TREE_VEC_LENGTH (a), decl);
4589                 else
4590                   error ("got %d template parameters for %q#T",
4591                          TREE_VEC_LENGTH (a), current);
4592                 error ("  but %d required", TREE_VEC_LENGTH (t));
4593                 return error_mark_node;
4594               }
4595
4596             if (current == decl)
4597               current = ctx;
4598             else if (current == NULL_TREE)
4599               /* Can happen in erroneous input.  */
4600               break;
4601             else
4602               current = (TYPE_P (current)
4603                          ? TYPE_CONTEXT (current)
4604                          : DECL_CONTEXT (current));
4605           }
4606
4607       /* Check that the parms are used in the appropriate qualifying scopes
4608          in the declarator.  */
4609       if (!comp_template_args
4610           (TI_ARGS (tinfo),
4611            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4612         {
4613           error ("\
4614 template arguments to %qD do not match original template %qD",
4615                  decl, DECL_TEMPLATE_RESULT (tmpl));
4616           if (!uses_template_parms (TI_ARGS (tinfo)))
4617             inform (input_location, "use template<> for an explicit specialization");
4618           /* Avoid crash in import_export_decl.  */
4619           DECL_INTERFACE_KNOWN (decl) = 1;
4620           return error_mark_node;
4621         }
4622     }
4623
4624   DECL_TEMPLATE_RESULT (tmpl) = decl;
4625   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4626
4627   /* Push template declarations for global functions and types.  Note
4628      that we do not try to push a global template friend declared in a
4629      template class; such a thing may well depend on the template
4630      parameters of the class.  */
4631   if (new_template_p && !ctx
4632       && !(is_friend && template_class_depth (current_class_type) > 0))
4633     {
4634       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4635       if (tmpl == error_mark_node)
4636         return error_mark_node;
4637
4638       /* Hide template friend classes that haven't been declared yet.  */
4639       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4640         {
4641           DECL_ANTICIPATED (tmpl) = 1;
4642           DECL_FRIEND_P (tmpl) = 1;
4643         }
4644     }
4645
4646   if (primary)
4647     {
4648       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4649       int i;
4650
4651       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4652       if (DECL_CONV_FN_P (tmpl))
4653         {
4654           int depth = TMPL_PARMS_DEPTH (parms);
4655
4656           /* It is a conversion operator. See if the type converted to
4657              depends on innermost template operands.  */
4658
4659           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4660                                          depth))
4661             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4662         }
4663
4664       /* Give template template parms a DECL_CONTEXT of the template
4665          for which they are a parameter.  */
4666       parms = INNERMOST_TEMPLATE_PARMS (parms);
4667       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4668         {
4669           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4670           if (TREE_CODE (parm) == TEMPLATE_DECL)
4671             DECL_CONTEXT (parm) = tmpl;
4672         }
4673     }
4674
4675   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4676      back to its most general template.  If TMPL is a specialization,
4677      ARGS may only have the innermost set of arguments.  Add the missing
4678      argument levels if necessary.  */
4679   if (DECL_TEMPLATE_INFO (tmpl))
4680     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4681
4682   info = build_template_info (tmpl, args);
4683
4684   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4685     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4686   else if (DECL_LANG_SPECIFIC (decl))
4687     DECL_TEMPLATE_INFO (decl) = info;
4688
4689   return DECL_TEMPLATE_RESULT (tmpl);
4690 }
4691
4692 tree
4693 push_template_decl (tree decl)
4694 {
4695   return push_template_decl_real (decl, false);
4696 }
4697
4698 /* Called when a class template TYPE is redeclared with the indicated
4699    template PARMS, e.g.:
4700
4701      template <class T> struct S;
4702      template <class T> struct S {};  */
4703
4704 bool
4705 redeclare_class_template (tree type, tree parms)
4706 {
4707   tree tmpl;
4708   tree tmpl_parms;
4709   int i;
4710
4711   if (!TYPE_TEMPLATE_INFO (type))
4712     {
4713       error ("%qT is not a template type", type);
4714       return false;
4715     }
4716
4717   tmpl = TYPE_TI_TEMPLATE (type);
4718   if (!PRIMARY_TEMPLATE_P (tmpl))
4719     /* The type is nested in some template class.  Nothing to worry
4720        about here; there are no new template parameters for the nested
4721        type.  */
4722     return true;
4723
4724   if (!parms)
4725     {
4726       error ("template specifiers not specified in declaration of %qD",
4727              tmpl);
4728       return false;
4729     }
4730
4731   parms = INNERMOST_TEMPLATE_PARMS (parms);
4732   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4733
4734   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4735     {
4736       error_n (input_location, TREE_VEC_LENGTH (parms),
4737                "redeclared with %d template parameter",
4738                "redeclared with %d template parameters",
4739                TREE_VEC_LENGTH (parms));
4740       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
4741                 "previous declaration %q+D used %d template parameter",
4742                 "previous declaration %q+D used %d template parameters",
4743                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
4744       return false;
4745     }
4746
4747   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4748     {
4749       tree tmpl_parm;
4750       tree parm;
4751       tree tmpl_default;
4752       tree parm_default;
4753
4754       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4755           || TREE_VEC_ELT (parms, i) == error_mark_node)
4756         continue;
4757
4758       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4759       if (tmpl_parm == error_mark_node)
4760         return false;
4761
4762       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4763       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4764       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4765
4766       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4767          TEMPLATE_DECL.  */
4768       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4769           || (TREE_CODE (tmpl_parm) != TYPE_DECL
4770               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4771           || (TREE_CODE (tmpl_parm) != PARM_DECL
4772               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4773                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4774           || (TREE_CODE (tmpl_parm) == PARM_DECL
4775               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4776                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
4777         {
4778           error ("template parameter %q+#D", tmpl_parm);
4779           error ("redeclared here as %q#D", parm);
4780           return false;
4781         }
4782
4783       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4784         {
4785           /* We have in [temp.param]:
4786
4787              A template-parameter may not be given default arguments
4788              by two different declarations in the same scope.  */
4789           error_at (input_location, "redefinition of default argument for %q#D", parm);
4790           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4791                   "original definition appeared here");
4792           return false;
4793         }
4794
4795       if (parm_default != NULL_TREE)
4796         /* Update the previous template parameters (which are the ones
4797            that will really count) with the new default value.  */
4798         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4799       else if (tmpl_default != NULL_TREE)
4800         /* Update the new parameters, too; they'll be used as the
4801            parameters for any members.  */
4802         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4803     }
4804
4805     return true;
4806 }
4807
4808 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4809    (possibly simplified) expression.  */
4810
4811 static tree
4812 fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
4813 {
4814   if (expr == NULL_TREE)
4815     return NULL_TREE;
4816
4817   /* If we're in a template, but EXPR isn't value dependent, simplify
4818      it.  We're supposed to treat:
4819
4820        template <typename T> void f(T[1 + 1]);
4821        template <typename T> void f(T[2]);
4822
4823      as two declarations of the same function, for example.  */
4824   if (processing_template_decl
4825       && !type_dependent_expression_p (expr)
4826       && !value_dependent_expression_p (expr))
4827     {
4828       HOST_WIDE_INT saved_processing_template_decl;
4829
4830       saved_processing_template_decl = processing_template_decl;
4831       processing_template_decl = 0;
4832       expr = tsubst_copy_and_build (expr,
4833                                     /*args=*/NULL_TREE,
4834                                     complain,
4835                                     /*in_decl=*/NULL_TREE,
4836                                     /*function_p=*/false,
4837                                     /*integral_constant_expression_p=*/true);
4838       processing_template_decl = saved_processing_template_decl;
4839     }
4840   return expr;
4841 }
4842
4843 tree
4844 fold_non_dependent_expr (tree expr)
4845 {
4846   return fold_non_dependent_expr_sfinae (expr, tf_error);
4847 }
4848
4849 /* EXPR is an expression which is used in a constant-expression context.
4850    For instance, it could be a VAR_DECL with a constant initializer.
4851    Extract the innermost constant expression.
4852
4853    This is basically a more powerful version of
4854    integral_constant_value, which can be used also in templates where
4855    initializers can maintain a syntactic rather than semantic form
4856    (even if they are non-dependent, for access-checking purposes).  */
4857
4858 static tree
4859 fold_decl_constant_value (tree expr)
4860 {
4861   tree const_expr = expr;
4862   do
4863     {
4864       expr = fold_non_dependent_expr (const_expr);
4865       const_expr = integral_constant_value (expr);
4866     }
4867   while (expr != const_expr);
4868
4869   return expr;
4870 }
4871
4872 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4873    must be a function or a pointer-to-function type, as specified
4874    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4875    and check that the resulting function has external linkage.  */
4876
4877 static tree
4878 convert_nontype_argument_function (tree type, tree expr)
4879 {
4880   tree fns = expr;
4881   tree fn, fn_no_ptr;
4882
4883   fn = instantiate_type (type, fns, tf_none);
4884   if (fn == error_mark_node)
4885     return error_mark_node;
4886
4887   fn_no_ptr = fn;
4888   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4889     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4890   if (TREE_CODE (fn_no_ptr) == BASELINK)
4891     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4892  
4893   /* [temp.arg.nontype]/1
4894
4895      A template-argument for a non-type, non-template template-parameter
4896      shall be one of:
4897      [...]
4898      -- the address of an object or function with external linkage.  */
4899   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4900     {
4901       error ("%qE is not a valid template argument for type %qT "
4902              "because function %qD has not external linkage",
4903              expr, type, fn_no_ptr);
4904       return NULL_TREE;
4905     }
4906
4907   return fn;
4908 }
4909
4910 /* Subroutine of convert_nontype_argument.
4911    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4912    Emit an error otherwise.  */
4913
4914 static bool
4915 check_valid_ptrmem_cst_expr (tree type, tree expr)
4916 {
4917   STRIP_NOPS (expr);
4918   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4919     return true;
4920   error ("%qE is not a valid template argument for type %qT",
4921          expr, type);
4922   error ("it must be a pointer-to-member of the form `&X::Y'");
4923   return false;
4924 }
4925
4926 /* Returns TRUE iff the address of OP is value-dependent.
4927
4928    14.6.2.4 [temp.dep.temp]:
4929    A non-integral non-type template-argument is dependent if its type is
4930    dependent or it has either of the following forms
4931      qualified-id
4932      & qualified-id
4933    and contains a nested-name-specifier which specifies a class-name that
4934    names a dependent type.
4935
4936    We generalize this to just say that the address of a member of a
4937    dependent class is value-dependent; the above doesn't cover the
4938    address of a static data member named with an unqualified-id.  */
4939
4940 static bool
4941 has_value_dependent_address (tree op)
4942 {
4943   /* We could use get_inner_reference here, but there's no need;
4944      this is only relevant for template non-type arguments, which
4945      can only be expressed as &id-expression.  */
4946   if (DECL_P (op))
4947     {
4948       tree ctx = CP_DECL_CONTEXT (op);
4949       if (TYPE_P (ctx) && dependent_type_p (ctx))
4950         return true;
4951     }
4952
4953   return false;
4954 }
4955
4956 /* Attempt to convert the non-type template parameter EXPR to the
4957    indicated TYPE.  If the conversion is successful, return the
4958    converted value.  If the conversion is unsuccessful, return
4959    NULL_TREE if we issued an error message, or error_mark_node if we
4960    did not.  We issue error messages for out-and-out bad template
4961    parameters, but not simply because the conversion failed, since we
4962    might be just trying to do argument deduction.  Both TYPE and EXPR
4963    must be non-dependent.
4964
4965    The conversion follows the special rules described in
4966    [temp.arg.nontype], and it is much more strict than an implicit
4967    conversion.
4968
4969    This function is called twice for each template argument (see
4970    lookup_template_class for a more accurate description of this
4971    problem). This means that we need to handle expressions which
4972    are not valid in a C++ source, but can be created from the
4973    first call (for instance, casts to perform conversions). These
4974    hacks can go away after we fix the double coercion problem.  */
4975
4976 static tree
4977 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
4978 {
4979   tree expr_type;
4980
4981   /* Detect immediately string literals as invalid non-type argument.
4982      This special-case is not needed for correctness (we would easily
4983      catch this later), but only to provide better diagnostic for this
4984      common user mistake. As suggested by DR 100, we do not mention
4985      linkage issues in the diagnostic as this is not the point.  */
4986   /* FIXME we're making this OK.  */
4987   if (TREE_CODE (expr) == STRING_CST)
4988     {
4989       if (complain & tf_error)
4990         error ("%qE is not a valid template argument for type %qT "
4991                "because string literals can never be used in this context",
4992                expr, type);
4993       return NULL_TREE;
4994     }
4995
4996   /* Add the ADDR_EXPR now for the benefit of
4997      value_dependent_expression_p.  */
4998   if (TYPE_PTROBV_P (type))
4999     expr = decay_conversion (expr);
5000
5001   /* If we are in a template, EXPR may be non-dependent, but still
5002      have a syntactic, rather than semantic, form.  For example, EXPR
5003      might be a SCOPE_REF, rather than the VAR_DECL to which the
5004      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5005      so that access checking can be performed when the template is
5006      instantiated -- but here we need the resolved form so that we can
5007      convert the argument.  */
5008   if (TYPE_REF_OBJ_P (type)
5009       && has_value_dependent_address (expr))
5010     /* If we want the address and it's value-dependent, don't fold.  */;
5011   else if (!type_unknown_p (expr))
5012     expr = fold_non_dependent_expr_sfinae (expr, complain);
5013   if (error_operand_p (expr))
5014     return error_mark_node;
5015   expr_type = TREE_TYPE (expr);
5016   if (TREE_CODE (type) == REFERENCE_TYPE)
5017     expr = mark_lvalue_use (expr);
5018   else
5019     expr = mark_rvalue_use (expr);
5020
5021   /* HACK: Due to double coercion, we can get a
5022      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5023      which is the tree that we built on the first call (see
5024      below when coercing to reference to object or to reference to
5025      function). We just strip everything and get to the arg.
5026      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5027      for examples.  */
5028   if (TREE_CODE (expr) == NOP_EXPR)
5029     {
5030       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5031         {
5032           /* ??? Maybe we could use convert_from_reference here, but we
5033              would need to relax its constraints because the NOP_EXPR
5034              could actually change the type to something more cv-qualified,
5035              and this is not folded by convert_from_reference.  */
5036           tree addr = TREE_OPERAND (expr, 0);
5037           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
5038           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
5039           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
5040           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5041                       (TREE_TYPE (expr_type),
5042                        TREE_TYPE (TREE_TYPE (addr))));
5043
5044           expr = TREE_OPERAND (addr, 0);
5045           expr_type = TREE_TYPE (expr);
5046         }
5047
5048       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5049          parameter is a pointer to object, through decay and
5050          qualification conversion. Let's strip everything.  */
5051       else if (TYPE_PTROBV_P (type))
5052         {
5053           STRIP_NOPS (expr);
5054           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5055           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5056           /* Skip the ADDR_EXPR only if it is part of the decay for
5057              an array. Otherwise, it is part of the original argument
5058              in the source code.  */
5059           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5060             expr = TREE_OPERAND (expr, 0);
5061           expr_type = TREE_TYPE (expr);
5062         }
5063     }
5064
5065   /* [temp.arg.nontype]/5, bullet 1
5066
5067      For a non-type template-parameter of integral or enumeration type,
5068      integral promotions (_conv.prom_) and integral conversions
5069      (_conv.integral_) are applied.  */
5070   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5071     {
5072       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
5073         return error_mark_node;
5074
5075       expr = fold_decl_constant_value (expr);
5076       /* Notice that there are constant expressions like '4 % 0' which
5077          do not fold into integer constants.  */
5078       if (TREE_CODE (expr) != INTEGER_CST)
5079         {
5080           if (complain & tf_error)
5081             error ("%qE is not a valid template argument for type %qT "
5082                    "because it is a non-constant expression", expr, type);
5083           return NULL_TREE;
5084         }
5085
5086       /* At this point, an implicit conversion does what we want,
5087          because we already know that the expression is of integral
5088          type.  */
5089       expr = perform_implicit_conversion (type, expr, complain);
5090       if (expr == error_mark_node)
5091         return error_mark_node;
5092
5093       /* Conversion was allowed: fold it to a bare integer constant.  */
5094       expr = fold (expr);
5095     }
5096   /* [temp.arg.nontype]/5, bullet 2
5097
5098      For a non-type template-parameter of type pointer to object,
5099      qualification conversions (_conv.qual_) and the array-to-pointer
5100      conversion (_conv.array_) are applied.  */
5101   else if (TYPE_PTROBV_P (type))
5102     {
5103       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5104
5105          A template-argument for a non-type, non-template template-parameter
5106          shall be one of: [...]
5107
5108          -- the name of a non-type template-parameter;
5109          -- the address of an object or function with external linkage, [...]
5110             expressed as "& id-expression" where the & is optional if the name
5111             refers to a function or array, or if the corresponding
5112             template-parameter is a reference.
5113
5114         Here, we do not care about functions, as they are invalid anyway
5115         for a parameter of type pointer-to-object.  */
5116
5117       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5118         /* Non-type template parameters are OK.  */
5119         ;
5120       else if (TREE_CODE (expr) != ADDR_EXPR
5121                && TREE_CODE (expr_type) != ARRAY_TYPE)
5122         {
5123           if (TREE_CODE (expr) == VAR_DECL)
5124             {
5125               error ("%qD is not a valid template argument "
5126                      "because %qD is a variable, not the address of "
5127                      "a variable",
5128                      expr, expr);
5129               return NULL_TREE;
5130             }
5131           /* Other values, like integer constants, might be valid
5132              non-type arguments of some other type.  */
5133           return error_mark_node;
5134         }
5135       else
5136         {
5137           tree decl;
5138
5139           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5140                   ? TREE_OPERAND (expr, 0) : expr);
5141           if (TREE_CODE (decl) != VAR_DECL)
5142             {
5143               error ("%qE is not a valid template argument of type %qT "
5144                      "because %qE is not a variable",
5145                      expr, type, decl);
5146               return NULL_TREE;
5147             }
5148           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5149             {
5150               error ("%qE is not a valid template argument of type %qT "
5151                      "because %qD does not have external linkage",
5152                      expr, type, decl);
5153               return NULL_TREE;
5154             }
5155         }
5156
5157       expr = decay_conversion (expr);
5158       if (expr == error_mark_node)
5159         return error_mark_node;
5160
5161       expr = perform_qualification_conversions (type, expr);
5162       if (expr == error_mark_node)
5163         return error_mark_node;
5164     }
5165   /* [temp.arg.nontype]/5, bullet 3
5166
5167      For a non-type template-parameter of type reference to object, no
5168      conversions apply. The type referred to by the reference may be more
5169      cv-qualified than the (otherwise identical) type of the
5170      template-argument. The template-parameter is bound directly to the
5171      template-argument, which must be an lvalue.  */
5172   else if (TYPE_REF_OBJ_P (type))
5173     {
5174       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5175                                                       expr_type))
5176         return error_mark_node;
5177
5178       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5179         {
5180           error ("%qE is not a valid template argument for type %qT "
5181                  "because of conflicts in cv-qualification", expr, type);
5182           return NULL_TREE;
5183         }
5184
5185       if (!real_lvalue_p (expr))
5186         {
5187           error ("%qE is not a valid template argument for type %qT "
5188                  "because it is not an lvalue", expr, type);
5189           return NULL_TREE;
5190         }
5191
5192       /* [temp.arg.nontype]/1
5193
5194          A template-argument for a non-type, non-template template-parameter
5195          shall be one of: [...]
5196
5197          -- the address of an object or function with external linkage.  */
5198       if (TREE_CODE (expr) == INDIRECT_REF
5199           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5200         {
5201           expr = TREE_OPERAND (expr, 0);
5202           if (DECL_P (expr))
5203             {
5204               error ("%q#D is not a valid template argument for type %qT "
5205                      "because a reference variable does not have a constant "
5206                      "address", expr, type);
5207               return NULL_TREE;
5208             }
5209         }
5210
5211       if (!DECL_P (expr))
5212         {
5213           error ("%qE is not a valid template argument for type %qT "
5214                  "because it is not an object with external linkage",
5215                  expr, type);
5216           return NULL_TREE;
5217         }
5218
5219       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5220         {
5221           error ("%qE is not a valid template argument for type %qT "
5222                  "because object %qD has not external linkage",
5223                  expr, type, expr);
5224           return NULL_TREE;
5225         }
5226
5227       expr = build_nop (type, build_address (expr));
5228     }
5229   /* [temp.arg.nontype]/5, bullet 4
5230
5231      For a non-type template-parameter of type pointer to function, only
5232      the function-to-pointer conversion (_conv.func_) is applied. If the
5233      template-argument represents a set of overloaded functions (or a
5234      pointer to such), the matching function is selected from the set
5235      (_over.over_).  */
5236   else if (TYPE_PTRFN_P (type))
5237     {
5238       /* If the argument is a template-id, we might not have enough
5239          context information to decay the pointer.  */
5240       if (!type_unknown_p (expr_type))
5241         {
5242           expr = decay_conversion (expr);
5243           if (expr == error_mark_node)
5244             return error_mark_node;
5245         }
5246
5247       expr = convert_nontype_argument_function (type, expr);
5248       if (!expr || expr == error_mark_node)
5249         return expr;
5250
5251       if (TREE_CODE (expr) != ADDR_EXPR)
5252         {
5253           error ("%qE is not a valid template argument for type %qT", expr, type);
5254           error ("it must be the address of a function with external linkage");
5255           return NULL_TREE;
5256         }
5257     }
5258   /* [temp.arg.nontype]/5, bullet 5
5259
5260      For a non-type template-parameter of type reference to function, no
5261      conversions apply. If the template-argument represents a set of
5262      overloaded functions, the matching function is selected from the set
5263      (_over.over_).  */
5264   else if (TYPE_REFFN_P (type))
5265     {
5266       if (TREE_CODE (expr) == ADDR_EXPR)
5267         {
5268           error ("%qE is not a valid template argument for type %qT "
5269                  "because it is a pointer", expr, type);
5270           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5271           return NULL_TREE;
5272         }
5273
5274       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5275       if (!expr || expr == error_mark_node)
5276         return expr;
5277
5278       expr = build_nop (type, build_address (expr));
5279     }
5280   /* [temp.arg.nontype]/5, bullet 6
5281
5282      For a non-type template-parameter of type pointer to member function,
5283      no conversions apply. If the template-argument represents a set of
5284      overloaded member functions, the matching member function is selected
5285      from the set (_over.over_).  */
5286   else if (TYPE_PTRMEMFUNC_P (type))
5287     {
5288       expr = instantiate_type (type, expr, tf_none);
5289       if (expr == error_mark_node)
5290         return error_mark_node;
5291
5292       /* [temp.arg.nontype] bullet 1 says the pointer to member
5293          expression must be a pointer-to-member constant.  */
5294       if (!check_valid_ptrmem_cst_expr (type, expr))
5295         return error_mark_node;
5296
5297       /* There is no way to disable standard conversions in
5298          resolve_address_of_overloaded_function (called by
5299          instantiate_type). It is possible that the call succeeded by
5300          converting &B::I to &D::I (where B is a base of D), so we need
5301          to reject this conversion here.
5302
5303          Actually, even if there was a way to disable standard conversions,
5304          it would still be better to reject them here so that we can
5305          provide a superior diagnostic.  */
5306       if (!same_type_p (TREE_TYPE (expr), type))
5307         {
5308           error ("%qE is not a valid template argument for type %qT "
5309                  "because it is of type %qT", expr, type,
5310                  TREE_TYPE (expr));
5311           /* If we are just one standard conversion off, explain.  */
5312           if (can_convert (type, TREE_TYPE (expr)))
5313             inform (input_location,
5314                     "standard conversions are not allowed in this context");
5315           return NULL_TREE;
5316         }
5317     }
5318   /* [temp.arg.nontype]/5, bullet 7
5319
5320      For a non-type template-parameter of type pointer to data member,
5321      qualification conversions (_conv.qual_) are applied.  */
5322   else if (TYPE_PTRMEM_P (type))
5323     {
5324       /* [temp.arg.nontype] bullet 1 says the pointer to member
5325          expression must be a pointer-to-member constant.  */
5326       if (!check_valid_ptrmem_cst_expr (type, expr))
5327         return error_mark_node;
5328
5329       expr = perform_qualification_conversions (type, expr);
5330       if (expr == error_mark_node)
5331         return expr;
5332     }
5333   /* A template non-type parameter must be one of the above.  */
5334   else
5335     gcc_unreachable ();
5336
5337   /* Sanity check: did we actually convert the argument to the
5338      right type?  */
5339   gcc_assert (same_type_ignoring_top_level_qualifiers_p
5340               (type, TREE_TYPE (expr)));
5341   return expr;
5342 }
5343
5344 /* Subroutine of coerce_template_template_parms, which returns 1 if
5345    PARM_PARM and ARG_PARM match using the rule for the template
5346    parameters of template template parameters. Both PARM and ARG are
5347    template parameters; the rest of the arguments are the same as for
5348    coerce_template_template_parms.
5349  */
5350 static int
5351 coerce_template_template_parm (tree parm,
5352                               tree arg,
5353                               tsubst_flags_t complain,
5354                               tree in_decl,
5355                               tree outer_args)
5356 {
5357   if (arg == NULL_TREE || arg == error_mark_node
5358       || parm == NULL_TREE || parm == error_mark_node)
5359     return 0;
5360   
5361   if (TREE_CODE (arg) != TREE_CODE (parm))
5362     return 0;
5363   
5364   switch (TREE_CODE (parm))
5365     {
5366     case TEMPLATE_DECL:
5367       /* We encounter instantiations of templates like
5368          template <template <template <class> class> class TT>
5369          class C;  */
5370       {
5371         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5372         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5373         
5374         if (!coerce_template_template_parms
5375             (parmparm, argparm, complain, in_decl, outer_args))
5376           return 0;
5377       }
5378       /* Fall through.  */
5379       
5380     case TYPE_DECL:
5381       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5382           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5383         /* Argument is a parameter pack but parameter is not.  */
5384         return 0;
5385       break;
5386       
5387     case PARM_DECL:
5388       /* The tsubst call is used to handle cases such as
5389          
5390            template <int> class C {};
5391            template <class T, template <T> class TT> class D {};
5392            D<int, C> d;
5393
5394          i.e. the parameter list of TT depends on earlier parameters.  */
5395       if (!uses_template_parms (TREE_TYPE (arg))
5396           && !same_type_p
5397                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5398                  TREE_TYPE (arg)))
5399         return 0;
5400       
5401       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5402           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5403         /* Argument is a parameter pack but parameter is not.  */
5404         return 0;
5405       
5406       break;
5407
5408     default:
5409       gcc_unreachable ();
5410     }
5411
5412   return 1;
5413 }
5414
5415
5416 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5417    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5418    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5419    or PARM_DECL.
5420
5421    Consider the example:
5422      template <class T> class A;
5423      template<template <class U> class TT> class B;
5424
5425    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5426    the parameters to A, and OUTER_ARGS contains A.  */
5427
5428 static int
5429 coerce_template_template_parms (tree parm_parms,
5430                                 tree arg_parms,
5431                                 tsubst_flags_t complain,
5432                                 tree in_decl,
5433                                 tree outer_args)
5434 {
5435   int nparms, nargs, i;
5436   tree parm, arg;
5437   int variadic_p = 0;
5438
5439   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5440   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5441
5442   nparms = TREE_VEC_LENGTH (parm_parms);
5443   nargs = TREE_VEC_LENGTH (arg_parms);
5444
5445   /* Determine whether we have a parameter pack at the end of the
5446      template template parameter's template parameter list.  */
5447   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5448     {
5449       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5450       
5451       if (parm == error_mark_node)
5452         return 0;
5453
5454       switch (TREE_CODE (parm))
5455         {
5456         case TEMPLATE_DECL:
5457         case TYPE_DECL:
5458           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5459             variadic_p = 1;
5460           break;
5461           
5462         case PARM_DECL:
5463           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5464             variadic_p = 1;
5465           break;
5466           
5467         default:
5468           gcc_unreachable ();
5469         }
5470     }
5471  
5472   if (nargs != nparms
5473       && !(variadic_p && nargs >= nparms - 1))
5474     return 0;
5475
5476   /* Check all of the template parameters except the parameter pack at
5477      the end (if any).  */
5478   for (i = 0; i < nparms - variadic_p; ++i)
5479     {
5480       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5481           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5482         continue;
5483
5484       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5485       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5486
5487       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5488                                           outer_args))
5489         return 0;
5490
5491     }
5492
5493   if (variadic_p)
5494     {
5495       /* Check each of the template parameters in the template
5496          argument against the template parameter pack at the end of
5497          the template template parameter.  */
5498       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5499         return 0;
5500
5501       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5502
5503       for (; i < nargs; ++i)
5504         {
5505           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5506             continue;
5507  
5508           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5509  
5510           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5511                                               outer_args))
5512             return 0;
5513         }
5514     }
5515
5516   return 1;
5517 }
5518
5519 /* Verifies that the deduced template arguments (in TARGS) for the
5520    template template parameters (in TPARMS) represent valid bindings,
5521    by comparing the template parameter list of each template argument
5522    to the template parameter list of its corresponding template
5523    template parameter, in accordance with DR150. This
5524    routine can only be called after all template arguments have been
5525    deduced. It will return TRUE if all of the template template
5526    parameter bindings are okay, FALSE otherwise.  */
5527 bool 
5528 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5529 {
5530   int i, ntparms = TREE_VEC_LENGTH (tparms);
5531   bool ret = true;
5532
5533   /* We're dealing with template parms in this process.  */
5534   ++processing_template_decl;
5535
5536   targs = INNERMOST_TEMPLATE_ARGS (targs);
5537
5538   for (i = 0; i < ntparms; ++i)
5539     {
5540       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5541       tree targ = TREE_VEC_ELT (targs, i);
5542
5543       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5544         {
5545           tree packed_args = NULL_TREE;
5546           int idx, len = 1;
5547
5548           if (ARGUMENT_PACK_P (targ))
5549             {
5550               /* Look inside the argument pack.  */
5551               packed_args = ARGUMENT_PACK_ARGS (targ);
5552               len = TREE_VEC_LENGTH (packed_args);
5553             }
5554
5555           for (idx = 0; idx < len; ++idx)
5556             {
5557               tree targ_parms = NULL_TREE;
5558
5559               if (packed_args)
5560                 /* Extract the next argument from the argument
5561                    pack.  */
5562                 targ = TREE_VEC_ELT (packed_args, idx);
5563
5564               if (PACK_EXPANSION_P (targ))
5565                 /* Look at the pattern of the pack expansion.  */
5566                 targ = PACK_EXPANSION_PATTERN (targ);
5567
5568               /* Extract the template parameters from the template
5569                  argument.  */
5570               if (TREE_CODE (targ) == TEMPLATE_DECL)
5571                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5572               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5573                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5574
5575               /* Verify that we can coerce the template template
5576                  parameters from the template argument to the template
5577                  parameter.  This requires an exact match.  */
5578               if (targ_parms
5579                   && !coerce_template_template_parms
5580                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5581                         targ_parms,
5582                         tf_none,
5583                         tparm,
5584                         targs))
5585                 {
5586                   ret = false;
5587                   goto out;
5588                 }
5589             }
5590         }
5591     }
5592
5593  out:
5594
5595   --processing_template_decl;
5596   return ret;
5597 }
5598
5599 /* Convert the indicated template ARG as necessary to match the
5600    indicated template PARM.  Returns the converted ARG, or
5601    error_mark_node if the conversion was unsuccessful.  Error and
5602    warning messages are issued under control of COMPLAIN.  This
5603    conversion is for the Ith parameter in the parameter list.  ARGS is
5604    the full set of template arguments deduced so far.  */
5605
5606 static tree
5607 convert_template_argument (tree parm,
5608                            tree arg,
5609                            tree args,
5610                            tsubst_flags_t complain,
5611                            int i,
5612                            tree in_decl)
5613 {
5614   tree orig_arg;
5615   tree val;
5616   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5617
5618   if (TREE_CODE (arg) == TREE_LIST
5619       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5620     {
5621       /* The template argument was the name of some
5622          member function.  That's usually
5623          invalid, but static members are OK.  In any
5624          case, grab the underlying fields/functions
5625          and issue an error later if required.  */
5626       orig_arg = TREE_VALUE (arg);
5627       TREE_TYPE (arg) = unknown_type_node;
5628     }
5629
5630   orig_arg = arg;
5631
5632   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5633   requires_type = (TREE_CODE (parm) == TYPE_DECL
5634                    || requires_tmpl_type);
5635
5636   /* When determining whether an argument pack expansion is a template,
5637      look at the pattern.  */
5638   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5639     arg = PACK_EXPANSION_PATTERN (arg);
5640
5641   /* Deal with an injected-class-name used as a template template arg.  */
5642   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5643     {
5644       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5645       if (TREE_CODE (t) == TEMPLATE_DECL)
5646         {
5647           if (complain & tf_warning_or_error)
5648             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5649                      " used as template template argument", TYPE_NAME (arg));
5650           else if (flag_pedantic_errors)
5651             t = arg;
5652
5653           arg = t;
5654         }
5655     }
5656
5657   is_tmpl_type = 
5658     ((TREE_CODE (arg) == TEMPLATE_DECL
5659       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5660      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5661      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5662
5663   if (is_tmpl_type
5664       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5665           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5666     arg = TYPE_STUB_DECL (arg);
5667
5668   is_type = TYPE_P (arg) || is_tmpl_type;
5669
5670   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5671       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5672     {
5673       permerror (input_location, "to refer to a type member of a template parameter, "
5674                  "use %<typename %E%>", orig_arg);
5675
5676       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5677                                      TREE_OPERAND (arg, 1),
5678                                      typename_type,
5679                                      complain & tf_error);
5680       arg = orig_arg;
5681       is_type = 1;
5682     }
5683   if (is_type != requires_type)
5684     {
5685       if (in_decl)
5686         {
5687           if (complain & tf_error)
5688             {
5689               error ("type/value mismatch at argument %d in template "
5690                      "parameter list for %qD",
5691                      i + 1, in_decl);
5692               if (is_type)
5693                 error ("  expected a constant of type %qT, got %qT",
5694                        TREE_TYPE (parm),
5695                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5696               else if (requires_tmpl_type)
5697                 error ("  expected a class template, got %qE", orig_arg);
5698               else
5699                 error ("  expected a type, got %qE", orig_arg);
5700             }
5701         }
5702       return error_mark_node;
5703     }
5704   if (is_tmpl_type ^ requires_tmpl_type)
5705     {
5706       if (in_decl && (complain & tf_error))
5707         {
5708           error ("type/value mismatch at argument %d in template "
5709                  "parameter list for %qD",
5710                  i + 1, in_decl);
5711           if (is_tmpl_type)
5712             error ("  expected a type, got %qT", DECL_NAME (arg));
5713           else
5714             error ("  expected a class template, got %qT", orig_arg);
5715         }
5716       return error_mark_node;
5717     }
5718
5719   if (is_type)
5720     {
5721       if (requires_tmpl_type)
5722         {
5723           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5724             /* The number of argument required is not known yet.
5725                Just accept it for now.  */
5726             val = TREE_TYPE (arg);
5727           else
5728             {
5729               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5730               tree argparm;
5731
5732               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5733
5734               if (coerce_template_template_parms (parmparm, argparm,
5735                                                   complain, in_decl,
5736                                                   args))
5737                 {
5738                   val = arg;
5739
5740                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5741                      TEMPLATE_DECL.  */
5742                   if (val != error_mark_node)
5743                     {
5744                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5745                         val = TREE_TYPE (val);
5746                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
5747                         val = make_pack_expansion (val);
5748                     }
5749                 }
5750               else
5751                 {
5752                   if (in_decl && (complain & tf_error))
5753                     {
5754                       error ("type/value mismatch at argument %d in "
5755                              "template parameter list for %qD",
5756                              i + 1, in_decl);
5757                       error ("  expected a template of type %qD, got %qT",
5758                              parm, orig_arg);
5759                     }
5760
5761                   val = error_mark_node;
5762                 }
5763             }
5764         }
5765       else
5766         val = orig_arg;
5767       /* We only form one instance of each template specialization.
5768          Therefore, if we use a non-canonical variant (i.e., a
5769          typedef), any future messages referring to the type will use
5770          the typedef, which is confusing if those future uses do not
5771          themselves also use the typedef.  */
5772       if (TYPE_P (val))
5773         val = strip_typedefs (val);
5774     }
5775   else
5776     {
5777       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5778
5779       if (invalid_nontype_parm_type_p (t, complain))
5780         return error_mark_node;
5781
5782       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5783         {
5784           if (same_type_p (t, TREE_TYPE (orig_arg)))
5785             val = orig_arg;
5786           else
5787             {
5788               /* Not sure if this is reachable, but it doesn't hurt
5789                  to be robust.  */
5790               error ("type mismatch in nontype parameter pack");
5791               val = error_mark_node;
5792             }
5793         }
5794       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5795         /* We used to call digest_init here.  However, digest_init
5796            will report errors, which we don't want when complain
5797            is zero.  More importantly, digest_init will try too
5798            hard to convert things: for example, `0' should not be
5799            converted to pointer type at this point according to
5800            the standard.  Accepting this is not merely an
5801            extension, since deciding whether or not these
5802            conversions can occur is part of determining which
5803            function template to call, or whether a given explicit
5804            argument specification is valid.  */
5805         val = convert_nontype_argument (t, orig_arg, complain);
5806       else
5807         val = orig_arg;
5808
5809       if (val == NULL_TREE)
5810         val = error_mark_node;
5811       else if (val == error_mark_node && (complain & tf_error))
5812         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5813
5814       if (TREE_CODE (val) == SCOPE_REF)
5815         {
5816           /* Strip typedefs from the SCOPE_REF.  */
5817           tree type = strip_typedefs (TREE_TYPE (val));
5818           tree scope = strip_typedefs (TREE_OPERAND (val, 0));
5819           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
5820                                       QUALIFIED_NAME_IS_TEMPLATE (val));
5821         }
5822     }
5823
5824   return val;
5825 }
5826
5827 /* Coerces the remaining template arguments in INNER_ARGS (from
5828    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5829    Returns the coerced argument pack. PARM_IDX is the position of this
5830    parameter in the template parameter list. ARGS is the original
5831    template argument list.  */
5832 static tree
5833 coerce_template_parameter_pack (tree parms,
5834                                 int parm_idx,
5835                                 tree args,
5836                                 tree inner_args,
5837                                 int arg_idx,
5838                                 tree new_args,
5839                                 int* lost,
5840                                 tree in_decl,
5841                                 tsubst_flags_t complain)
5842 {
5843   tree parm = TREE_VEC_ELT (parms, parm_idx);
5844   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5845   tree packed_args;
5846   tree argument_pack;
5847   tree packed_types = NULL_TREE;
5848
5849   if (arg_idx > nargs)
5850     arg_idx = nargs;
5851
5852   packed_args = make_tree_vec (nargs - arg_idx);
5853
5854   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5855       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5856     {
5857       /* When the template parameter is a non-type template
5858          parameter pack whose type uses parameter packs, we need
5859          to look at each of the template arguments
5860          separately. Build a vector of the types for these
5861          non-type template parameters in PACKED_TYPES.  */
5862       tree expansion 
5863         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5864       packed_types = tsubst_pack_expansion (expansion, args,
5865                                             complain, in_decl);
5866
5867       if (packed_types == error_mark_node)
5868         return error_mark_node;
5869
5870       /* Check that we have the right number of arguments.  */
5871       if (arg_idx < nargs
5872           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5873           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5874         {
5875           int needed_parms 
5876             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5877           error ("wrong number of template arguments (%d, should be %d)",
5878                  nargs, needed_parms);
5879           return error_mark_node;
5880         }
5881
5882       /* If we aren't able to check the actual arguments now
5883          (because they haven't been expanded yet), we can at least
5884          verify that all of the types used for the non-type
5885          template parameter pack are, in fact, valid for non-type
5886          template parameters.  */
5887       if (arg_idx < nargs 
5888           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5889         {
5890           int j, len = TREE_VEC_LENGTH (packed_types);
5891           for (j = 0; j < len; ++j)
5892             {
5893               tree t = TREE_VEC_ELT (packed_types, j);
5894               if (invalid_nontype_parm_type_p (t, complain))
5895                 return error_mark_node;
5896             }
5897         }
5898     }
5899
5900   /* Convert the remaining arguments, which will be a part of the
5901      parameter pack "parm".  */
5902   for (; arg_idx < nargs; ++arg_idx)
5903     {
5904       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5905       tree actual_parm = TREE_VALUE (parm);
5906
5907       if (packed_types && !PACK_EXPANSION_P (arg))
5908         {
5909           /* When we have a vector of types (corresponding to the
5910              non-type template parameter pack that uses parameter
5911              packs in its type, as mention above), and the
5912              argument is not an expansion (which expands to a
5913              currently unknown number of arguments), clone the
5914              parm and give it the next type in PACKED_TYPES.  */
5915           actual_parm = copy_node (actual_parm);
5916           TREE_TYPE (actual_parm) = 
5917             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5918         }
5919
5920       if (arg != error_mark_node)
5921         arg = convert_template_argument (actual_parm, 
5922                                          arg, new_args, complain, parm_idx,
5923                                          in_decl);
5924       if (arg == error_mark_node)
5925         (*lost)++;
5926       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5927     }
5928
5929   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5930       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5931     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5932   else
5933     {
5934       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5935       TREE_TYPE (argument_pack) 
5936         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5937       TREE_CONSTANT (argument_pack) = 1;
5938     }
5939
5940   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5941 #ifdef ENABLE_CHECKING
5942   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
5943                                        TREE_VEC_LENGTH (packed_args));
5944 #endif
5945   return argument_pack;
5946 }
5947
5948 /* Convert all template arguments to their appropriate types, and
5949    return a vector containing the innermost resulting template
5950    arguments.  If any error occurs, return error_mark_node. Error and
5951    warning messages are issued under control of COMPLAIN.
5952
5953    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5954    for arguments not specified in ARGS.  Otherwise, if
5955    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5956    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5957    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5958    ARGS.  */
5959
5960 static tree
5961 coerce_template_parms (tree parms,
5962                        tree args,
5963                        tree in_decl,
5964                        tsubst_flags_t complain,
5965                        bool require_all_args,
5966                        bool use_default_args)
5967 {
5968   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5969   tree inner_args;
5970   tree new_args;
5971   tree new_inner_args;
5972   int saved_unevaluated_operand;
5973   int saved_inhibit_evaluation_warnings;
5974
5975   /* When used as a boolean value, indicates whether this is a
5976      variadic template parameter list. Since it's an int, we can also
5977      subtract it from nparms to get the number of non-variadic
5978      parameters.  */
5979   int variadic_p = 0;
5980
5981   if (args == error_mark_node)
5982     return error_mark_node;
5983
5984   nparms = TREE_VEC_LENGTH (parms);
5985
5986   /* Determine if there are any parameter packs.  */
5987   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5988     {
5989       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5990       if (template_parameter_pack_p (tparm))
5991         ++variadic_p;
5992     }
5993
5994   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5995   /* If there are 0 or 1 parameter packs, we need to expand any argument
5996      packs so that we can deduce a parameter pack from some non-packed args
5997      followed by an argument pack, as in variadic85.C.  If there are more
5998      than that, we need to leave argument packs intact so the arguments are
5999      assigned to the right parameter packs.  This should only happen when
6000      dealing with a nested class inside a partial specialization of a class
6001      template, as in variadic92.C.  */
6002   if (variadic_p <= 1)
6003     inner_args = expand_template_argument_pack (inner_args);
6004
6005   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6006   if ((nargs > nparms && !variadic_p)
6007       || (nargs < nparms - variadic_p
6008           && require_all_args
6009           && (!use_default_args
6010               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6011                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6012     {
6013       if (complain & tf_error)
6014         {
6015           if (variadic_p)
6016             {
6017               --nparms;
6018               error ("wrong number of template arguments "
6019                      "(%d, should be %d or more)", nargs, nparms);
6020             }
6021           else
6022              error ("wrong number of template arguments "
6023                     "(%d, should be %d)", nargs, nparms);
6024
6025           if (in_decl)
6026             error ("provided for %q+D", in_decl);
6027         }
6028
6029       return error_mark_node;
6030     }
6031
6032   /* We need to evaluate the template arguments, even though this
6033      template-id may be nested within a "sizeof".  */
6034   saved_unevaluated_operand = cp_unevaluated_operand;
6035   cp_unevaluated_operand = 0;
6036   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6037   c_inhibit_evaluation_warnings = 0;
6038   new_inner_args = make_tree_vec (nparms);
6039   new_args = add_outermost_template_args (args, new_inner_args);
6040   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6041     {
6042       tree arg;
6043       tree parm;
6044
6045       /* Get the Ith template parameter.  */
6046       parm = TREE_VEC_ELT (parms, parm_idx);
6047  
6048       if (parm == error_mark_node)
6049       {
6050         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6051         continue;
6052       }
6053
6054       /* Calculate the next argument.  */
6055       if (arg_idx < nargs)
6056         arg = TREE_VEC_ELT (inner_args, arg_idx);
6057       else
6058         arg = NULL_TREE;
6059
6060       if (template_parameter_pack_p (TREE_VALUE (parm))
6061           && !(arg && ARGUMENT_PACK_P (arg)))
6062         {
6063           /* All remaining arguments will be placed in the
6064              template parameter pack PARM.  */
6065           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6066                                                 inner_args, arg_idx,
6067                                                 new_args, &lost,
6068                                                 in_decl, complain);
6069
6070           /* Store this argument.  */
6071           if (arg == error_mark_node)
6072             lost++;
6073           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6074
6075           /* We are done with all of the arguments.  */
6076           arg_idx = nargs;
6077           
6078           continue;
6079         }
6080       else if (arg)
6081         {
6082           if (PACK_EXPANSION_P (arg))
6083             {
6084               if (complain & tf_error)
6085                 {
6086                   /* FIXME this restriction was removed by N2555; see
6087                      bug 35722.  */
6088                   /* If ARG is a pack expansion, but PARM is not a
6089                      template parameter pack (if it were, we would have
6090                      handled it above), we're trying to expand into a
6091                      fixed-length argument list.  */
6092                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
6093                     sorry ("cannot expand %<%E%> into a fixed-length "
6094                            "argument list", arg);
6095                   else
6096                     sorry ("cannot expand %<%T%> into a fixed-length "
6097                            "argument list", arg);
6098                 }
6099               return error_mark_node;
6100             }
6101         }
6102       else if (require_all_args)
6103         {
6104           /* There must be a default arg in this case.  */
6105           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6106                                      complain, in_decl);
6107           /* The position of the first default template argument,
6108              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6109              Record that.  */
6110           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6111             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6112         }
6113       else
6114         break;
6115
6116       if (arg == error_mark_node)
6117         {
6118           if (complain & tf_error)
6119             error ("template argument %d is invalid", arg_idx + 1);
6120         }
6121       else if (!arg)
6122         /* This only occurs if there was an error in the template
6123            parameter list itself (which we would already have
6124            reported) that we are trying to recover from, e.g., a class
6125            template with a parameter list such as
6126            template<typename..., typename>.  */
6127         return error_mark_node;
6128       else
6129         arg = convert_template_argument (TREE_VALUE (parm),
6130                                          arg, new_args, complain, 
6131                                          parm_idx, in_decl);
6132
6133       if (arg == error_mark_node)
6134         lost++;
6135       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6136     }
6137   cp_unevaluated_operand = saved_unevaluated_operand;
6138   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6139
6140   if (lost)
6141     return error_mark_node;
6142
6143 #ifdef ENABLE_CHECKING
6144   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6145     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6146                                          TREE_VEC_LENGTH (new_inner_args));
6147 #endif
6148
6149   return new_inner_args;
6150 }
6151
6152 /* Returns 1 if template args OT and NT are equivalent.  */
6153
6154 static int
6155 template_args_equal (tree ot, tree nt)
6156 {
6157   if (nt == ot)
6158     return 1;
6159
6160   if (TREE_CODE (nt) == TREE_VEC)
6161     /* For member templates */
6162     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6163   else if (PACK_EXPANSION_P (ot))
6164     return PACK_EXPANSION_P (nt) 
6165       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6166                               PACK_EXPANSION_PATTERN (nt));
6167   else if (ARGUMENT_PACK_P (ot))
6168     {
6169       int i, len;
6170       tree opack, npack;
6171
6172       if (!ARGUMENT_PACK_P (nt))
6173         return 0;
6174
6175       opack = ARGUMENT_PACK_ARGS (ot);
6176       npack = ARGUMENT_PACK_ARGS (nt);
6177       len = TREE_VEC_LENGTH (opack);
6178       if (TREE_VEC_LENGTH (npack) != len)
6179         return 0;
6180       for (i = 0; i < len; ++i)
6181         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6182                                   TREE_VEC_ELT (npack, i)))
6183           return 0;
6184       return 1;
6185     }
6186   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6187     {
6188       /* We get here probably because we are in the middle of substituting
6189          into the pattern of a pack expansion. In that case the
6190          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6191          interested in. So we want to use the initial pack argument for
6192          the comparison.  */
6193       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6194       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6195         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6196       return template_args_equal (ot, nt);
6197     }
6198   else if (TYPE_P (nt))
6199     return TYPE_P (ot) && same_type_p (ot, nt);
6200   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6201     return 0;
6202   else
6203     return cp_tree_equal (ot, nt);
6204 }
6205
6206 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6207    of template arguments.  Returns 0 otherwise.  */
6208
6209 int
6210 comp_template_args (tree oldargs, tree newargs)
6211 {
6212   int i;
6213
6214   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6215     return 0;
6216
6217   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6218     {
6219       tree nt = TREE_VEC_ELT (newargs, i);
6220       tree ot = TREE_VEC_ELT (oldargs, i);
6221
6222       if (! template_args_equal (ot, nt))
6223         return 0;
6224     }
6225   return 1;
6226 }
6227
6228 static void
6229 add_pending_template (tree d)
6230 {
6231   tree ti = (TYPE_P (d)
6232              ? CLASSTYPE_TEMPLATE_INFO (d)
6233              : DECL_TEMPLATE_INFO (d));
6234   struct pending_template *pt;
6235   int level;
6236
6237   if (TI_PENDING_TEMPLATE_FLAG (ti))
6238     return;
6239
6240   /* We are called both from instantiate_decl, where we've already had a
6241      tinst_level pushed, and instantiate_template, where we haven't.
6242      Compensate.  */
6243   level = !current_tinst_level || current_tinst_level->decl != d;
6244
6245   if (level)
6246     push_tinst_level (d);
6247
6248   pt = ggc_alloc_pending_template ();
6249   pt->next = NULL;
6250   pt->tinst = current_tinst_level;
6251   if (last_pending_template)
6252     last_pending_template->next = pt;
6253   else
6254     pending_templates = pt;
6255
6256   last_pending_template = pt;
6257
6258   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6259
6260   if (level)
6261     pop_tinst_level ();
6262 }
6263
6264
6265 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6266    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6267    documentation for TEMPLATE_ID_EXPR.  */
6268
6269 tree
6270 lookup_template_function (tree fns, tree arglist)
6271 {
6272   tree type;
6273
6274   if (fns == error_mark_node || arglist == error_mark_node)
6275     return error_mark_node;
6276
6277   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6278   gcc_assert (fns && (is_overloaded_fn (fns)
6279                       || TREE_CODE (fns) == IDENTIFIER_NODE));
6280
6281   if (BASELINK_P (fns))
6282     {
6283       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6284                                          unknown_type_node,
6285                                          BASELINK_FUNCTIONS (fns),
6286                                          arglist);
6287       return fns;
6288     }
6289
6290   type = TREE_TYPE (fns);
6291   if (TREE_CODE (fns) == OVERLOAD || !type)
6292     type = unknown_type_node;
6293
6294   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6295 }
6296
6297 /* Within the scope of a template class S<T>, the name S gets bound
6298    (in build_self_reference) to a TYPE_DECL for the class, not a
6299    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6300    or one of its enclosing classes, and that type is a template,
6301    return the associated TEMPLATE_DECL.  Otherwise, the original
6302    DECL is returned.
6303
6304    Also handle the case when DECL is a TREE_LIST of ambiguous
6305    injected-class-names from different bases.  */
6306
6307 tree
6308 maybe_get_template_decl_from_type_decl (tree decl)
6309 {
6310   if (decl == NULL_TREE)
6311     return decl;
6312
6313   /* DR 176: A lookup that finds an injected-class-name (10.2
6314      [class.member.lookup]) can result in an ambiguity in certain cases
6315      (for example, if it is found in more than one base class). If all of
6316      the injected-class-names that are found refer to specializations of
6317      the same class template, and if the name is followed by a
6318      template-argument-list, the reference refers to the class template
6319      itself and not a specialization thereof, and is not ambiguous.  */
6320   if (TREE_CODE (decl) == TREE_LIST)
6321     {
6322       tree t, tmpl = NULL_TREE;
6323       for (t = decl; t; t = TREE_CHAIN (t))
6324         {
6325           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6326           if (!tmpl)
6327             tmpl = elt;
6328           else if (tmpl != elt)
6329             break;
6330         }
6331       if (tmpl && t == NULL_TREE)
6332         return tmpl;
6333       else
6334         return decl;
6335     }
6336
6337   return (decl != NULL_TREE
6338           && DECL_SELF_REFERENCE_P (decl)
6339           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6340     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6341 }
6342
6343 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6344    parameters, find the desired type.
6345
6346    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6347
6348    IN_DECL, if non-NULL, is the template declaration we are trying to
6349    instantiate.
6350
6351    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6352    the class we are looking up.
6353
6354    Issue error and warning messages under control of COMPLAIN.
6355
6356    If the template class is really a local class in a template
6357    function, then the FUNCTION_CONTEXT is the function in which it is
6358    being instantiated.
6359
6360    ??? Note that this function is currently called *twice* for each
6361    template-id: the first time from the parser, while creating the
6362    incomplete type (finish_template_type), and the second type during the
6363    real instantiation (instantiate_template_class). This is surely something
6364    that we want to avoid. It also causes some problems with argument
6365    coercion (see convert_nontype_argument for more information on this).  */
6366
6367 tree
6368 lookup_template_class (tree d1,
6369                        tree arglist,
6370                        tree in_decl,
6371                        tree context,
6372                        int entering_scope,
6373                        tsubst_flags_t complain)
6374 {
6375   tree templ = NULL_TREE, parmlist;
6376   tree t;
6377   spec_entry **slot;
6378   spec_entry *entry;
6379   spec_entry elt;
6380   hashval_t hash;
6381
6382   timevar_push (TV_NAME_LOOKUP);
6383
6384   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6385     {
6386       tree value = innermost_non_namespace_value (d1);
6387       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6388         templ = value;
6389       else
6390         {
6391           if (context)
6392             push_decl_namespace (context);
6393           templ = lookup_name (d1);
6394           templ = maybe_get_template_decl_from_type_decl (templ);
6395           if (context)
6396             pop_decl_namespace ();
6397         }
6398       if (templ)
6399         context = DECL_CONTEXT (templ);
6400     }
6401   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6402     {
6403       tree type = TREE_TYPE (d1);
6404
6405       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6406          an implicit typename for the second A.  Deal with it.  */
6407       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6408         type = TREE_TYPE (type);
6409
6410       if (CLASSTYPE_TEMPLATE_INFO (type))
6411         {
6412           templ = CLASSTYPE_TI_TEMPLATE (type);
6413           d1 = DECL_NAME (templ);
6414         }
6415     }
6416   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6417            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6418     {
6419       templ = TYPE_TI_TEMPLATE (d1);
6420       d1 = DECL_NAME (templ);
6421     }
6422   else if (TREE_CODE (d1) == TEMPLATE_DECL
6423            && DECL_TEMPLATE_RESULT (d1)
6424            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6425     {
6426       templ = d1;
6427       d1 = DECL_NAME (templ);
6428       context = DECL_CONTEXT (templ);
6429     }
6430
6431   /* Issue an error message if we didn't find a template.  */
6432   if (! templ)
6433     {
6434       if (complain & tf_error)
6435         error ("%qT is not a template", d1);
6436       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6437     }
6438
6439   if (TREE_CODE (templ) != TEMPLATE_DECL
6440          /* Make sure it's a user visible template, if it was named by
6441             the user.  */
6442       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6443           && !PRIMARY_TEMPLATE_P (templ)))
6444     {
6445       if (complain & tf_error)
6446         {
6447           error ("non-template type %qT used as a template", d1);
6448           if (in_decl)
6449             error ("for template declaration %q+D", in_decl);
6450         }
6451       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6452     }
6453
6454   complain &= ~tf_user;
6455
6456   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6457     {
6458       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6459          template arguments */
6460
6461       tree parm;
6462       tree arglist2;
6463       tree outer;
6464
6465       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6466
6467       /* Consider an example where a template template parameter declared as
6468
6469            template <class T, class U = std::allocator<T> > class TT
6470
6471          The template parameter level of T and U are one level larger than
6472          of TT.  To proper process the default argument of U, say when an
6473          instantiation `TT<int>' is seen, we need to build the full
6474          arguments containing {int} as the innermost level.  Outer levels,
6475          available when not appearing as default template argument, can be
6476          obtained from the arguments of the enclosing template.
6477
6478          Suppose that TT is later substituted with std::vector.  The above
6479          instantiation is `TT<int, std::allocator<T> >' with TT at
6480          level 1, and T at level 2, while the template arguments at level 1
6481          becomes {std::vector} and the inner level 2 is {int}.  */
6482
6483       outer = DECL_CONTEXT (templ);
6484       if (outer)
6485         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6486       else if (current_template_parms)
6487         /* This is an argument of the current template, so we haven't set
6488            DECL_CONTEXT yet.  */
6489         outer = current_template_args ();
6490
6491       if (outer)
6492         arglist = add_to_template_args (outer, arglist);
6493
6494       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6495                                         complain,
6496                                         /*require_all_args=*/true,
6497                                         /*use_default_args=*/true);
6498       if (arglist2 == error_mark_node
6499           || (!uses_template_parms (arglist2)
6500               && check_instantiated_args (templ, arglist2, complain)))
6501         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6502
6503       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6504       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6505     }
6506   else
6507     {
6508       tree template_type = TREE_TYPE (templ);
6509       tree gen_tmpl;
6510       tree type_decl;
6511       tree found = NULL_TREE;
6512       int arg_depth;
6513       int parm_depth;
6514       int is_dependent_type;
6515       int use_partial_inst_tmpl = false;
6516
6517       gen_tmpl = most_general_template (templ);
6518       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6519       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6520       arg_depth = TMPL_ARGS_DEPTH (arglist);
6521
6522       if (arg_depth == 1 && parm_depth > 1)
6523         {
6524           /* We've been given an incomplete set of template arguments.
6525              For example, given:
6526
6527                template <class T> struct S1 {
6528                  template <class U> struct S2 {};
6529                  template <class U> struct S2<U*> {};
6530                 };
6531
6532              we will be called with an ARGLIST of `U*', but the
6533              TEMPLATE will be `template <class T> template
6534              <class U> struct S1<T>::S2'.  We must fill in the missing
6535              arguments.  */
6536           arglist
6537             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6538                                            arglist);
6539           arg_depth = TMPL_ARGS_DEPTH (arglist);
6540         }
6541
6542       /* Now we should have enough arguments.  */
6543       gcc_assert (parm_depth == arg_depth);
6544
6545       /* From here on, we're only interested in the most general
6546          template.  */
6547
6548       /* Calculate the BOUND_ARGS.  These will be the args that are
6549          actually tsubst'd into the definition to create the
6550          instantiation.  */
6551       if (parm_depth > 1)
6552         {
6553           /* We have multiple levels of arguments to coerce, at once.  */
6554           int i;
6555           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6556
6557           tree bound_args = make_tree_vec (parm_depth);
6558
6559           for (i = saved_depth,
6560                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6561                i > 0 && t != NULL_TREE;
6562                --i, t = TREE_CHAIN (t))
6563             {
6564               tree a;
6565               if (i == saved_depth)
6566                 a = coerce_template_parms (TREE_VALUE (t),
6567                                            arglist, gen_tmpl,
6568                                            complain,
6569                                            /*require_all_args=*/true,
6570                                            /*use_default_args=*/true);
6571               else
6572                 /* Outer levels should have already been coerced.  */
6573                 a = TMPL_ARGS_LEVEL (arglist, i);
6574
6575               /* Don't process further if one of the levels fails.  */
6576               if (a == error_mark_node)
6577                 {
6578                   /* Restore the ARGLIST to its full size.  */
6579                   TREE_VEC_LENGTH (arglist) = saved_depth;
6580                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6581                 }
6582
6583               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6584
6585               /* We temporarily reduce the length of the ARGLIST so
6586                  that coerce_template_parms will see only the arguments
6587                  corresponding to the template parameters it is
6588                  examining.  */
6589               TREE_VEC_LENGTH (arglist)--;
6590             }
6591
6592           /* Restore the ARGLIST to its full size.  */
6593           TREE_VEC_LENGTH (arglist) = saved_depth;
6594
6595           arglist = bound_args;
6596         }
6597       else
6598         {
6599           push_tinst_level (templ);
6600           arglist
6601             = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6602                                      INNERMOST_TEMPLATE_ARGS (arglist),
6603                                      gen_tmpl,
6604                                      complain,
6605                                      /*require_all_args=*/true,
6606                                      /*use_default_args=*/true);
6607           pop_tinst_level ();
6608         }
6609
6610       if (arglist == error_mark_node)
6611         /* We were unable to bind the arguments.  */
6612         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6613
6614       /* In the scope of a template class, explicit references to the
6615          template class refer to the type of the template, not any
6616          instantiation of it.  For example, in:
6617
6618            template <class T> class C { void f(C<T>); }
6619
6620          the `C<T>' is just the same as `C'.  Outside of the
6621          class, however, such a reference is an instantiation.  */
6622       if ((entering_scope
6623            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6624            || currently_open_class (template_type))
6625           /* comp_template_args is expensive, check it last.  */
6626           && comp_template_args (TYPE_TI_ARGS (template_type),
6627                                  arglist))
6628         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6629
6630       /* If we already have this specialization, return it.  */
6631       elt.tmpl = gen_tmpl;
6632       elt.args = arglist;
6633       hash = hash_specialization (&elt);
6634       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6635                                                   &elt, hash);
6636
6637       if (entry)
6638         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6639
6640       is_dependent_type = uses_template_parms (arglist);
6641
6642       /* If the deduced arguments are invalid, then the binding
6643          failed.  */
6644       if (!is_dependent_type
6645           && check_instantiated_args (gen_tmpl,
6646                                       INNERMOST_TEMPLATE_ARGS (arglist),
6647                                       complain))
6648         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6649
6650       if (!is_dependent_type
6651           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6652           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6653           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6654         {
6655           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6656                                       DECL_NAME (gen_tmpl),
6657                                       /*tag_scope=*/ts_global);
6658           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6659         }
6660
6661       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6662                         complain, in_decl);
6663       if (!context)
6664         context = global_namespace;
6665
6666       /* Create the type.  */
6667       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6668         {
6669           if (!is_dependent_type)
6670             {
6671               set_current_access_from_decl (TYPE_NAME (template_type));
6672               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
6673                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6674                                       arglist, complain, in_decl),
6675                               SCOPED_ENUM_P (template_type), NULL);
6676             }
6677           else
6678             {
6679               /* We don't want to call start_enum for this type, since
6680                  the values for the enumeration constants may involve
6681                  template parameters.  And, no one should be interested
6682                  in the enumeration constants for such a type.  */
6683               t = cxx_make_type (ENUMERAL_TYPE);
6684               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6685             }
6686           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
6687         }
6688       else
6689         {
6690           t = make_class_type (TREE_CODE (template_type));
6691           CLASSTYPE_DECLARED_CLASS (t)
6692             = CLASSTYPE_DECLARED_CLASS (template_type);
6693           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6694           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6695
6696           /* A local class.  Make sure the decl gets registered properly.  */
6697           if (context == current_function_decl)
6698             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6699
6700           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6701             /* This instantiation is another name for the primary
6702                template type. Set the TYPE_CANONICAL field
6703                appropriately. */
6704             TYPE_CANONICAL (t) = template_type;
6705           else if (any_template_arguments_need_structural_equality_p (arglist))
6706             /* Some of the template arguments require structural
6707                equality testing, so this template class requires
6708                structural equality testing. */
6709             SET_TYPE_STRUCTURAL_EQUALITY (t);
6710         }
6711
6712       /* If we called start_enum or pushtag above, this information
6713          will already be set up.  */
6714       if (!TYPE_NAME (t))
6715         {
6716           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6717
6718           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6719           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6720           DECL_SOURCE_LOCATION (type_decl)
6721             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6722         }
6723       else
6724         type_decl = TYPE_NAME (t);
6725
6726       TREE_PRIVATE (type_decl)
6727         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6728       TREE_PROTECTED (type_decl)
6729         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6730       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6731         {
6732           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6733           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6734         }
6735
6736       /* Let's consider the explicit specialization of a member
6737          of a class template specialization that is implicitely instantiated,
6738          e.g.:
6739              template<class T>
6740              struct S
6741              {
6742                template<class U> struct M {}; //#0
6743              };
6744
6745              template<>
6746              template<>
6747              struct S<int>::M<char> //#1
6748              {
6749                int i;
6750              };
6751         [temp.expl.spec]/4 says this is valid.
6752
6753         In this case, when we write:
6754         S<int>::M<char> m;
6755
6756         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
6757         the one of #0.
6758
6759         When we encounter #1, we want to store the partial instantiation
6760         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
6761
6762         For all cases other than this "explicit specialization of member of a
6763         class template", we just want to store the most general template into
6764         the CLASSTYPE_TI_TEMPLATE of M.
6765
6766         This case of "explicit specialization of member of a class template"
6767         only happens when:
6768         1/ the enclosing class is an instantiation of, and therefore not
6769         the same as, the context of the most general template, and
6770         2/ we aren't looking at the partial instantiation itself, i.e.
6771         the innermost arguments are not the same as the innermost parms of
6772         the most general template.
6773
6774         So it's only when 1/ and 2/ happens that we want to use the partial
6775         instantiation of the member template in lieu of its most general
6776         template.  */
6777
6778       if (PRIMARY_TEMPLATE_P (gen_tmpl)
6779           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
6780           /* the enclosing class must be an instantiation...  */
6781           && CLASS_TYPE_P (context)
6782           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
6783         {
6784           tree partial_inst_args;
6785           TREE_VEC_LENGTH (arglist)--;
6786           ++processing_template_decl;
6787           partial_inst_args =
6788             tsubst (INNERMOST_TEMPLATE_ARGS
6789                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
6790                     arglist, complain, NULL_TREE);
6791           --processing_template_decl;
6792           TREE_VEC_LENGTH (arglist)++;
6793           use_partial_inst_tmpl =
6794             /*...and we must not be looking at the partial instantiation
6795              itself. */
6796             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
6797                                  partial_inst_args);
6798         }
6799
6800       if (!use_partial_inst_tmpl)
6801         /* This case is easy; there are no member templates involved.  */
6802         found = gen_tmpl;
6803       else
6804         {
6805           /* This is a full instantiation of a member template.  Find
6806              the partial instantiation of which this is an instance.  */
6807
6808           /* Temporarily reduce by one the number of levels in the ARGLIST
6809              so as to avoid comparing the last set of arguments.  */
6810           TREE_VEC_LENGTH (arglist)--;
6811           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6812           TREE_VEC_LENGTH (arglist)++;
6813           found = CLASSTYPE_TI_TEMPLATE (found);
6814         }
6815
6816       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
6817
6818       elt.spec = t;
6819       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6820                                                        &elt, hash, INSERT);
6821       *slot = ggc_alloc_spec_entry ();
6822       **slot = elt;
6823
6824       /* Note this use of the partial instantiation so we can check it
6825          later in maybe_process_partial_specialization.  */
6826       DECL_TEMPLATE_INSTANTIATIONS (templ)
6827         = tree_cons (arglist, t,
6828                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6829
6830       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
6831         /* Now that the type has been registered on the instantiations
6832            list, we set up the enumerators.  Because the enumeration
6833            constants may involve the enumeration type itself, we make
6834            sure to register the type first, and then create the
6835            constants.  That way, doing tsubst_expr for the enumeration
6836            constants won't result in recursive calls here; we'll find
6837            the instantiation and exit above.  */
6838         tsubst_enum (template_type, t, arglist);
6839
6840       if (is_dependent_type)
6841         /* If the type makes use of template parameters, the
6842            code that generates debugging information will crash.  */
6843         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6844
6845       /* Possibly limit visibility based on template args.  */
6846       TREE_PUBLIC (type_decl) = 1;
6847       determine_visibility (type_decl);
6848
6849       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6850     }
6851   timevar_pop (TV_NAME_LOOKUP);
6852 }
6853 \f
6854 struct pair_fn_data
6855 {
6856   tree_fn_t fn;
6857   void *data;
6858   /* True when we should also visit template parameters that occur in
6859      non-deduced contexts.  */
6860   bool include_nondeduced_p;
6861   struct pointer_set_t *visited;
6862 };
6863
6864 /* Called from for_each_template_parm via walk_tree.  */
6865
6866 static tree
6867 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6868 {
6869   tree t = *tp;
6870   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6871   tree_fn_t fn = pfd->fn;
6872   void *data = pfd->data;
6873
6874   if (TYPE_P (t)
6875       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6876       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6877                                  pfd->include_nondeduced_p))
6878     return error_mark_node;
6879
6880   switch (TREE_CODE (t))
6881     {
6882     case RECORD_TYPE:
6883       if (TYPE_PTRMEMFUNC_P (t))
6884         break;
6885       /* Fall through.  */
6886
6887     case UNION_TYPE:
6888     case ENUMERAL_TYPE:
6889       if (!TYPE_TEMPLATE_INFO (t))
6890         *walk_subtrees = 0;
6891       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
6892                                        fn, data, pfd->visited, 
6893                                        pfd->include_nondeduced_p))
6894         return error_mark_node;
6895       break;
6896
6897     case INTEGER_TYPE:
6898       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6899                                   fn, data, pfd->visited, 
6900                                   pfd->include_nondeduced_p)
6901           || for_each_template_parm (TYPE_MAX_VALUE (t),
6902                                      fn, data, pfd->visited,
6903                                      pfd->include_nondeduced_p))
6904         return error_mark_node;
6905       break;
6906
6907     case METHOD_TYPE:
6908       /* Since we're not going to walk subtrees, we have to do this
6909          explicitly here.  */
6910       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6911                                   pfd->visited, pfd->include_nondeduced_p))
6912         return error_mark_node;
6913       /* Fall through.  */
6914
6915     case FUNCTION_TYPE:
6916       /* Check the return type.  */
6917       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6918                                   pfd->include_nondeduced_p))
6919         return error_mark_node;
6920
6921       /* Check the parameter types.  Since default arguments are not
6922          instantiated until they are needed, the TYPE_ARG_TYPES may
6923          contain expressions that involve template parameters.  But,
6924          no-one should be looking at them yet.  And, once they're
6925          instantiated, they don't contain template parameters, so
6926          there's no point in looking at them then, either.  */
6927       {
6928         tree parm;
6929
6930         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6931           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6932                                       pfd->visited, pfd->include_nondeduced_p))
6933             return error_mark_node;
6934
6935         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6936            want walk_tree walking into them itself.  */
6937         *walk_subtrees = 0;
6938       }
6939       break;
6940
6941     case TYPEOF_TYPE:
6942       if (pfd->include_nondeduced_p
6943           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6944                                      pfd->visited, 
6945                                      pfd->include_nondeduced_p))
6946         return error_mark_node;
6947       break;
6948
6949     case FUNCTION_DECL:
6950     case VAR_DECL:
6951       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6952           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6953                                      pfd->visited, pfd->include_nondeduced_p))
6954         return error_mark_node;
6955       /* Fall through.  */
6956
6957     case PARM_DECL:
6958     case CONST_DECL:
6959       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6960           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6961                                      pfd->visited, pfd->include_nondeduced_p))
6962         return error_mark_node;
6963       if (DECL_CONTEXT (t)
6964           && pfd->include_nondeduced_p
6965           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6966                                      pfd->visited, pfd->include_nondeduced_p))
6967         return error_mark_node;
6968       break;
6969
6970     case BOUND_TEMPLATE_TEMPLATE_PARM:
6971       /* Record template parameters such as `T' inside `TT<T>'.  */
6972       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6973                                   pfd->include_nondeduced_p))
6974         return error_mark_node;
6975       /* Fall through.  */
6976
6977     case TEMPLATE_TEMPLATE_PARM:
6978     case TEMPLATE_TYPE_PARM:
6979     case TEMPLATE_PARM_INDEX:
6980       if (fn && (*fn)(t, data))
6981         return error_mark_node;
6982       else if (!fn)
6983         return error_mark_node;
6984       break;
6985
6986     case TEMPLATE_DECL:
6987       /* A template template parameter is encountered.  */
6988       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6989           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6990                                      pfd->include_nondeduced_p))
6991         return error_mark_node;
6992
6993       /* Already substituted template template parameter */
6994       *walk_subtrees = 0;
6995       break;
6996
6997     case TYPENAME_TYPE:
6998       if (!fn
6999           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
7000                                      data, pfd->visited, 
7001                                      pfd->include_nondeduced_p))
7002         return error_mark_node;
7003       break;
7004
7005     case CONSTRUCTOR:
7006       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
7007           && pfd->include_nondeduced_p
7008           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
7009                                      (TREE_TYPE (t)), fn, data,
7010                                      pfd->visited, pfd->include_nondeduced_p))
7011         return error_mark_node;
7012       break;
7013
7014     case INDIRECT_REF:
7015     case COMPONENT_REF:
7016       /* If there's no type, then this thing must be some expression
7017          involving template parameters.  */
7018       if (!fn && !TREE_TYPE (t))
7019         return error_mark_node;
7020       break;
7021
7022     case MODOP_EXPR:
7023     case CAST_EXPR:
7024     case REINTERPRET_CAST_EXPR:
7025     case CONST_CAST_EXPR:
7026     case STATIC_CAST_EXPR:
7027     case DYNAMIC_CAST_EXPR:
7028     case ARROW_EXPR:
7029     case DOTSTAR_EXPR:
7030     case TYPEID_EXPR:
7031     case PSEUDO_DTOR_EXPR:
7032       if (!fn)
7033         return error_mark_node;
7034       break;
7035
7036     default:
7037       break;
7038     }
7039
7040   /* We didn't find any template parameters we liked.  */
7041   return NULL_TREE;
7042 }
7043
7044 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7045    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7046    call FN with the parameter and the DATA.
7047    If FN returns nonzero, the iteration is terminated, and
7048    for_each_template_parm returns 1.  Otherwise, the iteration
7049    continues.  If FN never returns a nonzero value, the value
7050    returned by for_each_template_parm is 0.  If FN is NULL, it is
7051    considered to be the function which always returns 1.
7052
7053    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7054    parameters that occur in non-deduced contexts.  When false, only
7055    visits those template parameters that can be deduced.  */
7056
7057 static int
7058 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7059                         struct pointer_set_t *visited,
7060                         bool include_nondeduced_p)
7061 {
7062   struct pair_fn_data pfd;
7063   int result;
7064
7065   /* Set up.  */
7066   pfd.fn = fn;
7067   pfd.data = data;
7068   pfd.include_nondeduced_p = include_nondeduced_p;
7069
7070   /* Walk the tree.  (Conceptually, we would like to walk without
7071      duplicates, but for_each_template_parm_r recursively calls
7072      for_each_template_parm, so we would need to reorganize a fair
7073      bit to use walk_tree_without_duplicates, so we keep our own
7074      visited list.)  */
7075   if (visited)
7076     pfd.visited = visited;
7077   else
7078     pfd.visited = pointer_set_create ();
7079   result = cp_walk_tree (&t,
7080                          for_each_template_parm_r,
7081                          &pfd,
7082                          pfd.visited) != NULL_TREE;
7083
7084   /* Clean up.  */
7085   if (!visited)
7086     {
7087       pointer_set_destroy (pfd.visited);
7088       pfd.visited = 0;
7089     }
7090
7091   return result;
7092 }
7093
7094 /* Returns true if T depends on any template parameter.  */
7095
7096 int
7097 uses_template_parms (tree t)
7098 {
7099   bool dependent_p;
7100   int saved_processing_template_decl;
7101
7102   saved_processing_template_decl = processing_template_decl;
7103   if (!saved_processing_template_decl)
7104     processing_template_decl = 1;
7105   if (TYPE_P (t))
7106     dependent_p = dependent_type_p (t);
7107   else if (TREE_CODE (t) == TREE_VEC)
7108     dependent_p = any_dependent_template_arguments_p (t);
7109   else if (TREE_CODE (t) == TREE_LIST)
7110     dependent_p = (uses_template_parms (TREE_VALUE (t))
7111                    || uses_template_parms (TREE_CHAIN (t)));
7112   else if (TREE_CODE (t) == TYPE_DECL)
7113     dependent_p = dependent_type_p (TREE_TYPE (t));
7114   else if (DECL_P (t)
7115            || EXPR_P (t)
7116            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7117            || TREE_CODE (t) == OVERLOAD
7118            || TREE_CODE (t) == BASELINK
7119            || TREE_CODE (t) == IDENTIFIER_NODE
7120            || TREE_CODE (t) == TRAIT_EXPR
7121            || TREE_CODE (t) == CONSTRUCTOR
7122            || CONSTANT_CLASS_P (t))
7123     dependent_p = (type_dependent_expression_p (t)
7124                    || value_dependent_expression_p (t));
7125   else
7126     {
7127       gcc_assert (t == error_mark_node);
7128       dependent_p = false;
7129     }
7130
7131   processing_template_decl = saved_processing_template_decl;
7132
7133   return dependent_p;
7134 }
7135
7136 /* Returns true if T depends on any template parameter with level LEVEL.  */
7137
7138 int
7139 uses_template_parms_level (tree t, int level)
7140 {
7141   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7142                                  /*include_nondeduced_p=*/true);
7143 }
7144
7145 static int tinst_depth;
7146 extern int max_tinst_depth;
7147 #ifdef GATHER_STATISTICS
7148 int depth_reached;
7149 #endif
7150 static int tinst_level_tick;
7151 static int last_template_error_tick;
7152
7153 /* We're starting to instantiate D; record the template instantiation context
7154    for diagnostics and to restore it later.  */
7155
7156 int
7157 push_tinst_level (tree d)
7158 {
7159   struct tinst_level *new_level;
7160
7161   if (tinst_depth >= max_tinst_depth)
7162     {
7163       /* If the instantiation in question still has unbound template parms,
7164          we don't really care if we can't instantiate it, so just return.
7165          This happens with base instantiation for implicit `typename'.  */
7166       if (uses_template_parms (d))
7167         return 0;
7168
7169       last_template_error_tick = tinst_level_tick;
7170       error ("template instantiation depth exceeds maximum of %d (use "
7171              "-ftemplate-depth= to increase the maximum) instantiating %qD",
7172              max_tinst_depth, d);
7173
7174       print_instantiation_context ();
7175
7176       return 0;
7177     }
7178
7179   new_level = ggc_alloc_tinst_level ();
7180   new_level->decl = d;
7181   new_level->locus = input_location;
7182   new_level->in_system_header_p = in_system_header;
7183   new_level->next = current_tinst_level;
7184   current_tinst_level = new_level;
7185
7186   ++tinst_depth;
7187 #ifdef GATHER_STATISTICS
7188   if (tinst_depth > depth_reached)
7189     depth_reached = tinst_depth;
7190 #endif
7191
7192   ++tinst_level_tick;
7193   return 1;
7194 }
7195
7196 /* We're done instantiating this template; return to the instantiation
7197    context.  */
7198
7199 void
7200 pop_tinst_level (void)
7201 {
7202   /* Restore the filename and line number stashed away when we started
7203      this instantiation.  */
7204   input_location = current_tinst_level->locus;
7205   current_tinst_level = current_tinst_level->next;
7206   --tinst_depth;
7207   ++tinst_level_tick;
7208 }
7209
7210 /* We're instantiating a deferred template; restore the template
7211    instantiation context in which the instantiation was requested, which
7212    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7213
7214 static tree
7215 reopen_tinst_level (struct tinst_level *level)
7216 {
7217   struct tinst_level *t;
7218
7219   tinst_depth = 0;
7220   for (t = level; t; t = t->next)
7221     ++tinst_depth;
7222
7223   current_tinst_level = level;
7224   pop_tinst_level ();
7225   return level->decl;
7226 }
7227
7228 /* Returns the TINST_LEVEL which gives the original instantiation
7229    context.  */
7230
7231 struct tinst_level *
7232 outermost_tinst_level (void)
7233 {
7234   struct tinst_level *level = current_tinst_level;
7235   if (level)
7236     while (level->next)
7237       level = level->next;
7238   return level;
7239 }
7240
7241 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7242
7243 bool
7244 parameter_of_template_p (tree parm, tree templ)
7245 {
7246   tree parms;
7247   int i;
7248
7249   if (!parm || !templ)
7250     return false;
7251
7252   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7253   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7254
7255   parms = DECL_TEMPLATE_PARMS (templ);
7256   parms = INNERMOST_TEMPLATE_PARMS (parms);
7257
7258   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7259     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7260       return true;
7261
7262   return false;
7263 }
7264
7265 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7266    vector of template arguments, as for tsubst.
7267
7268    Returns an appropriate tsubst'd friend declaration.  */
7269
7270 static tree
7271 tsubst_friend_function (tree decl, tree args)
7272 {
7273   tree new_friend;
7274
7275   if (TREE_CODE (decl) == FUNCTION_DECL
7276       && DECL_TEMPLATE_INSTANTIATION (decl)
7277       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7278     /* This was a friend declared with an explicit template
7279        argument list, e.g.:
7280
7281        friend void f<>(T);
7282
7283        to indicate that f was a template instantiation, not a new
7284        function declaration.  Now, we have to figure out what
7285        instantiation of what template.  */
7286     {
7287       tree template_id, arglist, fns;
7288       tree new_args;
7289       tree tmpl;
7290       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7291
7292       /* Friend functions are looked up in the containing namespace scope.
7293          We must enter that scope, to avoid finding member functions of the
7294          current class with same name.  */
7295       push_nested_namespace (ns);
7296       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7297                          tf_warning_or_error, NULL_TREE,
7298                          /*integral_constant_expression_p=*/false);
7299       pop_nested_namespace (ns);
7300       arglist = tsubst (DECL_TI_ARGS (decl), args,
7301                         tf_warning_or_error, NULL_TREE);
7302       template_id = lookup_template_function (fns, arglist);
7303
7304       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7305       tmpl = determine_specialization (template_id, new_friend,
7306                                        &new_args,
7307                                        /*need_member_template=*/0,
7308                                        TREE_VEC_LENGTH (args),
7309                                        tsk_none);
7310       return instantiate_template (tmpl, new_args, tf_error);
7311     }
7312
7313   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7314
7315   /* The NEW_FRIEND will look like an instantiation, to the
7316      compiler, but is not an instantiation from the point of view of
7317      the language.  For example, we might have had:
7318
7319      template <class T> struct S {
7320        template <class U> friend void f(T, U);
7321      };
7322
7323      Then, in S<int>, template <class U> void f(int, U) is not an
7324      instantiation of anything.  */
7325   if (new_friend == error_mark_node)
7326     return error_mark_node;
7327
7328   DECL_USE_TEMPLATE (new_friend) = 0;
7329   if (TREE_CODE (decl) == TEMPLATE_DECL)
7330     {
7331       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7332       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7333         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7334     }
7335
7336   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7337      is not a template instantiation and should not be mangled like
7338      one.  Therefore, we forget the mangling here; we'll recompute it
7339      later if we need it.  */
7340   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7341     {
7342       SET_DECL_RTL (new_friend, NULL);
7343       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7344     }
7345
7346   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7347     {
7348       tree old_decl;
7349       tree new_friend_template_info;
7350       tree new_friend_result_template_info;
7351       tree ns;
7352       int  new_friend_is_defn;
7353
7354       /* We must save some information from NEW_FRIEND before calling
7355          duplicate decls since that function will free NEW_FRIEND if
7356          possible.  */
7357       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7358       new_friend_is_defn =
7359             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7360                            (template_for_substitution (new_friend)))
7361              != NULL_TREE);
7362       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7363         {
7364           /* This declaration is a `primary' template.  */
7365           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7366
7367           new_friend_result_template_info
7368             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7369         }
7370       else
7371         new_friend_result_template_info = NULL_TREE;
7372
7373       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7374       if (new_friend_is_defn)
7375         DECL_INITIAL (new_friend) = error_mark_node;
7376
7377       /* Inside pushdecl_namespace_level, we will push into the
7378          current namespace. However, the friend function should go
7379          into the namespace of the template.  */
7380       ns = decl_namespace_context (new_friend);
7381       push_nested_namespace (ns);
7382       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7383       pop_nested_namespace (ns);
7384
7385       if (old_decl == error_mark_node)
7386         return error_mark_node;
7387
7388       if (old_decl != new_friend)
7389         {
7390           /* This new friend declaration matched an existing
7391              declaration.  For example, given:
7392
7393                template <class T> void f(T);
7394                template <class U> class C {
7395                  template <class T> friend void f(T) {}
7396                };
7397
7398              the friend declaration actually provides the definition
7399              of `f', once C has been instantiated for some type.  So,
7400              old_decl will be the out-of-class template declaration,
7401              while new_friend is the in-class definition.
7402
7403              But, if `f' was called before this point, the
7404              instantiation of `f' will have DECL_TI_ARGS corresponding
7405              to `T' but not to `U', references to which might appear
7406              in the definition of `f'.  Previously, the most general
7407              template for an instantiation of `f' was the out-of-class
7408              version; now it is the in-class version.  Therefore, we
7409              run through all specialization of `f', adding to their
7410              DECL_TI_ARGS appropriately.  In particular, they need a
7411              new set of outer arguments, corresponding to the
7412              arguments for this class instantiation.
7413
7414              The same situation can arise with something like this:
7415
7416                friend void f(int);
7417                template <class T> class C {
7418                  friend void f(T) {}
7419                };
7420
7421              when `C<int>' is instantiated.  Now, `f(int)' is defined
7422              in the class.  */
7423
7424           if (!new_friend_is_defn)
7425             /* On the other hand, if the in-class declaration does
7426                *not* provide a definition, then we don't want to alter
7427                existing definitions.  We can just leave everything
7428                alone.  */
7429             ;
7430           else
7431             {
7432               tree new_template = TI_TEMPLATE (new_friend_template_info);
7433               tree new_args = TI_ARGS (new_friend_template_info);
7434
7435               /* Overwrite whatever template info was there before, if
7436                  any, with the new template information pertaining to
7437                  the declaration.  */
7438               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7439
7440               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7441                 {
7442                   /* We should have called reregister_specialization in
7443                      duplicate_decls.  */
7444                   gcc_assert (retrieve_specialization (new_template,
7445                                                        new_args, 0)
7446                               == old_decl);
7447
7448                   /* Instantiate it if the global has already been used.  */
7449                   if (DECL_ODR_USED (old_decl))
7450                     instantiate_decl (old_decl, /*defer_ok=*/true,
7451                                       /*expl_inst_class_mem_p=*/false);
7452                 }
7453               else
7454                 {
7455                   tree t;
7456
7457                   /* Indicate that the old function template is a partial
7458                      instantiation.  */
7459                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7460                     = new_friend_result_template_info;
7461
7462                   gcc_assert (new_template
7463                               == most_general_template (new_template));
7464                   gcc_assert (new_template != old_decl);
7465
7466                   /* Reassign any specializations already in the hash table
7467                      to the new more general template, and add the
7468                      additional template args.  */
7469                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7470                        t != NULL_TREE;
7471                        t = TREE_CHAIN (t))
7472                     {
7473                       tree spec = TREE_VALUE (t);
7474                       spec_entry elt;
7475
7476                       elt.tmpl = old_decl;
7477                       elt.args = DECL_TI_ARGS (spec);
7478                       elt.spec = NULL_TREE;
7479
7480                       htab_remove_elt (decl_specializations, &elt);
7481
7482                       DECL_TI_ARGS (spec)
7483                         = add_outermost_template_args (new_args,
7484                                                        DECL_TI_ARGS (spec));
7485
7486                       register_specialization
7487                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7488
7489                     }
7490                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7491                 }
7492             }
7493
7494           /* The information from NEW_FRIEND has been merged into OLD_DECL
7495              by duplicate_decls.  */
7496           new_friend = old_decl;
7497         }
7498     }
7499   else
7500     {
7501       tree context = DECL_CONTEXT (new_friend);
7502       bool dependent_p;
7503
7504       /* In the code
7505            template <class T> class C {
7506              template <class U> friend void C1<U>::f (); // case 1
7507              friend void C2<T>::f ();                    // case 2
7508            };
7509          we only need to make sure CONTEXT is a complete type for
7510          case 2.  To distinguish between the two cases, we note that
7511          CONTEXT of case 1 remains dependent type after tsubst while
7512          this isn't true for case 2.  */
7513       ++processing_template_decl;
7514       dependent_p = dependent_type_p (context);
7515       --processing_template_decl;
7516
7517       if (!dependent_p
7518           && !complete_type_or_else (context, NULL_TREE))
7519         return error_mark_node;
7520
7521       if (COMPLETE_TYPE_P (context))
7522         {
7523           /* Check to see that the declaration is really present, and,
7524              possibly obtain an improved declaration.  */
7525           tree fn = check_classfn (context,
7526                                    new_friend, NULL_TREE);
7527
7528           if (fn)
7529             new_friend = fn;
7530         }
7531     }
7532
7533   return new_friend;
7534 }
7535
7536 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7537    template arguments, as for tsubst.
7538
7539    Returns an appropriate tsubst'd friend type or error_mark_node on
7540    failure.  */
7541
7542 static tree
7543 tsubst_friend_class (tree friend_tmpl, tree args)
7544 {
7545   tree friend_type;
7546   tree tmpl;
7547   tree context;
7548
7549   context = CP_DECL_CONTEXT (friend_tmpl);
7550
7551   if (context != global_namespace)
7552     {
7553       if (TREE_CODE (context) == NAMESPACE_DECL)
7554         push_nested_namespace (context);
7555       else
7556         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7557     }
7558
7559   /* Look for a class template declaration.  We look for hidden names
7560      because two friend declarations of the same template are the
7561      same.  For example, in:
7562
7563        struct A { 
7564          template <typename> friend class F;
7565        };
7566        template <typename> struct B { 
7567          template <typename> friend class F;
7568        };
7569
7570      both F templates are the same.  */
7571   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7572                            /*block_p=*/true, 0, 
7573                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7574
7575   /* But, if we don't find one, it might be because we're in a
7576      situation like this:
7577
7578        template <class T>
7579        struct S {
7580          template <class U>
7581          friend struct S;
7582        };
7583
7584      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7585      for `S<int>', not the TEMPLATE_DECL.  */
7586   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7587     {
7588       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7589       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7590     }
7591
7592   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7593     {
7594       /* The friend template has already been declared.  Just
7595          check to see that the declarations match, and install any new
7596          default parameters.  We must tsubst the default parameters,
7597          of course.  We only need the innermost template parameters
7598          because that is all that redeclare_class_template will look
7599          at.  */
7600       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7601           > TMPL_ARGS_DEPTH (args))
7602         {
7603           tree parms;
7604           location_t saved_input_location;
7605           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7606                                          args, tf_warning_or_error);
7607
7608           saved_input_location = input_location;
7609           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7610           redeclare_class_template (TREE_TYPE (tmpl), parms);
7611           input_location = saved_input_location;
7612           
7613         }
7614
7615       friend_type = TREE_TYPE (tmpl);
7616     }
7617   else
7618     {
7619       /* The friend template has not already been declared.  In this
7620          case, the instantiation of the template class will cause the
7621          injection of this template into the global scope.  */
7622       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7623       if (tmpl == error_mark_node)
7624         return error_mark_node;
7625
7626       /* The new TMPL is not an instantiation of anything, so we
7627          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7628          the new type because that is supposed to be the corresponding
7629          template decl, i.e., TMPL.  */
7630       DECL_USE_TEMPLATE (tmpl) = 0;
7631       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7632       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7633       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7634         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7635
7636       /* Inject this template into the global scope.  */
7637       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7638     }
7639
7640   if (context != global_namespace)
7641     {
7642       if (TREE_CODE (context) == NAMESPACE_DECL)
7643         pop_nested_namespace (context);
7644       else
7645         pop_nested_class ();
7646     }
7647
7648   return friend_type;
7649 }
7650
7651 /* Returns zero if TYPE cannot be completed later due to circularity.
7652    Otherwise returns one.  */
7653
7654 static int
7655 can_complete_type_without_circularity (tree type)
7656 {
7657   if (type == NULL_TREE || type == error_mark_node)
7658     return 0;
7659   else if (COMPLETE_TYPE_P (type))
7660     return 1;
7661   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7662     return can_complete_type_without_circularity (TREE_TYPE (type));
7663   else if (CLASS_TYPE_P (type)
7664            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7665     return 0;
7666   else
7667     return 1;
7668 }
7669
7670 /* Apply any attributes which had to be deferred until instantiation
7671    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7672    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7673
7674 static void
7675 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7676                                 tree args, tsubst_flags_t complain, tree in_decl)
7677 {
7678   tree last_dep = NULL_TREE;
7679   tree t;
7680   tree *p;
7681
7682   for (t = attributes; t; t = TREE_CHAIN (t))
7683     if (ATTR_IS_DEPENDENT (t))
7684       {
7685         last_dep = t;
7686         attributes = copy_list (attributes);
7687         break;
7688       }
7689
7690   if (DECL_P (*decl_p))
7691     {
7692       if (TREE_TYPE (*decl_p) == error_mark_node)
7693         return;
7694       p = &DECL_ATTRIBUTES (*decl_p);
7695     }
7696   else
7697     p = &TYPE_ATTRIBUTES (*decl_p);
7698
7699   if (last_dep)
7700     {
7701       tree late_attrs = NULL_TREE;
7702       tree *q = &late_attrs;
7703
7704       for (*p = attributes; *p; )
7705         {
7706           t = *p;
7707           if (ATTR_IS_DEPENDENT (t))
7708             {
7709               *p = TREE_CHAIN (t);
7710               TREE_CHAIN (t) = NULL_TREE;
7711               /* If the first attribute argument is an identifier, don't
7712                  pass it through tsubst.  Attributes like mode, format,
7713                  cleanup and several target specific attributes expect it
7714                  unmodified.  */
7715               if (TREE_VALUE (t)
7716                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7717                   && TREE_VALUE (TREE_VALUE (t))
7718                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7719                       == IDENTIFIER_NODE))
7720                 {
7721                   tree chain
7722                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7723                                    in_decl,
7724                                    /*integral_constant_expression_p=*/false);
7725                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7726                     TREE_VALUE (t)
7727                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7728                                    chain);
7729                 }
7730               else
7731                 TREE_VALUE (t)
7732                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7733                                  /*integral_constant_expression_p=*/false);
7734               *q = t;
7735               q = &TREE_CHAIN (t);
7736             }
7737           else
7738             p = &TREE_CHAIN (t);
7739         }
7740
7741       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7742     }
7743 }
7744
7745 /* Perform (or defer) access check for typedefs that were referenced
7746    from within the template TMPL code.
7747    This is a subroutine of instantiate_template and instantiate_class_template.
7748    TMPL is the template to consider and TARGS is the list of arguments of
7749    that template.  */
7750
7751 static void
7752 perform_typedefs_access_check (tree tmpl, tree targs)
7753 {
7754   location_t saved_location;
7755   int i;
7756   qualified_typedef_usage_t *iter;
7757
7758   if (!tmpl
7759       || (!CLASS_TYPE_P (tmpl)
7760           && TREE_CODE (tmpl) != FUNCTION_DECL))
7761     return;
7762
7763   saved_location = input_location;
7764   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
7765                     get_types_needing_access_check (tmpl),
7766                     i, iter)
7767     {
7768       tree type_decl = iter->typedef_decl;
7769       tree type_scope = iter->context;
7770
7771       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7772         continue;
7773
7774       if (uses_template_parms (type_decl))
7775         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7776       if (uses_template_parms (type_scope))
7777         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7778
7779       /* Make access check error messages point to the location
7780          of the use of the typedef.  */
7781       input_location = iter->locus;
7782       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7783                                      type_decl, type_decl);
7784     }
7785     input_location = saved_location;
7786 }
7787
7788 tree
7789 instantiate_class_template (tree type)
7790 {
7791   tree templ, args, pattern, t, member;
7792   tree typedecl;
7793   tree pbinfo;
7794   tree base_list;
7795   unsigned int saved_maximum_field_alignment;
7796
7797   if (type == error_mark_node)
7798     return error_mark_node;
7799
7800   if (COMPLETE_OR_OPEN_TYPE_P (type)
7801       || uses_template_parms (type))
7802     return type;
7803
7804   /* Figure out which template is being instantiated.  */
7805   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7806   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7807
7808   /* Determine what specialization of the original template to
7809      instantiate.  */
7810   t = most_specialized_class (type, templ, tf_warning_or_error);
7811   if (t == error_mark_node)
7812     {
7813       TYPE_BEING_DEFINED (type) = 1;
7814       return error_mark_node;
7815     }
7816   else if (t)
7817     {
7818       /* This TYPE is actually an instantiation of a partial
7819          specialization.  We replace the innermost set of ARGS with
7820          the arguments appropriate for substitution.  For example,
7821          given:
7822
7823            template <class T> struct S {};
7824            template <class T> struct S<T*> {};
7825
7826          and supposing that we are instantiating S<int*>, ARGS will
7827          presently be {int*} -- but we need {int}.  */
7828       pattern = TREE_TYPE (t);
7829       args = TREE_PURPOSE (t);
7830     }
7831   else
7832     {
7833       pattern = TREE_TYPE (templ);
7834       args = CLASSTYPE_TI_ARGS (type);
7835     }
7836
7837   /* If the template we're instantiating is incomplete, then clearly
7838      there's nothing we can do.  */
7839   if (!COMPLETE_TYPE_P (pattern))
7840     return type;
7841
7842   /* If we've recursively instantiated too many templates, stop.  */
7843   if (! push_tinst_level (type))
7844     return type;
7845
7846   /* Now we're really doing the instantiation.  Mark the type as in
7847      the process of being defined.  */
7848   TYPE_BEING_DEFINED (type) = 1;
7849
7850   /* We may be in the middle of deferred access check.  Disable
7851      it now.  */
7852   push_deferring_access_checks (dk_no_deferred);
7853
7854   push_to_top_level ();
7855   /* Use #pragma pack from the template context.  */
7856   saved_maximum_field_alignment = maximum_field_alignment;
7857   maximum_field_alignment = TYPE_PRECISION (pattern);
7858
7859   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7860
7861   /* Set the input location to the most specialized template definition.
7862      This is needed if tsubsting causes an error.  */
7863   typedecl = TYPE_MAIN_DECL (pattern);
7864   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
7865     DECL_SOURCE_LOCATION (typedecl);
7866
7867   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7868   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7869   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7870   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7871   TYPE_HAS_COPY_ASSIGN (type) = TYPE_HAS_COPY_ASSIGN (pattern);
7872   TYPE_HAS_CONST_COPY_ASSIGN (type) = TYPE_HAS_CONST_COPY_ASSIGN (pattern);
7873   TYPE_HAS_COPY_CTOR (type) = TYPE_HAS_COPY_CTOR (pattern);
7874   TYPE_HAS_CONST_COPY_CTOR (type) = TYPE_HAS_CONST_COPY_CTOR (pattern);
7875   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7876   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7877   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7878   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7879   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7880   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7881   if (ANON_AGGR_TYPE_P (pattern))
7882     SET_ANON_AGGR_TYPE_P (type);
7883   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7884     {
7885       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7886       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7887     }
7888
7889   pbinfo = TYPE_BINFO (pattern);
7890
7891   /* We should never instantiate a nested class before its enclosing
7892      class; we need to look up the nested class by name before we can
7893      instantiate it, and that lookup should instantiate the enclosing
7894      class.  */
7895   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7896               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
7897
7898   base_list = NULL_TREE;
7899   if (BINFO_N_BASE_BINFOS (pbinfo))
7900     {
7901       tree pbase_binfo;
7902       tree pushed_scope;
7903       int i;
7904
7905       /* We must enter the scope containing the type, as that is where
7906          the accessibility of types named in dependent bases are
7907          looked up from.  */
7908       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
7909
7910       /* Substitute into each of the bases to determine the actual
7911          basetypes.  */
7912       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7913         {
7914           tree base;
7915           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7916           tree expanded_bases = NULL_TREE;
7917           int idx, len = 1;
7918
7919           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7920             {
7921               expanded_bases = 
7922                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7923                                        args, tf_error, NULL_TREE);
7924               if (expanded_bases == error_mark_node)
7925                 continue;
7926
7927               len = TREE_VEC_LENGTH (expanded_bases);
7928             }
7929
7930           for (idx = 0; idx < len; idx++)
7931             {
7932               if (expanded_bases)
7933                 /* Extract the already-expanded base class.  */
7934                 base = TREE_VEC_ELT (expanded_bases, idx);
7935               else
7936                 /* Substitute to figure out the base class.  */
7937                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7938                                NULL_TREE);
7939
7940               if (base == error_mark_node)
7941                 continue;
7942
7943               base_list = tree_cons (access, base, base_list);
7944               if (BINFO_VIRTUAL_P (pbase_binfo))
7945                 TREE_TYPE (base_list) = integer_type_node;
7946             }
7947         }
7948
7949       /* The list is now in reverse order; correct that.  */
7950       base_list = nreverse (base_list);
7951
7952       if (pushed_scope)
7953         pop_scope (pushed_scope);
7954     }
7955   /* Now call xref_basetypes to set up all the base-class
7956      information.  */
7957   xref_basetypes (type, base_list);
7958
7959   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7960                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7961                                   args, tf_error, NULL_TREE);
7962   fixup_attribute_variants (type);
7963
7964   /* Now that our base classes are set up, enter the scope of the
7965      class, so that name lookups into base classes, etc. will work
7966      correctly.  This is precisely analogous to what we do in
7967      begin_class_definition when defining an ordinary non-template
7968      class, except we also need to push the enclosing classes.  */
7969   push_nested_class (type);
7970
7971   /* Now members are processed in the order of declaration.  */
7972   for (member = CLASSTYPE_DECL_LIST (pattern);
7973        member; member = TREE_CHAIN (member))
7974     {
7975       tree t = TREE_VALUE (member);
7976
7977       if (TREE_PURPOSE (member))
7978         {
7979           if (TYPE_P (t))
7980             {
7981               /* Build new CLASSTYPE_NESTED_UTDS.  */
7982
7983               tree newtag;
7984               bool class_template_p;
7985
7986               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7987                                   && TYPE_LANG_SPECIFIC (t)
7988                                   && CLASSTYPE_IS_TEMPLATE (t));
7989               /* If the member is a class template, then -- even after
7990                  substitution -- there may be dependent types in the
7991                  template argument list for the class.  We increment
7992                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7993                  that function will assume that no types are dependent
7994                  when outside of a template.  */
7995               if (class_template_p)
7996                 ++processing_template_decl;
7997               newtag = tsubst (t, args, tf_error, NULL_TREE);
7998               if (class_template_p)
7999                 --processing_template_decl;
8000               if (newtag == error_mark_node)
8001                 continue;
8002
8003               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8004                 {
8005                   tree name = TYPE_IDENTIFIER (t);
8006
8007                   if (class_template_p)
8008                     /* Unfortunately, lookup_template_class sets
8009                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8010                        instantiation (i.e., for the type of a member
8011                        template class nested within a template class.)
8012                        This behavior is required for
8013                        maybe_process_partial_specialization to work
8014                        correctly, but is not accurate in this case;
8015                        the TAG is not an instantiation of anything.
8016                        (The corresponding TEMPLATE_DECL is an
8017                        instantiation, but the TYPE is not.) */
8018                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8019
8020                   /* Now, we call pushtag to put this NEWTAG into the scope of
8021                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8022                      pushtag calling push_template_decl.  We don't have to do
8023                      this for enums because it will already have been done in
8024                      tsubst_enum.  */
8025                   if (name)
8026                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8027                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8028                 }
8029             }
8030           else if (TREE_CODE (t) == FUNCTION_DECL
8031                    || DECL_FUNCTION_TEMPLATE_P (t))
8032             {
8033               /* Build new TYPE_METHODS.  */
8034               tree r;
8035
8036               if (TREE_CODE (t) == TEMPLATE_DECL)
8037                 ++processing_template_decl;
8038               r = tsubst (t, args, tf_error, NULL_TREE);
8039               if (TREE_CODE (t) == TEMPLATE_DECL)
8040                 --processing_template_decl;
8041               set_current_access_from_decl (r);
8042               finish_member_declaration (r);
8043             }
8044           else
8045             {
8046               /* Build new TYPE_FIELDS.  */
8047               if (TREE_CODE (t) == STATIC_ASSERT)
8048                 {
8049                   tree condition = 
8050                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8051                                  tf_warning_or_error, NULL_TREE,
8052                                  /*integral_constant_expression_p=*/true);
8053                   finish_static_assert (condition,
8054                                         STATIC_ASSERT_MESSAGE (t), 
8055                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8056                                         /*member_p=*/true);
8057                 }
8058               else if (TREE_CODE (t) != CONST_DECL)
8059                 {
8060                   tree r;
8061
8062                   /* The file and line for this declaration, to
8063                      assist in error message reporting.  Since we
8064                      called push_tinst_level above, we don't need to
8065                      restore these.  */
8066                   input_location = DECL_SOURCE_LOCATION (t);
8067
8068                   if (TREE_CODE (t) == TEMPLATE_DECL)
8069                     ++processing_template_decl;
8070                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8071                   if (TREE_CODE (t) == TEMPLATE_DECL)
8072                     --processing_template_decl;
8073                   if (TREE_CODE (r) == VAR_DECL)
8074                     {
8075                       /* In [temp.inst]:
8076
8077                            [t]he initialization (and any associated
8078                            side-effects) of a static data member does
8079                            not occur unless the static data member is
8080                            itself used in a way that requires the
8081                            definition of the static data member to
8082                            exist.
8083
8084                          Therefore, we do not substitute into the
8085                          initialized for the static data member here.  */
8086                       finish_static_data_member_decl
8087                         (r,
8088                          /*init=*/NULL_TREE,
8089                          /*init_const_expr_p=*/false,
8090                          /*asmspec_tree=*/NULL_TREE,
8091                          /*flags=*/0);
8092                       if (DECL_INITIALIZED_IN_CLASS_P (r))
8093                         check_static_variable_definition (r, TREE_TYPE (r));
8094                     }
8095                   else if (TREE_CODE (r) == FIELD_DECL)
8096                     {
8097                       /* Determine whether R has a valid type and can be
8098                          completed later.  If R is invalid, then it is
8099                          replaced by error_mark_node so that it will not be
8100                          added to TYPE_FIELDS.  */
8101                       tree rtype = TREE_TYPE (r);
8102                       if (can_complete_type_without_circularity (rtype))
8103                         complete_type (rtype);
8104
8105                       if (!COMPLETE_TYPE_P (rtype))
8106                         {
8107                           cxx_incomplete_type_error (r, rtype);
8108                           r = error_mark_node;
8109                         }
8110                     }
8111
8112                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8113                      such a thing will already have been added to the field
8114                      list by tsubst_enum in finish_member_declaration in the
8115                      CLASSTYPE_NESTED_UTDS case above.  */
8116                   if (!(TREE_CODE (r) == TYPE_DECL
8117                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8118                         && DECL_ARTIFICIAL (r)))
8119                     {
8120                       set_current_access_from_decl (r);
8121                       finish_member_declaration (r);
8122                     }
8123                 }
8124             }
8125         }
8126       else
8127         {
8128           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8129             {
8130               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8131
8132               tree friend_type = t;
8133               bool adjust_processing_template_decl = false;
8134
8135               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8136                 {
8137                   /* template <class T> friend class C;  */
8138                   friend_type = tsubst_friend_class (friend_type, args);
8139                   adjust_processing_template_decl = true;
8140                 }
8141               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8142                 {
8143                   /* template <class T> friend class C::D;  */
8144                   friend_type = tsubst (friend_type, args,
8145                                         tf_warning_or_error, NULL_TREE);
8146                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8147                     friend_type = TREE_TYPE (friend_type);
8148                   adjust_processing_template_decl = true;
8149                 }
8150               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
8151                 {
8152                   /* This could be either
8153
8154                        friend class T::C;
8155
8156                      when dependent_type_p is false or
8157
8158                        template <class U> friend class T::C;
8159
8160                      otherwise.  */
8161                   friend_type = tsubst (friend_type, args,
8162                                         tf_warning_or_error, NULL_TREE);
8163                   /* Bump processing_template_decl for correct
8164                      dependent_type_p calculation.  */
8165                   ++processing_template_decl;
8166                   if (dependent_type_p (friend_type))
8167                     adjust_processing_template_decl = true;
8168                   --processing_template_decl;
8169                 }
8170               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8171                        && hidden_name_p (TYPE_NAME (friend_type)))
8172                 {
8173                   /* friend class C;
8174
8175                      where C hasn't been declared yet.  Let's lookup name
8176                      from namespace scope directly, bypassing any name that
8177                      come from dependent base class.  */
8178                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8179
8180                   /* The call to xref_tag_from_type does injection for friend
8181                      classes.  */
8182                   push_nested_namespace (ns);
8183                   friend_type =
8184                     xref_tag_from_type (friend_type, NULL_TREE,
8185                                         /*tag_scope=*/ts_current);
8186                   pop_nested_namespace (ns);
8187                 }
8188               else if (uses_template_parms (friend_type))
8189                 /* friend class C<T>;  */
8190                 friend_type = tsubst (friend_type, args,
8191                                       tf_warning_or_error, NULL_TREE);
8192               /* Otherwise it's
8193
8194                    friend class C;
8195
8196                  where C is already declared or
8197
8198                    friend class C<int>;
8199
8200                  We don't have to do anything in these cases.  */
8201
8202               if (adjust_processing_template_decl)
8203                 /* Trick make_friend_class into realizing that the friend
8204                    we're adding is a template, not an ordinary class.  It's
8205                    important that we use make_friend_class since it will
8206                    perform some error-checking and output cross-reference
8207                    information.  */
8208                 ++processing_template_decl;
8209
8210               if (friend_type != error_mark_node)
8211                 make_friend_class (type, friend_type, /*complain=*/false);
8212
8213               if (adjust_processing_template_decl)
8214                 --processing_template_decl;
8215             }
8216           else
8217             {
8218               /* Build new DECL_FRIENDLIST.  */
8219               tree r;
8220
8221               /* The file and line for this declaration, to
8222                  assist in error message reporting.  Since we
8223                  called push_tinst_level above, we don't need to
8224                  restore these.  */
8225               input_location = DECL_SOURCE_LOCATION (t);
8226
8227               if (TREE_CODE (t) == TEMPLATE_DECL)
8228                 {
8229                   ++processing_template_decl;
8230                   push_deferring_access_checks (dk_no_check);
8231                 }
8232
8233               r = tsubst_friend_function (t, args);
8234               add_friend (type, r, /*complain=*/false);
8235               if (TREE_CODE (t) == TEMPLATE_DECL)
8236                 {
8237                   pop_deferring_access_checks ();
8238                   --processing_template_decl;
8239                 }
8240             }
8241         }
8242     }
8243
8244   /* Set the file and line number information to whatever is given for
8245      the class itself.  This puts error messages involving generated
8246      implicit functions at a predictable point, and the same point
8247      that would be used for non-template classes.  */
8248   input_location = DECL_SOURCE_LOCATION (typedecl);
8249
8250   unreverse_member_declarations (type);
8251   finish_struct_1 (type);
8252   TYPE_BEING_DEFINED (type) = 0;
8253
8254   /* We don't instantiate default arguments for member functions.  14.7.1:
8255
8256      The implicit instantiation of a class template specialization causes
8257      the implicit instantiation of the declarations, but not of the
8258      definitions or default arguments, of the class member functions,
8259      member classes, static data members and member templates....  */
8260
8261   /* Some typedefs referenced from within the template code need to be access
8262      checked at template instantiation time, i.e now. These types were
8263      added to the template at parsing time. Let's get those and perform
8264      the access checks then.  */
8265   perform_typedefs_access_check (pattern, args);
8266   perform_deferred_access_checks ();
8267   pop_nested_class ();
8268   maximum_field_alignment = saved_maximum_field_alignment;
8269   pop_from_top_level ();
8270   pop_deferring_access_checks ();
8271   pop_tinst_level ();
8272
8273   /* The vtable for a template class can be emitted in any translation
8274      unit in which the class is instantiated.  When there is no key
8275      method, however, finish_struct_1 will already have added TYPE to
8276      the keyed_classes list.  */
8277   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8278     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8279
8280   return type;
8281 }
8282
8283 static tree
8284 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8285 {
8286   tree r;
8287
8288   if (!t)
8289     r = t;
8290   else if (TYPE_P (t))
8291     r = tsubst (t, args, complain, in_decl);
8292   else
8293     {
8294       if (!(complain & tf_warning))
8295         ++c_inhibit_evaluation_warnings;
8296       r = tsubst_expr (t, args, complain, in_decl,
8297                        /*integral_constant_expression_p=*/true);
8298       if (!(complain & tf_warning))
8299         --c_inhibit_evaluation_warnings;
8300     }
8301   return r;
8302 }
8303
8304 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8305    NONTYPE_ARGUMENT_PACK.  */
8306
8307 static tree
8308 make_fnparm_pack (tree spec_parm)
8309 {
8310   /* Collect all of the extra "packed" parameters into an
8311      argument pack.  */
8312   tree parmvec;
8313   tree parmtypevec;
8314   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8315   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8316   int i, len = list_length (spec_parm);
8317
8318   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8319   parmvec = make_tree_vec (len);
8320   parmtypevec = make_tree_vec (len);
8321   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
8322     {
8323       TREE_VEC_ELT (parmvec, i) = spec_parm;
8324       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8325     }
8326
8327   /* Build the argument packs.  */
8328   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8329   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8330   TREE_TYPE (argpack) = argtypepack;
8331
8332   return argpack;
8333 }        
8334
8335 /* Substitute ARGS into T, which is an pack expansion
8336    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8337    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8338    (if only a partial substitution could be performed) or
8339    ERROR_MARK_NODE if there was an error.  */
8340 tree
8341 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8342                        tree in_decl)
8343 {
8344   tree pattern;
8345   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8346   int i, len = -1;
8347   tree result;
8348   int incomplete = 0;
8349   htab_t saved_local_specializations = NULL;
8350
8351   gcc_assert (PACK_EXPANSION_P (t));
8352   pattern = PACK_EXPANSION_PATTERN (t);
8353
8354   /* Determine the argument packs that will instantiate the parameter
8355      packs used in the expansion expression. While we're at it,
8356      compute the number of arguments to be expanded and make sure it
8357      is consistent.  */
8358   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8359        pack = TREE_CHAIN (pack))
8360     {
8361       tree parm_pack = TREE_VALUE (pack);
8362       tree arg_pack = NULL_TREE;
8363       tree orig_arg = NULL_TREE;
8364
8365       if (TREE_CODE (parm_pack) == PARM_DECL)
8366         {
8367           if (!cp_unevaluated_operand)
8368             arg_pack = retrieve_local_specialization (parm_pack);
8369           else
8370             {
8371               /* We can't rely on local_specializations for a parameter
8372                  name used later in a function declaration (such as in a
8373                  late-specified return type).  Even if it exists, it might
8374                  have the wrong value for a recursive call.  Just make a
8375                  dummy decl, since it's only used for its type.  */
8376               arg_pack = tsubst_decl (parm_pack, args, complain);
8377               arg_pack = make_fnparm_pack (arg_pack);
8378             }
8379         }
8380       else
8381         {
8382           int level, idx, levels;
8383           template_parm_level_and_index (parm_pack, &level, &idx);
8384
8385           levels = TMPL_ARGS_DEPTH (args);
8386           if (level <= levels)
8387             arg_pack = TMPL_ARG (args, level, idx);
8388         }
8389
8390       orig_arg = arg_pack;
8391       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8392         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8393       
8394       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8395         /* This can only happen if we forget to expand an argument
8396            pack somewhere else. Just return an error, silently.  */
8397         {
8398           result = make_tree_vec (1);
8399           TREE_VEC_ELT (result, 0) = error_mark_node;
8400           return result;
8401         }
8402
8403       if (arg_pack
8404           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8405           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8406         {
8407           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8408           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8409           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8410               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8411             /* The argument pack that the parameter maps to is just an
8412                expansion of the parameter itself, such as one would
8413                find in the implicit typedef of a class inside the
8414                class itself.  Consider this parameter "unsubstituted",
8415                so that we will maintain the outer pack expansion.  */
8416             arg_pack = NULL_TREE;
8417         }
8418           
8419       if (arg_pack)
8420         {
8421           int my_len = 
8422             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8423
8424           /* It's all-or-nothing with incomplete argument packs.  */
8425           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8426             return error_mark_node;
8427           
8428           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8429             incomplete = 1;
8430
8431           if (len < 0)
8432             len = my_len;
8433           else if (len != my_len)
8434             {
8435               if (incomplete)
8436                 /* We got explicit args for some packs but not others;
8437                    do nothing now and try again after deduction.  */
8438                 return t;
8439               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8440                 error ("mismatched argument pack lengths while expanding "
8441                        "%<%T%>",
8442                        pattern);
8443               else
8444                 error ("mismatched argument pack lengths while expanding "
8445                        "%<%E%>",
8446                        pattern);
8447               return error_mark_node;
8448             }
8449
8450           /* Keep track of the parameter packs and their corresponding
8451              argument packs.  */
8452           packs = tree_cons (parm_pack, arg_pack, packs);
8453           TREE_TYPE (packs) = orig_arg;
8454         }
8455       else
8456         /* We can't substitute for this parameter pack.  */
8457         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8458                                          TREE_VALUE (pack),
8459                                          unsubstituted_packs);
8460     }
8461
8462   /* We cannot expand this expansion expression, because we don't have
8463      all of the argument packs we need. Substitute into the pattern
8464      and return a PACK_EXPANSION_*. The caller will need to deal with
8465      that.  */
8466   if (unsubstituted_packs)
8467     {
8468       tree new_pat;
8469       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8470         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8471                                /*integral_constant_expression_p=*/false);
8472       else
8473         new_pat = tsubst (pattern, args, complain, in_decl);
8474       return make_pack_expansion (new_pat);
8475     }
8476
8477   /* We could not find any argument packs that work.  */
8478   if (len < 0)
8479     return error_mark_node;
8480
8481   if (cp_unevaluated_operand)
8482     {
8483       /* We're in a late-specified return type, so create our own local
8484          specializations table; the current table is either NULL or (in the
8485          case of recursive unification) might have bindings that we don't
8486          want to use or alter.  */
8487       saved_local_specializations = local_specializations;
8488       local_specializations = htab_create (37,
8489                                            hash_local_specialization,
8490                                            eq_local_specializations,
8491                                            NULL);
8492     }
8493
8494   /* For each argument in each argument pack, substitute into the
8495      pattern.  */
8496   result = make_tree_vec (len + incomplete);
8497   for (i = 0; i < len + incomplete; ++i)
8498     {
8499       /* For parameter pack, change the substitution of the parameter
8500          pack to the ith argument in its argument pack, then expand
8501          the pattern.  */
8502       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8503         {
8504           tree parm = TREE_PURPOSE (pack);
8505
8506           if (TREE_CODE (parm) == PARM_DECL)
8507             {
8508               /* Select the Ith argument from the pack.  */
8509               tree arg = make_node (ARGUMENT_PACK_SELECT);
8510               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8511               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8512               mark_used (parm);
8513               register_local_specialization (arg, parm);
8514             }
8515           else
8516             {
8517               tree value = parm;
8518               int idx, level;
8519               template_parm_level_and_index (parm, &level, &idx);
8520               
8521               if (i < len) 
8522                 {
8523                   /* Select the Ith argument from the pack. */
8524                   value = make_node (ARGUMENT_PACK_SELECT);
8525                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8526                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8527                 }
8528
8529               /* Update the corresponding argument.  */
8530               TMPL_ARG (args, level, idx) = value;
8531             }
8532         }
8533
8534       /* Substitute into the PATTERN with the altered arguments.  */
8535       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8536         TREE_VEC_ELT (result, i) = 
8537           tsubst_expr (pattern, args, complain, in_decl,
8538                        /*integral_constant_expression_p=*/false);
8539       else
8540         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8541
8542       if (i == len)
8543         /* When we have incomplete argument packs, the last "expanded"
8544            result is itself a pack expansion, which allows us
8545            to deduce more arguments.  */
8546         TREE_VEC_ELT (result, i) = 
8547           make_pack_expansion (TREE_VEC_ELT (result, i));
8548
8549       if (TREE_VEC_ELT (result, i) == error_mark_node)
8550         {
8551           result = error_mark_node;
8552           break;
8553         }
8554     }
8555
8556   /* Update ARGS to restore the substitution from parameter packs to
8557      their argument packs.  */
8558   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8559     {
8560       tree parm = TREE_PURPOSE (pack);
8561
8562       if (TREE_CODE (parm) == PARM_DECL)
8563         register_local_specialization (TREE_TYPE (pack), parm);
8564       else
8565         {
8566           int idx, level;
8567           template_parm_level_and_index (parm, &level, &idx);
8568           
8569           /* Update the corresponding argument.  */
8570           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8571             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8572               TREE_TYPE (pack);
8573           else
8574             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8575         }
8576     }
8577
8578   if (saved_local_specializations)
8579     {
8580       htab_delete (local_specializations);
8581       local_specializations = saved_local_specializations;
8582     }
8583   
8584   return result;
8585 }
8586
8587 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8588    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8589    parameter packs; all parms generated from a function parameter pack will
8590    have the same DECL_PARM_INDEX.  */
8591
8592 tree
8593 get_pattern_parm (tree parm, tree tmpl)
8594 {
8595   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8596   tree patparm;
8597
8598   if (DECL_ARTIFICIAL (parm))
8599     {
8600       for (patparm = DECL_ARGUMENTS (pattern);
8601            patparm; patparm = DECL_CHAIN (patparm))
8602         if (DECL_ARTIFICIAL (patparm)
8603             && DECL_NAME (parm) == DECL_NAME (patparm))
8604           break;
8605     }
8606   else
8607     {
8608       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8609       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8610       gcc_assert (DECL_PARM_INDEX (patparm)
8611                   == DECL_PARM_INDEX (parm));
8612     }
8613
8614   return patparm;
8615 }
8616
8617 /* Substitute ARGS into the vector or list of template arguments T.  */
8618
8619 static tree
8620 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8621 {
8622   tree orig_t = t;
8623   int len = TREE_VEC_LENGTH (t);
8624   int need_new = 0, i, expanded_len_adjust = 0, out;
8625   tree *elts = XALLOCAVEC (tree, len);
8626
8627   for (i = 0; i < len; i++)
8628     {
8629       tree orig_arg = TREE_VEC_ELT (t, i);
8630       tree new_arg;
8631
8632       if (TREE_CODE (orig_arg) == TREE_VEC)
8633         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8634       else if (PACK_EXPANSION_P (orig_arg))
8635         {
8636           /* Substitute into an expansion expression.  */
8637           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8638
8639           if (TREE_CODE (new_arg) == TREE_VEC)
8640             /* Add to the expanded length adjustment the number of
8641                expanded arguments. We subtract one from this
8642                measurement, because the argument pack expression
8643                itself is already counted as 1 in
8644                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8645                the argument pack is empty.  */
8646             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8647         }
8648       else if (ARGUMENT_PACK_P (orig_arg))
8649         {
8650           /* Substitute into each of the arguments.  */
8651           new_arg = TYPE_P (orig_arg)
8652             ? cxx_make_type (TREE_CODE (orig_arg))
8653             : make_node (TREE_CODE (orig_arg));
8654           
8655           SET_ARGUMENT_PACK_ARGS (
8656             new_arg,
8657             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8658                                   args, complain, in_decl));
8659
8660           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8661             new_arg = error_mark_node;
8662
8663           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8664             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8665                                           complain, in_decl);
8666             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8667
8668             if (TREE_TYPE (new_arg) == error_mark_node)
8669               new_arg = error_mark_node;
8670           }
8671         }
8672       else
8673         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8674
8675       if (new_arg == error_mark_node)
8676         return error_mark_node;
8677
8678       elts[i] = new_arg;
8679       if (new_arg != orig_arg)
8680         need_new = 1;
8681     }
8682
8683   if (!need_new)
8684     return t;
8685
8686   /* Make space for the expanded arguments coming from template
8687      argument packs.  */
8688   t = make_tree_vec (len + expanded_len_adjust);
8689   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
8690      arguments for a member template.
8691      In that case each TREE_VEC in ORIG_T represents a level of template
8692      arguments, and ORIG_T won't carry any non defaulted argument count.
8693      It will rather be the nested TREE_VECs that will carry one.
8694      In other words, ORIG_T carries a non defaulted argument count only
8695      if it doesn't contain any nested TREE_VEC.  */
8696   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
8697     {
8698       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
8699       count += expanded_len_adjust;
8700       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
8701     }
8702   for (i = 0, out = 0; i < len; i++)
8703     {
8704       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8705            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8706           && TREE_CODE (elts[i]) == TREE_VEC)
8707         {
8708           int idx;
8709
8710           /* Now expand the template argument pack "in place".  */
8711           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8712             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8713         }
8714       else
8715         {
8716           TREE_VEC_ELT (t, out) = elts[i];
8717           out++;
8718         }
8719     }
8720
8721   return t;
8722 }
8723
8724 /* Return the result of substituting ARGS into the template parameters
8725    given by PARMS.  If there are m levels of ARGS and m + n levels of
8726    PARMS, then the result will contain n levels of PARMS.  For
8727    example, if PARMS is `template <class T> template <class U>
8728    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8729    result will be `template <int*, double, class V>'.  */
8730
8731 static tree
8732 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8733 {
8734   tree r = NULL_TREE;
8735   tree* new_parms;
8736
8737   /* When substituting into a template, we must set
8738      PROCESSING_TEMPLATE_DECL as the template parameters may be
8739      dependent if they are based on one-another, and the dependency
8740      predicates are short-circuit outside of templates.  */
8741   ++processing_template_decl;
8742
8743   for (new_parms = &r;
8744        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8745        new_parms = &(TREE_CHAIN (*new_parms)),
8746          parms = TREE_CHAIN (parms))
8747     {
8748       tree new_vec =
8749         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8750       int i;
8751
8752       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8753         {
8754           tree tuple;
8755           tree default_value;
8756           tree parm_decl;
8757
8758           if (parms == error_mark_node)
8759             continue;
8760
8761           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8762
8763           if (tuple == error_mark_node)
8764             continue;
8765
8766           default_value = TREE_PURPOSE (tuple);
8767           parm_decl = TREE_VALUE (tuple);
8768
8769           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8770           if (TREE_CODE (parm_decl) == PARM_DECL
8771               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8772             parm_decl = error_mark_node;
8773           default_value = tsubst_template_arg (default_value, args,
8774                                                complain, NULL_TREE);
8775
8776           tuple = build_tree_list (default_value, parm_decl);
8777           TREE_VEC_ELT (new_vec, i) = tuple;
8778         }
8779
8780       *new_parms =
8781         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8782                              - TMPL_ARGS_DEPTH (args)),
8783                    new_vec, NULL_TREE);
8784     }
8785
8786   --processing_template_decl;
8787
8788   return r;
8789 }
8790
8791 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8792    type T.  If T is not an aggregate or enumeration type, it is
8793    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8794    ENTERING_SCOPE is nonzero, T is the context for a template which
8795    we are presently tsubst'ing.  Return the substituted value.  */
8796
8797 static tree
8798 tsubst_aggr_type (tree t,
8799                   tree args,
8800                   tsubst_flags_t complain,
8801                   tree in_decl,
8802                   int entering_scope)
8803 {
8804   if (t == NULL_TREE)
8805     return NULL_TREE;
8806
8807   switch (TREE_CODE (t))
8808     {
8809     case RECORD_TYPE:
8810       if (TYPE_PTRMEMFUNC_P (t))
8811         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8812
8813       /* Else fall through.  */
8814     case ENUMERAL_TYPE:
8815     case UNION_TYPE:
8816       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8817         {
8818           tree argvec;
8819           tree context;
8820           tree r;
8821           int saved_unevaluated_operand;
8822           int saved_inhibit_evaluation_warnings;
8823
8824           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8825           saved_unevaluated_operand = cp_unevaluated_operand;
8826           cp_unevaluated_operand = 0;
8827           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8828           c_inhibit_evaluation_warnings = 0;
8829
8830           /* First, determine the context for the type we are looking
8831              up.  */
8832           context = TYPE_CONTEXT (t);
8833           if (context)
8834             {
8835               context = tsubst_aggr_type (context, args, complain,
8836                                           in_decl, /*entering_scope=*/1);
8837               /* If context is a nested class inside a class template,
8838                  it may still need to be instantiated (c++/33959).  */
8839               if (TYPE_P (context))
8840                 context = complete_type (context);
8841             }
8842
8843           /* Then, figure out what arguments are appropriate for the
8844              type we are trying to find.  For example, given:
8845
8846                template <class T> struct S;
8847                template <class T, class U> void f(T, U) { S<U> su; }
8848
8849              and supposing that we are instantiating f<int, double>,
8850              then our ARGS will be {int, double}, but, when looking up
8851              S we only want {double}.  */
8852           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8853                                          complain, in_decl);
8854           if (argvec == error_mark_node)
8855             r = error_mark_node;
8856           else
8857             {
8858               r = lookup_template_class (t, argvec, in_decl, context,
8859                                          entering_scope, complain);
8860               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
8861             }
8862
8863           cp_unevaluated_operand = saved_unevaluated_operand;
8864           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8865
8866           return r;
8867         }
8868       else
8869         /* This is not a template type, so there's nothing to do.  */
8870         return t;
8871
8872     default:
8873       return tsubst (t, args, complain, in_decl);
8874     }
8875 }
8876
8877 /* Substitute into the default argument ARG (a default argument for
8878    FN), which has the indicated TYPE.  */
8879
8880 tree
8881 tsubst_default_argument (tree fn, tree type, tree arg)
8882 {
8883   tree saved_class_ptr = NULL_TREE;
8884   tree saved_class_ref = NULL_TREE;
8885
8886   /* This can happen in invalid code.  */
8887   if (TREE_CODE (arg) == DEFAULT_ARG)
8888     return arg;
8889
8890   /* This default argument came from a template.  Instantiate the
8891      default argument here, not in tsubst.  In the case of
8892      something like:
8893
8894        template <class T>
8895        struct S {
8896          static T t();
8897          void f(T = t());
8898        };
8899
8900      we must be careful to do name lookup in the scope of S<T>,
8901      rather than in the current class.  */
8902   push_access_scope (fn);
8903   /* The "this" pointer is not valid in a default argument.  */
8904   if (cfun)
8905     {
8906       saved_class_ptr = current_class_ptr;
8907       cp_function_chain->x_current_class_ptr = NULL_TREE;
8908       saved_class_ref = current_class_ref;
8909       cp_function_chain->x_current_class_ref = NULL_TREE;
8910     }
8911
8912   push_deferring_access_checks(dk_no_deferred);
8913   /* The default argument expression may cause implicitly defined
8914      member functions to be synthesized, which will result in garbage
8915      collection.  We must treat this situation as if we were within
8916      the body of function so as to avoid collecting live data on the
8917      stack.  */
8918   ++function_depth;
8919   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8920                      tf_warning_or_error, NULL_TREE,
8921                      /*integral_constant_expression_p=*/false);
8922   --function_depth;
8923   pop_deferring_access_checks();
8924
8925   /* Restore the "this" pointer.  */
8926   if (cfun)
8927     {
8928       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8929       cp_function_chain->x_current_class_ref = saved_class_ref;
8930     }
8931
8932   /* Make sure the default argument is reasonable.  */
8933   arg = check_default_argument (type, arg);
8934
8935   pop_access_scope (fn);
8936
8937   return arg;
8938 }
8939
8940 /* Substitute into all the default arguments for FN.  */
8941
8942 static void
8943 tsubst_default_arguments (tree fn)
8944 {
8945   tree arg;
8946   tree tmpl_args;
8947
8948   tmpl_args = DECL_TI_ARGS (fn);
8949
8950   /* If this function is not yet instantiated, we certainly don't need
8951      its default arguments.  */
8952   if (uses_template_parms (tmpl_args))
8953     return;
8954   /* Don't do this again for clones.  */
8955   if (DECL_CLONED_FUNCTION_P (fn))
8956     return;
8957
8958   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8959        arg;
8960        arg = TREE_CHAIN (arg))
8961     if (TREE_PURPOSE (arg))
8962       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8963                                                     TREE_VALUE (arg),
8964                                                     TREE_PURPOSE (arg));
8965 }
8966
8967 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8968    result of the substitution.  Issue error and warning messages under
8969    control of COMPLAIN.  */
8970
8971 static tree
8972 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8973 {
8974 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8975   location_t saved_loc;
8976   tree r = NULL_TREE;
8977   tree in_decl = t;
8978   hashval_t hash = 0;
8979
8980   /* Set the filename and linenumber to improve error-reporting.  */
8981   saved_loc = input_location;
8982   input_location = DECL_SOURCE_LOCATION (t);
8983
8984   switch (TREE_CODE (t))
8985     {
8986     case TEMPLATE_DECL:
8987       {
8988         /* We can get here when processing a member function template,
8989            member class template, or template template parameter.  */
8990         tree decl = DECL_TEMPLATE_RESULT (t);
8991         tree spec;
8992         tree tmpl_args;
8993         tree full_args;
8994
8995         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8996           {
8997             /* Template template parameter is treated here.  */
8998             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8999             if (new_type == error_mark_node)
9000               RETURN (error_mark_node);
9001
9002             r = copy_decl (t);
9003             DECL_CHAIN (r) = NULL_TREE;
9004             TREE_TYPE (r) = new_type;
9005             DECL_TEMPLATE_RESULT (r)
9006               = build_decl (DECL_SOURCE_LOCATION (decl),
9007                             TYPE_DECL, DECL_NAME (decl), new_type);
9008             DECL_TEMPLATE_PARMS (r)
9009               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9010                                        complain);
9011             TYPE_NAME (new_type) = r;
9012             break;
9013           }
9014
9015         /* We might already have an instance of this template.
9016            The ARGS are for the surrounding class type, so the
9017            full args contain the tsubst'd args for the context,
9018            plus the innermost args from the template decl.  */
9019         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
9020           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
9021           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
9022         /* Because this is a template, the arguments will still be
9023            dependent, even after substitution.  If
9024            PROCESSING_TEMPLATE_DECL is not set, the dependency
9025            predicates will short-circuit.  */
9026         ++processing_template_decl;
9027         full_args = tsubst_template_args (tmpl_args, args,
9028                                           complain, in_decl);
9029         --processing_template_decl;
9030         if (full_args == error_mark_node)
9031           RETURN (error_mark_node);
9032
9033         /* If this is a default template template argument,
9034            tsubst might not have changed anything.  */
9035         if (full_args == tmpl_args)
9036           RETURN (t);
9037
9038         hash = hash_tmpl_and_args (t, full_args);
9039         spec = retrieve_specialization (t, full_args, hash);
9040         if (spec != NULL_TREE)
9041           {
9042             r = spec;
9043             break;
9044           }
9045
9046         /* Make a new template decl.  It will be similar to the
9047            original, but will record the current template arguments.
9048            We also create a new function declaration, which is just
9049            like the old one, but points to this new template, rather
9050            than the old one.  */
9051         r = copy_decl (t);
9052         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9053         DECL_CHAIN (r) = NULL_TREE;
9054
9055         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9056
9057         if (TREE_CODE (decl) == TYPE_DECL)
9058           {
9059             tree new_type;
9060             ++processing_template_decl;
9061             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9062             --processing_template_decl;
9063             if (new_type == error_mark_node)
9064               RETURN (error_mark_node);
9065
9066             TREE_TYPE (r) = new_type;
9067             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9068             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9069             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9070             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9071           }
9072         else
9073           {
9074             tree new_decl;
9075             ++processing_template_decl;
9076             new_decl = tsubst (decl, args, complain, in_decl);
9077             --processing_template_decl;
9078             if (new_decl == error_mark_node)
9079               RETURN (error_mark_node);
9080
9081             DECL_TEMPLATE_RESULT (r) = new_decl;
9082             DECL_TI_TEMPLATE (new_decl) = r;
9083             TREE_TYPE (r) = TREE_TYPE (new_decl);
9084             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9085             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9086           }
9087
9088         SET_DECL_IMPLICIT_INSTANTIATION (r);
9089         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9090         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9091
9092         /* The template parameters for this new template are all the
9093            template parameters for the old template, except the
9094            outermost level of parameters.  */
9095         DECL_TEMPLATE_PARMS (r)
9096           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9097                                    complain);
9098
9099         if (PRIMARY_TEMPLATE_P (t))
9100           DECL_PRIMARY_TEMPLATE (r) = r;
9101
9102         if (TREE_CODE (decl) != TYPE_DECL)
9103           /* Record this non-type partial instantiation.  */
9104           register_specialization (r, t,
9105                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9106                                    false, hash);
9107       }
9108       break;
9109
9110     case FUNCTION_DECL:
9111       {
9112         tree ctx;
9113         tree argvec = NULL_TREE;
9114         tree *friends;
9115         tree gen_tmpl;
9116         tree type;
9117         int member;
9118         int args_depth;
9119         int parms_depth;
9120
9121         /* Nobody should be tsubst'ing into non-template functions.  */
9122         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9123
9124         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9125           {
9126             tree spec;
9127             bool dependent_p;
9128
9129             /* If T is not dependent, just return it.  We have to
9130                increment PROCESSING_TEMPLATE_DECL because
9131                value_dependent_expression_p assumes that nothing is
9132                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9133             ++processing_template_decl;
9134             dependent_p = value_dependent_expression_p (t);
9135             --processing_template_decl;
9136             if (!dependent_p)
9137               RETURN (t);
9138
9139             /* Calculate the most general template of which R is a
9140                specialization, and the complete set of arguments used to
9141                specialize R.  */
9142             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9143             argvec = tsubst_template_args (DECL_TI_ARGS
9144                                           (DECL_TEMPLATE_RESULT
9145                                                  (DECL_TI_TEMPLATE (t))),
9146                                            args, complain, in_decl);
9147
9148             /* Check to see if we already have this specialization.  */
9149             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9150             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9151
9152             if (spec)
9153               {
9154                 r = spec;
9155                 break;
9156               }
9157
9158             /* We can see more levels of arguments than parameters if
9159                there was a specialization of a member template, like
9160                this:
9161
9162                  template <class T> struct S { template <class U> void f(); }
9163                  template <> template <class U> void S<int>::f(U);
9164
9165                Here, we'll be substituting into the specialization,
9166                because that's where we can find the code we actually
9167                want to generate, but we'll have enough arguments for
9168                the most general template.
9169
9170                We also deal with the peculiar case:
9171
9172                  template <class T> struct S {
9173                    template <class U> friend void f();
9174                  };
9175                  template <class U> void f() {}
9176                  template S<int>;
9177                  template void f<double>();
9178
9179                Here, the ARGS for the instantiation of will be {int,
9180                double}.  But, we only need as many ARGS as there are
9181                levels of template parameters in CODE_PATTERN.  We are
9182                careful not to get fooled into reducing the ARGS in
9183                situations like:
9184
9185                  template <class T> struct S { template <class U> void f(U); }
9186                  template <class T> template <> void S<T>::f(int) {}
9187
9188                which we can spot because the pattern will be a
9189                specialization in this case.  */
9190             args_depth = TMPL_ARGS_DEPTH (args);
9191             parms_depth =
9192               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9193             if (args_depth > parms_depth
9194                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9195               args = get_innermost_template_args (args, parms_depth);
9196           }
9197         else
9198           {
9199             /* This special case arises when we have something like this:
9200
9201                  template <class T> struct S {
9202                    friend void f<int>(int, double);
9203                  };
9204
9205                Here, the DECL_TI_TEMPLATE for the friend declaration
9206                will be an IDENTIFIER_NODE.  We are being called from
9207                tsubst_friend_function, and we want only to create a
9208                new decl (R) with appropriate types so that we can call
9209                determine_specialization.  */
9210             gen_tmpl = NULL_TREE;
9211           }
9212
9213         if (DECL_CLASS_SCOPE_P (t))
9214           {
9215             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9216               member = 2;
9217             else
9218               member = 1;
9219             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9220                                     complain, t, /*entering_scope=*/1);
9221           }
9222         else
9223           {
9224             member = 0;
9225             ctx = DECL_CONTEXT (t);
9226           }
9227         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9228         if (type == error_mark_node)
9229           RETURN (error_mark_node);
9230
9231         /* We do NOT check for matching decls pushed separately at this
9232            point, as they may not represent instantiations of this
9233            template, and in any case are considered separate under the
9234            discrete model.  */
9235         r = copy_decl (t);
9236         DECL_USE_TEMPLATE (r) = 0;
9237         TREE_TYPE (r) = type;
9238         /* Clear out the mangled name and RTL for the instantiation.  */
9239         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9240         SET_DECL_RTL (r, NULL);
9241         /* Leave DECL_INITIAL set on deleted instantiations.  */
9242         if (!DECL_DELETED_FN (r))
9243           DECL_INITIAL (r) = NULL_TREE;
9244         DECL_CONTEXT (r) = ctx;
9245
9246         if (member && DECL_CONV_FN_P (r))
9247           /* Type-conversion operator.  Reconstruct the name, in
9248              case it's the name of one of the template's parameters.  */
9249           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9250
9251         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9252                                      complain, t);
9253         DECL_RESULT (r) = NULL_TREE;
9254
9255         TREE_STATIC (r) = 0;
9256         TREE_PUBLIC (r) = TREE_PUBLIC (t);
9257         DECL_EXTERNAL (r) = 1;
9258         /* If this is an instantiation of a function with internal
9259            linkage, we already know what object file linkage will be
9260            assigned to the instantiation.  */
9261         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9262         DECL_DEFER_OUTPUT (r) = 0;
9263         DECL_CHAIN (r) = NULL_TREE;
9264         DECL_PENDING_INLINE_INFO (r) = 0;
9265         DECL_PENDING_INLINE_P (r) = 0;
9266         DECL_SAVED_TREE (r) = NULL_TREE;
9267         DECL_STRUCT_FUNCTION (r) = NULL;
9268         TREE_USED (r) = 0;
9269         /* We'll re-clone as appropriate in instantiate_template.  */
9270         DECL_CLONED_FUNCTION (r) = NULL_TREE;
9271
9272         /* If we aren't complaining now, return on error before we register
9273            the specialization so that we'll complain eventually.  */
9274         if ((complain & tf_error) == 0
9275             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9276             && !grok_op_properties (r, /*complain=*/false))
9277           RETURN (error_mark_node);
9278
9279         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9280            this in the special friend case mentioned above where
9281            GEN_TMPL is NULL.  */
9282         if (gen_tmpl)
9283           {
9284             DECL_TEMPLATE_INFO (r)
9285               = build_template_info (gen_tmpl, argvec);
9286             SET_DECL_IMPLICIT_INSTANTIATION (r);
9287             register_specialization (r, gen_tmpl, argvec, false, hash);
9288
9289             /* We're not supposed to instantiate default arguments
9290                until they are called, for a template.  But, for a
9291                declaration like:
9292
9293                  template <class T> void f ()
9294                  { extern void g(int i = T()); }
9295
9296                we should do the substitution when the template is
9297                instantiated.  We handle the member function case in
9298                instantiate_class_template since the default arguments
9299                might refer to other members of the class.  */
9300             if (!member
9301                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9302                 && !uses_template_parms (argvec))
9303               tsubst_default_arguments (r);
9304           }
9305         else
9306           DECL_TEMPLATE_INFO (r) = NULL_TREE;
9307
9308         /* Copy the list of befriending classes.  */
9309         for (friends = &DECL_BEFRIENDING_CLASSES (r);
9310              *friends;
9311              friends = &TREE_CHAIN (*friends))
9312           {
9313             *friends = copy_node (*friends);
9314             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9315                                             args, complain,
9316                                             in_decl);
9317           }
9318
9319         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9320           {
9321             maybe_retrofit_in_chrg (r);
9322             if (DECL_CONSTRUCTOR_P (r))
9323               grok_ctor_properties (ctx, r);
9324             /* If this is an instantiation of a member template, clone it.
9325                If it isn't, that'll be handled by
9326                clone_constructors_and_destructors.  */
9327             if (PRIMARY_TEMPLATE_P (gen_tmpl))
9328               clone_function_decl (r, /*update_method_vec_p=*/0);
9329           }
9330         else if ((complain & tf_error) != 0
9331                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9332                  && !grok_op_properties (r, /*complain=*/true))
9333           RETURN (error_mark_node);
9334
9335         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9336           SET_DECL_FRIEND_CONTEXT (r,
9337                                    tsubst (DECL_FRIEND_CONTEXT (t),
9338                                             args, complain, in_decl));
9339
9340         /* Possibly limit visibility based on template args.  */
9341         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9342         if (DECL_VISIBILITY_SPECIFIED (t))
9343           {
9344             DECL_VISIBILITY_SPECIFIED (r) = 0;
9345             DECL_ATTRIBUTES (r)
9346               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9347           }
9348         determine_visibility (r);
9349         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9350             && !processing_template_decl)
9351           defaulted_late_check (r);
9352
9353         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9354                                         args, complain, in_decl);
9355       }
9356       break;
9357
9358     case PARM_DECL:
9359       {
9360         tree type = NULL_TREE;
9361         int i, len = 1;
9362         tree expanded_types = NULL_TREE;
9363         tree prev_r = NULL_TREE;
9364         tree first_r = NULL_TREE;
9365
9366         if (FUNCTION_PARAMETER_PACK_P (t))
9367           {
9368             /* If there is a local specialization that isn't a
9369                parameter pack, it means that we're doing a "simple"
9370                substitution from inside tsubst_pack_expansion. Just
9371                return the local specialization (which will be a single
9372                parm).  */
9373             tree spec = retrieve_local_specialization (t);
9374             if (spec 
9375                 && TREE_CODE (spec) == PARM_DECL
9376                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9377               RETURN (spec);
9378
9379             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9380                the parameters in this function parameter pack.  */
9381             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9382                                                     complain, in_decl);
9383             if (TREE_CODE (expanded_types) == TREE_VEC)
9384               {
9385                 len = TREE_VEC_LENGTH (expanded_types);
9386
9387                 /* Zero-length parameter packs are boring. Just substitute
9388                    into the chain.  */
9389                 if (len == 0)
9390                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9391                                   TREE_CHAIN (t)));
9392               }
9393             else
9394               {
9395                 /* All we did was update the type. Make a note of that.  */
9396                 type = expanded_types;
9397                 expanded_types = NULL_TREE;
9398               }
9399           }
9400
9401         /* Loop through all of the parameter's we'll build. When T is
9402            a function parameter pack, LEN is the number of expanded
9403            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9404         r = NULL_TREE;
9405         for (i = 0; i < len; ++i)
9406           {
9407             prev_r = r;
9408             r = copy_node (t);
9409             if (DECL_TEMPLATE_PARM_P (t))
9410               SET_DECL_TEMPLATE_PARM_P (r);
9411
9412             /* An argument of a function parameter pack is not a parameter
9413                pack.  */
9414             FUNCTION_PARAMETER_PACK_P (r) = false;
9415
9416             if (expanded_types)
9417               /* We're on the Ith parameter of the function parameter
9418                  pack.  */
9419               {
9420                 /* Get the Ith type.  */
9421                 type = TREE_VEC_ELT (expanded_types, i);
9422
9423                 if (DECL_NAME (r))
9424                   /* Rename the parameter to include the index.  */
9425                   DECL_NAME (r) =
9426                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9427               }
9428             else if (!type)
9429               /* We're dealing with a normal parameter.  */
9430               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9431
9432             type = type_decays_to (type);
9433             TREE_TYPE (r) = type;
9434             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9435
9436             if (DECL_INITIAL (r))
9437               {
9438                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9439                   DECL_INITIAL (r) = TREE_TYPE (r);
9440                 else
9441                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9442                                              complain, in_decl);
9443               }
9444
9445             DECL_CONTEXT (r) = NULL_TREE;
9446
9447             if (!DECL_TEMPLATE_PARM_P (r))
9448               DECL_ARG_TYPE (r) = type_passed_as (type);
9449
9450             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9451                                             args, complain, in_decl);
9452
9453             /* Keep track of the first new parameter we
9454                generate. That's what will be returned to the
9455                caller.  */
9456             if (!first_r)
9457               first_r = r;
9458
9459             /* Build a proper chain of parameters when substituting
9460                into a function parameter pack.  */
9461             if (prev_r)
9462               DECL_CHAIN (prev_r) = r;
9463           }
9464
9465         if (DECL_CHAIN (t))
9466           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
9467                                    complain, DECL_CHAIN (t));
9468
9469         /* FIRST_R contains the start of the chain we've built.  */
9470         r = first_r;
9471       }
9472       break;
9473
9474     case FIELD_DECL:
9475       {
9476         tree type;
9477
9478         r = copy_decl (t);
9479         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9480         if (type == error_mark_node)
9481           RETURN (error_mark_node);
9482         TREE_TYPE (r) = type;
9483         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9484
9485         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9486         DECL_INITIAL (r)
9487           = tsubst_expr (DECL_INITIAL (t), args,
9488                          complain, in_decl,
9489                          /*integral_constant_expression_p=*/true);
9490         /* We don't have to set DECL_CONTEXT here; it is set by
9491            finish_member_declaration.  */
9492         DECL_CHAIN (r) = NULL_TREE;
9493         if (VOID_TYPE_P (type))
9494           error ("instantiation of %q+D as type %qT", r, type);
9495
9496         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9497                                         args, complain, in_decl);
9498       }
9499       break;
9500
9501     case USING_DECL:
9502       /* We reach here only for member using decls.  */
9503       if (DECL_DEPENDENT_P (t))
9504         {
9505           r = do_class_using_decl
9506             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9507              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9508           if (!r)
9509             r = error_mark_node;
9510           else
9511             {
9512               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9513               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9514             }
9515         }
9516       else
9517         {
9518           r = copy_node (t);
9519           DECL_CHAIN (r) = NULL_TREE;
9520         }
9521       break;
9522
9523     case TYPE_DECL:
9524     case VAR_DECL:
9525       {
9526         tree argvec = NULL_TREE;
9527         tree gen_tmpl = NULL_TREE;
9528         tree spec;
9529         tree tmpl = NULL_TREE;
9530         tree ctx;
9531         tree type = NULL_TREE;
9532         bool local_p;
9533
9534         if (TREE_CODE (t) == TYPE_DECL
9535             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9536           {
9537             /* If this is the canonical decl, we don't have to
9538                mess with instantiations, and often we can't (for
9539                typename, template type parms and such).  Note that
9540                TYPE_NAME is not correct for the above test if
9541                we've copied the type for a typedef.  */
9542             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9543             if (type == error_mark_node)
9544               RETURN (error_mark_node);
9545             r = TYPE_NAME (type);
9546             break;
9547           }
9548
9549         /* Check to see if we already have the specialization we
9550            need.  */
9551         spec = NULL_TREE;
9552         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9553           {
9554             /* T is a static data member or namespace-scope entity.
9555                We have to substitute into namespace-scope variables
9556                (even though such entities are never templates) because
9557                of cases like:
9558                
9559                  template <class T> void f() { extern T t; }
9560
9561                where the entity referenced is not known until
9562                instantiation time.  */
9563             local_p = false;
9564             ctx = DECL_CONTEXT (t);
9565             if (DECL_CLASS_SCOPE_P (t))
9566               {
9567                 ctx = tsubst_aggr_type (ctx, args,
9568                                         complain,
9569                                         in_decl, /*entering_scope=*/1);
9570                 /* If CTX is unchanged, then T is in fact the
9571                    specialization we want.  That situation occurs when
9572                    referencing a static data member within in its own
9573                    class.  We can use pointer equality, rather than
9574                    same_type_p, because DECL_CONTEXT is always
9575                    canonical.  */
9576                 if (ctx == DECL_CONTEXT (t))
9577                   spec = t;
9578               }
9579
9580             if (!spec)
9581               {
9582                 tmpl = DECL_TI_TEMPLATE (t);
9583                 gen_tmpl = most_general_template (tmpl);
9584                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9585                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9586                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9587               }
9588           }
9589         else
9590           {
9591             /* A local variable.  */
9592             local_p = true;
9593             /* Subsequent calls to pushdecl will fill this in.  */
9594             ctx = NULL_TREE;
9595             spec = retrieve_local_specialization (t);
9596           }
9597         /* If we already have the specialization we need, there is
9598            nothing more to do.  */ 
9599         if (spec)
9600           {
9601             r = spec;
9602             break;
9603           }
9604
9605         /* Create a new node for the specialization we need.  */
9606         r = copy_decl (t);
9607         if (type == NULL_TREE)
9608           {
9609             if (is_typedef_decl (t))
9610               type = DECL_ORIGINAL_TYPE (t);
9611             else
9612               type = TREE_TYPE (t);
9613             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
9614               type = strip_array_domain (type);
9615             type = tsubst (type, args, complain, in_decl);
9616           }
9617         if (TREE_CODE (r) == VAR_DECL)
9618           {
9619             /* Even if the original location is out of scope, the
9620                newly substituted one is not.  */
9621             DECL_DEAD_FOR_LOCAL (r) = 0;
9622             DECL_INITIALIZED_P (r) = 0;
9623             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9624             if (type == error_mark_node)
9625               RETURN (error_mark_node);
9626             if (TREE_CODE (type) == FUNCTION_TYPE)
9627               {
9628                 /* It may seem that this case cannot occur, since:
9629
9630                      typedef void f();
9631                      void g() { f x; }
9632
9633                    declares a function, not a variable.  However:
9634       
9635                      typedef void f();
9636                      template <typename T> void g() { T t; }
9637                      template void g<f>();
9638
9639                    is an attempt to declare a variable with function
9640                    type.  */
9641                 error ("variable %qD has function type",
9642                        /* R is not yet sufficiently initialized, so we
9643                           just use its name.  */
9644                        DECL_NAME (r));
9645                 RETURN (error_mark_node);
9646               }
9647             type = complete_type (type);
9648             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9649               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9650             type = check_var_type (DECL_NAME (r), type);
9651
9652             if (DECL_HAS_VALUE_EXPR_P (t))
9653               {
9654                 tree ve = DECL_VALUE_EXPR (t);
9655                 ve = tsubst_expr (ve, args, complain, in_decl,
9656                                   /*constant_expression_p=*/false);
9657                 SET_DECL_VALUE_EXPR (r, ve);
9658               }
9659           }
9660         else if (DECL_SELF_REFERENCE_P (t))
9661           SET_DECL_SELF_REFERENCE_P (r);
9662         TREE_TYPE (r) = type;
9663         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9664         DECL_CONTEXT (r) = ctx;
9665         /* Clear out the mangled name and RTL for the instantiation.  */
9666         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9667         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9668           SET_DECL_RTL (r, NULL);
9669         /* The initializer must not be expanded until it is required;
9670            see [temp.inst].  */
9671         DECL_INITIAL (r) = NULL_TREE;
9672         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9673           SET_DECL_RTL (r, NULL);
9674         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9675         if (TREE_CODE (r) == VAR_DECL)
9676           {
9677             /* Possibly limit visibility based on template args.  */
9678             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9679             if (DECL_VISIBILITY_SPECIFIED (t))
9680               {
9681                 DECL_VISIBILITY_SPECIFIED (r) = 0;
9682                 DECL_ATTRIBUTES (r)
9683                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9684               }
9685             determine_visibility (r);
9686           }
9687
9688         if (!local_p)
9689           {
9690             /* A static data member declaration is always marked
9691                external when it is declared in-class, even if an
9692                initializer is present.  We mimic the non-template
9693                processing here.  */
9694             DECL_EXTERNAL (r) = 1;
9695
9696             register_specialization (r, gen_tmpl, argvec, false, hash);
9697             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
9698             SET_DECL_IMPLICIT_INSTANTIATION (r);
9699           }
9700         else if (cp_unevaluated_operand)
9701           {
9702             /* We're substituting this var in a decltype outside of its
9703                scope, such as for a lambda return type.  Don't add it to
9704                local_specializations, do perform auto deduction.  */
9705             tree auto_node = type_uses_auto (type);
9706             tree init
9707               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9708                              /*constant_expression_p=*/false);
9709
9710             if (auto_node && init && describable_type (init))
9711               {
9712                 type = do_auto_deduction (type, init, auto_node);
9713                 TREE_TYPE (r) = type;
9714               }
9715           }
9716         else
9717           register_local_specialization (r, t);
9718
9719         DECL_CHAIN (r) = NULL_TREE;
9720
9721         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9722                                         /*flags=*/0,
9723                                         args, complain, in_decl);
9724
9725         /* Preserve a typedef that names a type.  */
9726         if (is_typedef_decl (r))
9727           {
9728             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
9729             set_underlying_type (r);
9730           }
9731
9732         layout_decl (r, 0);
9733       }
9734       break;
9735
9736     default:
9737       gcc_unreachable ();
9738     }
9739 #undef RETURN
9740
9741  out:
9742   /* Restore the file and line information.  */
9743   input_location = saved_loc;
9744
9745   return r;
9746 }
9747
9748 /* Substitute into the ARG_TYPES of a function type.  */
9749
9750 static tree
9751 tsubst_arg_types (tree arg_types,
9752                   tree args,
9753                   tsubst_flags_t complain,
9754                   tree in_decl)
9755 {
9756   tree remaining_arg_types;
9757   tree type = NULL_TREE;
9758   int i = 1;
9759   tree expanded_args = NULL_TREE;
9760   tree default_arg;
9761
9762   if (!arg_types || arg_types == void_list_node)
9763     return arg_types;
9764
9765   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9766                                           args, complain, in_decl);
9767   if (remaining_arg_types == error_mark_node)
9768     return error_mark_node;
9769
9770   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9771     {
9772       /* For a pack expansion, perform substitution on the
9773          entire expression. Later on, we'll handle the arguments
9774          one-by-one.  */
9775       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9776                                             args, complain, in_decl);
9777
9778       if (TREE_CODE (expanded_args) == TREE_VEC)
9779         /* So that we'll spin through the parameters, one by one.  */
9780         i = TREE_VEC_LENGTH (expanded_args);
9781       else
9782         {
9783           /* We only partially substituted into the parameter
9784              pack. Our type is TYPE_PACK_EXPANSION.  */
9785           type = expanded_args;
9786           expanded_args = NULL_TREE;
9787         }
9788     }
9789
9790   while (i > 0) {
9791     --i;
9792     
9793     if (expanded_args)
9794       type = TREE_VEC_ELT (expanded_args, i);
9795     else if (!type)
9796       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9797
9798     if (type == error_mark_node)
9799       return error_mark_node;
9800     if (VOID_TYPE_P (type))
9801       {
9802         if (complain & tf_error)
9803           {
9804             error ("invalid parameter type %qT", type);
9805             if (in_decl)
9806               error ("in declaration %q+D", in_decl);
9807           }
9808         return error_mark_node;
9809     }
9810     
9811     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9812        top-level qualifiers as required.  */
9813     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9814
9815     /* We do not substitute into default arguments here.  The standard
9816        mandates that they be instantiated only when needed, which is
9817        done in build_over_call.  */
9818     default_arg = TREE_PURPOSE (arg_types);
9819
9820     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9821       {
9822         /* We've instantiated a template before its default arguments
9823            have been parsed.  This can happen for a nested template
9824            class, and is not an error unless we require the default
9825            argument in a call of this function.  */
9826         remaining_arg_types = 
9827           tree_cons (default_arg, type, remaining_arg_types);
9828         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9829                        remaining_arg_types);
9830       }
9831     else
9832       remaining_arg_types = 
9833         hash_tree_cons (default_arg, type, remaining_arg_types);
9834   }
9835         
9836   return remaining_arg_types;
9837 }
9838
9839 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9840    *not* handle the exception-specification for FNTYPE, because the
9841    initial substitution of explicitly provided template parameters
9842    during argument deduction forbids substitution into the
9843    exception-specification:
9844
9845      [temp.deduct]
9846
9847      All references in the function type of the function template to  the
9848      corresponding template parameters are replaced by the specified tem-
9849      plate argument values.  If a substitution in a template parameter or
9850      in  the function type of the function template results in an invalid
9851      type, type deduction fails.  [Note: The equivalent  substitution  in
9852      exception specifications is done only when the function is instanti-
9853      ated, at which point a program is  ill-formed  if  the  substitution
9854      results in an invalid type.]  */
9855
9856 static tree
9857 tsubst_function_type (tree t,
9858                       tree args,
9859                       tsubst_flags_t complain,
9860                       tree in_decl)
9861 {
9862   tree return_type;
9863   tree arg_types;
9864   tree fntype;
9865
9866   /* The TYPE_CONTEXT is not used for function/method types.  */
9867   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9868
9869   /* Substitute the return type.  */
9870   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9871   if (return_type == error_mark_node)
9872     return error_mark_node;
9873   /* The standard does not presently indicate that creation of a
9874      function type with an invalid return type is a deduction failure.
9875      However, that is clearly analogous to creating an array of "void"
9876      or a reference to a reference.  This is core issue #486.  */
9877   if (TREE_CODE (return_type) == ARRAY_TYPE
9878       || TREE_CODE (return_type) == FUNCTION_TYPE)
9879     {
9880       if (complain & tf_error)
9881         {
9882           if (TREE_CODE (return_type) == ARRAY_TYPE)
9883             error ("function returning an array");
9884           else
9885             error ("function returning a function");
9886         }
9887       return error_mark_node;
9888     }
9889
9890   /* Substitute the argument types.  */
9891   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9892                                 complain, in_decl);
9893   if (arg_types == error_mark_node)
9894     return error_mark_node;
9895
9896   /* Construct a new type node and return it.  */
9897   if (TREE_CODE (t) == FUNCTION_TYPE)
9898     {
9899       fntype = build_function_type (return_type, arg_types);
9900       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
9901     }
9902   else
9903     {
9904       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9905       if (! MAYBE_CLASS_TYPE_P (r))
9906         {
9907           /* [temp.deduct]
9908
9909              Type deduction may fail for any of the following
9910              reasons:
9911
9912              -- Attempting to create "pointer to member of T" when T
9913              is not a class type.  */
9914           if (complain & tf_error)
9915             error ("creating pointer to member function of non-class type %qT",
9916                       r);
9917           return error_mark_node;
9918         }
9919
9920       fntype = build_method_type_directly (r, return_type,
9921                                            TREE_CHAIN (arg_types));
9922     }
9923   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9924
9925   return fntype;
9926 }
9927
9928 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9929    ARGS into that specification, and return the substituted
9930    specification.  If there is no specification, return NULL_TREE.  */
9931
9932 static tree
9933 tsubst_exception_specification (tree fntype,
9934                                 tree args,
9935                                 tsubst_flags_t complain,
9936                                 tree in_decl)
9937 {
9938   tree specs;
9939   tree new_specs;
9940
9941   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9942   new_specs = NULL_TREE;
9943   if (specs && TREE_PURPOSE (specs))
9944     {
9945       /* A noexcept-specifier.  */
9946       new_specs = tsubst_copy_and_build
9947         (TREE_PURPOSE (specs), args, complain, in_decl, /*function_p=*/false,
9948          /*integral_constant_expression_p=*/true);
9949       new_specs = build_noexcept_spec (new_specs, complain);
9950     }
9951   else if (specs)
9952     {
9953       if (! TREE_VALUE (specs))
9954         new_specs = specs;
9955       else
9956         while (specs)
9957           {
9958             tree spec;
9959             int i, len = 1;
9960             tree expanded_specs = NULL_TREE;
9961
9962             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9963               {
9964                 /* Expand the pack expansion type.  */
9965                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9966                                                        args, complain,
9967                                                        in_decl);
9968
9969                 if (expanded_specs == error_mark_node)
9970                   return error_mark_node;
9971                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9972                   len = TREE_VEC_LENGTH (expanded_specs);
9973                 else
9974                   {
9975                     /* We're substituting into a member template, so
9976                        we got a TYPE_PACK_EXPANSION back.  Add that
9977                        expansion and move on.  */
9978                     gcc_assert (TREE_CODE (expanded_specs) 
9979                                 == TYPE_PACK_EXPANSION);
9980                     new_specs = add_exception_specifier (new_specs,
9981                                                          expanded_specs,
9982                                                          complain);
9983                     specs = TREE_CHAIN (specs);
9984                     continue;
9985                   }
9986               }
9987
9988             for (i = 0; i < len; ++i)
9989               {
9990                 if (expanded_specs)
9991                   spec = TREE_VEC_ELT (expanded_specs, i);
9992                 else
9993                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9994                 if (spec == error_mark_node)
9995                   return spec;
9996                 new_specs = add_exception_specifier (new_specs, spec, 
9997                                                      complain);
9998               }
9999
10000             specs = TREE_CHAIN (specs);
10001           }
10002     }
10003   return new_specs;
10004 }
10005
10006 /* Take the tree structure T and replace template parameters used
10007    therein with the argument vector ARGS.  IN_DECL is an associated
10008    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
10009    Issue error and warning messages under control of COMPLAIN.  Note
10010    that we must be relatively non-tolerant of extensions here, in
10011    order to preserve conformance; if we allow substitutions that
10012    should not be allowed, we may allow argument deductions that should
10013    not succeed, and therefore report ambiguous overload situations
10014    where there are none.  In theory, we could allow the substitution,
10015    but indicate that it should have failed, and allow our caller to
10016    make sure that the right thing happens, but we don't try to do this
10017    yet.
10018
10019    This function is used for dealing with types, decls and the like;
10020    for expressions, use tsubst_expr or tsubst_copy.  */
10021
10022 tree
10023 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10024 {
10025   enum tree_code code;
10026   tree type, r;
10027
10028   if (t == NULL_TREE || t == error_mark_node
10029       || t == integer_type_node
10030       || t == void_type_node
10031       || t == char_type_node
10032       || t == unknown_type_node
10033       || TREE_CODE (t) == NAMESPACE_DECL
10034       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
10035     return t;
10036
10037   if (DECL_P (t))
10038     return tsubst_decl (t, args, complain);
10039
10040   if (args == NULL_TREE)
10041     return t;
10042
10043   code = TREE_CODE (t);
10044
10045   if (code == IDENTIFIER_NODE)
10046     type = IDENTIFIER_TYPE_VALUE (t);
10047   else
10048     type = TREE_TYPE (t);
10049
10050   gcc_assert (type != unknown_type_node);
10051
10052   /* Reuse typedefs.  We need to do this to handle dependent attributes,
10053      such as attribute aligned.  */
10054   if (TYPE_P (t)
10055       && typedef_variant_p (t))
10056     {
10057       tree decl = TYPE_NAME (t);
10058       
10059       if (DECL_CLASS_SCOPE_P (decl)
10060           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
10061           && uses_template_parms (DECL_CONTEXT (decl)))
10062         {
10063           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10064           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
10065           r = retrieve_specialization (tmpl, gen_args, 0);
10066         }
10067       else if (DECL_FUNCTION_SCOPE_P (decl)
10068                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10069                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10070         r = retrieve_local_specialization (decl);
10071       else
10072         /* The typedef is from a non-template context.  */
10073         return t;
10074
10075       if (r)
10076         {
10077           r = TREE_TYPE (r);
10078           r = cp_build_qualified_type_real
10079             (r, cp_type_quals (t) | cp_type_quals (r),
10080              complain | tf_ignore_bad_quals);
10081           return r;
10082         }
10083       /* Else we must be instantiating the typedef, so fall through.  */
10084     }
10085
10086   if (type
10087       && code != TYPENAME_TYPE
10088       && code != TEMPLATE_TYPE_PARM
10089       && code != IDENTIFIER_NODE
10090       && code != FUNCTION_TYPE
10091       && code != METHOD_TYPE)
10092     type = tsubst (type, args, complain, in_decl);
10093   if (type == error_mark_node)
10094     return error_mark_node;
10095
10096   switch (code)
10097     {
10098     case RECORD_TYPE:
10099     case UNION_TYPE:
10100     case ENUMERAL_TYPE:
10101       return tsubst_aggr_type (t, args, complain, in_decl,
10102                                /*entering_scope=*/0);
10103
10104     case ERROR_MARK:
10105     case IDENTIFIER_NODE:
10106     case VOID_TYPE:
10107     case REAL_TYPE:
10108     case COMPLEX_TYPE:
10109     case VECTOR_TYPE:
10110     case BOOLEAN_TYPE:
10111     case NULLPTR_TYPE:
10112     case LANG_TYPE:
10113       return t;
10114
10115     case INTEGER_TYPE:
10116       if (t == integer_type_node)
10117         return t;
10118
10119       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10120           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10121         return t;
10122
10123       {
10124         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10125
10126         max = tsubst_expr (omax, args, complain, in_decl,
10127                            /*integral_constant_expression_p=*/false);
10128
10129         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10130            needed.  */
10131         if (TREE_CODE (max) == NOP_EXPR
10132             && TREE_SIDE_EFFECTS (omax)
10133             && !TREE_TYPE (max))
10134           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10135
10136         max = mark_rvalue_use (max);
10137         max = fold_decl_constant_value (max);
10138
10139         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10140            with TREE_SIDE_EFFECTS that indicates this is not an integral
10141            constant expression.  */
10142         if (processing_template_decl
10143             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10144           {
10145             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10146             TREE_SIDE_EFFECTS (max) = 1;
10147           }
10148
10149         if (TREE_CODE (max) != INTEGER_CST
10150             && !at_function_scope_p ()
10151             && !TREE_SIDE_EFFECTS (max)
10152             && !value_dependent_expression_p (max))
10153           {
10154             if (complain & tf_error)
10155               error ("array bound is not an integer constant");
10156             return error_mark_node;
10157           }
10158
10159         /* [temp.deduct]
10160
10161            Type deduction may fail for any of the following
10162            reasons:
10163
10164              Attempting to create an array with a size that is
10165              zero or negative.  */
10166         if (integer_zerop (max) && !(complain & tf_error))
10167           /* We must fail if performing argument deduction (as
10168              indicated by the state of complain), so that
10169              another substitution can be found.  */
10170           return error_mark_node;
10171         else if (TREE_CODE (max) == INTEGER_CST
10172                  && INT_CST_LT (max, integer_zero_node))
10173           {
10174             if (complain & tf_error)
10175               error ("creating array with negative size (%qE)", max);
10176
10177             return error_mark_node;
10178           }
10179
10180         return compute_array_index_type (NULL_TREE, max);
10181       }
10182
10183     case TEMPLATE_TYPE_PARM:
10184     case TEMPLATE_TEMPLATE_PARM:
10185     case BOUND_TEMPLATE_TEMPLATE_PARM:
10186     case TEMPLATE_PARM_INDEX:
10187       {
10188         int idx;
10189         int level;
10190         int levels;
10191         tree arg = NULL_TREE;
10192
10193         r = NULL_TREE;
10194
10195         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10196         template_parm_level_and_index (t, &level, &idx); 
10197
10198         levels = TMPL_ARGS_DEPTH (args);
10199         if (level <= levels)
10200           {
10201             arg = TMPL_ARG (args, level, idx);
10202
10203             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10204               /* See through ARGUMENT_PACK_SELECT arguments. */
10205               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10206           }
10207
10208         if (arg == error_mark_node)
10209           return error_mark_node;
10210         else if (arg != NULL_TREE)
10211           {
10212             if (ARGUMENT_PACK_P (arg))
10213               /* If ARG is an argument pack, we don't actually want to
10214                  perform a substitution here, because substitutions
10215                  for argument packs are only done
10216                  element-by-element. We can get to this point when
10217                  substituting the type of a non-type template
10218                  parameter pack, when that type actually contains
10219                  template parameter packs from an outer template, e.g.,
10220
10221                  template<typename... Types> struct A {
10222                    template<Types... Values> struct B { };
10223                  };  */
10224               return t;
10225
10226             if (code == TEMPLATE_TYPE_PARM)
10227               {
10228                 int quals;
10229                 gcc_assert (TYPE_P (arg));
10230
10231                 quals = cp_type_quals (arg) | cp_type_quals (t);
10232                   
10233                 return cp_build_qualified_type_real
10234                   (arg, quals, complain | tf_ignore_bad_quals);
10235               }
10236             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10237               {
10238                 /* We are processing a type constructed from a
10239                    template template parameter.  */
10240                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10241                                       args, complain, in_decl);
10242                 if (argvec == error_mark_node)
10243                   return error_mark_node;
10244
10245                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10246                    are resolving nested-types in the signature of a
10247                    member function templates.  Otherwise ARG is a
10248                    TEMPLATE_DECL and is the real template to be
10249                    instantiated.  */
10250                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10251                   arg = TYPE_NAME (arg);
10252
10253                 r = lookup_template_class (arg,
10254                                            argvec, in_decl,
10255                                            DECL_CONTEXT (arg),
10256                                             /*entering_scope=*/0,
10257                                            complain);
10258                 return cp_build_qualified_type_real
10259                   (r, cp_type_quals (t), complain);
10260               }
10261             else
10262               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10263               return unshare_expr (arg);
10264           }
10265
10266         if (level == 1)
10267           /* This can happen during the attempted tsubst'ing in
10268              unify.  This means that we don't yet have any information
10269              about the template parameter in question.  */
10270           return t;
10271
10272         /* If we get here, we must have been looking at a parm for a
10273            more deeply nested template.  Make a new version of this
10274            template parameter, but with a lower level.  */
10275         switch (code)
10276           {
10277           case TEMPLATE_TYPE_PARM:
10278           case TEMPLATE_TEMPLATE_PARM:
10279           case BOUND_TEMPLATE_TEMPLATE_PARM:
10280             if (cp_type_quals (t))
10281               {
10282                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10283                 r = cp_build_qualified_type_real
10284                   (r, cp_type_quals (t),
10285                    complain | (code == TEMPLATE_TYPE_PARM
10286                                ? tf_ignore_bad_quals : 0));
10287               }
10288             else
10289               {
10290                 r = copy_type (t);
10291                 TEMPLATE_TYPE_PARM_INDEX (r)
10292                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10293                                                 r, levels, args, complain);
10294                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10295                 TYPE_MAIN_VARIANT (r) = r;
10296                 TYPE_POINTER_TO (r) = NULL_TREE;
10297                 TYPE_REFERENCE_TO (r) = NULL_TREE;
10298
10299                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10300                   /* We have reduced the level of the template
10301                      template parameter, but not the levels of its
10302                      template parameters, so canonical_type_parameter
10303                      will not be able to find the canonical template
10304                      template parameter for this level. Thus, we
10305                      require structural equality checking to compare
10306                      TEMPLATE_TEMPLATE_PARMs. */
10307                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10308                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10309                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10310                 else
10311                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
10312
10313                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10314                   {
10315                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10316                                           complain, in_decl);
10317                     if (argvec == error_mark_node)
10318                       return error_mark_node;
10319
10320                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10321                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10322                   }
10323               }
10324             break;
10325
10326           case TEMPLATE_PARM_INDEX:
10327             r = reduce_template_parm_level (t, type, levels, args, complain);
10328             break;
10329
10330           default:
10331             gcc_unreachable ();
10332           }
10333
10334         return r;
10335       }
10336
10337     case TREE_LIST:
10338       {
10339         tree purpose, value, chain;
10340
10341         if (t == void_list_node)
10342           return t;
10343
10344         purpose = TREE_PURPOSE (t);
10345         if (purpose)
10346           {
10347             purpose = tsubst (purpose, args, complain, in_decl);
10348             if (purpose == error_mark_node)
10349               return error_mark_node;
10350           }
10351         value = TREE_VALUE (t);
10352         if (value)
10353           {
10354             value = tsubst (value, args, complain, in_decl);
10355             if (value == error_mark_node)
10356               return error_mark_node;
10357           }
10358         chain = TREE_CHAIN (t);
10359         if (chain && chain != void_type_node)
10360           {
10361             chain = tsubst (chain, args, complain, in_decl);
10362             if (chain == error_mark_node)
10363               return error_mark_node;
10364           }
10365         if (purpose == TREE_PURPOSE (t)
10366             && value == TREE_VALUE (t)
10367             && chain == TREE_CHAIN (t))
10368           return t;
10369         return hash_tree_cons (purpose, value, chain);
10370       }
10371
10372     case TREE_BINFO:
10373       /* We should never be tsubsting a binfo.  */
10374       gcc_unreachable ();
10375
10376     case TREE_VEC:
10377       /* A vector of template arguments.  */
10378       gcc_assert (!type);
10379       return tsubst_template_args (t, args, complain, in_decl);
10380
10381     case POINTER_TYPE:
10382     case REFERENCE_TYPE:
10383       {
10384         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10385           return t;
10386
10387         /* [temp.deduct]
10388
10389            Type deduction may fail for any of the following
10390            reasons:
10391
10392            -- Attempting to create a pointer to reference type.
10393            -- Attempting to create a reference to a reference type or
10394               a reference to void.
10395
10396           Core issue 106 says that creating a reference to a reference
10397           during instantiation is no longer a cause for failure. We
10398           only enforce this check in strict C++98 mode.  */
10399         if ((TREE_CODE (type) == REFERENCE_TYPE
10400              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10401             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10402           {
10403             static location_t last_loc;
10404
10405             /* We keep track of the last time we issued this error
10406                message to avoid spewing a ton of messages during a
10407                single bad template instantiation.  */
10408             if (complain & tf_error
10409                 && last_loc != input_location)
10410               {
10411                 if (TREE_CODE (type) == VOID_TYPE)
10412                   error ("forming reference to void");
10413                else if (code == POINTER_TYPE)
10414                  error ("forming pointer to reference type %qT", type);
10415                else
10416                   error ("forming reference to reference type %qT", type);
10417                 last_loc = input_location;
10418               }
10419
10420             return error_mark_node;
10421           }
10422         else if (code == POINTER_TYPE)
10423           {
10424             r = build_pointer_type (type);
10425             if (TREE_CODE (type) == METHOD_TYPE)
10426               r = build_ptrmemfunc_type (r);
10427           }
10428         else if (TREE_CODE (type) == REFERENCE_TYPE)
10429           /* In C++0x, during template argument substitution, when there is an
10430              attempt to create a reference to a reference type, reference
10431              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10432
10433              "If a template-argument for a template-parameter T names a type
10434              that is a reference to a type A, an attempt to create the type
10435              'lvalue reference to cv T' creates the type 'lvalue reference to
10436              A,' while an attempt to create the type type rvalue reference to
10437              cv T' creates the type T"
10438           */
10439           r = cp_build_reference_type
10440               (TREE_TYPE (type),
10441                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10442         else
10443           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10444         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
10445
10446         if (r != error_mark_node)
10447           /* Will this ever be needed for TYPE_..._TO values?  */
10448           layout_type (r);
10449
10450         return r;
10451       }
10452     case OFFSET_TYPE:
10453       {
10454         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10455         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10456           {
10457             /* [temp.deduct]
10458
10459                Type deduction may fail for any of the following
10460                reasons:
10461
10462                -- Attempting to create "pointer to member of T" when T
10463                   is not a class type.  */
10464             if (complain & tf_error)
10465               error ("creating pointer to member of non-class type %qT", r);
10466             return error_mark_node;
10467           }
10468         if (TREE_CODE (type) == REFERENCE_TYPE)
10469           {
10470             if (complain & tf_error)
10471               error ("creating pointer to member reference type %qT", type);
10472             return error_mark_node;
10473           }
10474         if (TREE_CODE (type) == VOID_TYPE)
10475           {
10476             if (complain & tf_error)
10477               error ("creating pointer to member of type void");
10478             return error_mark_node;
10479           }
10480         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10481         if (TREE_CODE (type) == FUNCTION_TYPE)
10482           {
10483             /* The type of the implicit object parameter gets its
10484                cv-qualifiers from the FUNCTION_TYPE. */
10485             tree memptr;
10486             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
10487             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10488             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10489                                                  complain);
10490           }
10491         else
10492           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10493                                                cp_type_quals (t),
10494                                                complain);
10495       }
10496     case FUNCTION_TYPE:
10497     case METHOD_TYPE:
10498       {
10499         tree fntype;
10500         tree specs;
10501         fntype = tsubst_function_type (t, args, complain, in_decl);
10502         if (fntype == error_mark_node)
10503           return error_mark_node;
10504
10505         /* Substitute the exception specification.  */
10506         specs = tsubst_exception_specification (t, args, complain,
10507                                                 in_decl);
10508         if (specs == error_mark_node)
10509           return error_mark_node;
10510         if (specs)
10511           fntype = build_exception_variant (fntype, specs);
10512         return fntype;
10513       }
10514     case ARRAY_TYPE:
10515       {
10516         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10517         if (domain == error_mark_node)
10518           return error_mark_node;
10519
10520         /* As an optimization, we avoid regenerating the array type if
10521            it will obviously be the same as T.  */
10522         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10523           return t;
10524
10525         /* These checks should match the ones in grokdeclarator.
10526
10527            [temp.deduct]
10528
10529            The deduction may fail for any of the following reasons:
10530
10531            -- Attempting to create an array with an element type that
10532               is void, a function type, or a reference type, or [DR337]
10533               an abstract class type.  */
10534         if (TREE_CODE (type) == VOID_TYPE
10535             || TREE_CODE (type) == FUNCTION_TYPE
10536             || TREE_CODE (type) == REFERENCE_TYPE)
10537           {
10538             if (complain & tf_error)
10539               error ("creating array of %qT", type);
10540             return error_mark_node;
10541           }
10542         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10543           {
10544             if (complain & tf_error)
10545               error ("creating array of %qT, which is an abstract class type",
10546                      type);
10547             return error_mark_node;
10548           }
10549
10550         r = build_cplus_array_type (type, domain);
10551
10552         if (TYPE_USER_ALIGN (t))
10553           {
10554             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10555             TYPE_USER_ALIGN (r) = 1;
10556           }
10557
10558         return r;
10559       }
10560
10561     case TYPENAME_TYPE:
10562       {
10563         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10564                                      in_decl, /*entering_scope=*/1);
10565         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10566                               complain, in_decl);
10567
10568         if (ctx == error_mark_node || f == error_mark_node)
10569           return error_mark_node;
10570
10571         if (!MAYBE_CLASS_TYPE_P (ctx))
10572           {
10573             if (complain & tf_error)
10574               error ("%qT is not a class, struct, or union type", ctx);
10575             return error_mark_node;
10576           }
10577         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10578           {
10579             /* Normally, make_typename_type does not require that the CTX
10580                have complete type in order to allow things like:
10581
10582                  template <class T> struct S { typename S<T>::X Y; };
10583
10584                But, such constructs have already been resolved by this
10585                point, so here CTX really should have complete type, unless
10586                it's a partial instantiation.  */
10587             if (!(complain & tf_no_class_instantiations))
10588               ctx = complete_type (ctx);
10589             if (!COMPLETE_TYPE_P (ctx))
10590               {
10591                 if (complain & tf_error)
10592                   cxx_incomplete_type_error (NULL_TREE, ctx);
10593                 return error_mark_node;
10594               }
10595           }
10596
10597         f = make_typename_type (ctx, f, typename_type,
10598                                 (complain & tf_error) | tf_keep_type_decl);
10599         if (f == error_mark_node)
10600           return f;
10601         if (TREE_CODE (f) == TYPE_DECL)
10602           {
10603             complain |= tf_ignore_bad_quals;
10604             f = TREE_TYPE (f);
10605           }
10606
10607         if (TREE_CODE (f) != TYPENAME_TYPE)
10608           {
10609             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10610               error ("%qT resolves to %qT, which is not an enumeration type",
10611                      t, f);
10612             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10613               error ("%qT resolves to %qT, which is is not a class type",
10614                      t, f);
10615           }
10616
10617         return cp_build_qualified_type_real
10618           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10619       }
10620
10621     case UNBOUND_CLASS_TEMPLATE:
10622       {
10623         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10624                                      in_decl, /*entering_scope=*/1);
10625         tree name = TYPE_IDENTIFIER (t);
10626         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10627
10628         if (ctx == error_mark_node || name == error_mark_node)
10629           return error_mark_node;
10630
10631         if (parm_list)
10632           parm_list = tsubst_template_parms (parm_list, args, complain);
10633         return make_unbound_class_template (ctx, name, parm_list, complain);
10634       }
10635
10636     case TYPEOF_TYPE:
10637       {
10638         tree type;
10639
10640         ++cp_unevaluated_operand;
10641         ++c_inhibit_evaluation_warnings;
10642
10643         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10644                             complain, in_decl,
10645                             /*integral_constant_expression_p=*/false);
10646
10647         --cp_unevaluated_operand;
10648         --c_inhibit_evaluation_warnings;
10649
10650         type = finish_typeof (type);
10651         return cp_build_qualified_type_real (type,
10652                                              cp_type_quals (t)
10653                                              | cp_type_quals (type),
10654                                              complain);
10655       }
10656
10657     case DECLTYPE_TYPE:
10658       {
10659         tree type;
10660
10661         ++cp_unevaluated_operand;
10662         ++c_inhibit_evaluation_warnings;
10663
10664         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10665                             complain, in_decl,
10666                             /*integral_constant_expression_p=*/false);
10667
10668         --cp_unevaluated_operand;
10669         --c_inhibit_evaluation_warnings;
10670
10671         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10672           type = lambda_capture_field_type (type);
10673         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10674           type = lambda_return_type (type);
10675         else
10676           type = finish_decltype_type
10677             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10678         return cp_build_qualified_type_real (type,
10679                                              cp_type_quals (t)
10680                                              | cp_type_quals (type),
10681                                              complain);
10682       }
10683
10684     case TYPE_ARGUMENT_PACK:
10685     case NONTYPE_ARGUMENT_PACK:
10686       {
10687         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
10688         tree packed_out = 
10689           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10690                                 args,
10691                                 complain,
10692                                 in_decl);
10693         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10694
10695         /* For template nontype argument packs, also substitute into
10696            the type.  */
10697         if (code == NONTYPE_ARGUMENT_PACK)
10698           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10699
10700         return r;
10701       }
10702       break;
10703
10704     case INTEGER_CST:
10705     case REAL_CST:
10706     case STRING_CST:
10707     case PLUS_EXPR:
10708     case MINUS_EXPR:
10709     case NEGATE_EXPR:
10710     case NOP_EXPR:
10711     case INDIRECT_REF:
10712     case ADDR_EXPR:
10713     case CALL_EXPR:
10714     case ARRAY_REF:
10715     case SCOPE_REF:
10716       /* We should use one of the expression tsubsts for these codes.  */
10717       gcc_unreachable ();
10718
10719     default:
10720       sorry ("use of %qs in template", tree_code_name [(int) code]);
10721       return error_mark_node;
10722     }
10723 }
10724
10725 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10726    type of the expression on the left-hand side of the "." or "->"
10727    operator.  */
10728
10729 static tree
10730 tsubst_baselink (tree baselink, tree object_type,
10731                  tree args, tsubst_flags_t complain, tree in_decl)
10732 {
10733     tree name;
10734     tree qualifying_scope;
10735     tree fns;
10736     tree optype;
10737     tree template_args = 0;
10738     bool template_id_p = false;
10739
10740     /* A baselink indicates a function from a base class.  Both the
10741        BASELINK_ACCESS_BINFO and the base class referenced may
10742        indicate bases of the template class, rather than the
10743        instantiated class.  In addition, lookups that were not
10744        ambiguous before may be ambiguous now.  Therefore, we perform
10745        the lookup again.  */
10746     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10747     qualifying_scope = tsubst (qualifying_scope, args,
10748                                complain, in_decl);
10749     fns = BASELINK_FUNCTIONS (baselink);
10750     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10751     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10752       {
10753         template_id_p = true;
10754         template_args = TREE_OPERAND (fns, 1);
10755         fns = TREE_OPERAND (fns, 0);
10756         if (template_args)
10757           template_args = tsubst_template_args (template_args, args,
10758                                                 complain, in_decl);
10759       }
10760     name = DECL_NAME (get_first_fn (fns));
10761     if (IDENTIFIER_TYPENAME_P (name))
10762       name = mangle_conv_op_name_for_type (optype);
10763     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10764     if (!baselink)
10765       return error_mark_node;
10766
10767     /* If lookup found a single function, mark it as used at this
10768        point.  (If it lookup found multiple functions the one selected
10769        later by overload resolution will be marked as used at that
10770        point.)  */
10771     if (BASELINK_P (baselink))
10772       fns = BASELINK_FUNCTIONS (baselink);
10773     if (!template_id_p && !really_overloaded_fn (fns))
10774       mark_used (OVL_CURRENT (fns));
10775
10776     /* Add back the template arguments, if present.  */
10777     if (BASELINK_P (baselink) && template_id_p)
10778       BASELINK_FUNCTIONS (baselink)
10779         = build_nt (TEMPLATE_ID_EXPR,
10780                     BASELINK_FUNCTIONS (baselink),
10781                     template_args);
10782     /* Update the conversion operator type.  */
10783     BASELINK_OPTYPE (baselink) = optype;
10784
10785     if (!object_type)
10786       object_type = current_class_type;
10787     return adjust_result_of_qualified_name_lookup (baselink,
10788                                                    qualifying_scope,
10789                                                    object_type);
10790 }
10791
10792 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10793    true if the qualified-id will be a postfix-expression in-and-of
10794    itself; false if more of the postfix-expression follows the
10795    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10796    of "&".  */
10797
10798 static tree
10799 tsubst_qualified_id (tree qualified_id, tree args,
10800                      tsubst_flags_t complain, tree in_decl,
10801                      bool done, bool address_p)
10802 {
10803   tree expr;
10804   tree scope;
10805   tree name;
10806   bool is_template;
10807   tree template_args;
10808
10809   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10810
10811   /* Figure out what name to look up.  */
10812   name = TREE_OPERAND (qualified_id, 1);
10813   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10814     {
10815       is_template = true;
10816       template_args = TREE_OPERAND (name, 1);
10817       if (template_args)
10818         template_args = tsubst_template_args (template_args, args,
10819                                               complain, in_decl);
10820       name = TREE_OPERAND (name, 0);
10821     }
10822   else
10823     {
10824       is_template = false;
10825       template_args = NULL_TREE;
10826     }
10827
10828   /* Substitute into the qualifying scope.  When there are no ARGS, we
10829      are just trying to simplify a non-dependent expression.  In that
10830      case the qualifying scope may be dependent, and, in any case,
10831      substituting will not help.  */
10832   scope = TREE_OPERAND (qualified_id, 0);
10833   if (args)
10834     {
10835       scope = tsubst (scope, args, complain, in_decl);
10836       expr = tsubst_copy (name, args, complain, in_decl);
10837     }
10838   else
10839     expr = name;
10840
10841   if (dependent_scope_p (scope))
10842     return build_qualified_name (NULL_TREE, scope, expr,
10843                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10844
10845   if (!BASELINK_P (name) && !DECL_P (expr))
10846     {
10847       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10848         {
10849           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10850           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10851             {
10852               error ("qualifying type %qT does not match destructor name ~%qT",
10853                      scope, TREE_OPERAND (expr, 0));
10854               expr = error_mark_node;
10855             }
10856           else
10857             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10858                                           /*is_type_p=*/0, false);
10859         }
10860       else
10861         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10862       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10863                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10864         {
10865           if (complain & tf_error)
10866             {
10867               error ("dependent-name %qE is parsed as a non-type, but "
10868                      "instantiation yields a type", qualified_id);
10869               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10870             }
10871           return error_mark_node;
10872         }
10873     }
10874
10875   if (DECL_P (expr))
10876     {
10877       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10878                                            scope);
10879       /* Remember that there was a reference to this entity.  */
10880       mark_used (expr);
10881     }
10882
10883   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10884     {
10885       if (complain & tf_error)
10886         qualified_name_lookup_error (scope,
10887                                      TREE_OPERAND (qualified_id, 1),
10888                                      expr, input_location);
10889       return error_mark_node;
10890     }
10891
10892   if (is_template)
10893     expr = lookup_template_function (expr, template_args);
10894
10895   if (expr == error_mark_node && complain & tf_error)
10896     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10897                                  expr, input_location);
10898   else if (TYPE_P (scope))
10899     {
10900       expr = (adjust_result_of_qualified_name_lookup
10901               (expr, scope, current_class_type));
10902       expr = (finish_qualified_id_expr
10903               (scope, expr, done, address_p,
10904                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10905                /*template_arg_p=*/false));
10906     }
10907
10908   /* Expressions do not generally have reference type.  */
10909   if (TREE_CODE (expr) != SCOPE_REF
10910       /* However, if we're about to form a pointer-to-member, we just
10911          want the referenced member referenced.  */
10912       && TREE_CODE (expr) != OFFSET_REF)
10913     expr = convert_from_reference (expr);
10914
10915   return expr;
10916 }
10917
10918 /* Like tsubst, but deals with expressions.  This function just replaces
10919    template parms; to finish processing the resultant expression, use
10920    tsubst_expr.  */
10921
10922 static tree
10923 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10924 {
10925   enum tree_code code;
10926   tree r;
10927
10928   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10929     return t;
10930
10931   code = TREE_CODE (t);
10932
10933   switch (code)
10934     {
10935     case PARM_DECL:
10936       r = retrieve_local_specialization (t);
10937
10938       if (r == NULL)
10939         {
10940           tree c;
10941           /* This can happen for a parameter name used later in a function
10942              declaration (such as in a late-specified return type).  Just
10943              make a dummy decl, since it's only used for its type.  */
10944           gcc_assert (cp_unevaluated_operand != 0);
10945           /* We copy T because want to tsubst the PARM_DECL only,
10946              not the following PARM_DECLs that are chained to T.  */
10947           c = copy_node (t);
10948           r = tsubst_decl (c, args, complain);
10949           /* Give it the template pattern as its context; its true context
10950              hasn't been instantiated yet and this is good enough for
10951              mangling.  */
10952           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10953         }
10954       
10955       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10956         r = ARGUMENT_PACK_SELECT_ARG (r);
10957       mark_used (r);
10958       return r;
10959
10960     case CONST_DECL:
10961       {
10962         tree enum_type;
10963         tree v;
10964
10965         if (DECL_TEMPLATE_PARM_P (t))
10966           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10967         /* There is no need to substitute into namespace-scope
10968            enumerators.  */
10969         if (DECL_NAMESPACE_SCOPE_P (t))
10970           return t;
10971         /* If ARGS is NULL, then T is known to be non-dependent.  */
10972         if (args == NULL_TREE)
10973           return integral_constant_value (t);
10974
10975         /* Unfortunately, we cannot just call lookup_name here.
10976            Consider:
10977
10978              template <int I> int f() {
10979              enum E { a = I };
10980              struct S { void g() { E e = a; } };
10981              };
10982
10983            When we instantiate f<7>::S::g(), say, lookup_name is not
10984            clever enough to find f<7>::a.  */
10985         enum_type
10986           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10987                               /*entering_scope=*/0);
10988
10989         for (v = TYPE_VALUES (enum_type);
10990              v != NULL_TREE;
10991              v = TREE_CHAIN (v))
10992           if (TREE_PURPOSE (v) == DECL_NAME (t))
10993             return TREE_VALUE (v);
10994
10995           /* We didn't find the name.  That should never happen; if
10996              name-lookup found it during preliminary parsing, we
10997              should find it again here during instantiation.  */
10998         gcc_unreachable ();
10999       }
11000       return t;
11001
11002     case FIELD_DECL:
11003       if (DECL_CONTEXT (t))
11004         {
11005           tree ctx;
11006
11007           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
11008                                   /*entering_scope=*/1);
11009           if (ctx != DECL_CONTEXT (t))
11010             {
11011               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
11012               if (!r)
11013                 {
11014                   if (complain & tf_error)
11015                     error ("using invalid field %qD", t);
11016                   return error_mark_node;
11017                 }
11018               return r;
11019             }
11020         }
11021
11022       return t;
11023
11024     case VAR_DECL:
11025     case FUNCTION_DECL:
11026       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11027           || local_variable_p (t))
11028         t = tsubst (t, args, complain, in_decl);
11029       mark_used (t);
11030       return t;
11031
11032     case OVERLOAD:
11033       /* An OVERLOAD will always be a non-dependent overload set; an
11034          overload set from function scope will just be represented with an
11035          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
11036       gcc_assert (!uses_template_parms (t));
11037       return t;
11038
11039     case BASELINK:
11040       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11041
11042     case TEMPLATE_DECL:
11043       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11044         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11045                        args, complain, in_decl);
11046       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11047         return tsubst (t, args, complain, in_decl);
11048       else if (DECL_CLASS_SCOPE_P (t)
11049                && uses_template_parms (DECL_CONTEXT (t)))
11050         {
11051           /* Template template argument like the following example need
11052              special treatment:
11053
11054                template <template <class> class TT> struct C {};
11055                template <class T> struct D {
11056                  template <class U> struct E {};
11057                  C<E> c;                                // #1
11058                };
11059                D<int> d;                                // #2
11060
11061              We are processing the template argument `E' in #1 for
11062              the template instantiation #2.  Originally, `E' is a
11063              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11064              have to substitute this with one having context `D<int>'.  */
11065
11066           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11067           return lookup_field (context, DECL_NAME(t), 0, false);
11068         }
11069       else
11070         /* Ordinary template template argument.  */
11071         return t;
11072
11073     case CAST_EXPR:
11074     case REINTERPRET_CAST_EXPR:
11075     case CONST_CAST_EXPR:
11076     case STATIC_CAST_EXPR:
11077     case DYNAMIC_CAST_EXPR:
11078     case NOP_EXPR:
11079       return build1
11080         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11081          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11082
11083     case SIZEOF_EXPR:
11084       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11085         {
11086           /* We only want to compute the number of arguments.  */
11087           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11088                                                 complain, in_decl);
11089           int len = 0;
11090
11091           if (TREE_CODE (expanded) == TREE_VEC)
11092             len = TREE_VEC_LENGTH (expanded);
11093
11094           if (expanded == error_mark_node)
11095             return error_mark_node;
11096           else if (PACK_EXPANSION_P (expanded)
11097                    || (TREE_CODE (expanded) == TREE_VEC
11098                        && len > 0
11099                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11100             {
11101               if (TREE_CODE (expanded) == TREE_VEC)
11102                 expanded = TREE_VEC_ELT (expanded, len - 1);
11103
11104               if (TYPE_P (expanded))
11105                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11106                                                    complain & tf_error);
11107               else
11108                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11109                                                    complain & tf_error);
11110             }
11111           else
11112             return build_int_cst (size_type_node, len);
11113         }
11114       /* Fall through */
11115
11116     case INDIRECT_REF:
11117     case NEGATE_EXPR:
11118     case TRUTH_NOT_EXPR:
11119     case BIT_NOT_EXPR:
11120     case ADDR_EXPR:
11121     case UNARY_PLUS_EXPR:      /* Unary + */
11122     case ALIGNOF_EXPR:
11123     case AT_ENCODE_EXPR:
11124     case ARROW_EXPR:
11125     case THROW_EXPR:
11126     case TYPEID_EXPR:
11127     case REALPART_EXPR:
11128     case IMAGPART_EXPR:
11129       return build1
11130         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11131          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11132
11133     case COMPONENT_REF:
11134       {
11135         tree object;
11136         tree name;
11137
11138         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11139         name = TREE_OPERAND (t, 1);
11140         if (TREE_CODE (name) == BIT_NOT_EXPR)
11141           {
11142             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11143                                 complain, in_decl);
11144             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11145           }
11146         else if (TREE_CODE (name) == SCOPE_REF
11147                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11148           {
11149             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11150                                      complain, in_decl);
11151             name = TREE_OPERAND (name, 1);
11152             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11153                                 complain, in_decl);
11154             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11155             name = build_qualified_name (/*type=*/NULL_TREE,
11156                                          base, name,
11157                                          /*template_p=*/false);
11158           }
11159         else if (TREE_CODE (name) == BASELINK)
11160           name = tsubst_baselink (name,
11161                                   non_reference (TREE_TYPE (object)),
11162                                   args, complain,
11163                                   in_decl);
11164         else
11165           name = tsubst_copy (name, args, complain, in_decl);
11166         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11167       }
11168
11169     case PLUS_EXPR:
11170     case MINUS_EXPR:
11171     case MULT_EXPR:
11172     case TRUNC_DIV_EXPR:
11173     case CEIL_DIV_EXPR:
11174     case FLOOR_DIV_EXPR:
11175     case ROUND_DIV_EXPR:
11176     case EXACT_DIV_EXPR:
11177     case BIT_AND_EXPR:
11178     case BIT_IOR_EXPR:
11179     case BIT_XOR_EXPR:
11180     case TRUNC_MOD_EXPR:
11181     case FLOOR_MOD_EXPR:
11182     case TRUTH_ANDIF_EXPR:
11183     case TRUTH_ORIF_EXPR:
11184     case TRUTH_AND_EXPR:
11185     case TRUTH_OR_EXPR:
11186     case RSHIFT_EXPR:
11187     case LSHIFT_EXPR:
11188     case RROTATE_EXPR:
11189     case LROTATE_EXPR:
11190     case EQ_EXPR:
11191     case NE_EXPR:
11192     case MAX_EXPR:
11193     case MIN_EXPR:
11194     case LE_EXPR:
11195     case GE_EXPR:
11196     case LT_EXPR:
11197     case GT_EXPR:
11198     case COMPOUND_EXPR:
11199     case DOTSTAR_EXPR:
11200     case MEMBER_REF:
11201     case PREDECREMENT_EXPR:
11202     case PREINCREMENT_EXPR:
11203     case POSTDECREMENT_EXPR:
11204     case POSTINCREMENT_EXPR:
11205       return build_nt
11206         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11207          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11208
11209     case SCOPE_REF:
11210       return build_qualified_name (/*type=*/NULL_TREE,
11211                                    tsubst_copy (TREE_OPERAND (t, 0),
11212                                                 args, complain, in_decl),
11213                                    tsubst_copy (TREE_OPERAND (t, 1),
11214                                                 args, complain, in_decl),
11215                                    QUALIFIED_NAME_IS_TEMPLATE (t));
11216
11217     case ARRAY_REF:
11218       return build_nt
11219         (ARRAY_REF,
11220          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11221          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11222          NULL_TREE, NULL_TREE);
11223
11224     case CALL_EXPR:
11225       {
11226         int n = VL_EXP_OPERAND_LENGTH (t);
11227         tree result = build_vl_exp (CALL_EXPR, n);
11228         int i;
11229         for (i = 0; i < n; i++)
11230           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11231                                              complain, in_decl);
11232         return result;
11233       }
11234
11235     case COND_EXPR:
11236     case MODOP_EXPR:
11237     case PSEUDO_DTOR_EXPR:
11238       {
11239         r = build_nt
11240           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11241            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11242            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11243         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11244         return r;
11245       }
11246
11247     case NEW_EXPR:
11248       {
11249         r = build_nt
11250         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11251          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11252          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11253         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11254         return r;
11255       }
11256
11257     case DELETE_EXPR:
11258       {
11259         r = build_nt
11260         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11261          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11262         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11263         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11264         return r;
11265       }
11266
11267     case TEMPLATE_ID_EXPR:
11268       {
11269         /* Substituted template arguments */
11270         tree fn = TREE_OPERAND (t, 0);
11271         tree targs = TREE_OPERAND (t, 1);
11272
11273         fn = tsubst_copy (fn, args, complain, in_decl);
11274         if (targs)
11275           targs = tsubst_template_args (targs, args, complain, in_decl);
11276
11277         return lookup_template_function (fn, targs);
11278       }
11279
11280     case TREE_LIST:
11281       {
11282         tree purpose, value, chain;
11283
11284         if (t == void_list_node)
11285           return t;
11286
11287         purpose = TREE_PURPOSE (t);
11288         if (purpose)
11289           purpose = tsubst_copy (purpose, args, complain, in_decl);
11290         value = TREE_VALUE (t);
11291         if (value)
11292           value = tsubst_copy (value, args, complain, in_decl);
11293         chain = TREE_CHAIN (t);
11294         if (chain && chain != void_type_node)
11295           chain = tsubst_copy (chain, args, complain, in_decl);
11296         if (purpose == TREE_PURPOSE (t)
11297             && value == TREE_VALUE (t)
11298             && chain == TREE_CHAIN (t))
11299           return t;
11300         return tree_cons (purpose, value, chain);
11301       }
11302
11303     case RECORD_TYPE:
11304     case UNION_TYPE:
11305     case ENUMERAL_TYPE:
11306     case INTEGER_TYPE:
11307     case TEMPLATE_TYPE_PARM:
11308     case TEMPLATE_TEMPLATE_PARM:
11309     case BOUND_TEMPLATE_TEMPLATE_PARM:
11310     case TEMPLATE_PARM_INDEX:
11311     case POINTER_TYPE:
11312     case REFERENCE_TYPE:
11313     case OFFSET_TYPE:
11314     case FUNCTION_TYPE:
11315     case METHOD_TYPE:
11316     case ARRAY_TYPE:
11317     case TYPENAME_TYPE:
11318     case UNBOUND_CLASS_TEMPLATE:
11319     case TYPEOF_TYPE:
11320     case DECLTYPE_TYPE:
11321     case TYPE_DECL:
11322       return tsubst (t, args, complain, in_decl);
11323
11324     case IDENTIFIER_NODE:
11325       if (IDENTIFIER_TYPENAME_P (t))
11326         {
11327           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11328           return mangle_conv_op_name_for_type (new_type);
11329         }
11330       else
11331         return t;
11332
11333     case CONSTRUCTOR:
11334       /* This is handled by tsubst_copy_and_build.  */
11335       gcc_unreachable ();
11336
11337     case VA_ARG_EXPR:
11338       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11339                                           in_decl),
11340                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11341
11342     case CLEANUP_POINT_EXPR:
11343       /* We shouldn't have built any of these during initial template
11344          generation.  Instead, they should be built during instantiation
11345          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11346       gcc_unreachable ();
11347
11348     case OFFSET_REF:
11349       r = build2
11350         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11351          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11352          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11353       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
11354       mark_used (TREE_OPERAND (r, 1));
11355       return r;
11356
11357     case EXPR_PACK_EXPANSION:
11358       error ("invalid use of pack expansion expression");
11359       return error_mark_node;
11360
11361     case NONTYPE_ARGUMENT_PACK:
11362       error ("use %<...%> to expand argument pack");
11363       return error_mark_node;
11364
11365     case INTEGER_CST:
11366     case REAL_CST:
11367     case STRING_CST:
11368       {
11369         /* Instantiate any typedefs in the type.  */
11370         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11371         r = fold_convert (type, t);
11372         gcc_assert (TREE_CODE (r) == code);
11373         return r;
11374       }
11375
11376     case PTRMEM_CST:
11377       /* These can sometimes show up in a partial instantiation, but never
11378          involve template parms.  */
11379       gcc_assert (!uses_template_parms (t));
11380       return t;
11381
11382     default:
11383       gcc_unreachable ();
11384     }
11385 }
11386
11387 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11388
11389 static tree
11390 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11391                     tree in_decl)
11392 {
11393   tree new_clauses = NULL, nc, oc;
11394
11395   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11396     {
11397       nc = copy_node (oc);
11398       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11399       new_clauses = nc;
11400
11401       switch (OMP_CLAUSE_CODE (nc))
11402         {
11403         case OMP_CLAUSE_LASTPRIVATE:
11404           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11405             {
11406               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11407               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11408                            in_decl, /*integral_constant_expression_p=*/false);
11409               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11410                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11411             }
11412           /* FALLTHRU */
11413         case OMP_CLAUSE_PRIVATE:
11414         case OMP_CLAUSE_SHARED:
11415         case OMP_CLAUSE_FIRSTPRIVATE:
11416         case OMP_CLAUSE_REDUCTION:
11417         case OMP_CLAUSE_COPYIN:
11418         case OMP_CLAUSE_COPYPRIVATE:
11419         case OMP_CLAUSE_IF:
11420         case OMP_CLAUSE_NUM_THREADS:
11421         case OMP_CLAUSE_SCHEDULE:
11422         case OMP_CLAUSE_COLLAPSE:
11423           OMP_CLAUSE_OPERAND (nc, 0)
11424             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11425                            in_decl, /*integral_constant_expression_p=*/false);
11426           break;
11427         case OMP_CLAUSE_NOWAIT:
11428         case OMP_CLAUSE_ORDERED:
11429         case OMP_CLAUSE_DEFAULT:
11430         case OMP_CLAUSE_UNTIED:
11431           break;
11432         default:
11433           gcc_unreachable ();
11434         }
11435     }
11436
11437   return finish_omp_clauses (nreverse (new_clauses));
11438 }
11439
11440 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11441
11442 static tree
11443 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11444                           tree in_decl)
11445 {
11446 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11447
11448   tree purpose, value, chain;
11449
11450   if (t == NULL)
11451     return t;
11452
11453   if (TREE_CODE (t) != TREE_LIST)
11454     return tsubst_copy_and_build (t, args, complain, in_decl,
11455                                   /*function_p=*/false,
11456                                   /*integral_constant_expression_p=*/false);
11457
11458   if (t == void_list_node)
11459     return t;
11460
11461   purpose = TREE_PURPOSE (t);
11462   if (purpose)
11463     purpose = RECUR (purpose);
11464   value = TREE_VALUE (t);
11465   if (value && TREE_CODE (value) != LABEL_DECL)
11466     value = RECUR (value);
11467   chain = TREE_CHAIN (t);
11468   if (chain && chain != void_type_node)
11469     chain = RECUR (chain);
11470   return tree_cons (purpose, value, chain);
11471 #undef RECUR
11472 }
11473
11474 /* Substitute one OMP_FOR iterator.  */
11475
11476 static void
11477 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11478                          tree condv, tree incrv, tree *clauses,
11479                          tree args, tsubst_flags_t complain, tree in_decl,
11480                          bool integral_constant_expression_p)
11481 {
11482 #define RECUR(NODE)                             \
11483   tsubst_expr ((NODE), args, complain, in_decl, \
11484                integral_constant_expression_p)
11485   tree decl, init, cond, incr, auto_node;
11486
11487   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11488   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11489   decl = RECUR (TREE_OPERAND (init, 0));
11490   init = TREE_OPERAND (init, 1);
11491   auto_node = type_uses_auto (TREE_TYPE (decl));
11492   if (auto_node && init)
11493     {
11494       tree init_expr = init;
11495       if (TREE_CODE (init_expr) == DECL_EXPR)
11496         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11497       init_expr = RECUR (init_expr);
11498       TREE_TYPE (decl)
11499         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11500     }
11501   gcc_assert (!type_dependent_expression_p (decl));
11502
11503   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11504     {
11505       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11506       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11507       if (TREE_CODE (incr) == MODIFY_EXPR)
11508         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11509                                     RECUR (TREE_OPERAND (incr, 1)),
11510                                     complain);
11511       else
11512         incr = RECUR (incr);
11513       TREE_VEC_ELT (declv, i) = decl;
11514       TREE_VEC_ELT (initv, i) = init;
11515       TREE_VEC_ELT (condv, i) = cond;
11516       TREE_VEC_ELT (incrv, i) = incr;
11517       return;
11518     }
11519
11520   if (init && TREE_CODE (init) != DECL_EXPR)
11521     {
11522       tree c;
11523       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11524         {
11525           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11526                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11527               && OMP_CLAUSE_DECL (c) == decl)
11528             break;
11529           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11530                    && OMP_CLAUSE_DECL (c) == decl)
11531             error ("iteration variable %qD should not be firstprivate", decl);
11532           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11533                    && OMP_CLAUSE_DECL (c) == decl)
11534             error ("iteration variable %qD should not be reduction", decl);
11535         }
11536       if (c == NULL)
11537         {
11538           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11539           OMP_CLAUSE_DECL (c) = decl;
11540           c = finish_omp_clauses (c);
11541           if (c)
11542             {
11543               OMP_CLAUSE_CHAIN (c) = *clauses;
11544               *clauses = c;
11545             }
11546         }
11547     }
11548   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11549   if (COMPARISON_CLASS_P (cond))
11550     cond = build2 (TREE_CODE (cond), boolean_type_node,
11551                    RECUR (TREE_OPERAND (cond, 0)),
11552                    RECUR (TREE_OPERAND (cond, 1)));
11553   else
11554     cond = RECUR (cond);
11555   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11556   switch (TREE_CODE (incr))
11557     {
11558     case PREINCREMENT_EXPR:
11559     case PREDECREMENT_EXPR:
11560     case POSTINCREMENT_EXPR:
11561     case POSTDECREMENT_EXPR:
11562       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11563                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11564       break;
11565     case MODIFY_EXPR:
11566       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11567           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11568         {
11569           tree rhs = TREE_OPERAND (incr, 1);
11570           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11571                          RECUR (TREE_OPERAND (incr, 0)),
11572                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11573                                  RECUR (TREE_OPERAND (rhs, 0)),
11574                                  RECUR (TREE_OPERAND (rhs, 1))));
11575         }
11576       else
11577         incr = RECUR (incr);
11578       break;
11579     case MODOP_EXPR:
11580       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11581           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11582         {
11583           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11584           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11585                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11586                                  TREE_TYPE (decl), lhs,
11587                                  RECUR (TREE_OPERAND (incr, 2))));
11588         }
11589       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11590                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11591                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11592         {
11593           tree rhs = TREE_OPERAND (incr, 2);
11594           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11595                          RECUR (TREE_OPERAND (incr, 0)),
11596                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11597                                  RECUR (TREE_OPERAND (rhs, 0)),
11598                                  RECUR (TREE_OPERAND (rhs, 1))));
11599         }
11600       else
11601         incr = RECUR (incr);
11602       break;
11603     default:
11604       incr = RECUR (incr);
11605       break;
11606     }
11607
11608   TREE_VEC_ELT (declv, i) = decl;
11609   TREE_VEC_ELT (initv, i) = init;
11610   TREE_VEC_ELT (condv, i) = cond;
11611   TREE_VEC_ELT (incrv, i) = incr;
11612 #undef RECUR
11613 }
11614
11615 /* Like tsubst_copy for expressions, etc. but also does semantic
11616    processing.  */
11617
11618 static tree
11619 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11620              bool integral_constant_expression_p)
11621 {
11622 #define RECUR(NODE)                             \
11623   tsubst_expr ((NODE), args, complain, in_decl, \
11624                integral_constant_expression_p)
11625
11626   tree stmt, tmp;
11627
11628   if (t == NULL_TREE || t == error_mark_node)
11629     return t;
11630
11631   if (EXPR_HAS_LOCATION (t))
11632     input_location = EXPR_LOCATION (t);
11633   if (STATEMENT_CODE_P (TREE_CODE (t)))
11634     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11635
11636   switch (TREE_CODE (t))
11637     {
11638     case STATEMENT_LIST:
11639       {
11640         tree_stmt_iterator i;
11641         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11642           RECUR (tsi_stmt (i));
11643         break;
11644       }
11645
11646     case CTOR_INITIALIZER:
11647       finish_mem_initializers (tsubst_initializer_list
11648                                (TREE_OPERAND (t, 0), args));
11649       break;
11650
11651     case RETURN_EXPR:
11652       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11653       break;
11654
11655     case EXPR_STMT:
11656       tmp = RECUR (EXPR_STMT_EXPR (t));
11657       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11658         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11659       else
11660         finish_expr_stmt (tmp);
11661       break;
11662
11663     case USING_STMT:
11664       do_using_directive (USING_STMT_NAMESPACE (t));
11665       break;
11666
11667     case DECL_EXPR:
11668       {
11669         tree decl;
11670         tree init;
11671
11672         decl = DECL_EXPR_DECL (t);
11673         if (TREE_CODE (decl) == LABEL_DECL)
11674           finish_label_decl (DECL_NAME (decl));
11675         else if (TREE_CODE (decl) == USING_DECL)
11676           {
11677             tree scope = USING_DECL_SCOPE (decl);
11678             tree name = DECL_NAME (decl);
11679             tree decl;
11680
11681             scope = tsubst (scope, args, complain, in_decl);
11682             decl = lookup_qualified_name (scope, name,
11683                                           /*is_type_p=*/false,
11684                                           /*complain=*/false);
11685             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11686               qualified_name_lookup_error (scope, name, decl, input_location);
11687             else
11688               do_local_using_decl (decl, scope, name);
11689           }
11690         else
11691           {
11692             init = DECL_INITIAL (decl);
11693             decl = tsubst (decl, args, complain, in_decl);
11694             if (decl != error_mark_node)
11695               {
11696                 /* By marking the declaration as instantiated, we avoid
11697                    trying to instantiate it.  Since instantiate_decl can't
11698                    handle local variables, and since we've already done
11699                    all that needs to be done, that's the right thing to
11700                    do.  */
11701                 if (TREE_CODE (decl) == VAR_DECL)
11702                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11703                 if (TREE_CODE (decl) == VAR_DECL
11704                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11705                   /* Anonymous aggregates are a special case.  */
11706                   finish_anon_union (decl);
11707                 else
11708                   {
11709                     maybe_push_decl (decl);
11710                     if (TREE_CODE (decl) == VAR_DECL
11711                         && DECL_PRETTY_FUNCTION_P (decl))
11712                       {
11713                         /* For __PRETTY_FUNCTION__ we have to adjust the
11714                            initializer.  */
11715                         const char *const name
11716                           = cxx_printable_name (current_function_decl, 2);
11717                         init = cp_fname_init (name, &TREE_TYPE (decl));
11718                       }
11719                     else
11720                       {
11721                         tree t = RECUR (init);
11722
11723                         if (init && !t)
11724                           {
11725                             /* If we had an initializer but it
11726                                instantiated to nothing,
11727                                value-initialize the object.  This will
11728                                only occur when the initializer was a
11729                                pack expansion where the parameter packs
11730                                used in that expansion were of length
11731                                zero.  */
11732                             init = build_value_init (TREE_TYPE (decl),
11733                                                      complain);
11734                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
11735                               init = get_target_expr (init);
11736                           }
11737                         else
11738                           init = t;
11739                       }
11740
11741                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11742                   }
11743               }
11744           }
11745
11746         /* A DECL_EXPR can also be used as an expression, in the condition
11747            clause of an if/for/while construct.  */
11748         return decl;
11749       }
11750
11751     case FOR_STMT:
11752       stmt = begin_for_stmt ();
11753       RECUR (FOR_INIT_STMT (t));
11754       finish_for_init_stmt (stmt);
11755       tmp = RECUR (FOR_COND (t));
11756       finish_for_cond (tmp, stmt);
11757       tmp = RECUR (FOR_EXPR (t));
11758       finish_for_expr (tmp, stmt);
11759       RECUR (FOR_BODY (t));
11760       finish_for_stmt (stmt);
11761       break;
11762
11763     case RANGE_FOR_STMT:
11764       {
11765         tree decl, expr;
11766         stmt = begin_for_stmt ();
11767         decl = RANGE_FOR_DECL (t);
11768         decl = tsubst (decl, args, complain, in_decl);
11769         maybe_push_decl (decl);
11770         expr = RECUR (RANGE_FOR_EXPR (t));
11771         stmt = cp_convert_range_for (stmt, decl, expr);
11772         RECUR (RANGE_FOR_BODY (t));
11773         finish_for_stmt (stmt);
11774       }
11775       break;
11776
11777     case WHILE_STMT:
11778       stmt = begin_while_stmt ();
11779       tmp = RECUR (WHILE_COND (t));
11780       finish_while_stmt_cond (tmp, stmt);
11781       RECUR (WHILE_BODY (t));
11782       finish_while_stmt (stmt);
11783       break;
11784
11785     case DO_STMT:
11786       stmt = begin_do_stmt ();
11787       RECUR (DO_BODY (t));
11788       finish_do_body (stmt);
11789       tmp = RECUR (DO_COND (t));
11790       finish_do_stmt (tmp, stmt);
11791       break;
11792
11793     case IF_STMT:
11794       stmt = begin_if_stmt ();
11795       tmp = RECUR (IF_COND (t));
11796       finish_if_stmt_cond (tmp, stmt);
11797       RECUR (THEN_CLAUSE (t));
11798       finish_then_clause (stmt);
11799
11800       if (ELSE_CLAUSE (t))
11801         {
11802           begin_else_clause (stmt);
11803           RECUR (ELSE_CLAUSE (t));
11804           finish_else_clause (stmt);
11805         }
11806
11807       finish_if_stmt (stmt);
11808       break;
11809
11810     case BIND_EXPR:
11811       if (BIND_EXPR_BODY_BLOCK (t))
11812         stmt = begin_function_body ();
11813       else
11814         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11815                                     ? BCS_TRY_BLOCK : 0);
11816
11817       RECUR (BIND_EXPR_BODY (t));
11818
11819       if (BIND_EXPR_BODY_BLOCK (t))
11820         finish_function_body (stmt);
11821       else
11822         finish_compound_stmt (stmt);
11823       break;
11824
11825     case BREAK_STMT:
11826       finish_break_stmt ();
11827       break;
11828
11829     case CONTINUE_STMT:
11830       finish_continue_stmt ();
11831       break;
11832
11833     case SWITCH_STMT:
11834       stmt = begin_switch_stmt ();
11835       tmp = RECUR (SWITCH_STMT_COND (t));
11836       finish_switch_cond (tmp, stmt);
11837       RECUR (SWITCH_STMT_BODY (t));
11838       finish_switch_stmt (stmt);
11839       break;
11840
11841     case CASE_LABEL_EXPR:
11842       finish_case_label (EXPR_LOCATION (t),
11843                          RECUR (CASE_LOW (t)),
11844                          RECUR (CASE_HIGH (t)));
11845       break;
11846
11847     case LABEL_EXPR:
11848       {
11849         tree decl = LABEL_EXPR_LABEL (t);
11850         tree label;
11851
11852         label = finish_label_stmt (DECL_NAME (decl));
11853         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11854           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11855       }
11856       break;
11857
11858     case GOTO_EXPR:
11859       tmp = GOTO_DESTINATION (t);
11860       if (TREE_CODE (tmp) != LABEL_DECL)
11861         /* Computed goto's must be tsubst'd into.  On the other hand,
11862            non-computed gotos must not be; the identifier in question
11863            will have no binding.  */
11864         tmp = RECUR (tmp);
11865       else
11866         tmp = DECL_NAME (tmp);
11867       finish_goto_stmt (tmp);
11868       break;
11869
11870     case ASM_EXPR:
11871       tmp = finish_asm_stmt
11872         (ASM_VOLATILE_P (t),
11873          RECUR (ASM_STRING (t)),
11874          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11875          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11876          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11877          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11878       {
11879         tree asm_expr = tmp;
11880         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11881           asm_expr = TREE_OPERAND (asm_expr, 0);
11882         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11883       }
11884       break;
11885
11886     case TRY_BLOCK:
11887       if (CLEANUP_P (t))
11888         {
11889           stmt = begin_try_block ();
11890           RECUR (TRY_STMTS (t));
11891           finish_cleanup_try_block (stmt);
11892           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11893         }
11894       else
11895         {
11896           tree compound_stmt = NULL_TREE;
11897
11898           if (FN_TRY_BLOCK_P (t))
11899             stmt = begin_function_try_block (&compound_stmt);
11900           else
11901             stmt = begin_try_block ();
11902
11903           RECUR (TRY_STMTS (t));
11904
11905           if (FN_TRY_BLOCK_P (t))
11906             finish_function_try_block (stmt);
11907           else
11908             finish_try_block (stmt);
11909
11910           RECUR (TRY_HANDLERS (t));
11911           if (FN_TRY_BLOCK_P (t))
11912             finish_function_handler_sequence (stmt, compound_stmt);
11913           else
11914             finish_handler_sequence (stmt);
11915         }
11916       break;
11917
11918     case HANDLER:
11919       {
11920         tree decl = HANDLER_PARMS (t);
11921
11922         if (decl)
11923           {
11924             decl = tsubst (decl, args, complain, in_decl);
11925             /* Prevent instantiate_decl from trying to instantiate
11926                this variable.  We've already done all that needs to be
11927                done.  */
11928             if (decl != error_mark_node)
11929               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11930           }
11931         stmt = begin_handler ();
11932         finish_handler_parms (decl, stmt);
11933         RECUR (HANDLER_BODY (t));
11934         finish_handler (stmt);
11935       }
11936       break;
11937
11938     case TAG_DEFN:
11939       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11940       break;
11941
11942     case STATIC_ASSERT:
11943       {
11944         tree condition = 
11945           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11946                        args,
11947                        complain, in_decl,
11948                        /*integral_constant_expression_p=*/true);
11949         finish_static_assert (condition,
11950                               STATIC_ASSERT_MESSAGE (t),
11951                               STATIC_ASSERT_SOURCE_LOCATION (t),
11952                               /*member_p=*/false);
11953       }
11954       break;
11955
11956     case OMP_PARALLEL:
11957       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11958                                 args, complain, in_decl);
11959       stmt = begin_omp_parallel ();
11960       RECUR (OMP_PARALLEL_BODY (t));
11961       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11962         = OMP_PARALLEL_COMBINED (t);
11963       break;
11964
11965     case OMP_TASK:
11966       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11967                                 args, complain, in_decl);
11968       stmt = begin_omp_task ();
11969       RECUR (OMP_TASK_BODY (t));
11970       finish_omp_task (tmp, stmt);
11971       break;
11972
11973     case OMP_FOR:
11974       {
11975         tree clauses, body, pre_body;
11976         tree declv, initv, condv, incrv;
11977         int i;
11978
11979         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11980                                       args, complain, in_decl);
11981         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11982         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11983         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11984         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11985
11986         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11987           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11988                                    &clauses, args, complain, in_decl,
11989                                    integral_constant_expression_p);
11990
11991         stmt = begin_omp_structured_block ();
11992
11993         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11994           if (TREE_VEC_ELT (initv, i) == NULL
11995               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11996             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11997           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11998             {
11999               tree init = RECUR (TREE_VEC_ELT (initv, i));
12000               gcc_assert (init == TREE_VEC_ELT (declv, i));
12001               TREE_VEC_ELT (initv, i) = NULL_TREE;
12002             }
12003           else
12004             {
12005               tree decl_expr = TREE_VEC_ELT (initv, i);
12006               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
12007               gcc_assert (init != NULL);
12008               TREE_VEC_ELT (initv, i) = RECUR (init);
12009               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
12010               RECUR (decl_expr);
12011               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
12012             }
12013
12014         pre_body = push_stmt_list ();
12015         RECUR (OMP_FOR_PRE_BODY (t));
12016         pre_body = pop_stmt_list (pre_body);
12017
12018         body = push_stmt_list ();
12019         RECUR (OMP_FOR_BODY (t));
12020         body = pop_stmt_list (body);
12021
12022         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
12023                             body, pre_body, clauses);
12024
12025         add_stmt (finish_omp_structured_block (stmt));
12026       }
12027       break;
12028
12029     case OMP_SECTIONS:
12030     case OMP_SINGLE:
12031       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
12032       stmt = push_stmt_list ();
12033       RECUR (OMP_BODY (t));
12034       stmt = pop_stmt_list (stmt);
12035
12036       t = copy_node (t);
12037       OMP_BODY (t) = stmt;
12038       OMP_CLAUSES (t) = tmp;
12039       add_stmt (t);
12040       break;
12041
12042     case OMP_SECTION:
12043     case OMP_CRITICAL:
12044     case OMP_MASTER:
12045     case OMP_ORDERED:
12046       stmt = push_stmt_list ();
12047       RECUR (OMP_BODY (t));
12048       stmt = pop_stmt_list (stmt);
12049
12050       t = copy_node (t);
12051       OMP_BODY (t) = stmt;
12052       add_stmt (t);
12053       break;
12054
12055     case OMP_ATOMIC:
12056       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
12057       {
12058         tree op1 = TREE_OPERAND (t, 1);
12059         tree lhs = RECUR (TREE_OPERAND (op1, 0));
12060         tree rhs = RECUR (TREE_OPERAND (op1, 1));
12061         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
12062       }
12063       break;
12064
12065     case EXPR_PACK_EXPANSION:
12066       error ("invalid use of pack expansion expression");
12067       return error_mark_node;
12068
12069     case NONTYPE_ARGUMENT_PACK:
12070       error ("use %<...%> to expand argument pack");
12071       return error_mark_node;
12072
12073     default:
12074       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
12075
12076       return tsubst_copy_and_build (t, args, complain, in_decl,
12077                                     /*function_p=*/false,
12078                                     integral_constant_expression_p);
12079     }
12080
12081   return NULL_TREE;
12082 #undef RECUR
12083 }
12084
12085 /* T is a postfix-expression that is not being used in a function
12086    call.  Return the substituted version of T.  */
12087
12088 static tree
12089 tsubst_non_call_postfix_expression (tree t, tree args,
12090                                     tsubst_flags_t complain,
12091                                     tree in_decl)
12092 {
12093   if (TREE_CODE (t) == SCOPE_REF)
12094     t = tsubst_qualified_id (t, args, complain, in_decl,
12095                              /*done=*/false, /*address_p=*/false);
12096   else
12097     t = tsubst_copy_and_build (t, args, complain, in_decl,
12098                                /*function_p=*/false,
12099                                /*integral_constant_expression_p=*/false);
12100
12101   return t;
12102 }
12103
12104 /* Like tsubst but deals with expressions and performs semantic
12105    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12106
12107 tree
12108 tsubst_copy_and_build (tree t,
12109                        tree args,
12110                        tsubst_flags_t complain,
12111                        tree in_decl,
12112                        bool function_p,
12113                        bool integral_constant_expression_p)
12114 {
12115 #define RECUR(NODE)                                             \
12116   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
12117                          /*function_p=*/false,                  \
12118                          integral_constant_expression_p)
12119
12120   tree op1;
12121
12122   if (t == NULL_TREE || t == error_mark_node)
12123     return t;
12124
12125   switch (TREE_CODE (t))
12126     {
12127     case USING_DECL:
12128       t = DECL_NAME (t);
12129       /* Fall through.  */
12130     case IDENTIFIER_NODE:
12131       {
12132         tree decl;
12133         cp_id_kind idk;
12134         bool non_integral_constant_expression_p;
12135         const char *error_msg;
12136
12137         if (IDENTIFIER_TYPENAME_P (t))
12138           {
12139             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12140             t = mangle_conv_op_name_for_type (new_type);
12141           }
12142
12143         /* Look up the name.  */
12144         decl = lookup_name (t);
12145
12146         /* By convention, expressions use ERROR_MARK_NODE to indicate
12147            failure, not NULL_TREE.  */
12148         if (decl == NULL_TREE)
12149           decl = error_mark_node;
12150
12151         decl = finish_id_expression (t, decl, NULL_TREE,
12152                                      &idk,
12153                                      integral_constant_expression_p,
12154                                      /*allow_non_integral_constant_expression_p=*/false,
12155                                      &non_integral_constant_expression_p,
12156                                      /*template_p=*/false,
12157                                      /*done=*/true,
12158                                      /*address_p=*/false,
12159                                      /*template_arg_p=*/false,
12160                                      &error_msg,
12161                                      input_location);
12162         if (error_msg)
12163           error (error_msg);
12164         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
12165           decl = unqualified_name_lookup_error (decl);
12166         return decl;
12167       }
12168
12169     case TEMPLATE_ID_EXPR:
12170       {
12171         tree object;
12172         tree templ = RECUR (TREE_OPERAND (t, 0));
12173         tree targs = TREE_OPERAND (t, 1);
12174
12175         if (targs)
12176           targs = tsubst_template_args (targs, args, complain, in_decl);
12177
12178         if (TREE_CODE (templ) == COMPONENT_REF)
12179           {
12180             object = TREE_OPERAND (templ, 0);
12181             templ = TREE_OPERAND (templ, 1);
12182           }
12183         else
12184           object = NULL_TREE;
12185         templ = lookup_template_function (templ, targs);
12186
12187         if (object)
12188           return build3 (COMPONENT_REF, TREE_TYPE (templ),
12189                          object, templ, NULL_TREE);
12190         else
12191           return baselink_for_fns (templ);
12192       }
12193
12194     case INDIRECT_REF:
12195       {
12196         tree r = RECUR (TREE_OPERAND (t, 0));
12197
12198         if (REFERENCE_REF_P (t))
12199           {
12200             /* A type conversion to reference type will be enclosed in
12201                such an indirect ref, but the substitution of the cast
12202                will have also added such an indirect ref.  */
12203             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
12204               r = convert_from_reference (r);
12205           }
12206         else
12207           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
12208         return r;
12209       }
12210
12211     case NOP_EXPR:
12212       return build_nop
12213         (tsubst (TREE_TYPE (t), args, complain, in_decl),
12214          RECUR (TREE_OPERAND (t, 0)));
12215
12216     case CAST_EXPR:
12217     case REINTERPRET_CAST_EXPR:
12218     case CONST_CAST_EXPR:
12219     case DYNAMIC_CAST_EXPR:
12220     case STATIC_CAST_EXPR:
12221       {
12222         tree type;
12223         tree op;
12224
12225         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12226         if (integral_constant_expression_p
12227             && !cast_valid_in_integral_constant_expression_p (type))
12228           {
12229             if (complain & tf_error)
12230               error ("a cast to a type other than an integral or "
12231                      "enumeration type cannot appear in a constant-expression");
12232             return error_mark_node; 
12233           }
12234
12235         op = RECUR (TREE_OPERAND (t, 0));
12236
12237         switch (TREE_CODE (t))
12238           {
12239           case CAST_EXPR:
12240             return build_functional_cast (type, op, complain);
12241           case REINTERPRET_CAST_EXPR:
12242             return build_reinterpret_cast (type, op, complain);
12243           case CONST_CAST_EXPR:
12244             return build_const_cast (type, op, complain);
12245           case DYNAMIC_CAST_EXPR:
12246             return build_dynamic_cast (type, op, complain);
12247           case STATIC_CAST_EXPR:
12248             return build_static_cast (type, op, complain);
12249           default:
12250             gcc_unreachable ();
12251           }
12252       }
12253
12254     case POSTDECREMENT_EXPR:
12255     case POSTINCREMENT_EXPR:
12256       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12257                                                 args, complain, in_decl);
12258       return build_x_unary_op (TREE_CODE (t), op1, complain);
12259
12260     case PREDECREMENT_EXPR:
12261     case PREINCREMENT_EXPR:
12262     case NEGATE_EXPR:
12263     case BIT_NOT_EXPR:
12264     case ABS_EXPR:
12265     case TRUTH_NOT_EXPR:
12266     case UNARY_PLUS_EXPR:  /* Unary + */
12267     case REALPART_EXPR:
12268     case IMAGPART_EXPR:
12269       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12270                                complain);
12271
12272     case ADDR_EXPR:
12273       op1 = TREE_OPERAND (t, 0);
12274       if (TREE_CODE (op1) == LABEL_DECL)
12275         return finish_label_address_expr (DECL_NAME (op1),
12276                                           EXPR_LOCATION (op1));
12277       if (TREE_CODE (op1) == SCOPE_REF)
12278         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12279                                    /*done=*/true, /*address_p=*/true);
12280       else
12281         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12282                                                   in_decl);
12283       return build_x_unary_op (ADDR_EXPR, op1, complain);
12284
12285     case PLUS_EXPR:
12286     case MINUS_EXPR:
12287     case MULT_EXPR:
12288     case TRUNC_DIV_EXPR:
12289     case CEIL_DIV_EXPR:
12290     case FLOOR_DIV_EXPR:
12291     case ROUND_DIV_EXPR:
12292     case EXACT_DIV_EXPR:
12293     case BIT_AND_EXPR:
12294     case BIT_IOR_EXPR:
12295     case BIT_XOR_EXPR:
12296     case TRUNC_MOD_EXPR:
12297     case FLOOR_MOD_EXPR:
12298     case TRUTH_ANDIF_EXPR:
12299     case TRUTH_ORIF_EXPR:
12300     case TRUTH_AND_EXPR:
12301     case TRUTH_OR_EXPR:
12302     case RSHIFT_EXPR:
12303     case LSHIFT_EXPR:
12304     case RROTATE_EXPR:
12305     case LROTATE_EXPR:
12306     case EQ_EXPR:
12307     case NE_EXPR:
12308     case MAX_EXPR:
12309     case MIN_EXPR:
12310     case LE_EXPR:
12311     case GE_EXPR:
12312     case LT_EXPR:
12313     case GT_EXPR:
12314     case MEMBER_REF:
12315     case DOTSTAR_EXPR:
12316       return build_x_binary_op
12317         (TREE_CODE (t),
12318          RECUR (TREE_OPERAND (t, 0)),
12319          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12320           ? ERROR_MARK
12321           : TREE_CODE (TREE_OPERAND (t, 0))),
12322          RECUR (TREE_OPERAND (t, 1)),
12323          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12324           ? ERROR_MARK
12325           : TREE_CODE (TREE_OPERAND (t, 1))),
12326          /*overloaded_p=*/NULL,
12327          complain);
12328
12329     case SCOPE_REF:
12330       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12331                                   /*address_p=*/false);
12332     case ARRAY_REF:
12333       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12334                                                 args, complain, in_decl);
12335       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12336
12337     case SIZEOF_EXPR:
12338       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12339         return tsubst_copy (t, args, complain, in_decl);
12340       /* Fall through */
12341       
12342     case ALIGNOF_EXPR:
12343       op1 = TREE_OPERAND (t, 0);
12344       if (!args)
12345         {
12346           /* When there are no ARGS, we are trying to evaluate a
12347              non-dependent expression from the parser.  Trying to do
12348              the substitutions may not work.  */
12349           if (!TYPE_P (op1))
12350             op1 = TREE_TYPE (op1);
12351         }
12352       else
12353         {
12354           ++cp_unevaluated_operand;
12355           ++c_inhibit_evaluation_warnings;
12356           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12357                                        /*function_p=*/false,
12358                                        /*integral_constant_expression_p=*/false);
12359           --cp_unevaluated_operand;
12360           --c_inhibit_evaluation_warnings;
12361         }
12362       if (TYPE_P (op1))
12363         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
12364                                            complain & tf_error);
12365       else
12366         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
12367                                            complain & tf_error);
12368
12369     case AT_ENCODE_EXPR:
12370       {
12371         op1 = TREE_OPERAND (t, 0);
12372         ++cp_unevaluated_operand;
12373         ++c_inhibit_evaluation_warnings;
12374         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12375                                      /*function_p=*/false,
12376                                      /*integral_constant_expression_p=*/false);
12377         --cp_unevaluated_operand;
12378         --c_inhibit_evaluation_warnings;
12379         return objc_build_encode_expr (op1);
12380       }
12381
12382     case NOEXCEPT_EXPR:
12383       op1 = TREE_OPERAND (t, 0);
12384       ++cp_unevaluated_operand;
12385       ++c_inhibit_evaluation_warnings;
12386       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12387                                    /*function_p=*/false,
12388                                    /*integral_constant_expression_p=*/false);
12389       --cp_unevaluated_operand;
12390       --c_inhibit_evaluation_warnings;
12391       return finish_noexcept_expr (op1, complain);
12392
12393     case MODOP_EXPR:
12394       {
12395         tree r = build_x_modify_expr
12396           (RECUR (TREE_OPERAND (t, 0)),
12397            TREE_CODE (TREE_OPERAND (t, 1)),
12398            RECUR (TREE_OPERAND (t, 2)),
12399            complain);
12400         /* TREE_NO_WARNING must be set if either the expression was
12401            parenthesized or it uses an operator such as >>= rather
12402            than plain assignment.  In the former case, it was already
12403            set and must be copied.  In the latter case,
12404            build_x_modify_expr sets it and it must not be reset
12405            here.  */
12406         if (TREE_NO_WARNING (t))
12407           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12408         return r;
12409       }
12410
12411     case ARROW_EXPR:
12412       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12413                                                 args, complain, in_decl);
12414       /* Remember that there was a reference to this entity.  */
12415       if (DECL_P (op1))
12416         mark_used (op1);
12417       return build_x_arrow (op1);
12418
12419     case NEW_EXPR:
12420       {
12421         tree placement = RECUR (TREE_OPERAND (t, 0));
12422         tree init = RECUR (TREE_OPERAND (t, 3));
12423         VEC(tree,gc) *placement_vec;
12424         VEC(tree,gc) *init_vec;
12425         tree ret;
12426
12427         if (placement == NULL_TREE)
12428           placement_vec = NULL;
12429         else
12430           {
12431             placement_vec = make_tree_vector ();
12432             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12433               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12434           }
12435
12436         /* If there was an initializer in the original tree, but it
12437            instantiated to an empty list, then we should pass a
12438            non-NULL empty vector to tell build_new that it was an
12439            empty initializer() rather than no initializer.  This can
12440            only happen when the initializer is a pack expansion whose
12441            parameter packs are of length zero.  */
12442         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12443           init_vec = NULL;
12444         else
12445           {
12446             init_vec = make_tree_vector ();
12447             if (init == void_zero_node)
12448               gcc_assert (init_vec != NULL);
12449             else
12450               {
12451                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12452                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12453               }
12454           }
12455
12456         ret = build_new (&placement_vec,
12457                          tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
12458                          RECUR (TREE_OPERAND (t, 2)),
12459                          &init_vec,
12460                          NEW_EXPR_USE_GLOBAL (t),
12461                          complain);
12462
12463         if (placement_vec != NULL)
12464           release_tree_vector (placement_vec);
12465         if (init_vec != NULL)
12466           release_tree_vector (init_vec);
12467
12468         return ret;
12469       }
12470
12471     case DELETE_EXPR:
12472      return delete_sanity
12473        (RECUR (TREE_OPERAND (t, 0)),
12474         RECUR (TREE_OPERAND (t, 1)),
12475         DELETE_EXPR_USE_VEC (t),
12476         DELETE_EXPR_USE_GLOBAL (t));
12477
12478     case COMPOUND_EXPR:
12479       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12480                                     RECUR (TREE_OPERAND (t, 1)),
12481                                     complain);
12482
12483     case CALL_EXPR:
12484       {
12485         tree function;
12486         VEC(tree,gc) *call_args;
12487         unsigned int nargs, i;
12488         bool qualified_p;
12489         bool koenig_p;
12490         tree ret;
12491
12492         function = CALL_EXPR_FN (t);
12493         /* When we parsed the expression,  we determined whether or
12494            not Koenig lookup should be performed.  */
12495         koenig_p = KOENIG_LOOKUP_P (t);
12496         if (TREE_CODE (function) == SCOPE_REF)
12497           {
12498             qualified_p = true;
12499             function = tsubst_qualified_id (function, args, complain, in_decl,
12500                                             /*done=*/false,
12501                                             /*address_p=*/false);
12502           }
12503         else
12504           {
12505             if (TREE_CODE (function) == COMPONENT_REF)
12506               {
12507                 tree op = TREE_OPERAND (function, 1);
12508
12509                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12510                                || (BASELINK_P (op)
12511                                    && BASELINK_QUALIFIED_P (op)));
12512               }
12513             else
12514               qualified_p = false;
12515
12516             function = tsubst_copy_and_build (function, args, complain,
12517                                               in_decl,
12518                                               !qualified_p,
12519                                               integral_constant_expression_p);
12520
12521             if (BASELINK_P (function))
12522               qualified_p = true;
12523           }
12524
12525         nargs = call_expr_nargs (t);
12526         call_args = make_tree_vector ();
12527         for (i = 0; i < nargs; ++i)
12528           {
12529             tree arg = CALL_EXPR_ARG (t, i);
12530
12531             if (!PACK_EXPANSION_P (arg))
12532               VEC_safe_push (tree, gc, call_args,
12533                              RECUR (CALL_EXPR_ARG (t, i)));
12534             else
12535               {
12536                 /* Expand the pack expansion and push each entry onto
12537                    CALL_ARGS.  */
12538                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12539                 if (TREE_CODE (arg) == TREE_VEC)
12540                   {
12541                     unsigned int len, j;
12542
12543                     len = TREE_VEC_LENGTH (arg);
12544                     for (j = 0; j < len; ++j)
12545                       {
12546                         tree value = TREE_VEC_ELT (arg, j);
12547                         if (value != NULL_TREE)
12548                           value = convert_from_reference (value);
12549                         VEC_safe_push (tree, gc, call_args, value);
12550                       }
12551                   }
12552                 else
12553                   {
12554                     /* A partial substitution.  Add one entry.  */
12555                     VEC_safe_push (tree, gc, call_args, arg);
12556                   }
12557               }
12558           }
12559
12560         /* We do not perform argument-dependent lookup if normal
12561            lookup finds a non-function, in accordance with the
12562            expected resolution of DR 218.  */
12563         if (koenig_p
12564             && ((is_overloaded_fn (function)
12565                  /* If lookup found a member function, the Koenig lookup is
12566                     not appropriate, even if an unqualified-name was used
12567                     to denote the function.  */
12568                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12569                 || TREE_CODE (function) == IDENTIFIER_NODE)
12570             /* Only do this when substitution turns a dependent call
12571                into a non-dependent call.  */
12572             && type_dependent_expression_p_push (t)
12573             && !any_type_dependent_arguments_p (call_args))
12574           function = perform_koenig_lookup (function, call_args, false);
12575
12576         if (TREE_CODE (function) == IDENTIFIER_NODE)
12577           {
12578             unqualified_name_lookup_error (function);
12579             release_tree_vector (call_args);
12580             return error_mark_node;
12581           }
12582
12583         /* Remember that there was a reference to this entity.  */
12584         if (DECL_P (function))
12585           mark_used (function);
12586
12587         if (TREE_CODE (function) == OFFSET_REF)
12588           ret = build_offset_ref_call_from_tree (function, &call_args);
12589         else if (TREE_CODE (function) == COMPONENT_REF)
12590           {
12591             tree instance = TREE_OPERAND (function, 0);
12592             tree fn = TREE_OPERAND (function, 1);
12593
12594             if (processing_template_decl
12595                 && (type_dependent_expression_p (instance)
12596                     || (!BASELINK_P (fn)
12597                         && TREE_CODE (fn) != FIELD_DECL)
12598                     || type_dependent_expression_p (fn)
12599                     || any_type_dependent_arguments_p (call_args)))
12600               ret = build_nt_call_vec (function, call_args);
12601             else if (!BASELINK_P (fn))
12602               ret = finish_call_expr (function, &call_args,
12603                                        /*disallow_virtual=*/false,
12604                                        /*koenig_p=*/false,
12605                                        complain);
12606             else
12607               ret = (build_new_method_call
12608                       (instance, fn,
12609                        &call_args, NULL_TREE,
12610                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12611                        /*fn_p=*/NULL,
12612                        complain));
12613           }
12614         else
12615           ret = finish_call_expr (function, &call_args,
12616                                   /*disallow_virtual=*/qualified_p,
12617                                   koenig_p,
12618                                   complain);
12619
12620         release_tree_vector (call_args);
12621
12622         return ret;
12623       }
12624
12625     case COND_EXPR:
12626       return build_x_conditional_expr
12627         (RECUR (TREE_OPERAND (t, 0)),
12628          RECUR (TREE_OPERAND (t, 1)),
12629          RECUR (TREE_OPERAND (t, 2)),
12630          complain);
12631
12632     case PSEUDO_DTOR_EXPR:
12633       return finish_pseudo_destructor_expr
12634         (RECUR (TREE_OPERAND (t, 0)),
12635          RECUR (TREE_OPERAND (t, 1)),
12636          RECUR (TREE_OPERAND (t, 2)));
12637
12638     case TREE_LIST:
12639       {
12640         tree purpose, value, chain;
12641
12642         if (t == void_list_node)
12643           return t;
12644
12645         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12646             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12647           {
12648             /* We have pack expansions, so expand those and
12649                create a new list out of it.  */
12650             tree purposevec = NULL_TREE;
12651             tree valuevec = NULL_TREE;
12652             tree chain;
12653             int i, len = -1;
12654
12655             /* Expand the argument expressions.  */
12656             if (TREE_PURPOSE (t))
12657               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12658                                                  complain, in_decl);
12659             if (TREE_VALUE (t))
12660               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12661                                                complain, in_decl);
12662
12663             /* Build the rest of the list.  */
12664             chain = TREE_CHAIN (t);
12665             if (chain && chain != void_type_node)
12666               chain = RECUR (chain);
12667
12668             /* Determine the number of arguments.  */
12669             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12670               {
12671                 len = TREE_VEC_LENGTH (purposevec);
12672                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12673               }
12674             else if (TREE_CODE (valuevec) == TREE_VEC)
12675               len = TREE_VEC_LENGTH (valuevec);
12676             else
12677               {
12678                 /* Since we only performed a partial substitution into
12679                    the argument pack, we only return a single list
12680                    node.  */
12681                 if (purposevec == TREE_PURPOSE (t)
12682                     && valuevec == TREE_VALUE (t)
12683                     && chain == TREE_CHAIN (t))
12684                   return t;
12685
12686                 return tree_cons (purposevec, valuevec, chain);
12687               }
12688             
12689             /* Convert the argument vectors into a TREE_LIST */
12690             i = len;
12691             while (i > 0)
12692               {
12693                 /* Grab the Ith values.  */
12694                 i--;
12695                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12696                                      : NULL_TREE;
12697                 value 
12698                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12699                              : NULL_TREE;
12700
12701                 /* Build the list (backwards).  */
12702                 chain = tree_cons (purpose, value, chain);
12703               }
12704
12705             return chain;
12706           }
12707
12708         purpose = TREE_PURPOSE (t);
12709         if (purpose)
12710           purpose = RECUR (purpose);
12711         value = TREE_VALUE (t);
12712         if (value)
12713           value = RECUR (value);
12714         chain = TREE_CHAIN (t);
12715         if (chain && chain != void_type_node)
12716           chain = RECUR (chain);
12717         if (purpose == TREE_PURPOSE (t)
12718             && value == TREE_VALUE (t)
12719             && chain == TREE_CHAIN (t))
12720           return t;
12721         return tree_cons (purpose, value, chain);
12722       }
12723
12724     case COMPONENT_REF:
12725       {
12726         tree object;
12727         tree object_type;
12728         tree member;
12729
12730         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12731                                                      args, complain, in_decl);
12732         /* Remember that there was a reference to this entity.  */
12733         if (DECL_P (object))
12734           mark_used (object);
12735         object_type = TREE_TYPE (object);
12736
12737         member = TREE_OPERAND (t, 1);
12738         if (BASELINK_P (member))
12739           member = tsubst_baselink (member,
12740                                     non_reference (TREE_TYPE (object)),
12741                                     args, complain, in_decl);
12742         else
12743           member = tsubst_copy (member, args, complain, in_decl);
12744         if (member == error_mark_node)
12745           return error_mark_node;
12746
12747         if (object_type && !CLASS_TYPE_P (object_type))
12748           {
12749             if (SCALAR_TYPE_P (object_type))
12750               {
12751                 tree s = NULL_TREE;
12752                 tree dtor = member;
12753
12754                 if (TREE_CODE (dtor) == SCOPE_REF)
12755                   {
12756                     s = TREE_OPERAND (dtor, 0);
12757                     dtor = TREE_OPERAND (dtor, 1);
12758                   }
12759                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12760                   {
12761                     dtor = TREE_OPERAND (dtor, 0);
12762                     if (TYPE_P (dtor))
12763                       return finish_pseudo_destructor_expr (object, s, dtor);
12764                   }
12765               }
12766           }
12767         else if (TREE_CODE (member) == SCOPE_REF
12768                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12769           {
12770             tree tmpl;
12771             tree args;
12772
12773             /* Lookup the template functions now that we know what the
12774                scope is.  */
12775             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12776             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12777             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12778                                             /*is_type_p=*/false,
12779                                             /*complain=*/false);
12780             if (BASELINK_P (member))
12781               {
12782                 BASELINK_FUNCTIONS (member)
12783                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12784                               args);
12785                 member = (adjust_result_of_qualified_name_lookup
12786                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12787                            object_type));
12788               }
12789             else
12790               {
12791                 qualified_name_lookup_error (object_type, tmpl, member,
12792                                              input_location);
12793                 return error_mark_node;
12794               }
12795           }
12796         else if (TREE_CODE (member) == SCOPE_REF
12797                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12798                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12799           {
12800             if (complain & tf_error)
12801               {
12802                 if (TYPE_P (TREE_OPERAND (member, 0)))
12803                   error ("%qT is not a class or namespace",
12804                          TREE_OPERAND (member, 0));
12805                 else
12806                   error ("%qD is not a class or namespace",
12807                          TREE_OPERAND (member, 0));
12808               }
12809             return error_mark_node;
12810           }
12811         else if (TREE_CODE (member) == FIELD_DECL)
12812           return finish_non_static_data_member (member, object, NULL_TREE);
12813
12814         return finish_class_member_access_expr (object, member,
12815                                                 /*template_p=*/false,
12816                                                 complain);
12817       }
12818
12819     case THROW_EXPR:
12820       return build_throw
12821         (RECUR (TREE_OPERAND (t, 0)));
12822
12823     case CONSTRUCTOR:
12824       {
12825         VEC(constructor_elt,gc) *n;
12826         constructor_elt *ce;
12827         unsigned HOST_WIDE_INT idx;
12828         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12829         bool process_index_p;
12830         int newlen;
12831         bool need_copy_p = false;
12832         tree r;
12833
12834         if (type == error_mark_node)
12835           return error_mark_node;
12836
12837         /* digest_init will do the wrong thing if we let it.  */
12838         if (type && TYPE_PTRMEMFUNC_P (type))
12839           return t;
12840
12841         /* We do not want to process the index of aggregate
12842            initializers as they are identifier nodes which will be
12843            looked up by digest_init.  */
12844         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12845
12846         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12847         newlen = VEC_length (constructor_elt, n);
12848         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
12849           {
12850             if (ce->index && process_index_p)
12851               ce->index = RECUR (ce->index);
12852
12853             if (PACK_EXPANSION_P (ce->value))
12854               {
12855                 /* Substitute into the pack expansion.  */
12856                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12857                                                   in_decl);
12858
12859                 if (ce->value == error_mark_node)
12860                   ;
12861                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12862                   /* Just move the argument into place.  */
12863                   ce->value = TREE_VEC_ELT (ce->value, 0);
12864                 else
12865                   {
12866                     /* Update the length of the final CONSTRUCTOR
12867                        arguments vector, and note that we will need to
12868                        copy.*/
12869                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12870                     need_copy_p = true;
12871                   }
12872               }
12873             else
12874               ce->value = RECUR (ce->value);
12875           }
12876
12877         if (need_copy_p)
12878           {
12879             VEC(constructor_elt,gc) *old_n = n;
12880
12881             n = VEC_alloc (constructor_elt, gc, newlen);
12882             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
12883               {
12884                 if (TREE_CODE (ce->value) == TREE_VEC)
12885                   {
12886                     int i, len = TREE_VEC_LENGTH (ce->value);
12887                     for (i = 0; i < len; ++i)
12888                       CONSTRUCTOR_APPEND_ELT (n, 0,
12889                                               TREE_VEC_ELT (ce->value, i));
12890                   }
12891                 else
12892                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12893               }
12894           }
12895
12896         r = build_constructor (init_list_type_node, n);
12897         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12898
12899         if (TREE_HAS_CONSTRUCTOR (t))
12900           return finish_compound_literal (type, r);
12901
12902         return r;
12903       }
12904
12905     case TYPEID_EXPR:
12906       {
12907         tree operand_0 = TREE_OPERAND (t, 0);
12908         if (TYPE_P (operand_0))
12909           {
12910             operand_0 = tsubst (operand_0, args, complain, in_decl);
12911             return get_typeid (operand_0);
12912           }
12913         else
12914           {
12915             operand_0 = RECUR (operand_0);
12916             return build_typeid (operand_0);
12917           }
12918       }
12919
12920     case VAR_DECL:
12921       if (!args)
12922         return t;
12923       /* Fall through */
12924
12925     case PARM_DECL:
12926       {
12927         tree r = tsubst_copy (t, args, complain, in_decl);
12928
12929         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12930           /* If the original type was a reference, we'll be wrapped in
12931              the appropriate INDIRECT_REF.  */
12932           r = convert_from_reference (r);
12933         return r;
12934       }
12935
12936     case VA_ARG_EXPR:
12937       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12938                              tsubst_copy (TREE_TYPE (t), args, complain,
12939                                           in_decl));
12940
12941     case OFFSETOF_EXPR:
12942       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12943
12944     case TRAIT_EXPR:
12945       {
12946         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12947                                   complain, in_decl);
12948
12949         tree type2 = TRAIT_EXPR_TYPE2 (t);
12950         if (type2)
12951           type2 = tsubst_copy (type2, args, complain, in_decl);
12952         
12953         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12954       }
12955
12956     case STMT_EXPR:
12957       {
12958         tree old_stmt_expr = cur_stmt_expr;
12959         tree stmt_expr = begin_stmt_expr ();
12960
12961         cur_stmt_expr = stmt_expr;
12962         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12963                      integral_constant_expression_p);
12964         stmt_expr = finish_stmt_expr (stmt_expr, false);
12965         cur_stmt_expr = old_stmt_expr;
12966
12967         /* If the resulting list of expression statement is empty,
12968            fold it further into void_zero_node.  */
12969         if (empty_expr_stmt_p (stmt_expr))
12970           stmt_expr = void_zero_node;
12971
12972         return stmt_expr;
12973       }
12974
12975     case CONST_DECL:
12976       t = tsubst_copy (t, args, complain, in_decl);
12977       /* As in finish_id_expression, we resolve enumeration constants
12978          to their underlying values.  */
12979       if (TREE_CODE (t) == CONST_DECL)
12980         {
12981           used_types_insert (TREE_TYPE (t));
12982           return DECL_INITIAL (t);
12983         }
12984       return t;
12985
12986     case LAMBDA_EXPR:
12987       {
12988         tree r = build_lambda_expr ();
12989
12990         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12991         TREE_TYPE (r) = type;
12992         CLASSTYPE_LAMBDA_EXPR (type) = r;
12993
12994         LAMBDA_EXPR_LOCATION (r)
12995           = LAMBDA_EXPR_LOCATION (t);
12996         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12997           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12998         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12999         LAMBDA_EXPR_DISCRIMINATOR (r)
13000           = (LAMBDA_EXPR_DISCRIMINATOR (t));
13001         LAMBDA_EXPR_CAPTURE_LIST (r)
13002           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
13003         LAMBDA_EXPR_THIS_CAPTURE (r)
13004           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
13005         LAMBDA_EXPR_EXTRA_SCOPE (r)
13006           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
13007
13008         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
13009         determine_visibility (TYPE_NAME (type));
13010         /* Now that we know visibility, instantiate the type so we have a
13011            declaration of the op() for later calls to lambda_function.  */
13012         complete_type (type);
13013
13014         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
13015         if (type)
13016           apply_lambda_return_type (r, type);
13017
13018         return build_lambda_object (r);
13019       }
13020
13021     default:
13022       /* Handle Objective-C++ constructs, if appropriate.  */
13023       {
13024         tree subst
13025           = objcp_tsubst_copy_and_build (t, args, complain,
13026                                          in_decl, /*function_p=*/false);
13027         if (subst)
13028           return subst;
13029       }
13030       return tsubst_copy (t, args, complain, in_decl);
13031     }
13032
13033 #undef RECUR
13034 }
13035
13036 /* Verify that the instantiated ARGS are valid. For type arguments,
13037    make sure that the type's linkage is ok. For non-type arguments,
13038    make sure they are constants if they are integral or enumerations.
13039    Emit an error under control of COMPLAIN, and return TRUE on error.  */
13040
13041 static bool
13042 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
13043 {
13044   if (ARGUMENT_PACK_P (t))
13045     {
13046       tree vec = ARGUMENT_PACK_ARGS (t);
13047       int len = TREE_VEC_LENGTH (vec);
13048       bool result = false;
13049       int i;
13050
13051       for (i = 0; i < len; ++i)
13052         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
13053           result = true;
13054       return result;
13055     }
13056   else if (TYPE_P (t))
13057     {
13058       /* [basic.link]: A name with no linkage (notably, the name
13059          of a class or enumeration declared in a local scope)
13060          shall not be used to declare an entity with linkage.
13061          This implies that names with no linkage cannot be used as
13062          template arguments
13063
13064          DR 757 relaxes this restriction for C++0x.  */
13065       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
13066                  : no_linkage_check (t, /*relaxed_p=*/false));
13067
13068       if (nt)
13069         {
13070           /* DR 488 makes use of a type with no linkage cause
13071              type deduction to fail.  */
13072           if (complain & tf_error)
13073             {
13074               if (TYPE_ANONYMOUS_P (nt))
13075                 error ("%qT is/uses anonymous type", t);
13076               else
13077                 error ("template argument for %qD uses local type %qT",
13078                        tmpl, t);
13079             }
13080           return true;
13081         }
13082       /* In order to avoid all sorts of complications, we do not
13083          allow variably-modified types as template arguments.  */
13084       else if (variably_modified_type_p (t, NULL_TREE))
13085         {
13086           if (complain & tf_error)
13087             error ("%qT is a variably modified type", t);
13088           return true;
13089         }
13090     }
13091   /* A non-type argument of integral or enumerated type must be a
13092      constant.  */
13093   else if (TREE_TYPE (t)
13094            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
13095            && !TREE_CONSTANT (t))
13096     {
13097       if (complain & tf_error)
13098         error ("integral expression %qE is not constant", t);
13099       return true;
13100     }
13101   return false;
13102 }
13103
13104 static bool
13105 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
13106 {
13107   int ix, len = DECL_NTPARMS (tmpl);
13108   bool result = false;
13109
13110   for (ix = 0; ix != len; ix++)
13111     {
13112       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
13113         result = true;
13114     }
13115   if (result && (complain & tf_error))
13116     error ("  trying to instantiate %qD", tmpl);
13117   return result;
13118 }
13119
13120 /* Instantiate the indicated variable or function template TMPL with
13121    the template arguments in TARG_PTR.  */
13122
13123 tree
13124 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
13125 {
13126   tree targ_ptr = orig_args;
13127   tree fndecl;
13128   tree gen_tmpl;
13129   tree spec;
13130   HOST_WIDE_INT saved_processing_template_decl;
13131
13132   if (tmpl == error_mark_node)
13133     return error_mark_node;
13134
13135   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
13136
13137   /* If this function is a clone, handle it specially.  */
13138   if (DECL_CLONED_FUNCTION_P (tmpl))
13139     {
13140       tree spec;
13141       tree clone;
13142
13143       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
13144          DECL_CLONED_FUNCTION.  */
13145       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
13146                                    targ_ptr, complain);
13147       if (spec == error_mark_node)
13148         return error_mark_node;
13149
13150       /* Look for the clone.  */
13151       FOR_EACH_CLONE (clone, spec)
13152         if (DECL_NAME (clone) == DECL_NAME (tmpl))
13153           return clone;
13154       /* We should always have found the clone by now.  */
13155       gcc_unreachable ();
13156       return NULL_TREE;
13157     }
13158
13159   /* Check to see if we already have this specialization.  */
13160   gen_tmpl = most_general_template (tmpl);
13161   if (tmpl != gen_tmpl)
13162     /* The TMPL is a partial instantiation.  To get a full set of
13163        arguments we must add the arguments used to perform the
13164        partial instantiation.  */
13165     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
13166                                             targ_ptr);
13167
13168   /* It would be nice to avoid hashing here and then again in tsubst_decl,
13169      but it doesn't seem to be on the hot path.  */
13170   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
13171
13172   gcc_assert (tmpl == gen_tmpl
13173               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
13174                   == spec)
13175               || fndecl == NULL_TREE);
13176
13177   if (spec != NULL_TREE)
13178     return spec;
13179
13180   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
13181                                complain))
13182     return error_mark_node;
13183
13184   /* We are building a FUNCTION_DECL, during which the access of its
13185      parameters and return types have to be checked.  However this
13186      FUNCTION_DECL which is the desired context for access checking
13187      is not built yet.  We solve this chicken-and-egg problem by
13188      deferring all checks until we have the FUNCTION_DECL.  */
13189   push_deferring_access_checks (dk_deferred);
13190
13191   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
13192      (because, for example, we have encountered a non-dependent
13193      function call in the body of a template function and must now
13194      determine which of several overloaded functions will be called),
13195      within the instantiation itself we are not processing a
13196      template.  */  
13197   saved_processing_template_decl = processing_template_decl;
13198   processing_template_decl = 0;
13199   /* Substitute template parameters to obtain the specialization.  */
13200   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
13201                    targ_ptr, complain, gen_tmpl);
13202   processing_template_decl = saved_processing_template_decl;
13203   if (fndecl == error_mark_node)
13204     return error_mark_node;
13205
13206   /* Now we know the specialization, compute access previously
13207      deferred.  */
13208   push_access_scope (fndecl);
13209
13210   /* Some typedefs referenced from within the template code need to be access
13211      checked at template instantiation time, i.e now. These types were
13212      added to the template at parsing time. Let's get those and perfom
13213      the acces checks then.  */
13214   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
13215   perform_deferred_access_checks ();
13216   pop_access_scope (fndecl);
13217   pop_deferring_access_checks ();
13218
13219   /* The DECL_TI_TEMPLATE should always be the immediate parent
13220      template, not the most general template.  */
13221   DECL_TI_TEMPLATE (fndecl) = tmpl;
13222
13223   /* If we've just instantiated the main entry point for a function,
13224      instantiate all the alternate entry points as well.  We do this
13225      by cloning the instantiation of the main entry point, not by
13226      instantiating the template clones.  */
13227   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
13228     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
13229
13230   return fndecl;
13231 }
13232
13233 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
13234    NARGS elements of the arguments that are being used when calling
13235    it.  TARGS is a vector into which the deduced template arguments
13236    are placed.
13237
13238    Return zero for success, 2 for an incomplete match that doesn't resolve
13239    all the types, and 1 for complete failure.  An error message will be
13240    printed only for an incomplete match.
13241
13242    If FN is a conversion operator, or we are trying to produce a specific
13243    specialization, RETURN_TYPE is the return type desired.
13244
13245    The EXPLICIT_TARGS are explicit template arguments provided via a
13246    template-id.
13247
13248    The parameter STRICT is one of:
13249
13250    DEDUCE_CALL:
13251      We are deducing arguments for a function call, as in
13252      [temp.deduct.call].
13253
13254    DEDUCE_CONV:
13255      We are deducing arguments for a conversion function, as in
13256      [temp.deduct.conv].
13257
13258    DEDUCE_EXACT:
13259      We are deducing arguments when doing an explicit instantiation
13260      as in [temp.explicit], when determining an explicit specialization
13261      as in [temp.expl.spec], or when taking the address of a function
13262      template, as in [temp.deduct.funcaddr].  */
13263
13264 int
13265 fn_type_unification (tree fn,
13266                      tree explicit_targs,
13267                      tree targs,
13268                      const tree *args,
13269                      unsigned int nargs,
13270                      tree return_type,
13271                      unification_kind_t strict,
13272                      int flags)
13273 {
13274   tree parms;
13275   tree fntype;
13276   int result;
13277   bool incomplete_argument_packs_p = false;
13278
13279   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13280
13281   fntype = TREE_TYPE (fn);
13282   if (explicit_targs)
13283     {
13284       /* [temp.deduct]
13285
13286          The specified template arguments must match the template
13287          parameters in kind (i.e., type, nontype, template), and there
13288          must not be more arguments than there are parameters;
13289          otherwise type deduction fails.
13290
13291          Nontype arguments must match the types of the corresponding
13292          nontype template parameters, or must be convertible to the
13293          types of the corresponding nontype parameters as specified in
13294          _temp.arg.nontype_, otherwise type deduction fails.
13295
13296          All references in the function type of the function template
13297          to the corresponding template parameters are replaced by the
13298          specified template argument values.  If a substitution in a
13299          template parameter or in the function type of the function
13300          template results in an invalid type, type deduction fails.  */
13301       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13302       int i, len = TREE_VEC_LENGTH (tparms);
13303       tree converted_args;
13304       bool incomplete = false;
13305
13306       if (explicit_targs == error_mark_node)
13307         return 1;
13308
13309       converted_args
13310         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13311                                   /*require_all_args=*/false,
13312                                   /*use_default_args=*/false));
13313       if (converted_args == error_mark_node)
13314         return 1;
13315
13316       /* Substitute the explicit args into the function type.  This is
13317          necessary so that, for instance, explicitly declared function
13318          arguments can match null pointed constants.  If we were given
13319          an incomplete set of explicit args, we must not do semantic
13320          processing during substitution as we could create partial
13321          instantiations.  */
13322       for (i = 0; i < len; i++)
13323         {
13324           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13325           bool parameter_pack = false;
13326
13327           /* Dig out the actual parm.  */
13328           if (TREE_CODE (parm) == TYPE_DECL
13329               || TREE_CODE (parm) == TEMPLATE_DECL)
13330             {
13331               parm = TREE_TYPE (parm);
13332               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13333             }
13334           else if (TREE_CODE (parm) == PARM_DECL)
13335             {
13336               parm = DECL_INITIAL (parm);
13337               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13338             }
13339
13340           if (parameter_pack)
13341             {
13342               int level, idx;
13343               tree targ;
13344               template_parm_level_and_index (parm, &level, &idx);
13345
13346               /* Mark the argument pack as "incomplete". We could
13347                  still deduce more arguments during unification.  */
13348               targ = TMPL_ARG (converted_args, level, idx);
13349               if (targ)
13350                 {
13351                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13352                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
13353                     = ARGUMENT_PACK_ARGS (targ);
13354                 }
13355
13356               /* We have some incomplete argument packs.  */
13357               incomplete_argument_packs_p = true;
13358             }
13359         }
13360
13361       if (incomplete_argument_packs_p)
13362         /* Any substitution is guaranteed to be incomplete if there
13363            are incomplete argument packs, because we can still deduce
13364            more arguments.  */
13365         incomplete = 1;
13366       else
13367         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
13368
13369       processing_template_decl += incomplete;
13370       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
13371       processing_template_decl -= incomplete;
13372
13373       if (fntype == error_mark_node)
13374         return 1;
13375
13376       /* Place the explicitly specified arguments in TARGS.  */
13377       for (i = NUM_TMPL_ARGS (converted_args); i--;)
13378         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
13379     }
13380
13381   /* Never do unification on the 'this' parameter.  */
13382   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
13383
13384   if (return_type)
13385     {
13386       tree *new_args;
13387
13388       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
13389       new_args = XALLOCAVEC (tree, nargs + 1);
13390       new_args[0] = return_type;
13391       memcpy (new_args + 1, args, nargs * sizeof (tree));
13392       args = new_args;
13393       ++nargs;
13394     }
13395
13396   /* We allow incomplete unification without an error message here
13397      because the standard doesn't seem to explicitly prohibit it.  Our
13398      callers must be ready to deal with unification failures in any
13399      event.  */
13400   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
13401                                   targs, parms, args, nargs, /*subr=*/0,
13402                                   strict, flags);
13403
13404   if (result == 0 && incomplete_argument_packs_p)
13405     {
13406       int i, len = NUM_TMPL_ARGS (targs);
13407
13408       /* Clear the "incomplete" flags on all argument packs.  */
13409       for (i = 0; i < len; i++)
13410         {
13411           tree arg = TREE_VEC_ELT (targs, i);
13412           if (ARGUMENT_PACK_P (arg))
13413             {
13414               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
13415               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
13416             }
13417         }
13418     }
13419
13420   /* Now that we have bindings for all of the template arguments,
13421      ensure that the arguments deduced for the template template
13422      parameters have compatible template parameter lists.  We cannot
13423      check this property before we have deduced all template
13424      arguments, because the template parameter types of a template
13425      template parameter might depend on prior template parameters
13426      deduced after the template template parameter.  The following
13427      ill-formed example illustrates this issue:
13428
13429        template<typename T, template<T> class C> void f(C<5>, T);
13430
13431        template<int N> struct X {};
13432
13433        void g() {
13434          f(X<5>(), 5l); // error: template argument deduction fails
13435        }
13436
13437      The template parameter list of 'C' depends on the template type
13438      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13439      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13440      time that we deduce 'C'.  */
13441   if (result == 0
13442       && !template_template_parm_bindings_ok_p 
13443            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13444     return 1;
13445
13446   if (result == 0)
13447     /* All is well so far.  Now, check:
13448
13449        [temp.deduct]
13450
13451        When all template arguments have been deduced, all uses of
13452        template parameters in nondeduced contexts are replaced with
13453        the corresponding deduced argument values.  If the
13454        substitution results in an invalid type, as described above,
13455        type deduction fails.  */
13456     {
13457       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13458       if (substed == error_mark_node)
13459         return 1;
13460
13461       /* If we're looking for an exact match, check that what we got
13462          is indeed an exact match.  It might not be if some template
13463          parameters are used in non-deduced contexts.  */
13464       if (strict == DEDUCE_EXACT)
13465         {
13466           unsigned int i;
13467
13468           tree sarg
13469             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13470           if (return_type)
13471             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13472           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13473             if (!same_type_p (args[i], TREE_VALUE (sarg)))
13474               return 1;
13475         }
13476     }
13477
13478   return result;
13479 }
13480
13481 /* Adjust types before performing type deduction, as described in
13482    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13483    sections are symmetric.  PARM is the type of a function parameter
13484    or the return type of the conversion function.  ARG is the type of
13485    the argument passed to the call, or the type of the value
13486    initialized with the result of the conversion function.
13487    ARG_EXPR is the original argument expression, which may be null.  */
13488
13489 static int
13490 maybe_adjust_types_for_deduction (unification_kind_t strict,
13491                                   tree* parm,
13492                                   tree* arg,
13493                                   tree arg_expr)
13494 {
13495   int result = 0;
13496
13497   switch (strict)
13498     {
13499     case DEDUCE_CALL:
13500       break;
13501
13502     case DEDUCE_CONV:
13503       {
13504         /* Swap PARM and ARG throughout the remainder of this
13505            function; the handling is precisely symmetric since PARM
13506            will initialize ARG rather than vice versa.  */
13507         tree* temp = parm;
13508         parm = arg;
13509         arg = temp;
13510         break;
13511       }
13512
13513     case DEDUCE_EXACT:
13514       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13515          too, but here handle it by stripping the reference from PARM
13516          rather than by adding it to ARG.  */
13517       if (TREE_CODE (*parm) == REFERENCE_TYPE
13518           && TYPE_REF_IS_RVALUE (*parm)
13519           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13520           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13521           && TREE_CODE (*arg) == REFERENCE_TYPE
13522           && !TYPE_REF_IS_RVALUE (*arg))
13523         *parm = TREE_TYPE (*parm);
13524       /* Nothing else to do in this case.  */
13525       return 0;
13526
13527     default:
13528       gcc_unreachable ();
13529     }
13530
13531   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13532     {
13533       /* [temp.deduct.call]
13534
13535          If P is not a reference type:
13536
13537          --If A is an array type, the pointer type produced by the
13538          array-to-pointer standard conversion (_conv.array_) is
13539          used in place of A for type deduction; otherwise,
13540
13541          --If A is a function type, the pointer type produced by
13542          the function-to-pointer standard conversion
13543          (_conv.func_) is used in place of A for type deduction;
13544          otherwise,
13545
13546          --If A is a cv-qualified type, the top level
13547          cv-qualifiers of A's type are ignored for type
13548          deduction.  */
13549       if (TREE_CODE (*arg) == ARRAY_TYPE)
13550         *arg = build_pointer_type (TREE_TYPE (*arg));
13551       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13552         *arg = build_pointer_type (*arg);
13553       else
13554         *arg = TYPE_MAIN_VARIANT (*arg);
13555     }
13556
13557   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13558      of the form T&&, where T is a template parameter, and the argument
13559      is an lvalue, T is deduced as A& */
13560   if (TREE_CODE (*parm) == REFERENCE_TYPE
13561       && TYPE_REF_IS_RVALUE (*parm)
13562       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13563       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13564       && arg_expr && real_lvalue_p (arg_expr))
13565     *arg = build_reference_type (*arg);
13566
13567   /* [temp.deduct.call]
13568
13569      If P is a cv-qualified type, the top level cv-qualifiers
13570      of P's type are ignored for type deduction.  If P is a
13571      reference type, the type referred to by P is used for
13572      type deduction.  */
13573   *parm = TYPE_MAIN_VARIANT (*parm);
13574   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13575     {
13576       *parm = TREE_TYPE (*parm);
13577       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13578     }
13579
13580   /* DR 322. For conversion deduction, remove a reference type on parm
13581      too (which has been swapped into ARG).  */
13582   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13583     *arg = TREE_TYPE (*arg);
13584
13585   return result;
13586 }
13587
13588 /* Most parms like fn_type_unification.
13589
13590    If SUBR is 1, we're being called recursively (to unify the
13591    arguments of a function or method parameter of a function
13592    template). */
13593
13594 static int
13595 type_unification_real (tree tparms,
13596                        tree targs,
13597                        tree xparms,
13598                        const tree *xargs,
13599                        unsigned int xnargs,
13600                        int subr,
13601                        unification_kind_t strict,
13602                        int flags)
13603 {
13604   tree parm, arg, arg_expr;
13605   int i;
13606   int ntparms = TREE_VEC_LENGTH (tparms);
13607   int sub_strict;
13608   int saw_undeduced = 0;
13609   tree parms;
13610   const tree *args;
13611   unsigned int nargs;
13612   unsigned int ia;
13613
13614   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13615   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13616   gcc_assert (ntparms > 0);
13617
13618   /* Reset the number of non-defaulted template arguments contained
13619      in in TARGS.  */
13620   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
13621
13622   switch (strict)
13623     {
13624     case DEDUCE_CALL:
13625       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13626                     | UNIFY_ALLOW_DERIVED);
13627       break;
13628
13629     case DEDUCE_CONV:
13630       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13631       break;
13632
13633     case DEDUCE_EXACT:
13634       sub_strict = UNIFY_ALLOW_NONE;
13635       break;
13636
13637     default:
13638       gcc_unreachable ();
13639     }
13640
13641  again:
13642   parms = xparms;
13643   args = xargs;
13644   nargs = xnargs;
13645
13646   ia = 0;
13647   while (parms && parms != void_list_node
13648          && ia < nargs)
13649     {
13650       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13651         break;
13652
13653       parm = TREE_VALUE (parms);
13654       parms = TREE_CHAIN (parms);
13655       arg = args[ia];
13656       ++ia;
13657       arg_expr = NULL;
13658
13659       if (arg == error_mark_node)
13660         return 1;
13661       if (arg == unknown_type_node)
13662         /* We can't deduce anything from this, but we might get all the
13663            template args from other function args.  */
13664         continue;
13665
13666       /* Conversions will be performed on a function argument that
13667          corresponds with a function parameter that contains only
13668          non-deducible template parameters and explicitly specified
13669          template parameters.  */
13670       if (!uses_template_parms (parm))
13671         {
13672           tree type;
13673
13674           if (!TYPE_P (arg))
13675             type = TREE_TYPE (arg);
13676           else
13677             type = arg;
13678
13679           if (same_type_p (parm, type))
13680             continue;
13681           if (strict != DEDUCE_EXACT
13682               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13683                                   flags))
13684             continue;
13685
13686           return 1;
13687         }
13688
13689       if (!TYPE_P (arg))
13690         {
13691           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13692           if (type_unknown_p (arg))
13693             {
13694               /* [temp.deduct.type] 
13695
13696                  A template-argument can be deduced from a pointer to
13697                  function or pointer to member function argument if
13698                  the set of overloaded functions does not contain
13699                  function templates and at most one of a set of
13700                  overloaded functions provides a unique match.  */
13701               if (resolve_overloaded_unification
13702                   (tparms, targs, parm, arg, strict, sub_strict))
13703                 continue;
13704
13705               return 1;
13706             }
13707           arg_expr = arg;
13708           arg = unlowered_expr_type (arg);
13709           if (arg == error_mark_node)
13710             return 1;
13711         }
13712
13713       {
13714         int arg_strict = sub_strict;
13715
13716         if (!subr)
13717           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13718                                                           arg_expr);
13719
13720         if (arg == init_list_type_node && arg_expr)
13721           arg = arg_expr;
13722         if (unify (tparms, targs, parm, arg, arg_strict))
13723           return 1;
13724       }
13725     }
13726
13727
13728   if (parms 
13729       && parms != void_list_node
13730       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13731     {
13732       /* Unify the remaining arguments with the pack expansion type.  */
13733       tree argvec;
13734       tree parmvec = make_tree_vec (1);
13735
13736       /* Allocate a TREE_VEC and copy in all of the arguments */ 
13737       argvec = make_tree_vec (nargs - ia);
13738       for (i = 0; ia < nargs; ++ia, ++i)
13739         TREE_VEC_ELT (argvec, i) = args[ia];
13740
13741       /* Copy the parameter into parmvec.  */
13742       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13743       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13744                                 /*call_args_p=*/true, /*subr=*/subr))
13745         return 1;
13746
13747       /* Advance to the end of the list of parameters.  */
13748       parms = TREE_CHAIN (parms);
13749     }
13750
13751   /* Fail if we've reached the end of the parm list, and more args
13752      are present, and the parm list isn't variadic.  */
13753   if (ia < nargs && parms == void_list_node)
13754     return 1;
13755   /* Fail if parms are left and they don't have default values.  */
13756   if (parms && parms != void_list_node
13757       && TREE_PURPOSE (parms) == NULL_TREE)
13758     return 1;
13759
13760   if (!subr)
13761     for (i = 0; i < ntparms; i++)
13762       if (!TREE_VEC_ELT (targs, i))
13763         {
13764           tree tparm;
13765
13766           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13767             continue;
13768
13769           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13770
13771           /* If this is an undeduced nontype parameter that depends on
13772              a type parameter, try another pass; its type may have been
13773              deduced from a later argument than the one from which
13774              this parameter can be deduced.  */
13775           if (TREE_CODE (tparm) == PARM_DECL
13776               && uses_template_parms (TREE_TYPE (tparm))
13777               && !saw_undeduced++)
13778             goto again;
13779
13780           /* Core issue #226 (C++0x) [temp.deduct]:
13781
13782                If a template argument has not been deduced, its
13783                default template argument, if any, is used. 
13784
13785              When we are in C++98 mode, TREE_PURPOSE will either
13786              be NULL_TREE or ERROR_MARK_NODE, so we do not need
13787              to explicitly check cxx_dialect here.  */
13788           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13789             {
13790               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13791               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13792               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13793               arg = convert_template_argument (parm, arg, targs, tf_none,
13794                                                i, NULL_TREE);
13795               if (arg == error_mark_node)
13796                 return 1;
13797               else
13798                 {
13799                   TREE_VEC_ELT (targs, i) = arg;
13800                   /* The position of the first default template argument,
13801                      is also the number of non-defaulted arguments in TARGS.
13802                      Record that.  */
13803                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13804                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
13805                   continue;
13806                 }
13807             }
13808
13809           /* If the type parameter is a parameter pack, then it will
13810              be deduced to an empty parameter pack.  */
13811           if (template_parameter_pack_p (tparm))
13812             {
13813               tree arg;
13814
13815               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13816                 {
13817                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13818                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13819                   TREE_CONSTANT (arg) = 1;
13820                 }
13821               else
13822                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13823
13824               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13825
13826               TREE_VEC_ELT (targs, i) = arg;
13827               continue;
13828             }
13829
13830           return 2;
13831         }
13832 #ifdef ENABLE_CHECKING
13833   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13834     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
13835 #endif
13836
13837   return 0;
13838 }
13839
13840 /* Subroutine of type_unification_real.  Args are like the variables
13841    at the call site.  ARG is an overloaded function (or template-id);
13842    we try deducing template args from each of the overloads, and if
13843    only one succeeds, we go with that.  Modifies TARGS and returns
13844    true on success.  */
13845
13846 static bool
13847 resolve_overloaded_unification (tree tparms,
13848                                 tree targs,
13849                                 tree parm,
13850                                 tree arg,
13851                                 unification_kind_t strict,
13852                                 int sub_strict)
13853 {
13854   tree tempargs = copy_node (targs);
13855   int good = 0;
13856   tree goodfn = NULL_TREE;
13857   bool addr_p;
13858
13859   if (TREE_CODE (arg) == ADDR_EXPR)
13860     {
13861       arg = TREE_OPERAND (arg, 0);
13862       addr_p = true;
13863     }
13864   else
13865     addr_p = false;
13866
13867   if (TREE_CODE (arg) == COMPONENT_REF)
13868     /* Handle `&x' where `x' is some static or non-static member
13869        function name.  */
13870     arg = TREE_OPERAND (arg, 1);
13871
13872   if (TREE_CODE (arg) == OFFSET_REF)
13873     arg = TREE_OPERAND (arg, 1);
13874
13875   /* Strip baselink information.  */
13876   if (BASELINK_P (arg))
13877     arg = BASELINK_FUNCTIONS (arg);
13878
13879   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13880     {
13881       /* If we got some explicit template args, we need to plug them into
13882          the affected templates before we try to unify, in case the
13883          explicit args will completely resolve the templates in question.  */
13884
13885       tree expl_subargs = TREE_OPERAND (arg, 1);
13886       arg = TREE_OPERAND (arg, 0);
13887
13888       for (; arg; arg = OVL_NEXT (arg))
13889         {
13890           tree fn = OVL_CURRENT (arg);
13891           tree subargs, elem;
13892
13893           if (TREE_CODE (fn) != TEMPLATE_DECL)
13894             continue;
13895
13896           ++processing_template_decl;
13897           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13898                                   expl_subargs, /*check_ret=*/false);
13899           if (subargs)
13900             {
13901               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13902               if (try_one_overload (tparms, targs, tempargs, parm,
13903                                     elem, strict, sub_strict, addr_p)
13904                   && (!goodfn || !decls_match (goodfn, elem)))
13905                 {
13906                   goodfn = elem;
13907                   ++good;
13908                 }
13909             }
13910           --processing_template_decl;
13911         }
13912     }
13913   else if (TREE_CODE (arg) != OVERLOAD
13914            && TREE_CODE (arg) != FUNCTION_DECL)
13915     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13916        -- but the deduction does not succeed because the expression is
13917        not just the function on its own.  */
13918     return false;
13919   else
13920     for (; arg; arg = OVL_NEXT (arg))
13921       if (try_one_overload (tparms, targs, tempargs, parm,
13922                             TREE_TYPE (OVL_CURRENT (arg)),
13923                             strict, sub_strict, addr_p)
13924           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13925         {
13926           goodfn = OVL_CURRENT (arg);
13927           ++good;
13928         }
13929
13930   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13931      to function or pointer to member function argument if the set of
13932      overloaded functions does not contain function templates and at most
13933      one of a set of overloaded functions provides a unique match.
13934
13935      So if we found multiple possibilities, we return success but don't
13936      deduce anything.  */
13937
13938   if (good == 1)
13939     {
13940       int i = TREE_VEC_LENGTH (targs);
13941       for (; i--; )
13942         if (TREE_VEC_ELT (tempargs, i))
13943           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13944     }
13945   if (good)
13946     return true;
13947
13948   return false;
13949 }
13950
13951 /* Core DR 115: In contexts where deduction is done and fails, or in
13952    contexts where deduction is not done, if a template argument list is
13953    specified and it, along with any default template arguments, identifies
13954    a single function template specialization, then the template-id is an
13955    lvalue for the function template specialization.  */
13956
13957 tree
13958 resolve_nondeduced_context (tree orig_expr)
13959 {
13960   tree expr, offset, baselink;
13961   bool addr;
13962
13963   if (!type_unknown_p (orig_expr))
13964     return orig_expr;
13965
13966   expr = orig_expr;
13967   addr = false;
13968   offset = NULL_TREE;
13969   baselink = NULL_TREE;
13970
13971   if (TREE_CODE (expr) == ADDR_EXPR)
13972     {
13973       expr = TREE_OPERAND (expr, 0);
13974       addr = true;
13975     }
13976   if (TREE_CODE (expr) == OFFSET_REF)
13977     {
13978       offset = expr;
13979       expr = TREE_OPERAND (expr, 1);
13980     }
13981   if (TREE_CODE (expr) == BASELINK)
13982     {
13983       baselink = expr;
13984       expr = BASELINK_FUNCTIONS (expr);
13985     }
13986
13987   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13988     {
13989       int good = 0;
13990       tree goodfn = NULL_TREE;
13991
13992       /* If we got some explicit template args, we need to plug them into
13993          the affected templates before we try to unify, in case the
13994          explicit args will completely resolve the templates in question.  */
13995
13996       tree expl_subargs = TREE_OPERAND (expr, 1);
13997       tree arg = TREE_OPERAND (expr, 0);
13998       tree badfn = NULL_TREE;
13999       tree badargs = NULL_TREE;
14000
14001       for (; arg; arg = OVL_NEXT (arg))
14002         {
14003           tree fn = OVL_CURRENT (arg);
14004           tree subargs, elem;
14005
14006           if (TREE_CODE (fn) != TEMPLATE_DECL)
14007             continue;
14008
14009           ++processing_template_decl;
14010           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
14011                                   expl_subargs, /*check_ret=*/false);
14012           if (subargs && !any_dependent_template_arguments_p (subargs))
14013             {
14014               elem = instantiate_template (fn, subargs, tf_none);
14015               if (elem == error_mark_node)
14016                 {
14017                   badfn = fn;
14018                   badargs = subargs;
14019                 }
14020               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
14021                 {
14022                   goodfn = elem;
14023                   ++good;
14024                 }
14025             }
14026           --processing_template_decl;
14027         }
14028       if (good == 1)
14029         {
14030           expr = goodfn;
14031           if (baselink)
14032             expr = build_baselink (BASELINK_BINFO (baselink),
14033                                    BASELINK_ACCESS_BINFO (baselink),
14034                                    expr, BASELINK_OPTYPE (baselink));
14035           if (offset)
14036             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
14037                            TREE_OPERAND (offset, 0), expr);
14038           if (addr)
14039             expr = build_address (expr);
14040           return expr;
14041         }
14042       else if (good == 0 && badargs)
14043         /* There were no good options and at least one bad one, so let the
14044            user know what the problem is.  */
14045         instantiate_template (badfn, badargs, tf_warning_or_error);
14046     }
14047   return orig_expr;
14048 }
14049
14050 /* Subroutine of resolve_overloaded_unification; does deduction for a single
14051    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
14052    different overloads deduce different arguments for a given parm.
14053    ADDR_P is true if the expression for which deduction is being
14054    performed was of the form "& fn" rather than simply "fn".
14055
14056    Returns 1 on success.  */
14057
14058 static int
14059 try_one_overload (tree tparms,
14060                   tree orig_targs,
14061                   tree targs,
14062                   tree parm,
14063                   tree arg,
14064                   unification_kind_t strict,
14065                   int sub_strict,
14066                   bool addr_p)
14067 {
14068   int nargs;
14069   tree tempargs;
14070   int i;
14071
14072   /* [temp.deduct.type] A template-argument can be deduced from a pointer
14073      to function or pointer to member function argument if the set of
14074      overloaded functions does not contain function templates and at most
14075      one of a set of overloaded functions provides a unique match.
14076
14077      So if this is a template, just return success.  */
14078
14079   if (uses_template_parms (arg))
14080     return 1;
14081
14082   if (TREE_CODE (arg) == METHOD_TYPE)
14083     arg = build_ptrmemfunc_type (build_pointer_type (arg));
14084   else if (addr_p)
14085     arg = build_pointer_type (arg);
14086
14087   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
14088
14089   /* We don't copy orig_targs for this because if we have already deduced
14090      some template args from previous args, unify would complain when we
14091      try to deduce a template parameter for the same argument, even though
14092      there isn't really a conflict.  */
14093   nargs = TREE_VEC_LENGTH (targs);
14094   tempargs = make_tree_vec (nargs);
14095
14096   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
14097     return 0;
14098
14099   /* First make sure we didn't deduce anything that conflicts with
14100      explicitly specified args.  */
14101   for (i = nargs; i--; )
14102     {
14103       tree elt = TREE_VEC_ELT (tempargs, i);
14104       tree oldelt = TREE_VEC_ELT (orig_targs, i);
14105
14106       if (!elt)
14107         /*NOP*/;
14108       else if (uses_template_parms (elt))
14109         /* Since we're unifying against ourselves, we will fill in
14110            template args used in the function parm list with our own
14111            template parms.  Discard them.  */
14112         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
14113       else if (oldelt && !template_args_equal (oldelt, elt))
14114         return 0;
14115     }
14116
14117   for (i = nargs; i--; )
14118     {
14119       tree elt = TREE_VEC_ELT (tempargs, i);
14120
14121       if (elt)
14122         TREE_VEC_ELT (targs, i) = elt;
14123     }
14124
14125   return 1;
14126 }
14127
14128 /* PARM is a template class (perhaps with unbound template
14129    parameters).  ARG is a fully instantiated type.  If ARG can be
14130    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
14131    TARGS are as for unify.  */
14132
14133 static tree
14134 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
14135 {
14136   tree copy_of_targs;
14137
14138   if (!CLASSTYPE_TEMPLATE_INFO (arg)
14139       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
14140           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
14141     return NULL_TREE;
14142
14143   /* We need to make a new template argument vector for the call to
14144      unify.  If we used TARGS, we'd clutter it up with the result of
14145      the attempted unification, even if this class didn't work out.
14146      We also don't want to commit ourselves to all the unifications
14147      we've already done, since unification is supposed to be done on
14148      an argument-by-argument basis.  In other words, consider the
14149      following pathological case:
14150
14151        template <int I, int J, int K>
14152        struct S {};
14153
14154        template <int I, int J>
14155        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
14156
14157        template <int I, int J, int K>
14158        void f(S<I, J, K>, S<I, I, I>);
14159
14160        void g() {
14161          S<0, 0, 0> s0;
14162          S<0, 1, 2> s2;
14163
14164          f(s0, s2);
14165        }
14166
14167      Now, by the time we consider the unification involving `s2', we
14168      already know that we must have `f<0, 0, 0>'.  But, even though
14169      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
14170      because there are two ways to unify base classes of S<0, 1, 2>
14171      with S<I, I, I>.  If we kept the already deduced knowledge, we
14172      would reject the possibility I=1.  */
14173   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
14174
14175   /* If unification failed, we're done.  */
14176   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
14177              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
14178     return NULL_TREE;
14179
14180   return arg;
14181 }
14182
14183 /* Given a template type PARM and a class type ARG, find the unique
14184    base type in ARG that is an instance of PARM.  We do not examine
14185    ARG itself; only its base-classes.  If there is not exactly one
14186    appropriate base class, return NULL_TREE.  PARM may be the type of
14187    a partial specialization, as well as a plain template type.  Used
14188    by unify.  */
14189
14190 static tree
14191 get_template_base (tree tparms, tree targs, tree parm, tree arg)
14192 {
14193   tree rval = NULL_TREE;
14194   tree binfo;
14195
14196   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
14197
14198   binfo = TYPE_BINFO (complete_type (arg));
14199   if (!binfo)
14200     /* The type could not be completed.  */
14201     return NULL_TREE;
14202
14203   /* Walk in inheritance graph order.  The search order is not
14204      important, and this avoids multiple walks of virtual bases.  */
14205   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
14206     {
14207       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
14208
14209       if (r)
14210         {
14211           /* If there is more than one satisfactory baseclass, then:
14212
14213                [temp.deduct.call]
14214
14215               If they yield more than one possible deduced A, the type
14216               deduction fails.
14217
14218              applies.  */
14219           if (rval && !same_type_p (r, rval))
14220             return NULL_TREE;
14221
14222           rval = r;
14223         }
14224     }
14225
14226   return rval;
14227 }
14228
14229 /* Returns the level of DECL, which declares a template parameter.  */
14230
14231 static int
14232 template_decl_level (tree decl)
14233 {
14234   switch (TREE_CODE (decl))
14235     {
14236     case TYPE_DECL:
14237     case TEMPLATE_DECL:
14238       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
14239
14240     case PARM_DECL:
14241       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
14242
14243     default:
14244       gcc_unreachable ();
14245     }
14246   return 0;
14247 }
14248
14249 /* Decide whether ARG can be unified with PARM, considering only the
14250    cv-qualifiers of each type, given STRICT as documented for unify.
14251    Returns nonzero iff the unification is OK on that basis.  */
14252
14253 static int
14254 check_cv_quals_for_unify (int strict, tree arg, tree parm)
14255 {
14256   int arg_quals = cp_type_quals (arg);
14257   int parm_quals = cp_type_quals (parm);
14258
14259   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14260       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14261     {
14262       /*  Although a CVR qualifier is ignored when being applied to a
14263           substituted template parameter ([8.3.2]/1 for example), that
14264           does not allow us to unify "const T" with "int&" because both
14265           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
14266           It is ok when we're allowing additional CV qualifiers
14267           at the outer level [14.8.2.1]/3,1st bullet.  */
14268       if ((TREE_CODE (arg) == REFERENCE_TYPE
14269            || TREE_CODE (arg) == FUNCTION_TYPE
14270            || TREE_CODE (arg) == METHOD_TYPE)
14271           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14272         return 0;
14273
14274       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14275           && (parm_quals & TYPE_QUAL_RESTRICT))
14276         return 0;
14277     }
14278
14279   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14280       && (arg_quals & parm_quals) != parm_quals)
14281     return 0;
14282
14283   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14284       && (parm_quals & arg_quals) != arg_quals)
14285     return 0;
14286
14287   return 1;
14288 }
14289
14290 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
14291 void 
14292 template_parm_level_and_index (tree parm, int* level, int* index)
14293 {
14294   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14295       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14296       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14297     {
14298       *index = TEMPLATE_TYPE_IDX (parm);
14299       *level = TEMPLATE_TYPE_LEVEL (parm);
14300     }
14301   else
14302     {
14303       *index = TEMPLATE_PARM_IDX (parm);
14304       *level = TEMPLATE_PARM_LEVEL (parm);
14305     }
14306 }
14307
14308 /* Unifies the remaining arguments in PACKED_ARGS with the pack
14309    expansion at the end of PACKED_PARMS. Returns 0 if the type
14310    deduction succeeds, 1 otherwise. STRICT is the same as in
14311    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14312    call argument list. We'll need to adjust the arguments to make them
14313    types. SUBR tells us if this is from a recursive call to
14314    type_unification_real.  */
14315 int
14316 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
14317                       tree packed_args, int strict, bool call_args_p,
14318                       bool subr)
14319 {
14320   tree parm 
14321     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14322   tree pattern = PACK_EXPANSION_PATTERN (parm);
14323   tree pack, packs = NULL_TREE;
14324   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14325   int len = TREE_VEC_LENGTH (packed_args);
14326
14327   /* Determine the parameter packs we will be deducing from the
14328      pattern, and record their current deductions.  */
14329   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
14330        pack; pack = TREE_CHAIN (pack))
14331     {
14332       tree parm_pack = TREE_VALUE (pack);
14333       int idx, level;
14334
14335       /* Determine the index and level of this parameter pack.  */
14336       template_parm_level_and_index (parm_pack, &level, &idx);
14337
14338       /* Keep track of the parameter packs and their corresponding
14339          argument packs.  */
14340       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
14341       TREE_TYPE (packs) = make_tree_vec (len - start);
14342     }
14343   
14344   /* Loop through all of the arguments that have not yet been
14345      unified and unify each with the pattern.  */
14346   for (i = start; i < len; i++)
14347     {
14348       tree parm = pattern;
14349
14350       /* For each parameter pack, clear out the deduced value so that
14351          we can deduce it again.  */
14352       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14353         {
14354           int idx, level;
14355           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14356
14357           TMPL_ARG (targs, level, idx) = NULL_TREE;
14358         }
14359
14360       /* Unify the pattern with the current argument.  */
14361       {
14362         tree arg = TREE_VEC_ELT (packed_args, i);
14363         tree arg_expr = NULL_TREE;
14364         int arg_strict = strict;
14365         bool skip_arg_p = false;
14366
14367         if (call_args_p)
14368           {
14369             int sub_strict;
14370
14371             /* This mirrors what we do in type_unification_real.  */
14372             switch (strict)
14373               {
14374               case DEDUCE_CALL:
14375                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
14376                               | UNIFY_ALLOW_MORE_CV_QUAL
14377                               | UNIFY_ALLOW_DERIVED);
14378                 break;
14379                 
14380               case DEDUCE_CONV:
14381                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14382                 break;
14383                 
14384               case DEDUCE_EXACT:
14385                 sub_strict = UNIFY_ALLOW_NONE;
14386                 break;
14387                 
14388               default:
14389                 gcc_unreachable ();
14390               }
14391
14392             if (!TYPE_P (arg))
14393               {
14394                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14395                 if (type_unknown_p (arg))
14396                   {
14397                     /* [temp.deduct.type] A template-argument can be
14398                        deduced from a pointer to function or pointer
14399                        to member function argument if the set of
14400                        overloaded functions does not contain function
14401                        templates and at most one of a set of
14402                        overloaded functions provides a unique
14403                        match.  */
14404
14405                     if (resolve_overloaded_unification
14406                         (tparms, targs, parm, arg,
14407                          (unification_kind_t) strict,
14408                          sub_strict)
14409                         != 0)
14410                       return 1;
14411                     skip_arg_p = true;
14412                   }
14413
14414                 if (!skip_arg_p)
14415                   {
14416                     arg_expr = arg;
14417                     arg = unlowered_expr_type (arg);
14418                     if (arg == error_mark_node)
14419                       return 1;
14420                   }
14421               }
14422       
14423             arg_strict = sub_strict;
14424
14425             if (!subr)
14426               arg_strict |= 
14427                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
14428                                                   &parm, &arg, arg_expr);
14429           }
14430
14431         if (!skip_arg_p)
14432           {
14433             /* For deduction from an init-list we need the actual list.  */
14434             if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14435               arg = arg_expr;
14436             if (unify (tparms, targs, parm, arg, arg_strict))
14437               return 1;
14438           }
14439       }
14440
14441       /* For each parameter pack, collect the deduced value.  */
14442       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14443         {
14444           int idx, level;
14445           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14446
14447           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
14448             TMPL_ARG (targs, level, idx);
14449         }
14450     }
14451
14452   /* Verify that the results of unification with the parameter packs
14453      produce results consistent with what we've seen before, and make
14454      the deduced argument packs available.  */
14455   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14456     {
14457       tree old_pack = TREE_VALUE (pack);
14458       tree new_args = TREE_TYPE (pack);
14459       int i, len = TREE_VEC_LENGTH (new_args);
14460       int idx, level;
14461       bool nondeduced_p = false;
14462
14463       /* By default keep the original deduced argument pack.
14464          If necessary, more specific code is going to update the
14465          resulting deduced argument later down in this function.  */
14466       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14467       TMPL_ARG (targs, level, idx) = old_pack;
14468
14469       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14470          actually deduce anything.  */
14471       for (i = 0; i < len && !nondeduced_p; ++i)
14472         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14473           nondeduced_p = true;
14474       if (nondeduced_p)
14475         continue;
14476
14477       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14478         {
14479           /* Prepend the explicit arguments onto NEW_ARGS.  */
14480           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14481           tree old_args = new_args;
14482           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14483           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14484
14485           /* Copy the explicit arguments.  */
14486           new_args = make_tree_vec (len);
14487           for (i = 0; i < explicit_len; i++)
14488             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14489
14490           /* Copy the deduced arguments.  */
14491           for (; i < len; i++)
14492             TREE_VEC_ELT (new_args, i) =
14493               TREE_VEC_ELT (old_args, i - explicit_len);
14494         }
14495
14496       if (!old_pack)
14497         {
14498           tree result;
14499           /* Build the deduced *_ARGUMENT_PACK.  */
14500           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14501             {
14502               result = make_node (NONTYPE_ARGUMENT_PACK);
14503               TREE_TYPE (result) = 
14504                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14505               TREE_CONSTANT (result) = 1;
14506             }
14507           else
14508             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14509
14510           SET_ARGUMENT_PACK_ARGS (result, new_args);
14511
14512           /* Note the deduced argument packs for this parameter
14513              pack.  */
14514           TMPL_ARG (targs, level, idx) = result;
14515         }
14516       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14517                && (ARGUMENT_PACK_ARGS (old_pack) 
14518                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14519         {
14520           /* We only had the explicitly-provided arguments before, but
14521              now we have a complete set of arguments.  */
14522           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14523
14524           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14525           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14526           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14527         }
14528       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14529                                     new_args))
14530         /* Inconsistent unification of this parameter pack.  */
14531         return 1;
14532     }
14533
14534   return 0;
14535 }
14536
14537 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14538    set of template parameters to a template.  TARGS is the bindings
14539    for those template parameters, as determined thus far; TARGS may
14540    include template arguments for outer levels of template parameters
14541    as well.  PARM is a parameter to a template function, or a
14542    subcomponent of that parameter; ARG is the corresponding argument.
14543    This function attempts to match PARM with ARG in a manner
14544    consistent with the existing assignments in TARGS.  If more values
14545    are deduced, then TARGS is updated.
14546
14547    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14548    parameter STRICT is a bitwise or of the following flags:
14549
14550      UNIFY_ALLOW_NONE:
14551        Require an exact match between PARM and ARG.
14552      UNIFY_ALLOW_MORE_CV_QUAL:
14553        Allow the deduced ARG to be more cv-qualified (by qualification
14554        conversion) than ARG.
14555      UNIFY_ALLOW_LESS_CV_QUAL:
14556        Allow the deduced ARG to be less cv-qualified than ARG.
14557      UNIFY_ALLOW_DERIVED:
14558        Allow the deduced ARG to be a template base class of ARG,
14559        or a pointer to a template base class of the type pointed to by
14560        ARG.
14561      UNIFY_ALLOW_INTEGER:
14562        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14563        case for more information.
14564      UNIFY_ALLOW_OUTER_LEVEL:
14565        This is the outermost level of a deduction. Used to determine validity
14566        of qualification conversions. A valid qualification conversion must
14567        have const qualified pointers leading up to the inner type which
14568        requires additional CV quals, except at the outer level, where const
14569        is not required [conv.qual]. It would be normal to set this flag in
14570        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14571      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14572        This is the outermost level of a deduction, and PARM can be more CV
14573        qualified at this point.
14574      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14575        This is the outermost level of a deduction, and PARM can be less CV
14576        qualified at this point.  */
14577
14578 static int
14579 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14580 {
14581   int idx;
14582   tree targ;
14583   tree tparm;
14584   int strict_in = strict;
14585
14586   /* I don't think this will do the right thing with respect to types.
14587      But the only case I've seen it in so far has been array bounds, where
14588      signedness is the only information lost, and I think that will be
14589      okay.  */
14590   while (TREE_CODE (parm) == NOP_EXPR)
14591     parm = TREE_OPERAND (parm, 0);
14592
14593   if (arg == error_mark_node)
14594     return 1;
14595   if (arg == unknown_type_node
14596       || arg == init_list_type_node)
14597     /* We can't deduce anything from this, but we might get all the
14598        template args from other function args.  */
14599     return 0;
14600
14601   /* If PARM uses template parameters, then we can't bail out here,
14602      even if ARG == PARM, since we won't record unifications for the
14603      template parameters.  We might need them if we're trying to
14604      figure out which of two things is more specialized.  */
14605   if (arg == parm && !uses_template_parms (parm))
14606     return 0;
14607
14608   /* Handle init lists early, so the rest of the function can assume
14609      we're dealing with a type. */
14610   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14611     {
14612       tree elt, elttype;
14613       unsigned i;
14614       tree orig_parm = parm;
14615
14616       /* Replace T with std::initializer_list<T> for deduction.  */
14617       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14618           && flag_deduce_init_list)
14619         parm = listify (parm);
14620
14621       if (!is_std_init_list (parm))
14622         /* We can only deduce from an initializer list argument if the
14623            parameter is std::initializer_list; otherwise this is a
14624            non-deduced context. */
14625         return 0;
14626
14627       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14628
14629       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14630         {
14631           int elt_strict = strict;
14632
14633           if (elt == error_mark_node)
14634             return 1;
14635
14636           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14637             {
14638               tree type = TREE_TYPE (elt);
14639               /* It should only be possible to get here for a call.  */
14640               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14641               elt_strict |= maybe_adjust_types_for_deduction
14642                 (DEDUCE_CALL, &elttype, &type, elt);
14643               elt = type;
14644             }
14645
14646           if (unify (tparms, targs, elttype, elt, elt_strict))
14647             return 1;
14648         }
14649
14650       /* If the std::initializer_list<T> deduction worked, replace the
14651          deduced A with std::initializer_list<A>.  */
14652       if (orig_parm != parm)
14653         {
14654           idx = TEMPLATE_TYPE_IDX (orig_parm);
14655           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14656           targ = listify (targ);
14657           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14658         }
14659       return 0;
14660     }
14661
14662   /* Immediately reject some pairs that won't unify because of
14663      cv-qualification mismatches.  */
14664   if (TREE_CODE (arg) == TREE_CODE (parm)
14665       && TYPE_P (arg)
14666       /* It is the elements of the array which hold the cv quals of an array
14667          type, and the elements might be template type parms. We'll check
14668          when we recurse.  */
14669       && TREE_CODE (arg) != ARRAY_TYPE
14670       /* We check the cv-qualifiers when unifying with template type
14671          parameters below.  We want to allow ARG `const T' to unify with
14672          PARM `T' for example, when computing which of two templates
14673          is more specialized, for example.  */
14674       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14675       && !check_cv_quals_for_unify (strict_in, arg, parm))
14676     return 1;
14677
14678   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14679       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14680     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14681   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14682   strict &= ~UNIFY_ALLOW_DERIVED;
14683   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14684   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14685
14686   switch (TREE_CODE (parm))
14687     {
14688     case TYPENAME_TYPE:
14689     case SCOPE_REF:
14690     case UNBOUND_CLASS_TEMPLATE:
14691       /* In a type which contains a nested-name-specifier, template
14692          argument values cannot be deduced for template parameters used
14693          within the nested-name-specifier.  */
14694       return 0;
14695
14696     case TEMPLATE_TYPE_PARM:
14697     case TEMPLATE_TEMPLATE_PARM:
14698     case BOUND_TEMPLATE_TEMPLATE_PARM:
14699       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14700       if (tparm == error_mark_node)
14701         return 1;
14702
14703       if (TEMPLATE_TYPE_LEVEL (parm)
14704           != template_decl_level (tparm))
14705         /* The PARM is not one we're trying to unify.  Just check
14706            to see if it matches ARG.  */
14707         return (TREE_CODE (arg) == TREE_CODE (parm)
14708                 && same_type_p (parm, arg)) ? 0 : 1;
14709       idx = TEMPLATE_TYPE_IDX (parm);
14710       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14711       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14712
14713       /* Check for mixed types and values.  */
14714       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14715            && TREE_CODE (tparm) != TYPE_DECL)
14716           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14717               && TREE_CODE (tparm) != TEMPLATE_DECL))
14718         return 1;
14719
14720       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14721         {
14722           /* ARG must be constructed from a template class or a template
14723              template parameter.  */
14724           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14725               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14726             return 1;
14727
14728           {
14729             tree parmvec = TYPE_TI_ARGS (parm);
14730             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14731             tree parm_parms 
14732               = DECL_INNERMOST_TEMPLATE_PARMS
14733                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14734             int i, len;
14735             int parm_variadic_p = 0;
14736
14737             /* The resolution to DR150 makes clear that default
14738                arguments for an N-argument may not be used to bind T
14739                to a template template parameter with fewer than N
14740                parameters.  It is not safe to permit the binding of
14741                default arguments as an extension, as that may change
14742                the meaning of a conforming program.  Consider:
14743
14744                   struct Dense { static const unsigned int dim = 1; };
14745
14746                   template <template <typename> class View,
14747                             typename Block>
14748                   void operator+(float, View<Block> const&);
14749
14750                   template <typename Block,
14751                             unsigned int Dim = Block::dim>
14752                   struct Lvalue_proxy { operator float() const; };
14753
14754                   void
14755                   test_1d (void) {
14756                     Lvalue_proxy<Dense> p;
14757                     float b;
14758                     b + p;
14759                   }
14760
14761               Here, if Lvalue_proxy is permitted to bind to View, then
14762               the global operator+ will be used; if they are not, the
14763               Lvalue_proxy will be converted to float.  */
14764             if (coerce_template_parms (parm_parms,
14765                                        argvec,
14766                                        TYPE_TI_TEMPLATE (parm),
14767                                        tf_none,
14768                                        /*require_all_args=*/true,
14769                                        /*use_default_args=*/false)
14770                 == error_mark_node)
14771               return 1;
14772
14773             /* Deduce arguments T, i from TT<T> or TT<i>.
14774                We check each element of PARMVEC and ARGVEC individually
14775                rather than the whole TREE_VEC since they can have
14776                different number of elements.  */
14777
14778             parmvec = expand_template_argument_pack (parmvec);
14779             argvec = expand_template_argument_pack (argvec);
14780
14781             len = TREE_VEC_LENGTH (parmvec);
14782
14783             /* Check if the parameters end in a pack, making them
14784                variadic.  */
14785             if (len > 0
14786                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14787               parm_variadic_p = 1;
14788             
14789             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14790               return 1;
14791
14792              for (i = 0; i < len - parm_variadic_p; ++i)
14793               {
14794                 if (unify (tparms, targs,
14795                            TREE_VEC_ELT (parmvec, i),
14796                            TREE_VEC_ELT (argvec, i),
14797                            UNIFY_ALLOW_NONE))
14798                   return 1;
14799               }
14800
14801             if (parm_variadic_p
14802                 && unify_pack_expansion (tparms, targs,
14803                                          parmvec, argvec,
14804                                          UNIFY_ALLOW_NONE,
14805                                          /*call_args_p=*/false,
14806                                          /*subr=*/false))
14807               return 1;
14808           }
14809           arg = TYPE_TI_TEMPLATE (arg);
14810
14811           /* Fall through to deduce template name.  */
14812         }
14813
14814       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14815           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14816         {
14817           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14818
14819           /* Simple cases: Value already set, does match or doesn't.  */
14820           if (targ != NULL_TREE && template_args_equal (targ, arg))
14821             return 0;
14822           else if (targ)
14823             return 1;
14824         }
14825       else
14826         {
14827           /* If PARM is `const T' and ARG is only `int', we don't have
14828              a match unless we are allowing additional qualification.
14829              If ARG is `const int' and PARM is just `T' that's OK;
14830              that binds `const int' to `T'.  */
14831           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14832                                          arg, parm))
14833             return 1;
14834
14835           /* Consider the case where ARG is `const volatile int' and
14836              PARM is `const T'.  Then, T should be `volatile int'.  */
14837           arg = cp_build_qualified_type_real
14838             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14839           if (arg == error_mark_node)
14840             return 1;
14841
14842           /* Simple cases: Value already set, does match or doesn't.  */
14843           if (targ != NULL_TREE && same_type_p (targ, arg))
14844             return 0;
14845           else if (targ)
14846             return 1;
14847
14848           /* Make sure that ARG is not a variable-sized array.  (Note
14849              that were talking about variable-sized arrays (like
14850              `int[n]'), rather than arrays of unknown size (like
14851              `int[]').)  We'll get very confused by such a type since
14852              the bound of the array will not be computable in an
14853              instantiation.  Besides, such types are not allowed in
14854              ISO C++, so we can do as we please here.  */
14855           if (variably_modified_type_p (arg, NULL_TREE))
14856             return 1;
14857
14858           /* Strip typedefs as in convert_template_argument.  */
14859           arg = strip_typedefs (arg);
14860         }
14861
14862       /* If ARG is a parameter pack or an expansion, we cannot unify
14863          against it unless PARM is also a parameter pack.  */
14864       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14865           && !template_parameter_pack_p (parm))
14866         return 1;
14867
14868       /* If the argument deduction results is a METHOD_TYPE,
14869          then there is a problem.
14870          METHOD_TYPE doesn't map to any real C++ type the result of
14871          the deduction can not be of that type.  */
14872       if (TREE_CODE (arg) == METHOD_TYPE)
14873         return 1;
14874
14875       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14876       return 0;
14877
14878     case TEMPLATE_PARM_INDEX:
14879       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14880       if (tparm == error_mark_node)
14881         return 1;
14882
14883       if (TEMPLATE_PARM_LEVEL (parm)
14884           != template_decl_level (tparm))
14885         /* The PARM is not one we're trying to unify.  Just check
14886            to see if it matches ARG.  */
14887         return !(TREE_CODE (arg) == TREE_CODE (parm)
14888                  && cp_tree_equal (parm, arg));
14889
14890       idx = TEMPLATE_PARM_IDX (parm);
14891       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14892
14893       if (targ)
14894         return !cp_tree_equal (targ, arg);
14895
14896       /* [temp.deduct.type] If, in the declaration of a function template
14897          with a non-type template-parameter, the non-type
14898          template-parameter is used in an expression in the function
14899          parameter-list and, if the corresponding template-argument is
14900          deduced, the template-argument type shall match the type of the
14901          template-parameter exactly, except that a template-argument
14902          deduced from an array bound may be of any integral type.
14903          The non-type parameter might use already deduced type parameters.  */
14904       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14905       if (!TREE_TYPE (arg))
14906         /* Template-parameter dependent expression.  Just accept it for now.
14907            It will later be processed in convert_template_argument.  */
14908         ;
14909       else if (same_type_p (TREE_TYPE (arg), tparm))
14910         /* OK */;
14911       else if ((strict & UNIFY_ALLOW_INTEGER)
14912                && (TREE_CODE (tparm) == INTEGER_TYPE
14913                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
14914         /* Convert the ARG to the type of PARM; the deduced non-type
14915            template argument must exactly match the types of the
14916            corresponding parameter.  */
14917         arg = fold (build_nop (tparm, arg));
14918       else if (uses_template_parms (tparm))
14919         /* We haven't deduced the type of this parameter yet.  Try again
14920            later.  */
14921         return 0;
14922       else
14923         return 1;
14924
14925       /* If ARG is a parameter pack or an expansion, we cannot unify
14926          against it unless PARM is also a parameter pack.  */
14927       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14928           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14929         return 1;
14930
14931       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14932       return 0;
14933
14934     case PTRMEM_CST:
14935      {
14936         /* A pointer-to-member constant can be unified only with
14937          another constant.  */
14938       if (TREE_CODE (arg) != PTRMEM_CST)
14939         return 1;
14940
14941       /* Just unify the class member. It would be useless (and possibly
14942          wrong, depending on the strict flags) to unify also
14943          PTRMEM_CST_CLASS, because we want to be sure that both parm and
14944          arg refer to the same variable, even if through different
14945          classes. For instance:
14946
14947          struct A { int x; };
14948          struct B : A { };
14949
14950          Unification of &A::x and &B::x must succeed.  */
14951       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14952                     PTRMEM_CST_MEMBER (arg), strict);
14953      }
14954
14955     case POINTER_TYPE:
14956       {
14957         if (TREE_CODE (arg) != POINTER_TYPE)
14958           return 1;
14959
14960         /* [temp.deduct.call]
14961
14962            A can be another pointer or pointer to member type that can
14963            be converted to the deduced A via a qualification
14964            conversion (_conv.qual_).
14965
14966            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14967            This will allow for additional cv-qualification of the
14968            pointed-to types if appropriate.  */
14969
14970         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14971           /* The derived-to-base conversion only persists through one
14972              level of pointers.  */
14973           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14974
14975         return unify (tparms, targs, TREE_TYPE (parm),
14976                       TREE_TYPE (arg), strict);
14977       }
14978
14979     case REFERENCE_TYPE:
14980       if (TREE_CODE (arg) != REFERENCE_TYPE)
14981         return 1;
14982       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14983                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14984
14985     case ARRAY_TYPE:
14986       if (TREE_CODE (arg) != ARRAY_TYPE)
14987         return 1;
14988       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14989           != (TYPE_DOMAIN (arg) == NULL_TREE))
14990         return 1;
14991       if (TYPE_DOMAIN (parm) != NULL_TREE)
14992         {
14993           tree parm_max;
14994           tree arg_max;
14995           bool parm_cst;
14996           bool arg_cst;
14997
14998           /* Our representation of array types uses "N - 1" as the
14999              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
15000              not an integer constant.  We cannot unify arbitrarily
15001              complex expressions, so we eliminate the MINUS_EXPRs
15002              here.  */
15003           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
15004           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
15005           if (!parm_cst)
15006             {
15007               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
15008               parm_max = TREE_OPERAND (parm_max, 0);
15009             }
15010           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
15011           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
15012           if (!arg_cst)
15013             {
15014               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
15015                  trying to unify the type of a variable with the type
15016                  of a template parameter.  For example:
15017
15018                    template <unsigned int N>
15019                    void f (char (&) [N]);
15020                    int g(); 
15021                    void h(int i) {
15022                      char a[g(i)];
15023                      f(a); 
15024                    }
15025
15026                 Here, the type of the ARG will be "int [g(i)]", and
15027                 may be a SAVE_EXPR, etc.  */
15028               if (TREE_CODE (arg_max) != MINUS_EXPR)
15029                 return 1;
15030               arg_max = TREE_OPERAND (arg_max, 0);
15031             }
15032
15033           /* If only one of the bounds used a MINUS_EXPR, compensate
15034              by adding one to the other bound.  */
15035           if (parm_cst && !arg_cst)
15036             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
15037                                     integer_type_node,
15038                                     parm_max,
15039                                     integer_one_node);
15040           else if (arg_cst && !parm_cst)
15041             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
15042                                    integer_type_node,
15043                                    arg_max,
15044                                    integer_one_node);
15045
15046           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
15047             return 1;
15048         }
15049       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15050                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
15051
15052     case REAL_TYPE:
15053     case COMPLEX_TYPE:
15054     case VECTOR_TYPE:
15055     case INTEGER_TYPE:
15056     case BOOLEAN_TYPE:
15057     case ENUMERAL_TYPE:
15058     case VOID_TYPE:
15059       if (TREE_CODE (arg) != TREE_CODE (parm))
15060         return 1;
15061
15062       /* We have already checked cv-qualification at the top of the
15063          function.  */
15064       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
15065         return 1;
15066
15067       /* As far as unification is concerned, this wins.  Later checks
15068          will invalidate it if necessary.  */
15069       return 0;
15070
15071       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
15072       /* Type INTEGER_CST can come from ordinary constant template args.  */
15073     case INTEGER_CST:
15074       while (TREE_CODE (arg) == NOP_EXPR)
15075         arg = TREE_OPERAND (arg, 0);
15076
15077       if (TREE_CODE (arg) != INTEGER_CST)
15078         return 1;
15079       return !tree_int_cst_equal (parm, arg);
15080
15081     case TREE_VEC:
15082       {
15083         int i;
15084         if (TREE_CODE (arg) != TREE_VEC)
15085           return 1;
15086         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
15087           return 1;
15088         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
15089           if (unify (tparms, targs,
15090                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
15091                      UNIFY_ALLOW_NONE))
15092             return 1;
15093         return 0;
15094       }
15095
15096     case RECORD_TYPE:
15097     case UNION_TYPE:
15098       if (TREE_CODE (arg) != TREE_CODE (parm))
15099         return 1;
15100
15101       if (TYPE_PTRMEMFUNC_P (parm))
15102         {
15103           if (!TYPE_PTRMEMFUNC_P (arg))
15104             return 1;
15105
15106           return unify (tparms, targs,
15107                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
15108                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
15109                         strict);
15110         }
15111
15112       if (CLASSTYPE_TEMPLATE_INFO (parm))
15113         {
15114           tree t = NULL_TREE;
15115
15116           if (strict_in & UNIFY_ALLOW_DERIVED)
15117             {
15118               /* First, we try to unify the PARM and ARG directly.  */
15119               t = try_class_unification (tparms, targs,
15120                                          parm, arg);
15121
15122               if (!t)
15123                 {
15124                   /* Fallback to the special case allowed in
15125                      [temp.deduct.call]:
15126
15127                        If P is a class, and P has the form
15128                        template-id, then A can be a derived class of
15129                        the deduced A.  Likewise, if P is a pointer to
15130                        a class of the form template-id, A can be a
15131                        pointer to a derived class pointed to by the
15132                        deduced A.  */
15133                   t = get_template_base (tparms, targs, parm, arg);
15134
15135                   if (!t)
15136                     return 1;
15137                 }
15138             }
15139           else if (CLASSTYPE_TEMPLATE_INFO (arg)
15140                    && (CLASSTYPE_TI_TEMPLATE (parm)
15141                        == CLASSTYPE_TI_TEMPLATE (arg)))
15142             /* Perhaps PARM is something like S<U> and ARG is S<int>.
15143                Then, we should unify `int' and `U'.  */
15144             t = arg;
15145           else
15146             /* There's no chance of unification succeeding.  */
15147             return 1;
15148
15149           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
15150                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
15151         }
15152       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
15153         return 1;
15154       return 0;
15155
15156     case METHOD_TYPE:
15157     case FUNCTION_TYPE:
15158       {
15159         unsigned int nargs;
15160         tree *args;
15161         tree a;
15162         unsigned int i;
15163
15164         if (TREE_CODE (arg) != TREE_CODE (parm))
15165           return 1;
15166
15167         /* CV qualifications for methods can never be deduced, they must
15168            match exactly.  We need to check them explicitly here,
15169            because type_unification_real treats them as any other
15170            cv-qualified parameter.  */
15171         if (TREE_CODE (parm) == METHOD_TYPE
15172             && (!check_cv_quals_for_unify
15173                 (UNIFY_ALLOW_NONE,
15174                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
15175                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
15176           return 1;
15177
15178         if (unify (tparms, targs, TREE_TYPE (parm),
15179                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
15180           return 1;
15181
15182         nargs = list_length (TYPE_ARG_TYPES (arg));
15183         args = XALLOCAVEC (tree, nargs);
15184         for (a = TYPE_ARG_TYPES (arg), i = 0;
15185              a != NULL_TREE && a != void_list_node;
15186              a = TREE_CHAIN (a), ++i)
15187           args[i] = TREE_VALUE (a);
15188         nargs = i;
15189
15190         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
15191                                       args, nargs, 1, DEDUCE_EXACT,
15192                                       LOOKUP_NORMAL);
15193       }
15194
15195     case OFFSET_TYPE:
15196       /* Unify a pointer to member with a pointer to member function, which
15197          deduces the type of the member as a function type. */
15198       if (TYPE_PTRMEMFUNC_P (arg))
15199         {
15200           tree method_type;
15201           tree fntype;
15202
15203           /* Check top-level cv qualifiers */
15204           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
15205             return 1;
15206
15207           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15208                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
15209             return 1;
15210
15211           /* Determine the type of the function we are unifying against. */
15212           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
15213           fntype =
15214             build_function_type (TREE_TYPE (method_type),
15215                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
15216
15217           /* Extract the cv-qualifiers of the member function from the
15218              implicit object parameter and place them on the function
15219              type to be restored later. */
15220           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
15221           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
15222         }
15223
15224       if (TREE_CODE (arg) != OFFSET_TYPE)
15225         return 1;
15226       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15227                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
15228         return 1;
15229       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15230                     strict);
15231
15232     case CONST_DECL:
15233       if (DECL_TEMPLATE_PARM_P (parm))
15234         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
15235       if (arg != integral_constant_value (parm))
15236         return 1;
15237       return 0;
15238
15239     case FIELD_DECL:
15240     case TEMPLATE_DECL:
15241       /* Matched cases are handled by the ARG == PARM test above.  */
15242       return 1;
15243
15244     case VAR_DECL:
15245       /* A non-type template parameter that is a variable should be a
15246          an integral constant, in which case, it whould have been
15247          folded into its (constant) value. So we should not be getting
15248          a variable here.  */
15249       gcc_unreachable ();
15250
15251     case TYPE_ARGUMENT_PACK:
15252     case NONTYPE_ARGUMENT_PACK:
15253       {
15254         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
15255         tree packed_args = ARGUMENT_PACK_ARGS (arg);
15256         int i, len = TREE_VEC_LENGTH (packed_parms);
15257         int argslen = TREE_VEC_LENGTH (packed_args);
15258         int parm_variadic_p = 0;
15259
15260         for (i = 0; i < len; ++i)
15261           {
15262             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
15263               {
15264                 if (i == len - 1)
15265                   /* We can unify against something with a trailing
15266                      parameter pack.  */
15267                   parm_variadic_p = 1;
15268                 else
15269                   /* Since there is something following the pack
15270                      expansion, we cannot unify this template argument
15271                      list.  */
15272                   return 0;
15273               }
15274           }
15275           
15276
15277         /* If we don't have enough arguments to satisfy the parameters
15278            (not counting the pack expression at the end), or we have
15279            too many arguments for a parameter list that doesn't end in
15280            a pack expression, we can't unify.  */
15281         if (argslen < (len - parm_variadic_p)
15282             || (argslen > len && !parm_variadic_p))
15283           return 1;
15284
15285         /* Unify all of the parameters that precede the (optional)
15286            pack expression.  */
15287         for (i = 0; i < len - parm_variadic_p; ++i)
15288           {
15289             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15290                        TREE_VEC_ELT (packed_args, i), strict))
15291               return 1;
15292           }
15293
15294         if (parm_variadic_p)
15295           return unify_pack_expansion (tparms, targs, 
15296                                        packed_parms, packed_args,
15297                                        strict, /*call_args_p=*/false,
15298                                        /*subr=*/false);
15299         return 0;
15300       }
15301
15302       break;
15303
15304     case TYPEOF_TYPE:
15305     case DECLTYPE_TYPE:
15306       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
15307          nodes.  */
15308       return 0;
15309
15310     case ERROR_MARK:
15311       /* Unification fails if we hit an error node.  */
15312       return 1;
15313
15314     default:
15315       gcc_assert (EXPR_P (parm));
15316
15317       /* We must be looking at an expression.  This can happen with
15318          something like:
15319
15320            template <int I>
15321            void foo(S<I>, S<I + 2>);
15322
15323          This is a "nondeduced context":
15324
15325            [deduct.type]
15326
15327            The nondeduced contexts are:
15328
15329            --A type that is a template-id in which one or more of
15330              the template-arguments is an expression that references
15331              a template-parameter.
15332
15333          In these cases, we assume deduction succeeded, but don't
15334          actually infer any unifications.  */
15335
15336       if (!uses_template_parms (parm)
15337           && !template_args_equal (parm, arg))
15338         return 1;
15339       else
15340         return 0;
15341     }
15342 }
15343 \f
15344 /* Note that DECL can be defined in this translation unit, if
15345    required.  */
15346
15347 static void
15348 mark_definable (tree decl)
15349 {
15350   tree clone;
15351   DECL_NOT_REALLY_EXTERN (decl) = 1;
15352   FOR_EACH_CLONE (clone, decl)
15353     DECL_NOT_REALLY_EXTERN (clone) = 1;
15354 }
15355
15356 /* Called if RESULT is explicitly instantiated, or is a member of an
15357    explicitly instantiated class.  */
15358
15359 void
15360 mark_decl_instantiated (tree result, int extern_p)
15361 {
15362   SET_DECL_EXPLICIT_INSTANTIATION (result);
15363
15364   /* If this entity has already been written out, it's too late to
15365      make any modifications.  */
15366   if (TREE_ASM_WRITTEN (result))
15367     return;
15368
15369   if (TREE_CODE (result) != FUNCTION_DECL)
15370     /* The TREE_PUBLIC flag for function declarations will have been
15371        set correctly by tsubst.  */
15372     TREE_PUBLIC (result) = 1;
15373
15374   /* This might have been set by an earlier implicit instantiation.  */
15375   DECL_COMDAT (result) = 0;
15376
15377   if (extern_p)
15378     DECL_NOT_REALLY_EXTERN (result) = 0;
15379   else
15380     {
15381       mark_definable (result);
15382       /* Always make artificials weak.  */
15383       if (DECL_ARTIFICIAL (result) && flag_weak)
15384         comdat_linkage (result);
15385       /* For WIN32 we also want to put explicit instantiations in
15386          linkonce sections.  */
15387       else if (TREE_PUBLIC (result))
15388         maybe_make_one_only (result);
15389     }
15390
15391   /* If EXTERN_P, then this function will not be emitted -- unless
15392      followed by an explicit instantiation, at which point its linkage
15393      will be adjusted.  If !EXTERN_P, then this function will be
15394      emitted here.  In neither circumstance do we want
15395      import_export_decl to adjust the linkage.  */
15396   DECL_INTERFACE_KNOWN (result) = 1;
15397 }
15398
15399 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
15400    important template arguments.  If any are missing, we check whether
15401    they're important by using error_mark_node for substituting into any
15402    args that were used for partial ordering (the ones between ARGS and END)
15403    and seeing if it bubbles up.  */
15404
15405 static bool
15406 check_undeduced_parms (tree targs, tree args, tree end)
15407 {
15408   bool found = false;
15409   int i;
15410   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
15411     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
15412       {
15413         found = true;
15414         TREE_VEC_ELT (targs, i) = error_mark_node;
15415       }
15416   if (found)
15417     {
15418       for (; args != end; args = TREE_CHAIN (args))
15419         {
15420           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
15421           if (substed == error_mark_node)
15422             return true;
15423         }
15424     }
15425   return false;
15426 }
15427
15428 /* Given two function templates PAT1 and PAT2, return:
15429
15430    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
15431    -1 if PAT2 is more specialized than PAT1.
15432    0 if neither is more specialized.
15433
15434    LEN indicates the number of parameters we should consider
15435    (defaulted parameters should not be considered).
15436
15437    The 1998 std underspecified function template partial ordering, and
15438    DR214 addresses the issue.  We take pairs of arguments, one from
15439    each of the templates, and deduce them against each other.  One of
15440    the templates will be more specialized if all the *other*
15441    template's arguments deduce against its arguments and at least one
15442    of its arguments *does* *not* deduce against the other template's
15443    corresponding argument.  Deduction is done as for class templates.
15444    The arguments used in deduction have reference and top level cv
15445    qualifiers removed.  Iff both arguments were originally reference
15446    types *and* deduction succeeds in both directions, the template
15447    with the more cv-qualified argument wins for that pairing (if
15448    neither is more cv-qualified, they both are equal).  Unlike regular
15449    deduction, after all the arguments have been deduced in this way,
15450    we do *not* verify the deduced template argument values can be
15451    substituted into non-deduced contexts.
15452
15453    The logic can be a bit confusing here, because we look at deduce1 and
15454    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15455    can find template arguments for pat1 to make arg1 look like arg2, that
15456    means that arg2 is at least as specialized as arg1.  */
15457
15458 int
15459 more_specialized_fn (tree pat1, tree pat2, int len)
15460 {
15461   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15462   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15463   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15464   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15465   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15466   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15467   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15468   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15469   tree origs1, origs2;
15470   bool lose1 = false;
15471   bool lose2 = false;
15472
15473   /* Remove the this parameter from non-static member functions.  If
15474      one is a non-static member function and the other is not a static
15475      member function, remove the first parameter from that function
15476      also.  This situation occurs for operator functions where we
15477      locate both a member function (with this pointer) and non-member
15478      operator (with explicit first operand).  */
15479   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15480     {
15481       len--; /* LEN is the number of significant arguments for DECL1 */
15482       args1 = TREE_CHAIN (args1);
15483       if (!DECL_STATIC_FUNCTION_P (decl2))
15484         args2 = TREE_CHAIN (args2);
15485     }
15486   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15487     {
15488       args2 = TREE_CHAIN (args2);
15489       if (!DECL_STATIC_FUNCTION_P (decl1))
15490         {
15491           len--;
15492           args1 = TREE_CHAIN (args1);
15493         }
15494     }
15495
15496   /* If only one is a conversion operator, they are unordered.  */
15497   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15498     return 0;
15499
15500   /* Consider the return type for a conversion function */
15501   if (DECL_CONV_FN_P (decl1))
15502     {
15503       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15504       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15505       len++;
15506     }
15507
15508   processing_template_decl++;
15509
15510   origs1 = args1;
15511   origs2 = args2;
15512
15513   while (len--
15514          /* Stop when an ellipsis is seen.  */
15515          && args1 != NULL_TREE && args2 != NULL_TREE)
15516     {
15517       tree arg1 = TREE_VALUE (args1);
15518       tree arg2 = TREE_VALUE (args2);
15519       int deduce1, deduce2;
15520       int quals1 = -1;
15521       int quals2 = -1;
15522
15523       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15524           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15525         {
15526           /* When both arguments are pack expansions, we need only
15527              unify the patterns themselves.  */
15528           arg1 = PACK_EXPANSION_PATTERN (arg1);
15529           arg2 = PACK_EXPANSION_PATTERN (arg2);
15530
15531           /* This is the last comparison we need to do.  */
15532           len = 0;
15533         }
15534
15535       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15536         {
15537           arg1 = TREE_TYPE (arg1);
15538           quals1 = cp_type_quals (arg1);
15539         }
15540
15541       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15542         {
15543           arg2 = TREE_TYPE (arg2);
15544           quals2 = cp_type_quals (arg2);
15545         }
15546
15547       if ((quals1 < 0) != (quals2 < 0))
15548         {
15549           /* Only of the args is a reference, see if we should apply
15550              array/function pointer decay to it.  This is not part of
15551              DR214, but is, IMHO, consistent with the deduction rules
15552              for the function call itself, and with our earlier
15553              implementation of the underspecified partial ordering
15554              rules.  (nathan).  */
15555           if (quals1 >= 0)
15556             {
15557               switch (TREE_CODE (arg1))
15558                 {
15559                 case ARRAY_TYPE:
15560                   arg1 = TREE_TYPE (arg1);
15561                   /* FALLTHROUGH. */
15562                 case FUNCTION_TYPE:
15563                   arg1 = build_pointer_type (arg1);
15564                   break;
15565
15566                 default:
15567                   break;
15568                 }
15569             }
15570           else
15571             {
15572               switch (TREE_CODE (arg2))
15573                 {
15574                 case ARRAY_TYPE:
15575                   arg2 = TREE_TYPE (arg2);
15576                   /* FALLTHROUGH. */
15577                 case FUNCTION_TYPE:
15578                   arg2 = build_pointer_type (arg2);
15579                   break;
15580
15581                 default:
15582                   break;
15583                 }
15584             }
15585         }
15586
15587       arg1 = TYPE_MAIN_VARIANT (arg1);
15588       arg2 = TYPE_MAIN_VARIANT (arg2);
15589
15590       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15591         {
15592           int i, len2 = list_length (args2);
15593           tree parmvec = make_tree_vec (1);
15594           tree argvec = make_tree_vec (len2);
15595           tree ta = args2;
15596
15597           /* Setup the parameter vector, which contains only ARG1.  */
15598           TREE_VEC_ELT (parmvec, 0) = arg1;
15599
15600           /* Setup the argument vector, which contains the remaining
15601              arguments.  */
15602           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15603             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15604
15605           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15606                                            argvec, UNIFY_ALLOW_NONE, 
15607                                            /*call_args_p=*/false, 
15608                                            /*subr=*/0);
15609
15610           /* We cannot deduce in the other direction, because ARG1 is
15611              a pack expansion but ARG2 is not.  */
15612           deduce2 = 0;
15613         }
15614       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15615         {
15616           int i, len1 = list_length (args1);
15617           tree parmvec = make_tree_vec (1);
15618           tree argvec = make_tree_vec (len1);
15619           tree ta = args1;
15620
15621           /* Setup the parameter vector, which contains only ARG1.  */
15622           TREE_VEC_ELT (parmvec, 0) = arg2;
15623
15624           /* Setup the argument vector, which contains the remaining
15625              arguments.  */
15626           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15627             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15628
15629           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15630                                            argvec, UNIFY_ALLOW_NONE, 
15631                                            /*call_args_p=*/false, 
15632                                            /*subr=*/0);
15633
15634           /* We cannot deduce in the other direction, because ARG2 is
15635              a pack expansion but ARG1 is not.*/
15636           deduce1 = 0;
15637         }
15638
15639       else
15640         {
15641           /* The normal case, where neither argument is a pack
15642              expansion.  */
15643           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15644           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15645         }
15646
15647       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15648          arg2, then arg2 is not as specialized as arg1.  */
15649       if (!deduce1)
15650         lose2 = true;
15651       if (!deduce2)
15652         lose1 = true;
15653
15654       /* "If, for a given type, deduction succeeds in both directions
15655          (i.e., the types are identical after the transformations above)
15656          and if the type from the argument template is more cv-qualified
15657          than the type from the parameter template (as described above)
15658          that type is considered to be more specialized than the other. If
15659          neither type is more cv-qualified than the other then neither type
15660          is more specialized than the other."  */
15661
15662       if (deduce1 && deduce2
15663           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
15664         {
15665           if ((quals1 & quals2) == quals2)
15666             lose2 = true;
15667           if ((quals1 & quals2) == quals1)
15668             lose1 = true;
15669         }
15670
15671       if (lose1 && lose2)
15672         /* We've failed to deduce something in either direction.
15673            These must be unordered.  */
15674         break;
15675
15676       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15677           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15678         /* We have already processed all of the arguments in our
15679            handing of the pack expansion type.  */
15680         len = 0;
15681
15682       args1 = TREE_CHAIN (args1);
15683       args2 = TREE_CHAIN (args2);
15684     }
15685
15686   /* "In most cases, all template parameters must have values in order for
15687      deduction to succeed, but for partial ordering purposes a template
15688      parameter may remain without a value provided it is not used in the
15689      types being used for partial ordering."
15690
15691      Thus, if we are missing any of the targs1 we need to substitute into
15692      origs1, then pat2 is not as specialized as pat1.  This can happen when
15693      there is a nondeduced context.  */
15694   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15695     lose2 = true;
15696   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15697     lose1 = true;
15698
15699   processing_template_decl--;
15700
15701   /* All things being equal, if the next argument is a pack expansion
15702      for one function but not for the other, prefer the
15703      non-variadic function.  FIXME this is bogus; see c++/41958.  */
15704   if (lose1 == lose2
15705       && args1 && TREE_VALUE (args1)
15706       && args2 && TREE_VALUE (args2))
15707     {
15708       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15709       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15710     }
15711
15712   if (lose1 == lose2)
15713     return 0;
15714   else if (!lose1)
15715     return 1;
15716   else
15717     return -1;
15718 }
15719
15720 /* Determine which of two partial specializations is more specialized.
15721
15722    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15723    to the first partial specialization.  The TREE_VALUE is the
15724    innermost set of template parameters for the partial
15725    specialization.  PAT2 is similar, but for the second template.
15726
15727    Return 1 if the first partial specialization is more specialized;
15728    -1 if the second is more specialized; 0 if neither is more
15729    specialized.
15730
15731    See [temp.class.order] for information about determining which of
15732    two templates is more specialized.  */
15733
15734 static int
15735 more_specialized_class (tree pat1, tree pat2)
15736 {
15737   tree targs;
15738   tree tmpl1, tmpl2;
15739   int winner = 0;
15740   bool any_deductions = false;
15741
15742   tmpl1 = TREE_TYPE (pat1);
15743   tmpl2 = TREE_TYPE (pat2);
15744
15745   /* Just like what happens for functions, if we are ordering between
15746      different class template specializations, we may encounter dependent
15747      types in the arguments, and we need our dependency check functions
15748      to behave correctly.  */
15749   ++processing_template_decl;
15750   targs = get_class_bindings (TREE_VALUE (pat1),
15751                               CLASSTYPE_TI_ARGS (tmpl1),
15752                               CLASSTYPE_TI_ARGS (tmpl2));
15753   if (targs)
15754     {
15755       --winner;
15756       any_deductions = true;
15757     }
15758
15759   targs = get_class_bindings (TREE_VALUE (pat2),
15760                               CLASSTYPE_TI_ARGS (tmpl2),
15761                               CLASSTYPE_TI_ARGS (tmpl1));
15762   if (targs)
15763     {
15764       ++winner;
15765       any_deductions = true;
15766     }
15767   --processing_template_decl;
15768
15769   /* In the case of a tie where at least one of the class templates
15770      has a parameter pack at the end, the template with the most
15771      non-packed parameters wins.  */
15772   if (winner == 0
15773       && any_deductions
15774       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15775           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15776     {
15777       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15778       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15779       int len1 = TREE_VEC_LENGTH (args1);
15780       int len2 = TREE_VEC_LENGTH (args2);
15781
15782       /* We don't count the pack expansion at the end.  */
15783       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15784         --len1;
15785       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15786         --len2;
15787
15788       if (len1 > len2)
15789         return 1;
15790       else if (len1 < len2)
15791         return -1;
15792     }
15793
15794   return winner;
15795 }
15796
15797 /* Return the template arguments that will produce the function signature
15798    DECL from the function template FN, with the explicit template
15799    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15800    also match.  Return NULL_TREE if no satisfactory arguments could be
15801    found.  */
15802
15803 static tree
15804 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15805 {
15806   int ntparms = DECL_NTPARMS (fn);
15807   tree targs = make_tree_vec (ntparms);
15808   tree decl_type;
15809   tree decl_arg_types;
15810   tree *args;
15811   unsigned int nargs, ix;
15812   tree arg;
15813
15814   /* Substitute the explicit template arguments into the type of DECL.
15815      The call to fn_type_unification will handle substitution into the
15816      FN.  */
15817   decl_type = TREE_TYPE (decl);
15818   if (explicit_args && uses_template_parms (decl_type))
15819     {
15820       tree tmpl;
15821       tree converted_args;
15822
15823       if (DECL_TEMPLATE_INFO (decl))
15824         tmpl = DECL_TI_TEMPLATE (decl);
15825       else
15826         /* We can get here for some invalid specializations.  */
15827         return NULL_TREE;
15828
15829       converted_args
15830         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15831                                  explicit_args, NULL_TREE,
15832                                  tf_none,
15833                                  /*require_all_args=*/false,
15834                                  /*use_default_args=*/false);
15835       if (converted_args == error_mark_node)
15836         return NULL_TREE;
15837
15838       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15839       if (decl_type == error_mark_node)
15840         return NULL_TREE;
15841     }
15842
15843   /* Never do unification on the 'this' parameter.  */
15844   decl_arg_types = skip_artificial_parms_for (decl, 
15845                                               TYPE_ARG_TYPES (decl_type));
15846
15847   nargs = list_length (decl_arg_types);
15848   args = XALLOCAVEC (tree, nargs);
15849   for (arg = decl_arg_types, ix = 0;
15850        arg != NULL_TREE && arg != void_list_node;
15851        arg = TREE_CHAIN (arg), ++ix)
15852     args[ix] = TREE_VALUE (arg);
15853
15854   if (fn_type_unification (fn, explicit_args, targs,
15855                            args, ix,
15856                            (check_rettype || DECL_CONV_FN_P (fn)
15857                             ? TREE_TYPE (decl_type) : NULL_TREE),
15858                            DEDUCE_EXACT, LOOKUP_NORMAL))
15859     return NULL_TREE;
15860
15861   return targs;
15862 }
15863
15864 /* Return the innermost template arguments that, when applied to a
15865    template specialization whose innermost template parameters are
15866    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15867    ARGS.
15868
15869    For example, suppose we have:
15870
15871      template <class T, class U> struct S {};
15872      template <class T> struct S<T*, int> {};
15873
15874    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15875    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15876    int}.  The resulting vector will be {double}, indicating that `T'
15877    is bound to `double'.  */
15878
15879 static tree
15880 get_class_bindings (tree tparms, tree spec_args, tree args)
15881 {
15882   int i, ntparms = TREE_VEC_LENGTH (tparms);
15883   tree deduced_args;
15884   tree innermost_deduced_args;
15885
15886   innermost_deduced_args = make_tree_vec (ntparms);
15887   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15888     {
15889       deduced_args = copy_node (args);
15890       SET_TMPL_ARGS_LEVEL (deduced_args,
15891                            TMPL_ARGS_DEPTH (deduced_args),
15892                            innermost_deduced_args);
15893     }
15894   else
15895     deduced_args = innermost_deduced_args;
15896
15897   if (unify (tparms, deduced_args,
15898              INNERMOST_TEMPLATE_ARGS (spec_args),
15899              INNERMOST_TEMPLATE_ARGS (args),
15900              UNIFY_ALLOW_NONE))
15901     return NULL_TREE;
15902
15903   for (i =  0; i < ntparms; ++i)
15904     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15905       return NULL_TREE;
15906
15907   /* Verify that nondeduced template arguments agree with the type
15908      obtained from argument deduction.
15909
15910      For example:
15911
15912        struct A { typedef int X; };
15913        template <class T, class U> struct C {};
15914        template <class T> struct C<T, typename T::X> {};
15915
15916      Then with the instantiation `C<A, int>', we can deduce that
15917      `T' is `A' but unify () does not check whether `typename T::X'
15918      is `int'.  */
15919   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15920   if (spec_args == error_mark_node
15921       /* We only need to check the innermost arguments; the other
15922          arguments will always agree.  */
15923       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15924                               INNERMOST_TEMPLATE_ARGS (args)))
15925     return NULL_TREE;
15926
15927   /* Now that we have bindings for all of the template arguments,
15928      ensure that the arguments deduced for the template template
15929      parameters have compatible template parameter lists.  See the use
15930      of template_template_parm_bindings_ok_p in fn_type_unification
15931      for more information.  */
15932   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15933     return NULL_TREE;
15934
15935   return deduced_args;
15936 }
15937
15938 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15939    Return the TREE_LIST node with the most specialized template, if
15940    any.  If there is no most specialized template, the error_mark_node
15941    is returned.
15942
15943    Note that this function does not look at, or modify, the
15944    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15945    returned is one of the elements of INSTANTIATIONS, callers may
15946    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15947    and retrieve it from the value returned.  */
15948
15949 tree
15950 most_specialized_instantiation (tree templates)
15951 {
15952   tree fn, champ;
15953
15954   ++processing_template_decl;
15955
15956   champ = templates;
15957   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15958     {
15959       int fate = 0;
15960
15961       if (get_bindings (TREE_VALUE (champ),
15962                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15963                         NULL_TREE, /*check_ret=*/false))
15964         fate--;
15965
15966       if (get_bindings (TREE_VALUE (fn),
15967                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15968                         NULL_TREE, /*check_ret=*/false))
15969         fate++;
15970
15971       if (fate == -1)
15972         champ = fn;
15973       else if (!fate)
15974         {
15975           /* Equally specialized, move to next function.  If there
15976              is no next function, nothing's most specialized.  */
15977           fn = TREE_CHAIN (fn);
15978           champ = fn;
15979           if (!fn)
15980             break;
15981         }
15982     }
15983
15984   if (champ)
15985     /* Now verify that champ is better than everything earlier in the
15986        instantiation list.  */
15987     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15988       if (get_bindings (TREE_VALUE (champ),
15989                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15990                         NULL_TREE, /*check_ret=*/false)
15991           || !get_bindings (TREE_VALUE (fn),
15992                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15993                             NULL_TREE, /*check_ret=*/false))
15994         {
15995           champ = NULL_TREE;
15996           break;
15997         }
15998
15999   processing_template_decl--;
16000
16001   if (!champ)
16002     return error_mark_node;
16003
16004   return champ;
16005 }
16006
16007 /* If DECL is a specialization of some template, return the most
16008    general such template.  Otherwise, returns NULL_TREE.
16009
16010    For example, given:
16011
16012      template <class T> struct S { template <class U> void f(U); };
16013
16014    if TMPL is `template <class U> void S<int>::f(U)' this will return
16015    the full template.  This function will not trace past partial
16016    specializations, however.  For example, given in addition:
16017
16018      template <class T> struct S<T*> { template <class U> void f(U); };
16019
16020    if TMPL is `template <class U> void S<int*>::f(U)' this will return
16021    `template <class T> template <class U> S<T*>::f(U)'.  */
16022
16023 tree
16024 most_general_template (tree decl)
16025 {
16026   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
16027      an immediate specialization.  */
16028   if (TREE_CODE (decl) == FUNCTION_DECL)
16029     {
16030       if (DECL_TEMPLATE_INFO (decl)) {
16031         decl = DECL_TI_TEMPLATE (decl);
16032
16033         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
16034            template friend.  */
16035         if (TREE_CODE (decl) != TEMPLATE_DECL)
16036           return NULL_TREE;
16037       } else
16038         return NULL_TREE;
16039     }
16040
16041   /* Look for more and more general templates.  */
16042   while (DECL_TEMPLATE_INFO (decl))
16043     {
16044       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
16045          (See cp-tree.h for details.)  */
16046       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
16047         break;
16048
16049       if (CLASS_TYPE_P (TREE_TYPE (decl))
16050           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
16051         break;
16052
16053       /* Stop if we run into an explicitly specialized class template.  */
16054       if (!DECL_NAMESPACE_SCOPE_P (decl)
16055           && DECL_CONTEXT (decl)
16056           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
16057         break;
16058
16059       decl = DECL_TI_TEMPLATE (decl);
16060     }
16061
16062   return decl;
16063 }
16064
16065 /* Return the most specialized of the class template partial
16066    specializations of TMPL which can produce TYPE, a specialization of
16067    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
16068    a _TYPE node corresponding to the partial specialization, while the
16069    TREE_PURPOSE is the set of template arguments that must be
16070    substituted into the TREE_TYPE in order to generate TYPE.
16071
16072    If the choice of partial specialization is ambiguous, a diagnostic
16073    is issued, and the error_mark_node is returned.  If there are no
16074    partial specializations of TMPL matching TYPE, then NULL_TREE is
16075    returned.  */
16076
16077 static tree
16078 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
16079 {
16080   tree list = NULL_TREE;
16081   tree t;
16082   tree champ;
16083   int fate;
16084   bool ambiguous_p;
16085   tree args;
16086   tree outer_args = NULL_TREE;
16087
16088   tmpl = most_general_template (tmpl);
16089   args = CLASSTYPE_TI_ARGS (type);
16090
16091   /* For determining which partial specialization to use, only the
16092      innermost args are interesting.  */
16093   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
16094     {
16095       outer_args = strip_innermost_template_args (args, 1);
16096       args = INNERMOST_TEMPLATE_ARGS (args);
16097     }
16098
16099   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
16100     {
16101       tree partial_spec_args;
16102       tree spec_args;
16103       tree parms = TREE_VALUE (t);
16104
16105       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
16106
16107       ++processing_template_decl;
16108
16109       if (outer_args)
16110         {
16111           int i;
16112
16113           /* Discard the outer levels of args, and then substitute in the
16114              template args from the enclosing class.  */
16115           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
16116           partial_spec_args = tsubst_template_args
16117             (partial_spec_args, outer_args, tf_none, NULL_TREE);
16118
16119           /* PARMS already refers to just the innermost parms, but the
16120              template parms in partial_spec_args had their levels lowered
16121              by tsubst, so we need to do the same for the parm list.  We
16122              can't just tsubst the TREE_VEC itself, as tsubst wants to
16123              treat a TREE_VEC as an argument vector.  */
16124           parms = copy_node (parms);
16125           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
16126             TREE_VEC_ELT (parms, i) =
16127               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
16128
16129         }
16130
16131       partial_spec_args =
16132           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16133                                  add_to_template_args (outer_args,
16134                                                        partial_spec_args),
16135                                  tmpl, tf_none,
16136                                  /*require_all_args=*/true,
16137                                  /*use_default_args=*/true);
16138
16139       --processing_template_decl;
16140
16141       if (partial_spec_args == error_mark_node)
16142         return error_mark_node;
16143
16144       spec_args = get_class_bindings (parms,
16145                                       partial_spec_args,
16146                                       args);
16147       if (spec_args)
16148         {
16149           if (outer_args)
16150             spec_args = add_to_template_args (outer_args, spec_args);
16151           list = tree_cons (spec_args, TREE_VALUE (t), list);
16152           TREE_TYPE (list) = TREE_TYPE (t);
16153         }
16154     }
16155
16156   if (! list)
16157     return NULL_TREE;
16158
16159   ambiguous_p = false;
16160   t = list;
16161   champ = t;
16162   t = TREE_CHAIN (t);
16163   for (; t; t = TREE_CHAIN (t))
16164     {
16165       fate = more_specialized_class (champ, t);
16166       if (fate == 1)
16167         ;
16168       else
16169         {
16170           if (fate == 0)
16171             {
16172               t = TREE_CHAIN (t);
16173               if (! t)
16174                 {
16175                   ambiguous_p = true;
16176                   break;
16177                 }
16178             }
16179           champ = t;
16180         }
16181     }
16182
16183   if (!ambiguous_p)
16184     for (t = list; t && t != champ; t = TREE_CHAIN (t))
16185       {
16186         fate = more_specialized_class (champ, t);
16187         if (fate != 1)
16188           {
16189             ambiguous_p = true;
16190             break;
16191           }
16192       }
16193
16194   if (ambiguous_p)
16195     {
16196       const char *str;
16197       char *spaces = NULL;
16198       if (!(complain & tf_error))
16199         return error_mark_node;
16200       error ("ambiguous class template instantiation for %q#T", type);
16201       str = TREE_CHAIN (list) ? _("candidates are:") : _("candidate is:");
16202       for (t = list; t; t = TREE_CHAIN (t))
16203         {
16204           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
16205           spaces = spaces ? spaces : get_spaces (str);
16206         }
16207       free (spaces);
16208       return error_mark_node;
16209     }
16210
16211   return champ;
16212 }
16213
16214 /* Explicitly instantiate DECL.  */
16215
16216 void
16217 do_decl_instantiation (tree decl, tree storage)
16218 {
16219   tree result = NULL_TREE;
16220   int extern_p = 0;
16221
16222   if (!decl || decl == error_mark_node)
16223     /* An error occurred, for which grokdeclarator has already issued
16224        an appropriate message.  */
16225     return;
16226   else if (! DECL_LANG_SPECIFIC (decl))
16227     {
16228       error ("explicit instantiation of non-template %q#D", decl);
16229       return;
16230     }
16231   else if (TREE_CODE (decl) == VAR_DECL)
16232     {
16233       /* There is an asymmetry here in the way VAR_DECLs and
16234          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
16235          the latter, the DECL we get back will be marked as a
16236          template instantiation, and the appropriate
16237          DECL_TEMPLATE_INFO will be set up.  This does not happen for
16238          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
16239          should handle VAR_DECLs as it currently handles
16240          FUNCTION_DECLs.  */
16241       if (!DECL_CLASS_SCOPE_P (decl))
16242         {
16243           error ("%qD is not a static data member of a class template", decl);
16244           return;
16245         }
16246       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
16247       if (!result || TREE_CODE (result) != VAR_DECL)
16248         {
16249           error ("no matching template for %qD found", decl);
16250           return;
16251         }
16252       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
16253         {
16254           error ("type %qT for explicit instantiation %qD does not match "
16255                  "declared type %qT", TREE_TYPE (result), decl,
16256                  TREE_TYPE (decl));
16257           return;
16258         }
16259     }
16260   else if (TREE_CODE (decl) != FUNCTION_DECL)
16261     {
16262       error ("explicit instantiation of %q#D", decl);
16263       return;
16264     }
16265   else
16266     result = decl;
16267
16268   /* Check for various error cases.  Note that if the explicit
16269      instantiation is valid the RESULT will currently be marked as an
16270      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
16271      until we get here.  */
16272
16273   if (DECL_TEMPLATE_SPECIALIZATION (result))
16274     {
16275       /* DR 259 [temp.spec].
16276
16277          Both an explicit instantiation and a declaration of an explicit
16278          specialization shall not appear in a program unless the explicit
16279          instantiation follows a declaration of the explicit specialization.
16280
16281          For a given set of template parameters, if an explicit
16282          instantiation of a template appears after a declaration of an
16283          explicit specialization for that template, the explicit
16284          instantiation has no effect.  */
16285       return;
16286     }
16287   else if (DECL_EXPLICIT_INSTANTIATION (result))
16288     {
16289       /* [temp.spec]
16290
16291          No program shall explicitly instantiate any template more
16292          than once.
16293
16294          We check DECL_NOT_REALLY_EXTERN so as not to complain when
16295          the first instantiation was `extern' and the second is not,
16296          and EXTERN_P for the opposite case.  */
16297       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16298         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16299       /* If an "extern" explicit instantiation follows an ordinary
16300          explicit instantiation, the template is instantiated.  */
16301       if (extern_p)
16302         return;
16303     }
16304   else if (!DECL_IMPLICIT_INSTANTIATION (result))
16305     {
16306       error ("no matching template for %qD found", result);
16307       return;
16308     }
16309   else if (!DECL_TEMPLATE_INFO (result))
16310     {
16311       permerror (input_location, "explicit instantiation of non-template %q#D", result);
16312       return;
16313     }
16314
16315   if (storage == NULL_TREE)
16316     ;
16317   else if (storage == ridpointers[(int) RID_EXTERN])
16318     {
16319       if (!in_system_header && (cxx_dialect == cxx98))
16320         pedwarn (input_location, OPT_pedantic, 
16321                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16322                  "instantiations");
16323       extern_p = 1;
16324     }
16325   else
16326     error ("storage class %qD applied to template instantiation", storage);
16327
16328   check_explicit_instantiation_namespace (result);
16329   mark_decl_instantiated (result, extern_p);
16330   if (! extern_p)
16331     instantiate_decl (result, /*defer_ok=*/1,
16332                       /*expl_inst_class_mem_p=*/false);
16333 }
16334
16335 static void
16336 mark_class_instantiated (tree t, int extern_p)
16337 {
16338   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
16339   SET_CLASSTYPE_INTERFACE_KNOWN (t);
16340   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
16341   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
16342   if (! extern_p)
16343     {
16344       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
16345       rest_of_type_compilation (t, 1);
16346     }
16347 }
16348
16349 /* Called from do_type_instantiation through binding_table_foreach to
16350    do recursive instantiation for the type bound in ENTRY.  */
16351 static void
16352 bt_instantiate_type_proc (binding_entry entry, void *data)
16353 {
16354   tree storage = *(tree *) data;
16355
16356   if (MAYBE_CLASS_TYPE_P (entry->type)
16357       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
16358     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
16359 }
16360
16361 /* Called from do_type_instantiation to instantiate a member
16362    (a member function or a static member variable) of an
16363    explicitly instantiated class template.  */
16364 static void
16365 instantiate_class_member (tree decl, int extern_p)
16366 {
16367   mark_decl_instantiated (decl, extern_p);
16368   if (! extern_p)
16369     instantiate_decl (decl, /*defer_ok=*/1,
16370                       /*expl_inst_class_mem_p=*/true);
16371 }
16372
16373 /* Perform an explicit instantiation of template class T.  STORAGE, if
16374    non-null, is the RID for extern, inline or static.  COMPLAIN is
16375    nonzero if this is called from the parser, zero if called recursively,
16376    since the standard is unclear (as detailed below).  */
16377
16378 void
16379 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
16380 {
16381   int extern_p = 0;
16382   int nomem_p = 0;
16383   int static_p = 0;
16384   int previous_instantiation_extern_p = 0;
16385
16386   if (TREE_CODE (t) == TYPE_DECL)
16387     t = TREE_TYPE (t);
16388
16389   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
16390     {
16391       error ("explicit instantiation of non-template type %qT", t);
16392       return;
16393     }
16394
16395   complete_type (t);
16396
16397   if (!COMPLETE_TYPE_P (t))
16398     {
16399       if (complain & tf_error)
16400         error ("explicit instantiation of %q#T before definition of template",
16401                t);
16402       return;
16403     }
16404
16405   if (storage != NULL_TREE)
16406     {
16407       if (!in_system_header)
16408         {
16409           if (storage == ridpointers[(int) RID_EXTERN])
16410             {
16411               if (cxx_dialect == cxx98)
16412                 pedwarn (input_location, OPT_pedantic, 
16413                          "ISO C++ 1998 forbids the use of %<extern%> on "
16414                          "explicit instantiations");
16415             }
16416           else
16417             pedwarn (input_location, OPT_pedantic, 
16418                      "ISO C++ forbids the use of %qE"
16419                      " on explicit instantiations", storage);
16420         }
16421
16422       if (storage == ridpointers[(int) RID_INLINE])
16423         nomem_p = 1;
16424       else if (storage == ridpointers[(int) RID_EXTERN])
16425         extern_p = 1;
16426       else if (storage == ridpointers[(int) RID_STATIC])
16427         static_p = 1;
16428       else
16429         {
16430           error ("storage class %qD applied to template instantiation",
16431                  storage);
16432           extern_p = 0;
16433         }
16434     }
16435
16436   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
16437     {
16438       /* DR 259 [temp.spec].
16439
16440          Both an explicit instantiation and a declaration of an explicit
16441          specialization shall not appear in a program unless the explicit
16442          instantiation follows a declaration of the explicit specialization.
16443
16444          For a given set of template parameters, if an explicit
16445          instantiation of a template appears after a declaration of an
16446          explicit specialization for that template, the explicit
16447          instantiation has no effect.  */
16448       return;
16449     }
16450   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
16451     {
16452       /* [temp.spec]
16453
16454          No program shall explicitly instantiate any template more
16455          than once.
16456
16457          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
16458          instantiation was `extern'.  If EXTERN_P then the second is.
16459          These cases are OK.  */
16460       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
16461
16462       if (!previous_instantiation_extern_p && !extern_p
16463           && (complain & tf_error))
16464         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16465
16466       /* If we've already instantiated the template, just return now.  */
16467       if (!CLASSTYPE_INTERFACE_ONLY (t))
16468         return;
16469     }
16470
16471   check_explicit_instantiation_namespace (TYPE_NAME (t));
16472   mark_class_instantiated (t, extern_p);
16473
16474   if (nomem_p)
16475     return;
16476
16477   {
16478     tree tmp;
16479
16480     /* In contrast to implicit instantiation, where only the
16481        declarations, and not the definitions, of members are
16482        instantiated, we have here:
16483
16484          [temp.explicit]
16485
16486          The explicit instantiation of a class template specialization
16487          implies the instantiation of all of its members not
16488          previously explicitly specialized in the translation unit
16489          containing the explicit instantiation.
16490
16491        Of course, we can't instantiate member template classes, since
16492        we don't have any arguments for them.  Note that the standard
16493        is unclear on whether the instantiation of the members are
16494        *explicit* instantiations or not.  However, the most natural
16495        interpretation is that it should be an explicit instantiation.  */
16496
16497     if (! static_p)
16498       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
16499         if (TREE_CODE (tmp) == FUNCTION_DECL
16500             && DECL_TEMPLATE_INSTANTIATION (tmp))
16501           instantiate_class_member (tmp, extern_p);
16502
16503     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
16504       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16505         instantiate_class_member (tmp, extern_p);
16506
16507     if (CLASSTYPE_NESTED_UTDS (t))
16508       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16509                              bt_instantiate_type_proc, &storage);
16510   }
16511 }
16512
16513 /* Given a function DECL, which is a specialization of TMPL, modify
16514    DECL to be a re-instantiation of TMPL with the same template
16515    arguments.  TMPL should be the template into which tsubst'ing
16516    should occur for DECL, not the most general template.
16517
16518    One reason for doing this is a scenario like this:
16519
16520      template <class T>
16521      void f(const T&, int i);
16522
16523      void g() { f(3, 7); }
16524
16525      template <class T>
16526      void f(const T& t, const int i) { }
16527
16528    Note that when the template is first instantiated, with
16529    instantiate_template, the resulting DECL will have no name for the
16530    first parameter, and the wrong type for the second.  So, when we go
16531    to instantiate the DECL, we regenerate it.  */
16532
16533 static void
16534 regenerate_decl_from_template (tree decl, tree tmpl)
16535 {
16536   /* The arguments used to instantiate DECL, from the most general
16537      template.  */
16538   tree args;
16539   tree code_pattern;
16540
16541   args = DECL_TI_ARGS (decl);
16542   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16543
16544   /* Make sure that we can see identifiers, and compute access
16545      correctly.  */
16546   push_access_scope (decl);
16547
16548   if (TREE_CODE (decl) == FUNCTION_DECL)
16549     {
16550       tree decl_parm;
16551       tree pattern_parm;
16552       tree specs;
16553       int args_depth;
16554       int parms_depth;
16555
16556       args_depth = TMPL_ARGS_DEPTH (args);
16557       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16558       if (args_depth > parms_depth)
16559         args = get_innermost_template_args (args, parms_depth);
16560
16561       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16562                                               args, tf_error, NULL_TREE);
16563       if (specs)
16564         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16565                                                     specs);
16566
16567       /* Merge parameter declarations.  */
16568       decl_parm = skip_artificial_parms_for (decl,
16569                                              DECL_ARGUMENTS (decl));
16570       pattern_parm
16571         = skip_artificial_parms_for (code_pattern,
16572                                      DECL_ARGUMENTS (code_pattern));
16573       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16574         {
16575           tree parm_type;
16576           tree attributes;
16577           
16578           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16579             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16580           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16581                               NULL_TREE);
16582           parm_type = type_decays_to (parm_type);
16583           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16584             TREE_TYPE (decl_parm) = parm_type;
16585           attributes = DECL_ATTRIBUTES (pattern_parm);
16586           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16587             {
16588               DECL_ATTRIBUTES (decl_parm) = attributes;
16589               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16590             }
16591           decl_parm = DECL_CHAIN (decl_parm);
16592           pattern_parm = DECL_CHAIN (pattern_parm);
16593         }
16594       /* Merge any parameters that match with the function parameter
16595          pack.  */
16596       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16597         {
16598           int i, len;
16599           tree expanded_types;
16600           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16601              the parameters in this function parameter pack.  */
16602           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16603                                                  args, tf_error, NULL_TREE);
16604           len = TREE_VEC_LENGTH (expanded_types);
16605           for (i = 0; i < len; i++)
16606             {
16607               tree parm_type;
16608               tree attributes;
16609           
16610               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16611                 /* Rename the parameter to include the index.  */
16612                 DECL_NAME (decl_parm) = 
16613                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16614               parm_type = TREE_VEC_ELT (expanded_types, i);
16615               parm_type = type_decays_to (parm_type);
16616               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16617                 TREE_TYPE (decl_parm) = parm_type;
16618               attributes = DECL_ATTRIBUTES (pattern_parm);
16619               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16620                 {
16621                   DECL_ATTRIBUTES (decl_parm) = attributes;
16622                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16623                 }
16624               decl_parm = DECL_CHAIN (decl_parm);
16625             }
16626         }
16627       /* Merge additional specifiers from the CODE_PATTERN.  */
16628       if (DECL_DECLARED_INLINE_P (code_pattern)
16629           && !DECL_DECLARED_INLINE_P (decl))
16630         DECL_DECLARED_INLINE_P (decl) = 1;
16631     }
16632   else if (TREE_CODE (decl) == VAR_DECL)
16633     {
16634       DECL_INITIAL (decl) =
16635         tsubst_expr (DECL_INITIAL (code_pattern), args,
16636                      tf_error, DECL_TI_TEMPLATE (decl),
16637                      /*integral_constant_expression_p=*/false);
16638       if (VAR_HAD_UNKNOWN_BOUND (decl))
16639         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
16640                                    tf_error, DECL_TI_TEMPLATE (decl));
16641     }
16642   else
16643     gcc_unreachable ();
16644
16645   pop_access_scope (decl);
16646 }
16647
16648 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16649    substituted to get DECL.  */
16650
16651 tree
16652 template_for_substitution (tree decl)
16653 {
16654   tree tmpl = DECL_TI_TEMPLATE (decl);
16655
16656   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16657      for the instantiation.  This is not always the most general
16658      template.  Consider, for example:
16659
16660         template <class T>
16661         struct S { template <class U> void f();
16662                    template <> void f<int>(); };
16663
16664      and an instantiation of S<double>::f<int>.  We want TD to be the
16665      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16666   while (/* An instantiation cannot have a definition, so we need a
16667             more general template.  */
16668          DECL_TEMPLATE_INSTANTIATION (tmpl)
16669            /* We must also deal with friend templates.  Given:
16670
16671                 template <class T> struct S {
16672                   template <class U> friend void f() {};
16673                 };
16674
16675               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16676               so far as the language is concerned, but that's still
16677               where we get the pattern for the instantiation from.  On
16678               other hand, if the definition comes outside the class, say:
16679
16680                 template <class T> struct S {
16681                   template <class U> friend void f();
16682                 };
16683                 template <class U> friend void f() {}
16684
16685               we don't need to look any further.  That's what the check for
16686               DECL_INITIAL is for.  */
16687           || (TREE_CODE (decl) == FUNCTION_DECL
16688               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16689               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16690     {
16691       /* The present template, TD, should not be a definition.  If it
16692          were a definition, we should be using it!  Note that we
16693          cannot restructure the loop to just keep going until we find
16694          a template with a definition, since that might go too far if
16695          a specialization was declared, but not defined.  */
16696       gcc_assert (TREE_CODE (decl) != VAR_DECL
16697                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16698
16699       /* Fetch the more general template.  */
16700       tmpl = DECL_TI_TEMPLATE (tmpl);
16701     }
16702
16703   return tmpl;
16704 }
16705
16706 /* Returns true if we need to instantiate this template instance even if we
16707    know we aren't going to emit it..  */
16708
16709 bool
16710 always_instantiate_p (tree decl)
16711 {
16712   /* We always instantiate inline functions so that we can inline them.  An
16713      explicit instantiation declaration prohibits implicit instantiation of
16714      non-inline functions.  With high levels of optimization, we would
16715      normally inline non-inline functions -- but we're not allowed to do
16716      that for "extern template" functions.  Therefore, we check
16717      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16718   return ((TREE_CODE (decl) == FUNCTION_DECL
16719            && DECL_DECLARED_INLINE_P (decl))
16720           /* And we need to instantiate static data members so that
16721              their initializers are available in integral constant
16722              expressions.  */
16723           || (TREE_CODE (decl) == VAR_DECL
16724               && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16725 }
16726
16727 /* Produce the definition of D, a _DECL generated from a template.  If
16728    DEFER_OK is nonzero, then we don't have to actually do the
16729    instantiation now; we just have to do it sometime.  Normally it is
16730    an error if this is an explicit instantiation but D is undefined.
16731    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16732    explicitly instantiated class template.  */
16733
16734 tree
16735 instantiate_decl (tree d, int defer_ok,
16736                   bool expl_inst_class_mem_p)
16737 {
16738   tree tmpl = DECL_TI_TEMPLATE (d);
16739   tree gen_args;
16740   tree args;
16741   tree td;
16742   tree code_pattern;
16743   tree spec;
16744   tree gen_tmpl;
16745   bool pattern_defined;
16746   int need_push;
16747   location_t saved_loc = input_location;
16748   bool external_p;
16749
16750   /* This function should only be used to instantiate templates for
16751      functions and static member variables.  */
16752   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16753               || TREE_CODE (d) == VAR_DECL);
16754
16755   /* Variables are never deferred; if instantiation is required, they
16756      are instantiated right away.  That allows for better code in the
16757      case that an expression refers to the value of the variable --
16758      if the variable has a constant value the referring expression can
16759      take advantage of that fact.  */
16760   if (TREE_CODE (d) == VAR_DECL)
16761     defer_ok = 0;
16762
16763   /* Don't instantiate cloned functions.  Instead, instantiate the
16764      functions they cloned.  */
16765   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16766     d = DECL_CLONED_FUNCTION (d);
16767
16768   if (DECL_TEMPLATE_INSTANTIATED (d)
16769       || DECL_TEMPLATE_SPECIALIZATION (d))
16770     /* D has already been instantiated or explicitly specialized, so
16771        there's nothing for us to do here.
16772
16773        It might seem reasonable to check whether or not D is an explicit
16774        instantiation, and, if so, stop here.  But when an explicit
16775        instantiation is deferred until the end of the compilation,
16776        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16777        the instantiation.  */
16778     return d;
16779
16780   /* Check to see whether we know that this template will be
16781      instantiated in some other file, as with "extern template"
16782      extension.  */
16783   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16784
16785   /* In general, we do not instantiate such templates.  */
16786   if (external_p && !always_instantiate_p (d))
16787     return d;
16788
16789   gen_tmpl = most_general_template (tmpl);
16790   gen_args = DECL_TI_ARGS (d);
16791
16792   if (tmpl != gen_tmpl)
16793     /* We should already have the extra args.  */
16794     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16795                 == TMPL_ARGS_DEPTH (gen_args));
16796   /* And what's in the hash table should match D.  */
16797   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16798               || spec == NULL_TREE);
16799
16800   /* This needs to happen before any tsubsting.  */
16801   if (! push_tinst_level (d))
16802     return d;
16803
16804   timevar_push (TV_PARSE);
16805
16806   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16807      for the instantiation.  */
16808   td = template_for_substitution (d);
16809   code_pattern = DECL_TEMPLATE_RESULT (td);
16810
16811   /* We should never be trying to instantiate a member of a class
16812      template or partial specialization.  */
16813   gcc_assert (d != code_pattern);
16814
16815   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16816       || DECL_TEMPLATE_SPECIALIZATION (td))
16817     /* In the case of a friend template whose definition is provided
16818        outside the class, we may have too many arguments.  Drop the
16819        ones we don't need.  The same is true for specializations.  */
16820     args = get_innermost_template_args
16821       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16822   else
16823     args = gen_args;
16824
16825   if (TREE_CODE (d) == FUNCTION_DECL)
16826     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16827   else
16828     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16829
16830   /* We may be in the middle of deferred access check.  Disable it now.  */
16831   push_deferring_access_checks (dk_no_deferred);
16832
16833   /* Unless an explicit instantiation directive has already determined
16834      the linkage of D, remember that a definition is available for
16835      this entity.  */
16836   if (pattern_defined
16837       && !DECL_INTERFACE_KNOWN (d)
16838       && !DECL_NOT_REALLY_EXTERN (d))
16839     mark_definable (d);
16840
16841   input_location = DECL_SOURCE_LOCATION (d);
16842
16843   /* If D is a member of an explicitly instantiated class template,
16844      and no definition is available, treat it like an implicit
16845      instantiation.  */
16846   if (!pattern_defined && expl_inst_class_mem_p
16847       && DECL_EXPLICIT_INSTANTIATION (d))
16848     {
16849       DECL_NOT_REALLY_EXTERN (d) = 0;
16850       DECL_INTERFACE_KNOWN (d) = 0;
16851       SET_DECL_IMPLICIT_INSTANTIATION (d);
16852     }
16853
16854   /* Recheck the substitutions to obtain any warning messages
16855      about ignoring cv qualifiers.  Don't do this for artificial decls,
16856      as it breaks the context-sensitive substitution for lambda op(). */
16857   if (!defer_ok && !DECL_ARTIFICIAL (d))
16858     {
16859       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16860       tree type = TREE_TYPE (gen);
16861
16862       /* Make sure that we can see identifiers, and compute access
16863          correctly.  D is already the target FUNCTION_DECL with the
16864          right context.  */
16865       push_access_scope (d);
16866
16867       if (TREE_CODE (gen) == FUNCTION_DECL)
16868         {
16869           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16870           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16871                                           d);
16872           /* Don't simply tsubst the function type, as that will give
16873              duplicate warnings about poor parameter qualifications.
16874              The function arguments are the same as the decl_arguments
16875              without the top level cv qualifiers.  */
16876           type = TREE_TYPE (type);
16877         }
16878       tsubst (type, gen_args, tf_warning_or_error, d);
16879
16880       pop_access_scope (d);
16881     }
16882
16883   /* Defer all other templates, unless we have been explicitly
16884      forbidden from doing so.  */
16885   if (/* If there is no definition, we cannot instantiate the
16886          template.  */
16887       ! pattern_defined
16888       /* If it's OK to postpone instantiation, do so.  */
16889       || defer_ok
16890       /* If this is a static data member that will be defined
16891          elsewhere, we don't want to instantiate the entire data
16892          member, but we do want to instantiate the initializer so that
16893          we can substitute that elsewhere.  */
16894       || (external_p && TREE_CODE (d) == VAR_DECL))
16895     {
16896       /* The definition of the static data member is now required so
16897          we must substitute the initializer.  */
16898       if (TREE_CODE (d) == VAR_DECL
16899           && !DECL_INITIAL (d)
16900           && DECL_INITIAL (code_pattern))
16901         {
16902           tree ns;
16903           tree init;
16904
16905           ns = decl_namespace_context (d);
16906           push_nested_namespace (ns);
16907           push_nested_class (DECL_CONTEXT (d));
16908           init = tsubst_expr (DECL_INITIAL (code_pattern),
16909                               args,
16910                               tf_warning_or_error, NULL_TREE,
16911                               /*integral_constant_expression_p=*/false);
16912           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16913                           /*asmspec_tree=*/NULL_TREE,
16914                           LOOKUP_ONLYCONVERTING);
16915           pop_nested_class ();
16916           pop_nested_namespace (ns);
16917         }
16918
16919       /* We restore the source position here because it's used by
16920          add_pending_template.  */
16921       input_location = saved_loc;
16922
16923       if (at_eof && !pattern_defined
16924           && DECL_EXPLICIT_INSTANTIATION (d)
16925           && DECL_NOT_REALLY_EXTERN (d))
16926         /* [temp.explicit]
16927
16928            The definition of a non-exported function template, a
16929            non-exported member function template, or a non-exported
16930            member function or static data member of a class template
16931            shall be present in every translation unit in which it is
16932            explicitly instantiated.  */
16933         permerror (input_location,  "explicit instantiation of %qD "
16934                    "but no definition available", d);
16935
16936       /* ??? Historically, we have instantiated inline functions, even
16937          when marked as "extern template".  */
16938       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16939         add_pending_template (d);
16940       goto out;
16941     }
16942   /* Tell the repository that D is available in this translation unit
16943      -- and see if it is supposed to be instantiated here.  */
16944   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16945     {
16946       /* In a PCH file, despite the fact that the repository hasn't
16947          requested instantiation in the PCH it is still possible that
16948          an instantiation will be required in a file that includes the
16949          PCH.  */
16950       if (pch_file)
16951         add_pending_template (d);
16952       /* Instantiate inline functions so that the inliner can do its
16953          job, even though we'll not be emitting a copy of this
16954          function.  */
16955       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16956         goto out;
16957     }
16958
16959   need_push = !cfun || !global_bindings_p ();
16960   if (need_push)
16961     push_to_top_level ();
16962
16963   /* Mark D as instantiated so that recursive calls to
16964      instantiate_decl do not try to instantiate it again.  */
16965   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16966
16967   /* Regenerate the declaration in case the template has been modified
16968      by a subsequent redeclaration.  */
16969   regenerate_decl_from_template (d, td);
16970
16971   /* We already set the file and line above.  Reset them now in case
16972      they changed as a result of calling regenerate_decl_from_template.  */
16973   input_location = DECL_SOURCE_LOCATION (d);
16974
16975   if (TREE_CODE (d) == VAR_DECL)
16976     {
16977       tree init;
16978
16979       /* Clear out DECL_RTL; whatever was there before may not be right
16980          since we've reset the type of the declaration.  */
16981       SET_DECL_RTL (d, NULL);
16982       DECL_IN_AGGR_P (d) = 0;
16983
16984       /* The initializer is placed in DECL_INITIAL by
16985          regenerate_decl_from_template.  Pull it out so that
16986          cp_finish_decl can process it.  */
16987       init = DECL_INITIAL (d);
16988       DECL_INITIAL (d) = NULL_TREE;
16989       DECL_INITIALIZED_P (d) = 0;
16990
16991       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16992          initializer.  That function will defer actual emission until
16993          we have a chance to determine linkage.  */
16994       DECL_EXTERNAL (d) = 0;
16995
16996       /* Enter the scope of D so that access-checking works correctly.  */
16997       push_nested_class (DECL_CONTEXT (d));
16998       cp_finish_decl (d, init, false, NULL_TREE, 0);
16999       pop_nested_class ();
17000     }
17001   else if (TREE_CODE (d) == FUNCTION_DECL)
17002     {
17003       htab_t saved_local_specializations;
17004       tree subst_decl;
17005       tree tmpl_parm;
17006       tree spec_parm;
17007
17008       /* Save away the current list, in case we are instantiating one
17009          template from within the body of another.  */
17010       saved_local_specializations = local_specializations;
17011
17012       /* Set up the list of local specializations.  */
17013       local_specializations = htab_create (37,
17014                                            hash_local_specialization,
17015                                            eq_local_specializations,
17016                                            NULL);
17017
17018       /* Set up context.  */
17019       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
17020
17021       /* Create substitution entries for the parameters.  */
17022       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
17023       tmpl_parm = DECL_ARGUMENTS (subst_decl);
17024       spec_parm = DECL_ARGUMENTS (d);
17025       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
17026         {
17027           register_local_specialization (spec_parm, tmpl_parm);
17028           spec_parm = skip_artificial_parms_for (d, spec_parm);
17029           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
17030         }
17031       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
17032         {
17033           register_local_specialization (spec_parm, tmpl_parm);
17034           tmpl_parm = DECL_CHAIN (tmpl_parm);
17035           spec_parm = DECL_CHAIN (spec_parm);
17036         }
17037       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
17038         {
17039           /* Register the (value) argument pack as a specialization of
17040              TMPL_PARM, then move on.  */
17041           tree argpack = make_fnparm_pack (spec_parm);
17042           register_local_specialization (argpack, tmpl_parm);
17043           tmpl_parm = DECL_CHAIN (tmpl_parm);
17044           spec_parm = NULL_TREE;
17045         }
17046       gcc_assert (!spec_parm);
17047
17048       /* Substitute into the body of the function.  */
17049       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
17050                    tf_warning_or_error, tmpl,
17051                    /*integral_constant_expression_p=*/false);
17052
17053       /* Set the current input_location to the end of the function
17054          so that finish_function knows where we are.  */
17055       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
17056
17057       /* We don't need the local specializations any more.  */
17058       htab_delete (local_specializations);
17059       local_specializations = saved_local_specializations;
17060
17061       /* Finish the function.  */
17062       d = finish_function (0);
17063       expand_or_defer_fn (d);
17064     }
17065
17066   /* We're not deferring instantiation any more.  */
17067   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
17068
17069   if (need_push)
17070     pop_from_top_level ();
17071
17072 out:
17073   input_location = saved_loc;
17074   pop_deferring_access_checks ();
17075   pop_tinst_level ();
17076
17077   timevar_pop (TV_PARSE);
17078
17079   return d;
17080 }
17081
17082 /* Run through the list of templates that we wish we could
17083    instantiate, and instantiate any we can.  RETRIES is the
17084    number of times we retry pending template instantiation.  */
17085
17086 void
17087 instantiate_pending_templates (int retries)
17088 {
17089   int reconsider;
17090   location_t saved_loc = input_location;
17091
17092   /* Instantiating templates may trigger vtable generation.  This in turn
17093      may require further template instantiations.  We place a limit here
17094      to avoid infinite loop.  */
17095   if (pending_templates && retries >= max_tinst_depth)
17096     {
17097       tree decl = pending_templates->tinst->decl;
17098
17099       error ("template instantiation depth exceeds maximum of %d"
17100              " instantiating %q+D, possibly from virtual table generation"
17101              " (use -ftemplate-depth= to increase the maximum)",
17102              max_tinst_depth, decl);
17103       if (TREE_CODE (decl) == FUNCTION_DECL)
17104         /* Pretend that we defined it.  */
17105         DECL_INITIAL (decl) = error_mark_node;
17106       return;
17107     }
17108
17109   do
17110     {
17111       struct pending_template **t = &pending_templates;
17112       struct pending_template *last = NULL;
17113       reconsider = 0;
17114       while (*t)
17115         {
17116           tree instantiation = reopen_tinst_level ((*t)->tinst);
17117           bool complete = false;
17118
17119           if (TYPE_P (instantiation))
17120             {
17121               tree fn;
17122
17123               if (!COMPLETE_TYPE_P (instantiation))
17124                 {
17125                   instantiate_class_template (instantiation);
17126                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
17127                     for (fn = TYPE_METHODS (instantiation);
17128                          fn;
17129                          fn = TREE_CHAIN (fn))
17130                       if (! DECL_ARTIFICIAL (fn))
17131                         instantiate_decl (fn,
17132                                           /*defer_ok=*/0,
17133                                           /*expl_inst_class_mem_p=*/false);
17134                   if (COMPLETE_TYPE_P (instantiation))
17135                     reconsider = 1;
17136                 }
17137
17138               complete = COMPLETE_TYPE_P (instantiation);
17139             }
17140           else
17141             {
17142               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
17143                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
17144                 {
17145                   instantiation
17146                     = instantiate_decl (instantiation,
17147                                         /*defer_ok=*/0,
17148                                         /*expl_inst_class_mem_p=*/false);
17149                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
17150                     reconsider = 1;
17151                 }
17152
17153               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
17154                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
17155             }
17156
17157           if (complete)
17158             /* If INSTANTIATION has been instantiated, then we don't
17159                need to consider it again in the future.  */
17160             *t = (*t)->next;
17161           else
17162             {
17163               last = *t;
17164               t = &(*t)->next;
17165             }
17166           tinst_depth = 0;
17167           current_tinst_level = NULL;
17168         }
17169       last_pending_template = last;
17170     }
17171   while (reconsider);
17172
17173   input_location = saved_loc;
17174 }
17175
17176 /* Substitute ARGVEC into T, which is a list of initializers for
17177    either base class or a non-static data member.  The TREE_PURPOSEs
17178    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
17179    instantiate_decl.  */
17180
17181 static tree
17182 tsubst_initializer_list (tree t, tree argvec)
17183 {
17184   tree inits = NULL_TREE;
17185
17186   for (; t; t = TREE_CHAIN (t))
17187     {
17188       tree decl;
17189       tree init;
17190       tree expanded_bases = NULL_TREE;
17191       tree expanded_arguments = NULL_TREE;
17192       int i, len = 1;
17193
17194       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
17195         {
17196           tree expr;
17197           tree arg;
17198
17199           /* Expand the base class expansion type into separate base
17200              classes.  */
17201           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
17202                                                  tf_warning_or_error,
17203                                                  NULL_TREE);
17204           if (expanded_bases == error_mark_node)
17205             continue;
17206           
17207           /* We'll be building separate TREE_LISTs of arguments for
17208              each base.  */
17209           len = TREE_VEC_LENGTH (expanded_bases);
17210           expanded_arguments = make_tree_vec (len);
17211           for (i = 0; i < len; i++)
17212             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
17213
17214           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
17215              expand each argument in the TREE_VALUE of t.  */
17216           expr = make_node (EXPR_PACK_EXPANSION);
17217           PACK_EXPANSION_PARAMETER_PACKS (expr) =
17218             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
17219
17220           if (TREE_VALUE (t) == void_type_node)
17221             /* VOID_TYPE_NODE is used to indicate
17222                value-initialization.  */
17223             {
17224               for (i = 0; i < len; i++)
17225                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
17226             }
17227           else
17228             {
17229               /* Substitute parameter packs into each argument in the
17230                  TREE_LIST.  */
17231               in_base_initializer = 1;
17232               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
17233                 {
17234                   tree expanded_exprs;
17235
17236                   /* Expand the argument.  */
17237                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
17238                   expanded_exprs 
17239                     = tsubst_pack_expansion (expr, argvec,
17240                                              tf_warning_or_error,
17241                                              NULL_TREE);
17242                   if (expanded_exprs == error_mark_node)
17243                     continue;
17244
17245                   /* Prepend each of the expanded expressions to the
17246                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
17247                   for (i = 0; i < len; i++)
17248                     {
17249                       TREE_VEC_ELT (expanded_arguments, i) = 
17250                         tree_cons (NULL_TREE, 
17251                                    TREE_VEC_ELT (expanded_exprs, i),
17252                                    TREE_VEC_ELT (expanded_arguments, i));
17253                     }
17254                 }
17255               in_base_initializer = 0;
17256
17257               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
17258                  since we built them backwards.  */
17259               for (i = 0; i < len; i++)
17260                 {
17261                   TREE_VEC_ELT (expanded_arguments, i) = 
17262                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
17263                 }
17264             }
17265         }
17266
17267       for (i = 0; i < len; ++i)
17268         {
17269           if (expanded_bases)
17270             {
17271               decl = TREE_VEC_ELT (expanded_bases, i);
17272               decl = expand_member_init (decl);
17273               init = TREE_VEC_ELT (expanded_arguments, i);
17274             }
17275           else
17276             {
17277               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
17278                                   tf_warning_or_error, NULL_TREE);
17279
17280               decl = expand_member_init (decl);
17281               if (decl && !DECL_P (decl))
17282                 in_base_initializer = 1;
17283
17284               init = TREE_VALUE (t);
17285               if (init != void_type_node)
17286                 init = tsubst_expr (init, argvec,
17287                                     tf_warning_or_error, NULL_TREE,
17288                                     /*integral_constant_expression_p=*/false);
17289               in_base_initializer = 0;
17290             }
17291
17292           if (decl)
17293             {
17294               init = build_tree_list (decl, init);
17295               TREE_CHAIN (init) = inits;
17296               inits = init;
17297             }
17298         }
17299     }
17300   return inits;
17301 }
17302
17303 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
17304
17305 static void
17306 set_current_access_from_decl (tree decl)
17307 {
17308   if (TREE_PRIVATE (decl))
17309     current_access_specifier = access_private_node;
17310   else if (TREE_PROTECTED (decl))
17311     current_access_specifier = access_protected_node;
17312   else
17313     current_access_specifier = access_public_node;
17314 }
17315
17316 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
17317    is the instantiation (which should have been created with
17318    start_enum) and ARGS are the template arguments to use.  */
17319
17320 static void
17321 tsubst_enum (tree tag, tree newtag, tree args)
17322 {
17323   tree e;
17324
17325   if (SCOPED_ENUM_P (newtag))
17326     begin_scope (sk_scoped_enum, newtag);
17327
17328   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
17329     {
17330       tree value;
17331       tree decl;
17332
17333       decl = TREE_VALUE (e);
17334       /* Note that in a template enum, the TREE_VALUE is the
17335          CONST_DECL, not the corresponding INTEGER_CST.  */
17336       value = tsubst_expr (DECL_INITIAL (decl),
17337                            args, tf_warning_or_error, NULL_TREE,
17338                            /*integral_constant_expression_p=*/true);
17339
17340       /* Give this enumeration constant the correct access.  */
17341       set_current_access_from_decl (decl);
17342
17343       /* Actually build the enumerator itself.  */
17344       build_enumerator
17345         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
17346     }
17347
17348   if (SCOPED_ENUM_P (newtag))
17349     finish_scope ();
17350
17351   finish_enum_value_list (newtag);
17352   finish_enum (newtag);
17353
17354   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
17355     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
17356 }
17357
17358 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
17359    its type -- but without substituting the innermost set of template
17360    arguments.  So, innermost set of template parameters will appear in
17361    the type.  */
17362
17363 tree
17364 get_mostly_instantiated_function_type (tree decl)
17365 {
17366   tree fn_type;
17367   tree tmpl;
17368   tree targs;
17369   tree tparms;
17370   int parm_depth;
17371
17372   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
17373   targs = DECL_TI_ARGS (decl);
17374   tparms = DECL_TEMPLATE_PARMS (tmpl);
17375   parm_depth = TMPL_PARMS_DEPTH (tparms);
17376
17377   /* There should be as many levels of arguments as there are levels
17378      of parameters.  */
17379   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
17380
17381   fn_type = TREE_TYPE (tmpl);
17382
17383   if (parm_depth == 1)
17384     /* No substitution is necessary.  */
17385     ;
17386   else
17387     {
17388       int i, save_access_control;
17389       tree partial_args;
17390
17391       /* Replace the innermost level of the TARGS with NULL_TREEs to
17392          let tsubst know not to substitute for those parameters.  */
17393       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
17394       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
17395         SET_TMPL_ARGS_LEVEL (partial_args, i,
17396                              TMPL_ARGS_LEVEL (targs, i));
17397       SET_TMPL_ARGS_LEVEL (partial_args,
17398                            TMPL_ARGS_DEPTH (targs),
17399                            make_tree_vec (DECL_NTPARMS (tmpl)));
17400
17401       /* Disable access control as this function is used only during
17402          name-mangling.  */
17403       save_access_control = flag_access_control;
17404       flag_access_control = 0;
17405
17406       ++processing_template_decl;
17407       /* Now, do the (partial) substitution to figure out the
17408          appropriate function type.  */
17409       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
17410       --processing_template_decl;
17411
17412       /* Substitute into the template parameters to obtain the real
17413          innermost set of parameters.  This step is important if the
17414          innermost set of template parameters contains value
17415          parameters whose types depend on outer template parameters.  */
17416       TREE_VEC_LENGTH (partial_args)--;
17417       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
17418
17419       flag_access_control = save_access_control;
17420     }
17421
17422   return fn_type;
17423 }
17424
17425 /* Return truthvalue if we're processing a template different from
17426    the last one involved in diagnostics.  */
17427 int
17428 problematic_instantiation_changed (void)
17429 {
17430   return last_template_error_tick != tinst_level_tick;
17431 }
17432
17433 /* Remember current template involved in diagnostics.  */
17434 void
17435 record_last_problematic_instantiation (void)
17436 {
17437   last_template_error_tick = tinst_level_tick;
17438 }
17439
17440 struct tinst_level *
17441 current_instantiation (void)
17442 {
17443   return current_tinst_level;
17444 }
17445
17446 /* [temp.param] Check that template non-type parm TYPE is of an allowable
17447    type. Return zero for ok, nonzero for disallowed. Issue error and
17448    warning messages under control of COMPLAIN.  */
17449
17450 static int
17451 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
17452 {
17453   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
17454     return 0;
17455   else if (POINTER_TYPE_P (type))
17456     return 0;
17457   else if (TYPE_PTR_TO_MEMBER_P (type))
17458     return 0;
17459   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
17460     return 0;
17461   else if (TREE_CODE (type) == TYPENAME_TYPE)
17462     return 0;
17463
17464   if (complain & tf_error)
17465     error ("%q#T is not a valid type for a template constant parameter", type);
17466   return 1;
17467 }
17468
17469 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
17470    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
17471
17472 static bool
17473 dependent_type_p_r (tree type)
17474 {
17475   tree scope;
17476
17477   /* [temp.dep.type]
17478
17479      A type is dependent if it is:
17480
17481      -- a template parameter. Template template parameters are types
17482         for us (since TYPE_P holds true for them) so we handle
17483         them here.  */
17484   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17485       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17486     return true;
17487   /* -- a qualified-id with a nested-name-specifier which contains a
17488         class-name that names a dependent type or whose unqualified-id
17489         names a dependent type.  */
17490   if (TREE_CODE (type) == TYPENAME_TYPE)
17491     return true;
17492   /* -- a cv-qualified type where the cv-unqualified type is
17493         dependent.  */
17494   type = TYPE_MAIN_VARIANT (type);
17495   /* -- a compound type constructed from any dependent type.  */
17496   if (TYPE_PTR_TO_MEMBER_P (type))
17497     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17498             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17499                                            (type)));
17500   else if (TREE_CODE (type) == POINTER_TYPE
17501            || TREE_CODE (type) == REFERENCE_TYPE)
17502     return dependent_type_p (TREE_TYPE (type));
17503   else if (TREE_CODE (type) == FUNCTION_TYPE
17504            || TREE_CODE (type) == METHOD_TYPE)
17505     {
17506       tree arg_type;
17507
17508       if (dependent_type_p (TREE_TYPE (type)))
17509         return true;
17510       for (arg_type = TYPE_ARG_TYPES (type);
17511            arg_type;
17512            arg_type = TREE_CHAIN (arg_type))
17513         if (dependent_type_p (TREE_VALUE (arg_type)))
17514           return true;
17515       return false;
17516     }
17517   /* -- an array type constructed from any dependent type or whose
17518         size is specified by a constant expression that is
17519         value-dependent.
17520
17521         We checked for type- and value-dependence of the bounds in
17522         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
17523   if (TREE_CODE (type) == ARRAY_TYPE)
17524     {
17525       if (TYPE_DOMAIN (type)
17526           && dependent_type_p (TYPE_DOMAIN (type)))
17527         return true;
17528       return dependent_type_p (TREE_TYPE (type));
17529     }
17530
17531   /* -- a template-id in which either the template name is a template
17532      parameter ...  */
17533   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17534     return true;
17535   /* ... or any of the template arguments is a dependent type or
17536         an expression that is type-dependent or value-dependent.  */
17537   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17538            && (any_dependent_template_arguments_p
17539                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17540     return true;
17541
17542   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17543      argument of the `typeof' expression is not type-dependent, then
17544      it should already been have resolved.  */
17545   if (TREE_CODE (type) == TYPEOF_TYPE
17546       || TREE_CODE (type) == DECLTYPE_TYPE)
17547     return true;
17548
17549   /* A template argument pack is dependent if any of its packed
17550      arguments are.  */
17551   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17552     {
17553       tree args = ARGUMENT_PACK_ARGS (type);
17554       int i, len = TREE_VEC_LENGTH (args);
17555       for (i = 0; i < len; ++i)
17556         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17557           return true;
17558     }
17559
17560   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17561      be template parameters.  */
17562   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17563     return true;
17564
17565   /* The standard does not specifically mention types that are local
17566      to template functions or local classes, but they should be
17567      considered dependent too.  For example:
17568
17569        template <int I> void f() {
17570          enum E { a = I };
17571          S<sizeof (E)> s;
17572        }
17573
17574      The size of `E' cannot be known until the value of `I' has been
17575      determined.  Therefore, `E' must be considered dependent.  */
17576   scope = TYPE_CONTEXT (type);
17577   if (scope && TYPE_P (scope))
17578     return dependent_type_p (scope);
17579   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17580     return type_dependent_expression_p (scope);
17581
17582   /* Other types are non-dependent.  */
17583   return false;
17584 }
17585
17586 /* Returns TRUE if TYPE is dependent, in the sense of
17587    [temp.dep.type].  */
17588
17589 bool
17590 dependent_type_p (tree type)
17591 {
17592   /* If there are no template parameters in scope, then there can't be
17593      any dependent types.  */
17594   if (!processing_template_decl)
17595     {
17596       /* If we are not processing a template, then nobody should be
17597          providing us with a dependent type.  */
17598       gcc_assert (type);
17599       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17600       return false;
17601     }
17602
17603   /* If the type is NULL, we have not computed a type for the entity
17604      in question; in that case, the type is dependent.  */
17605   if (!type)
17606     return true;
17607
17608   /* Erroneous types can be considered non-dependent.  */
17609   if (type == error_mark_node)
17610     return false;
17611
17612   /* If we have not already computed the appropriate value for TYPE,
17613      do so now.  */
17614   if (!TYPE_DEPENDENT_P_VALID (type))
17615     {
17616       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17617       TYPE_DEPENDENT_P_VALID (type) = 1;
17618     }
17619
17620   return TYPE_DEPENDENT_P (type);
17621 }
17622
17623 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17624    lookup.  In other words, a dependent type that is not the current
17625    instantiation.  */
17626
17627 bool
17628 dependent_scope_p (tree scope)
17629 {
17630   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17631           && !currently_open_class (scope));
17632 }
17633
17634 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17635    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17636    expression.  */
17637
17638 bool
17639 value_dependent_expression_p (tree expression)
17640 {
17641   if (!processing_template_decl)
17642     return false;
17643
17644   /* A name declared with a dependent type.  */
17645   if (DECL_P (expression) && type_dependent_expression_p (expression))
17646     return true;
17647
17648   switch (TREE_CODE (expression))
17649     {
17650     case IDENTIFIER_NODE:
17651       /* A name that has not been looked up -- must be dependent.  */
17652       return true;
17653
17654     case TEMPLATE_PARM_INDEX:
17655       /* A non-type template parm.  */
17656       return true;
17657
17658     case CONST_DECL:
17659       /* A non-type template parm.  */
17660       if (DECL_TEMPLATE_PARM_P (expression))
17661         return true;
17662       return value_dependent_expression_p (DECL_INITIAL (expression));
17663
17664     case VAR_DECL:
17665        /* A constant with integral or enumeration type and is initialized
17666           with an expression that is value-dependent.  */
17667       if (DECL_INITIAL (expression)
17668           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17669           && value_dependent_expression_p (DECL_INITIAL (expression)))
17670         return true;
17671       return false;
17672
17673     case DYNAMIC_CAST_EXPR:
17674     case STATIC_CAST_EXPR:
17675     case CONST_CAST_EXPR:
17676     case REINTERPRET_CAST_EXPR:
17677     case CAST_EXPR:
17678       /* These expressions are value-dependent if the type to which
17679          the cast occurs is dependent or the expression being casted
17680          is value-dependent.  */
17681       {
17682         tree type = TREE_TYPE (expression);
17683
17684         if (dependent_type_p (type))
17685           return true;
17686
17687         /* A functional cast has a list of operands.  */
17688         expression = TREE_OPERAND (expression, 0);
17689         if (!expression)
17690           {
17691             /* If there are no operands, it must be an expression such
17692                as "int()". This should not happen for aggregate types
17693                because it would form non-constant expressions.  */
17694             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17695
17696             return false;
17697           }
17698
17699         if (TREE_CODE (expression) == TREE_LIST)
17700           return any_value_dependent_elements_p (expression);
17701
17702         return value_dependent_expression_p (expression);
17703       }
17704
17705     case SIZEOF_EXPR:
17706     case ALIGNOF_EXPR:
17707       /* A `sizeof' expression is value-dependent if the operand is
17708          type-dependent or is a pack expansion.  */
17709       expression = TREE_OPERAND (expression, 0);
17710       if (PACK_EXPANSION_P (expression))
17711         return true;
17712       else if (TYPE_P (expression))
17713         return dependent_type_p (expression);
17714       return type_dependent_expression_p (expression);
17715
17716     case AT_ENCODE_EXPR:
17717       /* An 'encode' expression is value-dependent if the operand is
17718          type-dependent.  */
17719       expression = TREE_OPERAND (expression, 0);
17720       return dependent_type_p (expression);
17721
17722     case NOEXCEPT_EXPR:
17723       expression = TREE_OPERAND (expression, 0);
17724       /* FIXME why check value-dependency?  */
17725       return (type_dependent_expression_p (expression)
17726               || value_dependent_expression_p (expression));
17727
17728     case SCOPE_REF:
17729       {
17730         tree name = TREE_OPERAND (expression, 1);
17731         return value_dependent_expression_p (name);
17732       }
17733
17734     case COMPONENT_REF:
17735       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17736               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17737
17738     case CALL_EXPR:
17739       /* A CALL_EXPR may appear in a constant expression if it is a
17740          call to a builtin function, e.g., __builtin_constant_p.  All
17741          such calls are value-dependent.  */
17742       return true;
17743
17744     case NONTYPE_ARGUMENT_PACK:
17745       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17746          is value-dependent.  */
17747       {
17748         tree values = ARGUMENT_PACK_ARGS (expression);
17749         int i, len = TREE_VEC_LENGTH (values);
17750         
17751         for (i = 0; i < len; ++i)
17752           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17753             return true;
17754         
17755         return false;
17756       }
17757
17758     case TRAIT_EXPR:
17759       {
17760         tree type2 = TRAIT_EXPR_TYPE2 (expression);
17761         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17762                 || (type2 ? dependent_type_p (type2) : false));
17763       }
17764
17765     case MODOP_EXPR:
17766       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17767               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17768
17769     case ADDR_EXPR:
17770       {
17771         tree op = TREE_OPERAND (expression, 0);
17772         return (value_dependent_expression_p (op)
17773                 || has_value_dependent_address (op));
17774       }
17775
17776     default:
17777       /* A constant expression is value-dependent if any subexpression is
17778          value-dependent.  */
17779       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17780         {
17781         case tcc_reference:
17782         case tcc_unary:
17783           return (value_dependent_expression_p
17784                   (TREE_OPERAND (expression, 0)));
17785
17786         case tcc_comparison:
17787         case tcc_binary:
17788           return ((value_dependent_expression_p
17789                    (TREE_OPERAND (expression, 0)))
17790                   || (value_dependent_expression_p
17791                       (TREE_OPERAND (expression, 1))));
17792
17793         case tcc_expression:
17794         case tcc_vl_exp:
17795           {
17796             int i;
17797             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17798               /* In some cases, some of the operands may be missing.
17799                  (For example, in the case of PREDECREMENT_EXPR, the
17800                  amount to increment by may be missing.)  That doesn't
17801                  make the expression dependent.  */
17802               if (TREE_OPERAND (expression, i)
17803                   && (value_dependent_expression_p
17804                       (TREE_OPERAND (expression, i))))
17805                 return true;
17806             return false;
17807           }
17808
17809         default:
17810           break;
17811         }
17812     }
17813
17814   /* The expression is not value-dependent.  */
17815   return false;
17816 }
17817
17818 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17819    [temp.dep.expr].  */
17820
17821 bool
17822 type_dependent_expression_p (tree expression)
17823 {
17824   if (!processing_template_decl)
17825     return false;
17826
17827   if (expression == error_mark_node)
17828     return false;
17829
17830   /* An unresolved name is always dependent.  */
17831   if (TREE_CODE (expression) == IDENTIFIER_NODE
17832       || TREE_CODE (expression) == USING_DECL)
17833     return true;
17834
17835   /* Some expression forms are never type-dependent.  */
17836   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17837       || TREE_CODE (expression) == SIZEOF_EXPR
17838       || TREE_CODE (expression) == ALIGNOF_EXPR
17839       || TREE_CODE (expression) == AT_ENCODE_EXPR
17840       || TREE_CODE (expression) == NOEXCEPT_EXPR
17841       || TREE_CODE (expression) == TRAIT_EXPR
17842       || TREE_CODE (expression) == TYPEID_EXPR
17843       || TREE_CODE (expression) == DELETE_EXPR
17844       || TREE_CODE (expression) == VEC_DELETE_EXPR
17845       || TREE_CODE (expression) == THROW_EXPR)
17846     return false;
17847
17848   /* The types of these expressions depends only on the type to which
17849      the cast occurs.  */
17850   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17851       || TREE_CODE (expression) == STATIC_CAST_EXPR
17852       || TREE_CODE (expression) == CONST_CAST_EXPR
17853       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17854       || TREE_CODE (expression) == CAST_EXPR)
17855     return dependent_type_p (TREE_TYPE (expression));
17856
17857   /* The types of these expressions depends only on the type created
17858      by the expression.  */
17859   if (TREE_CODE (expression) == NEW_EXPR
17860       || TREE_CODE (expression) == VEC_NEW_EXPR)
17861     {
17862       /* For NEW_EXPR tree nodes created inside a template, either
17863          the object type itself or a TREE_LIST may appear as the
17864          operand 1.  */
17865       tree type = TREE_OPERAND (expression, 1);
17866       if (TREE_CODE (type) == TREE_LIST)
17867         /* This is an array type.  We need to check array dimensions
17868            as well.  */
17869         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17870                || value_dependent_expression_p
17871                     (TREE_OPERAND (TREE_VALUE (type), 1));
17872       else
17873         return dependent_type_p (type);
17874     }
17875
17876   if (TREE_CODE (expression) == SCOPE_REF)
17877     {
17878       tree scope = TREE_OPERAND (expression, 0);
17879       tree name = TREE_OPERAND (expression, 1);
17880
17881       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
17882          contains an identifier associated by name lookup with one or more
17883          declarations declared with a dependent type, or...a
17884          nested-name-specifier or qualified-id that names a member of an
17885          unknown specialization.  */
17886       return (type_dependent_expression_p (name)
17887               || dependent_scope_p (scope));
17888     }
17889
17890   if (TREE_CODE (expression) == FUNCTION_DECL
17891       && DECL_LANG_SPECIFIC (expression)
17892       && DECL_TEMPLATE_INFO (expression)
17893       && (any_dependent_template_arguments_p
17894           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17895     return true;
17896
17897   if (TREE_CODE (expression) == TEMPLATE_DECL
17898       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17899     return false;
17900
17901   if (TREE_CODE (expression) == STMT_EXPR)
17902     expression = stmt_expr_value_expr (expression);
17903
17904   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17905     {
17906       tree elt;
17907       unsigned i;
17908
17909       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17910         {
17911           if (type_dependent_expression_p (elt))
17912             return true;
17913         }
17914       return false;
17915     }
17916
17917   /* A static data member of the current instantiation with incomplete
17918      array type is type-dependent, as the definition and specializations
17919      can have different bounds.  */
17920   if (TREE_CODE (expression) == VAR_DECL
17921       && DECL_CLASS_SCOPE_P (expression)
17922       && dependent_type_p (DECL_CONTEXT (expression))
17923       && VAR_HAD_UNKNOWN_BOUND (expression))
17924     return true;
17925
17926   if (TREE_TYPE (expression) == unknown_type_node)
17927     {
17928       if (TREE_CODE (expression) == ADDR_EXPR)
17929         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17930       if (TREE_CODE (expression) == COMPONENT_REF
17931           || TREE_CODE (expression) == OFFSET_REF)
17932         {
17933           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17934             return true;
17935           expression = TREE_OPERAND (expression, 1);
17936           if (TREE_CODE (expression) == IDENTIFIER_NODE)
17937             return false;
17938         }
17939       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17940       if (TREE_CODE (expression) == SCOPE_REF)
17941         return false;
17942
17943       if (TREE_CODE (expression) == BASELINK)
17944         expression = BASELINK_FUNCTIONS (expression);
17945
17946       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17947         {
17948           if (any_dependent_template_arguments_p
17949               (TREE_OPERAND (expression, 1)))
17950             return true;
17951           expression = TREE_OPERAND (expression, 0);
17952         }
17953       gcc_assert (TREE_CODE (expression) == OVERLOAD
17954                   || TREE_CODE (expression) == FUNCTION_DECL);
17955
17956       while (expression)
17957         {
17958           if (type_dependent_expression_p (OVL_CURRENT (expression)))
17959             return true;
17960           expression = OVL_NEXT (expression);
17961         }
17962       return false;
17963     }
17964
17965   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17966
17967   return (dependent_type_p (TREE_TYPE (expression)));
17968 }
17969
17970 /* Like type_dependent_expression_p, but it also works while not processing
17971    a template definition, i.e. during substitution or mangling.  */
17972
17973 bool
17974 type_dependent_expression_p_push (tree expr)
17975 {
17976   bool b;
17977   ++processing_template_decl;
17978   b = type_dependent_expression_p (expr);
17979   --processing_template_decl;
17980   return b;
17981 }
17982
17983 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17984
17985 bool
17986 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17987 {
17988   unsigned int i;
17989   tree arg;
17990
17991   FOR_EACH_VEC_ELT (tree, args, i, arg)
17992     {
17993       if (type_dependent_expression_p (arg))
17994         return true;
17995     }
17996   return false;
17997 }
17998
17999 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
18000    expressions) contains any value-dependent expressions.  */
18001
18002 bool
18003 any_value_dependent_elements_p (const_tree list)
18004 {
18005   for (; list; list = TREE_CHAIN (list))
18006     if (value_dependent_expression_p (TREE_VALUE (list)))
18007       return true;
18008
18009   return false;
18010 }
18011
18012 /* Returns TRUE if the ARG (a template argument) is dependent.  */
18013
18014 bool
18015 dependent_template_arg_p (tree arg)
18016 {
18017   if (!processing_template_decl)
18018     return false;
18019
18020   if (TREE_CODE (arg) == TEMPLATE_DECL
18021       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
18022     return dependent_template_p (arg);
18023   else if (ARGUMENT_PACK_P (arg))
18024     {
18025       tree args = ARGUMENT_PACK_ARGS (arg);
18026       int i, len = TREE_VEC_LENGTH (args);
18027       for (i = 0; i < len; ++i)
18028         {
18029           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
18030             return true;
18031         }
18032
18033       return false;
18034     }
18035   else if (TYPE_P (arg))
18036     return dependent_type_p (arg);
18037   else
18038     return (type_dependent_expression_p (arg)
18039             || value_dependent_expression_p (arg));
18040 }
18041
18042 /* Returns true if ARGS (a collection of template arguments) contains
18043    any types that require structural equality testing.  */
18044
18045 bool
18046 any_template_arguments_need_structural_equality_p (tree args)
18047 {
18048   int i;
18049   int j;
18050
18051   if (!args)
18052     return false;
18053   if (args == error_mark_node)
18054     return true;
18055
18056   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
18057     {
18058       tree level = TMPL_ARGS_LEVEL (args, i + 1);
18059       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
18060         {
18061           tree arg = TREE_VEC_ELT (level, j);
18062           tree packed_args = NULL_TREE;
18063           int k, len = 1;
18064
18065           if (ARGUMENT_PACK_P (arg))
18066             {
18067               /* Look inside the argument pack.  */
18068               packed_args = ARGUMENT_PACK_ARGS (arg);
18069               len = TREE_VEC_LENGTH (packed_args);
18070             }
18071
18072           for (k = 0; k < len; ++k)
18073             {
18074               if (packed_args)
18075                 arg = TREE_VEC_ELT (packed_args, k);
18076
18077               if (error_operand_p (arg))
18078                 return true;
18079               else if (TREE_CODE (arg) == TEMPLATE_DECL
18080                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
18081                 continue;
18082               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
18083                 return true;
18084               else if (!TYPE_P (arg) && TREE_TYPE (arg)
18085                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
18086                 return true;
18087             }
18088         }
18089     }
18090
18091   return false;
18092 }
18093
18094 /* Returns true if ARGS (a collection of template arguments) contains
18095    any dependent arguments.  */
18096
18097 bool
18098 any_dependent_template_arguments_p (const_tree args)
18099 {
18100   int i;
18101   int j;
18102
18103   if (!args)
18104     return false;
18105   if (args == error_mark_node)
18106     return true;
18107
18108   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
18109     {
18110       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
18111       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
18112         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
18113           return true;
18114     }
18115
18116   return false;
18117 }
18118
18119 /* Returns TRUE if the template TMPL is dependent.  */
18120
18121 bool
18122 dependent_template_p (tree tmpl)
18123 {
18124   if (TREE_CODE (tmpl) == OVERLOAD)
18125     {
18126       while (tmpl)
18127         {
18128           if (dependent_template_p (OVL_FUNCTION (tmpl)))
18129             return true;
18130           tmpl = OVL_CHAIN (tmpl);
18131         }
18132       return false;
18133     }
18134
18135   /* Template template parameters are dependent.  */
18136   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
18137       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
18138     return true;
18139   /* So are names that have not been looked up.  */
18140   if (TREE_CODE (tmpl) == SCOPE_REF
18141       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
18142     return true;
18143   /* So are member templates of dependent classes.  */
18144   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
18145     return dependent_type_p (DECL_CONTEXT (tmpl));
18146   return false;
18147 }
18148
18149 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
18150
18151 bool
18152 dependent_template_id_p (tree tmpl, tree args)
18153 {
18154   return (dependent_template_p (tmpl)
18155           || any_dependent_template_arguments_p (args));
18156 }
18157
18158 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
18159    is dependent.  */
18160
18161 bool
18162 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
18163 {
18164   int i;
18165
18166   if (!processing_template_decl)
18167     return false;
18168
18169   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
18170     {
18171       tree decl = TREE_VEC_ELT (declv, i);
18172       tree init = TREE_VEC_ELT (initv, i);
18173       tree cond = TREE_VEC_ELT (condv, i);
18174       tree incr = TREE_VEC_ELT (incrv, i);
18175
18176       if (type_dependent_expression_p (decl))
18177         return true;
18178
18179       if (init && type_dependent_expression_p (init))
18180         return true;
18181
18182       if (type_dependent_expression_p (cond))
18183         return true;
18184
18185       if (COMPARISON_CLASS_P (cond)
18186           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
18187               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
18188         return true;
18189
18190       if (TREE_CODE (incr) == MODOP_EXPR)
18191         {
18192           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
18193               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
18194             return true;
18195         }
18196       else if (type_dependent_expression_p (incr))
18197         return true;
18198       else if (TREE_CODE (incr) == MODIFY_EXPR)
18199         {
18200           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
18201             return true;
18202           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
18203             {
18204               tree t = TREE_OPERAND (incr, 1);
18205               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
18206                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
18207                 return true;
18208             }
18209         }
18210     }
18211
18212   return false;
18213 }
18214
18215 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
18216    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
18217    no such TYPE can be found.  Note that this function peers inside
18218    uninstantiated templates and therefore should be used only in
18219    extremely limited situations.  ONLY_CURRENT_P restricts this
18220    peering to the currently open classes hierarchy (which is required
18221    when comparing types).  */
18222
18223 tree
18224 resolve_typename_type (tree type, bool only_current_p)
18225 {
18226   tree scope;
18227   tree name;
18228   tree decl;
18229   int quals;
18230   tree pushed_scope;
18231   tree result;
18232
18233   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
18234
18235   scope = TYPE_CONTEXT (type);
18236   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
18237      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
18238      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
18239      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
18240      identifier  of the TYPENAME_TYPE anymore.
18241      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
18242      TYPENAME_TYPE instead, we avoid messing up with a possible
18243      typedef variant case.  */
18244   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
18245
18246   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
18247      it first before we can figure out what NAME refers to.  */
18248   if (TREE_CODE (scope) == TYPENAME_TYPE)
18249     scope = resolve_typename_type (scope, only_current_p);
18250   /* If we don't know what SCOPE refers to, then we cannot resolve the
18251      TYPENAME_TYPE.  */
18252   if (TREE_CODE (scope) == TYPENAME_TYPE)
18253     return type;
18254   /* If the SCOPE is a template type parameter, we have no way of
18255      resolving the name.  */
18256   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
18257     return type;
18258   /* If the SCOPE is not the current instantiation, there's no reason
18259      to look inside it.  */
18260   if (only_current_p && !currently_open_class (scope))
18261     return type;
18262   /* If this is a typedef, we don't want to look inside (c++/11987).  */
18263   if (typedef_variant_p (type))
18264     return type;
18265   /* If SCOPE isn't the template itself, it will not have a valid
18266      TYPE_FIELDS list.  */
18267   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
18268     /* scope is either the template itself or a compatible instantiation
18269        like X<T>, so look up the name in the original template.  */
18270     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
18271   else
18272     /* scope is a partial instantiation, so we can't do the lookup or we
18273        will lose the template arguments.  */
18274     return type;
18275   /* Enter the SCOPE so that name lookup will be resolved as if we
18276      were in the class definition.  In particular, SCOPE will no
18277      longer be considered a dependent type.  */
18278   pushed_scope = push_scope (scope);
18279   /* Look up the declaration.  */
18280   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
18281
18282   result = NULL_TREE;
18283   
18284   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
18285      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
18286   if (!decl)
18287     /*nop*/;
18288   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
18289            && TREE_CODE (decl) == TYPE_DECL)
18290     {
18291       result = TREE_TYPE (decl);
18292       if (result == error_mark_node)
18293         result = NULL_TREE;
18294     }
18295   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
18296            && DECL_CLASS_TEMPLATE_P (decl))
18297     {
18298       tree tmpl;
18299       tree args;
18300       /* Obtain the template and the arguments.  */
18301       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
18302       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
18303       /* Instantiate the template.  */
18304       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
18305                                       /*entering_scope=*/0,
18306                                       tf_error | tf_user);
18307       if (result == error_mark_node)
18308         result = NULL_TREE;
18309     }
18310   
18311   /* Leave the SCOPE.  */
18312   if (pushed_scope)
18313     pop_scope (pushed_scope);
18314
18315   /* If we failed to resolve it, return the original typename.  */
18316   if (!result)
18317     return type;
18318   
18319   /* If lookup found a typename type, resolve that too.  */
18320   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
18321     {
18322       /* Ill-formed programs can cause infinite recursion here, so we
18323          must catch that.  */
18324       TYPENAME_IS_RESOLVING_P (type) = 1;
18325       result = resolve_typename_type (result, only_current_p);
18326       TYPENAME_IS_RESOLVING_P (type) = 0;
18327     }
18328   
18329   /* Qualify the resulting type.  */
18330   quals = cp_type_quals (type);
18331   if (quals)
18332     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
18333
18334   return result;
18335 }
18336
18337 /* EXPR is an expression which is not type-dependent.  Return a proxy
18338    for EXPR that can be used to compute the types of larger
18339    expressions containing EXPR.  */
18340
18341 tree
18342 build_non_dependent_expr (tree expr)
18343 {
18344   tree inner_expr;
18345
18346   /* Preserve null pointer constants so that the type of things like
18347      "p == 0" where "p" is a pointer can be determined.  */
18348   if (null_ptr_cst_p (expr))
18349     return expr;
18350   /* Preserve OVERLOADs; the functions must be available to resolve
18351      types.  */
18352   inner_expr = expr;
18353   if (TREE_CODE (inner_expr) == STMT_EXPR)
18354     inner_expr = stmt_expr_value_expr (inner_expr);
18355   if (TREE_CODE (inner_expr) == ADDR_EXPR)
18356     inner_expr = TREE_OPERAND (inner_expr, 0);
18357   if (TREE_CODE (inner_expr) == COMPONENT_REF)
18358     inner_expr = TREE_OPERAND (inner_expr, 1);
18359   if (is_overloaded_fn (inner_expr)
18360       || TREE_CODE (inner_expr) == OFFSET_REF)
18361     return expr;
18362   /* There is no need to return a proxy for a variable.  */
18363   if (TREE_CODE (expr) == VAR_DECL)
18364     return expr;
18365   /* Preserve string constants; conversions from string constants to
18366      "char *" are allowed, even though normally a "const char *"
18367      cannot be used to initialize a "char *".  */
18368   if (TREE_CODE (expr) == STRING_CST)
18369     return expr;
18370   /* Preserve arithmetic constants, as an optimization -- there is no
18371      reason to create a new node.  */
18372   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
18373     return expr;
18374   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
18375      There is at least one place where we want to know that a
18376      particular expression is a throw-expression: when checking a ?:
18377      expression, there are special rules if the second or third
18378      argument is a throw-expression.  */
18379   if (TREE_CODE (expr) == THROW_EXPR)
18380     return expr;
18381
18382   if (TREE_CODE (expr) == COND_EXPR)
18383     return build3 (COND_EXPR,
18384                    TREE_TYPE (expr),
18385                    TREE_OPERAND (expr, 0),
18386                    (TREE_OPERAND (expr, 1)
18387                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
18388                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
18389                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
18390   if (TREE_CODE (expr) == COMPOUND_EXPR
18391       && !COMPOUND_EXPR_OVERLOADED (expr))
18392     return build2 (COMPOUND_EXPR,
18393                    TREE_TYPE (expr),
18394                    TREE_OPERAND (expr, 0),
18395                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
18396
18397   /* If the type is unknown, it can't really be non-dependent */
18398   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
18399
18400   /* Otherwise, build a NON_DEPENDENT_EXPR.
18401
18402      REFERENCE_TYPEs are not stripped for expressions in templates
18403      because doing so would play havoc with mangling.  Consider, for
18404      example:
18405
18406        template <typename T> void f<T& g>() { g(); }
18407
18408      In the body of "f", the expression for "g" will have
18409      REFERENCE_TYPE, even though the standard says that it should
18410      not.  The reason is that we must preserve the syntactic form of
18411      the expression so that mangling (say) "f<g>" inside the body of
18412      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
18413      stripped here.  */
18414   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
18415 }
18416
18417 /* ARGS is a vector of expressions as arguments to a function call.
18418    Replace the arguments with equivalent non-dependent expressions.
18419    This modifies ARGS in place.  */
18420
18421 void
18422 make_args_non_dependent (VEC(tree,gc) *args)
18423 {
18424   unsigned int ix;
18425   tree arg;
18426
18427   FOR_EACH_VEC_ELT (tree, args, ix, arg)
18428     {
18429       tree newarg = build_non_dependent_expr (arg);
18430       if (newarg != arg)
18431         VEC_replace (tree, args, ix, newarg);
18432     }
18433 }
18434
18435 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
18436    with a level one deeper than the actual template parms.  */
18437
18438 tree
18439 make_auto (void)
18440 {
18441   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
18442   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
18443                                TYPE_DECL, get_identifier ("auto"), au);
18444   TYPE_STUB_DECL (au) = TYPE_NAME (au);
18445   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
18446     (0, processing_template_decl + 1, processing_template_decl + 1,
18447      TYPE_NAME (au), NULL_TREE);
18448   TYPE_CANONICAL (au) = canonical_type_parameter (au);
18449   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
18450   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
18451
18452   return au;
18453 }
18454
18455 /* Given type ARG, return std::initializer_list<ARG>.  */
18456
18457 static tree
18458 listify (tree arg)
18459 {
18460   tree std_init_list = namespace_binding
18461     (get_identifier ("initializer_list"), std_node);
18462   tree argvec;
18463   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
18464     {    
18465       error ("deducing from brace-enclosed initializer list requires "
18466              "#include <initializer_list>");
18467       return error_mark_node;
18468     }
18469   argvec = make_tree_vec (1);
18470   TREE_VEC_ELT (argvec, 0) = arg;
18471   return lookup_template_class (std_init_list, argvec, NULL_TREE,
18472                                 NULL_TREE, 0, tf_warning_or_error);
18473 }
18474
18475 /* Replace auto in TYPE with std::initializer_list<auto>.  */
18476
18477 static tree
18478 listify_autos (tree type, tree auto_node)
18479 {
18480   tree init_auto = listify (auto_node);
18481   tree argvec = make_tree_vec (1);
18482   TREE_VEC_ELT (argvec, 0) = init_auto;
18483   if (processing_template_decl)
18484     argvec = add_to_template_args (current_template_args (), argvec);
18485   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18486 }
18487
18488 /* walk_tree helper for do_auto_deduction.  */
18489
18490 static tree
18491 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
18492                  void *type)
18493 {
18494   /* Is this a variable with the type we're looking for?  */
18495   if (DECL_P (*tp)
18496       && TREE_TYPE (*tp) == type)
18497     return *tp;
18498   else
18499     return NULL_TREE;
18500 }
18501
18502 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18503    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18504
18505 tree
18506 do_auto_deduction (tree type, tree init, tree auto_node)
18507 {
18508   tree parms, tparms, targs;
18509   tree args[1];
18510   tree decl;
18511   int val;
18512
18513   /* The name of the object being declared shall not appear in the
18514      initializer expression.  */
18515   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
18516   if (decl)
18517     {
18518       error ("variable %q#D with %<auto%> type used in its own "
18519              "initializer", decl);
18520       return error_mark_node;
18521     }
18522
18523   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18524      with either a new invented type template parameter U or, if the
18525      initializer is a braced-init-list (8.5.4), with
18526      std::initializer_list<U>.  */
18527   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18528     type = listify_autos (type, auto_node);
18529
18530   parms = build_tree_list (NULL_TREE, type);
18531   args[0] = init;
18532   tparms = make_tree_vec (1);
18533   targs = make_tree_vec (1);
18534   TREE_VEC_ELT (tparms, 0)
18535     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18536   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18537                                DEDUCE_CALL, LOOKUP_NORMAL);
18538   if (val > 0)
18539     {
18540       error ("unable to deduce %qT from %qE", type, init);
18541       return error_mark_node;
18542     }
18543
18544   /* If the list of declarators contains more than one declarator, the type
18545      of each declared variable is determined as described above. If the
18546      type deduced for the template parameter U is not the same in each
18547      deduction, the program is ill-formed.  */
18548   if (TREE_TYPE (auto_node)
18549       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18550     {
18551       error ("inconsistent deduction for %qT: %qT and then %qT",
18552              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18553       return error_mark_node;
18554     }
18555   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18556
18557   if (processing_template_decl)
18558     targs = add_to_template_args (current_template_args (), targs);
18559   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18560 }
18561
18562 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18563    result.  */
18564
18565 tree
18566 splice_late_return_type (tree type, tree late_return_type)
18567 {
18568   tree argvec;
18569
18570   if (late_return_type == NULL_TREE)
18571     return type;
18572   argvec = make_tree_vec (1);
18573   TREE_VEC_ELT (argvec, 0) = late_return_type;
18574   if (processing_template_decl)
18575     argvec = add_to_template_args (current_template_args (), argvec);
18576   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18577 }
18578
18579 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18580
18581 bool
18582 is_auto (const_tree type)
18583 {
18584   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18585       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18586     return true;
18587   else
18588     return false;
18589 }
18590
18591 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18592    appear as a type-specifier for the declaration in question, we don't
18593    have to look through the whole type.  */
18594
18595 tree
18596 type_uses_auto (tree type)
18597 {
18598   enum tree_code code;
18599   if (is_auto (type))
18600     return type;
18601
18602   code = TREE_CODE (type);
18603
18604   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18605       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18606       || code == METHOD_TYPE || code == ARRAY_TYPE)
18607     return type_uses_auto (TREE_TYPE (type));
18608
18609   if (TYPE_PTRMEMFUNC_P (type))
18610     return type_uses_auto (TREE_TYPE (TREE_TYPE
18611                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18612
18613   return NULL_TREE;
18614 }
18615
18616 /* For a given template T, return the vector of typedefs referenced
18617    in T for which access check is needed at T instantiation time.
18618    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18619    Those typedefs were added to T by the function
18620    append_type_to_template_for_access_check.  */
18621
18622 VEC(qualified_typedef_usage_t,gc)*
18623 get_types_needing_access_check (tree t)
18624 {
18625   tree ti;
18626   VEC(qualified_typedef_usage_t,gc) *result = NULL;
18627
18628   if (!t || t == error_mark_node)
18629     return NULL;
18630
18631   if (!(ti = get_template_info (t)))
18632     return NULL;
18633
18634   if (CLASS_TYPE_P (t)
18635       || TREE_CODE (t) == FUNCTION_DECL)
18636     {
18637       if (!TI_TEMPLATE (ti))
18638         return NULL;
18639
18640       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18641     }
18642
18643   return result;
18644 }
18645
18646 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
18647    tied to T. That list of typedefs will be access checked at
18648    T instantiation time.
18649    T is either a FUNCTION_DECL or a RECORD_TYPE.
18650    TYPE_DECL is a TYPE_DECL node representing a typedef.
18651    SCOPE is the scope through which TYPE_DECL is accessed.
18652    LOCATION is the location of the usage point of TYPE_DECL.
18653
18654    This function is a subroutine of
18655    append_type_to_template_for_access_check.  */
18656
18657 static void
18658 append_type_to_template_for_access_check_1 (tree t,
18659                                             tree type_decl,
18660                                             tree scope,
18661                                             location_t location)
18662 {
18663   qualified_typedef_usage_t typedef_usage;
18664   tree ti;
18665
18666   if (!t || t == error_mark_node)
18667     return;
18668
18669   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18670                || CLASS_TYPE_P (t))
18671               && type_decl
18672               && TREE_CODE (type_decl) == TYPE_DECL
18673               && scope);
18674
18675   if (!(ti = get_template_info (t)))
18676     return;
18677
18678   gcc_assert (TI_TEMPLATE (ti));
18679
18680   typedef_usage.typedef_decl = type_decl;
18681   typedef_usage.context = scope;
18682   typedef_usage.locus = location;
18683
18684   VEC_safe_push (qualified_typedef_usage_t, gc,
18685                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
18686                  &typedef_usage);
18687 }
18688
18689 /* Append TYPE_DECL to the template TEMPL.
18690    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18691    At TEMPL instanciation time, TYPE_DECL will be checked to see
18692    if it can be accessed through SCOPE.
18693    LOCATION is the location of the usage point of TYPE_DECL.
18694
18695    e.g. consider the following code snippet:
18696
18697      class C
18698      {
18699        typedef int myint;
18700      };
18701
18702      template<class U> struct S
18703      {
18704        C::myint mi; // <-- usage point of the typedef C::myint
18705      };
18706
18707      S<char> s;
18708
18709    At S<char> instantiation time, we need to check the access of C::myint
18710    In other words, we need to check the access of the myint typedef through
18711    the C scope. For that purpose, this function will add the myint typedef
18712    and the scope C through which its being accessed to a list of typedefs
18713    tied to the template S. That list will be walked at template instantiation
18714    time and access check performed on each typedefs it contains.
18715    Note that this particular code snippet should yield an error because
18716    myint is private to C.  */
18717
18718 void
18719 append_type_to_template_for_access_check (tree templ,
18720                                           tree type_decl,
18721                                           tree scope,
18722                                           location_t location)
18723 {
18724   qualified_typedef_usage_t *iter;
18725   int i;
18726
18727   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18728
18729   /* Make sure we don't append the type to the template twice.  */
18730   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
18731                     get_types_needing_access_check (templ),
18732                     i, iter)
18733     if (iter->typedef_decl == type_decl && scope == iter->context)
18734       return;
18735
18736   append_type_to_template_for_access_check_1 (templ, type_decl,
18737                                               scope, location);
18738 }
18739
18740 /* Set up the hash tables for template instantiations.  */
18741
18742 void
18743 init_template_processing (void)
18744 {
18745   decl_specializations = htab_create_ggc (37,
18746                                           hash_specialization,
18747                                           eq_specializations,
18748                                           ggc_free);
18749   type_specializations = htab_create_ggc (37,
18750                                           hash_specialization,
18751                                           eq_specializations,
18752                                           ggc_free);
18753 }
18754
18755 /* Print stats about the template hash tables for -fstats.  */
18756
18757 void
18758 print_template_statistics (void)
18759 {
18760   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
18761            "%f collisions\n", (long) htab_size (decl_specializations),
18762            (long) htab_elements (decl_specializations),
18763            htab_collisions (decl_specializations));
18764   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
18765            "%f collisions\n", (long) htab_size (type_specializations),
18766            (long) htab_elements (type_specializations),
18767            htab_collisions (type_specializations));
18768 }
18769
18770 #include "gt-cp-pt.h"