OSDN Git Service

72ea5b2d74009c998d372b7019d19a3ccacf4a29
[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
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 "obstack.h"
34 #include "tree.h"
35 #include "pointer-set.h"
36 #include "flags.h"
37 #include "c-common.h"
38 #include "cp-tree.h"
39 #include "cp-objcp-common.h"
40 #include "tree-inline.h"
41 #include "decl.h"
42 #include "output.h"
43 #include "except.h"
44 #include "toplev.h"
45 #include "rtl.h"
46 #include "timevar.h"
47 #include "tree-iterator.h"
48 #include "vecprim.h"
49
50 /* The type of functions taking a tree, and some additional data, and
51    returning an int.  */
52 typedef int (*tree_fn_t) (tree, void*);
53
54 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
55    instantiations have been deferred, either because their definitions
56    were not yet available, or because we were putting off doing the work.  */
57 struct GTY (()) pending_template {
58   struct pending_template *next;
59   struct tinst_level *tinst;
60 };
61
62 static GTY(()) struct pending_template *pending_templates;
63 static GTY(()) struct pending_template *last_pending_template;
64
65 int processing_template_parmlist;
66 static int template_header_count;
67
68 static GTY(()) tree saved_trees;
69 static VEC(int,heap) *inline_parm_levels;
70
71 static GTY(()) struct tinst_level *current_tinst_level;
72
73 static GTY(()) tree saved_access_scope;
74
75 /* Live only within one (recursive) call to tsubst_expr.  We use
76    this to pass the statement expression node from the STMT_EXPR
77    to the EXPR_STMT that is its result.  */
78 static tree cur_stmt_expr;
79
80 /* A map from local variable declarations in the body of the template
81    presently being instantiated to the corresponding instantiated
82    local variables.  */
83 static htab_t local_specializations;
84
85 /* Contains canonical template parameter types. The vector is indexed by
86    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
87    TREE_LIST, whose TREE_VALUEs contain the canonical template
88    parameters of various types and levels.  */
89 static GTY(()) VEC(tree,gc) *canonical_template_parms;
90
91 #define UNIFY_ALLOW_NONE 0
92 #define UNIFY_ALLOW_MORE_CV_QUAL 1
93 #define UNIFY_ALLOW_LESS_CV_QUAL 2
94 #define UNIFY_ALLOW_DERIVED 4
95 #define UNIFY_ALLOW_INTEGER 8
96 #define UNIFY_ALLOW_OUTER_LEVEL 16
97 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
98 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
99
100 static void push_access_scope (tree);
101 static void pop_access_scope (tree);
102 static bool resolve_overloaded_unification (tree, tree, tree, tree,
103                                             unification_kind_t, int);
104 static int try_one_overload (tree, tree, tree, tree, tree,
105                              unification_kind_t, int, bool);
106 static int unify (tree, tree, tree, tree, int);
107 static void add_pending_template (tree);
108 static int push_tinst_level (tree);
109 static void pop_tinst_level (void);
110 static tree reopen_tinst_level (struct tinst_level *);
111 static tree tsubst_initializer_list (tree, tree);
112 static tree get_class_bindings (tree, tree, tree);
113 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
114                                    bool, bool);
115 static void tsubst_enum (tree, tree, tree);
116 static tree add_to_template_args (tree, tree);
117 static tree add_outermost_template_args (tree, tree);
118 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
119 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
120                                              tree);
121 static int type_unification_real (tree, tree, tree, const tree *,
122                                   unsigned int, int, unification_kind_t, int);
123 static void note_template_header (int);
124 static tree convert_nontype_argument_function (tree, tree);
125 static tree convert_nontype_argument (tree, tree);
126 static tree convert_template_argument (tree, tree, tree,
127                                        tsubst_flags_t, int, tree);
128 static int for_each_template_parm (tree, tree_fn_t, void*,
129                                    struct pointer_set_t*, bool);
130 static tree expand_template_argument_pack (tree);
131 static tree build_template_parm_index (int, int, int, tree, tree);
132 static bool inline_needs_template_parms (tree);
133 static void push_inline_template_parms_recursive (tree, int);
134 static tree retrieve_local_specialization (tree);
135 static void register_local_specialization (tree, tree);
136 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
137 static int mark_template_parm (tree, void *);
138 static int template_parm_this_level_p (tree, void *);
139 static tree tsubst_friend_function (tree, tree);
140 static tree tsubst_friend_class (tree, tree);
141 static int can_complete_type_without_circularity (tree);
142 static tree get_bindings (tree, tree, tree, bool);
143 static int template_decl_level (tree);
144 static int check_cv_quals_for_unify (int, tree, tree);
145 static void template_parm_level_and_index (tree, int*, int*);
146 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
147 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
148 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
149 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
150 static void regenerate_decl_from_template (tree, tree);
151 static tree most_specialized_class (tree, tree);
152 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
153 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
154 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
155 static bool check_specialization_scope (void);
156 static tree process_partial_specialization (tree);
157 static void set_current_access_from_decl (tree);
158 static tree get_template_base (tree, tree, tree, tree);
159 static tree try_class_unification (tree, tree, tree, tree);
160 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
161                                            tree, tree);
162 static bool template_template_parm_bindings_ok_p (tree, tree);
163 static int template_args_equal (tree, tree);
164 static void tsubst_default_arguments (tree);
165 static tree for_each_template_parm_r (tree *, int *, void *);
166 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
167 static void copy_default_args_to_explicit_spec (tree);
168 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
169 static int eq_local_specializations (const void *, const void *);
170 static bool dependent_template_arg_p (tree);
171 static bool any_template_arguments_need_structural_equality_p (tree);
172 static bool dependent_type_p_r (tree);
173 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
174 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
175 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
176 static tree tsubst_decl (tree, tree, tsubst_flags_t);
177 static void perform_typedefs_access_check (tree tmpl, tree targs);
178 static void append_type_to_template_for_access_check_1 (tree, tree, tree);
179
180 /* Make the current scope suitable for access checking when we are
181    processing T.  T can be FUNCTION_DECL for instantiated function
182    template, or VAR_DECL for static member variable (need by
183    instantiate_decl).  */
184
185 static void
186 push_access_scope (tree t)
187 {
188   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
189               || TREE_CODE (t) == VAR_DECL);
190
191   if (DECL_FRIEND_CONTEXT (t))
192     push_nested_class (DECL_FRIEND_CONTEXT (t));
193   else if (DECL_CLASS_SCOPE_P (t))
194     push_nested_class (DECL_CONTEXT (t));
195   else
196     push_to_top_level ();
197
198   if (TREE_CODE (t) == FUNCTION_DECL)
199     {
200       saved_access_scope = tree_cons
201         (NULL_TREE, current_function_decl, saved_access_scope);
202       current_function_decl = t;
203     }
204 }
205
206 /* Restore the scope set up by push_access_scope.  T is the node we
207    are processing.  */
208
209 static void
210 pop_access_scope (tree t)
211 {
212   if (TREE_CODE (t) == FUNCTION_DECL)
213     {
214       current_function_decl = TREE_VALUE (saved_access_scope);
215       saved_access_scope = TREE_CHAIN (saved_access_scope);
216     }
217
218   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
219     pop_nested_class ();
220   else
221     pop_from_top_level ();
222 }
223
224 /* Do any processing required when DECL (a member template
225    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
226    to DECL, unless it is a specialization, in which case the DECL
227    itself is returned.  */
228
229 tree
230 finish_member_template_decl (tree decl)
231 {
232   if (decl == error_mark_node)
233     return error_mark_node;
234
235   gcc_assert (DECL_P (decl));
236
237   if (TREE_CODE (decl) == TYPE_DECL)
238     {
239       tree type;
240
241       type = TREE_TYPE (decl);
242       if (type == error_mark_node)
243         return error_mark_node;
244       if (MAYBE_CLASS_TYPE_P (type)
245           && CLASSTYPE_TEMPLATE_INFO (type)
246           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
247         {
248           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
249           check_member_template (tmpl);
250           return tmpl;
251         }
252       return NULL_TREE;
253     }
254   else if (TREE_CODE (decl) == FIELD_DECL)
255     error ("data member %qD cannot be a member template", decl);
256   else if (DECL_TEMPLATE_INFO (decl))
257     {
258       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
259         {
260           check_member_template (DECL_TI_TEMPLATE (decl));
261           return DECL_TI_TEMPLATE (decl);
262         }
263       else
264         return decl;
265     }
266   else
267     error ("invalid member template declaration %qD", decl);
268
269   return error_mark_node;
270 }
271
272 /* Return the template info node corresponding to T, whatever T is.  */
273
274 tree
275 get_template_info (tree t)
276 {
277   tree tinfo = NULL_TREE;
278
279   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
280     tinfo = DECL_TEMPLATE_INFO (t);
281
282   if (!tinfo && TREE_CODE (t) == TYPE_DECL)
283     t = TREE_TYPE (t);
284
285   if (TAGGED_TYPE_P (t))
286     tinfo = TYPE_TEMPLATE_INFO (t);
287
288   return tinfo;
289 }
290
291 /* Returns the template nesting level of the indicated class TYPE.
292
293    For example, in:
294      template <class T>
295      struct A
296      {
297        template <class U>
298        struct B {};
299      };
300
301    A<T>::B<U> has depth two, while A<T> has depth one.
302    Both A<T>::B<int> and A<int>::B<U> have depth one, if
303    they are instantiations, not specializations.
304
305    This function is guaranteed to return 0 if passed NULL_TREE so
306    that, for example, `template_class_depth (current_class_type)' is
307    always safe.  */
308
309 int
310 template_class_depth (tree type)
311 {
312   int depth;
313
314   for (depth = 0;
315        type && TREE_CODE (type) != NAMESPACE_DECL;
316        type = (TREE_CODE (type) == FUNCTION_DECL)
317          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
318     {
319       tree tinfo = get_template_info (type);
320
321       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
322           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
323         ++depth;
324     }
325
326   return depth;
327 }
328
329 /* Subroutine of maybe_begin_member_template_processing.
330    Returns true if processing DECL needs us to push template parms.  */
331
332 static bool
333 inline_needs_template_parms (tree decl)
334 {
335   if (! DECL_TEMPLATE_INFO (decl))
336     return false;
337
338   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
339           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
340 }
341
342 /* Subroutine of maybe_begin_member_template_processing.
343    Push the template parms in PARMS, starting from LEVELS steps into the
344    chain, and ending at the beginning, since template parms are listed
345    innermost first.  */
346
347 static void
348 push_inline_template_parms_recursive (tree parmlist, int levels)
349 {
350   tree parms = TREE_VALUE (parmlist);
351   int i;
352
353   if (levels > 1)
354     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
355
356   ++processing_template_decl;
357   current_template_parms
358     = tree_cons (size_int (processing_template_decl),
359                  parms, current_template_parms);
360   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
361
362   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
363                NULL);
364   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
365     {
366       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
367
368       if (parm == error_mark_node)
369         continue;
370
371       gcc_assert (DECL_P (parm));
372
373       switch (TREE_CODE (parm))
374         {
375         case TYPE_DECL:
376         case TEMPLATE_DECL:
377           pushdecl (parm);
378           break;
379
380         case PARM_DECL:
381           {
382             /* Make a CONST_DECL as is done in process_template_parm.
383                It is ugly that we recreate this here; the original
384                version built in process_template_parm is no longer
385                available.  */
386             tree decl = build_decl (CONST_DECL, DECL_NAME (parm),
387                                     TREE_TYPE (parm));
388             DECL_ARTIFICIAL (decl) = 1;
389             TREE_CONSTANT (decl) = 1;
390             TREE_READONLY (decl) = 1;
391             DECL_INITIAL (decl) = DECL_INITIAL (parm);
392             SET_DECL_TEMPLATE_PARM_P (decl);
393             pushdecl (decl);
394           }
395           break;
396
397         default:
398           gcc_unreachable ();
399         }
400     }
401 }
402
403 /* Restore the template parameter context for a member template or
404    a friend template defined in a class definition.  */
405
406 void
407 maybe_begin_member_template_processing (tree decl)
408 {
409   tree parms;
410   int levels = 0;
411
412   if (inline_needs_template_parms (decl))
413     {
414       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
415       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
416
417       if (DECL_TEMPLATE_SPECIALIZATION (decl))
418         {
419           --levels;
420           parms = TREE_CHAIN (parms);
421         }
422
423       push_inline_template_parms_recursive (parms, levels);
424     }
425
426   /* Remember how many levels of template parameters we pushed so that
427      we can pop them later.  */
428   VEC_safe_push (int, heap, inline_parm_levels, levels);
429 }
430
431 /* Undo the effects of maybe_begin_member_template_processing.  */
432
433 void
434 maybe_end_member_template_processing (void)
435 {
436   int i;
437   int last;
438
439   if (VEC_length (int, inline_parm_levels) == 0)
440     return;
441
442   last = VEC_pop (int, inline_parm_levels);
443   for (i = 0; i < last; ++i)
444     {
445       --processing_template_decl;
446       current_template_parms = TREE_CHAIN (current_template_parms);
447       poplevel (0, 0, 0);
448     }
449 }
450
451 /* Return a new template argument vector which contains all of ARGS,
452    but has as its innermost set of arguments the EXTRA_ARGS.  */
453
454 static tree
455 add_to_template_args (tree args, tree extra_args)
456 {
457   tree new_args;
458   int extra_depth;
459   int i;
460   int j;
461
462   extra_depth = TMPL_ARGS_DEPTH (extra_args);
463   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
464
465   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
466     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
467
468   for (j = 1; j <= extra_depth; ++j, ++i)
469     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
470
471   return new_args;
472 }
473
474 /* Like add_to_template_args, but only the outermost ARGS are added to
475    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
476    (EXTRA_ARGS) levels are added.  This function is used to combine
477    the template arguments from a partial instantiation with the
478    template arguments used to attain the full instantiation from the
479    partial instantiation.  */
480
481 static tree
482 add_outermost_template_args (tree args, tree extra_args)
483 {
484   tree new_args;
485
486   /* If there are more levels of EXTRA_ARGS than there are ARGS,
487      something very fishy is going on.  */
488   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
489
490   /* If *all* the new arguments will be the EXTRA_ARGS, just return
491      them.  */
492   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
493     return extra_args;
494
495   /* For the moment, we make ARGS look like it contains fewer levels.  */
496   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
497
498   new_args = add_to_template_args (args, extra_args);
499
500   /* Now, we restore ARGS to its full dimensions.  */
501   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
502
503   return new_args;
504 }
505
506 /* Return the N levels of innermost template arguments from the ARGS.  */
507
508 tree
509 get_innermost_template_args (tree args, int n)
510 {
511   tree new_args;
512   int extra_levels;
513   int i;
514
515   gcc_assert (n >= 0);
516
517   /* If N is 1, just return the innermost set of template arguments.  */
518   if (n == 1)
519     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
520
521   /* If we're not removing anything, just return the arguments we were
522      given.  */
523   extra_levels = TMPL_ARGS_DEPTH (args) - n;
524   gcc_assert (extra_levels >= 0);
525   if (extra_levels == 0)
526     return args;
527
528   /* Make a new set of arguments, not containing the outer arguments.  */
529   new_args = make_tree_vec (n);
530   for (i = 1; i <= n; ++i)
531     SET_TMPL_ARGS_LEVEL (new_args, i,
532                          TMPL_ARGS_LEVEL (args, i + extra_levels));
533
534   return new_args;
535 }
536
537 /* The inverse of get_innermost_template_args: Return all but the innermost
538    EXTRA_LEVELS levels of template arguments from the ARGS.  */
539
540 static tree
541 strip_innermost_template_args (tree args, int extra_levels)
542 {
543   tree new_args;
544   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
545   int i;
546
547   gcc_assert (n >= 0);
548
549   /* If N is 1, just return the outermost set of template arguments.  */
550   if (n == 1)
551     return TMPL_ARGS_LEVEL (args, 1);
552
553   /* If we're not removing anything, just return the arguments we were
554      given.  */
555   gcc_assert (extra_levels >= 0);
556   if (extra_levels == 0)
557     return args;
558
559   /* Make a new set of arguments, not containing the inner arguments.  */
560   new_args = make_tree_vec (n);
561   for (i = 1; i <= n; ++i)
562     SET_TMPL_ARGS_LEVEL (new_args, i,
563                          TMPL_ARGS_LEVEL (args, i));
564
565   return new_args;
566 }
567
568 /* We've got a template header coming up; push to a new level for storing
569    the parms.  */
570
571 void
572 begin_template_parm_list (void)
573 {
574   /* We use a non-tag-transparent scope here, which causes pushtag to
575      put tags in this scope, rather than in the enclosing class or
576      namespace scope.  This is the right thing, since we want
577      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
578      global template class, push_template_decl handles putting the
579      TEMPLATE_DECL into top-level scope.  For a nested template class,
580      e.g.:
581
582        template <class T> struct S1 {
583          template <class T> struct S2 {};
584        };
585
586      pushtag contains special code to call pushdecl_with_scope on the
587      TEMPLATE_DECL for S2.  */
588   begin_scope (sk_template_parms, NULL);
589   ++processing_template_decl;
590   ++processing_template_parmlist;
591   note_template_header (0);
592 }
593
594 /* This routine is called when a specialization is declared.  If it is
595    invalid to declare a specialization here, an error is reported and
596    false is returned, otherwise this routine will return true.  */
597
598 static bool
599 check_specialization_scope (void)
600 {
601   tree scope = current_scope ();
602
603   /* [temp.expl.spec]
604
605      An explicit specialization shall be declared in the namespace of
606      which the template is a member, or, for member templates, in the
607      namespace of which the enclosing class or enclosing class
608      template is a member.  An explicit specialization of a member
609      function, member class or static data member of a class template
610      shall be declared in the namespace of which the class template
611      is a member.  */
612   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
613     {
614       error ("explicit specialization in non-namespace scope %qD", scope);
615       return false;
616     }
617
618   /* [temp.expl.spec]
619
620      In an explicit specialization declaration for a member of a class
621      template or a member template that appears in namespace scope,
622      the member template and some of its enclosing class templates may
623      remain unspecialized, except that the declaration shall not
624      explicitly specialize a class member template if its enclosing
625      class templates are not explicitly specialized as well.  */
626   if (current_template_parms)
627     {
628       error ("enclosing class templates are not explicitly specialized");
629       return false;
630     }
631
632   return true;
633 }
634
635 /* We've just seen template <>.  */
636
637 bool
638 begin_specialization (void)
639 {
640   begin_scope (sk_template_spec, NULL);
641   note_template_header (1);
642   return check_specialization_scope ();
643 }
644
645 /* Called at then end of processing a declaration preceded by
646    template<>.  */
647
648 void
649 end_specialization (void)
650 {
651   finish_scope ();
652   reset_specialization ();
653 }
654
655 /* Any template <>'s that we have seen thus far are not referring to a
656    function specialization.  */
657
658 void
659 reset_specialization (void)
660 {
661   processing_specialization = 0;
662   template_header_count = 0;
663 }
664
665 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
666    it was of the form template <>.  */
667
668 static void
669 note_template_header (int specialization)
670 {
671   processing_specialization = specialization;
672   template_header_count++;
673 }
674
675 /* We're beginning an explicit instantiation.  */
676
677 void
678 begin_explicit_instantiation (void)
679 {
680   gcc_assert (!processing_explicit_instantiation);
681   processing_explicit_instantiation = true;
682 }
683
684
685 void
686 end_explicit_instantiation (void)
687 {
688   gcc_assert (processing_explicit_instantiation);
689   processing_explicit_instantiation = false;
690 }
691
692 /* An explicit specialization or partial specialization TMPL is being
693    declared.  Check that the namespace in which the specialization is
694    occurring is permissible.  Returns false iff it is invalid to
695    specialize TMPL in the current namespace.  */
696
697 static bool
698 check_specialization_namespace (tree tmpl)
699 {
700   tree tpl_ns = decl_namespace_context (tmpl);
701
702   /* [tmpl.expl.spec]
703
704      An explicit specialization shall be declared in the namespace of
705      which the template is a member, or, for member templates, in the
706      namespace of which the enclosing class or enclosing class
707      template is a member.  An explicit specialization of a member
708      function, member class or static data member of a class template
709      shall be declared in the namespace of which the class template is
710      a member.  */
711   if (is_associated_namespace (current_namespace, tpl_ns))
712     /* Same or super-using namespace.  */
713     return true;
714   else
715     {
716       permerror (input_location, "specialization of %qD in different namespace", tmpl);
717       permerror (input_location, "  from definition of %q+#D", tmpl);
718       return false;
719     }
720 }
721
722 /* SPEC is an explicit instantiation.  Check that it is valid to
723    perform this explicit instantiation in the current namespace.  */
724
725 static void
726 check_explicit_instantiation_namespace (tree spec)
727 {
728   tree ns;
729
730   /* DR 275: An explicit instantiation shall appear in an enclosing
731      namespace of its template.  */
732   ns = decl_namespace_context (spec);
733   if (!is_ancestor (current_namespace, ns))
734     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
735                "(which does not enclose namespace %qD)",
736                spec, current_namespace, ns);
737 }
738
739 /* The TYPE is being declared.  If it is a template type, that means it
740    is a partial specialization.  Do appropriate error-checking.  */
741
742 tree
743 maybe_process_partial_specialization (tree type)
744 {
745   tree context;
746
747   if (type == error_mark_node)
748     return error_mark_node;
749
750   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
751     {
752       error ("name of class shadows template template parameter %qD",
753              TYPE_NAME (type));
754       return error_mark_node;
755     }
756
757   context = TYPE_CONTEXT (type);
758
759   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
760     {
761       /* This is for ordinary explicit specialization and partial
762          specialization of a template class such as:
763
764            template <> class C<int>;
765
766          or:
767
768            template <class T> class C<T*>;
769
770          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
771
772       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
773           && !COMPLETE_TYPE_P (type))
774         {
775           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
776           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
777           if (processing_template_decl)
778             {
779               if (push_template_decl (TYPE_MAIN_DECL (type))
780                   == error_mark_node)
781                 return error_mark_node;
782             }
783         }
784       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
785         error ("specialization of %qT after instantiation", type);
786     }
787   else if (CLASS_TYPE_P (type)
788            && !CLASSTYPE_USE_TEMPLATE (type)
789            && CLASSTYPE_TEMPLATE_INFO (type)
790            && context && CLASS_TYPE_P (context)
791            && CLASSTYPE_TEMPLATE_INFO (context))
792     {
793       /* This is for an explicit specialization of member class
794          template according to [temp.expl.spec/18]:
795
796            template <> template <class U> class C<int>::D;
797
798          The context `C<int>' must be an implicit instantiation.
799          Otherwise this is just a member class template declared
800          earlier like:
801
802            template <> class C<int> { template <class U> class D; };
803            template <> template <class U> class C<int>::D;
804
805          In the first case, `C<int>::D' is a specialization of `C<T>::D'
806          while in the second case, `C<int>::D' is a primary template
807          and `C<T>::D' may not exist.  */
808
809       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
810           && !COMPLETE_TYPE_P (type))
811         {
812           tree t;
813
814           if (current_namespace
815               != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
816             {
817               permerror (input_location, "specializing %q#T in different namespace", type);
818               permerror (input_location, "  from definition of %q+#D",
819                          CLASSTYPE_TI_TEMPLATE (type));
820             }
821
822           /* Check for invalid specialization after instantiation:
823
824                template <> template <> class C<int>::D<int>;
825                template <> template <class U> class C<int>::D;  */
826
827           for (t = DECL_TEMPLATE_INSTANTIATIONS
828                  (most_general_template (CLASSTYPE_TI_TEMPLATE (type)));
829                t; t = TREE_CHAIN (t))
830             if (TREE_VALUE (t) != type
831                 && TYPE_CONTEXT (TREE_VALUE (t)) == context)
832               error ("specialization %qT after instantiation %qT",
833                      type, TREE_VALUE (t));
834
835           /* Mark TYPE as a specialization.  And as a result, we only
836              have one level of template argument for the innermost
837              class template.  */
838           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
839           CLASSTYPE_TI_ARGS (type)
840             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
841         }
842     }
843   else if (processing_specialization)
844     {
845       error ("explicit specialization of non-template %qT", type);
846       return error_mark_node;
847     }
848
849   return type;
850 }
851
852 /* Returns nonzero if we can optimize the retrieval of specializations
853    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
854    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
855
856 static inline bool
857 optimize_specialization_lookup_p (tree tmpl)
858 {
859   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
860           && DECL_CLASS_SCOPE_P (tmpl)
861           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
862              parameter.  */
863           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
864           /* The optimized lookup depends on the fact that the
865              template arguments for the member function template apply
866              purely to the containing class, which is not true if the
867              containing class is an explicit or partial
868              specialization.  */
869           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
870           && !DECL_MEMBER_TEMPLATE_P (tmpl)
871           && !DECL_CONV_FN_P (tmpl)
872           /* It is possible to have a template that is not a member
873              template and is not a member of a template class:
874
875              template <typename T>
876              struct S { friend A::f(); };
877
878              Here, the friend function is a template, but the context does
879              not have template information.  The optimized lookup relies
880              on having ARGS be the template arguments for both the class
881              and the function template.  */
882           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
883 }
884
885 /* Retrieve the specialization (in the sense of [temp.spec] - a
886    specialization is either an instantiation or an explicit
887    specialization) of TMPL for the given template ARGS.  If there is
888    no such specialization, return NULL_TREE.  The ARGS are a vector of
889    arguments, or a vector of vectors of arguments, in the case of
890    templates with more than one level of parameters.
891
892    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
893    then we search for a partial specialization matching ARGS.  This
894    parameter is ignored if TMPL is not a class template.  */
895
896 static tree
897 retrieve_specialization (tree tmpl, tree args,
898                          bool class_specializations_p)
899 {
900   if (args == error_mark_node)
901     return NULL_TREE;
902
903   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
904
905   /* There should be as many levels of arguments as there are
906      levels of parameters.  */
907   gcc_assert (TMPL_ARGS_DEPTH (args)
908               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
909
910   if (optimize_specialization_lookup_p (tmpl))
911     {
912       tree class_template;
913       tree class_specialization;
914       VEC(tree,gc) *methods;
915       tree fns;
916       int idx;
917
918       /* The template arguments actually apply to the containing
919          class.  Find the class specialization with those
920          arguments.  */
921       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
922       class_specialization
923         = retrieve_specialization (class_template, args,
924                                    /*class_specializations_p=*/false);
925       if (!class_specialization)
926         return NULL_TREE;
927       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
928          for the specialization.  */
929       idx = class_method_index_for_fn (class_specialization, tmpl);
930       if (idx == -1)
931         return NULL_TREE;
932       /* Iterate through the methods with the indicated name, looking
933          for the one that has an instance of TMPL.  */
934       methods = CLASSTYPE_METHOD_VEC (class_specialization);
935       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
936         {
937           tree fn = OVL_CURRENT (fns);
938           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl)
939             return fn;
940         }
941       return NULL_TREE;
942     }
943   else
944     {
945       tree *sp;
946       tree *head;
947
948       /* Class templates store their instantiations on the
949          DECL_TEMPLATE_INSTANTIATIONS list; other templates use the
950          DECL_TEMPLATE_SPECIALIZATIONS list.  */
951       if (!class_specializations_p
952           && TREE_CODE (DECL_TEMPLATE_RESULT (tmpl)) == TYPE_DECL
953           && !is_typedef_decl (DECL_TEMPLATE_RESULT (tmpl))
954           && TAGGED_TYPE_P (TREE_TYPE (tmpl)))
955         sp = &DECL_TEMPLATE_INSTANTIATIONS (tmpl);
956       else
957         sp = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
958       head = sp;
959       /* Iterate through the list until we find a matching template.  */
960       while (*sp != NULL_TREE)
961         {
962           tree spec = *sp;
963
964           if (comp_template_args (TREE_PURPOSE (spec), args))
965             {
966               /* Use the move-to-front heuristic to speed up future
967                  searches.  */
968               if (spec != *head)
969                 {
970                   *sp = TREE_CHAIN (*sp);
971                   TREE_CHAIN (spec) = *head;
972                   *head = spec;
973                 }
974               return TREE_VALUE (spec);
975             }
976           sp = &TREE_CHAIN (spec);
977         }
978     }
979
980   return NULL_TREE;
981 }
982
983 /* Like retrieve_specialization, but for local declarations.  */
984
985 static tree
986 retrieve_local_specialization (tree tmpl)
987 {
988   tree spec;
989
990   if (local_specializations == NULL)
991     return NULL_TREE;
992
993   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
994                                      htab_hash_pointer (tmpl));
995   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
996 }
997
998 /* Returns nonzero iff DECL is a specialization of TMPL.  */
999
1000 int
1001 is_specialization_of (tree decl, tree tmpl)
1002 {
1003   tree t;
1004
1005   if (TREE_CODE (decl) == FUNCTION_DECL)
1006     {
1007       for (t = decl;
1008            t != NULL_TREE;
1009            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1010         if (t == tmpl)
1011           return 1;
1012     }
1013   else
1014     {
1015       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1016
1017       for (t = TREE_TYPE (decl);
1018            t != NULL_TREE;
1019            t = CLASSTYPE_USE_TEMPLATE (t)
1020              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1021         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1022           return 1;
1023     }
1024
1025   return 0;
1026 }
1027
1028 /* Returns nonzero iff DECL is a specialization of friend declaration
1029    FRIEND_DECL according to [temp.friend].  */
1030
1031 bool
1032 is_specialization_of_friend (tree decl, tree friend_decl)
1033 {
1034   bool need_template = true;
1035   int template_depth;
1036
1037   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1038               || TREE_CODE (decl) == TYPE_DECL);
1039
1040   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1041      of a template class, we want to check if DECL is a specialization
1042      if this.  */
1043   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1044       && DECL_TEMPLATE_INFO (friend_decl)
1045       && !DECL_USE_TEMPLATE (friend_decl))
1046     {
1047       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1048       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1049       need_template = false;
1050     }
1051   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1052            && !PRIMARY_TEMPLATE_P (friend_decl))
1053     need_template = false;
1054
1055   /* There is nothing to do if this is not a template friend.  */
1056   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1057     return false;
1058
1059   if (is_specialization_of (decl, friend_decl))
1060     return true;
1061
1062   /* [temp.friend/6]
1063      A member of a class template may be declared to be a friend of a
1064      non-template class.  In this case, the corresponding member of
1065      every specialization of the class template is a friend of the
1066      class granting friendship.
1067
1068      For example, given a template friend declaration
1069
1070        template <class T> friend void A<T>::f();
1071
1072      the member function below is considered a friend
1073
1074        template <> struct A<int> {
1075          void f();
1076        };
1077
1078      For this type of template friend, TEMPLATE_DEPTH below will be
1079      nonzero.  To determine if DECL is a friend of FRIEND, we first
1080      check if the enclosing class is a specialization of another.  */
1081
1082   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1083   if (template_depth
1084       && DECL_CLASS_SCOPE_P (decl)
1085       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1086                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1087     {
1088       /* Next, we check the members themselves.  In order to handle
1089          a few tricky cases, such as when FRIEND_DECL's are
1090
1091            template <class T> friend void A<T>::g(T t);
1092            template <class T> template <T t> friend void A<T>::h();
1093
1094          and DECL's are
1095
1096            void A<int>::g(int);
1097            template <int> void A<int>::h();
1098
1099          we need to figure out ARGS, the template arguments from
1100          the context of DECL.  This is required for template substitution
1101          of `T' in the function parameter of `g' and template parameter
1102          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1103
1104       tree context = DECL_CONTEXT (decl);
1105       tree args = NULL_TREE;
1106       int current_depth = 0;
1107
1108       while (current_depth < template_depth)
1109         {
1110           if (CLASSTYPE_TEMPLATE_INFO (context))
1111             {
1112               if (current_depth == 0)
1113                 args = TYPE_TI_ARGS (context);
1114               else
1115                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1116               current_depth++;
1117             }
1118           context = TYPE_CONTEXT (context);
1119         }
1120
1121       if (TREE_CODE (decl) == FUNCTION_DECL)
1122         {
1123           bool is_template;
1124           tree friend_type;
1125           tree decl_type;
1126           tree friend_args_type;
1127           tree decl_args_type;
1128
1129           /* Make sure that both DECL and FRIEND_DECL are templates or
1130              non-templates.  */
1131           is_template = DECL_TEMPLATE_INFO (decl)
1132                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1133           if (need_template ^ is_template)
1134             return false;
1135           else if (is_template)
1136             {
1137               /* If both are templates, check template parameter list.  */
1138               tree friend_parms
1139                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1140                                          args, tf_none);
1141               if (!comp_template_parms
1142                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1143                       friend_parms))
1144                 return false;
1145
1146               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1147             }
1148           else
1149             decl_type = TREE_TYPE (decl);
1150
1151           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1152                                               tf_none, NULL_TREE);
1153           if (friend_type == error_mark_node)
1154             return false;
1155
1156           /* Check if return types match.  */
1157           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1158             return false;
1159
1160           /* Check if function parameter types match, ignoring the
1161              `this' parameter.  */
1162           friend_args_type = TYPE_ARG_TYPES (friend_type);
1163           decl_args_type = TYPE_ARG_TYPES (decl_type);
1164           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1165             friend_args_type = TREE_CHAIN (friend_args_type);
1166           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1167             decl_args_type = TREE_CHAIN (decl_args_type);
1168
1169           return compparms (decl_args_type, friend_args_type);
1170         }
1171       else
1172         {
1173           /* DECL is a TYPE_DECL */
1174           bool is_template;
1175           tree decl_type = TREE_TYPE (decl);
1176
1177           /* Make sure that both DECL and FRIEND_DECL are templates or
1178              non-templates.  */
1179           is_template
1180             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1181               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1182
1183           if (need_template ^ is_template)
1184             return false;
1185           else if (is_template)
1186             {
1187               tree friend_parms;
1188               /* If both are templates, check the name of the two
1189                  TEMPLATE_DECL's first because is_friend didn't.  */
1190               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1191                   != DECL_NAME (friend_decl))
1192                 return false;
1193
1194               /* Now check template parameter list.  */
1195               friend_parms
1196                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1197                                          args, tf_none);
1198               return comp_template_parms
1199                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1200                  friend_parms);
1201             }
1202           else
1203             return (DECL_NAME (decl)
1204                     == DECL_NAME (friend_decl));
1205         }
1206     }
1207   return false;
1208 }
1209
1210 /* Register the specialization SPEC as a specialization of TMPL with
1211    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1212    is actually just a friend declaration.  Returns SPEC, or an
1213    equivalent prior declaration, if available.  */
1214
1215 static tree
1216 register_specialization (tree spec, tree tmpl, tree args, bool is_friend)
1217 {
1218   tree fn;
1219
1220   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1221
1222   if (TREE_CODE (spec) == FUNCTION_DECL
1223       && uses_template_parms (DECL_TI_ARGS (spec)))
1224     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1225        register it; we want the corresponding TEMPLATE_DECL instead.
1226        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1227        the more obvious `uses_template_parms (spec)' to avoid problems
1228        with default function arguments.  In particular, given
1229        something like this:
1230
1231           template <class T> void f(T t1, T t = T())
1232
1233        the default argument expression is not substituted for in an
1234        instantiation unless and until it is actually needed.  */
1235     return spec;
1236
1237   fn = retrieve_specialization (tmpl, args,
1238                                 /*class_specializations_p=*/false);
1239   /* We can sometimes try to re-register a specialization that we've
1240      already got.  In particular, regenerate_decl_from_template calls
1241      duplicate_decls which will update the specialization list.  But,
1242      we'll still get called again here anyhow.  It's more convenient
1243      to simply allow this than to try to prevent it.  */
1244   if (fn == spec)
1245     return spec;
1246   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1247     {
1248       if (DECL_TEMPLATE_INSTANTIATION (fn))
1249         {
1250           if (TREE_USED (fn)
1251               || DECL_EXPLICIT_INSTANTIATION (fn))
1252             {
1253               error ("specialization of %qD after instantiation",
1254                      fn);
1255               return error_mark_node;
1256             }
1257           else
1258             {
1259               tree clone;
1260               /* This situation should occur only if the first
1261                  specialization is an implicit instantiation, the
1262                  second is an explicit specialization, and the
1263                  implicit instantiation has not yet been used.  That
1264                  situation can occur if we have implicitly
1265                  instantiated a member function and then specialized
1266                  it later.
1267
1268                  We can also wind up here if a friend declaration that
1269                  looked like an instantiation turns out to be a
1270                  specialization:
1271
1272                    template <class T> void foo(T);
1273                    class S { friend void foo<>(int) };
1274                    template <> void foo(int);
1275
1276                  We transform the existing DECL in place so that any
1277                  pointers to it become pointers to the updated
1278                  declaration.
1279
1280                  If there was a definition for the template, but not
1281                  for the specialization, we want this to look as if
1282                  there were no definition, and vice versa.  */
1283               DECL_INITIAL (fn) = NULL_TREE;
1284               duplicate_decls (spec, fn, is_friend);
1285               /* The call to duplicate_decls will have applied
1286                  [temp.expl.spec]:
1287
1288                    An explicit specialization of a function template
1289                    is inline only if it is explicitly declared to be,
1290                    and independently of whether its function template
1291                    is.
1292
1293                 to the primary function; now copy the inline bits to
1294                 the various clones.  */
1295               FOR_EACH_CLONE (clone, fn)
1296                 DECL_DECLARED_INLINE_P (clone)
1297                   = DECL_DECLARED_INLINE_P (fn);
1298               check_specialization_namespace (fn);
1299
1300               return fn;
1301             }
1302         }
1303       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1304         {
1305           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1306             /* Dup decl failed, but this is a new definition. Set the
1307                line number so any errors match this new
1308                definition.  */
1309             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1310
1311           return fn;
1312         }
1313     }
1314
1315   /* A specialization must be declared in the same namespace as the
1316      template it is specializing.  */
1317   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1318       && !check_specialization_namespace (tmpl))
1319     DECL_CONTEXT (spec) = FROB_CONTEXT (decl_namespace_context (tmpl));
1320
1321   if (!optimize_specialization_lookup_p (tmpl))
1322     DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
1323       = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
1324
1325   return spec;
1326 }
1327
1328 /* Unregister the specialization SPEC as a specialization of TMPL.
1329    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1330    if the SPEC was listed as a specialization of TMPL.  */
1331
1332 bool
1333 reregister_specialization (tree spec, tree tmpl, tree new_spec)
1334 {
1335   tree* s;
1336
1337   for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
1338        *s != NULL_TREE;
1339        s = &TREE_CHAIN (*s))
1340     if (TREE_VALUE (*s) == spec)
1341       {
1342         if (!new_spec)
1343           *s = TREE_CHAIN (*s);
1344         else
1345           TREE_VALUE (*s) = new_spec;
1346         return 1;
1347       }
1348
1349   return 0;
1350 }
1351
1352 /* Compare an entry in the local specializations hash table P1 (which
1353    is really a pointer to a TREE_LIST) with P2 (which is really a
1354    DECL).  */
1355
1356 static int
1357 eq_local_specializations (const void *p1, const void *p2)
1358 {
1359   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1360 }
1361
1362 /* Hash P1, an entry in the local specializations table.  */
1363
1364 static hashval_t
1365 hash_local_specialization (const void* p1)
1366 {
1367   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1368 }
1369
1370 /* Like register_specialization, but for local declarations.  We are
1371    registering SPEC, an instantiation of TMPL.  */
1372
1373 static void
1374 register_local_specialization (tree spec, tree tmpl)
1375 {
1376   void **slot;
1377
1378   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1379                                    htab_hash_pointer (tmpl), INSERT);
1380   *slot = build_tree_list (spec, tmpl);
1381 }
1382
1383 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1384    specialized class.  */
1385
1386 bool
1387 explicit_class_specialization_p (tree type)
1388 {
1389   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1390     return false;
1391   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1392 }
1393
1394 /* Print the list of candidate FNS in an error message.  */
1395
1396 void
1397 print_candidates (tree fns)
1398 {
1399   tree fn;
1400
1401   const char *str = "candidates are:";
1402
1403   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1404     {
1405       tree f;
1406
1407       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1408         error ("%s %+#D", str, OVL_CURRENT (f));
1409       str = "               ";
1410     }
1411 }
1412
1413 /* Returns the template (one of the functions given by TEMPLATE_ID)
1414    which can be specialized to match the indicated DECL with the
1415    explicit template args given in TEMPLATE_ID.  The DECL may be
1416    NULL_TREE if none is available.  In that case, the functions in
1417    TEMPLATE_ID are non-members.
1418
1419    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1420    specialization of a member template.
1421
1422    The TEMPLATE_COUNT is the number of references to qualifying
1423    template classes that appeared in the name of the function. See
1424    check_explicit_specialization for a more accurate description.
1425
1426    TSK indicates what kind of template declaration (if any) is being
1427    declared.  TSK_TEMPLATE indicates that the declaration given by
1428    DECL, though a FUNCTION_DECL, has template parameters, and is
1429    therefore a template function.
1430
1431    The template args (those explicitly specified and those deduced)
1432    are output in a newly created vector *TARGS_OUT.
1433
1434    If it is impossible to determine the result, an error message is
1435    issued.  The error_mark_node is returned to indicate failure.  */
1436
1437 static tree
1438 determine_specialization (tree template_id,
1439                           tree decl,
1440                           tree* targs_out,
1441                           int need_member_template,
1442                           int template_count,
1443                           tmpl_spec_kind tsk)
1444 {
1445   tree fns;
1446   tree targs;
1447   tree explicit_targs;
1448   tree candidates = NULL_TREE;
1449   /* A TREE_LIST of templates of which DECL may be a specialization.
1450      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1451      corresponding TREE_PURPOSE is the set of template arguments that,
1452      when used to instantiate the template, would produce a function
1453      with the signature of DECL.  */
1454   tree templates = NULL_TREE;
1455   int header_count;
1456   struct cp_binding_level *b;
1457
1458   *targs_out = NULL_TREE;
1459
1460   if (template_id == error_mark_node || decl == error_mark_node)
1461     return error_mark_node;
1462
1463   fns = TREE_OPERAND (template_id, 0);
1464   explicit_targs = TREE_OPERAND (template_id, 1);
1465
1466   if (fns == error_mark_node)
1467     return error_mark_node;
1468
1469   /* Check for baselinks.  */
1470   if (BASELINK_P (fns))
1471     fns = BASELINK_FUNCTIONS (fns);
1472
1473   if (!is_overloaded_fn (fns))
1474     {
1475       error ("%qD is not a function template", fns);
1476       return error_mark_node;
1477     }
1478
1479   /* Count the number of template headers specified for this
1480      specialization.  */
1481   header_count = 0;
1482   for (b = current_binding_level;
1483        b->kind == sk_template_parms;
1484        b = b->level_chain)
1485     ++header_count;
1486
1487   for (; fns; fns = OVL_NEXT (fns))
1488     {
1489       tree fn = OVL_CURRENT (fns);
1490
1491       if (TREE_CODE (fn) == TEMPLATE_DECL)
1492         {
1493           tree decl_arg_types;
1494           tree fn_arg_types;
1495
1496           /* In case of explicit specialization, we need to check if
1497              the number of template headers appearing in the specialization
1498              is correct. This is usually done in check_explicit_specialization,
1499              but the check done there cannot be exhaustive when specializing
1500              member functions. Consider the following code:
1501
1502              template <> void A<int>::f(int);
1503              template <> template <> void A<int>::f(int);
1504
1505              Assuming that A<int> is not itself an explicit specialization
1506              already, the first line specializes "f" which is a non-template
1507              member function, whilst the second line specializes "f" which
1508              is a template member function. So both lines are syntactically
1509              correct, and check_explicit_specialization does not reject
1510              them.
1511
1512              Here, we can do better, as we are matching the specialization
1513              against the declarations. We count the number of template
1514              headers, and we check if they match TEMPLATE_COUNT + 1
1515              (TEMPLATE_COUNT is the number of qualifying template classes,
1516              plus there must be another header for the member template
1517              itself).
1518
1519              Notice that if header_count is zero, this is not a
1520              specialization but rather a template instantiation, so there
1521              is no check we can perform here.  */
1522           if (header_count && header_count != template_count + 1)
1523             continue;
1524
1525           /* Check that the number of template arguments at the
1526              innermost level for DECL is the same as for FN.  */
1527           if (current_binding_level->kind == sk_template_parms
1528               && !current_binding_level->explicit_spec_p
1529               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1530                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1531                                       (current_template_parms))))
1532             continue;
1533
1534           /* DECL might be a specialization of FN.  */
1535           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1536           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1537
1538           /* For a non-static member function, we need to make sure
1539              that the const qualification is the same.  Since
1540              get_bindings does not try to merge the "this" parameter,
1541              we must do the comparison explicitly.  */
1542           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1543               && !same_type_p (TREE_VALUE (fn_arg_types),
1544                                TREE_VALUE (decl_arg_types)))
1545             continue;
1546
1547           /* Skip the "this" parameter and, for constructors of
1548              classes with virtual bases, the VTT parameter.  A
1549              full specialization of a constructor will have a VTT
1550              parameter, but a template never will.  */ 
1551           decl_arg_types 
1552             = skip_artificial_parms_for (decl, decl_arg_types);
1553           fn_arg_types 
1554             = skip_artificial_parms_for (fn, fn_arg_types);
1555
1556           /* Check that the number of function parameters matches.
1557              For example,
1558                template <class T> void f(int i = 0);
1559                template <> void f<int>();
1560              The specialization f<int> is invalid but is not caught
1561              by get_bindings below.  */
1562           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1563             continue;
1564
1565           /* Function templates cannot be specializations; there are
1566              no partial specializations of functions.  Therefore, if
1567              the type of DECL does not match FN, there is no
1568              match.  */
1569           if (tsk == tsk_template)
1570             {
1571               if (compparms (fn_arg_types, decl_arg_types))
1572                 candidates = tree_cons (NULL_TREE, fn, candidates);
1573               continue;
1574             }
1575
1576           /* See whether this function might be a specialization of this
1577              template.  */
1578           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1579
1580           if (!targs)
1581             /* We cannot deduce template arguments that when used to
1582                specialize TMPL will produce DECL.  */
1583             continue;
1584
1585           /* Save this template, and the arguments deduced.  */
1586           templates = tree_cons (targs, fn, templates);
1587         }
1588       else if (need_member_template)
1589         /* FN is an ordinary member function, and we need a
1590            specialization of a member template.  */
1591         ;
1592       else if (TREE_CODE (fn) != FUNCTION_DECL)
1593         /* We can get IDENTIFIER_NODEs here in certain erroneous
1594            cases.  */
1595         ;
1596       else if (!DECL_FUNCTION_MEMBER_P (fn))
1597         /* This is just an ordinary non-member function.  Nothing can
1598            be a specialization of that.  */
1599         ;
1600       else if (DECL_ARTIFICIAL (fn))
1601         /* Cannot specialize functions that are created implicitly.  */
1602         ;
1603       else
1604         {
1605           tree decl_arg_types;
1606
1607           /* This is an ordinary member function.  However, since
1608              we're here, we can assume it's enclosing class is a
1609              template class.  For example,
1610
1611                template <typename T> struct S { void f(); };
1612                template <> void S<int>::f() {}
1613
1614              Here, S<int>::f is a non-template, but S<int> is a
1615              template class.  If FN has the same type as DECL, we
1616              might be in business.  */
1617
1618           if (!DECL_TEMPLATE_INFO (fn))
1619             /* Its enclosing class is an explicit specialization
1620                of a template class.  This is not a candidate.  */
1621             continue;
1622
1623           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1624                             TREE_TYPE (TREE_TYPE (fn))))
1625             /* The return types differ.  */
1626             continue;
1627
1628           /* Adjust the type of DECL in case FN is a static member.  */
1629           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1630           if (DECL_STATIC_FUNCTION_P (fn)
1631               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1632             decl_arg_types = TREE_CHAIN (decl_arg_types);
1633
1634           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1635                          decl_arg_types))
1636             /* They match!  */
1637             candidates = tree_cons (NULL_TREE, fn, candidates);
1638         }
1639     }
1640
1641   if (templates && TREE_CHAIN (templates))
1642     {
1643       /* We have:
1644
1645            [temp.expl.spec]
1646
1647            It is possible for a specialization with a given function
1648            signature to be instantiated from more than one function
1649            template.  In such cases, explicit specification of the
1650            template arguments must be used to uniquely identify the
1651            function template specialization being specialized.
1652
1653          Note that here, there's no suggestion that we're supposed to
1654          determine which of the candidate templates is most
1655          specialized.  However, we, also have:
1656
1657            [temp.func.order]
1658
1659            Partial ordering of overloaded function template
1660            declarations is used in the following contexts to select
1661            the function template to which a function template
1662            specialization refers:
1663
1664            -- when an explicit specialization refers to a function
1665               template.
1666
1667          So, we do use the partial ordering rules, at least for now.
1668          This extension can only serve to make invalid programs valid,
1669          so it's safe.  And, there is strong anecdotal evidence that
1670          the committee intended the partial ordering rules to apply;
1671          the EDG front end has that behavior, and John Spicer claims
1672          that the committee simply forgot to delete the wording in
1673          [temp.expl.spec].  */
1674       tree tmpl = most_specialized_instantiation (templates);
1675       if (tmpl != error_mark_node)
1676         {
1677           templates = tmpl;
1678           TREE_CHAIN (templates) = NULL_TREE;
1679         }
1680     }
1681
1682   if (templates == NULL_TREE && candidates == NULL_TREE)
1683     {
1684       error ("template-id %qD for %q+D does not match any template "
1685              "declaration", template_id, decl);
1686       return error_mark_node;
1687     }
1688   else if ((templates && TREE_CHAIN (templates))
1689            || (candidates && TREE_CHAIN (candidates))
1690            || (templates && candidates))
1691     {
1692       error ("ambiguous template specialization %qD for %q+D",
1693              template_id, decl);
1694       chainon (candidates, templates);
1695       print_candidates (candidates);
1696       return error_mark_node;
1697     }
1698
1699   /* We have one, and exactly one, match.  */
1700   if (candidates)
1701     {
1702       tree fn = TREE_VALUE (candidates);
1703       /* DECL is a re-declaration of a template function.  */
1704       if (TREE_CODE (fn) == TEMPLATE_DECL)
1705         return fn;
1706       /* It was a specialization of an ordinary member function in a
1707          template class.  */
1708       *targs_out = copy_node (DECL_TI_ARGS (fn));
1709       return DECL_TI_TEMPLATE (fn);
1710     }
1711
1712   /* It was a specialization of a template.  */
1713   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1714   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1715     {
1716       *targs_out = copy_node (targs);
1717       SET_TMPL_ARGS_LEVEL (*targs_out,
1718                            TMPL_ARGS_DEPTH (*targs_out),
1719                            TREE_PURPOSE (templates));
1720     }
1721   else
1722     *targs_out = TREE_PURPOSE (templates);
1723   return TREE_VALUE (templates);
1724 }
1725
1726 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1727    but with the default argument values filled in from those in the
1728    TMPL_TYPES.  */
1729
1730 static tree
1731 copy_default_args_to_explicit_spec_1 (tree spec_types,
1732                                       tree tmpl_types)
1733 {
1734   tree new_spec_types;
1735
1736   if (!spec_types)
1737     return NULL_TREE;
1738
1739   if (spec_types == void_list_node)
1740     return void_list_node;
1741
1742   /* Substitute into the rest of the list.  */
1743   new_spec_types =
1744     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1745                                           TREE_CHAIN (tmpl_types));
1746
1747   /* Add the default argument for this parameter.  */
1748   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1749                          TREE_VALUE (spec_types),
1750                          new_spec_types);
1751 }
1752
1753 /* DECL is an explicit specialization.  Replicate default arguments
1754    from the template it specializes.  (That way, code like:
1755
1756      template <class T> void f(T = 3);
1757      template <> void f(double);
1758      void g () { f (); }
1759
1760    works, as required.)  An alternative approach would be to look up
1761    the correct default arguments at the call-site, but this approach
1762    is consistent with how implicit instantiations are handled.  */
1763
1764 static void
1765 copy_default_args_to_explicit_spec (tree decl)
1766 {
1767   tree tmpl;
1768   tree spec_types;
1769   tree tmpl_types;
1770   tree new_spec_types;
1771   tree old_type;
1772   tree new_type;
1773   tree t;
1774   tree object_type = NULL_TREE;
1775   tree in_charge = NULL_TREE;
1776   tree vtt = NULL_TREE;
1777
1778   /* See if there's anything we need to do.  */
1779   tmpl = DECL_TI_TEMPLATE (decl);
1780   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
1781   for (t = tmpl_types; t; t = TREE_CHAIN (t))
1782     if (TREE_PURPOSE (t))
1783       break;
1784   if (!t)
1785     return;
1786
1787   old_type = TREE_TYPE (decl);
1788   spec_types = TYPE_ARG_TYPES (old_type);
1789
1790   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1791     {
1792       /* Remove the this pointer, but remember the object's type for
1793          CV quals.  */
1794       object_type = TREE_TYPE (TREE_VALUE (spec_types));
1795       spec_types = TREE_CHAIN (spec_types);
1796       tmpl_types = TREE_CHAIN (tmpl_types);
1797
1798       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
1799         {
1800           /* DECL may contain more parameters than TMPL due to the extra
1801              in-charge parameter in constructors and destructors.  */
1802           in_charge = spec_types;
1803           spec_types = TREE_CHAIN (spec_types);
1804         }
1805       if (DECL_HAS_VTT_PARM_P (decl))
1806         {
1807           vtt = spec_types;
1808           spec_types = TREE_CHAIN (spec_types);
1809         }
1810     }
1811
1812   /* Compute the merged default arguments.  */
1813   new_spec_types =
1814     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
1815
1816   /* Compute the new FUNCTION_TYPE.  */
1817   if (object_type)
1818     {
1819       if (vtt)
1820         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
1821                                          TREE_VALUE (vtt),
1822                                          new_spec_types);
1823
1824       if (in_charge)
1825         /* Put the in-charge parameter back.  */
1826         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
1827                                          TREE_VALUE (in_charge),
1828                                          new_spec_types);
1829
1830       new_type = build_method_type_directly (object_type,
1831                                              TREE_TYPE (old_type),
1832                                              new_spec_types);
1833     }
1834   else
1835     new_type = build_function_type (TREE_TYPE (old_type),
1836                                     new_spec_types);
1837   new_type = cp_build_type_attribute_variant (new_type,
1838                                               TYPE_ATTRIBUTES (old_type));
1839   new_type = build_exception_variant (new_type,
1840                                       TYPE_RAISES_EXCEPTIONS (old_type));
1841   TREE_TYPE (decl) = new_type;
1842 }
1843
1844 /* Check to see if the function just declared, as indicated in
1845    DECLARATOR, and in DECL, is a specialization of a function
1846    template.  We may also discover that the declaration is an explicit
1847    instantiation at this point.
1848
1849    Returns DECL, or an equivalent declaration that should be used
1850    instead if all goes well.  Issues an error message if something is
1851    amiss.  Returns error_mark_node if the error is not easily
1852    recoverable.
1853
1854    FLAGS is a bitmask consisting of the following flags:
1855
1856    2: The function has a definition.
1857    4: The function is a friend.
1858
1859    The TEMPLATE_COUNT is the number of references to qualifying
1860    template classes that appeared in the name of the function.  For
1861    example, in
1862
1863      template <class T> struct S { void f(); };
1864      void S<int>::f();
1865
1866    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
1867    classes are not counted in the TEMPLATE_COUNT, so that in
1868
1869      template <class T> struct S {};
1870      template <> struct S<int> { void f(); }
1871      template <> void S<int>::f();
1872
1873    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
1874    invalid; there should be no template <>.)
1875
1876    If the function is a specialization, it is marked as such via
1877    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
1878    is set up correctly, and it is added to the list of specializations
1879    for that template.  */
1880
1881 tree
1882 check_explicit_specialization (tree declarator,
1883                                tree decl,
1884                                int template_count,
1885                                int flags)
1886 {
1887   int have_def = flags & 2;
1888   int is_friend = flags & 4;
1889   int specialization = 0;
1890   int explicit_instantiation = 0;
1891   int member_specialization = 0;
1892   tree ctype = DECL_CLASS_CONTEXT (decl);
1893   tree dname = DECL_NAME (decl);
1894   tmpl_spec_kind tsk;
1895
1896   if (is_friend)
1897     {
1898       if (!processing_specialization)
1899         tsk = tsk_none;
1900       else
1901         tsk = tsk_excessive_parms;
1902     }
1903   else
1904     tsk = current_tmpl_spec_kind (template_count);
1905
1906   switch (tsk)
1907     {
1908     case tsk_none:
1909       if (processing_specialization)
1910         {
1911           specialization = 1;
1912           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1913         }
1914       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1915         {
1916           if (is_friend)
1917             /* This could be something like:
1918
1919                template <class T> void f(T);
1920                class S { friend void f<>(int); }  */
1921             specialization = 1;
1922           else
1923             {
1924               /* This case handles bogus declarations like template <>
1925                  template <class T> void f<int>(); */
1926
1927               error ("template-id %qD in declaration of primary template",
1928                      declarator);
1929               return decl;
1930             }
1931         }
1932       break;
1933
1934     case tsk_invalid_member_spec:
1935       /* The error has already been reported in
1936          check_specialization_scope.  */
1937       return error_mark_node;
1938
1939     case tsk_invalid_expl_inst:
1940       error ("template parameter list used in explicit instantiation");
1941
1942       /* Fall through.  */
1943
1944     case tsk_expl_inst:
1945       if (have_def)
1946         error ("definition provided for explicit instantiation");
1947
1948       explicit_instantiation = 1;
1949       break;
1950
1951     case tsk_excessive_parms:
1952     case tsk_insufficient_parms:
1953       if (tsk == tsk_excessive_parms)
1954         error ("too many template parameter lists in declaration of %qD",
1955                decl);
1956       else if (template_header_count)
1957         error("too few template parameter lists in declaration of %qD", decl);
1958       else
1959         error("explicit specialization of %qD must be introduced by "
1960               "%<template <>%>", decl);
1961
1962       /* Fall through.  */
1963     case tsk_expl_spec:
1964       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1965       if (ctype)
1966         member_specialization = 1;
1967       else
1968         specialization = 1;
1969       break;
1970
1971     case tsk_template:
1972       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1973         {
1974           /* This case handles bogus declarations like template <>
1975              template <class T> void f<int>(); */
1976
1977           if (uses_template_parms (declarator))
1978             error ("function template partial specialization %qD "
1979                    "is not allowed", declarator);
1980           else
1981             error ("template-id %qD in declaration of primary template",
1982                    declarator);
1983           return decl;
1984         }
1985
1986       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
1987         /* This is a specialization of a member template, without
1988            specialization the containing class.  Something like:
1989
1990              template <class T> struct S {
1991                template <class U> void f (U);
1992              };
1993              template <> template <class U> void S<int>::f(U) {}
1994
1995            That's a specialization -- but of the entire template.  */
1996         specialization = 1;
1997       break;
1998
1999     default:
2000       gcc_unreachable ();
2001     }
2002
2003   if (specialization || member_specialization)
2004     {
2005       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2006       for (; t; t = TREE_CHAIN (t))
2007         if (TREE_PURPOSE (t))
2008           {
2009             permerror (input_location, 
2010                        "default argument specified in explicit specialization");
2011             break;
2012           }
2013     }
2014
2015   if (specialization || member_specialization || explicit_instantiation)
2016     {
2017       tree tmpl = NULL_TREE;
2018       tree targs = NULL_TREE;
2019
2020       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2021       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2022         {
2023           tree fns;
2024
2025           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2026           if (ctype)
2027             fns = dname;
2028           else
2029             {
2030               /* If there is no class context, the explicit instantiation
2031                  must be at namespace scope.  */
2032               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2033
2034               /* Find the namespace binding, using the declaration
2035                  context.  */
2036               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2037                                            false, true);
2038               if (fns == error_mark_node || !is_overloaded_fn (fns))
2039                 {
2040                   error ("%qD is not a template function", dname);
2041                   fns = error_mark_node;
2042                 }
2043               else
2044                 {
2045                   tree fn = OVL_CURRENT (fns);
2046                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2047                                                 CP_DECL_CONTEXT (fn)))
2048                     error ("%qD is not declared in %qD",
2049                            decl, current_namespace);
2050                 }
2051             }
2052
2053           declarator = lookup_template_function (fns, NULL_TREE);
2054         }
2055
2056       if (declarator == error_mark_node)
2057         return error_mark_node;
2058
2059       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2060         {
2061           if (!explicit_instantiation)
2062             /* A specialization in class scope.  This is invalid,
2063                but the error will already have been flagged by
2064                check_specialization_scope.  */
2065             return error_mark_node;
2066           else
2067             {
2068               /* It's not valid to write an explicit instantiation in
2069                  class scope, e.g.:
2070
2071                    class C { template void f(); }
2072
2073                    This case is caught by the parser.  However, on
2074                    something like:
2075
2076                    template class C { void f(); };
2077
2078                    (which is invalid) we can get here.  The error will be
2079                    issued later.  */
2080               ;
2081             }
2082
2083           return decl;
2084         }
2085       else if (ctype != NULL_TREE
2086                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2087                    IDENTIFIER_NODE))
2088         {
2089           /* Find the list of functions in ctype that have the same
2090              name as the declared function.  */
2091           tree name = TREE_OPERAND (declarator, 0);
2092           tree fns = NULL_TREE;
2093           int idx;
2094
2095           if (constructor_name_p (name, ctype))
2096             {
2097               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2098
2099               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2100                   : !CLASSTYPE_DESTRUCTORS (ctype))
2101                 {
2102                   /* From [temp.expl.spec]:
2103
2104                      If such an explicit specialization for the member
2105                      of a class template names an implicitly-declared
2106                      special member function (clause _special_), the
2107                      program is ill-formed.
2108
2109                      Similar language is found in [temp.explicit].  */
2110                   error ("specialization of implicitly-declared special member function");
2111                   return error_mark_node;
2112                 }
2113
2114               name = is_constructor ? ctor_identifier : dtor_identifier;
2115             }
2116
2117           if (!DECL_CONV_FN_P (decl))
2118             {
2119               idx = lookup_fnfields_1 (ctype, name);
2120               if (idx >= 0)
2121                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2122             }
2123           else
2124             {
2125               VEC(tree,gc) *methods;
2126               tree ovl;
2127
2128               /* For a type-conversion operator, we cannot do a
2129                  name-based lookup.  We might be looking for `operator
2130                  int' which will be a specialization of `operator T'.
2131                  So, we find *all* the conversion operators, and then
2132                  select from them.  */
2133               fns = NULL_TREE;
2134
2135               methods = CLASSTYPE_METHOD_VEC (ctype);
2136               if (methods)
2137                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2138                      VEC_iterate (tree, methods, idx, ovl);
2139                      ++idx)
2140                   {
2141                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2142                       /* There are no more conversion functions.  */
2143                       break;
2144
2145                     /* Glue all these conversion functions together
2146                        with those we already have.  */
2147                     for (; ovl; ovl = OVL_NEXT (ovl))
2148                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2149                   }
2150             }
2151
2152           if (fns == NULL_TREE)
2153             {
2154               error ("no member function %qD declared in %qT", name, ctype);
2155               return error_mark_node;
2156             }
2157           else
2158             TREE_OPERAND (declarator, 0) = fns;
2159         }
2160
2161       /* Figure out what exactly is being specialized at this point.
2162          Note that for an explicit instantiation, even one for a
2163          member function, we cannot tell apriori whether the
2164          instantiation is for a member template, or just a member
2165          function of a template class.  Even if a member template is
2166          being instantiated, the member template arguments may be
2167          elided if they can be deduced from the rest of the
2168          declaration.  */
2169       tmpl = determine_specialization (declarator, decl,
2170                                        &targs,
2171                                        member_specialization,
2172                                        template_count,
2173                                        tsk);
2174
2175       if (!tmpl || tmpl == error_mark_node)
2176         /* We couldn't figure out what this declaration was
2177            specializing.  */
2178         return error_mark_node;
2179       else
2180         {
2181           tree gen_tmpl = most_general_template (tmpl);
2182
2183           if (explicit_instantiation)
2184             {
2185               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2186                  is done by do_decl_instantiation later.  */
2187
2188               int arg_depth = TMPL_ARGS_DEPTH (targs);
2189               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2190
2191               if (arg_depth > parm_depth)
2192                 {
2193                   /* If TMPL is not the most general template (for
2194                      example, if TMPL is a friend template that is
2195                      injected into namespace scope), then there will
2196                      be too many levels of TARGS.  Remove some of them
2197                      here.  */
2198                   int i;
2199                   tree new_targs;
2200
2201                   new_targs = make_tree_vec (parm_depth);
2202                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2203                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2204                       = TREE_VEC_ELT (targs, i);
2205                   targs = new_targs;
2206                 }
2207
2208               return instantiate_template (tmpl, targs, tf_error);
2209             }
2210
2211           /* If we thought that the DECL was a member function, but it
2212              turns out to be specializing a static member function,
2213              make DECL a static member function as well.  */
2214           if (DECL_STATIC_FUNCTION_P (tmpl)
2215               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2216             revert_static_member_fn (decl);
2217
2218           /* If this is a specialization of a member template of a
2219              template class, we want to return the TEMPLATE_DECL, not
2220              the specialization of it.  */
2221           if (tsk == tsk_template)
2222             {
2223               tree result = DECL_TEMPLATE_RESULT (tmpl);
2224               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2225               DECL_INITIAL (result) = NULL_TREE;
2226               if (have_def)
2227                 {
2228                   tree parm;
2229                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2230                   DECL_SOURCE_LOCATION (result)
2231                     = DECL_SOURCE_LOCATION (decl);
2232                   /* We want to use the argument list specified in the
2233                      definition, not in the original declaration.  */
2234                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2235                   for (parm = DECL_ARGUMENTS (result); parm;
2236                        parm = TREE_CHAIN (parm))
2237                     DECL_CONTEXT (parm) = result;
2238                 }
2239               return tmpl;
2240             }
2241
2242           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2243           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2244
2245           /* Inherit default function arguments from the template
2246              DECL is specializing.  */
2247           copy_default_args_to_explicit_spec (decl);
2248
2249           /* This specialization has the same protection as the
2250              template it specializes.  */
2251           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2252           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2253
2254           /* 7.1.1-1 [dcl.stc]
2255
2256              A storage-class-specifier shall not be specified in an
2257              explicit specialization...
2258
2259              The parser rejects these, so unless action is taken here,
2260              explicit function specializations will always appear with
2261              global linkage.
2262
2263              The action recommended by the C++ CWG in response to C++
2264              defect report 605 is to make the storage class and linkage
2265              of the explicit specialization match the templated function:
2266
2267              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2268            */
2269           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2270             {
2271               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2272               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2273
2274               /* This specialization has the same linkage and visibility as
2275                  the function template it specializes.  */
2276               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2277               if (! TREE_PUBLIC (decl))
2278                 {
2279                   DECL_INTERFACE_KNOWN (decl) = 1;
2280                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2281                 }
2282               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2283               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2284                 {
2285                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2286                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2287                 }
2288             }
2289
2290           /* If DECL is a friend declaration, declared using an
2291              unqualified name, the namespace associated with DECL may
2292              have been set incorrectly.  For example, in:
2293
2294                template <typename T> void f(T);
2295                namespace N {
2296                  struct S { friend void f<int>(int); }
2297                }
2298
2299              we will have set the DECL_CONTEXT for the friend
2300              declaration to N, rather than to the global namespace.  */
2301           if (DECL_NAMESPACE_SCOPE_P (decl))
2302             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2303
2304           if (is_friend && !have_def)
2305             /* This is not really a declaration of a specialization.
2306                It's just the name of an instantiation.  But, it's not
2307                a request for an instantiation, either.  */
2308             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2309           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2310             /* This is indeed a specialization.  In case of constructors
2311                and destructors, we need in-charge and not-in-charge
2312                versions in V3 ABI.  */
2313             clone_function_decl (decl, /*update_method_vec_p=*/0);
2314
2315           /* Register this specialization so that we can find it
2316              again.  */
2317           decl = register_specialization (decl, gen_tmpl, targs, is_friend);
2318         }
2319     }
2320
2321   return decl;
2322 }
2323
2324 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2325    parameters.  These are represented in the same format used for
2326    DECL_TEMPLATE_PARMS.  */
2327
2328 int
2329 comp_template_parms (const_tree parms1, const_tree parms2)
2330 {
2331   const_tree p1;
2332   const_tree p2;
2333
2334   if (parms1 == parms2)
2335     return 1;
2336
2337   for (p1 = parms1, p2 = parms2;
2338        p1 != NULL_TREE && p2 != NULL_TREE;
2339        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2340     {
2341       tree t1 = TREE_VALUE (p1);
2342       tree t2 = TREE_VALUE (p2);
2343       int i;
2344
2345       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2346       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2347
2348       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2349         return 0;
2350
2351       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2352         {
2353           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2354           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2355
2356           /* If either of the template parameters are invalid, assume
2357              they match for the sake of error recovery. */
2358           if (parm1 == error_mark_node || parm2 == error_mark_node)
2359             return 1;
2360
2361           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2362             return 0;
2363
2364           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2365               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2366                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2367             continue;
2368           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2369             return 0;
2370         }
2371     }
2372
2373   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2374     /* One set of parameters has more parameters lists than the
2375        other.  */
2376     return 0;
2377
2378   return 1;
2379 }
2380
2381 /* Determine whether PARM is a parameter pack.  */
2382 bool 
2383 template_parameter_pack_p (const_tree parm)
2384 {
2385   /* Determine if we have a non-type template parameter pack.  */
2386   if (TREE_CODE (parm) == PARM_DECL)
2387     return (DECL_TEMPLATE_PARM_P (parm) 
2388             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2389
2390   /* If this is a list of template parameters, we could get a
2391      TYPE_DECL or a TEMPLATE_DECL.  */ 
2392   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2393     parm = TREE_TYPE (parm);
2394
2395   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2396            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2397           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2398 }
2399
2400 /* Determine whether ARGS describes a variadic template args list,
2401    i.e., one that is terminated by a template argument pack.  */
2402 static bool 
2403 template_args_variadic_p (tree args)
2404 {
2405   int nargs;
2406   tree last_parm;
2407
2408   if (args == NULL_TREE)
2409     return false;
2410
2411   args = INNERMOST_TEMPLATE_ARGS (args);
2412   nargs = TREE_VEC_LENGTH (args);
2413
2414   if (nargs == 0)
2415     return false;
2416
2417   last_parm = TREE_VEC_ELT (args, nargs - 1);
2418
2419   return ARGUMENT_PACK_P (last_parm);
2420 }
2421
2422 /* Generate a new name for the parameter pack name NAME (an
2423    IDENTIFIER_NODE) that incorporates its */
2424 static tree
2425 make_ith_pack_parameter_name (tree name, int i)
2426 {
2427   /* Munge the name to include the parameter index.  */
2428   char numbuf[128];
2429   char* newname;
2430   
2431   sprintf(numbuf, "%i", i);
2432   newname = (char*)alloca (IDENTIFIER_LENGTH (name) + strlen(numbuf) + 2);
2433   sprintf(newname, "%s#%i", IDENTIFIER_POINTER (name), i);
2434   return get_identifier (newname);
2435 }
2436
2437 /* Structure used to track the progress of find_parameter_packs_r.  */
2438 struct find_parameter_pack_data 
2439 {
2440   /* TREE_LIST that will contain all of the parameter packs found by
2441      the traversal.  */
2442   tree* parameter_packs;
2443
2444   /* Set of AST nodes that have been visited by the traversal.  */
2445   struct pointer_set_t *visited;
2446 };
2447
2448 /* Identifies all of the argument packs that occur in a template
2449    argument and appends them to the TREE_LIST inside DATA, which is a
2450    find_parameter_pack_data structure. This is a subroutine of
2451    make_pack_expansion and uses_parameter_packs.  */
2452 static tree
2453 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2454 {
2455   tree t = *tp;
2456   struct find_parameter_pack_data* ppd = 
2457     (struct find_parameter_pack_data*)data;
2458   bool parameter_pack_p = false;
2459
2460   /* Identify whether this is a parameter pack or not.  */
2461   switch (TREE_CODE (t))
2462     {
2463     case TEMPLATE_PARM_INDEX:
2464       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2465         parameter_pack_p = true;
2466       break;
2467
2468     case TEMPLATE_TYPE_PARM:
2469     case TEMPLATE_TEMPLATE_PARM:
2470       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2471         parameter_pack_p = true;
2472       break;
2473
2474     case PARM_DECL:
2475       if (FUNCTION_PARAMETER_PACK_P (t))
2476         {
2477           /* We don't want to walk into the type of a PARM_DECL,
2478              because we don't want to see the type parameter pack.  */
2479           *walk_subtrees = 0;
2480           parameter_pack_p = true;
2481         }
2482       break;
2483
2484     default:
2485       /* Not a parameter pack.  */
2486       break;
2487     }
2488
2489   if (parameter_pack_p)
2490     {
2491       /* Add this parameter pack to the list.  */
2492       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2493     }
2494
2495   if (TYPE_P (t))
2496     cp_walk_tree (&TYPE_CONTEXT (t), 
2497                   &find_parameter_packs_r, ppd, ppd->visited);
2498
2499   /* This switch statement will return immediately if we don't find a
2500      parameter pack.  */
2501   switch (TREE_CODE (t)) 
2502     {
2503     case TEMPLATE_PARM_INDEX:
2504       return NULL_TREE;
2505
2506     case BOUND_TEMPLATE_TEMPLATE_PARM:
2507       /* Check the template itself.  */
2508       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2509                     &find_parameter_packs_r, ppd, ppd->visited);
2510       /* Check the template arguments.  */
2511       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2512                     ppd->visited);
2513       *walk_subtrees = 0;
2514       return NULL_TREE;
2515
2516     case TEMPLATE_TYPE_PARM:
2517     case TEMPLATE_TEMPLATE_PARM:
2518       return NULL_TREE;
2519
2520     case PARM_DECL:
2521       return NULL_TREE;
2522
2523     case RECORD_TYPE:
2524       if (TYPE_PTRMEMFUNC_P (t))
2525         return NULL_TREE;
2526       /* Fall through.  */
2527
2528     case UNION_TYPE:
2529     case ENUMERAL_TYPE:
2530       if (TYPE_TEMPLATE_INFO (t))
2531         cp_walk_tree (&TREE_VALUE (TYPE_TEMPLATE_INFO (t)), 
2532                       &find_parameter_packs_r, ppd, ppd->visited);
2533
2534       *walk_subtrees = 0;
2535       return NULL_TREE;
2536
2537     case TEMPLATE_DECL:
2538       cp_walk_tree (&TREE_TYPE (t),
2539                     &find_parameter_packs_r, ppd, ppd->visited);
2540       return NULL_TREE;
2541  
2542     case TYPENAME_TYPE:
2543       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2544                    ppd, ppd->visited);
2545       *walk_subtrees = 0;
2546       return NULL_TREE;
2547       
2548     case TYPE_PACK_EXPANSION:
2549     case EXPR_PACK_EXPANSION:
2550       *walk_subtrees = 0;
2551       return NULL_TREE;
2552
2553     case INTEGER_TYPE:
2554       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2555                     ppd, ppd->visited);
2556       *walk_subtrees = 0;
2557       return NULL_TREE;
2558
2559     case IDENTIFIER_NODE:
2560       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2561                     ppd->visited);
2562       *walk_subtrees = 0;
2563       return NULL_TREE;
2564
2565     default:
2566       return NULL_TREE;
2567     }
2568
2569   return NULL_TREE;
2570 }
2571
2572 /* Determines if the expression or type T uses any parameter packs.  */
2573 bool
2574 uses_parameter_packs (tree t)
2575 {
2576   tree parameter_packs = NULL_TREE;
2577   struct find_parameter_pack_data ppd;
2578   ppd.parameter_packs = &parameter_packs;
2579   ppd.visited = pointer_set_create ();
2580   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2581   pointer_set_destroy (ppd.visited);
2582   return parameter_packs != NULL_TREE;
2583 }
2584
2585 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2586    representation a base-class initializer into a parameter pack
2587    expansion. If all goes well, the resulting node will be an
2588    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2589    respectively.  */
2590 tree 
2591 make_pack_expansion (tree arg)
2592 {
2593   tree result;
2594   tree parameter_packs = NULL_TREE;
2595   bool for_types = false;
2596   struct find_parameter_pack_data ppd;
2597
2598   if (!arg || arg == error_mark_node)
2599     return arg;
2600
2601   if (TREE_CODE (arg) == TREE_LIST)
2602     {
2603       /* The only time we will see a TREE_LIST here is for a base
2604          class initializer.  In this case, the TREE_PURPOSE will be a
2605          _TYPE node (representing the base class expansion we're
2606          initializing) and the TREE_VALUE will be a TREE_LIST
2607          containing the initialization arguments. 
2608
2609          The resulting expansion looks somewhat different from most
2610          expansions. Rather than returning just one _EXPANSION, we
2611          return a TREE_LIST whose TREE_PURPOSE is a
2612          TYPE_PACK_EXPANSION containing the bases that will be
2613          initialized.  The TREE_VALUE will be identical to the
2614          original TREE_VALUE, which is a list of arguments that will
2615          be passed to each base.  We do not introduce any new pack
2616          expansion nodes into the TREE_VALUE (although it is possible
2617          that some already exist), because the TREE_PURPOSE and
2618          TREE_VALUE all need to be expanded together with the same
2619          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2620          resulting TREE_PURPOSE will mention the parameter packs in
2621          both the bases and the arguments to the bases.  */
2622       tree purpose;
2623       tree value;
2624       tree parameter_packs = NULL_TREE;
2625
2626       /* Determine which parameter packs will be used by the base
2627          class expansion.  */
2628       ppd.visited = pointer_set_create ();
2629       ppd.parameter_packs = &parameter_packs;
2630       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
2631                     &ppd, ppd.visited);
2632
2633       if (parameter_packs == NULL_TREE)
2634         {
2635           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
2636           pointer_set_destroy (ppd.visited);
2637           return error_mark_node;
2638         }
2639
2640       if (TREE_VALUE (arg) != void_type_node)
2641         {
2642           /* Collect the sets of parameter packs used in each of the
2643              initialization arguments.  */
2644           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
2645             {
2646               /* Determine which parameter packs will be expanded in this
2647                  argument.  */
2648               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
2649                             &ppd, ppd.visited);
2650             }
2651         }
2652
2653       pointer_set_destroy (ppd.visited);
2654
2655       /* Create the pack expansion type for the base type.  */
2656       purpose = make_node (TYPE_PACK_EXPANSION);
2657       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
2658       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
2659
2660       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2661          they will rarely be compared to anything.  */
2662       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
2663
2664       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
2665     }
2666
2667   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
2668     for_types = true;
2669
2670   /* Build the PACK_EXPANSION_* node.  */
2671   result = make_node (for_types ? TYPE_PACK_EXPANSION : EXPR_PACK_EXPANSION);
2672   SET_PACK_EXPANSION_PATTERN (result, arg);
2673   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
2674     {
2675       /* Propagate type and const-expression information.  */
2676       TREE_TYPE (result) = TREE_TYPE (arg);
2677       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
2678     }
2679   else
2680     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2681        they will rarely be compared to anything.  */
2682     SET_TYPE_STRUCTURAL_EQUALITY (result);
2683
2684   /* Determine which parameter packs will be expanded.  */
2685   ppd.parameter_packs = &parameter_packs;
2686   ppd.visited = pointer_set_create ();
2687   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
2688   pointer_set_destroy (ppd.visited);
2689
2690   /* Make sure we found some parameter packs.  */
2691   if (parameter_packs == NULL_TREE)
2692     {
2693       if (TYPE_P (arg))
2694         error ("expansion pattern %<%T%> contains no argument packs", arg);
2695       else
2696         error ("expansion pattern %<%E%> contains no argument packs", arg);
2697       return error_mark_node;
2698     }
2699   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
2700
2701   return result;
2702 }
2703
2704 /* Checks T for any "bare" parameter packs, which have not yet been
2705    expanded, and issues an error if any are found. This operation can
2706    only be done on full expressions or types (e.g., an expression
2707    statement, "if" condition, etc.), because we could have expressions like:
2708
2709      foo(f(g(h(args)))...)
2710
2711    where "args" is a parameter pack. check_for_bare_parameter_packs
2712    should not be called for the subexpressions args, h(args),
2713    g(h(args)), or f(g(h(args))), because we would produce erroneous
2714    error messages. 
2715
2716    Returns TRUE and emits an error if there were bare parameter packs,
2717    returns FALSE otherwise.  */
2718 bool 
2719 check_for_bare_parameter_packs (tree t)
2720 {
2721   tree parameter_packs = NULL_TREE;
2722   struct find_parameter_pack_data ppd;
2723
2724   if (!processing_template_decl || !t || t == error_mark_node)
2725     return false;
2726
2727   if (TREE_CODE (t) == TYPE_DECL)
2728     t = TREE_TYPE (t);
2729
2730   ppd.parameter_packs = &parameter_packs;
2731   ppd.visited = pointer_set_create ();
2732   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2733   pointer_set_destroy (ppd.visited);
2734
2735   if (parameter_packs) 
2736     {
2737       error ("parameter packs not expanded with %<...%>:");
2738       while (parameter_packs)
2739         {
2740           tree pack = TREE_VALUE (parameter_packs);
2741           tree name = NULL_TREE;
2742
2743           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
2744               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
2745             name = TYPE_NAME (pack);
2746           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
2747             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
2748           else
2749             name = DECL_NAME (pack);
2750
2751           if (name)
2752             inform (input_location, "        %qD", name);
2753           else
2754             inform (input_location, "        <anonymous>");
2755
2756           parameter_packs = TREE_CHAIN (parameter_packs);
2757         }
2758
2759       return true;
2760     }
2761
2762   return false;
2763 }
2764
2765 /* Expand any parameter packs that occur in the template arguments in
2766    ARGS.  */
2767 tree
2768 expand_template_argument_pack (tree args)
2769 {
2770   tree result_args = NULL_TREE;
2771   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
2772   int num_result_args = -1;
2773
2774   /* First, determine if we need to expand anything, and the number of
2775      slots we'll need.  */
2776   for (in_arg = 0; in_arg < nargs; ++in_arg)
2777     {
2778       tree arg = TREE_VEC_ELT (args, in_arg);
2779       if (ARGUMENT_PACK_P (arg))
2780         {
2781           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
2782           if (num_result_args < 0)
2783             num_result_args = in_arg + num_packed;
2784           else
2785             num_result_args += num_packed;
2786         }
2787       else
2788         {
2789           if (num_result_args >= 0)
2790             num_result_args++;
2791         }
2792     }
2793
2794   /* If no expansion is necessary, we're done.  */
2795   if (num_result_args < 0)
2796     return args;
2797
2798   /* Expand arguments.  */
2799   result_args = make_tree_vec (num_result_args);
2800   for (in_arg = 0; in_arg < nargs; ++in_arg)
2801     {
2802       tree arg = TREE_VEC_ELT (args, in_arg);
2803       if (ARGUMENT_PACK_P (arg))
2804         {
2805           tree packed = ARGUMENT_PACK_ARGS (arg);
2806           int i, num_packed = TREE_VEC_LENGTH (packed);
2807           for (i = 0; i < num_packed; ++i, ++out_arg)
2808             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
2809         }
2810       else
2811         {
2812           TREE_VEC_ELT (result_args, out_arg) = arg;
2813           ++out_arg;
2814         }
2815     }
2816
2817   return result_args;
2818 }
2819
2820 /* Checks if DECL shadows a template parameter.
2821
2822    [temp.local]: A template-parameter shall not be redeclared within its
2823    scope (including nested scopes).
2824
2825    Emits an error and returns TRUE if the DECL shadows a parameter,
2826    returns FALSE otherwise.  */
2827
2828 bool
2829 check_template_shadow (tree decl)
2830 {
2831   tree olddecl;
2832
2833   /* If we're not in a template, we can't possibly shadow a template
2834      parameter.  */
2835   if (!current_template_parms)
2836     return true;
2837
2838   /* Figure out what we're shadowing.  */
2839   if (TREE_CODE (decl) == OVERLOAD)
2840     decl = OVL_CURRENT (decl);
2841   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
2842
2843   /* If there's no previous binding for this name, we're not shadowing
2844      anything, let alone a template parameter.  */
2845   if (!olddecl)
2846     return true;
2847
2848   /* If we're not shadowing a template parameter, we're done.  Note
2849      that OLDDECL might be an OVERLOAD (or perhaps even an
2850      ERROR_MARK), so we can't just blithely assume it to be a _DECL
2851      node.  */
2852   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
2853     return true;
2854
2855   /* We check for decl != olddecl to avoid bogus errors for using a
2856      name inside a class.  We check TPFI to avoid duplicate errors for
2857      inline member templates.  */
2858   if (decl == olddecl
2859       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
2860     return true;
2861
2862   error ("declaration of %q+#D", decl);
2863   error (" shadows template parm %q+#D", olddecl);
2864   return false;
2865 }
2866
2867 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
2868    ORIG_LEVEL, DECL, and TYPE.  */
2869
2870 static tree
2871 build_template_parm_index (int index,
2872                            int level,
2873                            int orig_level,
2874                            tree decl,
2875                            tree type)
2876 {
2877   tree t = make_node (TEMPLATE_PARM_INDEX);
2878   TEMPLATE_PARM_IDX (t) = index;
2879   TEMPLATE_PARM_LEVEL (t) = level;
2880   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
2881   TEMPLATE_PARM_DECL (t) = decl;
2882   TREE_TYPE (t) = type;
2883   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
2884   TREE_READONLY (t) = TREE_READONLY (decl);
2885
2886   return t;
2887 }
2888
2889 /* Find the canonical type parameter for the given template type
2890    parameter.  Returns the canonical type parameter, which may be TYPE
2891    if no such parameter existed.  */
2892 static tree
2893 canonical_type_parameter (tree type)
2894 {
2895   tree list;
2896   int idx = TEMPLATE_TYPE_IDX (type);
2897   if (!canonical_template_parms)
2898     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
2899
2900   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
2901     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
2902
2903   list = VEC_index (tree, canonical_template_parms, idx);
2904   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
2905     list = TREE_CHAIN (list);
2906
2907   if (list)
2908     return TREE_VALUE (list);
2909   else
2910     {
2911       VEC_replace(tree, canonical_template_parms, idx,
2912                   tree_cons (NULL_TREE, type, 
2913                              VEC_index (tree, canonical_template_parms, idx)));
2914       return type;
2915     }
2916 }
2917
2918 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
2919    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
2920    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
2921    new one is created.  */
2922
2923 static tree
2924 reduce_template_parm_level (tree index, tree type, int levels, tree args,
2925                             tsubst_flags_t complain)
2926 {
2927   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
2928       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
2929           != TEMPLATE_PARM_LEVEL (index) - levels))
2930     {
2931       tree orig_decl = TEMPLATE_PARM_DECL (index);
2932       tree decl, t;
2933
2934       decl = build_decl (TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
2935       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
2936       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
2937       DECL_ARTIFICIAL (decl) = 1;
2938       SET_DECL_TEMPLATE_PARM_P (decl);
2939
2940       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
2941                                      TEMPLATE_PARM_LEVEL (index) - levels,
2942                                      TEMPLATE_PARM_ORIG_LEVEL (index),
2943                                      decl, type);
2944       TEMPLATE_PARM_DESCENDANTS (index) = t;
2945       TEMPLATE_PARM_PARAMETER_PACK (t) 
2946         = TEMPLATE_PARM_PARAMETER_PACK (index);
2947
2948         /* Template template parameters need this.  */
2949       if (TREE_CODE (decl) == TEMPLATE_DECL)
2950         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
2951           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
2952            args, complain);
2953     }
2954
2955   return TEMPLATE_PARM_DESCENDANTS (index);
2956 }
2957
2958 /* Process information from new template parameter PARM and append it to the
2959    LIST being built.  This new parameter is a non-type parameter iff
2960    IS_NON_TYPE is true. This new parameter is a parameter
2961    pack iff IS_PARAMETER_PACK is true.  */
2962
2963 tree
2964 process_template_parm (tree list, tree parm, bool is_non_type, 
2965                        bool is_parameter_pack)
2966 {
2967   tree decl = 0;
2968   tree defval;
2969   tree err_parm_list;
2970   int idx = 0;
2971
2972   gcc_assert (TREE_CODE (parm) == TREE_LIST);
2973   defval = TREE_PURPOSE (parm);
2974
2975   if (list)
2976     {
2977       tree p = tree_last (list);
2978
2979       if (p && TREE_VALUE (p) != error_mark_node)
2980         {
2981           p = TREE_VALUE (p);
2982           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
2983             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
2984           else
2985             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
2986         }
2987
2988       ++idx;
2989     }
2990   else
2991     idx = 0;
2992
2993   if (is_non_type)
2994     {
2995       parm = TREE_VALUE (parm);
2996
2997       SET_DECL_TEMPLATE_PARM_P (parm);
2998
2999       if (TREE_TYPE (parm) == error_mark_node)
3000         {
3001           err_parm_list = build_tree_list (defval, parm);
3002           TREE_VALUE (err_parm_list) = error_mark_node;
3003            return chainon (list, err_parm_list);
3004         }
3005       else
3006       {
3007         /* [temp.param]
3008
3009            The top-level cv-qualifiers on the template-parameter are
3010            ignored when determining its type.  */
3011         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3012         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3013           {
3014             err_parm_list = build_tree_list (defval, parm);
3015             TREE_VALUE (err_parm_list) = error_mark_node;
3016              return chainon (list, err_parm_list);
3017           }
3018
3019         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3020           {
3021             /* This template parameter is not a parameter pack, but it
3022                should be. Complain about "bare" parameter packs.  */
3023             check_for_bare_parameter_packs (TREE_TYPE (parm));
3024             
3025             /* Recover by calling this a parameter pack.  */
3026             is_parameter_pack = true;
3027           }
3028       }
3029
3030       /* A template parameter is not modifiable.  */
3031       TREE_CONSTANT (parm) = 1;
3032       TREE_READONLY (parm) = 1;
3033       decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3034       TREE_CONSTANT (decl) = 1;
3035       TREE_READONLY (decl) = 1;
3036       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3037         = build_template_parm_index (idx, processing_template_decl,
3038                                      processing_template_decl,
3039                                      decl, TREE_TYPE (parm));
3040
3041       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3042         = is_parameter_pack;
3043     }
3044   else
3045     {
3046       tree t;
3047       parm = TREE_VALUE (TREE_VALUE (parm));
3048
3049       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3050         {
3051           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3052           /* This is for distinguishing between real templates and template
3053              template parameters */
3054           TREE_TYPE (parm) = t;
3055           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3056           decl = parm;
3057         }
3058       else
3059         {
3060           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3061           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3062           decl = build_decl (TYPE_DECL, parm, t);
3063         }
3064
3065       TYPE_NAME (t) = decl;
3066       TYPE_STUB_DECL (t) = decl;
3067       parm = decl;
3068       TEMPLATE_TYPE_PARM_INDEX (t)
3069         = build_template_parm_index (idx, processing_template_decl,
3070                                      processing_template_decl,
3071                                      decl, TREE_TYPE (parm));
3072       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3073       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3074     }
3075   DECL_ARTIFICIAL (decl) = 1;
3076   SET_DECL_TEMPLATE_PARM_P (decl);
3077   pushdecl (decl);
3078   parm = build_tree_list (defval, parm);
3079   return chainon (list, parm);
3080 }
3081
3082 /* The end of a template parameter list has been reached.  Process the
3083    tree list into a parameter vector, converting each parameter into a more
3084    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3085    as PARM_DECLs.  */
3086
3087 tree
3088 end_template_parm_list (tree parms)
3089 {
3090   int nparms;
3091   tree parm, next;
3092   tree saved_parmlist = make_tree_vec (list_length (parms));
3093
3094   current_template_parms
3095     = tree_cons (size_int (processing_template_decl),
3096                  saved_parmlist, current_template_parms);
3097
3098   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3099     {
3100       next = TREE_CHAIN (parm);
3101       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3102       TREE_CHAIN (parm) = NULL_TREE;
3103     }
3104
3105   --processing_template_parmlist;
3106
3107   return saved_parmlist;
3108 }
3109
3110 /* end_template_decl is called after a template declaration is seen.  */
3111
3112 void
3113 end_template_decl (void)
3114 {
3115   reset_specialization ();
3116
3117   if (! processing_template_decl)
3118     return;
3119
3120   /* This matches the pushlevel in begin_template_parm_list.  */
3121   finish_scope ();
3122
3123   --processing_template_decl;
3124   current_template_parms = TREE_CHAIN (current_template_parms);
3125 }
3126
3127 /* Within the declaration of a template, return all levels of template
3128    parameters that apply.  The template parameters are represented as
3129    a TREE_VEC, in the form documented in cp-tree.h for template
3130    arguments.  */
3131
3132 static tree
3133 current_template_args (void)
3134 {
3135   tree header;
3136   tree args = NULL_TREE;
3137   int length = TMPL_PARMS_DEPTH (current_template_parms);
3138   int l = length;
3139
3140   /* If there is only one level of template parameters, we do not
3141      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3142      TREE_VEC containing the arguments.  */
3143   if (length > 1)
3144     args = make_tree_vec (length);
3145
3146   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3147     {
3148       tree a = copy_node (TREE_VALUE (header));
3149       int i;
3150
3151       TREE_TYPE (a) = NULL_TREE;
3152       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3153         {
3154           tree t = TREE_VEC_ELT (a, i);
3155
3156           /* T will be a list if we are called from within a
3157              begin/end_template_parm_list pair, but a vector directly
3158              if within a begin/end_member_template_processing pair.  */
3159           if (TREE_CODE (t) == TREE_LIST)
3160             {
3161               t = TREE_VALUE (t);
3162
3163               if (!error_operand_p (t))
3164                 {
3165                   if (TREE_CODE (t) == TYPE_DECL
3166                       || TREE_CODE (t) == TEMPLATE_DECL)
3167                     {
3168                       t = TREE_TYPE (t);
3169                       
3170                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3171                         {
3172                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3173                              with a single element, which expands T.  */
3174                           tree vec = make_tree_vec (1);
3175                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3176                           
3177                           t = make_node (TYPE_ARGUMENT_PACK);
3178                           SET_ARGUMENT_PACK_ARGS (t, vec);
3179                         }
3180                     }
3181                   else
3182                     {
3183                       t = DECL_INITIAL (t);
3184                       
3185                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3186                         {
3187                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3188                              with a single element, which expands T.  */
3189                           tree vec = make_tree_vec (1);
3190                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3191                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3192                           
3193                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3194                           SET_ARGUMENT_PACK_ARGS (t, vec);
3195                           TREE_TYPE (t) = type;
3196                         }
3197                     }
3198                   TREE_VEC_ELT (a, i) = t;
3199                 }
3200             }
3201         }
3202
3203       if (length > 1)
3204         TREE_VEC_ELT (args, --l) = a;
3205       else
3206         args = a;
3207     }
3208
3209   return args;
3210 }
3211
3212 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3213    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3214    a member template.  Used by push_template_decl below.  */
3215
3216 static tree
3217 build_template_decl (tree decl, tree parms, bool member_template_p)
3218 {
3219   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3220   DECL_TEMPLATE_PARMS (tmpl) = parms;
3221   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3222   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3223   if (DECL_LANG_SPECIFIC (decl))
3224     {
3225       DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
3226       DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
3227       DECL_DESTRUCTOR_P (tmpl) = DECL_DESTRUCTOR_P (decl);
3228       DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
3229       DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
3230       if (DECL_OVERLOADED_OPERATOR_P (decl))
3231         SET_OVERLOADED_OPERATOR_CODE (tmpl,
3232                                       DECL_OVERLOADED_OPERATOR_P (decl));
3233     }
3234
3235   return tmpl;
3236 }
3237
3238 struct template_parm_data
3239 {
3240   /* The level of the template parameters we are currently
3241      processing.  */
3242   int level;
3243
3244   /* The index of the specialization argument we are currently
3245      processing.  */
3246   int current_arg;
3247
3248   /* An array whose size is the number of template parameters.  The
3249      elements are nonzero if the parameter has been used in any one
3250      of the arguments processed so far.  */
3251   int* parms;
3252
3253   /* An array whose size is the number of template arguments.  The
3254      elements are nonzero if the argument makes use of template
3255      parameters of this level.  */
3256   int* arg_uses_template_parms;
3257 };
3258
3259 /* Subroutine of push_template_decl used to see if each template
3260    parameter in a partial specialization is used in the explicit
3261    argument list.  If T is of the LEVEL given in DATA (which is
3262    treated as a template_parm_data*), then DATA->PARMS is marked
3263    appropriately.  */
3264
3265 static int
3266 mark_template_parm (tree t, void* data)
3267 {
3268   int level;
3269   int idx;
3270   struct template_parm_data* tpd = (struct template_parm_data*) data;
3271
3272   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3273     {
3274       level = TEMPLATE_PARM_LEVEL (t);
3275       idx = TEMPLATE_PARM_IDX (t);
3276     }
3277   else
3278     {
3279       level = TEMPLATE_TYPE_LEVEL (t);
3280       idx = TEMPLATE_TYPE_IDX (t);
3281     }
3282
3283   if (level == tpd->level)
3284     {
3285       tpd->parms[idx] = 1;
3286       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3287     }
3288
3289   /* Return zero so that for_each_template_parm will continue the
3290      traversal of the tree; we want to mark *every* template parm.  */
3291   return 0;
3292 }
3293
3294 /* Process the partial specialization DECL.  */
3295
3296 static tree
3297 process_partial_specialization (tree decl)
3298 {
3299   tree type = TREE_TYPE (decl);
3300   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3301   tree specargs = CLASSTYPE_TI_ARGS (type);
3302   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3303   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3304   tree inner_parms;
3305   int nargs = TREE_VEC_LENGTH (inner_args);
3306   int ntparms;
3307   int  i;
3308   int did_error_intro = 0;
3309   struct template_parm_data tpd;
3310   struct template_parm_data tpd2;
3311
3312   gcc_assert (current_template_parms);
3313
3314   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3315   ntparms = TREE_VEC_LENGTH (inner_parms);
3316
3317   /* We check that each of the template parameters given in the
3318      partial specialization is used in the argument list to the
3319      specialization.  For example:
3320
3321        template <class T> struct S;
3322        template <class T> struct S<T*>;
3323
3324      The second declaration is OK because `T*' uses the template
3325      parameter T, whereas
3326
3327        template <class T> struct S<int>;
3328
3329      is no good.  Even trickier is:
3330
3331        template <class T>
3332        struct S1
3333        {
3334           template <class U>
3335           struct S2;
3336           template <class U>
3337           struct S2<T>;
3338        };
3339
3340      The S2<T> declaration is actually invalid; it is a
3341      full-specialization.  Of course,
3342
3343           template <class U>
3344           struct S2<T (*)(U)>;
3345
3346      or some such would have been OK.  */
3347   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3348   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3349   memset (tpd.parms, 0, sizeof (int) * ntparms);
3350
3351   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3352   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3353   for (i = 0; i < nargs; ++i)
3354     {
3355       tpd.current_arg = i;
3356       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3357                               &mark_template_parm,
3358                               &tpd,
3359                               NULL,
3360                               /*include_nondeduced_p=*/false);
3361     }
3362   for (i = 0; i < ntparms; ++i)
3363     if (tpd.parms[i] == 0)
3364       {
3365         /* One of the template parms was not used in the
3366            specialization.  */
3367         if (!did_error_intro)
3368           {
3369             error ("template parameters not used in partial specialization:");
3370             did_error_intro = 1;
3371           }
3372
3373         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3374       }
3375
3376   /* [temp.class.spec]
3377
3378      The argument list of the specialization shall not be identical to
3379      the implicit argument list of the primary template.  */
3380   if (comp_template_args
3381       (inner_args,
3382        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3383                                                    (maintmpl)))))
3384     error ("partial specialization %qT does not specialize any template arguments", type);
3385
3386   /* [temp.class.spec]
3387
3388      A partially specialized non-type argument expression shall not
3389      involve template parameters of the partial specialization except
3390      when the argument expression is a simple identifier.
3391
3392      The type of a template parameter corresponding to a specialized
3393      non-type argument shall not be dependent on a parameter of the
3394      specialization. 
3395
3396      Also, we verify that pack expansions only occur at the
3397      end of the argument list.  */
3398   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3399   tpd2.parms = 0;
3400   for (i = 0; i < nargs; ++i)
3401     {
3402       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3403       tree arg = TREE_VEC_ELT (inner_args, i);
3404       tree packed_args = NULL_TREE;
3405       int j, len = 1;
3406
3407       if (ARGUMENT_PACK_P (arg))
3408         {
3409           /* Extract the arguments from the argument pack. We'll be
3410              iterating over these in the following loop.  */
3411           packed_args = ARGUMENT_PACK_ARGS (arg);
3412           len = TREE_VEC_LENGTH (packed_args);
3413         }
3414
3415       for (j = 0; j < len; j++)
3416         {
3417           if (packed_args)
3418             /* Get the Jth argument in the parameter pack.  */
3419             arg = TREE_VEC_ELT (packed_args, j);
3420
3421           if (PACK_EXPANSION_P (arg))
3422             {
3423               /* Pack expansions must come at the end of the
3424                  argument list.  */
3425               if ((packed_args && j < len - 1)
3426                   || (!packed_args && i < nargs - 1))
3427                 {
3428                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3429                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3430                   else
3431                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3432
3433                   if (packed_args)
3434                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3435                 }
3436             }
3437
3438           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3439             /* We only care about the pattern.  */
3440             arg = PACK_EXPANSION_PATTERN (arg);
3441
3442           if (/* These first two lines are the `non-type' bit.  */
3443               !TYPE_P (arg)
3444               && TREE_CODE (arg) != TEMPLATE_DECL
3445               /* This next line is the `argument expression is not just a
3446                  simple identifier' condition and also the `specialized
3447                  non-type argument' bit.  */
3448               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3449             {
3450               if ((!packed_args && tpd.arg_uses_template_parms[i])
3451                   || (packed_args && uses_template_parms (arg)))
3452                 error ("template argument %qE involves template parameter(s)",
3453                        arg);
3454               else 
3455                 {
3456                   /* Look at the corresponding template parameter,
3457                      marking which template parameters its type depends
3458                      upon.  */
3459                   tree type = TREE_TYPE (parm);
3460
3461                   if (!tpd2.parms)
3462                     {
3463                       /* We haven't yet initialized TPD2.  Do so now.  */
3464                       tpd2.arg_uses_template_parms 
3465                         = (int *) alloca (sizeof (int) * nargs);
3466                       /* The number of parameters here is the number in the
3467                          main template, which, as checked in the assertion
3468                          above, is NARGS.  */
3469                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3470                       tpd2.level = 
3471                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3472                     }
3473
3474                   /* Mark the template parameters.  But this time, we're
3475                      looking for the template parameters of the main
3476                      template, not in the specialization.  */
3477                   tpd2.current_arg = i;
3478                   tpd2.arg_uses_template_parms[i] = 0;
3479                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3480                   for_each_template_parm (type,
3481                                           &mark_template_parm,
3482                                           &tpd2,
3483                                           NULL,
3484                                           /*include_nondeduced_p=*/false);
3485
3486                   if (tpd2.arg_uses_template_parms [i])
3487                     {
3488                       /* The type depended on some template parameters.
3489                          If they are fully specialized in the
3490                          specialization, that's OK.  */
3491                       int j;
3492                       for (j = 0; j < nargs; ++j)
3493                         if (tpd2.parms[j] != 0
3494                             && tpd.arg_uses_template_parms [j])
3495                           {
3496                             error ("type %qT of template argument %qE depends "
3497                                    "on template parameter(s)", 
3498                                    type,
3499                                    arg);
3500                             break;
3501                           }
3502                     }
3503                 }
3504             }
3505         }
3506     }
3507
3508   if (retrieve_specialization (maintmpl, specargs,
3509                                /*class_specializations_p=*/true))
3510     /* We've already got this specialization.  */
3511     return decl;
3512
3513   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3514     = tree_cons (specargs, inner_parms,
3515                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3516   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3517   return decl;
3518 }
3519
3520 /* Check that a template declaration's use of default arguments and
3521    parameter packs is not invalid.  Here, PARMS are the template
3522    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3523    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3524    specialization.
3525    
3526
3527    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3528    declaration (but not a definition); 1 indicates a declaration, 2
3529    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3530    emitted for extraneous default arguments.
3531
3532    Returns TRUE if there were no errors found, FALSE otherwise. */
3533
3534 bool
3535 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3536                          int is_partial, int is_friend_decl)
3537 {
3538   const char *msg;
3539   int last_level_to_check;
3540   tree parm_level;
3541   bool no_errors = true;
3542
3543   /* [temp.param]
3544
3545      A default template-argument shall not be specified in a
3546      function template declaration or a function template definition, nor
3547      in the template-parameter-list of the definition of a member of a
3548      class template.  */
3549
3550   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3551     /* You can't have a function template declaration in a local
3552        scope, nor you can you define a member of a class template in a
3553        local scope.  */
3554     return true;
3555
3556   if (current_class_type
3557       && !TYPE_BEING_DEFINED (current_class_type)
3558       && DECL_LANG_SPECIFIC (decl)
3559       /* If this is either a friend defined in the scope of the class
3560          or a member function.  */
3561       && (DECL_FUNCTION_MEMBER_P (decl)
3562           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3563           : DECL_FRIEND_CONTEXT (decl)
3564           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3565           : false)
3566       /* And, if it was a member function, it really was defined in
3567          the scope of the class.  */
3568       && (!DECL_FUNCTION_MEMBER_P (decl)
3569           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3570     /* We already checked these parameters when the template was
3571        declared, so there's no need to do it again now.  This function
3572        was defined in class scope, but we're processing it's body now
3573        that the class is complete.  */
3574     return true;
3575
3576   /* Core issue 226 (C++0x only): the following only applies to class
3577      templates.  */
3578   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3579     {
3580       /* [temp.param]
3581
3582          If a template-parameter has a default template-argument, all
3583          subsequent template-parameters shall have a default
3584          template-argument supplied.  */
3585       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3586         {
3587           tree inner_parms = TREE_VALUE (parm_level);
3588           int ntparms = TREE_VEC_LENGTH (inner_parms);
3589           int seen_def_arg_p = 0;
3590           int i;
3591
3592           for (i = 0; i < ntparms; ++i)
3593             {
3594               tree parm = TREE_VEC_ELT (inner_parms, i);
3595
3596               if (parm == error_mark_node)
3597                 continue;
3598
3599               if (TREE_PURPOSE (parm))
3600                 seen_def_arg_p = 1;
3601               else if (seen_def_arg_p
3602                        && !template_parameter_pack_p (TREE_VALUE (parm)))
3603                 {
3604                   error ("no default argument for %qD", TREE_VALUE (parm));
3605                   /* For better subsequent error-recovery, we indicate that
3606                      there should have been a default argument.  */
3607                   TREE_PURPOSE (parm) = error_mark_node;
3608                   no_errors = false;
3609                 }
3610               else if (is_primary
3611                        && !is_partial
3612                        && !is_friend_decl
3613                        /* Don't complain about an enclosing partial
3614                           specialization.  */
3615                        && parm_level == parms
3616                        && TREE_CODE (decl) == TYPE_DECL
3617                        && i < ntparms - 1
3618                        && template_parameter_pack_p (TREE_VALUE (parm)))
3619                 {
3620                   /* A primary class template can only have one
3621                      parameter pack, at the end of the template
3622                      parameter list.  */
3623
3624                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
3625                     error ("parameter pack %qE must be at the end of the"
3626                            " template parameter list", TREE_VALUE (parm));
3627                   else
3628                     error ("parameter pack %qT must be at the end of the"
3629                            " template parameter list", 
3630                            TREE_TYPE (TREE_VALUE (parm)));
3631
3632                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
3633                     = error_mark_node;
3634                   no_errors = false;
3635                 }
3636             }
3637         }
3638     }
3639
3640   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
3641       || is_partial 
3642       || !is_primary
3643       || is_friend_decl)
3644     /* For an ordinary class template, default template arguments are
3645        allowed at the innermost level, e.g.:
3646          template <class T = int>
3647          struct S {};
3648        but, in a partial specialization, they're not allowed even
3649        there, as we have in [temp.class.spec]:
3650
3651          The template parameter list of a specialization shall not
3652          contain default template argument values.
3653
3654        So, for a partial specialization, or for a function template
3655        (in C++98/C++03), we look at all of them.  */
3656     ;
3657   else
3658     /* But, for a primary class template that is not a partial
3659        specialization we look at all template parameters except the
3660        innermost ones.  */
3661     parms = TREE_CHAIN (parms);
3662
3663   /* Figure out what error message to issue.  */
3664   if (is_friend_decl == 2)
3665     msg = "default template arguments may not be used in function template friend re-declaration";
3666   else if (is_friend_decl)
3667     msg = "default template arguments may not be used in function template friend declarations";
3668   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
3669     msg = "default template arguments may not be used in function templates";
3670   else if (is_partial)
3671     msg = "default template arguments may not be used in partial specializations";
3672   else
3673     msg = "default argument for template parameter for class enclosing %qD";
3674
3675   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
3676     /* If we're inside a class definition, there's no need to
3677        examine the parameters to the class itself.  On the one
3678        hand, they will be checked when the class is defined, and,
3679        on the other, default arguments are valid in things like:
3680          template <class T = double>
3681          struct S { template <class U> void f(U); };
3682        Here the default argument for `S' has no bearing on the
3683        declaration of `f'.  */
3684     last_level_to_check = template_class_depth (current_class_type) + 1;
3685   else
3686     /* Check everything.  */
3687     last_level_to_check = 0;
3688
3689   for (parm_level = parms;
3690        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
3691        parm_level = TREE_CHAIN (parm_level))
3692     {
3693       tree inner_parms = TREE_VALUE (parm_level);
3694       int i;
3695       int ntparms;
3696
3697       ntparms = TREE_VEC_LENGTH (inner_parms);
3698       for (i = 0; i < ntparms; ++i)
3699         {
3700           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
3701             continue;
3702
3703           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
3704             {
3705               if (msg)
3706                 {
3707                   no_errors = false;
3708                   if (is_friend_decl == 2)
3709                     return no_errors;
3710
3711                   error (msg, decl);
3712                   msg = 0;
3713                 }
3714
3715               /* Clear out the default argument so that we are not
3716                  confused later.  */
3717               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
3718             }
3719         }
3720
3721       /* At this point, if we're still interested in issuing messages,
3722          they must apply to classes surrounding the object declared.  */
3723       if (msg)
3724         msg = "default argument for template parameter for class enclosing %qD";
3725     }
3726
3727   return no_errors;
3728 }
3729
3730 /* Worker for push_template_decl_real, called via
3731    for_each_template_parm.  DATA is really an int, indicating the
3732    level of the parameters we are interested in.  If T is a template
3733    parameter of that level, return nonzero.  */
3734
3735 static int
3736 template_parm_this_level_p (tree t, void* data)
3737 {
3738   int this_level = *(int *)data;
3739   int level;
3740
3741   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3742     level = TEMPLATE_PARM_LEVEL (t);
3743   else
3744     level = TEMPLATE_TYPE_LEVEL (t);
3745   return level == this_level;
3746 }
3747
3748 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
3749    parameters given by current_template_args, or reuses a
3750    previously existing one, if appropriate.  Returns the DECL, or an
3751    equivalent one, if it is replaced via a call to duplicate_decls.
3752
3753    If IS_FRIEND is true, DECL is a friend declaration.  */
3754
3755 tree
3756 push_template_decl_real (tree decl, bool is_friend)
3757 {
3758   tree tmpl;
3759   tree args;
3760   tree info;
3761   tree ctx;
3762   int primary;
3763   int is_partial;
3764   int new_template_p = 0;
3765   /* True if the template is a member template, in the sense of
3766      [temp.mem].  */
3767   bool member_template_p = false;
3768
3769   if (decl == error_mark_node || !current_template_parms)
3770     return error_mark_node;
3771
3772   /* See if this is a partial specialization.  */
3773   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
3774                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3775                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
3776
3777   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
3778     is_friend = true;
3779
3780   if (is_friend)
3781     /* For a friend, we want the context of the friend function, not
3782        the type of which it is a friend.  */
3783     ctx = DECL_CONTEXT (decl);
3784   else if (CP_DECL_CONTEXT (decl)
3785            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
3786     /* In the case of a virtual function, we want the class in which
3787        it is defined.  */
3788     ctx = CP_DECL_CONTEXT (decl);
3789   else
3790     /* Otherwise, if we're currently defining some class, the DECL
3791        is assumed to be a member of the class.  */
3792     ctx = current_scope ();
3793
3794   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
3795     ctx = NULL_TREE;
3796
3797   if (!DECL_CONTEXT (decl))
3798     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
3799
3800   /* See if this is a primary template.  */
3801   if (is_friend && ctx)
3802     /* A friend template that specifies a class context, i.e.
3803          template <typename T> friend void A<T>::f();
3804        is not primary.  */
3805     primary = 0;
3806   else
3807     primary = template_parm_scope_p ();
3808
3809   if (primary)
3810     {
3811       if (DECL_CLASS_SCOPE_P (decl))
3812         member_template_p = true;
3813       if (TREE_CODE (decl) == TYPE_DECL
3814           && ANON_AGGRNAME_P (DECL_NAME (decl)))
3815         {
3816           error ("template class without a name");
3817           return error_mark_node;
3818         }
3819       else if (TREE_CODE (decl) == FUNCTION_DECL)
3820         {
3821           if (DECL_DESTRUCTOR_P (decl))
3822             {
3823               /* [temp.mem]
3824
3825                  A destructor shall not be a member template.  */
3826               error ("destructor %qD declared as member template", decl);
3827               return error_mark_node;
3828             }
3829           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
3830               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
3831                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
3832                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
3833                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
3834                       == void_list_node)))
3835             {
3836               /* [basic.stc.dynamic.allocation]
3837
3838                  An allocation function can be a function
3839                  template. ... Template allocation functions shall
3840                  have two or more parameters.  */
3841               error ("invalid template declaration of %qD", decl);
3842               return error_mark_node;
3843             }
3844         }
3845       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3846                && CLASS_TYPE_P (TREE_TYPE (decl)))
3847         /* OK */;
3848       else
3849         {
3850           error ("template declaration of %q#D", decl);
3851           return error_mark_node;
3852         }
3853     }
3854
3855   /* Check to see that the rules regarding the use of default
3856      arguments are not being violated.  */
3857   check_default_tmpl_args (decl, current_template_parms,
3858                            primary, is_partial, /*is_friend_decl=*/0);
3859
3860   /* Ensure that there are no parameter packs in the type of this
3861      declaration that have not been expanded.  */
3862   if (TREE_CODE (decl) == FUNCTION_DECL)
3863     {
3864       /* Check each of the arguments individually to see if there are
3865          any bare parameter packs.  */
3866       tree type = TREE_TYPE (decl);
3867       tree arg = DECL_ARGUMENTS (decl);
3868       tree argtype = TYPE_ARG_TYPES (type);
3869
3870       while (arg && argtype)
3871         {
3872           if (!FUNCTION_PARAMETER_PACK_P (arg)
3873               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
3874             {
3875             /* This is a PARM_DECL that contains unexpanded parameter
3876                packs. We have already complained about this in the
3877                check_for_bare_parameter_packs call, so just replace
3878                these types with ERROR_MARK_NODE.  */
3879               TREE_TYPE (arg) = error_mark_node;
3880               TREE_VALUE (argtype) = error_mark_node;
3881             }
3882
3883           arg = TREE_CHAIN (arg);
3884           argtype = TREE_CHAIN (argtype);
3885         }
3886
3887       /* Check for bare parameter packs in the return type and the
3888          exception specifiers.  */
3889       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
3890         /* Errors were already issued, set return type to int
3891            as the frontend doesn't expect error_mark_node as
3892            the return type.  */
3893         TREE_TYPE (type) = integer_type_node;
3894       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
3895         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
3896     }
3897   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
3898     {
3899       TREE_TYPE (decl) = error_mark_node;
3900       return error_mark_node;
3901     }
3902
3903   if (is_partial)
3904     return process_partial_specialization (decl);
3905
3906   args = current_template_args ();
3907
3908   if (!ctx
3909       || TREE_CODE (ctx) == FUNCTION_DECL
3910       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
3911       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
3912     {
3913       if (DECL_LANG_SPECIFIC (decl)
3914           && DECL_TEMPLATE_INFO (decl)
3915           && DECL_TI_TEMPLATE (decl))
3916         tmpl = DECL_TI_TEMPLATE (decl);
3917       /* If DECL is a TYPE_DECL for a class-template, then there won't
3918          be DECL_LANG_SPECIFIC.  The information equivalent to
3919          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
3920       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3921                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3922                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3923         {
3924           /* Since a template declaration already existed for this
3925              class-type, we must be redeclaring it here.  Make sure
3926              that the redeclaration is valid.  */
3927           redeclare_class_template (TREE_TYPE (decl),
3928                                     current_template_parms);
3929           /* We don't need to create a new TEMPLATE_DECL; just use the
3930              one we already had.  */
3931           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3932         }
3933       else
3934         {
3935           tmpl = build_template_decl (decl, current_template_parms,
3936                                       member_template_p);
3937           new_template_p = 1;
3938
3939           if (DECL_LANG_SPECIFIC (decl)
3940               && DECL_TEMPLATE_SPECIALIZATION (decl))
3941             {
3942               /* A specialization of a member template of a template
3943                  class.  */
3944               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3945               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
3946               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
3947             }
3948         }
3949     }
3950   else
3951     {
3952       tree a, t, current, parms;
3953       int i;
3954       tree tinfo = get_template_info (decl);
3955
3956       if (!tinfo)
3957         {
3958           error ("template definition of non-template %q#D", decl);
3959           return error_mark_node;
3960         }
3961
3962       tmpl = TI_TEMPLATE (tinfo);
3963
3964       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3965           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
3966           && DECL_TEMPLATE_SPECIALIZATION (decl)
3967           && DECL_MEMBER_TEMPLATE_P (tmpl))
3968         {
3969           tree new_tmpl;
3970
3971           /* The declaration is a specialization of a member
3972              template, declared outside the class.  Therefore, the
3973              innermost template arguments will be NULL, so we
3974              replace them with the arguments determined by the
3975              earlier call to check_explicit_specialization.  */
3976           args = DECL_TI_ARGS (decl);
3977
3978           new_tmpl
3979             = build_template_decl (decl, current_template_parms,
3980                                    member_template_p);
3981           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
3982           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
3983           DECL_TI_TEMPLATE (decl) = new_tmpl;
3984           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
3985           DECL_TEMPLATE_INFO (new_tmpl)
3986             = tree_cons (tmpl, args, NULL_TREE);
3987
3988           register_specialization (new_tmpl,
3989                                    most_general_template (tmpl),
3990                                    args,
3991                                    is_friend);
3992           return decl;
3993         }
3994
3995       /* Make sure the template headers we got make sense.  */
3996
3997       parms = DECL_TEMPLATE_PARMS (tmpl);
3998       i = TMPL_PARMS_DEPTH (parms);
3999       if (TMPL_ARGS_DEPTH (args) != i)
4000         {
4001           error ("expected %d levels of template parms for %q#D, got %d",
4002                  i, decl, TMPL_ARGS_DEPTH (args));
4003         }
4004       else
4005         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4006           {
4007             a = TMPL_ARGS_LEVEL (args, i);
4008             t = INNERMOST_TEMPLATE_PARMS (parms);
4009
4010             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4011               {
4012                 if (current == decl)
4013                   error ("got %d template parameters for %q#D",
4014                          TREE_VEC_LENGTH (a), decl);
4015                 else
4016                   error ("got %d template parameters for %q#T",
4017                          TREE_VEC_LENGTH (a), current);
4018                 error ("  but %d required", TREE_VEC_LENGTH (t));
4019                 return error_mark_node;
4020               }
4021
4022             if (current == decl)
4023               current = ctx;
4024             else
4025               current = (TYPE_P (current)
4026                          ? TYPE_CONTEXT (current)
4027                          : DECL_CONTEXT (current));
4028           }
4029
4030       /* Check that the parms are used in the appropriate qualifying scopes
4031          in the declarator.  */
4032       if (!comp_template_args
4033           (TI_ARGS (tinfo),
4034            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4035         {
4036           error ("\
4037 template arguments to %qD do not match original template %qD",
4038                  decl, DECL_TEMPLATE_RESULT (tmpl));
4039           if (!uses_template_parms (TI_ARGS (tinfo)))
4040             inform (input_location, "use template<> for an explicit specialization");
4041           /* Avoid crash in import_export_decl.  */
4042           DECL_INTERFACE_KNOWN (decl) = 1;
4043           return error_mark_node;
4044         }
4045     }
4046
4047   DECL_TEMPLATE_RESULT (tmpl) = decl;
4048   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4049
4050   /* Push template declarations for global functions and types.  Note
4051      that we do not try to push a global template friend declared in a
4052      template class; such a thing may well depend on the template
4053      parameters of the class.  */
4054   if (new_template_p && !ctx
4055       && !(is_friend && template_class_depth (current_class_type) > 0))
4056     {
4057       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4058       if (tmpl == error_mark_node)
4059         return error_mark_node;
4060
4061       /* Hide template friend classes that haven't been declared yet.  */
4062       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4063         {
4064           DECL_ANTICIPATED (tmpl) = 1;
4065           DECL_FRIEND_P (tmpl) = 1;
4066         }
4067     }
4068
4069   if (primary)
4070     {
4071       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4072       int i;
4073
4074       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4075       if (DECL_CONV_FN_P (tmpl))
4076         {
4077           int depth = TMPL_PARMS_DEPTH (parms);
4078
4079           /* It is a conversion operator. See if the type converted to
4080              depends on innermost template operands.  */
4081
4082           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4083                                          depth))
4084             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4085         }
4086
4087       /* Give template template parms a DECL_CONTEXT of the template
4088          for which they are a parameter.  */
4089       parms = INNERMOST_TEMPLATE_PARMS (parms);
4090       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4091         {
4092           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4093           if (TREE_CODE (parm) == TEMPLATE_DECL)
4094             DECL_CONTEXT (parm) = tmpl;
4095         }
4096     }
4097
4098   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4099      back to its most general template.  If TMPL is a specialization,
4100      ARGS may only have the innermost set of arguments.  Add the missing
4101      argument levels if necessary.  */
4102   if (DECL_TEMPLATE_INFO (tmpl))
4103     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4104
4105   info = tree_cons (tmpl, args, NULL_TREE);
4106
4107   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4108     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4109   else if (DECL_LANG_SPECIFIC (decl))
4110     DECL_TEMPLATE_INFO (decl) = info;
4111
4112   return DECL_TEMPLATE_RESULT (tmpl);
4113 }
4114
4115 tree
4116 push_template_decl (tree decl)
4117 {
4118   return push_template_decl_real (decl, false);
4119 }
4120
4121 /* Called when a class template TYPE is redeclared with the indicated
4122    template PARMS, e.g.:
4123
4124      template <class T> struct S;
4125      template <class T> struct S {};  */
4126
4127 bool
4128 redeclare_class_template (tree type, tree parms)
4129 {
4130   tree tmpl;
4131   tree tmpl_parms;
4132   int i;
4133
4134   if (!TYPE_TEMPLATE_INFO (type))
4135     {
4136       error ("%qT is not a template type", type);
4137       return false;
4138     }
4139
4140   tmpl = TYPE_TI_TEMPLATE (type);
4141   if (!PRIMARY_TEMPLATE_P (tmpl))
4142     /* The type is nested in some template class.  Nothing to worry
4143        about here; there are no new template parameters for the nested
4144        type.  */
4145     return true;
4146
4147   if (!parms)
4148     {
4149       error ("template specifiers not specified in declaration of %qD",
4150              tmpl);
4151       return false;
4152     }
4153
4154   parms = INNERMOST_TEMPLATE_PARMS (parms);
4155   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4156
4157   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4158     {
4159       error ("redeclared with %d template parameter(s)", 
4160              TREE_VEC_LENGTH (parms));
4161       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4162              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4163       return false;
4164     }
4165
4166   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4167     {
4168       tree tmpl_parm;
4169       tree parm;
4170       tree tmpl_default;
4171       tree parm_default;
4172
4173       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4174           || TREE_VEC_ELT (parms, i) == error_mark_node)
4175         continue;
4176
4177       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4178       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4179       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4180       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4181
4182       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4183          TEMPLATE_DECL.  */
4184       if (tmpl_parm != error_mark_node
4185           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4186               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4187                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4188               || (TREE_CODE (tmpl_parm) != PARM_DECL
4189                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4190                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4191               || (TREE_CODE (tmpl_parm) == PARM_DECL
4192                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4193                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4194         {
4195           error ("template parameter %q+#D", tmpl_parm);
4196           error ("redeclared here as %q#D", parm);
4197           return false;
4198         }
4199
4200       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4201         {
4202           /* We have in [temp.param]:
4203
4204              A template-parameter may not be given default arguments
4205              by two different declarations in the same scope.  */
4206           error ("redefinition of default argument for %q#D", parm);
4207           inform (input_location, "%Joriginal definition appeared here", tmpl_parm);
4208           return false;
4209         }
4210
4211       if (parm_default != NULL_TREE)
4212         /* Update the previous template parameters (which are the ones
4213            that will really count) with the new default value.  */
4214         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4215       else if (tmpl_default != NULL_TREE)
4216         /* Update the new parameters, too; they'll be used as the
4217            parameters for any members.  */
4218         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4219     }
4220
4221     return true;
4222 }
4223
4224 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4225    (possibly simplified) expression.  */
4226
4227 tree
4228 fold_non_dependent_expr (tree expr)
4229 {
4230   if (expr == NULL_TREE)
4231     return NULL_TREE;
4232
4233   /* If we're in a template, but EXPR isn't value dependent, simplify
4234      it.  We're supposed to treat:
4235
4236        template <typename T> void f(T[1 + 1]);
4237        template <typename T> void f(T[2]);
4238
4239      as two declarations of the same function, for example.  */
4240   if (processing_template_decl
4241       && !type_dependent_expression_p (expr)
4242       && !value_dependent_expression_p (expr))
4243     {
4244       HOST_WIDE_INT saved_processing_template_decl;
4245
4246       saved_processing_template_decl = processing_template_decl;
4247       processing_template_decl = 0;
4248       expr = tsubst_copy_and_build (expr,
4249                                     /*args=*/NULL_TREE,
4250                                     tf_error,
4251                                     /*in_decl=*/NULL_TREE,
4252                                     /*function_p=*/false,
4253                                     /*integral_constant_expression_p=*/true);
4254       processing_template_decl = saved_processing_template_decl;
4255     }
4256   return expr;
4257 }
4258
4259 /* EXPR is an expression which is used in a constant-expression context.
4260    For instance, it could be a VAR_DECL with a constant initializer.
4261    Extract the innermost constant expression.
4262
4263    This is basically a more powerful version of
4264    integral_constant_value, which can be used also in templates where
4265    initializers can maintain a syntactic rather than semantic form
4266    (even if they are non-dependent, for access-checking purposes).  */
4267
4268 static tree
4269 fold_decl_constant_value (tree expr)
4270 {
4271   tree const_expr = expr;
4272   do
4273     {
4274       expr = fold_non_dependent_expr (const_expr);
4275       const_expr = integral_constant_value (expr);
4276     }
4277   while (expr != const_expr);
4278
4279   return expr;
4280 }
4281
4282 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4283    must be a function or a pointer-to-function type, as specified
4284    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4285    and check that the resulting function has external linkage.  */
4286
4287 static tree
4288 convert_nontype_argument_function (tree type, tree expr)
4289 {
4290   tree fns = expr;
4291   tree fn, fn_no_ptr;
4292
4293   fn = instantiate_type (type, fns, tf_none);
4294   if (fn == error_mark_node)
4295     return error_mark_node;
4296
4297   fn_no_ptr = fn;
4298   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4299     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4300   if (TREE_CODE (fn_no_ptr) == BASELINK)
4301     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4302  
4303   /* [temp.arg.nontype]/1
4304
4305      A template-argument for a non-type, non-template template-parameter
4306      shall be one of:
4307      [...]
4308      -- the address of an object or function with external linkage.  */
4309   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4310     {
4311       error ("%qE is not a valid template argument for type %qT "
4312              "because function %qD has not external linkage",
4313              expr, type, fn_no_ptr);
4314       return NULL_TREE;
4315     }
4316
4317   return fn;
4318 }
4319
4320 /* Attempt to convert the non-type template parameter EXPR to the
4321    indicated TYPE.  If the conversion is successful, return the
4322    converted value.  If the conversion is unsuccessful, return
4323    NULL_TREE if we issued an error message, or error_mark_node if we
4324    did not.  We issue error messages for out-and-out bad template
4325    parameters, but not simply because the conversion failed, since we
4326    might be just trying to do argument deduction.  Both TYPE and EXPR
4327    must be non-dependent.
4328
4329    The conversion follows the special rules described in
4330    [temp.arg.nontype], and it is much more strict than an implicit
4331    conversion.
4332
4333    This function is called twice for each template argument (see
4334    lookup_template_class for a more accurate description of this
4335    problem). This means that we need to handle expressions which
4336    are not valid in a C++ source, but can be created from the
4337    first call (for instance, casts to perform conversions). These
4338    hacks can go away after we fix the double coercion problem.  */
4339
4340 static tree
4341 convert_nontype_argument (tree type, tree expr)
4342 {
4343   tree expr_type;
4344
4345   /* Detect immediately string literals as invalid non-type argument.
4346      This special-case is not needed for correctness (we would easily
4347      catch this later), but only to provide better diagnostic for this
4348      common user mistake. As suggested by DR 100, we do not mention
4349      linkage issues in the diagnostic as this is not the point.  */
4350   if (TREE_CODE (expr) == STRING_CST)
4351     {
4352       error ("%qE is not a valid template argument for type %qT "
4353              "because string literals can never be used in this context",
4354              expr, type);
4355       return NULL_TREE;
4356     }
4357
4358   /* If we are in a template, EXPR may be non-dependent, but still
4359      have a syntactic, rather than semantic, form.  For example, EXPR
4360      might be a SCOPE_REF, rather than the VAR_DECL to which the
4361      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4362      so that access checking can be performed when the template is
4363      instantiated -- but here we need the resolved form so that we can
4364      convert the argument.  */
4365   expr = fold_non_dependent_expr (expr);
4366   if (error_operand_p (expr))
4367     return error_mark_node;
4368   expr_type = TREE_TYPE (expr);
4369
4370   /* HACK: Due to double coercion, we can get a
4371      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4372      which is the tree that we built on the first call (see
4373      below when coercing to reference to object or to reference to
4374      function). We just strip everything and get to the arg.
4375      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4376      for examples.  */
4377   if (TREE_CODE (expr) == NOP_EXPR)
4378     {
4379       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4380         {
4381           /* ??? Maybe we could use convert_from_reference here, but we
4382              would need to relax its constraints because the NOP_EXPR
4383              could actually change the type to something more cv-qualified,
4384              and this is not folded by convert_from_reference.  */
4385           tree addr = TREE_OPERAND (expr, 0);
4386           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4387           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4388           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4389           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4390                       (TREE_TYPE (expr_type),
4391                        TREE_TYPE (TREE_TYPE (addr))));
4392
4393           expr = TREE_OPERAND (addr, 0);
4394           expr_type = TREE_TYPE (expr);
4395         }
4396
4397       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4398          parameter is a pointer to object, through decay and
4399          qualification conversion. Let's strip everything.  */
4400       else if (TYPE_PTROBV_P (type))
4401         {
4402           STRIP_NOPS (expr);
4403           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4404           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4405           /* Skip the ADDR_EXPR only if it is part of the decay for
4406              an array. Otherwise, it is part of the original argument
4407              in the source code.  */
4408           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4409             expr = TREE_OPERAND (expr, 0);
4410           expr_type = TREE_TYPE (expr);
4411         }
4412     }
4413
4414   /* [temp.arg.nontype]/5, bullet 1
4415
4416      For a non-type template-parameter of integral or enumeration type,
4417      integral promotions (_conv.prom_) and integral conversions
4418      (_conv.integral_) are applied.  */
4419   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4420     {
4421       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4422         return error_mark_node;
4423
4424       expr = fold_decl_constant_value (expr);
4425       /* Notice that there are constant expressions like '4 % 0' which
4426          do not fold into integer constants.  */
4427       if (TREE_CODE (expr) != INTEGER_CST)
4428         {
4429           error ("%qE is not a valid template argument for type %qT "
4430                  "because it is a non-constant expression", expr, type);
4431           return NULL_TREE;
4432         }
4433
4434       /* At this point, an implicit conversion does what we want,
4435          because we already know that the expression is of integral
4436          type.  */
4437       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4438       if (expr == error_mark_node)
4439         return error_mark_node;
4440
4441       /* Conversion was allowed: fold it to a bare integer constant.  */
4442       expr = fold (expr);
4443     }
4444   /* [temp.arg.nontype]/5, bullet 2
4445
4446      For a non-type template-parameter of type pointer to object,
4447      qualification conversions (_conv.qual_) and the array-to-pointer
4448      conversion (_conv.array_) are applied.  */
4449   else if (TYPE_PTROBV_P (type))
4450     {
4451       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4452
4453          A template-argument for a non-type, non-template template-parameter
4454          shall be one of: [...]
4455
4456          -- the name of a non-type template-parameter;
4457          -- the address of an object or function with external linkage, [...]
4458             expressed as "& id-expression" where the & is optional if the name
4459             refers to a function or array, or if the corresponding
4460             template-parameter is a reference.
4461
4462         Here, we do not care about functions, as they are invalid anyway
4463         for a parameter of type pointer-to-object.  */
4464
4465       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4466         /* Non-type template parameters are OK.  */
4467         ;
4468       else if (TREE_CODE (expr) != ADDR_EXPR
4469                && TREE_CODE (expr_type) != ARRAY_TYPE)
4470         {
4471           if (TREE_CODE (expr) == VAR_DECL)
4472             {
4473               error ("%qD is not a valid template argument "
4474                      "because %qD is a variable, not the address of "
4475                      "a variable",
4476                      expr, expr);
4477               return NULL_TREE;
4478             }
4479           /* Other values, like integer constants, might be valid
4480              non-type arguments of some other type.  */
4481           return error_mark_node;
4482         }
4483       else
4484         {
4485           tree decl;
4486
4487           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4488                   ? TREE_OPERAND (expr, 0) : expr);
4489           if (TREE_CODE (decl) != VAR_DECL)
4490             {
4491               error ("%qE is not a valid template argument of type %qT "
4492                      "because %qE is not a variable",
4493                      expr, type, decl);
4494               return NULL_TREE;
4495             }
4496           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4497             {
4498               error ("%qE is not a valid template argument of type %qT "
4499                      "because %qD does not have external linkage",
4500                      expr, type, decl);
4501               return NULL_TREE;
4502             }
4503         }
4504
4505       expr = decay_conversion (expr);
4506       if (expr == error_mark_node)
4507         return error_mark_node;
4508
4509       expr = perform_qualification_conversions (type, expr);
4510       if (expr == error_mark_node)
4511         return error_mark_node;
4512     }
4513   /* [temp.arg.nontype]/5, bullet 3
4514
4515      For a non-type template-parameter of type reference to object, no
4516      conversions apply. The type referred to by the reference may be more
4517      cv-qualified than the (otherwise identical) type of the
4518      template-argument. The template-parameter is bound directly to the
4519      template-argument, which must be an lvalue.  */
4520   else if (TYPE_REF_OBJ_P (type))
4521     {
4522       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4523                                                       expr_type))
4524         return error_mark_node;
4525
4526       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4527         {
4528           error ("%qE is not a valid template argument for type %qT "
4529                  "because of conflicts in cv-qualification", expr, type);
4530           return NULL_TREE;
4531         }
4532
4533       if (!real_lvalue_p (expr))
4534         {
4535           error ("%qE is not a valid template argument for type %qT "
4536                  "because it is not an lvalue", expr, type);
4537           return NULL_TREE;
4538         }
4539
4540       /* [temp.arg.nontype]/1
4541
4542          A template-argument for a non-type, non-template template-parameter
4543          shall be one of: [...]
4544
4545          -- the address of an object or function with external linkage.  */
4546       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4547         {
4548           error ("%qE is not a valid template argument for type %qT "
4549                  "because object %qD has not external linkage",
4550                  expr, type, expr);
4551           return NULL_TREE;
4552         }
4553
4554       expr = build_nop (type, build_address (expr));
4555     }
4556   /* [temp.arg.nontype]/5, bullet 4
4557
4558      For a non-type template-parameter of type pointer to function, only
4559      the function-to-pointer conversion (_conv.func_) is applied. If the
4560      template-argument represents a set of overloaded functions (or a
4561      pointer to such), the matching function is selected from the set
4562      (_over.over_).  */
4563   else if (TYPE_PTRFN_P (type))
4564     {
4565       /* If the argument is a template-id, we might not have enough
4566          context information to decay the pointer.  */
4567       if (!type_unknown_p (expr_type))
4568         {
4569           expr = decay_conversion (expr);
4570           if (expr == error_mark_node)
4571             return error_mark_node;
4572         }
4573
4574       expr = convert_nontype_argument_function (type, expr);
4575       if (!expr || expr == error_mark_node)
4576         return expr;
4577
4578       if (TREE_CODE (expr) != ADDR_EXPR)
4579         {
4580           error ("%qE is not a valid template argument for type %qT", expr, type);
4581           error ("it must be the address of a function with external linkage");
4582           return NULL_TREE;
4583         }
4584     }
4585   /* [temp.arg.nontype]/5, bullet 5
4586
4587      For a non-type template-parameter of type reference to function, no
4588      conversions apply. If the template-argument represents a set of
4589      overloaded functions, the matching function is selected from the set
4590      (_over.over_).  */
4591   else if (TYPE_REFFN_P (type))
4592     {
4593       if (TREE_CODE (expr) == ADDR_EXPR)
4594         {
4595           error ("%qE is not a valid template argument for type %qT "
4596                  "because it is a pointer", expr, type);
4597           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
4598           return NULL_TREE;
4599         }
4600
4601       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4602       if (!expr || expr == error_mark_node)
4603         return expr;
4604
4605       expr = build_nop (type, build_address (expr));
4606     }
4607   /* [temp.arg.nontype]/5, bullet 6
4608
4609      For a non-type template-parameter of type pointer to member function,
4610      no conversions apply. If the template-argument represents a set of
4611      overloaded member functions, the matching member function is selected
4612      from the set (_over.over_).  */
4613   else if (TYPE_PTRMEMFUNC_P (type))
4614     {
4615       expr = instantiate_type (type, expr, tf_none);
4616       if (expr == error_mark_node)
4617         return error_mark_node;
4618
4619       /* There is no way to disable standard conversions in
4620          resolve_address_of_overloaded_function (called by
4621          instantiate_type). It is possible that the call succeeded by
4622          converting &B::I to &D::I (where B is a base of D), so we need
4623          to reject this conversion here.
4624
4625          Actually, even if there was a way to disable standard conversions,
4626          it would still be better to reject them here so that we can
4627          provide a superior diagnostic.  */
4628       if (!same_type_p (TREE_TYPE (expr), type))
4629         {
4630           /* Make sure we are just one standard conversion off.  */
4631           gcc_assert (can_convert (type, TREE_TYPE (expr)));
4632           error ("%qE is not a valid template argument for type %qT "
4633                  "because it is of type %qT", expr, type,
4634                  TREE_TYPE (expr));
4635           inform (input_location, "standard conversions are not allowed in this context");
4636           return NULL_TREE;
4637         }
4638     }
4639   /* [temp.arg.nontype]/5, bullet 7
4640
4641      For a non-type template-parameter of type pointer to data member,
4642      qualification conversions (_conv.qual_) are applied.  */
4643   else if (TYPE_PTRMEM_P (type))
4644     {
4645       expr = perform_qualification_conversions (type, expr);
4646       if (expr == error_mark_node)
4647         return expr;
4648     }
4649   /* A template non-type parameter must be one of the above.  */
4650   else
4651     gcc_unreachable ();
4652
4653   /* Sanity check: did we actually convert the argument to the
4654      right type?  */
4655   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
4656   return expr;
4657 }
4658
4659 /* Subroutine of coerce_template_template_parms, which returns 1 if
4660    PARM_PARM and ARG_PARM match using the rule for the template
4661    parameters of template template parameters. Both PARM and ARG are
4662    template parameters; the rest of the arguments are the same as for
4663    coerce_template_template_parms.
4664  */
4665 static int
4666 coerce_template_template_parm (tree parm,
4667                               tree arg,
4668                               tsubst_flags_t complain,
4669                               tree in_decl,
4670                               tree outer_args)
4671 {
4672   if (arg == NULL_TREE || arg == error_mark_node
4673       || parm == NULL_TREE || parm == error_mark_node)
4674     return 0;
4675   
4676   if (TREE_CODE (arg) != TREE_CODE (parm))
4677     return 0;
4678   
4679   switch (TREE_CODE (parm))
4680     {
4681     case TEMPLATE_DECL:
4682       /* We encounter instantiations of templates like
4683          template <template <template <class> class> class TT>
4684          class C;  */
4685       {
4686         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4687         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4688         
4689         if (!coerce_template_template_parms
4690             (parmparm, argparm, complain, in_decl, outer_args))
4691           return 0;
4692       }
4693       /* Fall through.  */
4694       
4695     case TYPE_DECL:
4696       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
4697           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4698         /* Argument is a parameter pack but parameter is not.  */
4699         return 0;
4700       break;
4701       
4702     case PARM_DECL:
4703       /* The tsubst call is used to handle cases such as
4704          
4705            template <int> class C {};
4706            template <class T, template <T> class TT> class D {};
4707            D<int, C> d;
4708
4709          i.e. the parameter list of TT depends on earlier parameters.  */
4710       if (!uses_template_parms (TREE_TYPE (arg))
4711           && !same_type_p
4712                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
4713                  TREE_TYPE (arg)))
4714         return 0;
4715       
4716       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
4717           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4718         /* Argument is a parameter pack but parameter is not.  */
4719         return 0;
4720       
4721       break;
4722
4723     default:
4724       gcc_unreachable ();
4725     }
4726
4727   return 1;
4728 }
4729
4730
4731 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
4732    template template parameters.  Both PARM_PARMS and ARG_PARMS are
4733    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
4734    or PARM_DECL.
4735
4736    Consider the example:
4737      template <class T> class A;
4738      template<template <class U> class TT> class B;
4739
4740    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
4741    the parameters to A, and OUTER_ARGS contains A.  */
4742
4743 static int
4744 coerce_template_template_parms (tree parm_parms,
4745                                 tree arg_parms,
4746                                 tsubst_flags_t complain,
4747                                 tree in_decl,
4748                                 tree outer_args)
4749 {
4750   int nparms, nargs, i;
4751   tree parm, arg;
4752   int variadic_p = 0;
4753
4754   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
4755   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
4756
4757   nparms = TREE_VEC_LENGTH (parm_parms);
4758   nargs = TREE_VEC_LENGTH (arg_parms);
4759
4760   /* Determine whether we have a parameter pack at the end of the
4761      template template parameter's template parameter list.  */
4762   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
4763     {
4764       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
4765       
4766       if (parm == error_mark_node)
4767         return 0;
4768
4769       switch (TREE_CODE (parm))
4770         {
4771         case TEMPLATE_DECL:
4772         case TYPE_DECL:
4773           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4774             variadic_p = 1;
4775           break;
4776           
4777         case PARM_DECL:
4778           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4779             variadic_p = 1;
4780           break;
4781           
4782         default:
4783           gcc_unreachable ();
4784         }
4785     }
4786  
4787   if (nargs != nparms
4788       && !(variadic_p && nargs >= nparms - 1))
4789     return 0;
4790
4791   /* Check all of the template parameters except the parameter pack at
4792      the end (if any).  */
4793   for (i = 0; i < nparms - variadic_p; ++i)
4794     {
4795       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
4796           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4797         continue;
4798
4799       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4800       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4801
4802       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4803                                           outer_args))
4804         return 0;
4805
4806     }
4807
4808   if (variadic_p)
4809     {
4810       /* Check each of the template parameters in the template
4811          argument against the template parameter pack at the end of
4812          the template template parameter.  */
4813       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
4814         return 0;
4815
4816       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4817
4818       for (; i < nargs; ++i)
4819         {
4820           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4821             continue;
4822  
4823           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4824  
4825           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4826                                               outer_args))
4827             return 0;
4828         }
4829     }
4830
4831   return 1;
4832 }
4833
4834 /* Verifies that the deduced template arguments (in TARGS) for the
4835    template template parameters (in TPARMS) represent valid bindings,
4836    by comparing the template parameter list of each template argument
4837    to the template parameter list of its corresponding template
4838    template parameter, in accordance with DR150. This
4839    routine can only be called after all template arguments have been
4840    deduced. It will return TRUE if all of the template template
4841    parameter bindings are okay, FALSE otherwise.  */
4842 bool 
4843 template_template_parm_bindings_ok_p (tree tparms, tree targs)
4844 {
4845   int i, ntparms = TREE_VEC_LENGTH (tparms);
4846   bool ret = true;
4847
4848   /* We're dealing with template parms in this process.  */
4849   ++processing_template_decl;
4850
4851   targs = INNERMOST_TEMPLATE_ARGS (targs);
4852
4853   for (i = 0; i < ntparms; ++i)
4854     {
4855       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
4856       tree targ = TREE_VEC_ELT (targs, i);
4857
4858       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
4859         {
4860           tree packed_args = NULL_TREE;
4861           int idx, len = 1;
4862
4863           if (ARGUMENT_PACK_P (targ))
4864             {
4865               /* Look inside the argument pack.  */
4866               packed_args = ARGUMENT_PACK_ARGS (targ);
4867               len = TREE_VEC_LENGTH (packed_args);
4868             }
4869
4870           for (idx = 0; idx < len; ++idx)
4871             {
4872               tree targ_parms = NULL_TREE;
4873
4874               if (packed_args)
4875                 /* Extract the next argument from the argument
4876                    pack.  */
4877                 targ = TREE_VEC_ELT (packed_args, idx);
4878
4879               if (PACK_EXPANSION_P (targ))
4880                 /* Look at the pattern of the pack expansion.  */
4881                 targ = PACK_EXPANSION_PATTERN (targ);
4882
4883               /* Extract the template parameters from the template
4884                  argument.  */
4885               if (TREE_CODE (targ) == TEMPLATE_DECL)
4886                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
4887               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
4888                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
4889
4890               /* Verify that we can coerce the template template
4891                  parameters from the template argument to the template
4892                  parameter.  This requires an exact match.  */
4893               if (targ_parms
4894                   && !coerce_template_template_parms
4895                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
4896                         targ_parms,
4897                         tf_none,
4898                         tparm,
4899                         targs))
4900                 {
4901                   ret = false;
4902                   goto out;
4903                 }
4904             }
4905         }
4906     }
4907
4908  out:
4909
4910   --processing_template_decl;
4911   return ret;
4912 }
4913
4914 /* Convert the indicated template ARG as necessary to match the
4915    indicated template PARM.  Returns the converted ARG, or
4916    error_mark_node if the conversion was unsuccessful.  Error and
4917    warning messages are issued under control of COMPLAIN.  This
4918    conversion is for the Ith parameter in the parameter list.  ARGS is
4919    the full set of template arguments deduced so far.  */
4920
4921 static tree
4922 convert_template_argument (tree parm,
4923                            tree arg,
4924                            tree args,
4925                            tsubst_flags_t complain,
4926                            int i,
4927                            tree in_decl)
4928 {
4929   tree orig_arg;
4930   tree val;
4931   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
4932
4933   if (TREE_CODE (arg) == TREE_LIST
4934       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
4935     {
4936       /* The template argument was the name of some
4937          member function.  That's usually
4938          invalid, but static members are OK.  In any
4939          case, grab the underlying fields/functions
4940          and issue an error later if required.  */
4941       orig_arg = TREE_VALUE (arg);
4942       TREE_TYPE (arg) = unknown_type_node;
4943     }
4944
4945   orig_arg = arg;
4946
4947   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
4948   requires_type = (TREE_CODE (parm) == TYPE_DECL
4949                    || requires_tmpl_type);
4950
4951   /* When determining whether an argument pack expansion is a template,
4952      look at the pattern.  */
4953   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
4954     arg = PACK_EXPANSION_PATTERN (arg);
4955
4956   is_tmpl_type = 
4957     ((TREE_CODE (arg) == TEMPLATE_DECL
4958       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
4959      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4960      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
4961
4962   if (is_tmpl_type
4963       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4964           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
4965     arg = TYPE_STUB_DECL (arg);
4966
4967   is_type = TYPE_P (arg) || is_tmpl_type;
4968
4969   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
4970       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
4971     {
4972       permerror (input_location, "to refer to a type member of a template parameter, "
4973                  "use %<typename %E%>", orig_arg);
4974
4975       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
4976                                      TREE_OPERAND (arg, 1),
4977                                      typename_type,
4978                                      complain & tf_error);
4979       arg = orig_arg;
4980       is_type = 1;
4981     }
4982   if (is_type != requires_type)
4983     {
4984       if (in_decl)
4985         {
4986           if (complain & tf_error)
4987             {
4988               error ("type/value mismatch at argument %d in template "
4989                      "parameter list for %qD",
4990                      i + 1, in_decl);
4991               if (is_type)
4992                 error ("  expected a constant of type %qT, got %qT",
4993                        TREE_TYPE (parm),
4994                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
4995               else if (requires_tmpl_type)
4996                 error ("  expected a class template, got %qE", orig_arg);
4997               else
4998                 error ("  expected a type, got %qE", orig_arg);
4999             }
5000         }
5001       return error_mark_node;
5002     }
5003   if (is_tmpl_type ^ requires_tmpl_type)
5004     {
5005       if (in_decl && (complain & tf_error))
5006         {
5007           error ("type/value mismatch at argument %d in template "
5008                  "parameter list for %qD",
5009                  i + 1, in_decl);
5010           if (is_tmpl_type)
5011             error ("  expected a type, got %qT", DECL_NAME (arg));
5012           else
5013             error ("  expected a class template, got %qT", orig_arg);
5014         }
5015       return error_mark_node;
5016     }
5017
5018   if (is_type)
5019     {
5020       if (requires_tmpl_type)
5021         {
5022           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5023             /* The number of argument required is not known yet.
5024                Just accept it for now.  */
5025             val = TREE_TYPE (arg);
5026           else
5027             {
5028               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5029               tree argparm;
5030
5031               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5032
5033               if (coerce_template_template_parms (parmparm, argparm,
5034                                                   complain, in_decl,
5035                                                   args))
5036                 {
5037                   val = orig_arg;
5038
5039                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5040                      TEMPLATE_DECL.  */
5041                   if (val != error_mark_node)
5042                     {
5043                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5044                         val = TREE_TYPE (val);
5045                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
5046                                && DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
5047                         {
5048                           val = TREE_TYPE (arg);
5049                           val = make_pack_expansion (val);
5050                         }
5051                     }
5052                 }
5053               else
5054                 {
5055                   if (in_decl && (complain & tf_error))
5056                     {
5057                       error ("type/value mismatch at argument %d in "
5058                              "template parameter list for %qD",
5059                              i + 1, in_decl);
5060                       error ("  expected a template of type %qD, got %qD",
5061                              parm, orig_arg);
5062                     }
5063
5064                   val = error_mark_node;
5065                 }
5066             }
5067         }
5068       else
5069         val = orig_arg;
5070       /* We only form one instance of each template specialization.
5071          Therefore, if we use a non-canonical variant (i.e., a
5072          typedef), any future messages referring to the type will use
5073          the typedef, which is confusing if those future uses do not
5074          themselves also use the typedef.  */
5075       if (TYPE_P (val))
5076         val = strip_typedefs (val);
5077     }
5078   else
5079     {
5080       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5081
5082       if (invalid_nontype_parm_type_p (t, complain))
5083         return error_mark_node;
5084
5085       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5086         {
5087           if (same_type_p (t, TREE_TYPE (orig_arg)))
5088             val = orig_arg;
5089           else
5090             {
5091               /* Not sure if this is reachable, but it doesn't hurt
5092                  to be robust.  */
5093               error ("type mismatch in nontype parameter pack");
5094               val = error_mark_node;
5095             }
5096         }
5097       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5098         /* We used to call digest_init here.  However, digest_init
5099            will report errors, which we don't want when complain
5100            is zero.  More importantly, digest_init will try too
5101            hard to convert things: for example, `0' should not be
5102            converted to pointer type at this point according to
5103            the standard.  Accepting this is not merely an
5104            extension, since deciding whether or not these
5105            conversions can occur is part of determining which
5106            function template to call, or whether a given explicit
5107            argument specification is valid.  */
5108         val = convert_nontype_argument (t, orig_arg);
5109       else
5110         val = orig_arg;
5111
5112       if (val == NULL_TREE)
5113         val = error_mark_node;
5114       else if (val == error_mark_node && (complain & tf_error))
5115         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5116     }
5117
5118   return val;
5119 }
5120
5121 /* Coerces the remaining template arguments in INNER_ARGS (from
5122    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5123    Returns the coerced argument pack. PARM_IDX is the position of this
5124    parameter in the template parameter list. ARGS is the original
5125    template argument list.  */
5126 static tree
5127 coerce_template_parameter_pack (tree parms,
5128                                 int parm_idx,
5129                                 tree args,
5130                                 tree inner_args,
5131                                 int arg_idx,
5132                                 tree new_args,
5133                                 int* lost,
5134                                 tree in_decl,
5135                                 tsubst_flags_t complain)
5136 {
5137   tree parm = TREE_VEC_ELT (parms, parm_idx);
5138   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5139   tree packed_args;
5140   tree argument_pack;
5141   tree packed_types = NULL_TREE;
5142
5143   if (arg_idx > nargs)
5144     arg_idx = nargs;
5145
5146   packed_args = make_tree_vec (nargs - arg_idx);
5147
5148   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5149       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5150     {
5151       /* When the template parameter is a non-type template
5152          parameter pack whose type uses parameter packs, we need
5153          to look at each of the template arguments
5154          separately. Build a vector of the types for these
5155          non-type template parameters in PACKED_TYPES.  */
5156       tree expansion 
5157         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5158       packed_types = tsubst_pack_expansion (expansion, args,
5159                                             complain, in_decl);
5160
5161       if (packed_types == error_mark_node)
5162         return error_mark_node;
5163
5164       /* Check that we have the right number of arguments.  */
5165       if (arg_idx < nargs
5166           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5167           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5168         {
5169           int needed_parms 
5170             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5171           error ("wrong number of template arguments (%d, should be %d)",
5172                  nargs, needed_parms);
5173           return error_mark_node;
5174         }
5175
5176       /* If we aren't able to check the actual arguments now
5177          (because they haven't been expanded yet), we can at least
5178          verify that all of the types used for the non-type
5179          template parameter pack are, in fact, valid for non-type
5180          template parameters.  */
5181       if (arg_idx < nargs 
5182           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5183         {
5184           int j, len = TREE_VEC_LENGTH (packed_types);
5185           for (j = 0; j < len; ++j)
5186             {
5187               tree t = TREE_VEC_ELT (packed_types, j);
5188               if (invalid_nontype_parm_type_p (t, complain))
5189                 return error_mark_node;
5190             }
5191         }
5192     }
5193
5194   /* Convert the remaining arguments, which will be a part of the
5195      parameter pack "parm".  */
5196   for (; arg_idx < nargs; ++arg_idx)
5197     {
5198       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5199       tree actual_parm = TREE_VALUE (parm);
5200
5201       if (packed_types && !PACK_EXPANSION_P (arg))
5202         {
5203           /* When we have a vector of types (corresponding to the
5204              non-type template parameter pack that uses parameter
5205              packs in its type, as mention above), and the
5206              argument is not an expansion (which expands to a
5207              currently unknown number of arguments), clone the
5208              parm and give it the next type in PACKED_TYPES.  */
5209           actual_parm = copy_node (actual_parm);
5210           TREE_TYPE (actual_parm) = 
5211             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5212         }
5213
5214       if (arg != error_mark_node)
5215         arg = convert_template_argument (actual_parm, 
5216                                          arg, new_args, complain, parm_idx,
5217                                          in_decl);
5218       if (arg == error_mark_node)
5219         (*lost)++;
5220       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5221     }
5222
5223   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5224       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5225     argument_pack = make_node (TYPE_ARGUMENT_PACK);
5226   else
5227     {
5228       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5229       TREE_TYPE (argument_pack) 
5230         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5231       TREE_CONSTANT (argument_pack) = 1;
5232     }
5233
5234   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5235   return argument_pack;
5236 }
5237
5238 /* Convert all template arguments to their appropriate types, and
5239    return a vector containing the innermost resulting template
5240    arguments.  If any error occurs, return error_mark_node. Error and
5241    warning messages are issued under control of COMPLAIN.
5242
5243    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5244    for arguments not specified in ARGS.  Otherwise, if
5245    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5246    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5247    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5248    ARGS.  */
5249
5250 static tree
5251 coerce_template_parms (tree parms,
5252                        tree args,
5253                        tree in_decl,
5254                        tsubst_flags_t complain,
5255                        bool require_all_args,
5256                        bool use_default_args)
5257 {
5258   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5259   tree inner_args;
5260   tree new_args;
5261   tree new_inner_args;
5262   bool saved_skip_evaluation;
5263
5264   /* When used as a boolean value, indicates whether this is a
5265      variadic template parameter list. Since it's an int, we can also
5266      subtract it from nparms to get the number of non-variadic
5267      parameters.  */
5268   int variadic_p = 0;
5269
5270   nparms = TREE_VEC_LENGTH (parms);
5271
5272   /* Determine if there are any parameter packs.  */
5273   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5274     {
5275       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5276       if (template_parameter_pack_p (tparm))
5277         ++variadic_p;
5278     }
5279
5280   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5281   /* If there are 0 or 1 parameter packs, we need to expand any argument
5282      packs so that we can deduce a parameter pack from some non-packed args
5283      followed by an argument pack, as in variadic85.C.  If there are more
5284      than that, we need to leave argument packs intact so the arguments are
5285      assigned to the right parameter packs.  This should only happen when
5286      dealing with a nested class inside a partial specialization of a class
5287      template, as in variadic92.C.  */
5288   if (variadic_p <= 1)
5289     inner_args = expand_template_argument_pack (inner_args);
5290
5291   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5292   if ((nargs > nparms && !variadic_p)
5293       || (nargs < nparms - variadic_p
5294           && require_all_args
5295           && (!use_default_args
5296               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5297                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5298     {
5299       if (complain & tf_error)
5300         {
5301           const char *or_more = "";
5302           if (variadic_p)
5303             {
5304               or_more = " or more";
5305               --nparms;
5306             }
5307
5308           error ("wrong number of template arguments (%d, should be %d%s)",
5309                  nargs, nparms, or_more);
5310
5311           if (in_decl)
5312             error ("provided for %q+D", in_decl);
5313         }
5314
5315       return error_mark_node;
5316     }
5317
5318   /* We need to evaluate the template arguments, even though this
5319      template-id may be nested within a "sizeof".  */
5320   saved_skip_evaluation = skip_evaluation;
5321   skip_evaluation = false;
5322   new_inner_args = make_tree_vec (nparms);
5323   new_args = add_outermost_template_args (args, new_inner_args);
5324   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5325     {
5326       tree arg;
5327       tree parm;
5328
5329       /* Get the Ith template parameter.  */
5330       parm = TREE_VEC_ELT (parms, parm_idx);
5331  
5332       if (parm == error_mark_node)
5333       {
5334         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5335         continue;
5336       }
5337
5338       /* Calculate the next argument.  */
5339       if (arg_idx < nargs)
5340         arg = TREE_VEC_ELT (inner_args, arg_idx);
5341       else
5342         arg = NULL_TREE;
5343
5344       if (template_parameter_pack_p (TREE_VALUE (parm))
5345           && !(arg && ARGUMENT_PACK_P (arg)))
5346         {
5347           /* All remaining arguments will be placed in the
5348              template parameter pack PARM.  */
5349           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5350                                                 inner_args, arg_idx,
5351                                                 new_args, &lost,
5352                                                 in_decl, complain);
5353
5354           /* Store this argument.  */
5355           if (arg == error_mark_node)
5356             lost++;
5357           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5358
5359           /* We are done with all of the arguments.  */
5360           arg_idx = nargs;
5361           
5362           continue;
5363         }
5364       else if (arg)
5365         {
5366           if (PACK_EXPANSION_P (arg))
5367             {
5368               if (complain & tf_error)
5369                 {
5370                   /* FIXME this restriction was removed by N2555; see
5371                      bug 35722.  */
5372                   /* If ARG is a pack expansion, but PARM is not a
5373                      template parameter pack (if it were, we would have
5374                      handled it above), we're trying to expand into a
5375                      fixed-length argument list.  */
5376                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5377                     sorry ("cannot expand %<%E%> into a fixed-length "
5378                            "argument list", arg);
5379                   else
5380                     sorry ("cannot expand %<%T%> into a fixed-length "
5381                            "argument list", arg);
5382                 }
5383               return error_mark_node;
5384             }
5385         }
5386       else if (require_all_args)
5387         /* There must be a default arg in this case.  */
5388         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5389                                    complain, in_decl);
5390       else
5391         break;
5392
5393       if (arg == error_mark_node)
5394         {
5395           if (complain & tf_error)
5396             error ("template argument %d is invalid", arg_idx + 1);
5397         }
5398       else if (!arg)
5399         /* This only occurs if there was an error in the template
5400            parameter list itself (which we would already have
5401            reported) that we are trying to recover from, e.g., a class
5402            template with a parameter list such as
5403            template<typename..., typename>.  */
5404         return error_mark_node;
5405       else
5406         arg = convert_template_argument (TREE_VALUE (parm),
5407                                          arg, new_args, complain, 
5408                                          parm_idx, in_decl);
5409
5410       if (arg == error_mark_node)
5411         lost++;
5412       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5413     }
5414   skip_evaluation = saved_skip_evaluation;
5415
5416   if (lost)
5417     return error_mark_node;
5418
5419   return new_inner_args;
5420 }
5421
5422 /* Returns 1 if template args OT and NT are equivalent.  */
5423
5424 static int
5425 template_args_equal (tree ot, tree nt)
5426 {
5427   if (nt == ot)
5428     return 1;
5429
5430   if (TREE_CODE (nt) == TREE_VEC)
5431     /* For member templates */
5432     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5433   else if (PACK_EXPANSION_P (ot))
5434     return PACK_EXPANSION_P (nt) 
5435       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5436                               PACK_EXPANSION_PATTERN (nt));
5437   else if (ARGUMENT_PACK_P (ot))
5438     {
5439       int i, len;
5440       tree opack, npack;
5441
5442       if (!ARGUMENT_PACK_P (nt))
5443         return 0;
5444
5445       opack = ARGUMENT_PACK_ARGS (ot);
5446       npack = ARGUMENT_PACK_ARGS (nt);
5447       len = TREE_VEC_LENGTH (opack);
5448       if (TREE_VEC_LENGTH (npack) != len)
5449         return 0;
5450       for (i = 0; i < len; ++i)
5451         if (!template_args_equal (TREE_VEC_ELT (opack, i),
5452                                   TREE_VEC_ELT (npack, i)))
5453           return 0;
5454       return 1;
5455     }
5456   else if (TYPE_P (nt))
5457     return TYPE_P (ot) && same_type_p (ot, nt);
5458   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5459     return 0;
5460   else
5461     return cp_tree_equal (ot, nt);
5462 }
5463
5464 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5465    of template arguments.  Returns 0 otherwise.  */
5466
5467 int
5468 comp_template_args (tree oldargs, tree newargs)
5469 {
5470   int i;
5471
5472   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5473     return 0;
5474
5475   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5476     {
5477       tree nt = TREE_VEC_ELT (newargs, i);
5478       tree ot = TREE_VEC_ELT (oldargs, i);
5479
5480       if (! template_args_equal (ot, nt))
5481         return 0;
5482     }
5483   return 1;
5484 }
5485
5486 static void
5487 add_pending_template (tree d)
5488 {
5489   tree ti = (TYPE_P (d)
5490              ? CLASSTYPE_TEMPLATE_INFO (d)
5491              : DECL_TEMPLATE_INFO (d));
5492   struct pending_template *pt;
5493   int level;
5494
5495   if (TI_PENDING_TEMPLATE_FLAG (ti))
5496     return;
5497
5498   /* We are called both from instantiate_decl, where we've already had a
5499      tinst_level pushed, and instantiate_template, where we haven't.
5500      Compensate.  */
5501   level = !current_tinst_level || current_tinst_level->decl != d;
5502
5503   if (level)
5504     push_tinst_level (d);
5505
5506   pt = GGC_NEW (struct pending_template);
5507   pt->next = NULL;
5508   pt->tinst = current_tinst_level;
5509   if (last_pending_template)
5510     last_pending_template->next = pt;
5511   else
5512     pending_templates = pt;
5513
5514   last_pending_template = pt;
5515
5516   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5517
5518   if (level)
5519     pop_tinst_level ();
5520 }
5521
5522
5523 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5524    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5525    documentation for TEMPLATE_ID_EXPR.  */
5526
5527 tree
5528 lookup_template_function (tree fns, tree arglist)
5529 {
5530   tree type;
5531
5532   if (fns == error_mark_node || arglist == error_mark_node)
5533     return error_mark_node;
5534
5535   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5536   gcc_assert (fns && (is_overloaded_fn (fns)
5537                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5538
5539   if (BASELINK_P (fns))
5540     {
5541       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5542                                          unknown_type_node,
5543                                          BASELINK_FUNCTIONS (fns),
5544                                          arglist);
5545       return fns;
5546     }
5547
5548   type = TREE_TYPE (fns);
5549   if (TREE_CODE (fns) == OVERLOAD || !type)
5550     type = unknown_type_node;
5551
5552   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5553 }
5554
5555 /* Within the scope of a template class S<T>, the name S gets bound
5556    (in build_self_reference) to a TYPE_DECL for the class, not a
5557    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5558    or one of its enclosing classes, and that type is a template,
5559    return the associated TEMPLATE_DECL.  Otherwise, the original
5560    DECL is returned.  */
5561
5562 tree
5563 maybe_get_template_decl_from_type_decl (tree decl)
5564 {
5565   return (decl != NULL_TREE
5566           && TREE_CODE (decl) == TYPE_DECL
5567           && DECL_ARTIFICIAL (decl)
5568           && CLASS_TYPE_P (TREE_TYPE (decl))
5569           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5570     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5571 }
5572
5573 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5574    parameters, find the desired type.
5575
5576    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5577
5578    IN_DECL, if non-NULL, is the template declaration we are trying to
5579    instantiate.
5580
5581    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5582    the class we are looking up.
5583
5584    Issue error and warning messages under control of COMPLAIN.
5585
5586    If the template class is really a local class in a template
5587    function, then the FUNCTION_CONTEXT is the function in which it is
5588    being instantiated.
5589
5590    ??? Note that this function is currently called *twice* for each
5591    template-id: the first time from the parser, while creating the
5592    incomplete type (finish_template_type), and the second type during the
5593    real instantiation (instantiate_template_class). This is surely something
5594    that we want to avoid. It also causes some problems with argument
5595    coercion (see convert_nontype_argument for more information on this).  */
5596
5597 tree
5598 lookup_template_class (tree d1,
5599                        tree arglist,
5600                        tree in_decl,
5601                        tree context,
5602                        int entering_scope,
5603                        tsubst_flags_t complain)
5604 {
5605   tree templ = NULL_TREE, parmlist;
5606   tree t;
5607
5608   timevar_push (TV_NAME_LOOKUP);
5609
5610   if (TREE_CODE (d1) == IDENTIFIER_NODE)
5611     {
5612       tree value = innermost_non_namespace_value (d1);
5613       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
5614         templ = value;
5615       else
5616         {
5617           if (context)
5618             push_decl_namespace (context);
5619           templ = lookup_name (d1);
5620           templ = maybe_get_template_decl_from_type_decl (templ);
5621           if (context)
5622             pop_decl_namespace ();
5623         }
5624       if (templ)
5625         context = DECL_CONTEXT (templ);
5626     }
5627   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
5628     {
5629       tree type = TREE_TYPE (d1);
5630
5631       /* If we are declaring a constructor, say A<T>::A<T>, we will get
5632          an implicit typename for the second A.  Deal with it.  */
5633       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
5634         type = TREE_TYPE (type);
5635
5636       if (CLASSTYPE_TEMPLATE_INFO (type))
5637         {
5638           templ = CLASSTYPE_TI_TEMPLATE (type);
5639           d1 = DECL_NAME (templ);
5640         }
5641     }
5642   else if (TREE_CODE (d1) == ENUMERAL_TYPE
5643            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
5644     {
5645       templ = TYPE_TI_TEMPLATE (d1);
5646       d1 = DECL_NAME (templ);
5647     }
5648   else if (TREE_CODE (d1) == TEMPLATE_DECL
5649            && DECL_TEMPLATE_RESULT (d1)
5650            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
5651     {
5652       templ = d1;
5653       d1 = DECL_NAME (templ);
5654       context = DECL_CONTEXT (templ);
5655     }
5656
5657   /* Issue an error message if we didn't find a template.  */
5658   if (! templ)
5659     {
5660       if (complain & tf_error)
5661         error ("%qT is not a template", d1);
5662       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5663     }
5664
5665   if (TREE_CODE (templ) != TEMPLATE_DECL
5666          /* Make sure it's a user visible template, if it was named by
5667             the user.  */
5668       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
5669           && !PRIMARY_TEMPLATE_P (templ)))
5670     {
5671       if (complain & tf_error)
5672         {
5673           error ("non-template type %qT used as a template", d1);
5674           if (in_decl)
5675             error ("for template declaration %q+D", in_decl);
5676         }
5677       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5678     }
5679
5680   complain &= ~tf_user;
5681
5682   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
5683     {
5684       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
5685          template arguments */
5686
5687       tree parm;
5688       tree arglist2;
5689       tree outer;
5690
5691       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
5692
5693       /* Consider an example where a template template parameter declared as
5694
5695            template <class T, class U = std::allocator<T> > class TT
5696
5697          The template parameter level of T and U are one level larger than
5698          of TT.  To proper process the default argument of U, say when an
5699          instantiation `TT<int>' is seen, we need to build the full
5700          arguments containing {int} as the innermost level.  Outer levels,
5701          available when not appearing as default template argument, can be
5702          obtained from the arguments of the enclosing template.
5703
5704          Suppose that TT is later substituted with std::vector.  The above
5705          instantiation is `TT<int, std::allocator<T> >' with TT at
5706          level 1, and T at level 2, while the template arguments at level 1
5707          becomes {std::vector} and the inner level 2 is {int}.  */
5708
5709       outer = DECL_CONTEXT (templ);
5710       if (outer)
5711         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
5712       else if (current_template_parms)
5713         /* This is an argument of the current template, so we haven't set
5714            DECL_CONTEXT yet.  */
5715         outer = current_template_args ();
5716
5717       if (outer)
5718         arglist = add_to_template_args (outer, arglist);
5719
5720       arglist2 = coerce_template_parms (parmlist, arglist, templ,
5721                                         complain,
5722                                         /*require_all_args=*/true,
5723                                         /*use_default_args=*/true);
5724       if (arglist2 == error_mark_node
5725           || (!uses_template_parms (arglist2)
5726               && check_instantiated_args (templ, arglist2, complain)))
5727         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5728
5729       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
5730       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
5731     }
5732   else
5733     {
5734       tree template_type = TREE_TYPE (templ);
5735       tree gen_tmpl;
5736       tree type_decl;
5737       tree found = NULL_TREE;
5738       int arg_depth;
5739       int parm_depth;
5740       int is_partial_instantiation;
5741
5742       gen_tmpl = most_general_template (templ);
5743       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
5744       parm_depth = TMPL_PARMS_DEPTH (parmlist);
5745       arg_depth = TMPL_ARGS_DEPTH (arglist);
5746
5747       if (arg_depth == 1 && parm_depth > 1)
5748         {
5749           /* We've been given an incomplete set of template arguments.
5750              For example, given:
5751
5752                template <class T> struct S1 {
5753                  template <class U> struct S2 {};
5754                  template <class U> struct S2<U*> {};
5755                 };
5756
5757              we will be called with an ARGLIST of `U*', but the
5758              TEMPLATE will be `template <class T> template
5759              <class U> struct S1<T>::S2'.  We must fill in the missing
5760              arguments.  */
5761           arglist
5762             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
5763                                            arglist);
5764           arg_depth = TMPL_ARGS_DEPTH (arglist);
5765         }
5766
5767       /* Now we should have enough arguments.  */
5768       gcc_assert (parm_depth == arg_depth);
5769
5770       /* From here on, we're only interested in the most general
5771          template.  */
5772       templ = gen_tmpl;
5773
5774       /* Calculate the BOUND_ARGS.  These will be the args that are
5775          actually tsubst'd into the definition to create the
5776          instantiation.  */
5777       if (parm_depth > 1)
5778         {
5779           /* We have multiple levels of arguments to coerce, at once.  */
5780           int i;
5781           int saved_depth = TMPL_ARGS_DEPTH (arglist);
5782
5783           tree bound_args = make_tree_vec (parm_depth);
5784
5785           for (i = saved_depth,
5786                  t = DECL_TEMPLATE_PARMS (templ);
5787                i > 0 && t != NULL_TREE;
5788                --i, t = TREE_CHAIN (t))
5789             {
5790               tree a = coerce_template_parms (TREE_VALUE (t),
5791                                               arglist, templ,
5792                                               complain,
5793                                               /*require_all_args=*/true,
5794                                               /*use_default_args=*/true);
5795
5796               /* Don't process further if one of the levels fails.  */
5797               if (a == error_mark_node)
5798                 {
5799                   /* Restore the ARGLIST to its full size.  */
5800                   TREE_VEC_LENGTH (arglist) = saved_depth;
5801                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5802                 }
5803
5804               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
5805
5806               /* We temporarily reduce the length of the ARGLIST so
5807                  that coerce_template_parms will see only the arguments
5808                  corresponding to the template parameters it is
5809                  examining.  */
5810               TREE_VEC_LENGTH (arglist)--;
5811             }
5812
5813           /* Restore the ARGLIST to its full size.  */
5814           TREE_VEC_LENGTH (arglist) = saved_depth;
5815
5816           arglist = bound_args;
5817         }
5818       else
5819         arglist
5820           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
5821                                    INNERMOST_TEMPLATE_ARGS (arglist),
5822                                    templ,
5823                                    complain,
5824                                    /*require_all_args=*/true,
5825                                    /*use_default_args=*/true);
5826
5827       if (arglist == error_mark_node)
5828         /* We were unable to bind the arguments.  */
5829         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5830
5831       /* In the scope of a template class, explicit references to the
5832          template class refer to the type of the template, not any
5833          instantiation of it.  For example, in:
5834
5835            template <class T> class C { void f(C<T>); }
5836
5837          the `C<T>' is just the same as `C'.  Outside of the
5838          class, however, such a reference is an instantiation.  */
5839       if (comp_template_args (TYPE_TI_ARGS (template_type),
5840                               arglist))
5841         {
5842           found = template_type;
5843
5844           if (!entering_scope && PRIMARY_TEMPLATE_P (templ))
5845             {
5846               tree ctx;
5847
5848               for (ctx = current_class_type;
5849                    ctx && TREE_CODE (ctx) != NAMESPACE_DECL;
5850                    ctx = (TYPE_P (ctx)
5851                           ? TYPE_CONTEXT (ctx)
5852                           : DECL_CONTEXT (ctx)))
5853                 if (TYPE_P (ctx) && same_type_p (ctx, template_type))
5854                   goto found_ctx;
5855
5856               /* We're not in the scope of the class, so the
5857                  TEMPLATE_TYPE is not the type we want after all.  */
5858               found = NULL_TREE;
5859             found_ctx:;
5860             }
5861         }
5862       if (found)
5863         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5864
5865       /* If we already have this specialization, return it.  */
5866       found = retrieve_specialization (templ, arglist,
5867                                        /*class_specializations_p=*/false);
5868       if (found)
5869         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5870
5871       /* This type is a "partial instantiation" if any of the template
5872          arguments still involve template parameters.  Note that we set
5873          IS_PARTIAL_INSTANTIATION for partial specializations as
5874          well.  */
5875       is_partial_instantiation = uses_template_parms (arglist);
5876
5877       /* If the deduced arguments are invalid, then the binding
5878          failed.  */
5879       if (!is_partial_instantiation
5880           && check_instantiated_args (templ,
5881                                       INNERMOST_TEMPLATE_ARGS (arglist),
5882                                       complain))
5883         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5884
5885       if (!is_partial_instantiation
5886           && !PRIMARY_TEMPLATE_P (templ)
5887           && TREE_CODE (CP_DECL_CONTEXT (templ)) == NAMESPACE_DECL)
5888         {
5889           found = xref_tag_from_type (TREE_TYPE (templ),
5890                                       DECL_NAME (templ),
5891                                       /*tag_scope=*/ts_global);
5892           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5893         }
5894
5895       context = tsubst (DECL_CONTEXT (templ), arglist,
5896                         complain, in_decl);
5897       if (!context)
5898         context = global_namespace;
5899
5900       /* Create the type.  */
5901       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
5902         {
5903           if (!is_partial_instantiation)
5904             {
5905               set_current_access_from_decl (TYPE_NAME (template_type));
5906               t = start_enum (TYPE_IDENTIFIER (template_type),
5907                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
5908                                       arglist, complain, in_decl),
5909                               SCOPED_ENUM_P (template_type));
5910             }
5911           else
5912             {
5913               /* We don't want to call start_enum for this type, since
5914                  the values for the enumeration constants may involve
5915                  template parameters.  And, no one should be interested
5916                  in the enumeration constants for such a type.  */
5917               t = make_node (ENUMERAL_TYPE);
5918               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
5919             }
5920         }
5921       else
5922         {
5923           t = make_class_type (TREE_CODE (template_type));
5924           CLASSTYPE_DECLARED_CLASS (t)
5925             = CLASSTYPE_DECLARED_CLASS (template_type);
5926           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
5927           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
5928
5929           /* A local class.  Make sure the decl gets registered properly.  */
5930           if (context == current_function_decl)
5931             pushtag (DECL_NAME (templ), t, /*tag_scope=*/ts_current);
5932
5933           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
5934             /* This instantiation is another name for the primary
5935                template type. Set the TYPE_CANONICAL field
5936                appropriately. */
5937             TYPE_CANONICAL (t) = template_type;
5938           else if (any_template_arguments_need_structural_equality_p (arglist))
5939             /* Some of the template arguments require structural
5940                equality testing, so this template class requires
5941                structural equality testing. */
5942             SET_TYPE_STRUCTURAL_EQUALITY (t);
5943         }
5944
5945       /* If we called start_enum or pushtag above, this information
5946          will already be set up.  */
5947       if (!TYPE_NAME (t))
5948         {
5949           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
5950
5951           type_decl = create_implicit_typedef (DECL_NAME (templ), t);
5952           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
5953           TYPE_STUB_DECL (t) = type_decl;
5954           DECL_SOURCE_LOCATION (type_decl)
5955             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
5956         }
5957       else
5958         type_decl = TYPE_NAME (t);
5959
5960       TREE_PRIVATE (type_decl)
5961         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
5962       TREE_PROTECTED (type_decl)
5963         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
5964       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
5965         {
5966           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
5967           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
5968         }
5969
5970       /* Set up the template information.  We have to figure out which
5971          template is the immediate parent if this is a full
5972          instantiation.  */
5973       if (parm_depth == 1 || is_partial_instantiation
5974           || !PRIMARY_TEMPLATE_P (templ))
5975         /* This case is easy; there are no member templates involved.  */
5976         found = templ;
5977       else
5978         {
5979           /* This is a full instantiation of a member template.  Look
5980              for a partial instantiation of which this is an instance.  */
5981
5982           for (found = DECL_TEMPLATE_INSTANTIATIONS (templ);
5983                found; found = TREE_CHAIN (found))
5984             {
5985               int success;
5986               tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
5987
5988               /* We only want partial instantiations, here, not
5989                  specializations or full instantiations.  */
5990               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
5991                   || !uses_template_parms (TREE_VALUE (found)))
5992                 continue;
5993
5994               /* Temporarily reduce by one the number of levels in the
5995                  ARGLIST and in FOUND so as to avoid comparing the
5996                  last set of arguments.  */
5997               TREE_VEC_LENGTH (arglist)--;
5998               TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
5999
6000               /* See if the arguments match.  If they do, then TMPL is
6001                  the partial instantiation we want.  */
6002               success = comp_template_args (TREE_PURPOSE (found), arglist);
6003
6004               /* Restore the argument vectors to their full size.  */
6005               TREE_VEC_LENGTH (arglist)++;
6006               TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
6007
6008               if (success)
6009                 {
6010                   found = tmpl;
6011                   break;
6012                 }
6013             }
6014
6015           if (!found)
6016             {
6017               /* There was no partial instantiation. This happens
6018                  where C<T> is a member template of A<T> and it's used
6019                  in something like
6020
6021                   template <typename T> struct B { A<T>::C<int> m; };
6022                   B<float>;
6023
6024                  Create the partial instantiation.
6025                */
6026               TREE_VEC_LENGTH (arglist)--;
6027               found = tsubst (templ, arglist, complain, NULL_TREE);
6028               TREE_VEC_LENGTH (arglist)++;
6029             }
6030         }
6031
6032       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
6033       DECL_TEMPLATE_INSTANTIATIONS (templ)
6034         = tree_cons (arglist, t,
6035                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6036
6037       if (TREE_CODE (t) == ENUMERAL_TYPE
6038           && !is_partial_instantiation)
6039         /* Now that the type has been registered on the instantiations
6040            list, we set up the enumerators.  Because the enumeration
6041            constants may involve the enumeration type itself, we make
6042            sure to register the type first, and then create the
6043            constants.  That way, doing tsubst_expr for the enumeration
6044            constants won't result in recursive calls here; we'll find
6045            the instantiation and exit above.  */
6046         tsubst_enum (template_type, t, arglist);
6047
6048       if (is_partial_instantiation)
6049         /* If the type makes use of template parameters, the
6050            code that generates debugging information will crash.  */
6051         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6052
6053       /* Possibly limit visibility based on template args.  */
6054       TREE_PUBLIC (type_decl) = 1;
6055       determine_visibility (type_decl);
6056
6057       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6058     }
6059   timevar_pop (TV_NAME_LOOKUP);
6060 }
6061 \f
6062 struct pair_fn_data
6063 {
6064   tree_fn_t fn;
6065   void *data;
6066   /* True when we should also visit template parameters that occur in
6067      non-deduced contexts.  */
6068   bool include_nondeduced_p;
6069   struct pointer_set_t *visited;
6070 };
6071
6072 /* Called from for_each_template_parm via walk_tree.  */
6073
6074 static tree
6075 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6076 {
6077   tree t = *tp;
6078   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6079   tree_fn_t fn = pfd->fn;
6080   void *data = pfd->data;
6081
6082   if (TYPE_P (t)
6083       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6084       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6085                                  pfd->include_nondeduced_p))
6086     return error_mark_node;
6087
6088   switch (TREE_CODE (t))
6089     {
6090     case RECORD_TYPE:
6091       if (TYPE_PTRMEMFUNC_P (t))
6092         break;
6093       /* Fall through.  */
6094
6095     case UNION_TYPE:
6096     case ENUMERAL_TYPE:
6097       if (!TYPE_TEMPLATE_INFO (t))
6098         *walk_subtrees = 0;
6099       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
6100                                        fn, data, pfd->visited, 
6101                                        pfd->include_nondeduced_p))
6102         return error_mark_node;
6103       break;
6104
6105     case INTEGER_TYPE:
6106       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6107                                   fn, data, pfd->visited, 
6108                                   pfd->include_nondeduced_p)
6109           || for_each_template_parm (TYPE_MAX_VALUE (t),
6110                                      fn, data, pfd->visited,
6111                                      pfd->include_nondeduced_p))
6112         return error_mark_node;
6113       break;
6114
6115     case METHOD_TYPE:
6116       /* Since we're not going to walk subtrees, we have to do this
6117          explicitly here.  */
6118       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6119                                   pfd->visited, pfd->include_nondeduced_p))
6120         return error_mark_node;
6121       /* Fall through.  */
6122
6123     case FUNCTION_TYPE:
6124       /* Check the return type.  */
6125       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6126                                   pfd->include_nondeduced_p))
6127         return error_mark_node;
6128
6129       /* Check the parameter types.  Since default arguments are not
6130          instantiated until they are needed, the TYPE_ARG_TYPES may
6131          contain expressions that involve template parameters.  But,
6132          no-one should be looking at them yet.  And, once they're
6133          instantiated, they don't contain template parameters, so
6134          there's no point in looking at them then, either.  */
6135       {
6136         tree parm;
6137
6138         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6139           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6140                                       pfd->visited, pfd->include_nondeduced_p))
6141             return error_mark_node;
6142
6143         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6144            want walk_tree walking into them itself.  */
6145         *walk_subtrees = 0;
6146       }
6147       break;
6148
6149     case TYPEOF_TYPE:
6150       if (pfd->include_nondeduced_p
6151           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6152                                      pfd->visited, 
6153                                      pfd->include_nondeduced_p))
6154         return error_mark_node;
6155       break;
6156
6157     case FUNCTION_DECL:
6158     case VAR_DECL:
6159       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6160           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6161                                      pfd->visited, pfd->include_nondeduced_p))
6162         return error_mark_node;
6163       /* Fall through.  */
6164
6165     case PARM_DECL:
6166     case CONST_DECL:
6167       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6168           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6169                                      pfd->visited, pfd->include_nondeduced_p))
6170         return error_mark_node;
6171       if (DECL_CONTEXT (t)
6172           && pfd->include_nondeduced_p
6173           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6174                                      pfd->visited, pfd->include_nondeduced_p))
6175         return error_mark_node;
6176       break;
6177
6178     case BOUND_TEMPLATE_TEMPLATE_PARM:
6179       /* Record template parameters such as `T' inside `TT<T>'.  */
6180       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6181                                   pfd->include_nondeduced_p))
6182         return error_mark_node;
6183       /* Fall through.  */
6184
6185     case TEMPLATE_TEMPLATE_PARM:
6186     case TEMPLATE_TYPE_PARM:
6187     case TEMPLATE_PARM_INDEX:
6188       if (fn && (*fn)(t, data))
6189         return error_mark_node;
6190       else if (!fn)
6191         return error_mark_node;
6192       break;
6193
6194     case TEMPLATE_DECL:
6195       /* A template template parameter is encountered.  */
6196       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6197           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6198                                      pfd->include_nondeduced_p))
6199         return error_mark_node;
6200
6201       /* Already substituted template template parameter */
6202       *walk_subtrees = 0;
6203       break;
6204
6205     case TYPENAME_TYPE:
6206       if (!fn
6207           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6208                                      data, pfd->visited, 
6209                                      pfd->include_nondeduced_p))
6210         return error_mark_node;
6211       break;
6212
6213     case CONSTRUCTOR:
6214       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6215           && pfd->include_nondeduced_p
6216           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6217                                      (TREE_TYPE (t)), fn, data,
6218                                      pfd->visited, pfd->include_nondeduced_p))
6219         return error_mark_node;
6220       break;
6221
6222     case INDIRECT_REF:
6223     case COMPONENT_REF:
6224       /* If there's no type, then this thing must be some expression
6225          involving template parameters.  */
6226       if (!fn && !TREE_TYPE (t))
6227         return error_mark_node;
6228       break;
6229
6230     case MODOP_EXPR:
6231     case CAST_EXPR:
6232     case REINTERPRET_CAST_EXPR:
6233     case CONST_CAST_EXPR:
6234     case STATIC_CAST_EXPR:
6235     case DYNAMIC_CAST_EXPR:
6236     case ARROW_EXPR:
6237     case DOTSTAR_EXPR:
6238     case TYPEID_EXPR:
6239     case PSEUDO_DTOR_EXPR:
6240       if (!fn)
6241         return error_mark_node;
6242       break;
6243
6244     default:
6245       break;
6246     }
6247
6248   /* We didn't find any template parameters we liked.  */
6249   return NULL_TREE;
6250 }
6251
6252 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6253    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6254    call FN with the parameter and the DATA.
6255    If FN returns nonzero, the iteration is terminated, and
6256    for_each_template_parm returns 1.  Otherwise, the iteration
6257    continues.  If FN never returns a nonzero value, the value
6258    returned by for_each_template_parm is 0.  If FN is NULL, it is
6259    considered to be the function which always returns 1.
6260
6261    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6262    parameters that occur in non-deduced contexts.  When false, only
6263    visits those template parameters that can be deduced.  */
6264
6265 static int
6266 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6267                         struct pointer_set_t *visited,
6268                         bool include_nondeduced_p)
6269 {
6270   struct pair_fn_data pfd;
6271   int result;
6272
6273   /* Set up.  */
6274   pfd.fn = fn;
6275   pfd.data = data;
6276   pfd.include_nondeduced_p = include_nondeduced_p;
6277
6278   /* Walk the tree.  (Conceptually, we would like to walk without
6279      duplicates, but for_each_template_parm_r recursively calls
6280      for_each_template_parm, so we would need to reorganize a fair
6281      bit to use walk_tree_without_duplicates, so we keep our own
6282      visited list.)  */
6283   if (visited)
6284     pfd.visited = visited;
6285   else
6286     pfd.visited = pointer_set_create ();
6287   result = cp_walk_tree (&t,
6288                          for_each_template_parm_r,
6289                          &pfd,
6290                          pfd.visited) != NULL_TREE;
6291
6292   /* Clean up.  */
6293   if (!visited)
6294     {
6295       pointer_set_destroy (pfd.visited);
6296       pfd.visited = 0;
6297     }
6298
6299   return result;
6300 }
6301
6302 /* Returns true if T depends on any template parameter.  */
6303
6304 int
6305 uses_template_parms (tree t)
6306 {
6307   bool dependent_p;
6308   int saved_processing_template_decl;
6309
6310   saved_processing_template_decl = processing_template_decl;
6311   if (!saved_processing_template_decl)
6312     processing_template_decl = 1;
6313   if (TYPE_P (t))
6314     dependent_p = dependent_type_p (t);
6315   else if (TREE_CODE (t) == TREE_VEC)
6316     dependent_p = any_dependent_template_arguments_p (t);
6317   else if (TREE_CODE (t) == TREE_LIST)
6318     dependent_p = (uses_template_parms (TREE_VALUE (t))
6319                    || uses_template_parms (TREE_CHAIN (t)));
6320   else if (TREE_CODE (t) == TYPE_DECL)
6321     dependent_p = dependent_type_p (TREE_TYPE (t));
6322   else if (DECL_P (t)
6323            || EXPR_P (t)
6324            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6325            || TREE_CODE (t) == OVERLOAD
6326            || TREE_CODE (t) == BASELINK
6327            || TREE_CODE (t) == IDENTIFIER_NODE
6328            || TREE_CODE (t) == TRAIT_EXPR
6329            || TREE_CODE (t) == CONSTRUCTOR
6330            || CONSTANT_CLASS_P (t))
6331     dependent_p = (type_dependent_expression_p (t)
6332                    || value_dependent_expression_p (t));
6333   else
6334     {
6335       gcc_assert (t == error_mark_node);
6336       dependent_p = false;
6337     }
6338
6339   processing_template_decl = saved_processing_template_decl;
6340
6341   return dependent_p;
6342 }
6343
6344 /* Returns true if T depends on any template parameter with level LEVEL.  */
6345
6346 int
6347 uses_template_parms_level (tree t, int level)
6348 {
6349   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6350                                  /*include_nondeduced_p=*/true);
6351 }
6352
6353 static int tinst_depth;
6354 extern int max_tinst_depth;
6355 #ifdef GATHER_STATISTICS
6356 int depth_reached;
6357 #endif
6358 static int tinst_level_tick;
6359 static int last_template_error_tick;
6360
6361 /* We're starting to instantiate D; record the template instantiation context
6362    for diagnostics and to restore it later.  */
6363
6364 static int
6365 push_tinst_level (tree d)
6366 {
6367   struct tinst_level *new_level;
6368
6369   if (tinst_depth >= max_tinst_depth)
6370     {
6371       /* If the instantiation in question still has unbound template parms,
6372          we don't really care if we can't instantiate it, so just return.
6373          This happens with base instantiation for implicit `typename'.  */
6374       if (uses_template_parms (d))
6375         return 0;
6376
6377       last_template_error_tick = tinst_level_tick;
6378       error ("template instantiation depth exceeds maximum of %d (use "
6379              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6380              max_tinst_depth, d);
6381
6382       print_instantiation_context ();
6383
6384       return 0;
6385     }
6386
6387   new_level = GGC_NEW (struct tinst_level);
6388   new_level->decl = d;
6389   new_level->locus = input_location;
6390   new_level->in_system_header_p = in_system_header;
6391   new_level->next = current_tinst_level;
6392   current_tinst_level = new_level;
6393
6394   ++tinst_depth;
6395 #ifdef GATHER_STATISTICS
6396   if (tinst_depth > depth_reached)
6397     depth_reached = tinst_depth;
6398 #endif
6399
6400   ++tinst_level_tick;
6401   return 1;
6402 }
6403
6404 /* We're done instantiating this template; return to the instantiation
6405    context.  */
6406
6407 static void
6408 pop_tinst_level (void)
6409 {
6410   /* Restore the filename and line number stashed away when we started
6411      this instantiation.  */
6412   input_location = current_tinst_level->locus;
6413   current_tinst_level = current_tinst_level->next;
6414   --tinst_depth;
6415   ++tinst_level_tick;
6416 }
6417
6418 /* We're instantiating a deferred template; restore the template
6419    instantiation context in which the instantiation was requested, which
6420    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6421
6422 static tree
6423 reopen_tinst_level (struct tinst_level *level)
6424 {
6425   struct tinst_level *t;
6426
6427   tinst_depth = 0;
6428   for (t = level; t; t = t->next)
6429     ++tinst_depth;
6430
6431   current_tinst_level = level;
6432   pop_tinst_level ();
6433   return level->decl;
6434 }
6435
6436 /* Returns the TINST_LEVEL which gives the original instantiation
6437    context.  */
6438
6439 struct tinst_level *
6440 outermost_tinst_level (void)
6441 {
6442   struct tinst_level *level = current_tinst_level;
6443   if (level)
6444     while (level->next)
6445       level = level->next;
6446   return level;
6447 }
6448
6449 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
6450
6451 bool
6452 parameter_of_template_p (tree parm, tree templ)
6453 {
6454   tree parms;
6455   int i;
6456
6457   if (!parm || !templ)
6458     return false;
6459
6460   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
6461   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6462
6463   parms = DECL_TEMPLATE_PARMS (templ);
6464   parms = INNERMOST_TEMPLATE_PARMS (parms);
6465
6466   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
6467     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
6468       return true;
6469
6470   return false;
6471 }
6472
6473 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6474    vector of template arguments, as for tsubst.
6475
6476    Returns an appropriate tsubst'd friend declaration.  */
6477
6478 static tree
6479 tsubst_friend_function (tree decl, tree args)
6480 {
6481   tree new_friend;
6482
6483   if (TREE_CODE (decl) == FUNCTION_DECL
6484       && DECL_TEMPLATE_INSTANTIATION (decl)
6485       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6486     /* This was a friend declared with an explicit template
6487        argument list, e.g.:
6488
6489        friend void f<>(T);
6490
6491        to indicate that f was a template instantiation, not a new
6492        function declaration.  Now, we have to figure out what
6493        instantiation of what template.  */
6494     {
6495       tree template_id, arglist, fns;
6496       tree new_args;
6497       tree tmpl;
6498       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6499
6500       /* Friend functions are looked up in the containing namespace scope.
6501          We must enter that scope, to avoid finding member functions of the
6502          current class with same name.  */
6503       push_nested_namespace (ns);
6504       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6505                          tf_warning_or_error, NULL_TREE,
6506                          /*integral_constant_expression_p=*/false);
6507       pop_nested_namespace (ns);
6508       arglist = tsubst (DECL_TI_ARGS (decl), args,
6509                         tf_warning_or_error, NULL_TREE);
6510       template_id = lookup_template_function (fns, arglist);
6511
6512       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6513       tmpl = determine_specialization (template_id, new_friend,
6514                                        &new_args,
6515                                        /*need_member_template=*/0,
6516                                        TREE_VEC_LENGTH (args),
6517                                        tsk_none);
6518       return instantiate_template (tmpl, new_args, tf_error);
6519     }
6520
6521   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6522
6523   /* The NEW_FRIEND will look like an instantiation, to the
6524      compiler, but is not an instantiation from the point of view of
6525      the language.  For example, we might have had:
6526
6527      template <class T> struct S {
6528        template <class U> friend void f(T, U);
6529      };
6530
6531      Then, in S<int>, template <class U> void f(int, U) is not an
6532      instantiation of anything.  */
6533   if (new_friend == error_mark_node)
6534     return error_mark_node;
6535
6536   DECL_USE_TEMPLATE (new_friend) = 0;
6537   if (TREE_CODE (decl) == TEMPLATE_DECL)
6538     {
6539       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6540       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6541         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6542     }
6543
6544   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6545      is not a template instantiation and should not be mangled like
6546      one.  Therefore, we forget the mangling here; we'll recompute it
6547      later if we need it.  */
6548   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6549     {
6550       SET_DECL_RTL (new_friend, NULL_RTX);
6551       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6552     }
6553
6554   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6555     {
6556       tree old_decl;
6557       tree new_friend_template_info;
6558       tree new_friend_result_template_info;
6559       tree ns;
6560       int  new_friend_is_defn;
6561
6562       /* We must save some information from NEW_FRIEND before calling
6563          duplicate decls since that function will free NEW_FRIEND if
6564          possible.  */
6565       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6566       new_friend_is_defn =
6567             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6568                            (template_for_substitution (new_friend)))
6569              != NULL_TREE);
6570       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6571         {
6572           /* This declaration is a `primary' template.  */
6573           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6574
6575           new_friend_result_template_info
6576             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6577         }
6578       else
6579         new_friend_result_template_info = NULL_TREE;
6580
6581       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6582       if (new_friend_is_defn)
6583         DECL_INITIAL (new_friend) = error_mark_node;
6584
6585       /* Inside pushdecl_namespace_level, we will push into the
6586          current namespace. However, the friend function should go
6587          into the namespace of the template.  */
6588       ns = decl_namespace_context (new_friend);
6589       push_nested_namespace (ns);
6590       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6591       pop_nested_namespace (ns);
6592
6593       if (old_decl == error_mark_node)
6594         return error_mark_node;
6595
6596       if (old_decl != new_friend)
6597         {
6598           /* This new friend declaration matched an existing
6599              declaration.  For example, given:
6600
6601                template <class T> void f(T);
6602                template <class U> class C {
6603                  template <class T> friend void f(T) {}
6604                };
6605
6606              the friend declaration actually provides the definition
6607              of `f', once C has been instantiated for some type.  So,
6608              old_decl will be the out-of-class template declaration,
6609              while new_friend is the in-class definition.
6610
6611              But, if `f' was called before this point, the
6612              instantiation of `f' will have DECL_TI_ARGS corresponding
6613              to `T' but not to `U', references to which might appear
6614              in the definition of `f'.  Previously, the most general
6615              template for an instantiation of `f' was the out-of-class
6616              version; now it is the in-class version.  Therefore, we
6617              run through all specialization of `f', adding to their
6618              DECL_TI_ARGS appropriately.  In particular, they need a
6619              new set of outer arguments, corresponding to the
6620              arguments for this class instantiation.
6621
6622              The same situation can arise with something like this:
6623
6624                friend void f(int);
6625                template <class T> class C {
6626                  friend void f(T) {}
6627                };
6628
6629              when `C<int>' is instantiated.  Now, `f(int)' is defined
6630              in the class.  */
6631
6632           if (!new_friend_is_defn)
6633             /* On the other hand, if the in-class declaration does
6634                *not* provide a definition, then we don't want to alter
6635                existing definitions.  We can just leave everything
6636                alone.  */
6637             ;
6638           else
6639             {
6640               /* Overwrite whatever template info was there before, if
6641                  any, with the new template information pertaining to
6642                  the declaration.  */
6643               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
6644
6645               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
6646                 reregister_specialization (new_friend,
6647                                            most_general_template (old_decl),
6648                                            old_decl);
6649               else
6650                 {
6651                   tree t;
6652                   tree new_friend_args;
6653
6654                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
6655                     = new_friend_result_template_info;
6656
6657                   new_friend_args = TI_ARGS (new_friend_template_info);
6658                   for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl);
6659                        t != NULL_TREE;
6660                        t = TREE_CHAIN (t))
6661                     {
6662                       tree spec = TREE_VALUE (t);
6663
6664                       DECL_TI_ARGS (spec)
6665                         = add_outermost_template_args (new_friend_args,
6666                                                        DECL_TI_ARGS (spec));
6667                     }
6668
6669                   /* Now, since specializations are always supposed to
6670                      hang off of the most general template, we must move
6671                      them.  */
6672                   t = most_general_template (old_decl);
6673                   if (t != old_decl)
6674                     {
6675                       DECL_TEMPLATE_SPECIALIZATIONS (t)
6676                         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
6677                                    DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
6678                       DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
6679                     }
6680                 }
6681             }
6682
6683           /* The information from NEW_FRIEND has been merged into OLD_DECL
6684              by duplicate_decls.  */
6685           new_friend = old_decl;
6686         }
6687     }
6688   else
6689     {
6690       tree context = DECL_CONTEXT (new_friend);
6691       bool dependent_p;
6692
6693       /* In the code
6694            template <class T> class C {
6695              template <class U> friend void C1<U>::f (); // case 1
6696              friend void C2<T>::f ();                    // case 2
6697            };
6698          we only need to make sure CONTEXT is a complete type for
6699          case 2.  To distinguish between the two cases, we note that
6700          CONTEXT of case 1 remains dependent type after tsubst while
6701          this isn't true for case 2.  */
6702       ++processing_template_decl;
6703       dependent_p = dependent_type_p (context);
6704       --processing_template_decl;
6705
6706       if (!dependent_p
6707           && !complete_type_or_else (context, NULL_TREE))
6708         return error_mark_node;
6709
6710       if (COMPLETE_TYPE_P (context))
6711         {
6712           /* Check to see that the declaration is really present, and,
6713              possibly obtain an improved declaration.  */
6714           tree fn = check_classfn (context,
6715                                    new_friend, NULL_TREE);
6716
6717           if (fn)
6718             new_friend = fn;
6719         }
6720     }
6721
6722   return new_friend;
6723 }
6724
6725 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
6726    template arguments, as for tsubst.
6727
6728    Returns an appropriate tsubst'd friend type or error_mark_node on
6729    failure.  */
6730
6731 static tree
6732 tsubst_friend_class (tree friend_tmpl, tree args)
6733 {
6734   tree friend_type;
6735   tree tmpl;
6736   tree context;
6737
6738   context = DECL_CONTEXT (friend_tmpl);
6739
6740   if (context)
6741     {
6742       if (TREE_CODE (context) == NAMESPACE_DECL)
6743         push_nested_namespace (context);
6744       else
6745         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
6746     }
6747
6748   /* Look for a class template declaration.  We look for hidden names
6749      because two friend declarations of the same template are the
6750      same.  For example, in:
6751
6752        struct A { 
6753          template <typename> friend class F;
6754        };
6755        template <typename> struct B { 
6756          template <typename> friend class F;
6757        };
6758
6759      both F templates are the same.  */
6760   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
6761                            /*block_p=*/true, 0, 
6762                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
6763
6764   /* But, if we don't find one, it might be because we're in a
6765      situation like this:
6766
6767        template <class T>
6768        struct S {
6769          template <class U>
6770          friend struct S;
6771        };
6772
6773      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
6774      for `S<int>', not the TEMPLATE_DECL.  */
6775   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
6776     {
6777       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
6778       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
6779     }
6780
6781   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
6782     {
6783       /* The friend template has already been declared.  Just
6784          check to see that the declarations match, and install any new
6785          default parameters.  We must tsubst the default parameters,
6786          of course.  We only need the innermost template parameters
6787          because that is all that redeclare_class_template will look
6788          at.  */
6789       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
6790           > TMPL_ARGS_DEPTH (args))
6791         {
6792           tree parms;
6793           location_t saved_input_location;
6794           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
6795                                          args, tf_warning_or_error);
6796
6797           saved_input_location = input_location;
6798           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
6799           redeclare_class_template (TREE_TYPE (tmpl), parms);
6800           input_location = saved_input_location;
6801           
6802         }
6803
6804       friend_type = TREE_TYPE (tmpl);
6805     }
6806   else
6807     {
6808       /* The friend template has not already been declared.  In this
6809          case, the instantiation of the template class will cause the
6810          injection of this template into the global scope.  */
6811       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
6812       if (tmpl == error_mark_node)
6813         return error_mark_node;
6814
6815       /* The new TMPL is not an instantiation of anything, so we
6816          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
6817          the new type because that is supposed to be the corresponding
6818          template decl, i.e., TMPL.  */
6819       DECL_USE_TEMPLATE (tmpl) = 0;
6820       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
6821       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
6822       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
6823         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
6824
6825       /* Inject this template into the global scope.  */
6826       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
6827     }
6828
6829   if (context)
6830     {
6831       if (TREE_CODE (context) == NAMESPACE_DECL)
6832         pop_nested_namespace (context);
6833       else
6834         pop_nested_class ();
6835     }
6836
6837   return friend_type;
6838 }
6839
6840 /* Returns zero if TYPE cannot be completed later due to circularity.
6841    Otherwise returns one.  */
6842
6843 static int
6844 can_complete_type_without_circularity (tree type)
6845 {
6846   if (type == NULL_TREE || type == error_mark_node)
6847     return 0;
6848   else if (COMPLETE_TYPE_P (type))
6849     return 1;
6850   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
6851     return can_complete_type_without_circularity (TREE_TYPE (type));
6852   else if (CLASS_TYPE_P (type)
6853            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
6854     return 0;
6855   else
6856     return 1;
6857 }
6858
6859 /* Apply any attributes which had to be deferred until instantiation
6860    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
6861    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
6862
6863 static void
6864 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
6865                                 tree args, tsubst_flags_t complain, tree in_decl)
6866 {
6867   tree last_dep = NULL_TREE;
6868   tree t;
6869   tree *p;
6870
6871   for (t = attributes; t; t = TREE_CHAIN (t))
6872     if (ATTR_IS_DEPENDENT (t))
6873       {
6874         last_dep = t;
6875         attributes = copy_list (attributes);
6876         break;
6877       }
6878
6879   if (DECL_P (*decl_p))
6880     {
6881       if (TREE_TYPE (*decl_p) == error_mark_node)
6882         return;
6883       p = &DECL_ATTRIBUTES (*decl_p);
6884     }
6885   else
6886     p = &TYPE_ATTRIBUTES (*decl_p);
6887
6888   if (last_dep)
6889     {
6890       tree late_attrs = NULL_TREE;
6891       tree *q = &late_attrs;
6892
6893       for (*p = attributes; *p; )
6894         {
6895           t = *p;
6896           if (ATTR_IS_DEPENDENT (t))
6897             {
6898               *p = TREE_CHAIN (t);
6899               TREE_CHAIN (t) = NULL_TREE;
6900               /* If the first attribute argument is an identifier, don't
6901                  pass it through tsubst.  Attributes like mode, format,
6902                  cleanup and several target specific attributes expect it
6903                  unmodified.  */
6904               if (TREE_VALUE (t)
6905                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
6906                   && TREE_VALUE (TREE_VALUE (t))
6907                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
6908                       == IDENTIFIER_NODE))
6909                 {
6910                   tree chain
6911                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
6912                                    in_decl,
6913                                    /*integral_constant_expression_p=*/false);
6914                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
6915                     TREE_VALUE (t)
6916                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
6917                                    chain);
6918                 }
6919               else
6920                 TREE_VALUE (t)
6921                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
6922                                  /*integral_constant_expression_p=*/false);
6923               *q = t;
6924               q = &TREE_CHAIN (t);
6925             }
6926           else
6927             p = &TREE_CHAIN (t);
6928         }
6929
6930       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
6931     }
6932 }
6933
6934 /* Perform (or defer) access check for typedefs that were referenced
6935    from within the template TMPL code.
6936    This is a subroutine of instantiate_template and instantiate_class_template.
6937    TMPL is the template to consider and TARGS is the list of arguments of
6938    that template.  */
6939
6940 static void
6941 perform_typedefs_access_check (tree tmpl, tree targs)
6942 {
6943   tree t;
6944
6945   if (!tmpl
6946       || (TREE_CODE (tmpl) != RECORD_TYPE
6947           && TREE_CODE (tmpl) != FUNCTION_DECL))
6948     return;
6949
6950   for (t = get_types_needing_access_check (tmpl); t; t = TREE_CHAIN (t))
6951     {
6952       tree type_decl = TREE_PURPOSE (t);
6953       tree type_scope = TREE_VALUE (t);
6954
6955       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
6956         continue;
6957
6958       if (uses_template_parms (type_decl))
6959         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
6960       if (uses_template_parms (type_scope))
6961         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
6962
6963       perform_or_defer_access_check (TYPE_BINFO (type_scope),
6964                                      type_decl, type_decl);
6965     }
6966 }
6967
6968 tree
6969 instantiate_class_template (tree type)
6970 {
6971   tree templ, args, pattern, t, member;
6972   tree typedecl;
6973   tree pbinfo;
6974   tree base_list;
6975
6976   if (type == error_mark_node)
6977     return error_mark_node;
6978
6979   if (TYPE_BEING_DEFINED (type)
6980       || COMPLETE_TYPE_P (type)
6981       || dependent_type_p (type))
6982     return type;
6983
6984   /* Figure out which template is being instantiated.  */
6985   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
6986   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6987
6988   /* Determine what specialization of the original template to
6989      instantiate.  */
6990   t = most_specialized_class (type, templ);
6991   if (t == error_mark_node)
6992     {
6993       TYPE_BEING_DEFINED (type) = 1;
6994       return error_mark_node;
6995     }
6996   else if (t)
6997     {
6998       /* This TYPE is actually an instantiation of a partial
6999          specialization.  We replace the innermost set of ARGS with
7000          the arguments appropriate for substitution.  For example,
7001          given:
7002
7003            template <class T> struct S {};
7004            template <class T> struct S<T*> {};
7005
7006          and supposing that we are instantiating S<int*>, ARGS will
7007          presently be {int*} -- but we need {int}.  */
7008       pattern = TREE_TYPE (t);
7009       args = TREE_PURPOSE (t);
7010     }
7011   else
7012     {
7013       pattern = TREE_TYPE (templ);
7014       args = CLASSTYPE_TI_ARGS (type);
7015     }
7016
7017   /* If the template we're instantiating is incomplete, then clearly
7018      there's nothing we can do.  */
7019   if (!COMPLETE_TYPE_P (pattern))
7020     return type;
7021
7022   /* If we've recursively instantiated too many templates, stop.  */
7023   if (! push_tinst_level (type))
7024     return type;
7025
7026   /* Now we're really doing the instantiation.  Mark the type as in
7027      the process of being defined.  */
7028   TYPE_BEING_DEFINED (type) = 1;
7029
7030   /* We may be in the middle of deferred access check.  Disable
7031      it now.  */
7032   push_deferring_access_checks (dk_no_deferred);
7033
7034   push_to_top_level ();
7035
7036   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7037
7038   /* Set the input location to the most specialized template definition.
7039      This is needed if tsubsting causes an error.  */
7040   typedecl = TYPE_MAIN_DECL (pattern);
7041   input_location = DECL_SOURCE_LOCATION (typedecl);
7042
7043   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7044   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7045   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7046   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7047   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7048   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7049   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7050   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7051   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7052   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7053   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7054   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7055   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7056   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7057   if (ANON_AGGR_TYPE_P (pattern))
7058     SET_ANON_AGGR_TYPE_P (type);
7059   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7060     {
7061       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7062       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7063     }
7064
7065   pbinfo = TYPE_BINFO (pattern);
7066
7067   /* We should never instantiate a nested class before its enclosing
7068      class; we need to look up the nested class by name before we can
7069      instantiate it, and that lookup should instantiate the enclosing
7070      class.  */
7071   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7072               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7073               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7074
7075   base_list = NULL_TREE;
7076   if (BINFO_N_BASE_BINFOS (pbinfo))
7077     {
7078       tree pbase_binfo;
7079       tree context = TYPE_CONTEXT (type);
7080       tree pushed_scope;
7081       int i;
7082
7083       /* We must enter the scope containing the type, as that is where
7084          the accessibility of types named in dependent bases are
7085          looked up from.  */
7086       pushed_scope = push_scope (context ? context : global_namespace);
7087
7088       /* Substitute into each of the bases to determine the actual
7089          basetypes.  */
7090       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7091         {
7092           tree base;
7093           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7094           tree expanded_bases = NULL_TREE;
7095           int idx, len = 1;
7096
7097           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7098             {
7099               expanded_bases = 
7100                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7101                                        args, tf_error, NULL_TREE);
7102               if (expanded_bases == error_mark_node)
7103                 continue;
7104
7105               len = TREE_VEC_LENGTH (expanded_bases);
7106             }
7107
7108           for (idx = 0; idx < len; idx++)
7109             {
7110               if (expanded_bases)
7111                 /* Extract the already-expanded base class.  */
7112                 base = TREE_VEC_ELT (expanded_bases, idx);
7113               else
7114                 /* Substitute to figure out the base class.  */
7115                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7116                                NULL_TREE);
7117
7118               if (base == error_mark_node)
7119                 continue;
7120
7121               base_list = tree_cons (access, base, base_list);
7122               if (BINFO_VIRTUAL_P (pbase_binfo))
7123                 TREE_TYPE (base_list) = integer_type_node;
7124             }
7125         }
7126
7127       /* The list is now in reverse order; correct that.  */
7128       base_list = nreverse (base_list);
7129
7130       if (pushed_scope)
7131         pop_scope (pushed_scope);
7132     }
7133   /* Now call xref_basetypes to set up all the base-class
7134      information.  */
7135   xref_basetypes (type, base_list);
7136
7137   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7138                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7139                                   args, tf_error, NULL_TREE);
7140
7141   /* Now that our base classes are set up, enter the scope of the
7142      class, so that name lookups into base classes, etc. will work
7143      correctly.  This is precisely analogous to what we do in
7144      begin_class_definition when defining an ordinary non-template
7145      class, except we also need to push the enclosing classes.  */
7146   push_nested_class (type);
7147
7148   /* Now members are processed in the order of declaration.  */
7149   for (member = CLASSTYPE_DECL_LIST (pattern);
7150        member; member = TREE_CHAIN (member))
7151     {
7152       tree t = TREE_VALUE (member);
7153
7154       if (TREE_PURPOSE (member))
7155         {
7156           if (TYPE_P (t))
7157             {
7158               /* Build new CLASSTYPE_NESTED_UTDS.  */
7159
7160               tree newtag;
7161               bool class_template_p;
7162
7163               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7164                                   && TYPE_LANG_SPECIFIC (t)
7165                                   && CLASSTYPE_IS_TEMPLATE (t));
7166               /* If the member is a class template, then -- even after
7167                  substitution -- there may be dependent types in the
7168                  template argument list for the class.  We increment
7169                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7170                  that function will assume that no types are dependent
7171                  when outside of a template.  */
7172               if (class_template_p)
7173                 ++processing_template_decl;
7174               newtag = tsubst (t, args, tf_error, NULL_TREE);
7175               if (class_template_p)
7176                 --processing_template_decl;
7177               if (newtag == error_mark_node)
7178                 continue;
7179
7180               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7181                 {
7182                   tree name = TYPE_IDENTIFIER (t);
7183
7184                   if (class_template_p)
7185                     /* Unfortunately, lookup_template_class sets
7186                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7187                        instantiation (i.e., for the type of a member
7188                        template class nested within a template class.)
7189                        This behavior is required for
7190                        maybe_process_partial_specialization to work
7191                        correctly, but is not accurate in this case;
7192                        the TAG is not an instantiation of anything.
7193                        (The corresponding TEMPLATE_DECL is an
7194                        instantiation, but the TYPE is not.) */
7195                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7196
7197                   /* Now, we call pushtag to put this NEWTAG into the scope of
7198                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7199                      pushtag calling push_template_decl.  We don't have to do
7200                      this for enums because it will already have been done in
7201                      tsubst_enum.  */
7202                   if (name)
7203                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7204                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7205                 }
7206             }
7207           else if (TREE_CODE (t) == FUNCTION_DECL
7208                    || DECL_FUNCTION_TEMPLATE_P (t))
7209             {
7210               /* Build new TYPE_METHODS.  */
7211               tree r;
7212
7213               if (TREE_CODE (t) == TEMPLATE_DECL)
7214                 ++processing_template_decl;
7215               r = tsubst (t, args, tf_error, NULL_TREE);
7216               if (TREE_CODE (t) == TEMPLATE_DECL)
7217                 --processing_template_decl;
7218               set_current_access_from_decl (r);
7219               finish_member_declaration (r);
7220             }
7221           else
7222             {
7223               /* Build new TYPE_FIELDS.  */
7224               if (TREE_CODE (t) == STATIC_ASSERT)
7225                 {
7226                   tree condition = 
7227                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7228                                  tf_warning_or_error, NULL_TREE,
7229                                  /*integral_constant_expression_p=*/true);
7230                   finish_static_assert (condition,
7231                                         STATIC_ASSERT_MESSAGE (t), 
7232                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7233                                         /*member_p=*/true);
7234                 }
7235               else if (TREE_CODE (t) != CONST_DECL)
7236                 {
7237                   tree r;
7238
7239                   /* The file and line for this declaration, to
7240                      assist in error message reporting.  Since we
7241                      called push_tinst_level above, we don't need to
7242                      restore these.  */
7243                   input_location = DECL_SOURCE_LOCATION (t);
7244
7245                   if (TREE_CODE (t) == TEMPLATE_DECL)
7246                     ++processing_template_decl;
7247                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7248                   if (TREE_CODE (t) == TEMPLATE_DECL)
7249                     --processing_template_decl;
7250                   if (TREE_CODE (r) == VAR_DECL)
7251                     {
7252                       /* In [temp.inst]:
7253
7254                            [t]he initialization (and any associated
7255                            side-effects) of a static data member does
7256                            not occur unless the static data member is
7257                            itself used in a way that requires the
7258                            definition of the static data member to
7259                            exist.
7260
7261                          Therefore, we do not substitute into the
7262                          initialized for the static data member here.  */
7263                       finish_static_data_member_decl
7264                         (r,
7265                          /*init=*/NULL_TREE,
7266                          /*init_const_expr_p=*/false,
7267                          /*asmspec_tree=*/NULL_TREE,
7268                          /*flags=*/0);
7269                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7270                         check_static_variable_definition (r, TREE_TYPE (r));
7271                     }
7272                   else if (TREE_CODE (r) == FIELD_DECL)
7273                     {
7274                       /* Determine whether R has a valid type and can be
7275                          completed later.  If R is invalid, then it is
7276                          replaced by error_mark_node so that it will not be
7277                          added to TYPE_FIELDS.  */
7278                       tree rtype = TREE_TYPE (r);
7279                       if (can_complete_type_without_circularity (rtype))
7280                         complete_type (rtype);
7281
7282                       if (!COMPLETE_TYPE_P (rtype))
7283                         {
7284                           cxx_incomplete_type_error (r, rtype);
7285                           r = error_mark_node;
7286                         }
7287                     }
7288
7289                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7290                      such a thing will already have been added to the field
7291                      list by tsubst_enum in finish_member_declaration in the
7292                      CLASSTYPE_NESTED_UTDS case above.  */
7293                   if (!(TREE_CODE (r) == TYPE_DECL
7294                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7295                         && DECL_ARTIFICIAL (r)))
7296                     {
7297                       set_current_access_from_decl (r);
7298                       finish_member_declaration (r);
7299                     }
7300                 }
7301             }
7302         }
7303       else
7304         {
7305           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7306             {
7307               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7308
7309               tree friend_type = t;
7310               bool adjust_processing_template_decl = false;
7311
7312               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7313                 {
7314                   /* template <class T> friend class C;  */
7315                   friend_type = tsubst_friend_class (friend_type, args);
7316                   adjust_processing_template_decl = true;
7317                 }
7318               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7319                 {
7320                   /* template <class T> friend class C::D;  */
7321                   friend_type = tsubst (friend_type, args,
7322                                         tf_warning_or_error, NULL_TREE);
7323                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7324                     friend_type = TREE_TYPE (friend_type);
7325                   adjust_processing_template_decl = true;
7326                 }
7327               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7328                 {
7329                   /* This could be either
7330
7331                        friend class T::C;
7332
7333                      when dependent_type_p is false or
7334
7335                        template <class U> friend class T::C;
7336
7337                      otherwise.  */
7338                   friend_type = tsubst (friend_type, args,
7339                                         tf_warning_or_error, NULL_TREE);
7340                   /* Bump processing_template_decl for correct
7341                      dependent_type_p calculation.  */
7342                   ++processing_template_decl;
7343                   if (dependent_type_p (friend_type))
7344                     adjust_processing_template_decl = true;
7345                   --processing_template_decl;
7346                 }
7347               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7348                        && hidden_name_p (TYPE_NAME (friend_type)))
7349                 {
7350                   /* friend class C;
7351
7352                      where C hasn't been declared yet.  Let's lookup name
7353                      from namespace scope directly, bypassing any name that
7354                      come from dependent base class.  */
7355                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7356
7357                   /* The call to xref_tag_from_type does injection for friend
7358                      classes.  */
7359                   push_nested_namespace (ns);
7360                   friend_type =
7361                     xref_tag_from_type (friend_type, NULL_TREE,
7362                                         /*tag_scope=*/ts_current);
7363                   pop_nested_namespace (ns);
7364                 }
7365               else if (uses_template_parms (friend_type))
7366                 /* friend class C<T>;  */
7367                 friend_type = tsubst (friend_type, args,
7368                                       tf_warning_or_error, NULL_TREE);
7369               /* Otherwise it's
7370
7371                    friend class C;
7372
7373                  where C is already declared or
7374
7375                    friend class C<int>;
7376
7377                  We don't have to do anything in these cases.  */
7378
7379               if (adjust_processing_template_decl)
7380                 /* Trick make_friend_class into realizing that the friend
7381                    we're adding is a template, not an ordinary class.  It's
7382                    important that we use make_friend_class since it will
7383                    perform some error-checking and output cross-reference
7384                    information.  */
7385                 ++processing_template_decl;
7386
7387               if (friend_type != error_mark_node)
7388                 make_friend_class (type, friend_type, /*complain=*/false);
7389
7390               if (adjust_processing_template_decl)
7391                 --processing_template_decl;
7392             }
7393           else
7394             {
7395               /* Build new DECL_FRIENDLIST.  */
7396               tree r;
7397
7398               /* The file and line for this declaration, to
7399                  assist in error message reporting.  Since we
7400                  called push_tinst_level above, we don't need to
7401                  restore these.  */
7402               input_location = DECL_SOURCE_LOCATION (t);
7403
7404               if (TREE_CODE (t) == TEMPLATE_DECL)
7405                 {
7406                   ++processing_template_decl;
7407                   push_deferring_access_checks (dk_no_check);
7408                 }
7409
7410               r = tsubst_friend_function (t, args);
7411               add_friend (type, r, /*complain=*/false);
7412               if (TREE_CODE (t) == TEMPLATE_DECL)
7413                 {
7414                   pop_deferring_access_checks ();
7415                   --processing_template_decl;
7416                 }
7417             }
7418         }
7419     }
7420
7421   /* Set the file and line number information to whatever is given for
7422      the class itself.  This puts error messages involving generated
7423      implicit functions at a predictable point, and the same point
7424      that would be used for non-template classes.  */
7425   input_location = DECL_SOURCE_LOCATION (typedecl);
7426
7427   unreverse_member_declarations (type);
7428   finish_struct_1 (type);
7429   TYPE_BEING_DEFINED (type) = 0;
7430
7431   /* Now that the class is complete, instantiate default arguments for
7432      any member functions.  We don't do this earlier because the
7433      default arguments may reference members of the class.  */
7434   if (!PRIMARY_TEMPLATE_P (templ))
7435     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7436       if (TREE_CODE (t) == FUNCTION_DECL
7437           /* Implicitly generated member functions will not have template
7438              information; they are not instantiations, but instead are
7439              created "fresh" for each instantiation.  */
7440           && DECL_TEMPLATE_INFO (t))
7441         tsubst_default_arguments (t);
7442
7443   /* Some typedefs referenced from within the template code need to be access
7444      checked at template instantiation time, i.e now. These types were
7445      added to the template at parsing time. Let's get those and perform
7446      the access checks then.  */
7447   perform_typedefs_access_check (pattern, args);
7448   perform_deferred_access_checks ();
7449   pop_nested_class ();
7450   pop_from_top_level ();
7451   pop_deferring_access_checks ();
7452   pop_tinst_level ();
7453
7454   /* The vtable for a template class can be emitted in any translation
7455      unit in which the class is instantiated.  When there is no key
7456      method, however, finish_struct_1 will already have added TYPE to
7457      the keyed_classes list.  */
7458   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7459     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7460
7461   return type;
7462 }
7463
7464 static tree
7465 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7466 {
7467   tree r;
7468
7469   if (!t)
7470     r = t;
7471   else if (TYPE_P (t))
7472     r = tsubst (t, args, complain, in_decl);
7473   else
7474     {
7475       r = tsubst_expr (t, args, complain, in_decl,
7476                        /*integral_constant_expression_p=*/true);
7477       r = fold_non_dependent_expr (r);
7478     }
7479   return r;
7480 }
7481
7482 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
7483    NONTYPE_ARGUMENT_PACK.  */
7484
7485 static tree
7486 make_fnparm_pack (tree spec_parm)
7487 {
7488   /* Collect all of the extra "packed" parameters into an
7489      argument pack.  */
7490   tree parmvec;
7491   tree parmtypevec;
7492   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
7493   tree argtypepack = make_node (TYPE_ARGUMENT_PACK);
7494   int i, len = list_length (spec_parm);
7495
7496   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
7497   parmvec = make_tree_vec (len);
7498   parmtypevec = make_tree_vec (len);
7499   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
7500     {
7501       TREE_VEC_ELT (parmvec, i) = spec_parm;
7502       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
7503     }
7504
7505   /* Build the argument packs.  */
7506   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
7507   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
7508   TREE_TYPE (argpack) = argtypepack;
7509
7510   return argpack;
7511 }        
7512
7513 /* Substitute ARGS into T, which is an pack expansion
7514    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7515    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7516    (if only a partial substitution could be performed) or
7517    ERROR_MARK_NODE if there was an error.  */
7518 tree
7519 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7520                        tree in_decl)
7521 {
7522   tree pattern;
7523   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7524   tree first_arg_pack; int i, len = -1;
7525   tree result;
7526   int incomplete = 0;
7527   bool very_local_specializations = false;
7528
7529   gcc_assert (PACK_EXPANSION_P (t));
7530   pattern = PACK_EXPANSION_PATTERN (t);
7531
7532   /* Determine the argument packs that will instantiate the parameter
7533      packs used in the expansion expression. While we're at it,
7534      compute the number of arguments to be expanded and make sure it
7535      is consistent.  */
7536   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7537        pack = TREE_CHAIN (pack))
7538     {
7539       tree parm_pack = TREE_VALUE (pack);
7540       tree arg_pack = NULL_TREE;
7541       tree orig_arg = NULL_TREE;
7542
7543       if (TREE_CODE (parm_pack) == PARM_DECL)
7544         {
7545           arg_pack = retrieve_local_specialization (parm_pack);
7546           if (arg_pack == NULL_TREE)
7547             {
7548               /* This can happen for a parameter name used later in a function
7549                  declaration (such as in a late-specified return type).  Just
7550                  make a dummy decl, since it's only used for its type.  */
7551               gcc_assert (skip_evaluation);
7552               arg_pack = tsubst_decl (parm_pack, args, complain);
7553               arg_pack = make_fnparm_pack (arg_pack);
7554             }
7555         }
7556       else
7557         {
7558           int level, idx, levels;
7559           template_parm_level_and_index (parm_pack, &level, &idx);
7560
7561           levels = TMPL_ARGS_DEPTH (args);
7562           if (level <= levels)
7563             arg_pack = TMPL_ARG (args, level, idx);
7564         }
7565
7566       orig_arg = arg_pack;
7567       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7568         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7569       
7570       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7571         /* This can only happen if we forget to expand an argument
7572            pack somewhere else. Just return an error, silently.  */
7573         {
7574           result = make_tree_vec (1);
7575           TREE_VEC_ELT (result, 0) = error_mark_node;
7576           return result;
7577         }
7578
7579       if (arg_pack
7580           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
7581           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
7582         {
7583           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
7584           tree pattern = PACK_EXPANSION_PATTERN (expansion);
7585           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
7586               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
7587             /* The argument pack that the parameter maps to is just an
7588                expansion of the parameter itself, such as one would
7589                find in the implicit typedef of a class inside the
7590                class itself.  Consider this parameter "unsubstituted",
7591                so that we will maintain the outer pack expansion.  */
7592             arg_pack = NULL_TREE;
7593         }
7594           
7595       if (arg_pack)
7596         {
7597           int my_len = 
7598             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7599
7600           /* It's all-or-nothing with incomplete argument packs.  */
7601           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7602             return error_mark_node;
7603           
7604           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7605             incomplete = 1;
7606
7607           if (len < 0)
7608             {
7609               len = my_len;
7610               first_arg_pack = arg_pack;
7611             }
7612           else if (len != my_len)
7613             {
7614               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
7615                 error ("mismatched argument pack lengths while expanding "
7616                        "%<%T%>",
7617                        pattern);
7618               else
7619                 error ("mismatched argument pack lengths while expanding "
7620                        "%<%E%>",
7621                        pattern);
7622               return error_mark_node;
7623             }
7624
7625           /* Keep track of the parameter packs and their corresponding
7626              argument packs.  */
7627           packs = tree_cons (parm_pack, arg_pack, packs);
7628           TREE_TYPE (packs) = orig_arg;
7629         }
7630       else
7631         /* We can't substitute for this parameter pack.  */
7632         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
7633                                          TREE_VALUE (pack),
7634                                          unsubstituted_packs);
7635     }
7636
7637   /* We cannot expand this expansion expression, because we don't have
7638      all of the argument packs we need. Substitute into the pattern
7639      and return a PACK_EXPANSION_*. The caller will need to deal with
7640      that.  */
7641   if (unsubstituted_packs)
7642     return make_pack_expansion (tsubst (pattern, args, complain, 
7643                                         in_decl));
7644
7645   /* We could not find any argument packs that work.  */
7646   if (len < 0)
7647     return error_mark_node;
7648
7649   if (!local_specializations)
7650     {
7651       /* We're in a late-specified return type, so we don't have a local
7652          specializations table.  Create one for doing this expansion.  */
7653       very_local_specializations = true;
7654       local_specializations = htab_create (37,
7655                                            hash_local_specialization,
7656                                            eq_local_specializations,
7657                                            NULL);
7658     }
7659
7660   /* For each argument in each argument pack, substitute into the
7661      pattern.  */
7662   result = make_tree_vec (len + incomplete);
7663   for (i = 0; i < len + incomplete; ++i)
7664     {
7665       /* For parameter pack, change the substitution of the parameter
7666          pack to the ith argument in its argument pack, then expand
7667          the pattern.  */
7668       for (pack = packs; pack; pack = TREE_CHAIN (pack))
7669         {
7670           tree parm = TREE_PURPOSE (pack);
7671
7672           if (TREE_CODE (parm) == PARM_DECL)
7673             {
7674               /* Select the Ith argument from the pack.  */
7675               tree arg = make_node (ARGUMENT_PACK_SELECT);
7676               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
7677               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
7678               mark_used (parm);
7679               register_local_specialization (arg, parm);
7680             }
7681           else
7682             {
7683               tree value = parm;
7684               int idx, level;
7685               template_parm_level_and_index (parm, &level, &idx);
7686               
7687               if (i < len) 
7688                 {
7689                   /* Select the Ith argument from the pack. */
7690                   value = make_node (ARGUMENT_PACK_SELECT);
7691                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
7692                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
7693                 }
7694
7695               /* Update the corresponding argument.  */
7696               TMPL_ARG (args, level, idx) = value;
7697             }
7698         }
7699
7700       /* Substitute into the PATTERN with the altered arguments.  */
7701       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7702         TREE_VEC_ELT (result, i) = 
7703           tsubst_expr (pattern, args, complain, in_decl,
7704                        /*integral_constant_expression_p=*/false);
7705       else
7706         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
7707
7708       if (i == len)
7709         /* When we have incomplete argument packs, the last "expanded"
7710            result is itself a pack expansion, which allows us
7711            to deduce more arguments.  */
7712         TREE_VEC_ELT (result, i) = 
7713           make_pack_expansion (TREE_VEC_ELT (result, i));
7714
7715       if (TREE_VEC_ELT (result, i) == error_mark_node)
7716         {
7717           result = error_mark_node;
7718           break;
7719         }
7720     }
7721
7722   /* Update ARGS to restore the substitution from parameter packs to
7723      their argument packs.  */
7724   for (pack = packs; pack; pack = TREE_CHAIN (pack))
7725     {
7726       tree parm = TREE_PURPOSE (pack);
7727
7728       if (TREE_CODE (parm) == PARM_DECL)
7729         register_local_specialization (TREE_TYPE (pack), parm);
7730       else
7731         {
7732           int idx, level;
7733           template_parm_level_and_index (parm, &level, &idx);
7734           
7735           /* Update the corresponding argument.  */
7736           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
7737             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
7738               TREE_TYPE (pack);
7739           else
7740             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
7741         }
7742     }
7743
7744   if (very_local_specializations)
7745     {
7746       htab_delete (local_specializations);
7747       local_specializations = NULL;
7748     }
7749   
7750   return result;
7751 }
7752
7753 /* Substitute ARGS into the vector or list of template arguments T.  */
7754
7755 static tree
7756 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7757 {
7758   tree orig_t = t;
7759   int len = TREE_VEC_LENGTH (t);
7760   int need_new = 0, i, expanded_len_adjust = 0, out;
7761   tree *elts = (tree *) alloca (len * sizeof (tree));
7762
7763   for (i = 0; i < len; i++)
7764     {
7765       tree orig_arg = TREE_VEC_ELT (t, i);
7766       tree new_arg;
7767
7768       if (TREE_CODE (orig_arg) == TREE_VEC)
7769         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
7770       else if (PACK_EXPANSION_P (orig_arg))
7771         {
7772           /* Substitute into an expansion expression.  */
7773           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
7774
7775           if (TREE_CODE (new_arg) == TREE_VEC)
7776             /* Add to the expanded length adjustment the number of
7777                expanded arguments. We subtract one from this
7778                measurement, because the argument pack expression
7779                itself is already counted as 1 in
7780                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
7781                the argument pack is empty.  */
7782             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
7783         }
7784       else if (ARGUMENT_PACK_P (orig_arg))
7785         {
7786           /* Substitute into each of the arguments.  */
7787           new_arg = make_node (TREE_CODE (orig_arg));
7788           
7789           SET_ARGUMENT_PACK_ARGS (
7790             new_arg,
7791             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
7792                                   args, complain, in_decl));
7793
7794           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
7795             new_arg = error_mark_node;
7796
7797           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
7798             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
7799                                           complain, in_decl);
7800             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
7801
7802             if (TREE_TYPE (new_arg) == error_mark_node)
7803               new_arg = error_mark_node;
7804           }
7805         }
7806       else
7807         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
7808
7809       if (new_arg == error_mark_node)
7810         return error_mark_node;
7811
7812       elts[i] = new_arg;
7813       if (new_arg != orig_arg)
7814         need_new = 1;
7815     }
7816
7817   if (!need_new)
7818     return t;
7819
7820   /* Make space for the expanded arguments coming from template
7821      argument packs.  */
7822   t = make_tree_vec (len + expanded_len_adjust);
7823   for (i = 0, out = 0; i < len; i++)
7824     {
7825       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
7826            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
7827           && TREE_CODE (elts[i]) == TREE_VEC)
7828         {
7829           int idx;
7830
7831           /* Now expand the template argument pack "in place".  */
7832           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
7833             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
7834         }
7835       else
7836         {
7837           TREE_VEC_ELT (t, out) = elts[i];
7838           out++;
7839         }
7840     }
7841
7842   return t;
7843 }
7844
7845 /* Return the result of substituting ARGS into the template parameters
7846    given by PARMS.  If there are m levels of ARGS and m + n levels of
7847    PARMS, then the result will contain n levels of PARMS.  For
7848    example, if PARMS is `template <class T> template <class U>
7849    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
7850    result will be `template <int*, double, class V>'.  */
7851
7852 static tree
7853 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
7854 {
7855   tree r = NULL_TREE;
7856   tree* new_parms;
7857
7858   /* When substituting into a template, we must set
7859      PROCESSING_TEMPLATE_DECL as the template parameters may be
7860      dependent if they are based on one-another, and the dependency
7861      predicates are short-circuit outside of templates.  */
7862   ++processing_template_decl;
7863
7864   for (new_parms = &r;
7865        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
7866        new_parms = &(TREE_CHAIN (*new_parms)),
7867          parms = TREE_CHAIN (parms))
7868     {
7869       tree new_vec =
7870         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
7871       int i;
7872
7873       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
7874         {
7875           tree tuple;
7876           tree default_value;
7877           tree parm_decl;
7878
7879           if (parms == error_mark_node)
7880             continue;
7881
7882           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
7883
7884           if (tuple == error_mark_node)
7885             continue;
7886
7887           default_value = TREE_PURPOSE (tuple);
7888           parm_decl = TREE_VALUE (tuple);
7889
7890           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
7891           if (TREE_CODE (parm_decl) == PARM_DECL
7892               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
7893             parm_decl = error_mark_node;
7894           default_value = tsubst_template_arg (default_value, args,
7895                                                complain, NULL_TREE);
7896
7897           tuple = build_tree_list (default_value, parm_decl);
7898           TREE_VEC_ELT (new_vec, i) = tuple;
7899         }
7900
7901       *new_parms =
7902         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
7903                              - TMPL_ARGS_DEPTH (args)),
7904                    new_vec, NULL_TREE);
7905     }
7906
7907   --processing_template_decl;
7908
7909   return r;
7910 }
7911
7912 /* Substitute the ARGS into the indicated aggregate (or enumeration)
7913    type T.  If T is not an aggregate or enumeration type, it is
7914    handled as if by tsubst.  IN_DECL is as for tsubst.  If
7915    ENTERING_SCOPE is nonzero, T is the context for a template which
7916    we are presently tsubst'ing.  Return the substituted value.  */
7917
7918 static tree
7919 tsubst_aggr_type (tree t,
7920                   tree args,
7921                   tsubst_flags_t complain,
7922                   tree in_decl,
7923                   int entering_scope)
7924 {
7925   if (t == NULL_TREE)
7926     return NULL_TREE;
7927
7928   switch (TREE_CODE (t))
7929     {
7930     case RECORD_TYPE:
7931       if (TYPE_PTRMEMFUNC_P (t))
7932         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
7933
7934       /* Else fall through.  */
7935     case ENUMERAL_TYPE:
7936     case UNION_TYPE:
7937       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
7938         {
7939           tree argvec;
7940           tree context;
7941           tree r;
7942           bool saved_skip_evaluation;
7943
7944           /* In "sizeof(X<I>)" we need to evaluate "I".  */
7945           saved_skip_evaluation = skip_evaluation;
7946           skip_evaluation = false;
7947
7948           /* First, determine the context for the type we are looking
7949              up.  */
7950           context = TYPE_CONTEXT (t);
7951           if (context)
7952             {
7953               context = tsubst_aggr_type (context, args, complain,
7954                                           in_decl, /*entering_scope=*/1);
7955               /* If context is a nested class inside a class template,
7956                  it may still need to be instantiated (c++/33959).  */
7957               if (TYPE_P (context))
7958                 context = complete_type (context);
7959             }
7960
7961           /* Then, figure out what arguments are appropriate for the
7962              type we are trying to find.  For example, given:
7963
7964                template <class T> struct S;
7965                template <class T, class U> void f(T, U) { S<U> su; }
7966
7967              and supposing that we are instantiating f<int, double>,
7968              then our ARGS will be {int, double}, but, when looking up
7969              S we only want {double}.  */
7970           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
7971                                          complain, in_decl);
7972           if (argvec == error_mark_node)
7973             r = error_mark_node;
7974           else
7975             {
7976               r = lookup_template_class (t, argvec, in_decl, context,
7977                                          entering_scope, complain);
7978               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
7979             }
7980
7981           skip_evaluation = saved_skip_evaluation;
7982
7983           return r;
7984         }
7985       else
7986         /* This is not a template type, so there's nothing to do.  */
7987         return t;
7988
7989     default:
7990       return tsubst (t, args, complain, in_decl);
7991     }
7992 }
7993
7994 /* Substitute into the default argument ARG (a default argument for
7995    FN), which has the indicated TYPE.  */
7996
7997 tree
7998 tsubst_default_argument (tree fn, tree type, tree arg)
7999 {
8000   tree saved_class_ptr = NULL_TREE;
8001   tree saved_class_ref = NULL_TREE;
8002
8003   /* This default argument came from a template.  Instantiate the
8004      default argument here, not in tsubst.  In the case of
8005      something like:
8006
8007        template <class T>
8008        struct S {
8009          static T t();
8010          void f(T = t());
8011        };
8012
8013      we must be careful to do name lookup in the scope of S<T>,
8014      rather than in the current class.  */
8015   push_access_scope (fn);
8016   /* The "this" pointer is not valid in a default argument.  */
8017   if (cfun)
8018     {
8019       saved_class_ptr = current_class_ptr;
8020       cp_function_chain->x_current_class_ptr = NULL_TREE;
8021       saved_class_ref = current_class_ref;
8022       cp_function_chain->x_current_class_ref = NULL_TREE;
8023     }
8024
8025   push_deferring_access_checks(dk_no_deferred);
8026   /* The default argument expression may cause implicitly defined
8027      member functions to be synthesized, which will result in garbage
8028      collection.  We must treat this situation as if we were within
8029      the body of function so as to avoid collecting live data on the
8030      stack.  */
8031   ++function_depth;
8032   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8033                      tf_warning_or_error, NULL_TREE,
8034                      /*integral_constant_expression_p=*/false);
8035   --function_depth;
8036   pop_deferring_access_checks();
8037
8038   /* Restore the "this" pointer.  */
8039   if (cfun)
8040     {
8041       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8042       cp_function_chain->x_current_class_ref = saved_class_ref;
8043     }
8044
8045   pop_access_scope (fn);
8046
8047   /* Make sure the default argument is reasonable.  */
8048   arg = check_default_argument (type, arg);
8049
8050   return arg;
8051 }
8052
8053 /* Substitute into all the default arguments for FN.  */
8054
8055 static void
8056 tsubst_default_arguments (tree fn)
8057 {
8058   tree arg;
8059   tree tmpl_args;
8060
8061   tmpl_args = DECL_TI_ARGS (fn);
8062
8063   /* If this function is not yet instantiated, we certainly don't need
8064      its default arguments.  */
8065   if (uses_template_parms (tmpl_args))
8066     return;
8067
8068   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8069        arg;
8070        arg = TREE_CHAIN (arg))
8071     if (TREE_PURPOSE (arg))
8072       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8073                                                     TREE_VALUE (arg),
8074                                                     TREE_PURPOSE (arg));
8075 }
8076
8077 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8078    result of the substitution.  Issue error and warning messages under
8079    control of COMPLAIN.  */
8080
8081 static tree
8082 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8083 {
8084   location_t saved_loc;
8085   tree r = NULL_TREE;
8086   tree in_decl = t;
8087
8088   /* Set the filename and linenumber to improve error-reporting.  */
8089   saved_loc = input_location;
8090   input_location = DECL_SOURCE_LOCATION (t);
8091
8092   switch (TREE_CODE (t))
8093     {
8094     case TEMPLATE_DECL:
8095       {
8096         /* We can get here when processing a member function template,
8097            member class template, and template template parameter of
8098            a template class.  */
8099         tree decl = DECL_TEMPLATE_RESULT (t);
8100         tree spec;
8101         tree tmpl_args;
8102         tree full_args;
8103
8104         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8105           {
8106             /* Template template parameter is treated here.  */
8107             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8108             if (new_type == error_mark_node)
8109               return error_mark_node;
8110
8111             r = copy_decl (t);
8112             TREE_CHAIN (r) = NULL_TREE;
8113             TREE_TYPE (r) = new_type;
8114             DECL_TEMPLATE_RESULT (r)
8115               = build_decl (TYPE_DECL, DECL_NAME (decl), new_type);
8116             DECL_TEMPLATE_PARMS (r)
8117               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8118                                        complain);
8119             TYPE_NAME (new_type) = r;
8120             break;
8121           }
8122
8123         /* We might already have an instance of this template.
8124            The ARGS are for the surrounding class type, so the
8125            full args contain the tsubst'd args for the context,
8126            plus the innermost args from the template decl.  */
8127         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8128           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8129           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8130         /* Because this is a template, the arguments will still be
8131            dependent, even after substitution.  If
8132            PROCESSING_TEMPLATE_DECL is not set, the dependency
8133            predicates will short-circuit.  */
8134         ++processing_template_decl;
8135         full_args = tsubst_template_args (tmpl_args, args,
8136                                           complain, in_decl);
8137         --processing_template_decl;
8138         if (full_args == error_mark_node)
8139           return error_mark_node;
8140
8141         /* tsubst_template_args doesn't copy the vector if
8142            nothing changed.  But, *something* should have
8143            changed.  */
8144         gcc_assert (full_args != tmpl_args);
8145
8146         spec = retrieve_specialization (t, full_args,
8147                                         /*class_specializations_p=*/true);
8148         if (spec != NULL_TREE)
8149           {
8150             r = spec;
8151             break;
8152           }
8153
8154         /* Make a new template decl.  It will be similar to the
8155            original, but will record the current template arguments.
8156            We also create a new function declaration, which is just
8157            like the old one, but points to this new template, rather
8158            than the old one.  */
8159         r = copy_decl (t);
8160         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8161         TREE_CHAIN (r) = NULL_TREE;
8162
8163         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
8164
8165         if (TREE_CODE (decl) == TYPE_DECL)
8166           {
8167             tree new_type;
8168             ++processing_template_decl;
8169             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8170             --processing_template_decl;
8171             if (new_type == error_mark_node)
8172               return error_mark_node;
8173
8174             TREE_TYPE (r) = new_type;
8175             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8176             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8177             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8178             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8179           }
8180         else
8181           {
8182             tree new_decl;
8183             ++processing_template_decl;
8184             new_decl = tsubst (decl, args, complain, in_decl);
8185             --processing_template_decl;
8186             if (new_decl == error_mark_node)
8187               return error_mark_node;
8188
8189             DECL_TEMPLATE_RESULT (r) = new_decl;
8190             DECL_TI_TEMPLATE (new_decl) = r;
8191             TREE_TYPE (r) = TREE_TYPE (new_decl);
8192             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8193             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8194           }
8195
8196         SET_DECL_IMPLICIT_INSTANTIATION (r);
8197         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8198         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8199
8200         /* The template parameters for this new template are all the
8201            template parameters for the old template, except the
8202            outermost level of parameters.  */
8203         DECL_TEMPLATE_PARMS (r)
8204           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8205                                    complain);
8206
8207         if (PRIMARY_TEMPLATE_P (t))
8208           DECL_PRIMARY_TEMPLATE (r) = r;
8209
8210         if (TREE_CODE (decl) != TYPE_DECL)
8211           /* Record this non-type partial instantiation.  */
8212           register_specialization (r, t,
8213                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8214                                    false);
8215       }
8216       break;
8217
8218     case FUNCTION_DECL:
8219       {
8220         tree ctx;
8221         tree argvec = NULL_TREE;
8222         tree *friends;
8223         tree gen_tmpl;
8224         tree type;
8225         int member;
8226         int args_depth;
8227         int parms_depth;
8228
8229         /* Nobody should be tsubst'ing into non-template functions.  */
8230         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8231
8232         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8233           {
8234             tree spec;
8235             bool dependent_p;
8236
8237             /* If T is not dependent, just return it.  We have to
8238                increment PROCESSING_TEMPLATE_DECL because
8239                value_dependent_expression_p assumes that nothing is
8240                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8241             ++processing_template_decl;
8242             dependent_p = value_dependent_expression_p (t);
8243             --processing_template_decl;
8244             if (!dependent_p)
8245               return t;
8246
8247             /* Calculate the most general template of which R is a
8248                specialization, and the complete set of arguments used to
8249                specialize R.  */
8250             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8251             argvec = tsubst_template_args (DECL_TI_ARGS
8252                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8253                                            args, complain, in_decl);
8254
8255             /* Check to see if we already have this specialization.  */
8256             spec = retrieve_specialization (gen_tmpl, argvec,
8257                                             /*class_specializations_p=*/false);
8258
8259             if (spec)
8260               {
8261                 r = spec;
8262                 break;
8263               }
8264
8265             /* We can see more levels of arguments than parameters if
8266                there was a specialization of a member template, like
8267                this:
8268
8269                  template <class T> struct S { template <class U> void f(); }
8270                  template <> template <class U> void S<int>::f(U);
8271
8272                Here, we'll be substituting into the specialization,
8273                because that's where we can find the code we actually
8274                want to generate, but we'll have enough arguments for
8275                the most general template.
8276
8277                We also deal with the peculiar case:
8278
8279                  template <class T> struct S {
8280                    template <class U> friend void f();
8281                  };
8282                  template <class U> void f() {}
8283                  template S<int>;
8284                  template void f<double>();
8285
8286                Here, the ARGS for the instantiation of will be {int,
8287                double}.  But, we only need as many ARGS as there are
8288                levels of template parameters in CODE_PATTERN.  We are
8289                careful not to get fooled into reducing the ARGS in
8290                situations like:
8291
8292                  template <class T> struct S { template <class U> void f(U); }
8293                  template <class T> template <> void S<T>::f(int) {}
8294
8295                which we can spot because the pattern will be a
8296                specialization in this case.  */
8297             args_depth = TMPL_ARGS_DEPTH (args);
8298             parms_depth =
8299               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8300             if (args_depth > parms_depth
8301                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8302               args = get_innermost_template_args (args, parms_depth);
8303           }
8304         else
8305           {
8306             /* This special case arises when we have something like this:
8307
8308                  template <class T> struct S {
8309                    friend void f<int>(int, double);
8310                  };
8311
8312                Here, the DECL_TI_TEMPLATE for the friend declaration
8313                will be an IDENTIFIER_NODE.  We are being called from
8314                tsubst_friend_function, and we want only to create a
8315                new decl (R) with appropriate types so that we can call
8316                determine_specialization.  */
8317             gen_tmpl = NULL_TREE;
8318           }
8319
8320         if (DECL_CLASS_SCOPE_P (t))
8321           {
8322             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8323               member = 2;
8324             else
8325               member = 1;
8326             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8327                                     complain, t, /*entering_scope=*/1);
8328           }
8329         else
8330           {
8331             member = 0;
8332             ctx = DECL_CONTEXT (t);
8333           }
8334         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8335         if (type == error_mark_node)
8336           return error_mark_node;
8337
8338         /* We do NOT check for matching decls pushed separately at this
8339            point, as they may not represent instantiations of this
8340            template, and in any case are considered separate under the
8341            discrete model.  */
8342         r = copy_decl (t);
8343         DECL_USE_TEMPLATE (r) = 0;
8344         TREE_TYPE (r) = type;
8345         /* Clear out the mangled name and RTL for the instantiation.  */
8346         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8347         SET_DECL_RTL (r, NULL_RTX);
8348         /* Leave DECL_INITIAL set on deleted instantiations.  */
8349         if (!DECL_DELETED_FN (r))
8350           DECL_INITIAL (r) = NULL_TREE;
8351         DECL_CONTEXT (r) = ctx;
8352
8353         if (member && DECL_CONV_FN_P (r))
8354           /* Type-conversion operator.  Reconstruct the name, in
8355              case it's the name of one of the template's parameters.  */
8356           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8357
8358         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8359                                      complain, t);
8360         DECL_RESULT (r) = NULL_TREE;
8361
8362         TREE_STATIC (r) = 0;
8363         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8364         DECL_EXTERNAL (r) = 1;
8365         /* If this is an instantiation of a function with internal
8366            linkage, we already know what object file linkage will be
8367            assigned to the instantiation.  */
8368         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8369         DECL_DEFER_OUTPUT (r) = 0;
8370         TREE_CHAIN (r) = NULL_TREE;
8371         DECL_PENDING_INLINE_INFO (r) = 0;
8372         DECL_PENDING_INLINE_P (r) = 0;
8373         DECL_SAVED_TREE (r) = NULL_TREE;
8374         DECL_STRUCT_FUNCTION (r) = NULL;
8375         TREE_USED (r) = 0;
8376         if (DECL_CLONED_FUNCTION (r))
8377           {
8378             DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
8379                                                args, complain, t);
8380             TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
8381             TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
8382           }
8383
8384         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8385            this in the special friend case mentioned above where
8386            GEN_TMPL is NULL.  */
8387         if (gen_tmpl)
8388           {
8389             DECL_TEMPLATE_INFO (r)
8390               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8391             SET_DECL_IMPLICIT_INSTANTIATION (r);
8392             register_specialization (r, gen_tmpl, argvec, false);
8393
8394             /* We're not supposed to instantiate default arguments
8395                until they are called, for a template.  But, for a
8396                declaration like:
8397
8398                  template <class T> void f ()
8399                  { extern void g(int i = T()); }
8400
8401                we should do the substitution when the template is
8402                instantiated.  We handle the member function case in
8403                instantiate_class_template since the default arguments
8404                might refer to other members of the class.  */
8405             if (!member
8406                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8407                 && !uses_template_parms (argvec))
8408               tsubst_default_arguments (r);
8409           }
8410         else
8411           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8412
8413         /* Copy the list of befriending classes.  */
8414         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8415              *friends;
8416              friends = &TREE_CHAIN (*friends))
8417           {
8418             *friends = copy_node (*friends);
8419             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8420                                             args, complain,
8421                                             in_decl);
8422           }
8423
8424         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8425           {
8426             maybe_retrofit_in_chrg (r);
8427             if (DECL_CONSTRUCTOR_P (r))
8428               grok_ctor_properties (ctx, r);
8429             /* If this is an instantiation of a member template, clone it.
8430                If it isn't, that'll be handled by
8431                clone_constructors_and_destructors.  */
8432             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8433               clone_function_decl (r, /*update_method_vec_p=*/0);
8434           }
8435         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r))
8436                  && !grok_op_properties (r, (complain & tf_error) != 0))
8437           return error_mark_node;
8438
8439         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8440           SET_DECL_FRIEND_CONTEXT (r,
8441                                    tsubst (DECL_FRIEND_CONTEXT (t),
8442                                             args, complain, in_decl));
8443
8444         /* Possibly limit visibility based on template args.  */
8445         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8446         if (DECL_VISIBILITY_SPECIFIED (t))
8447           {
8448             DECL_VISIBILITY_SPECIFIED (r) = 0;
8449             DECL_ATTRIBUTES (r)
8450               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8451           }
8452         determine_visibility (r);
8453
8454         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8455                                         args, complain, in_decl);
8456       }
8457       break;
8458
8459     case PARM_DECL:
8460       {
8461         tree type = NULL_TREE;
8462         int i, len = 1;
8463         tree expanded_types = NULL_TREE;
8464         tree prev_r = NULL_TREE;
8465         tree first_r = NULL_TREE;
8466
8467         if (FUNCTION_PARAMETER_PACK_P (t))
8468           {
8469             /* If there is a local specialization that isn't a
8470                parameter pack, it means that we're doing a "simple"
8471                substitution from inside tsubst_pack_expansion. Just
8472                return the local specialization (which will be a single
8473                parm).  */
8474             tree spec = retrieve_local_specialization (t);
8475             if (spec 
8476                 && TREE_CODE (spec) == PARM_DECL
8477                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8478               return spec;
8479
8480             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8481                the parameters in this function parameter pack.  */
8482             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8483                                                     complain, in_decl);
8484             if (TREE_CODE (expanded_types) == TREE_VEC)
8485               {
8486                 len = TREE_VEC_LENGTH (expanded_types);
8487
8488                 /* Zero-length parameter packs are boring. Just substitute
8489                    into the chain.  */
8490                 if (len == 0)
8491                   return tsubst (TREE_CHAIN (t), args, complain, 
8492                                  TREE_CHAIN (t));
8493               }
8494             else
8495               {
8496                 /* All we did was update the type. Make a note of that.  */
8497                 type = expanded_types;
8498                 expanded_types = NULL_TREE;
8499               }
8500           }
8501
8502         /* Loop through all of the parameter's we'll build. When T is
8503            a function parameter pack, LEN is the number of expanded
8504            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8505         r = NULL_TREE;
8506         for (i = 0; i < len; ++i)
8507           {
8508             prev_r = r;
8509             r = copy_node (t);
8510             if (DECL_TEMPLATE_PARM_P (t))
8511               SET_DECL_TEMPLATE_PARM_P (r);
8512
8513             if (expanded_types)
8514               /* We're on the Ith parameter of the function parameter
8515                  pack.  */
8516               {
8517                 /* Get the Ith type.  */
8518                 type = TREE_VEC_ELT (expanded_types, i);
8519
8520                 if (DECL_NAME (r))
8521                   /* Rename the parameter to include the index.  */
8522                   DECL_NAME (r) =
8523                     make_ith_pack_parameter_name (DECL_NAME (r), i);
8524               }
8525             else if (!type)
8526               /* We're dealing with a normal parameter.  */
8527               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8528
8529             type = type_decays_to (type);
8530             TREE_TYPE (r) = type;
8531             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8532
8533             if (DECL_INITIAL (r))
8534               {
8535                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
8536                   DECL_INITIAL (r) = TREE_TYPE (r);
8537                 else
8538                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
8539                                              complain, in_decl);
8540               }
8541
8542             DECL_CONTEXT (r) = NULL_TREE;
8543
8544             if (!DECL_TEMPLATE_PARM_P (r))
8545               DECL_ARG_TYPE (r) = type_passed_as (type);
8546
8547             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8548                                             args, complain, in_decl);
8549
8550             /* Keep track of the first new parameter we
8551                generate. That's what will be returned to the
8552                caller.  */
8553             if (!first_r)
8554               first_r = r;
8555
8556             /* Build a proper chain of parameters when substituting
8557                into a function parameter pack.  */
8558             if (prev_r)
8559               TREE_CHAIN (prev_r) = r;
8560           }
8561
8562         if (TREE_CHAIN (t))
8563           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
8564                                    complain, TREE_CHAIN (t));
8565
8566         /* FIRST_R contains the start of the chain we've built.  */
8567         r = first_r;
8568       }
8569       break;
8570
8571     case FIELD_DECL:
8572       {
8573         tree type;
8574
8575         r = copy_decl (t);
8576         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8577         if (type == error_mark_node)
8578           return error_mark_node;
8579         TREE_TYPE (r) = type;
8580         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8581
8582         /* DECL_INITIAL gives the number of bits in a bit-field.  */
8583         DECL_INITIAL (r)
8584           = tsubst_expr (DECL_INITIAL (t), args,
8585                          complain, in_decl,
8586                          /*integral_constant_expression_p=*/true);
8587         /* We don't have to set DECL_CONTEXT here; it is set by
8588            finish_member_declaration.  */
8589         TREE_CHAIN (r) = NULL_TREE;
8590         if (VOID_TYPE_P (type))
8591           error ("instantiation of %q+D as type %qT", r, type);
8592
8593         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8594                                         args, complain, in_decl);
8595       }
8596       break;
8597
8598     case USING_DECL:
8599       /* We reach here only for member using decls.  */
8600       if (DECL_DEPENDENT_P (t))
8601         {
8602           r = do_class_using_decl
8603             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
8604              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
8605           if (!r)
8606             r = error_mark_node;
8607           else
8608             {
8609               TREE_PROTECTED (r) = TREE_PROTECTED (t);
8610               TREE_PRIVATE (r) = TREE_PRIVATE (t);
8611             }
8612         }
8613       else
8614         {
8615           r = copy_node (t);
8616           TREE_CHAIN (r) = NULL_TREE;
8617         }
8618       break;
8619
8620     case TYPE_DECL:
8621     case VAR_DECL:
8622       {
8623         tree argvec = NULL_TREE;
8624         tree gen_tmpl = NULL_TREE;
8625         tree spec;
8626         tree tmpl = NULL_TREE;
8627         tree ctx;
8628         tree type = NULL_TREE;
8629         bool local_p;
8630
8631         if (TREE_CODE (t) == TYPE_DECL
8632             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
8633           {
8634             /* If this is the canonical decl, we don't have to
8635                mess with instantiations, and often we can't (for
8636                typename, template type parms and such).  Note that
8637                TYPE_NAME is not correct for the above test if
8638                we've copied the type for a typedef.  */
8639             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8640             if (type == error_mark_node)
8641               return error_mark_node;
8642             r = TYPE_NAME (type);
8643             break;
8644           }
8645
8646         /* Check to see if we already have the specialization we
8647            need.  */
8648         spec = NULL_TREE;
8649         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
8650           {
8651             /* T is a static data member or namespace-scope entity.
8652                We have to substitute into namespace-scope variables
8653                (even though such entities are never templates) because
8654                of cases like:
8655                
8656                  template <class T> void f() { extern T t; }
8657
8658                where the entity referenced is not known until
8659                instantiation time.  */
8660             local_p = false;
8661             ctx = DECL_CONTEXT (t);
8662             if (DECL_CLASS_SCOPE_P (t))
8663               {
8664                 ctx = tsubst_aggr_type (ctx, args,
8665                                         complain,
8666                                         in_decl, /*entering_scope=*/1);
8667                 /* If CTX is unchanged, then T is in fact the
8668                    specialization we want.  That situation occurs when
8669                    referencing a static data member within in its own
8670                    class.  We can use pointer equality, rather than
8671                    same_type_p, because DECL_CONTEXT is always
8672                    canonical.  */
8673                 if (ctx == DECL_CONTEXT (t))
8674                   spec = t;
8675               }
8676
8677             if (!spec)
8678               {
8679                 tmpl = DECL_TI_TEMPLATE (t);
8680                 gen_tmpl = most_general_template (tmpl);
8681                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
8682                 spec = (retrieve_specialization 
8683                         (gen_tmpl, argvec,
8684                          /*class_specializations_p=*/false));
8685               }
8686           }
8687         else
8688           {
8689             /* A local variable.  */
8690             local_p = true;
8691             /* Subsequent calls to pushdecl will fill this in.  */
8692             ctx = NULL_TREE;
8693             spec = retrieve_local_specialization (t);
8694           }
8695         /* If we already have the specialization we need, there is
8696            nothing more to do.  */ 
8697         if (spec)
8698           {
8699             r = spec;
8700             break;
8701           }
8702
8703         /* Create a new node for the specialization we need.  */
8704         r = copy_decl (t);
8705         if (type == NULL_TREE)
8706           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8707         if (TREE_CODE (r) == VAR_DECL)
8708           {
8709             /* Even if the original location is out of scope, the
8710                newly substituted one is not.  */
8711             DECL_DEAD_FOR_LOCAL (r) = 0;
8712             DECL_INITIALIZED_P (r) = 0;
8713             DECL_TEMPLATE_INSTANTIATED (r) = 0;
8714             if (type == error_mark_node)
8715               return error_mark_node;
8716             if (TREE_CODE (type) == FUNCTION_TYPE)
8717               {
8718                 /* It may seem that this case cannot occur, since:
8719
8720                      typedef void f();
8721                      void g() { f x; }
8722
8723                    declares a function, not a variable.  However:
8724       
8725                      typedef void f();
8726                      template <typename T> void g() { T t; }
8727                      template void g<f>();
8728
8729                    is an attempt to declare a variable with function
8730                    type.  */
8731                 error ("variable %qD has function type",
8732                        /* R is not yet sufficiently initialized, so we
8733                           just use its name.  */
8734                        DECL_NAME (r));
8735                 return error_mark_node;
8736               }
8737             type = complete_type (type);
8738             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
8739               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
8740             type = check_var_type (DECL_NAME (r), type);
8741
8742             if (DECL_HAS_VALUE_EXPR_P (t))
8743               {
8744                 tree ve = DECL_VALUE_EXPR (t);
8745                 ve = tsubst_expr (ve, args, complain, in_decl,
8746                                   /*constant_expression_p=*/false);
8747                 SET_DECL_VALUE_EXPR (r, ve);
8748               }
8749           }
8750         else if (DECL_SELF_REFERENCE_P (t))
8751           SET_DECL_SELF_REFERENCE_P (r);
8752         TREE_TYPE (r) = type;
8753         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8754         DECL_CONTEXT (r) = ctx;
8755         /* Clear out the mangled name and RTL for the instantiation.  */
8756         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8757         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8758           SET_DECL_RTL (r, NULL_RTX);
8759         /* The initializer must not be expanded until it is required;
8760            see [temp.inst].  */
8761         DECL_INITIAL (r) = NULL_TREE;
8762         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8763           SET_DECL_RTL (r, NULL_RTX);
8764         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
8765         if (TREE_CODE (r) == VAR_DECL)
8766           {
8767             /* Possibly limit visibility based on template args.  */
8768             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8769             if (DECL_VISIBILITY_SPECIFIED (t))
8770               {
8771                 DECL_VISIBILITY_SPECIFIED (r) = 0;
8772                 DECL_ATTRIBUTES (r)
8773                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8774               }
8775             determine_visibility (r);
8776           }
8777         /* Preserve a typedef that names a type.  */
8778         else if (TREE_CODE (r) == TYPE_DECL
8779                  && DECL_ORIGINAL_TYPE (t)
8780                  && type != error_mark_node)
8781           {
8782             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
8783                                              args, complain, in_decl);
8784             TREE_TYPE (r) = type = build_variant_type_copy (type);
8785             TYPE_NAME (type) = r;
8786           }
8787
8788         if (!local_p)
8789           {
8790             /* A static data member declaration is always marked
8791                external when it is declared in-class, even if an
8792                initializer is present.  We mimic the non-template
8793                processing here.  */
8794             DECL_EXTERNAL (r) = 1;
8795
8796             register_specialization (r, gen_tmpl, argvec, false);
8797             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
8798             SET_DECL_IMPLICIT_INSTANTIATION (r);
8799           }
8800         else
8801           register_local_specialization (r, t);
8802
8803         TREE_CHAIN (r) = NULL_TREE;
8804
8805         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
8806                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
8807                                         args, complain, in_decl);
8808         layout_decl (r, 0);
8809       }
8810       break;
8811
8812     default:
8813       gcc_unreachable ();
8814     }
8815
8816   /* Restore the file and line information.  */
8817   input_location = saved_loc;
8818
8819   return r;
8820 }
8821
8822 /* Substitute into the ARG_TYPES of a function type.  */
8823
8824 static tree
8825 tsubst_arg_types (tree arg_types,
8826                   tree args,
8827                   tsubst_flags_t complain,
8828                   tree in_decl)
8829 {
8830   tree remaining_arg_types;
8831   tree type = NULL_TREE;
8832   int i = 1;
8833   tree expanded_args = NULL_TREE;
8834   tree default_arg;
8835
8836   if (!arg_types || arg_types == void_list_node)
8837     return arg_types;
8838
8839   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
8840                                           args, complain, in_decl);
8841   if (remaining_arg_types == error_mark_node)
8842     return error_mark_node;
8843
8844   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
8845     {
8846       /* For a pack expansion, perform substitution on the
8847          entire expression. Later on, we'll handle the arguments
8848          one-by-one.  */
8849       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
8850                                             args, complain, in_decl);
8851
8852       if (TREE_CODE (expanded_args) == TREE_VEC)
8853         /* So that we'll spin through the parameters, one by one.  */
8854         i = TREE_VEC_LENGTH (expanded_args);
8855       else
8856         {
8857           /* We only partially substituted into the parameter
8858              pack. Our type is TYPE_PACK_EXPANSION.  */
8859           type = expanded_args;
8860           expanded_args = NULL_TREE;
8861         }
8862     }
8863
8864   while (i > 0) {
8865     --i;
8866     
8867     if (expanded_args)
8868       type = TREE_VEC_ELT (expanded_args, i);
8869     else if (!type)
8870       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
8871
8872     if (type == error_mark_node)
8873       return error_mark_node;
8874     if (VOID_TYPE_P (type))
8875       {
8876         if (complain & tf_error)
8877           {
8878             error ("invalid parameter type %qT", type);
8879             if (in_decl)
8880               error ("in declaration %q+D", in_decl);
8881           }
8882         return error_mark_node;
8883     }
8884     
8885     /* Do array-to-pointer, function-to-pointer conversion, and ignore
8886        top-level qualifiers as required.  */
8887     type = TYPE_MAIN_VARIANT (type_decays_to (type));
8888
8889     /* We do not substitute into default arguments here.  The standard
8890        mandates that they be instantiated only when needed, which is
8891        done in build_over_call.  */
8892     default_arg = TREE_PURPOSE (arg_types);
8893
8894     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
8895       {
8896         /* We've instantiated a template before its default arguments
8897            have been parsed.  This can happen for a nested template
8898            class, and is not an error unless we require the default
8899            argument in a call of this function.  */
8900         remaining_arg_types = 
8901           tree_cons (default_arg, type, remaining_arg_types);
8902         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
8903                        remaining_arg_types);
8904       }
8905     else
8906       remaining_arg_types = 
8907         hash_tree_cons (default_arg, type, remaining_arg_types);
8908   }
8909         
8910   return remaining_arg_types;
8911 }
8912
8913 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
8914    *not* handle the exception-specification for FNTYPE, because the
8915    initial substitution of explicitly provided template parameters
8916    during argument deduction forbids substitution into the
8917    exception-specification:
8918
8919      [temp.deduct]
8920
8921      All references in the function type of the function template to  the
8922      corresponding template parameters are replaced by the specified tem-
8923      plate argument values.  If a substitution in a template parameter or
8924      in  the function type of the function template results in an invalid
8925      type, type deduction fails.  [Note: The equivalent  substitution  in
8926      exception specifications is done only when the function is instanti-
8927      ated, at which point a program is  ill-formed  if  the  substitution
8928      results in an invalid type.]  */
8929
8930 static tree
8931 tsubst_function_type (tree t,
8932                       tree args,
8933                       tsubst_flags_t complain,
8934                       tree in_decl)
8935 {
8936   tree return_type;
8937   tree arg_types;
8938   tree fntype;
8939
8940   /* The TYPE_CONTEXT is not used for function/method types.  */
8941   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
8942
8943   /* Substitute the return type.  */
8944   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8945   if (return_type == error_mark_node)
8946     return error_mark_node;
8947   /* The standard does not presently indicate that creation of a
8948      function type with an invalid return type is a deduction failure.
8949      However, that is clearly analogous to creating an array of "void"
8950      or a reference to a reference.  This is core issue #486.  */
8951   if (TREE_CODE (return_type) == ARRAY_TYPE
8952       || TREE_CODE (return_type) == FUNCTION_TYPE)
8953     {
8954       if (complain & tf_error)
8955         {
8956           if (TREE_CODE (return_type) == ARRAY_TYPE)
8957             error ("function returning an array");
8958           else
8959             error ("function returning a function");
8960         }
8961       return error_mark_node;
8962     }
8963
8964   /* Substitute the argument types.  */
8965   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
8966                                 complain, in_decl);
8967   if (arg_types == error_mark_node)
8968     return error_mark_node;
8969
8970   /* Construct a new type node and return it.  */
8971   if (TREE_CODE (t) == FUNCTION_TYPE)
8972     fntype = build_function_type (return_type, arg_types);
8973   else
8974     {
8975       tree r = TREE_TYPE (TREE_VALUE (arg_types));
8976       if (! MAYBE_CLASS_TYPE_P (r))
8977         {
8978           /* [temp.deduct]
8979
8980              Type deduction may fail for any of the following
8981              reasons:
8982
8983              -- Attempting to create "pointer to member of T" when T
8984              is not a class type.  */
8985           if (complain & tf_error)
8986             error ("creating pointer to member function of non-class type %qT",
8987                       r);
8988           return error_mark_node;
8989         }
8990
8991       fntype = build_method_type_directly (r, return_type,
8992                                            TREE_CHAIN (arg_types));
8993     }
8994   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
8995   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
8996
8997   return fntype;
8998 }
8999
9000 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9001    ARGS into that specification, and return the substituted
9002    specification.  If there is no specification, return NULL_TREE.  */
9003
9004 static tree
9005 tsubst_exception_specification (tree fntype,
9006                                 tree args,
9007                                 tsubst_flags_t complain,
9008                                 tree in_decl)
9009 {
9010   tree specs;
9011   tree new_specs;
9012
9013   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9014   new_specs = NULL_TREE;
9015   if (specs)
9016     {
9017       if (! TREE_VALUE (specs))
9018         new_specs = specs;
9019       else
9020         while (specs)
9021           {
9022             tree spec;
9023             int i, len = 1;
9024             tree expanded_specs = NULL_TREE;
9025
9026             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9027               {
9028                 /* Expand the pack expansion type.  */
9029                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9030                                                        args, complain,
9031                                                        in_decl);
9032
9033                 if (expanded_specs == error_mark_node)
9034                   return error_mark_node;
9035                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9036                   len = TREE_VEC_LENGTH (expanded_specs);
9037                 else
9038                   {
9039                     /* We're substituting into a member template, so
9040                        we got a TYPE_PACK_EXPANSION back.  Add that
9041                        expansion and move on.  */
9042                     gcc_assert (TREE_CODE (expanded_specs) 
9043                                 == TYPE_PACK_EXPANSION);
9044                     new_specs = add_exception_specifier (new_specs,
9045                                                          expanded_specs,
9046                                                          complain);
9047                     specs = TREE_CHAIN (specs);
9048                     continue;
9049                   }
9050               }
9051
9052             for (i = 0; i < len; ++i)
9053               {
9054                 if (expanded_specs)
9055                   spec = TREE_VEC_ELT (expanded_specs, i);
9056                 else
9057                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9058                 if (spec == error_mark_node)
9059                   return spec;
9060                 new_specs = add_exception_specifier (new_specs, spec, 
9061                                                      complain);
9062               }
9063
9064             specs = TREE_CHAIN (specs);
9065           }
9066     }
9067   return new_specs;
9068 }
9069
9070 /* Take the tree structure T and replace template parameters used
9071    therein with the argument vector ARGS.  IN_DECL is an associated
9072    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9073    Issue error and warning messages under control of COMPLAIN.  Note
9074    that we must be relatively non-tolerant of extensions here, in
9075    order to preserve conformance; if we allow substitutions that
9076    should not be allowed, we may allow argument deductions that should
9077    not succeed, and therefore report ambiguous overload situations
9078    where there are none.  In theory, we could allow the substitution,
9079    but indicate that it should have failed, and allow our caller to
9080    make sure that the right thing happens, but we don't try to do this
9081    yet.
9082
9083    This function is used for dealing with types, decls and the like;
9084    for expressions, use tsubst_expr or tsubst_copy.  */
9085
9086 tree
9087 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9088 {
9089   tree type, r;
9090
9091   if (t == NULL_TREE || t == error_mark_node
9092       || t == integer_type_node
9093       || t == void_type_node
9094       || t == char_type_node
9095       || t == unknown_type_node
9096       || TREE_CODE (t) == NAMESPACE_DECL)
9097     return t;
9098
9099   if (DECL_P (t))
9100     return tsubst_decl (t, args, complain);
9101
9102   if (args == NULL_TREE)
9103     return t;
9104
9105   if (TREE_CODE (t) == IDENTIFIER_NODE)
9106     type = IDENTIFIER_TYPE_VALUE (t);
9107   else
9108     type = TREE_TYPE (t);
9109
9110   gcc_assert (type != unknown_type_node);
9111
9112   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9113      such as attribute aligned.  */
9114   if (TYPE_P (t)
9115       && TYPE_NAME (t)
9116       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9117     {
9118       tree decl = TYPE_NAME (t);
9119       
9120       if (DECL_CLASS_SCOPE_P (decl)
9121           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9122           && uses_template_parms (DECL_CONTEXT (decl)))
9123         {
9124           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9125           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9126           r = retrieve_specialization (tmpl, gen_args, false);
9127         }
9128       else if (DECL_FUNCTION_SCOPE_P (decl)
9129                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9130                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9131         r = retrieve_local_specialization (decl);
9132       else
9133         /* The typedef is from a non-template context.  */
9134         return t;
9135
9136       if (r)
9137         {
9138           r = TREE_TYPE (r);
9139           r = cp_build_qualified_type_real
9140             (r, cp_type_quals (t) | cp_type_quals (r),
9141              complain | tf_ignore_bad_quals);
9142           return r;
9143         }
9144       /* Else we must be instantiating the typedef, so fall through.  */
9145     }
9146
9147   if (type
9148       && TREE_CODE (t) != TYPENAME_TYPE
9149       && TREE_CODE (t) != IDENTIFIER_NODE
9150       && TREE_CODE (t) != FUNCTION_TYPE
9151       && TREE_CODE (t) != METHOD_TYPE)
9152     type = tsubst (type, args, complain, in_decl);
9153   if (type == error_mark_node)
9154     return error_mark_node;
9155
9156   switch (TREE_CODE (t))
9157     {
9158     case RECORD_TYPE:
9159     case UNION_TYPE:
9160     case ENUMERAL_TYPE:
9161       return tsubst_aggr_type (t, args, complain, in_decl,
9162                                /*entering_scope=*/0);
9163
9164     case ERROR_MARK:
9165     case IDENTIFIER_NODE:
9166     case VOID_TYPE:
9167     case REAL_TYPE:
9168     case COMPLEX_TYPE:
9169     case VECTOR_TYPE:
9170     case BOOLEAN_TYPE:
9171     case INTEGER_CST:
9172     case REAL_CST:
9173     case STRING_CST:
9174       return t;
9175
9176     case INTEGER_TYPE:
9177       if (t == integer_type_node)
9178         return t;
9179
9180       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9181           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9182         return t;
9183
9184       {
9185         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9186
9187         max = tsubst_expr (omax, args, complain, in_decl,
9188                            /*integral_constant_expression_p=*/false);
9189
9190         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9191            needed.  */
9192         if (TREE_CODE (max) == NOP_EXPR
9193             && TREE_SIDE_EFFECTS (omax)
9194             && !TREE_TYPE (max))
9195           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9196
9197         max = fold_decl_constant_value (max);
9198
9199         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9200            with TREE_SIDE_EFFECTS that indicates this is not an integral
9201            constant expression.  */
9202         if (processing_template_decl
9203             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9204           {
9205             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9206             TREE_SIDE_EFFECTS (max) = 1;
9207           }
9208
9209         if (TREE_CODE (max) != INTEGER_CST
9210             && !at_function_scope_p ()
9211             && !TREE_SIDE_EFFECTS (max)
9212             && !value_dependent_expression_p (max))
9213           {
9214             if (complain & tf_error)
9215               error ("array bound is not an integer constant");
9216             return error_mark_node;
9217           }
9218
9219         /* [temp.deduct]
9220
9221            Type deduction may fail for any of the following
9222            reasons:
9223
9224              Attempting to create an array with a size that is
9225              zero or negative.  */
9226         if (integer_zerop (max) && !(complain & tf_error))
9227           /* We must fail if performing argument deduction (as
9228              indicated by the state of complain), so that
9229              another substitution can be found.  */
9230           return error_mark_node;
9231         else if (TREE_CODE (max) == INTEGER_CST
9232                  && INT_CST_LT (max, integer_zero_node))
9233           {
9234             if (complain & tf_error)
9235               error ("creating array with negative size (%qE)", max);
9236
9237             return error_mark_node;
9238           }
9239
9240         return compute_array_index_type (NULL_TREE, max);
9241       }
9242
9243     case TEMPLATE_TYPE_PARM:
9244     case TEMPLATE_TEMPLATE_PARM:
9245     case BOUND_TEMPLATE_TEMPLATE_PARM:
9246     case TEMPLATE_PARM_INDEX:
9247       {
9248         int idx;
9249         int level;
9250         int levels;
9251         tree arg = NULL_TREE;
9252
9253         r = NULL_TREE;
9254
9255         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9256         template_parm_level_and_index (t, &level, &idx); 
9257
9258         levels = TMPL_ARGS_DEPTH (args);
9259         if (level <= levels)
9260           {
9261             arg = TMPL_ARG (args, level, idx);
9262
9263             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9264               /* See through ARGUMENT_PACK_SELECT arguments. */
9265               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9266           }
9267
9268         if (arg == error_mark_node)
9269           return error_mark_node;
9270         else if (arg != NULL_TREE)
9271           {
9272             if (ARGUMENT_PACK_P (arg))
9273               /* If ARG is an argument pack, we don't actually want to
9274                  perform a substitution here, because substitutions
9275                  for argument packs are only done
9276                  element-by-element. We can get to this point when
9277                  substituting the type of a non-type template
9278                  parameter pack, when that type actually contains
9279                  template parameter packs from an outer template, e.g.,
9280
9281                  template<typename... Types> struct A {
9282                    template<Types... Values> struct B { };
9283                  };  */
9284               return t;
9285
9286             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9287               {
9288                 int quals;
9289                 gcc_assert (TYPE_P (arg));
9290
9291                 /* cv-quals from the template are discarded when
9292                    substituting in a function or reference type.  */
9293                 if (TREE_CODE (arg) == FUNCTION_TYPE
9294                     || TREE_CODE (arg) == METHOD_TYPE
9295                     || TREE_CODE (arg) == REFERENCE_TYPE)
9296                   quals = cp_type_quals (arg);
9297                 else
9298                   quals = cp_type_quals (arg) | cp_type_quals (t);
9299                   
9300                 return cp_build_qualified_type_real
9301                   (arg, quals, complain | tf_ignore_bad_quals);
9302               }
9303             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9304               {
9305                 /* We are processing a type constructed from a
9306                    template template parameter.  */
9307                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9308                                       args, complain, in_decl);
9309                 if (argvec == error_mark_node)
9310                   return error_mark_node;
9311
9312                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9313                    are resolving nested-types in the signature of a
9314                    member function templates.  Otherwise ARG is a
9315                    TEMPLATE_DECL and is the real template to be
9316                    instantiated.  */
9317                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9318                   arg = TYPE_NAME (arg);
9319
9320                 r = lookup_template_class (arg,
9321                                            argvec, in_decl,
9322                                            DECL_CONTEXT (arg),
9323                                             /*entering_scope=*/0,
9324                                            complain);
9325                 return cp_build_qualified_type_real
9326                   (r, TYPE_QUALS (t), complain);
9327               }
9328             else
9329               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9330               return arg;
9331           }
9332
9333         if (level == 1)
9334           /* This can happen during the attempted tsubst'ing in
9335              unify.  This means that we don't yet have any information
9336              about the template parameter in question.  */
9337           return t;
9338
9339         /* If we get here, we must have been looking at a parm for a
9340            more deeply nested template.  Make a new version of this
9341            template parameter, but with a lower level.  */
9342         switch (TREE_CODE (t))
9343           {
9344           case TEMPLATE_TYPE_PARM:
9345           case TEMPLATE_TEMPLATE_PARM:
9346           case BOUND_TEMPLATE_TEMPLATE_PARM:
9347             if (cp_type_quals (t))
9348               {
9349                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9350                 r = cp_build_qualified_type_real
9351                   (r, cp_type_quals (t),
9352                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9353                                ? tf_ignore_bad_quals : 0));
9354               }
9355             else
9356               {
9357                 r = copy_type (t);
9358                 TEMPLATE_TYPE_PARM_INDEX (r)
9359                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9360                                                 r, levels, args, complain);
9361                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9362                 TYPE_MAIN_VARIANT (r) = r;
9363                 TYPE_POINTER_TO (r) = NULL_TREE;
9364                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9365
9366                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9367                   /* We have reduced the level of the template
9368                      template parameter, but not the levels of its
9369                      template parameters, so canonical_type_parameter
9370                      will not be able to find the canonical template
9371                      template parameter for this level. Thus, we
9372                      require structural equality checking to compare
9373                      TEMPLATE_TEMPLATE_PARMs. */
9374                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9375                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9376                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9377                 else
9378                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9379
9380                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9381                   {
9382                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9383                                           complain, in_decl);
9384                     if (argvec == error_mark_node)
9385                       return error_mark_node;
9386
9387                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9388                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9389                   }
9390               }
9391             break;
9392
9393           case TEMPLATE_PARM_INDEX:
9394             r = reduce_template_parm_level (t, type, levels, args, complain);
9395             break;
9396
9397           default:
9398             gcc_unreachable ();
9399           }
9400
9401         return r;
9402       }
9403
9404     case TREE_LIST:
9405       {
9406         tree purpose, value, chain;
9407
9408         if (t == void_list_node)
9409           return t;
9410
9411         purpose = TREE_PURPOSE (t);
9412         if (purpose)
9413           {
9414             purpose = tsubst (purpose, args, complain, in_decl);
9415             if (purpose == error_mark_node)
9416               return error_mark_node;
9417           }
9418         value = TREE_VALUE (t);
9419         if (value)
9420           {
9421             value = tsubst (value, args, complain, in_decl);
9422             if (value == error_mark_node)
9423               return error_mark_node;
9424           }
9425         chain = TREE_CHAIN (t);
9426         if (chain && chain != void_type_node)
9427           {
9428             chain = tsubst (chain, args, complain, in_decl);
9429             if (chain == error_mark_node)
9430               return error_mark_node;
9431           }
9432         if (purpose == TREE_PURPOSE (t)
9433             && value == TREE_VALUE (t)
9434             && chain == TREE_CHAIN (t))
9435           return t;
9436         return hash_tree_cons (purpose, value, chain);
9437       }
9438
9439     case TREE_BINFO:
9440       /* We should never be tsubsting a binfo.  */
9441       gcc_unreachable ();
9442
9443     case TREE_VEC:
9444       /* A vector of template arguments.  */
9445       gcc_assert (!type);
9446       return tsubst_template_args (t, args, complain, in_decl);
9447
9448     case POINTER_TYPE:
9449     case REFERENCE_TYPE:
9450       {
9451         enum tree_code code;
9452
9453         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9454           return t;
9455
9456         code = TREE_CODE (t);
9457
9458
9459         /* [temp.deduct]
9460
9461            Type deduction may fail for any of the following
9462            reasons:
9463
9464            -- Attempting to create a pointer to reference type.
9465            -- Attempting to create a reference to a reference type or
9466               a reference to void.
9467
9468           Core issue 106 says that creating a reference to a reference
9469           during instantiation is no longer a cause for failure. We
9470           only enforce this check in strict C++98 mode.  */
9471         if ((TREE_CODE (type) == REFERENCE_TYPE
9472              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9473             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9474           {
9475             static location_t last_loc;
9476
9477             /* We keep track of the last time we issued this error
9478                message to avoid spewing a ton of messages during a
9479                single bad template instantiation.  */
9480             if (complain & tf_error
9481                 && last_loc != input_location)
9482               {
9483                 if (TREE_CODE (type) == VOID_TYPE)
9484                   error ("forming reference to void");
9485                 else
9486                   error ("forming %s to reference type %qT",
9487                          (code == POINTER_TYPE) ? "pointer" : "reference",
9488                          type);
9489                 last_loc = input_location;
9490               }
9491
9492             return error_mark_node;
9493           }
9494         else if (code == POINTER_TYPE)
9495           {
9496             r = build_pointer_type (type);
9497             if (TREE_CODE (type) == METHOD_TYPE)
9498               r = build_ptrmemfunc_type (r);
9499           }
9500         else if (TREE_CODE (type) == REFERENCE_TYPE)
9501           /* In C++0x, during template argument substitution, when there is an
9502              attempt to create a reference to a reference type, reference
9503              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9504
9505              "If a template-argument for a template-parameter T names a type
9506              that is a reference to a type A, an attempt to create the type
9507              'lvalue reference to cv T' creates the type 'lvalue reference to
9508              A,' while an attempt to create the type type rvalue reference to
9509              cv T' creates the type T"
9510           */
9511           r = cp_build_reference_type
9512               (TREE_TYPE (type),
9513                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9514         else
9515           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9516         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9517
9518         if (r != error_mark_node)
9519           /* Will this ever be needed for TYPE_..._TO values?  */
9520           layout_type (r);
9521
9522         return r;
9523       }
9524     case OFFSET_TYPE:
9525       {
9526         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9527         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
9528           {
9529             /* [temp.deduct]
9530
9531                Type deduction may fail for any of the following
9532                reasons:
9533
9534                -- Attempting to create "pointer to member of T" when T
9535                   is not a class type.  */
9536             if (complain & tf_error)
9537               error ("creating pointer to member of non-class type %qT", r);
9538             return error_mark_node;
9539           }
9540         if (TREE_CODE (type) == REFERENCE_TYPE)
9541           {
9542             if (complain & tf_error)
9543               error ("creating pointer to member reference type %qT", type);
9544             return error_mark_node;
9545           }
9546         if (TREE_CODE (type) == VOID_TYPE)
9547           {
9548             if (complain & tf_error)
9549               error ("creating pointer to member of type void");
9550             return error_mark_node;
9551           }
9552         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
9553         if (TREE_CODE (type) == FUNCTION_TYPE)
9554           {
9555             /* The type of the implicit object parameter gets its
9556                cv-qualifiers from the FUNCTION_TYPE. */
9557             tree method_type;
9558             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
9559                                                       cp_type_quals (type));
9560             tree memptr;
9561             method_type = build_method_type_directly (this_type,
9562                                                       TREE_TYPE (type),
9563                                                       TYPE_ARG_TYPES (type));
9564             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
9565             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
9566                                                  complain);
9567           }
9568         else
9569           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
9570                                                TYPE_QUALS (t),
9571                                                complain);
9572       }
9573     case FUNCTION_TYPE:
9574     case METHOD_TYPE:
9575       {
9576         tree fntype;
9577         tree specs;
9578         fntype = tsubst_function_type (t, args, complain, in_decl);
9579         if (fntype == error_mark_node)
9580           return error_mark_node;
9581
9582         /* Substitute the exception specification.  */
9583         specs = tsubst_exception_specification (t, args, complain,
9584                                                 in_decl);
9585         if (specs == error_mark_node)
9586           return error_mark_node;
9587         if (specs)
9588           fntype = build_exception_variant (fntype, specs);
9589         return fntype;
9590       }
9591     case ARRAY_TYPE:
9592       {
9593         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
9594         if (domain == error_mark_node)
9595           return error_mark_node;
9596
9597         /* As an optimization, we avoid regenerating the array type if
9598            it will obviously be the same as T.  */
9599         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
9600           return t;
9601
9602         /* These checks should match the ones in grokdeclarator.
9603
9604            [temp.deduct]
9605
9606            The deduction may fail for any of the following reasons:
9607
9608            -- Attempting to create an array with an element type that
9609               is void, a function type, or a reference type, or [DR337]
9610               an abstract class type.  */
9611         if (TREE_CODE (type) == VOID_TYPE
9612             || TREE_CODE (type) == FUNCTION_TYPE
9613             || TREE_CODE (type) == REFERENCE_TYPE)
9614           {
9615             if (complain & tf_error)
9616               error ("creating array of %qT", type);
9617             return error_mark_node;
9618           }
9619         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
9620           {
9621             if (complain & tf_error)
9622               error ("creating array of %qT, which is an abstract class type",
9623                      type);
9624             return error_mark_node;
9625           }
9626
9627         r = build_cplus_array_type (type, domain);
9628
9629         if (TYPE_USER_ALIGN (t))
9630           {
9631             TYPE_ALIGN (r) = TYPE_ALIGN (t);
9632             TYPE_USER_ALIGN (r) = 1;
9633           }
9634
9635         return r;
9636       }
9637
9638     case PLUS_EXPR:
9639     case MINUS_EXPR:
9640       {
9641         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9642         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9643
9644         if (e1 == error_mark_node || e2 == error_mark_node)
9645           return error_mark_node;
9646
9647         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
9648       }
9649
9650     case NEGATE_EXPR:
9651     case NOP_EXPR:
9652       {
9653         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9654         if (e == error_mark_node)
9655           return error_mark_node;
9656
9657         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
9658       }
9659
9660     case TYPENAME_TYPE:
9661       {
9662         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9663                                      in_decl, /*entering_scope=*/1);
9664         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
9665                               complain, in_decl);
9666
9667         if (ctx == error_mark_node || f == error_mark_node)
9668           return error_mark_node;
9669
9670         if (!MAYBE_CLASS_TYPE_P (ctx))
9671           {
9672             if (complain & tf_error)
9673               error ("%qT is not a class, struct, or union type", ctx);
9674             return error_mark_node;
9675           }
9676         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
9677           {
9678             /* Normally, make_typename_type does not require that the CTX
9679                have complete type in order to allow things like:
9680
9681                  template <class T> struct S { typename S<T>::X Y; };
9682
9683                But, such constructs have already been resolved by this
9684                point, so here CTX really should have complete type, unless
9685                it's a partial instantiation.  */
9686             ctx = complete_type (ctx);
9687             if (!COMPLETE_TYPE_P (ctx))
9688               {
9689                 if (complain & tf_error)
9690                   cxx_incomplete_type_error (NULL_TREE, ctx);
9691                 return error_mark_node;
9692               }
9693           }
9694
9695         f = make_typename_type (ctx, f, typename_type,
9696                                 (complain & tf_error) | tf_keep_type_decl);
9697         if (f == error_mark_node)
9698           return f;
9699         if (TREE_CODE (f) == TYPE_DECL)
9700           {
9701             complain |= tf_ignore_bad_quals;
9702             f = TREE_TYPE (f);
9703           }
9704
9705         if (TREE_CODE (f) != TYPENAME_TYPE)
9706           {
9707             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
9708               error ("%qT resolves to %qT, which is not an enumeration type",
9709                      t, f);
9710             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
9711               error ("%qT resolves to %qT, which is is not a class type",
9712                      t, f);
9713           }
9714
9715         return cp_build_qualified_type_real
9716           (f, cp_type_quals (f) | cp_type_quals (t), complain);
9717       }
9718
9719     case UNBOUND_CLASS_TEMPLATE:
9720       {
9721         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9722                                      in_decl, /*entering_scope=*/1);
9723         tree name = TYPE_IDENTIFIER (t);
9724         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
9725
9726         if (ctx == error_mark_node || name == error_mark_node)
9727           return error_mark_node;
9728
9729         if (parm_list)
9730           parm_list = tsubst_template_parms (parm_list, args, complain);
9731         return make_unbound_class_template (ctx, name, parm_list, complain);
9732       }
9733
9734     case INDIRECT_REF:
9735     case ADDR_EXPR:
9736     case CALL_EXPR:
9737       gcc_unreachable ();
9738
9739     case ARRAY_REF:
9740       {
9741         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9742         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
9743                                /*integral_constant_expression_p=*/false);
9744         if (e1 == error_mark_node || e2 == error_mark_node)
9745           return error_mark_node;
9746
9747         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
9748       }
9749
9750     case SCOPE_REF:
9751       {
9752         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9753         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9754         if (e1 == error_mark_node || e2 == error_mark_node)
9755           return error_mark_node;
9756
9757         return build_qualified_name (/*type=*/NULL_TREE,
9758                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
9759       }
9760
9761     case TYPEOF_TYPE:
9762       {
9763         tree type;
9764
9765         type = finish_typeof (tsubst_expr 
9766                               (TYPEOF_TYPE_EXPR (t), args,
9767                                complain, in_decl,
9768                                /*integral_constant_expression_p=*/false));
9769         return cp_build_qualified_type_real (type,
9770                                              cp_type_quals (t)
9771                                              | cp_type_quals (type),
9772                                              complain);
9773       }
9774
9775     case DECLTYPE_TYPE:
9776       {
9777         tree type;
9778
9779         ++skip_evaluation;
9780
9781         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
9782                             complain, in_decl,
9783                             /*integral_constant_expression_p=*/false);
9784
9785         --skip_evaluation;
9786
9787         type =
9788           finish_decltype_type (type,
9789                                 DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
9790         return cp_build_qualified_type_real (type,
9791                                              cp_type_quals (t)
9792                                              | cp_type_quals (type),
9793                                              complain);
9794       }
9795
9796     case TYPE_ARGUMENT_PACK:
9797     case NONTYPE_ARGUMENT_PACK:
9798       {
9799         tree r = make_node (TREE_CODE (t));
9800         tree packed_out = 
9801           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
9802                                 args,
9803                                 complain,
9804                                 in_decl);
9805         SET_ARGUMENT_PACK_ARGS (r, packed_out);
9806
9807         /* For template nontype argument packs, also substitute into
9808            the type.  */
9809         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
9810           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
9811
9812         return r;
9813       }
9814       break;
9815
9816     default:
9817       sorry ("use of %qs in template",
9818              tree_code_name [(int) TREE_CODE (t)]);
9819       return error_mark_node;
9820     }
9821 }
9822
9823 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
9824    type of the expression on the left-hand side of the "." or "->"
9825    operator.  */
9826
9827 static tree
9828 tsubst_baselink (tree baselink, tree object_type,
9829                  tree args, tsubst_flags_t complain, tree in_decl)
9830 {
9831     tree name;
9832     tree qualifying_scope;
9833     tree fns;
9834     tree optype;
9835     tree template_args = 0;
9836     bool template_id_p = false;
9837
9838     /* A baselink indicates a function from a base class.  Both the
9839        BASELINK_ACCESS_BINFO and the base class referenced may
9840        indicate bases of the template class, rather than the
9841        instantiated class.  In addition, lookups that were not
9842        ambiguous before may be ambiguous now.  Therefore, we perform
9843        the lookup again.  */
9844     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
9845     qualifying_scope = tsubst (qualifying_scope, args,
9846                                complain, in_decl);
9847     fns = BASELINK_FUNCTIONS (baselink);
9848     optype = BASELINK_OPTYPE (baselink);
9849     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
9850       {
9851         template_id_p = true;
9852         template_args = TREE_OPERAND (fns, 1);
9853         fns = TREE_OPERAND (fns, 0);
9854         if (template_args)
9855           template_args = tsubst_template_args (template_args, args,
9856                                                 complain, in_decl);
9857       }
9858     name = DECL_NAME (get_first_fn (fns));
9859     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
9860
9861     /* If lookup found a single function, mark it as used at this
9862        point.  (If it lookup found multiple functions the one selected
9863        later by overload resolution will be marked as used at that
9864        point.)  */
9865     if (BASELINK_P (baselink))
9866       fns = BASELINK_FUNCTIONS (baselink);
9867     if (!template_id_p && !really_overloaded_fn (fns))
9868       mark_used (OVL_CURRENT (fns));
9869
9870     /* Add back the template arguments, if present.  */
9871     if (BASELINK_P (baselink) && template_id_p)
9872       BASELINK_FUNCTIONS (baselink)
9873         = build_nt (TEMPLATE_ID_EXPR,
9874                     BASELINK_FUNCTIONS (baselink),
9875                     template_args);
9876     /* Update the conversion operator type.  */
9877     BASELINK_OPTYPE (baselink) 
9878       = tsubst (optype, args, complain, in_decl);
9879
9880     if (!object_type)
9881       object_type = current_class_type;
9882     return adjust_result_of_qualified_name_lookup (baselink,
9883                                                    qualifying_scope,
9884                                                    object_type);
9885 }
9886
9887 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
9888    true if the qualified-id will be a postfix-expression in-and-of
9889    itself; false if more of the postfix-expression follows the
9890    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
9891    of "&".  */
9892
9893 static tree
9894 tsubst_qualified_id (tree qualified_id, tree args,
9895                      tsubst_flags_t complain, tree in_decl,
9896                      bool done, bool address_p)
9897 {
9898   tree expr;
9899   tree scope;
9900   tree name;
9901   bool is_template;
9902   tree template_args;
9903
9904   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
9905
9906   /* Figure out what name to look up.  */
9907   name = TREE_OPERAND (qualified_id, 1);
9908   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
9909     {
9910       is_template = true;
9911       template_args = TREE_OPERAND (name, 1);
9912       if (template_args)
9913         template_args = tsubst_template_args (template_args, args,
9914                                               complain, in_decl);
9915       name = TREE_OPERAND (name, 0);
9916     }
9917   else
9918     {
9919       is_template = false;
9920       template_args = NULL_TREE;
9921     }
9922
9923   /* Substitute into the qualifying scope.  When there are no ARGS, we
9924      are just trying to simplify a non-dependent expression.  In that
9925      case the qualifying scope may be dependent, and, in any case,
9926      substituting will not help.  */
9927   scope = TREE_OPERAND (qualified_id, 0);
9928   if (args)
9929     {
9930       scope = tsubst (scope, args, complain, in_decl);
9931       expr = tsubst_copy (name, args, complain, in_decl);
9932     }
9933   else
9934     expr = name;
9935
9936   if (dependent_type_p (scope))
9937     {
9938       tree type = NULL_TREE;
9939       if (DECL_P (expr) && !dependent_scope_p (scope))
9940         type = TREE_TYPE (expr);
9941       return build_qualified_name (type, scope, expr,
9942                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
9943     }
9944
9945   if (!BASELINK_P (name) && !DECL_P (expr))
9946     {
9947       if (TREE_CODE (expr) == BIT_NOT_EXPR)
9948         {
9949           /* A BIT_NOT_EXPR is used to represent a destructor.  */
9950           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
9951             {
9952               error ("qualifying type %qT does not match destructor name ~%qT",
9953                      scope, TREE_OPERAND (expr, 0));
9954               expr = error_mark_node;
9955             }
9956           else
9957             expr = lookup_qualified_name (scope, complete_dtor_identifier,
9958                                           /*is_type_p=*/0, false);
9959         }
9960       else
9961         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
9962       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
9963                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
9964         {
9965           if (complain & tf_error)
9966             {
9967               error ("dependent-name %qE is parsed as a non-type, but "
9968                      "instantiation yields a type", qualified_id);
9969               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
9970             }
9971           return error_mark_node;
9972         }
9973     }
9974
9975   if (DECL_P (expr))
9976     {
9977       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
9978                                            scope);
9979       /* Remember that there was a reference to this entity.  */
9980       mark_used (expr);
9981     }
9982
9983   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
9984     {
9985       if (complain & tf_error)
9986         qualified_name_lookup_error (scope,
9987                                      TREE_OPERAND (qualified_id, 1),
9988                                      expr, input_location);
9989       return error_mark_node;
9990     }
9991
9992   if (is_template)
9993     expr = lookup_template_function (expr, template_args);
9994
9995   if (expr == error_mark_node && complain & tf_error)
9996     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
9997                                  expr, input_location);
9998   else if (TYPE_P (scope))
9999     {
10000       expr = (adjust_result_of_qualified_name_lookup
10001               (expr, scope, current_class_type));
10002       expr = (finish_qualified_id_expr
10003               (scope, expr, done, address_p,
10004                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10005                /*template_arg_p=*/false));
10006     }
10007
10008   /* Expressions do not generally have reference type.  */
10009   if (TREE_CODE (expr) != SCOPE_REF
10010       /* However, if we're about to form a pointer-to-member, we just
10011          want the referenced member referenced.  */
10012       && TREE_CODE (expr) != OFFSET_REF)
10013     expr = convert_from_reference (expr);
10014
10015   return expr;
10016 }
10017
10018 /* Like tsubst, but deals with expressions.  This function just replaces
10019    template parms; to finish processing the resultant expression, use
10020    tsubst_expr.  */
10021
10022 static tree
10023 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10024 {
10025   enum tree_code code;
10026   tree r;
10027
10028   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10029     return t;
10030
10031   code = TREE_CODE (t);
10032
10033   switch (code)
10034     {
10035     case PARM_DECL:
10036       r = retrieve_local_specialization (t);
10037
10038       if (r == NULL)
10039         {
10040           tree c;
10041           /* This can happen for a parameter name used later in a function
10042              declaration (such as in a late-specified return type).  Just
10043              make a dummy decl, since it's only used for its type.  */
10044           gcc_assert (skip_evaluation);   
10045           /* We copy T because want to tsubst the PARM_DECL only,
10046              not the following PARM_DECLs that are chained to T.  */
10047           c = copy_node (t);
10048           r = tsubst_decl (c, args, complain);
10049           /* Give it the template pattern as its context; its true context
10050              hasn't been instantiated yet and this is good enough for
10051              mangling.  */
10052           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10053         }
10054       
10055       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10056         r = ARGUMENT_PACK_SELECT_ARG (r);
10057       mark_used (r);
10058       return r;
10059
10060     case CONST_DECL:
10061       {
10062         tree enum_type;
10063         tree v;
10064
10065         if (DECL_TEMPLATE_PARM_P (t))
10066           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10067         /* There is no need to substitute into namespace-scope
10068            enumerators.  */
10069         if (DECL_NAMESPACE_SCOPE_P (t))
10070           return t;
10071         /* If ARGS is NULL, then T is known to be non-dependent.  */
10072         if (args == NULL_TREE)
10073           return integral_constant_value (t);
10074
10075         /* Unfortunately, we cannot just call lookup_name here.
10076            Consider:
10077
10078              template <int I> int f() {
10079              enum E { a = I };
10080              struct S { void g() { E e = a; } };
10081              };
10082
10083            When we instantiate f<7>::S::g(), say, lookup_name is not
10084            clever enough to find f<7>::a.  */
10085         enum_type
10086           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10087                               /*entering_scope=*/0);
10088
10089         for (v = TYPE_VALUES (enum_type);
10090              v != NULL_TREE;
10091              v = TREE_CHAIN (v))
10092           if (TREE_PURPOSE (v) == DECL_NAME (t))
10093             return TREE_VALUE (v);
10094
10095           /* We didn't find the name.  That should never happen; if
10096              name-lookup found it during preliminary parsing, we
10097              should find it again here during instantiation.  */
10098         gcc_unreachable ();
10099       }
10100       return t;
10101
10102     case FIELD_DECL:
10103       if (DECL_CONTEXT (t))
10104         {
10105           tree ctx;
10106
10107           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10108                                   /*entering_scope=*/1);
10109           if (ctx != DECL_CONTEXT (t))
10110             {
10111               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10112               if (!r)
10113                 {
10114                   if (complain & tf_error)
10115                     error ("using invalid field %qD", t);
10116                   return error_mark_node;
10117                 }
10118               return r;
10119             }
10120         }
10121
10122       return t;
10123
10124     case VAR_DECL:
10125     case FUNCTION_DECL:
10126       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10127           || local_variable_p (t))
10128         t = tsubst (t, args, complain, in_decl);
10129       mark_used (t);
10130       return t;
10131
10132     case BASELINK:
10133       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10134
10135     case TEMPLATE_DECL:
10136       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10137         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10138                        args, complain, in_decl);
10139       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10140         return tsubst (t, args, complain, in_decl);
10141       else if (DECL_CLASS_SCOPE_P (t)
10142                && uses_template_parms (DECL_CONTEXT (t)))
10143         {
10144           /* Template template argument like the following example need
10145              special treatment:
10146
10147                template <template <class> class TT> struct C {};
10148                template <class T> struct D {
10149                  template <class U> struct E {};
10150                  C<E> c;                                // #1
10151                };
10152                D<int> d;                                // #2
10153
10154              We are processing the template argument `E' in #1 for
10155              the template instantiation #2.  Originally, `E' is a
10156              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10157              have to substitute this with one having context `D<int>'.  */
10158
10159           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10160           return lookup_field (context, DECL_NAME(t), 0, false);
10161         }
10162       else
10163         /* Ordinary template template argument.  */
10164         return t;
10165
10166     case CAST_EXPR:
10167     case REINTERPRET_CAST_EXPR:
10168     case CONST_CAST_EXPR:
10169     case STATIC_CAST_EXPR:
10170     case DYNAMIC_CAST_EXPR:
10171     case NOP_EXPR:
10172       return build1
10173         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10174          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10175
10176     case SIZEOF_EXPR:
10177       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10178         {
10179           /* We only want to compute the number of arguments.  */
10180           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10181                                                 complain, in_decl);
10182           int len = 0;
10183
10184           if (TREE_CODE (expanded) == TREE_VEC)
10185             len = TREE_VEC_LENGTH (expanded);
10186
10187           if (expanded == error_mark_node)
10188             return error_mark_node;
10189           else if (PACK_EXPANSION_P (expanded)
10190                    || (TREE_CODE (expanded) == TREE_VEC
10191                        && len > 0
10192                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10193             {
10194               if (TREE_CODE (expanded) == TREE_VEC)
10195                 expanded = TREE_VEC_ELT (expanded, len - 1);
10196
10197               if (TYPE_P (expanded))
10198                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10199                                                    complain & tf_error);
10200               else
10201                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10202                                                    complain & tf_error);
10203             }
10204           else
10205             return build_int_cst (size_type_node, len);
10206         }
10207       /* Fall through */
10208
10209     case INDIRECT_REF:
10210     case NEGATE_EXPR:
10211     case TRUTH_NOT_EXPR:
10212     case BIT_NOT_EXPR:
10213     case ADDR_EXPR:
10214     case UNARY_PLUS_EXPR:      /* Unary + */
10215     case ALIGNOF_EXPR:
10216     case ARROW_EXPR:
10217     case THROW_EXPR:
10218     case TYPEID_EXPR:
10219     case REALPART_EXPR:
10220     case IMAGPART_EXPR:
10221       return build1
10222         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10223          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10224
10225     case COMPONENT_REF:
10226       {
10227         tree object;
10228         tree name;
10229
10230         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10231         name = TREE_OPERAND (t, 1);
10232         if (TREE_CODE (name) == BIT_NOT_EXPR)
10233           {
10234             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10235                                 complain, in_decl);
10236             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10237           }
10238         else if (TREE_CODE (name) == SCOPE_REF
10239                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10240           {
10241             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10242                                      complain, in_decl);
10243             name = TREE_OPERAND (name, 1);
10244             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10245                                 complain, in_decl);
10246             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10247             name = build_qualified_name (/*type=*/NULL_TREE,
10248                                          base, name,
10249                                          /*template_p=*/false);
10250           }
10251         else if (TREE_CODE (name) == BASELINK)
10252           name = tsubst_baselink (name,
10253                                   non_reference (TREE_TYPE (object)),
10254                                   args, complain,
10255                                   in_decl);
10256         else
10257           name = tsubst_copy (name, args, complain, in_decl);
10258         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10259       }
10260
10261     case PLUS_EXPR:
10262     case MINUS_EXPR:
10263     case MULT_EXPR:
10264     case TRUNC_DIV_EXPR:
10265     case CEIL_DIV_EXPR:
10266     case FLOOR_DIV_EXPR:
10267     case ROUND_DIV_EXPR:
10268     case EXACT_DIV_EXPR:
10269     case BIT_AND_EXPR:
10270     case BIT_IOR_EXPR:
10271     case BIT_XOR_EXPR:
10272     case TRUNC_MOD_EXPR:
10273     case FLOOR_MOD_EXPR:
10274     case TRUTH_ANDIF_EXPR:
10275     case TRUTH_ORIF_EXPR:
10276     case TRUTH_AND_EXPR:
10277     case TRUTH_OR_EXPR:
10278     case RSHIFT_EXPR:
10279     case LSHIFT_EXPR:
10280     case RROTATE_EXPR:
10281     case LROTATE_EXPR:
10282     case EQ_EXPR:
10283     case NE_EXPR:
10284     case MAX_EXPR:
10285     case MIN_EXPR:
10286     case LE_EXPR:
10287     case GE_EXPR:
10288     case LT_EXPR:
10289     case GT_EXPR:
10290     case COMPOUND_EXPR:
10291     case DOTSTAR_EXPR:
10292     case MEMBER_REF:
10293     case PREDECREMENT_EXPR:
10294     case PREINCREMENT_EXPR:
10295     case POSTDECREMENT_EXPR:
10296     case POSTINCREMENT_EXPR:
10297       return build_nt
10298         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10299          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10300
10301     case SCOPE_REF:
10302       return build_qualified_name (/*type=*/NULL_TREE,
10303                                    tsubst_copy (TREE_OPERAND (t, 0),
10304                                                 args, complain, in_decl),
10305                                    tsubst_copy (TREE_OPERAND (t, 1),
10306                                                 args, complain, in_decl),
10307                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10308
10309     case ARRAY_REF:
10310       return build_nt
10311         (ARRAY_REF,
10312          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10313          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10314          NULL_TREE, NULL_TREE);
10315
10316     case CALL_EXPR:
10317       {
10318         int n = VL_EXP_OPERAND_LENGTH (t);
10319         tree result = build_vl_exp (CALL_EXPR, n);
10320         int i;
10321         for (i = 0; i < n; i++)
10322           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10323                                              complain, in_decl);
10324         return result;
10325       }
10326
10327     case COND_EXPR:
10328     case MODOP_EXPR:
10329     case PSEUDO_DTOR_EXPR:
10330       {
10331         r = build_nt
10332           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10333            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10334            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10335         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10336         return r;
10337       }
10338
10339     case NEW_EXPR:
10340       {
10341         r = build_nt
10342         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10343          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10344          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10345         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10346         return r;
10347       }
10348
10349     case DELETE_EXPR:
10350       {
10351         r = build_nt
10352         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10353          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10354         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10355         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10356         return r;
10357       }
10358
10359     case TEMPLATE_ID_EXPR:
10360       {
10361         /* Substituted template arguments */
10362         tree fn = TREE_OPERAND (t, 0);
10363         tree targs = TREE_OPERAND (t, 1);
10364
10365         fn = tsubst_copy (fn, args, complain, in_decl);
10366         if (targs)
10367           targs = tsubst_template_args (targs, args, complain, in_decl);
10368
10369         return lookup_template_function (fn, targs);
10370       }
10371
10372     case TREE_LIST:
10373       {
10374         tree purpose, value, chain;
10375
10376         if (t == void_list_node)
10377           return t;
10378
10379         purpose = TREE_PURPOSE (t);
10380         if (purpose)
10381           purpose = tsubst_copy (purpose, args, complain, in_decl);
10382         value = TREE_VALUE (t);
10383         if (value)
10384           value = tsubst_copy (value, args, complain, in_decl);
10385         chain = TREE_CHAIN (t);
10386         if (chain && chain != void_type_node)
10387           chain = tsubst_copy (chain, args, complain, in_decl);
10388         if (purpose == TREE_PURPOSE (t)
10389             && value == TREE_VALUE (t)
10390             && chain == TREE_CHAIN (t))
10391           return t;
10392         return tree_cons (purpose, value, chain);
10393       }
10394
10395     case RECORD_TYPE:
10396     case UNION_TYPE:
10397     case ENUMERAL_TYPE:
10398     case INTEGER_TYPE:
10399     case TEMPLATE_TYPE_PARM:
10400     case TEMPLATE_TEMPLATE_PARM:
10401     case BOUND_TEMPLATE_TEMPLATE_PARM:
10402     case TEMPLATE_PARM_INDEX:
10403     case POINTER_TYPE:
10404     case REFERENCE_TYPE:
10405     case OFFSET_TYPE:
10406     case FUNCTION_TYPE:
10407     case METHOD_TYPE:
10408     case ARRAY_TYPE:
10409     case TYPENAME_TYPE:
10410     case UNBOUND_CLASS_TEMPLATE:
10411     case TYPEOF_TYPE:
10412     case DECLTYPE_TYPE:
10413     case TYPE_DECL:
10414       return tsubst (t, args, complain, in_decl);
10415
10416     case IDENTIFIER_NODE:
10417       if (IDENTIFIER_TYPENAME_P (t))
10418         {
10419           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10420           return mangle_conv_op_name_for_type (new_type);
10421         }
10422       else
10423         return t;
10424
10425     case CONSTRUCTOR:
10426       /* This is handled by tsubst_copy_and_build.  */
10427       gcc_unreachable ();
10428
10429     case VA_ARG_EXPR:
10430       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10431                                           in_decl),
10432                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10433
10434     case CLEANUP_POINT_EXPR:
10435       /* We shouldn't have built any of these during initial template
10436          generation.  Instead, they should be built during instantiation
10437          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10438       gcc_unreachable ();
10439
10440     case OFFSET_REF:
10441       mark_used (TREE_OPERAND (t, 1));
10442       return t;
10443
10444     case EXPR_PACK_EXPANSION:
10445       error ("invalid use of pack expansion expression");
10446       return error_mark_node;
10447
10448     case NONTYPE_ARGUMENT_PACK:
10449       error ("use %<...%> to expand argument pack");
10450       return error_mark_node;
10451
10452     default:
10453       return t;
10454     }
10455 }
10456
10457 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10458
10459 static tree
10460 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10461                     tree in_decl)
10462 {
10463   tree new_clauses = NULL, nc, oc;
10464
10465   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10466     {
10467       nc = copy_node (oc);
10468       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10469       new_clauses = nc;
10470
10471       switch (OMP_CLAUSE_CODE (nc))
10472         {
10473         case OMP_CLAUSE_LASTPRIVATE:
10474           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
10475             {
10476               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
10477               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
10478                            in_decl, /*integral_constant_expression_p=*/false);
10479               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
10480                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
10481             }
10482           /* FALLTHRU */
10483         case OMP_CLAUSE_PRIVATE:
10484         case OMP_CLAUSE_SHARED:
10485         case OMP_CLAUSE_FIRSTPRIVATE:
10486         case OMP_CLAUSE_REDUCTION:
10487         case OMP_CLAUSE_COPYIN:
10488         case OMP_CLAUSE_COPYPRIVATE:
10489         case OMP_CLAUSE_IF:
10490         case OMP_CLAUSE_NUM_THREADS:
10491         case OMP_CLAUSE_SCHEDULE:
10492         case OMP_CLAUSE_COLLAPSE:
10493           OMP_CLAUSE_OPERAND (nc, 0)
10494             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10495                            in_decl, /*integral_constant_expression_p=*/false);
10496           break;
10497         case OMP_CLAUSE_NOWAIT:
10498         case OMP_CLAUSE_ORDERED:
10499         case OMP_CLAUSE_DEFAULT:
10500         case OMP_CLAUSE_UNTIED:
10501           break;
10502         default:
10503           gcc_unreachable ();
10504         }
10505     }
10506
10507   return finish_omp_clauses (nreverse (new_clauses));
10508 }
10509
10510 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10511
10512 static tree
10513 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10514                           tree in_decl)
10515 {
10516 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10517
10518   tree purpose, value, chain;
10519
10520   if (t == NULL)
10521     return t;
10522
10523   if (TREE_CODE (t) != TREE_LIST)
10524     return tsubst_copy_and_build (t, args, complain, in_decl,
10525                                   /*function_p=*/false,
10526                                   /*integral_constant_expression_p=*/false);
10527
10528   if (t == void_list_node)
10529     return t;
10530
10531   purpose = TREE_PURPOSE (t);
10532   if (purpose)
10533     purpose = RECUR (purpose);
10534   value = TREE_VALUE (t);
10535   if (value)
10536     value = RECUR (value);
10537   chain = TREE_CHAIN (t);
10538   if (chain && chain != void_type_node)
10539     chain = RECUR (chain);
10540   return tree_cons (purpose, value, chain);
10541 #undef RECUR
10542 }
10543
10544 /* Substitute one OMP_FOR iterator.  */
10545
10546 static void
10547 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
10548                          tree condv, tree incrv, tree *clauses,
10549                          tree args, tsubst_flags_t complain, tree in_decl,
10550                          bool integral_constant_expression_p)
10551 {
10552 #define RECUR(NODE)                             \
10553   tsubst_expr ((NODE), args, complain, in_decl, \
10554                integral_constant_expression_p)
10555   tree decl, init, cond, incr, auto_node;
10556
10557   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
10558   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10559   decl = RECUR (TREE_OPERAND (init, 0));
10560   init = TREE_OPERAND (init, 1);
10561   auto_node = type_uses_auto (TREE_TYPE (decl));
10562   if (auto_node && init)
10563     {
10564       tree init_expr = init;
10565       if (TREE_CODE (init_expr) == DECL_EXPR)
10566         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
10567       init_expr = RECUR (init_expr);
10568       TREE_TYPE (decl)
10569         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
10570     }
10571   gcc_assert (!type_dependent_expression_p (decl));
10572
10573   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
10574     {
10575       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
10576       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10577       if (TREE_CODE (incr) == MODIFY_EXPR)
10578         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
10579                                     RECUR (TREE_OPERAND (incr, 1)),
10580                                     complain);
10581       else
10582         incr = RECUR (incr);
10583       TREE_VEC_ELT (declv, i) = decl;
10584       TREE_VEC_ELT (initv, i) = init;
10585       TREE_VEC_ELT (condv, i) = cond;
10586       TREE_VEC_ELT (incrv, i) = incr;
10587       return;
10588     }
10589
10590   if (init && TREE_CODE (init) != DECL_EXPR)
10591     {
10592       tree c;
10593       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
10594         {
10595           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
10596                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
10597               && OMP_CLAUSE_DECL (c) == decl)
10598             break;
10599           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
10600                    && OMP_CLAUSE_DECL (c) == decl)
10601             error ("iteration variable %qD should not be firstprivate", decl);
10602           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
10603                    && OMP_CLAUSE_DECL (c) == decl)
10604             error ("iteration variable %qD should not be reduction", decl);
10605         }
10606       if (c == NULL)
10607         {
10608           c = build_omp_clause (OMP_CLAUSE_PRIVATE);
10609           OMP_CLAUSE_DECL (c) = decl;
10610           c = finish_omp_clauses (c);
10611           if (c)
10612             {
10613               OMP_CLAUSE_CHAIN (c) = *clauses;
10614               *clauses = c;
10615             }
10616         }
10617     }
10618   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
10619   if (COMPARISON_CLASS_P (cond))
10620     cond = build2 (TREE_CODE (cond), boolean_type_node,
10621                    RECUR (TREE_OPERAND (cond, 0)),
10622                    RECUR (TREE_OPERAND (cond, 1)));
10623   else
10624     cond = RECUR (cond);
10625   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10626   switch (TREE_CODE (incr))
10627     {
10628     case PREINCREMENT_EXPR:
10629     case PREDECREMENT_EXPR:
10630     case POSTINCREMENT_EXPR:
10631     case POSTDECREMENT_EXPR:
10632       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
10633                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
10634       break;
10635     case MODIFY_EXPR:
10636       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10637           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10638         {
10639           tree rhs = TREE_OPERAND (incr, 1);
10640           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10641                          RECUR (TREE_OPERAND (incr, 0)),
10642                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10643                                  RECUR (TREE_OPERAND (rhs, 0)),
10644                                  RECUR (TREE_OPERAND (rhs, 1))));
10645         }
10646       else
10647         incr = RECUR (incr);
10648       break;
10649     case MODOP_EXPR:
10650       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10651           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10652         {
10653           tree lhs = RECUR (TREE_OPERAND (incr, 0));
10654           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
10655                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
10656                                  TREE_TYPE (decl), lhs,
10657                                  RECUR (TREE_OPERAND (incr, 2))));
10658         }
10659       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
10660                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
10661                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
10662         {
10663           tree rhs = TREE_OPERAND (incr, 2);
10664           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10665                          RECUR (TREE_OPERAND (incr, 0)),
10666                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10667                                  RECUR (TREE_OPERAND (rhs, 0)),
10668                                  RECUR (TREE_OPERAND (rhs, 1))));
10669         }
10670       else
10671         incr = RECUR (incr);
10672       break;
10673     default:
10674       incr = RECUR (incr);
10675       break;
10676     }
10677
10678   TREE_VEC_ELT (declv, i) = decl;
10679   TREE_VEC_ELT (initv, i) = init;
10680   TREE_VEC_ELT (condv, i) = cond;
10681   TREE_VEC_ELT (incrv, i) = incr;
10682 #undef RECUR
10683 }
10684
10685 /* Like tsubst_copy for expressions, etc. but also does semantic
10686    processing.  */
10687
10688 static tree
10689 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
10690              bool integral_constant_expression_p)
10691 {
10692 #define RECUR(NODE)                             \
10693   tsubst_expr ((NODE), args, complain, in_decl, \
10694                integral_constant_expression_p)
10695
10696   tree stmt, tmp;
10697
10698   if (t == NULL_TREE || t == error_mark_node)
10699     return t;
10700
10701   if (EXPR_HAS_LOCATION (t))
10702     input_location = EXPR_LOCATION (t);
10703   if (STATEMENT_CODE_P (TREE_CODE (t)))
10704     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
10705
10706   switch (TREE_CODE (t))
10707     {
10708     case STATEMENT_LIST:
10709       {
10710         tree_stmt_iterator i;
10711         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
10712           RECUR (tsi_stmt (i));
10713         break;
10714       }
10715
10716     case CTOR_INITIALIZER:
10717       finish_mem_initializers (tsubst_initializer_list
10718                                (TREE_OPERAND (t, 0), args));
10719       break;
10720
10721     case RETURN_EXPR:
10722       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
10723       break;
10724
10725     case EXPR_STMT:
10726       tmp = RECUR (EXPR_STMT_EXPR (t));
10727       if (EXPR_STMT_STMT_EXPR_RESULT (t))
10728         finish_stmt_expr_expr (tmp, cur_stmt_expr);
10729       else
10730         finish_expr_stmt (tmp);
10731       break;
10732
10733     case USING_STMT:
10734       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
10735       break;
10736
10737     case DECL_EXPR:
10738       {
10739         tree decl;
10740         tree init;
10741
10742         decl = DECL_EXPR_DECL (t);
10743         if (TREE_CODE (decl) == LABEL_DECL)
10744           finish_label_decl (DECL_NAME (decl));
10745         else if (TREE_CODE (decl) == USING_DECL)
10746           {
10747             tree scope = USING_DECL_SCOPE (decl);
10748             tree name = DECL_NAME (decl);
10749             tree decl;
10750
10751             scope = RECUR (scope);
10752             decl = lookup_qualified_name (scope, name,
10753                                           /*is_type_p=*/false,
10754                                           /*complain=*/false);
10755             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
10756               qualified_name_lookup_error (scope, name, decl, input_location);
10757             else
10758               do_local_using_decl (decl, scope, name);
10759           }
10760         else
10761           {
10762             init = DECL_INITIAL (decl);
10763             decl = tsubst (decl, args, complain, in_decl);
10764             if (decl != error_mark_node)
10765               {
10766                 /* By marking the declaration as instantiated, we avoid
10767                    trying to instantiate it.  Since instantiate_decl can't
10768                    handle local variables, and since we've already done
10769                    all that needs to be done, that's the right thing to
10770                    do.  */
10771                 if (TREE_CODE (decl) == VAR_DECL)
10772                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10773                 if (TREE_CODE (decl) == VAR_DECL
10774                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
10775                   /* Anonymous aggregates are a special case.  */
10776                   finish_anon_union (decl);
10777                 else
10778                   {
10779                     maybe_push_decl (decl);
10780                     if (TREE_CODE (decl) == VAR_DECL
10781                         && DECL_PRETTY_FUNCTION_P (decl))
10782                       {
10783                         /* For __PRETTY_FUNCTION__ we have to adjust the
10784                            initializer.  */
10785                         const char *const name
10786                           = cxx_printable_name (current_function_decl, 2);
10787                         init = cp_fname_init (name, &TREE_TYPE (decl));
10788                       }
10789                     else
10790                       {
10791                         tree t = RECUR (init);
10792
10793                         if (init && !t)
10794                           /* If we had an initializer but it
10795                              instantiated to nothing,
10796                              value-initialize the object.  This will
10797                              only occur when the initializer was a
10798                              pack expansion where the parameter packs
10799                              used in that expansion were of length
10800                              zero.  */
10801                           init = build_value_init (TREE_TYPE (decl));
10802                         else
10803                           init = t;
10804                       }
10805
10806                     finish_decl (decl, init, NULL_TREE, NULL_TREE);
10807                   }
10808               }
10809           }
10810
10811         /* A DECL_EXPR can also be used as an expression, in the condition
10812            clause of an if/for/while construct.  */
10813         return decl;
10814       }
10815
10816     case FOR_STMT:
10817       stmt = begin_for_stmt ();
10818                           RECUR (FOR_INIT_STMT (t));
10819       finish_for_init_stmt (stmt);
10820       tmp = RECUR (FOR_COND (t));
10821       finish_for_cond (tmp, stmt);
10822       tmp = RECUR (FOR_EXPR (t));
10823       finish_for_expr (tmp, stmt);
10824       RECUR (FOR_BODY (t));
10825       finish_for_stmt (stmt);
10826       break;
10827
10828     case WHILE_STMT:
10829       stmt = begin_while_stmt ();
10830       tmp = RECUR (WHILE_COND (t));
10831       finish_while_stmt_cond (tmp, stmt);
10832       RECUR (WHILE_BODY (t));
10833       finish_while_stmt (stmt);
10834       break;
10835
10836     case DO_STMT:
10837       stmt = begin_do_stmt ();
10838       RECUR (DO_BODY (t));
10839       finish_do_body (stmt);
10840       tmp = RECUR (DO_COND (t));
10841       finish_do_stmt (tmp, stmt);
10842       break;
10843
10844     case IF_STMT:
10845       stmt = begin_if_stmt ();
10846       tmp = RECUR (IF_COND (t));
10847       finish_if_stmt_cond (tmp, stmt);
10848       RECUR (THEN_CLAUSE (t));
10849       finish_then_clause (stmt);
10850
10851       if (ELSE_CLAUSE (t))
10852         {
10853           begin_else_clause (stmt);
10854           RECUR (ELSE_CLAUSE (t));
10855           finish_else_clause (stmt);
10856         }
10857
10858       finish_if_stmt (stmt);
10859       break;
10860
10861     case BIND_EXPR:
10862       if (BIND_EXPR_BODY_BLOCK (t))
10863         stmt = begin_function_body ();
10864       else
10865         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
10866                                     ? BCS_TRY_BLOCK : 0);
10867
10868       RECUR (BIND_EXPR_BODY (t));
10869
10870       if (BIND_EXPR_BODY_BLOCK (t))
10871         finish_function_body (stmt);
10872       else
10873         finish_compound_stmt (stmt);
10874       break;
10875
10876     case BREAK_STMT:
10877       finish_break_stmt ();
10878       break;
10879
10880     case CONTINUE_STMT:
10881       finish_continue_stmt ();
10882       break;
10883
10884     case SWITCH_STMT:
10885       stmt = begin_switch_stmt ();
10886       tmp = RECUR (SWITCH_STMT_COND (t));
10887       finish_switch_cond (tmp, stmt);
10888       RECUR (SWITCH_STMT_BODY (t));
10889       finish_switch_stmt (stmt);
10890       break;
10891
10892     case CASE_LABEL_EXPR:
10893       finish_case_label (RECUR (CASE_LOW (t)),
10894                          RECUR (CASE_HIGH (t)));
10895       break;
10896
10897     case LABEL_EXPR:
10898       finish_label_stmt (DECL_NAME (LABEL_EXPR_LABEL (t)));
10899       break;
10900
10901     case GOTO_EXPR:
10902       tmp = GOTO_DESTINATION (t);
10903       if (TREE_CODE (tmp) != LABEL_DECL)
10904         /* Computed goto's must be tsubst'd into.  On the other hand,
10905            non-computed gotos must not be; the identifier in question
10906            will have no binding.  */
10907         tmp = RECUR (tmp);
10908       else
10909         tmp = DECL_NAME (tmp);
10910       finish_goto_stmt (tmp);
10911       break;
10912
10913     case ASM_EXPR:
10914       tmp = finish_asm_stmt
10915         (ASM_VOLATILE_P (t),
10916          RECUR (ASM_STRING (t)),
10917          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
10918          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
10919          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
10920       {
10921         tree asm_expr = tmp;
10922         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
10923           asm_expr = TREE_OPERAND (asm_expr, 0);
10924         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
10925       }
10926       break;
10927
10928     case TRY_BLOCK:
10929       if (CLEANUP_P (t))
10930         {
10931           stmt = begin_try_block ();
10932           RECUR (TRY_STMTS (t));
10933           finish_cleanup_try_block (stmt);
10934           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
10935         }
10936       else
10937         {
10938           tree compound_stmt = NULL_TREE;
10939
10940           if (FN_TRY_BLOCK_P (t))
10941             stmt = begin_function_try_block (&compound_stmt);
10942           else
10943             stmt = begin_try_block ();
10944
10945           RECUR (TRY_STMTS (t));
10946
10947           if (FN_TRY_BLOCK_P (t))
10948             finish_function_try_block (stmt);
10949           else
10950             finish_try_block (stmt);
10951
10952           RECUR (TRY_HANDLERS (t));
10953           if (FN_TRY_BLOCK_P (t))
10954             finish_function_handler_sequence (stmt, compound_stmt);
10955           else
10956             finish_handler_sequence (stmt);
10957         }
10958       break;
10959
10960     case HANDLER:
10961       {
10962         tree decl = HANDLER_PARMS (t);
10963
10964         if (decl)
10965           {
10966             decl = tsubst (decl, args, complain, in_decl);
10967             /* Prevent instantiate_decl from trying to instantiate
10968                this variable.  We've already done all that needs to be
10969                done.  */
10970             if (decl != error_mark_node)
10971               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10972           }
10973         stmt = begin_handler ();
10974         finish_handler_parms (decl, stmt);
10975         RECUR (HANDLER_BODY (t));
10976         finish_handler (stmt);
10977       }
10978       break;
10979
10980     case TAG_DEFN:
10981       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
10982       break;
10983
10984     case STATIC_ASSERT:
10985       {
10986         tree condition = 
10987           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
10988                        args,
10989                        complain, in_decl,
10990                        /*integral_constant_expression_p=*/true);
10991         finish_static_assert (condition,
10992                               STATIC_ASSERT_MESSAGE (t),
10993                               STATIC_ASSERT_SOURCE_LOCATION (t),
10994                               /*member_p=*/false);
10995       }
10996       break;
10997
10998     case OMP_PARALLEL:
10999       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11000                                 args, complain, in_decl);
11001       stmt = begin_omp_parallel ();
11002       RECUR (OMP_PARALLEL_BODY (t));
11003       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11004         = OMP_PARALLEL_COMBINED (t);
11005       break;
11006
11007     case OMP_TASK:
11008       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11009                                 args, complain, in_decl);
11010       stmt = begin_omp_task ();
11011       RECUR (OMP_TASK_BODY (t));
11012       finish_omp_task (tmp, stmt);
11013       break;
11014
11015     case OMP_FOR:
11016       {
11017         tree clauses, body, pre_body;
11018         tree declv, initv, condv, incrv;
11019         int i;
11020
11021         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11022                                       args, complain, in_decl);
11023         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11024         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11025         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11026         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11027
11028         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11029           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11030                                    &clauses, args, complain, in_decl,
11031                                    integral_constant_expression_p);
11032
11033         stmt = begin_omp_structured_block ();
11034
11035         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11036           if (TREE_VEC_ELT (initv, i) == NULL
11037               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11038             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11039           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11040             {
11041               tree init = RECUR (TREE_VEC_ELT (initv, i));
11042               gcc_assert (init == TREE_VEC_ELT (declv, i));
11043               TREE_VEC_ELT (initv, i) = NULL_TREE;
11044             }
11045           else
11046             {
11047               tree decl_expr = TREE_VEC_ELT (initv, i);
11048               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11049               gcc_assert (init != NULL);
11050               TREE_VEC_ELT (initv, i) = RECUR (init);
11051               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11052               RECUR (decl_expr);
11053               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11054             }
11055
11056         pre_body = push_stmt_list ();
11057         RECUR (OMP_FOR_PRE_BODY (t));
11058         pre_body = pop_stmt_list (pre_body);
11059
11060         body = push_stmt_list ();
11061         RECUR (OMP_FOR_BODY (t));
11062         body = pop_stmt_list (body);
11063
11064         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11065                             body, pre_body, clauses);
11066
11067         add_stmt (finish_omp_structured_block (stmt));
11068       }
11069       break;
11070
11071     case OMP_SECTIONS:
11072     case OMP_SINGLE:
11073       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11074       stmt = push_stmt_list ();
11075       RECUR (OMP_BODY (t));
11076       stmt = pop_stmt_list (stmt);
11077
11078       t = copy_node (t);
11079       OMP_BODY (t) = stmt;
11080       OMP_CLAUSES (t) = tmp;
11081       add_stmt (t);
11082       break;
11083
11084     case OMP_SECTION:
11085     case OMP_CRITICAL:
11086     case OMP_MASTER:
11087     case OMP_ORDERED:
11088       stmt = push_stmt_list ();
11089       RECUR (OMP_BODY (t));
11090       stmt = pop_stmt_list (stmt);
11091
11092       t = copy_node (t);
11093       OMP_BODY (t) = stmt;
11094       add_stmt (t);
11095       break;
11096
11097     case OMP_ATOMIC:
11098       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11099       {
11100         tree op1 = TREE_OPERAND (t, 1);
11101         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11102         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11103         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11104       }
11105       break;
11106
11107     case EXPR_PACK_EXPANSION:
11108       error ("invalid use of pack expansion expression");
11109       return error_mark_node;
11110
11111     case NONTYPE_ARGUMENT_PACK:
11112       error ("use %<...%> to expand argument pack");
11113       return error_mark_node;
11114
11115     default:
11116       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11117
11118       return tsubst_copy_and_build (t, args, complain, in_decl,
11119                                     /*function_p=*/false,
11120                                     integral_constant_expression_p);
11121     }
11122
11123   return NULL_TREE;
11124 #undef RECUR
11125 }
11126
11127 /* T is a postfix-expression that is not being used in a function
11128    call.  Return the substituted version of T.  */
11129
11130 static tree
11131 tsubst_non_call_postfix_expression (tree t, tree args,
11132                                     tsubst_flags_t complain,
11133                                     tree in_decl)
11134 {
11135   if (TREE_CODE (t) == SCOPE_REF)
11136     t = tsubst_qualified_id (t, args, complain, in_decl,
11137                              /*done=*/false, /*address_p=*/false);
11138   else
11139     t = tsubst_copy_and_build (t, args, complain, in_decl,
11140                                /*function_p=*/false,
11141                                /*integral_constant_expression_p=*/false);
11142
11143   return t;
11144 }
11145
11146 /* Like tsubst but deals with expressions and performs semantic
11147    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11148
11149 tree
11150 tsubst_copy_and_build (tree t,
11151                        tree args,
11152                        tsubst_flags_t complain,
11153                        tree in_decl,
11154                        bool function_p,
11155                        bool integral_constant_expression_p)
11156 {
11157 #define RECUR(NODE)                                             \
11158   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11159                          /*function_p=*/false,                  \
11160                          integral_constant_expression_p)
11161
11162   tree op1;
11163
11164   if (t == NULL_TREE || t == error_mark_node)
11165     return t;
11166
11167   switch (TREE_CODE (t))
11168     {
11169     case USING_DECL:
11170       t = DECL_NAME (t);
11171       /* Fall through.  */
11172     case IDENTIFIER_NODE:
11173       {
11174         tree decl;
11175         cp_id_kind idk;
11176         bool non_integral_constant_expression_p;
11177         const char *error_msg;
11178
11179         if (IDENTIFIER_TYPENAME_P (t))
11180           {
11181             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11182             t = mangle_conv_op_name_for_type (new_type);
11183           }
11184
11185         /* Look up the name.  */
11186         decl = lookup_name (t);
11187
11188         /* By convention, expressions use ERROR_MARK_NODE to indicate
11189            failure, not NULL_TREE.  */
11190         if (decl == NULL_TREE)
11191           decl = error_mark_node;
11192
11193         decl = finish_id_expression (t, decl, NULL_TREE,
11194                                      &idk,
11195                                      integral_constant_expression_p,
11196                                      /*allow_non_integral_constant_expression_p=*/false,
11197                                      &non_integral_constant_expression_p,
11198                                      /*template_p=*/false,
11199                                      /*done=*/true,
11200                                      /*address_p=*/false,
11201                                      /*template_arg_p=*/false,
11202                                      &error_msg,
11203                                      input_location);
11204         if (error_msg)
11205           error (error_msg);
11206         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11207           decl = unqualified_name_lookup_error (decl);
11208         return decl;
11209       }
11210
11211     case TEMPLATE_ID_EXPR:
11212       {
11213         tree object;
11214         tree templ = RECUR (TREE_OPERAND (t, 0));
11215         tree targs = TREE_OPERAND (t, 1);
11216
11217         if (targs)
11218           targs = tsubst_template_args (targs, args, complain, in_decl);
11219
11220         if (TREE_CODE (templ) == COMPONENT_REF)
11221           {
11222             object = TREE_OPERAND (templ, 0);
11223             templ = TREE_OPERAND (templ, 1);
11224           }
11225         else
11226           object = NULL_TREE;
11227         templ = lookup_template_function (templ, targs);
11228
11229         if (object)
11230           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11231                          object, templ, NULL_TREE);
11232         else
11233           return baselink_for_fns (templ);
11234       }
11235
11236     case INDIRECT_REF:
11237       {
11238         tree r = RECUR (TREE_OPERAND (t, 0));
11239
11240         if (REFERENCE_REF_P (t))
11241           {
11242             /* A type conversion to reference type will be enclosed in
11243                such an indirect ref, but the substitution of the cast
11244                will have also added such an indirect ref.  */
11245             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11246               r = convert_from_reference (r);
11247           }
11248         else
11249           r = build_x_indirect_ref (r, "unary *", complain);
11250         return r;
11251       }
11252
11253     case NOP_EXPR:
11254       return build_nop
11255         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11256          RECUR (TREE_OPERAND (t, 0)));
11257
11258     case CAST_EXPR:
11259     case REINTERPRET_CAST_EXPR:
11260     case CONST_CAST_EXPR:
11261     case DYNAMIC_CAST_EXPR:
11262     case STATIC_CAST_EXPR:
11263       {
11264         tree type;
11265         tree op;
11266
11267         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11268         if (integral_constant_expression_p
11269             && !cast_valid_in_integral_constant_expression_p (type))
11270           {
11271             if (complain & tf_error)
11272               error ("a cast to a type other than an integral or "
11273                      "enumeration type cannot appear in a constant-expression");
11274             return error_mark_node; 
11275           }
11276
11277         op = RECUR (TREE_OPERAND (t, 0));
11278
11279         switch (TREE_CODE (t))
11280           {
11281           case CAST_EXPR:
11282             return build_functional_cast (type, op, complain);
11283           case REINTERPRET_CAST_EXPR:
11284             return build_reinterpret_cast (type, op, complain);
11285           case CONST_CAST_EXPR:
11286             return build_const_cast (type, op, complain);
11287           case DYNAMIC_CAST_EXPR:
11288             return build_dynamic_cast (type, op, complain);
11289           case STATIC_CAST_EXPR:
11290             return build_static_cast (type, op, complain);
11291           default:
11292             gcc_unreachable ();
11293           }
11294       }
11295
11296     case POSTDECREMENT_EXPR:
11297     case POSTINCREMENT_EXPR:
11298       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11299                                                 args, complain, in_decl);
11300       return build_x_unary_op (TREE_CODE (t), op1, complain);
11301
11302     case PREDECREMENT_EXPR:
11303     case PREINCREMENT_EXPR:
11304     case NEGATE_EXPR:
11305     case BIT_NOT_EXPR:
11306     case ABS_EXPR:
11307     case TRUTH_NOT_EXPR:
11308     case UNARY_PLUS_EXPR:  /* Unary + */
11309     case REALPART_EXPR:
11310     case IMAGPART_EXPR:
11311       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11312                                complain);
11313
11314     case ADDR_EXPR:
11315       op1 = TREE_OPERAND (t, 0);
11316       if (TREE_CODE (op1) == SCOPE_REF)
11317         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11318                                    /*done=*/true, /*address_p=*/true);
11319       else
11320         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11321                                                   in_decl);
11322       if (TREE_CODE (op1) == LABEL_DECL)
11323         return finish_label_address_expr (DECL_NAME (op1),
11324                                           EXPR_LOCATION (op1));
11325       return build_x_unary_op (ADDR_EXPR, op1, complain);
11326
11327     case PLUS_EXPR:
11328     case MINUS_EXPR:
11329     case MULT_EXPR:
11330     case TRUNC_DIV_EXPR:
11331     case CEIL_DIV_EXPR:
11332     case FLOOR_DIV_EXPR:
11333     case ROUND_DIV_EXPR:
11334     case EXACT_DIV_EXPR:
11335     case BIT_AND_EXPR:
11336     case BIT_IOR_EXPR:
11337     case BIT_XOR_EXPR:
11338     case TRUNC_MOD_EXPR:
11339     case FLOOR_MOD_EXPR:
11340     case TRUTH_ANDIF_EXPR:
11341     case TRUTH_ORIF_EXPR:
11342     case TRUTH_AND_EXPR:
11343     case TRUTH_OR_EXPR:
11344     case RSHIFT_EXPR:
11345     case LSHIFT_EXPR:
11346     case RROTATE_EXPR:
11347     case LROTATE_EXPR:
11348     case EQ_EXPR:
11349     case NE_EXPR:
11350     case MAX_EXPR:
11351     case MIN_EXPR:
11352     case LE_EXPR:
11353     case GE_EXPR:
11354     case LT_EXPR:
11355     case GT_EXPR:
11356     case MEMBER_REF:
11357     case DOTSTAR_EXPR:
11358       return build_x_binary_op
11359         (TREE_CODE (t),
11360          RECUR (TREE_OPERAND (t, 0)),
11361          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11362           ? ERROR_MARK
11363           : TREE_CODE (TREE_OPERAND (t, 0))),
11364          RECUR (TREE_OPERAND (t, 1)),
11365          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11366           ? ERROR_MARK
11367           : TREE_CODE (TREE_OPERAND (t, 1))),
11368          /*overloaded_p=*/NULL,
11369          complain);
11370
11371     case SCOPE_REF:
11372       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11373                                   /*address_p=*/false);
11374     case ARRAY_REF:
11375       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11376                                                 args, complain, in_decl);
11377       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11378
11379     case SIZEOF_EXPR:
11380       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11381         return tsubst_copy (t, args, complain, in_decl);
11382       /* Fall through */
11383       
11384     case ALIGNOF_EXPR:
11385       op1 = TREE_OPERAND (t, 0);
11386       if (!args)
11387         {
11388           /* When there are no ARGS, we are trying to evaluate a
11389              non-dependent expression from the parser.  Trying to do
11390              the substitutions may not work.  */
11391           if (!TYPE_P (op1))
11392             op1 = TREE_TYPE (op1);
11393         }
11394       else
11395         {
11396           ++skip_evaluation;
11397           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11398                                        /*function_p=*/false,
11399                                        /*integral_constant_expression_p=*/false);
11400           --skip_evaluation;
11401         }
11402       if (TYPE_P (op1))
11403         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11404                                            complain & tf_error);
11405       else
11406         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11407                                            complain & tf_error);
11408
11409     case MODOP_EXPR:
11410       {
11411         tree r = build_x_modify_expr
11412           (RECUR (TREE_OPERAND (t, 0)),
11413            TREE_CODE (TREE_OPERAND (t, 1)),
11414            RECUR (TREE_OPERAND (t, 2)),
11415            complain);
11416         /* TREE_NO_WARNING must be set if either the expression was
11417            parenthesized or it uses an operator such as >>= rather
11418            than plain assignment.  In the former case, it was already
11419            set and must be copied.  In the latter case,
11420            build_x_modify_expr sets it and it must not be reset
11421            here.  */
11422         if (TREE_NO_WARNING (t))
11423           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11424         return r;
11425       }
11426
11427     case ARROW_EXPR:
11428       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11429                                                 args, complain, in_decl);
11430       /* Remember that there was a reference to this entity.  */
11431       if (DECL_P (op1))
11432         mark_used (op1);
11433       return build_x_arrow (op1);
11434
11435     case NEW_EXPR:
11436       {
11437         tree placement = RECUR (TREE_OPERAND (t, 0));
11438         tree init = RECUR (TREE_OPERAND (t, 3));
11439         VEC(tree,gc) *placement_vec;
11440         VEC(tree,gc) *init_vec;
11441         tree ret;
11442
11443         if (placement == NULL_TREE)
11444           placement_vec = NULL;
11445         else
11446           {
11447             placement_vec = make_tree_vector ();
11448             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
11449               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
11450           }
11451
11452         /* If there was an initializer in the original tree, but it
11453            instantiated to an empty list, then we should pass a
11454            non-NULL empty vector to tell build_new that it was an
11455            empty initializer() rather than no initializer.  This can
11456            only happen when the initializer is a pack expansion whose
11457            parameter packs are of length zero.  */
11458         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
11459           init_vec = NULL;
11460         else
11461           {
11462             init_vec = make_tree_vector ();
11463             if (init == void_zero_node)
11464               gcc_assert (init_vec != NULL);
11465             else
11466               {
11467                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
11468                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
11469               }
11470           }
11471
11472         ret = build_new (&placement_vec,
11473                          RECUR (TREE_OPERAND (t, 1)),
11474                          RECUR (TREE_OPERAND (t, 2)),
11475                          &init_vec,
11476                          NEW_EXPR_USE_GLOBAL (t),
11477                          complain);
11478
11479         if (placement_vec != NULL)
11480           release_tree_vector (placement_vec);
11481         if (init_vec != NULL)
11482           release_tree_vector (init_vec);
11483
11484         return ret;
11485       }
11486
11487     case DELETE_EXPR:
11488      return delete_sanity
11489        (RECUR (TREE_OPERAND (t, 0)),
11490         RECUR (TREE_OPERAND (t, 1)),
11491         DELETE_EXPR_USE_VEC (t),
11492         DELETE_EXPR_USE_GLOBAL (t));
11493
11494     case COMPOUND_EXPR:
11495       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
11496                                     RECUR (TREE_OPERAND (t, 1)),
11497                                     complain);
11498
11499     case CALL_EXPR:
11500       {
11501         tree function;
11502         VEC(tree,gc) *call_args;
11503         unsigned int nargs, i;
11504         bool qualified_p;
11505         bool koenig_p;
11506         tree ret;
11507
11508         function = CALL_EXPR_FN (t);
11509         /* When we parsed the expression,  we determined whether or
11510            not Koenig lookup should be performed.  */
11511         koenig_p = KOENIG_LOOKUP_P (t);
11512         if (TREE_CODE (function) == SCOPE_REF)
11513           {
11514             qualified_p = true;
11515             function = tsubst_qualified_id (function, args, complain, in_decl,
11516                                             /*done=*/false,
11517                                             /*address_p=*/false);
11518           }
11519         else
11520           {
11521             if (TREE_CODE (function) == COMPONENT_REF)
11522               {
11523                 tree op = TREE_OPERAND (function, 1);
11524
11525                 qualified_p = (TREE_CODE (op) == SCOPE_REF
11526                                || (BASELINK_P (op)
11527                                    && BASELINK_QUALIFIED_P (op)));
11528               }
11529             else
11530               qualified_p = false;
11531
11532             function = tsubst_copy_and_build (function, args, complain,
11533                                               in_decl,
11534                                               !qualified_p,
11535                                               integral_constant_expression_p);
11536
11537             if (BASELINK_P (function))
11538               qualified_p = true;
11539           }
11540
11541         nargs = call_expr_nargs (t);
11542         call_args = make_tree_vector ();
11543         for (i = 0; i < nargs; ++i)
11544           {
11545             tree arg = CALL_EXPR_ARG (t, i);
11546
11547             if (!PACK_EXPANSION_P (arg))
11548               VEC_safe_push (tree, gc, call_args,
11549                              RECUR (CALL_EXPR_ARG (t, i)));
11550             else
11551               {
11552                 /* Expand the pack expansion and push each entry onto
11553                    CALL_ARGS.  */
11554                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
11555                 if (TREE_CODE (arg) == TREE_VEC)
11556                   {
11557                     unsigned int len, j;
11558
11559                     len = TREE_VEC_LENGTH (arg);
11560                     for (j = 0; j < len; ++j)
11561                       {
11562                         tree value = TREE_VEC_ELT (arg, j);
11563                         if (value != NULL_TREE)
11564                           value = convert_from_reference (value);
11565                         VEC_safe_push (tree, gc, call_args, value);
11566                       }
11567                   }
11568                 else
11569                   {
11570                     /* A partial substitution.  Add one entry.  */
11571                     VEC_safe_push (tree, gc, call_args, arg);
11572                   }
11573               }
11574           }
11575
11576         /* We do not perform argument-dependent lookup if normal
11577            lookup finds a non-function, in accordance with the
11578            expected resolution of DR 218.  */
11579         if (koenig_p
11580             && ((is_overloaded_fn (function)
11581                  /* If lookup found a member function, the Koenig lookup is
11582                     not appropriate, even if an unqualified-name was used
11583                     to denote the function.  */
11584                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
11585                 || TREE_CODE (function) == IDENTIFIER_NODE)
11586             /* Only do this when substitution turns a dependent call
11587                into a non-dependent call.  */
11588             && type_dependent_expression_p_push (t)
11589             && !any_type_dependent_arguments_p (call_args))
11590           function = perform_koenig_lookup (function, call_args);
11591
11592         if (TREE_CODE (function) == IDENTIFIER_NODE)
11593           {
11594             unqualified_name_lookup_error (function);
11595             release_tree_vector (call_args);
11596             return error_mark_node;
11597           }
11598
11599         /* Remember that there was a reference to this entity.  */
11600         if (DECL_P (function))
11601           mark_used (function);
11602
11603         if (TREE_CODE (function) == OFFSET_REF)
11604           ret = build_offset_ref_call_from_tree (function, &call_args);
11605         else if (TREE_CODE (function) == COMPONENT_REF)
11606           {
11607             if (!BASELINK_P (TREE_OPERAND (function, 1)))
11608               ret = finish_call_expr (function, &call_args,
11609                                        /*disallow_virtual=*/false,
11610                                        /*koenig_p=*/false,
11611                                        complain);
11612             else
11613               ret = (build_new_method_call
11614                       (TREE_OPERAND (function, 0),
11615                        TREE_OPERAND (function, 1),
11616                        &call_args, NULL_TREE,
11617                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
11618                        /*fn_p=*/NULL,
11619                        complain));
11620           }
11621         else
11622           ret = finish_call_expr (function, &call_args,
11623                                   /*disallow_virtual=*/qualified_p,
11624                                   koenig_p,
11625                                   complain);
11626
11627         release_tree_vector (call_args);
11628
11629         return ret;
11630       }
11631
11632     case COND_EXPR:
11633       return build_x_conditional_expr
11634         (RECUR (TREE_OPERAND (t, 0)),
11635          RECUR (TREE_OPERAND (t, 1)),
11636          RECUR (TREE_OPERAND (t, 2)),
11637          complain);
11638
11639     case PSEUDO_DTOR_EXPR:
11640       return finish_pseudo_destructor_expr
11641         (RECUR (TREE_OPERAND (t, 0)),
11642          RECUR (TREE_OPERAND (t, 1)),
11643          RECUR (TREE_OPERAND (t, 2)));
11644
11645     case TREE_LIST:
11646       {
11647         tree purpose, value, chain;
11648
11649         if (t == void_list_node)
11650           return t;
11651
11652         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
11653             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
11654           {
11655             /* We have pack expansions, so expand those and
11656                create a new list out of it.  */
11657             tree purposevec = NULL_TREE;
11658             tree valuevec = NULL_TREE;
11659             tree chain;
11660             int i, len = -1;
11661
11662             /* Expand the argument expressions.  */
11663             if (TREE_PURPOSE (t))
11664               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
11665                                                  complain, in_decl);
11666             if (TREE_VALUE (t))
11667               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
11668                                                complain, in_decl);
11669
11670             /* Build the rest of the list.  */
11671             chain = TREE_CHAIN (t);
11672             if (chain && chain != void_type_node)
11673               chain = RECUR (chain);
11674
11675             /* Determine the number of arguments.  */
11676             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
11677               {
11678                 len = TREE_VEC_LENGTH (purposevec);
11679                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
11680               }
11681             else if (TREE_CODE (valuevec) == TREE_VEC)
11682               len = TREE_VEC_LENGTH (valuevec);
11683             else
11684               {
11685                 /* Since we only performed a partial substitution into
11686                    the argument pack, we only return a single list
11687                    node.  */
11688                 if (purposevec == TREE_PURPOSE (t)
11689                     && valuevec == TREE_VALUE (t)
11690                     && chain == TREE_CHAIN (t))
11691                   return t;
11692
11693                 return tree_cons (purposevec, valuevec, chain);
11694               }
11695             
11696             /* Convert the argument vectors into a TREE_LIST */
11697             i = len;
11698             while (i > 0)
11699               {
11700                 /* Grab the Ith values.  */
11701                 i--;
11702                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
11703                                      : NULL_TREE;
11704                 value 
11705                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
11706                              : NULL_TREE;
11707
11708                 /* Build the list (backwards).  */
11709                 chain = tree_cons (purpose, value, chain);
11710               }
11711
11712             return chain;
11713           }
11714
11715         purpose = TREE_PURPOSE (t);
11716         if (purpose)
11717           purpose = RECUR (purpose);
11718         value = TREE_VALUE (t);
11719         if (value)
11720           value = RECUR (value);
11721         chain = TREE_CHAIN (t);
11722         if (chain && chain != void_type_node)
11723           chain = RECUR (chain);
11724         if (purpose == TREE_PURPOSE (t)
11725             && value == TREE_VALUE (t)
11726             && chain == TREE_CHAIN (t))
11727           return t;
11728         return tree_cons (purpose, value, chain);
11729       }
11730
11731     case COMPONENT_REF:
11732       {
11733         tree object;
11734         tree object_type;
11735         tree member;
11736
11737         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11738                                                      args, complain, in_decl);
11739         /* Remember that there was a reference to this entity.  */
11740         if (DECL_P (object))
11741           mark_used (object);
11742         object_type = TREE_TYPE (object);
11743
11744         member = TREE_OPERAND (t, 1);
11745         if (BASELINK_P (member))
11746           member = tsubst_baselink (member,
11747                                     non_reference (TREE_TYPE (object)),
11748                                     args, complain, in_decl);
11749         else
11750           member = tsubst_copy (member, args, complain, in_decl);
11751         if (member == error_mark_node)
11752           return error_mark_node;
11753
11754         if (object_type && !CLASS_TYPE_P (object_type))
11755           {
11756             if (SCALAR_TYPE_P (object_type))
11757               {
11758                 tree s = NULL_TREE;
11759                 tree dtor = member;
11760
11761                 if (TREE_CODE (dtor) == SCOPE_REF)
11762                   {
11763                     s = TREE_OPERAND (dtor, 0);
11764                     dtor = TREE_OPERAND (dtor, 1);
11765                   }
11766                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
11767                   {
11768                     dtor = TREE_OPERAND (dtor, 0);
11769                     if (TYPE_P (dtor))
11770                       return finish_pseudo_destructor_expr (object, s, dtor);
11771                   }
11772               }
11773           }
11774         else if (TREE_CODE (member) == SCOPE_REF
11775                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
11776           {
11777             tree tmpl;
11778             tree args;
11779
11780             /* Lookup the template functions now that we know what the
11781                scope is.  */
11782             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
11783             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
11784             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
11785                                             /*is_type_p=*/false,
11786                                             /*complain=*/false);
11787             if (BASELINK_P (member))
11788               {
11789                 BASELINK_FUNCTIONS (member)
11790                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
11791                               args);
11792                 member = (adjust_result_of_qualified_name_lookup
11793                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
11794                            object_type));
11795               }
11796             else
11797               {
11798                 qualified_name_lookup_error (object_type, tmpl, member,
11799                                              input_location);
11800                 return error_mark_node;
11801               }
11802           }
11803         else if (TREE_CODE (member) == SCOPE_REF
11804                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
11805                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
11806           {
11807             if (complain & tf_error)
11808               {
11809                 if (TYPE_P (TREE_OPERAND (member, 0)))
11810                   error ("%qT is not a class or namespace",
11811                          TREE_OPERAND (member, 0));
11812                 else
11813                   error ("%qD is not a class or namespace",
11814                          TREE_OPERAND (member, 0));
11815               }
11816             return error_mark_node;
11817           }
11818         else if (TREE_CODE (member) == FIELD_DECL)
11819           return finish_non_static_data_member (member, object, NULL_TREE);
11820
11821         return finish_class_member_access_expr (object, member,
11822                                                 /*template_p=*/false,
11823                                                 complain);
11824       }
11825
11826     case THROW_EXPR:
11827       return build_throw
11828         (RECUR (TREE_OPERAND (t, 0)));
11829
11830     case CONSTRUCTOR:
11831       {
11832         VEC(constructor_elt,gc) *n;
11833         constructor_elt *ce;
11834         unsigned HOST_WIDE_INT idx;
11835         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11836         bool process_index_p;
11837         int newlen;
11838         bool need_copy_p = false;
11839         tree r;
11840
11841         if (type == error_mark_node)
11842           return error_mark_node;
11843
11844         /* digest_init will do the wrong thing if we let it.  */
11845         if (type && TYPE_PTRMEMFUNC_P (type))
11846           return t;
11847
11848         /* We do not want to process the index of aggregate
11849            initializers as they are identifier nodes which will be
11850            looked up by digest_init.  */
11851         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
11852
11853         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
11854         newlen = VEC_length (constructor_elt, n);
11855         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
11856           {
11857             if (ce->index && process_index_p)
11858               ce->index = RECUR (ce->index);
11859
11860             if (PACK_EXPANSION_P (ce->value))
11861               {
11862                 /* Substitute into the pack expansion.  */
11863                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
11864                                                   in_decl);
11865
11866                 if (ce->value == error_mark_node)
11867                   ;
11868                 else if (TREE_VEC_LENGTH (ce->value) == 1)
11869                   /* Just move the argument into place.  */
11870                   ce->value = TREE_VEC_ELT (ce->value, 0);
11871                 else
11872                   {
11873                     /* Update the length of the final CONSTRUCTOR
11874                        arguments vector, and note that we will need to
11875                        copy.*/
11876                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
11877                     need_copy_p = true;
11878                   }
11879               }
11880             else
11881               ce->value = RECUR (ce->value);
11882           }
11883
11884         if (need_copy_p)
11885           {
11886             VEC(constructor_elt,gc) *old_n = n;
11887
11888             n = VEC_alloc (constructor_elt, gc, newlen);
11889             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
11890                  idx++)
11891               {
11892                 if (TREE_CODE (ce->value) == TREE_VEC)
11893                   {
11894                     int i, len = TREE_VEC_LENGTH (ce->value);
11895                     for (i = 0; i < len; ++i)
11896                       CONSTRUCTOR_APPEND_ELT (n, 0,
11897                                               TREE_VEC_ELT (ce->value, i));
11898                   }
11899                 else
11900                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
11901               }
11902           }
11903
11904         r = build_constructor (init_list_type_node, n);
11905         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
11906
11907         if (TREE_HAS_CONSTRUCTOR (t))
11908           return finish_compound_literal (type, r);
11909
11910         return r;
11911       }
11912
11913     case TYPEID_EXPR:
11914       {
11915         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
11916         if (TYPE_P (operand_0))
11917           return get_typeid (operand_0);
11918         return build_typeid (operand_0);
11919       }
11920
11921     case VAR_DECL:
11922       if (!args)
11923         return t;
11924       /* Fall through */
11925
11926     case PARM_DECL:
11927       {
11928         tree r = tsubst_copy (t, args, complain, in_decl);
11929
11930         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
11931           /* If the original type was a reference, we'll be wrapped in
11932              the appropriate INDIRECT_REF.  */
11933           r = convert_from_reference (r);
11934         return r;
11935       }
11936
11937     case VA_ARG_EXPR:
11938       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
11939                              tsubst_copy (TREE_TYPE (t), args, complain,
11940                                           in_decl));
11941
11942     case OFFSETOF_EXPR:
11943       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
11944
11945     case TRAIT_EXPR:
11946       {
11947         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
11948                                   complain, in_decl);
11949
11950         tree type2 = TRAIT_EXPR_TYPE2 (t);
11951         if (type2)
11952           type2 = tsubst_copy (type2, args, complain, in_decl);
11953         
11954         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
11955       }
11956
11957     case STMT_EXPR:
11958       {
11959         tree old_stmt_expr = cur_stmt_expr;
11960         tree stmt_expr = begin_stmt_expr ();
11961
11962         cur_stmt_expr = stmt_expr;
11963         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
11964                      integral_constant_expression_p);
11965         stmt_expr = finish_stmt_expr (stmt_expr, false);
11966         cur_stmt_expr = old_stmt_expr;
11967
11968         return stmt_expr;
11969       }
11970
11971     case CONST_DECL:
11972       t = tsubst_copy (t, args, complain, in_decl);
11973       /* As in finish_id_expression, we resolve enumeration constants
11974          to their underlying values.  */
11975       if (TREE_CODE (t) == CONST_DECL)
11976         {
11977           used_types_insert (TREE_TYPE (t));
11978           return DECL_INITIAL (t);
11979         }
11980       return t;
11981
11982     default:
11983       /* Handle Objective-C++ constructs, if appropriate.  */
11984       {
11985         tree subst
11986           = objcp_tsubst_copy_and_build (t, args, complain,
11987                                          in_decl, /*function_p=*/false);
11988         if (subst)
11989           return subst;
11990       }
11991       return tsubst_copy (t, args, complain, in_decl);
11992     }
11993
11994 #undef RECUR
11995 }
11996
11997 /* Verify that the instantiated ARGS are valid. For type arguments,
11998    make sure that the type's linkage is ok. For non-type arguments,
11999    make sure they are constants if they are integral or enumerations.
12000    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12001
12002 static bool
12003 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12004 {
12005   if (ARGUMENT_PACK_P (t))
12006     {
12007       tree vec = ARGUMENT_PACK_ARGS (t);
12008       int len = TREE_VEC_LENGTH (vec);
12009       bool result = false;
12010       int i;
12011
12012       for (i = 0; i < len; ++i)
12013         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12014           result = true;
12015       return result;
12016     }
12017   else if (TYPE_P (t))
12018     {
12019       /* [basic.link]: A name with no linkage (notably, the name
12020          of a class or enumeration declared in a local scope)
12021          shall not be used to declare an entity with linkage.
12022          This implies that names with no linkage cannot be used as
12023          template arguments.  */
12024       tree nt = no_linkage_check (t, /*relaxed_p=*/false);
12025
12026       if (nt)
12027         {
12028           /* DR 488 makes use of a type with no linkage cause
12029              type deduction to fail.  */
12030           if (complain & tf_error)
12031             {
12032               if (TYPE_ANONYMOUS_P (nt))
12033                 error ("%qT is/uses anonymous type", t);
12034               else
12035                 error ("template argument for %qD uses local type %qT",
12036                        tmpl, t);
12037             }
12038           return true;
12039         }
12040       /* In order to avoid all sorts of complications, we do not
12041          allow variably-modified types as template arguments.  */
12042       else if (variably_modified_type_p (t, NULL_TREE))
12043         {
12044           if (complain & tf_error)
12045             error ("%qT is a variably modified type", t);
12046           return true;
12047         }
12048     }
12049   /* A non-type argument of integral or enumerated type must be a
12050      constant.  */
12051   else if (TREE_TYPE (t)
12052            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12053            && !TREE_CONSTANT (t))
12054     {
12055       if (complain & tf_error)
12056         error ("integral expression %qE is not constant", t);
12057       return true;
12058     }
12059   return false;
12060 }
12061
12062 static bool
12063 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12064 {
12065   int ix, len = DECL_NTPARMS (tmpl);
12066   bool result = false;
12067
12068   for (ix = 0; ix != len; ix++)
12069     {
12070       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12071         result = true;
12072     }
12073   if (result && (complain & tf_error))
12074     error ("  trying to instantiate %qD", tmpl);
12075   return result;
12076 }
12077
12078 /* Instantiate the indicated variable or function template TMPL with
12079    the template arguments in TARG_PTR.  */
12080
12081 tree
12082 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
12083 {
12084   tree fndecl;
12085   tree gen_tmpl;
12086   tree spec;
12087   HOST_WIDE_INT saved_processing_template_decl;
12088
12089   if (tmpl == error_mark_node)
12090     return error_mark_node;
12091
12092   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12093
12094   /* If this function is a clone, handle it specially.  */
12095   if (DECL_CLONED_FUNCTION_P (tmpl))
12096     {
12097       tree spec;
12098       tree clone;
12099
12100       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
12101                                    complain);
12102       if (spec == error_mark_node)
12103         return error_mark_node;
12104
12105       /* Look for the clone.  */
12106       FOR_EACH_CLONE (clone, spec)
12107         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12108           return clone;
12109       /* We should always have found the clone by now.  */
12110       gcc_unreachable ();
12111       return NULL_TREE;
12112     }
12113
12114   /* Check to see if we already have this specialization.  */
12115   spec = retrieve_specialization (tmpl, targ_ptr,
12116                                   /*class_specializations_p=*/false);
12117   if (spec != NULL_TREE)
12118     return spec;
12119
12120   gen_tmpl = most_general_template (tmpl);
12121   if (tmpl != gen_tmpl)
12122     {
12123       /* The TMPL is a partial instantiation.  To get a full set of
12124          arguments we must add the arguments used to perform the
12125          partial instantiation.  */
12126       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12127                                               targ_ptr);
12128
12129       /* Check to see if we already have this specialization.  */
12130       spec = retrieve_specialization (gen_tmpl, targ_ptr,
12131                                       /*class_specializations_p=*/false);
12132       if (spec != NULL_TREE)
12133         return spec;
12134     }
12135
12136   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12137                                complain))
12138     return error_mark_node;
12139
12140   /* We are building a FUNCTION_DECL, during which the access of its
12141      parameters and return types have to be checked.  However this
12142      FUNCTION_DECL which is the desired context for access checking
12143      is not built yet.  We solve this chicken-and-egg problem by
12144      deferring all checks until we have the FUNCTION_DECL.  */
12145   push_deferring_access_checks (dk_deferred);
12146
12147   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12148      (because, for example, we have encountered a non-dependent
12149      function call in the body of a template function and must now
12150      determine which of several overloaded functions will be called),
12151      within the instantiation itself we are not processing a
12152      template.  */  
12153   saved_processing_template_decl = processing_template_decl;
12154   processing_template_decl = 0;
12155   /* Substitute template parameters to obtain the specialization.  */
12156   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12157                    targ_ptr, complain, gen_tmpl);
12158   processing_template_decl = saved_processing_template_decl;
12159   if (fndecl == error_mark_node)
12160     return error_mark_node;
12161
12162   /* Now we know the specialization, compute access previously
12163      deferred.  */
12164   push_access_scope (fndecl);
12165
12166   /* Some typedefs referenced from within the template code need to be access
12167      checked at template instantiation time, i.e now. These types were
12168      added to the template at parsing time. Let's get those and perfom
12169      the acces checks then.  */
12170   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
12171   perform_deferred_access_checks ();
12172   pop_access_scope (fndecl);
12173   pop_deferring_access_checks ();
12174
12175   /* The DECL_TI_TEMPLATE should always be the immediate parent
12176      template, not the most general template.  */
12177   DECL_TI_TEMPLATE (fndecl) = tmpl;
12178
12179   /* If we've just instantiated the main entry point for a function,
12180      instantiate all the alternate entry points as well.  We do this
12181      by cloning the instantiation of the main entry point, not by
12182      instantiating the template clones.  */
12183   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
12184     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
12185
12186   return fndecl;
12187 }
12188
12189 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
12190    NARGS elements of the arguments that are being used when calling
12191    it.  TARGS is a vector into which the deduced template arguments
12192    are placed.
12193
12194    Return zero for success, 2 for an incomplete match that doesn't resolve
12195    all the types, and 1 for complete failure.  An error message will be
12196    printed only for an incomplete match.
12197
12198    If FN is a conversion operator, or we are trying to produce a specific
12199    specialization, RETURN_TYPE is the return type desired.
12200
12201    The EXPLICIT_TARGS are explicit template arguments provided via a
12202    template-id.
12203
12204    The parameter STRICT is one of:
12205
12206    DEDUCE_CALL:
12207      We are deducing arguments for a function call, as in
12208      [temp.deduct.call].
12209
12210    DEDUCE_CONV:
12211      We are deducing arguments for a conversion function, as in
12212      [temp.deduct.conv].
12213
12214    DEDUCE_EXACT:
12215      We are deducing arguments when doing an explicit instantiation
12216      as in [temp.explicit], when determining an explicit specialization
12217      as in [temp.expl.spec], or when taking the address of a function
12218      template, as in [temp.deduct.funcaddr].  */
12219
12220 int
12221 fn_type_unification (tree fn,
12222                      tree explicit_targs,
12223                      tree targs,
12224                      const tree *args,
12225                      unsigned int nargs,
12226                      tree return_type,
12227                      unification_kind_t strict,
12228                      int flags)
12229 {
12230   tree parms;
12231   tree fntype;
12232   int result;
12233   bool incomplete_argument_packs_p = false;
12234
12235   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12236
12237   fntype = TREE_TYPE (fn);
12238   if (explicit_targs)
12239     {
12240       /* [temp.deduct]
12241
12242          The specified template arguments must match the template
12243          parameters in kind (i.e., type, nontype, template), and there
12244          must not be more arguments than there are parameters;
12245          otherwise type deduction fails.
12246
12247          Nontype arguments must match the types of the corresponding
12248          nontype template parameters, or must be convertible to the
12249          types of the corresponding nontype parameters as specified in
12250          _temp.arg.nontype_, otherwise type deduction fails.
12251
12252          All references in the function type of the function template
12253          to the corresponding template parameters are replaced by the
12254          specified template argument values.  If a substitution in a
12255          template parameter or in the function type of the function
12256          template results in an invalid type, type deduction fails.  */
12257       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12258       int i, len = TREE_VEC_LENGTH (tparms);
12259       tree converted_args;
12260       bool incomplete = false;
12261
12262       if (explicit_targs == error_mark_node)
12263         return 1;
12264
12265       converted_args
12266         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12267                                   /*require_all_args=*/false,
12268                                   /*use_default_args=*/false));
12269       if (converted_args == error_mark_node)
12270         return 1;
12271
12272       /* Substitute the explicit args into the function type.  This is
12273          necessary so that, for instance, explicitly declared function
12274          arguments can match null pointed constants.  If we were given
12275          an incomplete set of explicit args, we must not do semantic
12276          processing during substitution as we could create partial
12277          instantiations.  */
12278       for (i = 0; i < len; i++)
12279         {
12280           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12281           bool parameter_pack = false;
12282
12283           /* Dig out the actual parm.  */
12284           if (TREE_CODE (parm) == TYPE_DECL
12285               || TREE_CODE (parm) == TEMPLATE_DECL)
12286             {
12287               parm = TREE_TYPE (parm);
12288               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12289             }
12290           else if (TREE_CODE (parm) == PARM_DECL)
12291             {
12292               parm = DECL_INITIAL (parm);
12293               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12294             }
12295
12296           if (parameter_pack)
12297             {
12298               int level, idx;
12299               tree targ;
12300               template_parm_level_and_index (parm, &level, &idx);
12301
12302               /* Mark the argument pack as "incomplete". We could
12303                  still deduce more arguments during unification.  */
12304               targ = TMPL_ARG (converted_args, level, idx);
12305               if (targ)
12306                 {
12307                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12308                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12309                     = ARGUMENT_PACK_ARGS (targ);
12310                 }
12311
12312               /* We have some incomplete argument packs.  */
12313               incomplete_argument_packs_p = true;
12314             }
12315         }
12316
12317       if (incomplete_argument_packs_p)
12318         /* Any substitution is guaranteed to be incomplete if there
12319            are incomplete argument packs, because we can still deduce
12320            more arguments.  */
12321         incomplete = 1;
12322       else
12323         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12324
12325       processing_template_decl += incomplete;
12326       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12327       processing_template_decl -= incomplete;
12328
12329       if (fntype == error_mark_node)
12330         return 1;
12331
12332       /* Place the explicitly specified arguments in TARGS.  */
12333       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12334         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12335     }
12336
12337   /* Never do unification on the 'this' parameter.  */
12338   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12339
12340   if (return_type)
12341     {
12342       tree *new_args;
12343
12344       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12345       new_args = XALLOCAVEC (tree, nargs + 1);
12346       new_args[0] = return_type;
12347       memcpy (new_args + 1, args, nargs * sizeof (tree));
12348       args = new_args;
12349       ++nargs;
12350     }
12351
12352   /* We allow incomplete unification without an error message here
12353      because the standard doesn't seem to explicitly prohibit it.  Our
12354      callers must be ready to deal with unification failures in any
12355      event.  */
12356   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12357                                   targs, parms, args, nargs, /*subr=*/0,
12358                                   strict, flags);
12359
12360   if (result == 0 && incomplete_argument_packs_p)
12361     {
12362       int i, len = NUM_TMPL_ARGS (targs);
12363
12364       /* Clear the "incomplete" flags on all argument packs.  */
12365       for (i = 0; i < len; i++)
12366         {
12367           tree arg = TREE_VEC_ELT (targs, i);
12368           if (ARGUMENT_PACK_P (arg))
12369             {
12370               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12371               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12372             }
12373         }
12374     }
12375
12376   /* Now that we have bindings for all of the template arguments,
12377      ensure that the arguments deduced for the template template
12378      parameters have compatible template parameter lists.  We cannot
12379      check this property before we have deduced all template
12380      arguments, because the template parameter types of a template
12381      template parameter might depend on prior template parameters
12382      deduced after the template template parameter.  The following
12383      ill-formed example illustrates this issue:
12384
12385        template<typename T, template<T> class C> void f(C<5>, T);
12386
12387        template<int N> struct X {};
12388
12389        void g() {
12390          f(X<5>(), 5l); // error: template argument deduction fails
12391        }
12392
12393      The template parameter list of 'C' depends on the template type
12394      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
12395      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
12396      time that we deduce 'C'.  */
12397   if (result == 0
12398       && !template_template_parm_bindings_ok_p 
12399            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
12400     return 1;
12401
12402   if (result == 0)
12403     /* All is well so far.  Now, check:
12404
12405        [temp.deduct]
12406
12407        When all template arguments have been deduced, all uses of
12408        template parameters in nondeduced contexts are replaced with
12409        the corresponding deduced argument values.  If the
12410        substitution results in an invalid type, as described above,
12411        type deduction fails.  */
12412     {
12413       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
12414       if (substed == error_mark_node)
12415         return 1;
12416
12417       /* If we're looking for an exact match, check that what we got
12418          is indeed an exact match.  It might not be if some template
12419          parameters are used in non-deduced contexts.  */
12420       if (strict == DEDUCE_EXACT)
12421         {
12422           unsigned int i;
12423
12424           tree sarg
12425             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
12426           if (return_type)
12427             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
12428           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
12429             if (!same_type_p (args[i], TREE_VALUE (sarg)))
12430               return 1;
12431         }
12432     }
12433
12434   return result;
12435 }
12436
12437 /* Adjust types before performing type deduction, as described in
12438    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
12439    sections are symmetric.  PARM is the type of a function parameter
12440    or the return type of the conversion function.  ARG is the type of
12441    the argument passed to the call, or the type of the value
12442    initialized with the result of the conversion function.
12443    ARG_EXPR is the original argument expression, which may be null.  */
12444
12445 static int
12446 maybe_adjust_types_for_deduction (unification_kind_t strict,
12447                                   tree* parm,
12448                                   tree* arg,
12449                                   tree arg_expr)
12450 {
12451   int result = 0;
12452
12453   switch (strict)
12454     {
12455     case DEDUCE_CALL:
12456       break;
12457
12458     case DEDUCE_CONV:
12459       {
12460         /* Swap PARM and ARG throughout the remainder of this
12461            function; the handling is precisely symmetric since PARM
12462            will initialize ARG rather than vice versa.  */
12463         tree* temp = parm;
12464         parm = arg;
12465         arg = temp;
12466         break;
12467       }
12468
12469     case DEDUCE_EXACT:
12470       /* There is nothing to do in this case.  */
12471       return 0;
12472
12473     default:
12474       gcc_unreachable ();
12475     }
12476
12477   if (TREE_CODE (*parm) != REFERENCE_TYPE)
12478     {
12479       /* [temp.deduct.call]
12480
12481          If P is not a reference type:
12482
12483          --If A is an array type, the pointer type produced by the
12484          array-to-pointer standard conversion (_conv.array_) is
12485          used in place of A for type deduction; otherwise,
12486
12487          --If A is a function type, the pointer type produced by
12488          the function-to-pointer standard conversion
12489          (_conv.func_) is used in place of A for type deduction;
12490          otherwise,
12491
12492          --If A is a cv-qualified type, the top level
12493          cv-qualifiers of A's type are ignored for type
12494          deduction.  */
12495       if (TREE_CODE (*arg) == ARRAY_TYPE)
12496         *arg = build_pointer_type (TREE_TYPE (*arg));
12497       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
12498         *arg = build_pointer_type (*arg);
12499       else
12500         *arg = TYPE_MAIN_VARIANT (*arg);
12501     }
12502
12503   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
12504      of the form T&&, where T is a template parameter, and the argument
12505      is an lvalue, T is deduced as A& */
12506   if (TREE_CODE (*parm) == REFERENCE_TYPE
12507       && TYPE_REF_IS_RVALUE (*parm)
12508       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
12509       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
12510       && arg_expr && real_lvalue_p (arg_expr))
12511     *arg = build_reference_type (*arg);
12512
12513   /* [temp.deduct.call]
12514
12515      If P is a cv-qualified type, the top level cv-qualifiers
12516      of P's type are ignored for type deduction.  If P is a
12517      reference type, the type referred to by P is used for
12518      type deduction.  */
12519   *parm = TYPE_MAIN_VARIANT (*parm);
12520   if (TREE_CODE (*parm) == REFERENCE_TYPE)
12521     {
12522       *parm = TREE_TYPE (*parm);
12523       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12524     }
12525
12526   /* DR 322. For conversion deduction, remove a reference type on parm
12527      too (which has been swapped into ARG).  */
12528   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
12529     *arg = TREE_TYPE (*arg);
12530
12531   return result;
12532 }
12533
12534 /* Most parms like fn_type_unification.
12535
12536    If SUBR is 1, we're being called recursively (to unify the
12537    arguments of a function or method parameter of a function
12538    template). */
12539
12540 static int
12541 type_unification_real (tree tparms,
12542                        tree targs,
12543                        tree xparms,
12544                        const tree *xargs,
12545                        unsigned int xnargs,
12546                        int subr,
12547                        unification_kind_t strict,
12548                        int flags)
12549 {
12550   tree parm, arg, arg_expr;
12551   int i;
12552   int ntparms = TREE_VEC_LENGTH (tparms);
12553   int sub_strict;
12554   int saw_undeduced = 0;
12555   tree parms;
12556   const tree *args;
12557   unsigned int nargs;
12558   unsigned int ia;
12559
12560   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
12561   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
12562   gcc_assert (ntparms > 0);
12563
12564   switch (strict)
12565     {
12566     case DEDUCE_CALL:
12567       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
12568                     | UNIFY_ALLOW_DERIVED);
12569       break;
12570
12571     case DEDUCE_CONV:
12572       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12573       break;
12574
12575     case DEDUCE_EXACT:
12576       sub_strict = UNIFY_ALLOW_NONE;
12577       break;
12578
12579     default:
12580       gcc_unreachable ();
12581     }
12582
12583  again:
12584   parms = xparms;
12585   args = xargs;
12586   nargs = xnargs;
12587
12588   ia = 0;
12589   while (parms && parms != void_list_node
12590          && ia < nargs)
12591     {
12592       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12593         break;
12594
12595       parm = TREE_VALUE (parms);
12596       parms = TREE_CHAIN (parms);
12597       arg = args[ia];
12598       ++ia;
12599       arg_expr = NULL;
12600
12601       if (arg == error_mark_node)
12602         return 1;
12603       if (arg == unknown_type_node)
12604         /* We can't deduce anything from this, but we might get all the
12605            template args from other function args.  */
12606         continue;
12607
12608       /* Conversions will be performed on a function argument that
12609          corresponds with a function parameter that contains only
12610          non-deducible template parameters and explicitly specified
12611          template parameters.  */
12612       if (!uses_template_parms (parm))
12613         {
12614           tree type;
12615
12616           if (!TYPE_P (arg))
12617             type = TREE_TYPE (arg);
12618           else
12619             type = arg;
12620
12621           if (same_type_p (parm, type))
12622             continue;
12623           if (strict != DEDUCE_EXACT
12624               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
12625                                   flags))
12626             continue;
12627
12628           return 1;
12629         }
12630
12631       if (!TYPE_P (arg))
12632         {
12633           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12634           if (type_unknown_p (arg))
12635             {
12636               /* [temp.deduct.type] 
12637
12638                  A template-argument can be deduced from a pointer to
12639                  function or pointer to member function argument if
12640                  the set of overloaded functions does not contain
12641                  function templates and at most one of a set of
12642                  overloaded functions provides a unique match.  */
12643               if (resolve_overloaded_unification
12644                   (tparms, targs, parm, arg, strict, sub_strict))
12645                 continue;
12646
12647               return 1;
12648             }
12649           arg_expr = arg;
12650           arg = unlowered_expr_type (arg);
12651           if (arg == error_mark_node)
12652             return 1;
12653         }
12654
12655       {
12656         int arg_strict = sub_strict;
12657
12658         if (!subr)
12659           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
12660                                                           arg_expr);
12661
12662         if (arg == init_list_type_node && arg_expr)
12663           arg = arg_expr;
12664         if (unify (tparms, targs, parm, arg, arg_strict))
12665           return 1;
12666       }
12667     }
12668
12669
12670   if (parms 
12671       && parms != void_list_node
12672       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12673     {
12674       /* Unify the remaining arguments with the pack expansion type.  */
12675       tree argvec;
12676       tree parmvec = make_tree_vec (1);
12677
12678       /* Allocate a TREE_VEC and copy in all of the arguments */ 
12679       argvec = make_tree_vec (nargs - ia);
12680       for (i = 0; ia < nargs; ++ia, ++i)
12681         TREE_VEC_ELT (argvec, i) = args[ia];
12682
12683       /* Copy the parameter into parmvec.  */
12684       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
12685       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
12686                                 /*call_args_p=*/true, /*subr=*/subr))
12687         return 1;
12688
12689       /* Advance to the end of the list of parameters.  */
12690       parms = TREE_CHAIN (parms);
12691     }
12692
12693   /* Fail if we've reached the end of the parm list, and more args
12694      are present, and the parm list isn't variadic.  */
12695   if (ia < nargs && parms == void_list_node)
12696     return 1;
12697   /* Fail if parms are left and they don't have default values.  */
12698   if (parms && parms != void_list_node
12699       && TREE_PURPOSE (parms) == NULL_TREE)
12700     return 1;
12701
12702   if (!subr)
12703     for (i = 0; i < ntparms; i++)
12704       if (!TREE_VEC_ELT (targs, i))
12705         {
12706           tree tparm;
12707
12708           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
12709             continue;
12710
12711           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12712
12713           /* If this is an undeduced nontype parameter that depends on
12714              a type parameter, try another pass; its type may have been
12715              deduced from a later argument than the one from which
12716              this parameter can be deduced.  */
12717           if (TREE_CODE (tparm) == PARM_DECL
12718               && uses_template_parms (TREE_TYPE (tparm))
12719               && !saw_undeduced++)
12720             goto again;
12721
12722           /* Core issue #226 (C++0x) [temp.deduct]:
12723
12724                If a template argument has not been deduced, its
12725                default template argument, if any, is used. 
12726
12727              When we are in C++98 mode, TREE_PURPOSE will either
12728              be NULL_TREE or ERROR_MARK_NODE, so we do not need
12729              to explicitly check cxx_dialect here.  */
12730           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
12731             {
12732               tree arg = tsubst (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)), 
12733                                  targs, tf_none, NULL_TREE);
12734               if (arg == error_mark_node)
12735                 return 1;
12736               else
12737                 {
12738                   TREE_VEC_ELT (targs, i) = arg;
12739                   continue;
12740                 }
12741             }
12742
12743           /* If the type parameter is a parameter pack, then it will
12744              be deduced to an empty parameter pack.  */
12745           if (template_parameter_pack_p (tparm))
12746             {
12747               tree arg;
12748
12749               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
12750                 {
12751                   arg = make_node (NONTYPE_ARGUMENT_PACK);
12752                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
12753                   TREE_CONSTANT (arg) = 1;
12754                 }
12755               else
12756                 arg = make_node (TYPE_ARGUMENT_PACK);
12757
12758               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
12759
12760               TREE_VEC_ELT (targs, i) = arg;
12761               continue;
12762             }
12763
12764           return 2;
12765         }
12766
12767   return 0;
12768 }
12769
12770 /* Subroutine of type_unification_real.  Args are like the variables
12771    at the call site.  ARG is an overloaded function (or template-id);
12772    we try deducing template args from each of the overloads, and if
12773    only one succeeds, we go with that.  Modifies TARGS and returns
12774    true on success.  */
12775
12776 static bool
12777 resolve_overloaded_unification (tree tparms,
12778                                 tree targs,
12779                                 tree parm,
12780                                 tree arg,
12781                                 unification_kind_t strict,
12782                                 int sub_strict)
12783 {
12784   tree tempargs = copy_node (targs);
12785   int good = 0;
12786   tree goodfn = NULL_TREE;
12787   bool addr_p;
12788
12789   if (TREE_CODE (arg) == ADDR_EXPR)
12790     {
12791       arg = TREE_OPERAND (arg, 0);
12792       addr_p = true;
12793     }
12794   else
12795     addr_p = false;
12796
12797   if (TREE_CODE (arg) == COMPONENT_REF)
12798     /* Handle `&x' where `x' is some static or non-static member
12799        function name.  */
12800     arg = TREE_OPERAND (arg, 1);
12801
12802   if (TREE_CODE (arg) == OFFSET_REF)
12803     arg = TREE_OPERAND (arg, 1);
12804
12805   /* Strip baselink information.  */
12806   if (BASELINK_P (arg))
12807     arg = BASELINK_FUNCTIONS (arg);
12808
12809   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
12810     {
12811       /* If we got some explicit template args, we need to plug them into
12812          the affected templates before we try to unify, in case the
12813          explicit args will completely resolve the templates in question.  */
12814
12815       tree expl_subargs = TREE_OPERAND (arg, 1);
12816       arg = TREE_OPERAND (arg, 0);
12817
12818       for (; arg; arg = OVL_NEXT (arg))
12819         {
12820           tree fn = OVL_CURRENT (arg);
12821           tree subargs, elem;
12822
12823           if (TREE_CODE (fn) != TEMPLATE_DECL)
12824             continue;
12825
12826           ++processing_template_decl;
12827           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
12828                                   expl_subargs, /*check_ret=*/false);
12829           if (subargs)
12830             {
12831               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
12832               if (try_one_overload (tparms, targs, tempargs, parm,
12833                                     elem, strict, sub_strict, addr_p)
12834                   && (!goodfn || !decls_match (goodfn, elem)))
12835                 {
12836                   goodfn = elem;
12837                   ++good;
12838                 }
12839             }
12840           --processing_template_decl;
12841         }
12842     }
12843   else if (TREE_CODE (arg) != OVERLOAD
12844            && TREE_CODE (arg) != FUNCTION_DECL)
12845     /* If ARG is, for example, "(0, &f)" then its type will be unknown
12846        -- but the deduction does not succeed because the expression is
12847        not just the function on its own.  */
12848     return false;
12849   else
12850     for (; arg; arg = OVL_NEXT (arg))
12851       if (try_one_overload (tparms, targs, tempargs, parm,
12852                             TREE_TYPE (OVL_CURRENT (arg)),
12853                             strict, sub_strict, addr_p)
12854           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
12855         {
12856           goodfn = OVL_CURRENT (arg);
12857           ++good;
12858         }
12859
12860   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12861      to function or pointer to member function argument if the set of
12862      overloaded functions does not contain function templates and at most
12863      one of a set of overloaded functions provides a unique match.
12864
12865      So if we found multiple possibilities, we return success but don't
12866      deduce anything.  */
12867
12868   if (good == 1)
12869     {
12870       int i = TREE_VEC_LENGTH (targs);
12871       for (; i--; )
12872         if (TREE_VEC_ELT (tempargs, i))
12873           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
12874     }
12875   if (good)
12876     return true;
12877
12878   return false;
12879 }
12880
12881 /* Subroutine of resolve_overloaded_unification; does deduction for a single
12882    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
12883    different overloads deduce different arguments for a given parm.
12884    ADDR_P is true if the expression for which deduction is being
12885    performed was of the form "& fn" rather than simply "fn".
12886
12887    Returns 1 on success.  */
12888
12889 static int
12890 try_one_overload (tree tparms,
12891                   tree orig_targs,
12892                   tree targs,
12893                   tree parm,
12894                   tree arg,
12895                   unification_kind_t strict,
12896                   int sub_strict,
12897                   bool addr_p)
12898 {
12899   int nargs;
12900   tree tempargs;
12901   int i;
12902
12903   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12904      to function or pointer to member function argument if the set of
12905      overloaded functions does not contain function templates and at most
12906      one of a set of overloaded functions provides a unique match.
12907
12908      So if this is a template, just return success.  */
12909
12910   if (uses_template_parms (arg))
12911     return 1;
12912
12913   if (TREE_CODE (arg) == METHOD_TYPE)
12914     arg = build_ptrmemfunc_type (build_pointer_type (arg));
12915   else if (addr_p)
12916     arg = build_pointer_type (arg);
12917
12918   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
12919
12920   /* We don't copy orig_targs for this because if we have already deduced
12921      some template args from previous args, unify would complain when we
12922      try to deduce a template parameter for the same argument, even though
12923      there isn't really a conflict.  */
12924   nargs = TREE_VEC_LENGTH (targs);
12925   tempargs = make_tree_vec (nargs);
12926
12927   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
12928     return 0;
12929
12930   /* First make sure we didn't deduce anything that conflicts with
12931      explicitly specified args.  */
12932   for (i = nargs; i--; )
12933     {
12934       tree elt = TREE_VEC_ELT (tempargs, i);
12935       tree oldelt = TREE_VEC_ELT (orig_targs, i);
12936
12937       if (!elt)
12938         /*NOP*/;
12939       else if (uses_template_parms (elt))
12940         /* Since we're unifying against ourselves, we will fill in
12941            template args used in the function parm list with our own
12942            template parms.  Discard them.  */
12943         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
12944       else if (oldelt && !template_args_equal (oldelt, elt))
12945         return 0;
12946     }
12947
12948   for (i = nargs; i--; )
12949     {
12950       tree elt = TREE_VEC_ELT (tempargs, i);
12951
12952       if (elt)
12953         TREE_VEC_ELT (targs, i) = elt;
12954     }
12955
12956   return 1;
12957 }
12958
12959 /* PARM is a template class (perhaps with unbound template
12960    parameters).  ARG is a fully instantiated type.  If ARG can be
12961    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
12962    TARGS are as for unify.  */
12963
12964 static tree
12965 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
12966 {
12967   tree copy_of_targs;
12968
12969   if (!CLASSTYPE_TEMPLATE_INFO (arg)
12970       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
12971           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
12972     return NULL_TREE;
12973
12974   /* We need to make a new template argument vector for the call to
12975      unify.  If we used TARGS, we'd clutter it up with the result of
12976      the attempted unification, even if this class didn't work out.
12977      We also don't want to commit ourselves to all the unifications
12978      we've already done, since unification is supposed to be done on
12979      an argument-by-argument basis.  In other words, consider the
12980      following pathological case:
12981
12982        template <int I, int J, int K>
12983        struct S {};
12984
12985        template <int I, int J>
12986        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
12987
12988        template <int I, int J, int K>
12989        void f(S<I, J, K>, S<I, I, I>);
12990
12991        void g() {
12992          S<0, 0, 0> s0;
12993          S<0, 1, 2> s2;
12994
12995          f(s0, s2);
12996        }
12997
12998      Now, by the time we consider the unification involving `s2', we
12999      already know that we must have `f<0, 0, 0>'.  But, even though
13000      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
13001      because there are two ways to unify base classes of S<0, 1, 2>
13002      with S<I, I, I>.  If we kept the already deduced knowledge, we
13003      would reject the possibility I=1.  */
13004   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
13005
13006   /* If unification failed, we're done.  */
13007   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
13008              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
13009     return NULL_TREE;
13010
13011   return arg;
13012 }
13013
13014 /* Given a template type PARM and a class type ARG, find the unique
13015    base type in ARG that is an instance of PARM.  We do not examine
13016    ARG itself; only its base-classes.  If there is not exactly one
13017    appropriate base class, return NULL_TREE.  PARM may be the type of
13018    a partial specialization, as well as a plain template type.  Used
13019    by unify.  */
13020
13021 static tree
13022 get_template_base (tree tparms, tree targs, tree parm, tree arg)
13023 {
13024   tree rval = NULL_TREE;
13025   tree binfo;
13026
13027   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
13028
13029   binfo = TYPE_BINFO (complete_type (arg));
13030   if (!binfo)
13031     /* The type could not be completed.  */
13032     return NULL_TREE;
13033
13034   /* Walk in inheritance graph order.  The search order is not
13035      important, and this avoids multiple walks of virtual bases.  */
13036   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
13037     {
13038       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
13039
13040       if (r)
13041         {
13042           /* If there is more than one satisfactory baseclass, then:
13043
13044                [temp.deduct.call]
13045
13046               If they yield more than one possible deduced A, the type
13047               deduction fails.
13048
13049              applies.  */
13050           if (rval && !same_type_p (r, rval))
13051             return NULL_TREE;
13052
13053           rval = r;
13054         }
13055     }
13056
13057   return rval;
13058 }
13059
13060 /* Returns the level of DECL, which declares a template parameter.  */
13061
13062 static int
13063 template_decl_level (tree decl)
13064 {
13065   switch (TREE_CODE (decl))
13066     {
13067     case TYPE_DECL:
13068     case TEMPLATE_DECL:
13069       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
13070
13071     case PARM_DECL:
13072       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
13073
13074     default:
13075       gcc_unreachable ();
13076     }
13077   return 0;
13078 }
13079
13080 /* Decide whether ARG can be unified with PARM, considering only the
13081    cv-qualifiers of each type, given STRICT as documented for unify.
13082    Returns nonzero iff the unification is OK on that basis.  */
13083
13084 static int
13085 check_cv_quals_for_unify (int strict, tree arg, tree parm)
13086 {
13087   int arg_quals = cp_type_quals (arg);
13088   int parm_quals = cp_type_quals (parm);
13089
13090   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13091       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13092     {
13093       /*  Although a CVR qualifier is ignored when being applied to a
13094           substituted template parameter ([8.3.2]/1 for example), that
13095           does not apply during deduction [14.8.2.4]/1, (even though
13096           that is not explicitly mentioned, [14.8.2.4]/9 indicates
13097           this).  Except when we're allowing additional CV qualifiers
13098           at the outer level [14.8.2.1]/3,1st bullet.  */
13099       if ((TREE_CODE (arg) == REFERENCE_TYPE
13100            || TREE_CODE (arg) == FUNCTION_TYPE
13101            || TREE_CODE (arg) == METHOD_TYPE)
13102           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
13103         return 0;
13104
13105       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
13106           && (parm_quals & TYPE_QUAL_RESTRICT))
13107         return 0;
13108     }
13109
13110   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13111       && (arg_quals & parm_quals) != parm_quals)
13112     return 0;
13113
13114   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
13115       && (parm_quals & arg_quals) != arg_quals)
13116     return 0;
13117
13118   return 1;
13119 }
13120
13121 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
13122 void 
13123 template_parm_level_and_index (tree parm, int* level, int* index)
13124 {
13125   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13126       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13127       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13128     {
13129       *index = TEMPLATE_TYPE_IDX (parm);
13130       *level = TEMPLATE_TYPE_LEVEL (parm);
13131     }
13132   else
13133     {
13134       *index = TEMPLATE_PARM_IDX (parm);
13135       *level = TEMPLATE_PARM_LEVEL (parm);
13136     }
13137 }
13138
13139 /* Unifies the remaining arguments in PACKED_ARGS with the pack
13140    expansion at the end of PACKED_PARMS. Returns 0 if the type
13141    deduction succeeds, 1 otherwise. STRICT is the same as in
13142    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
13143    call argument list. We'll need to adjust the arguments to make them
13144    types. SUBR tells us if this is from a recursive call to
13145    type_unification_real.  */
13146 int
13147 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
13148                       tree packed_args, int strict, bool call_args_p,
13149                       bool subr)
13150 {
13151   tree parm 
13152     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
13153   tree pattern = PACK_EXPANSION_PATTERN (parm);
13154   tree pack, packs = NULL_TREE;
13155   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
13156   int len = TREE_VEC_LENGTH (packed_args);
13157
13158   /* Determine the parameter packs we will be deducing from the
13159      pattern, and record their current deductions.  */
13160   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
13161        pack; pack = TREE_CHAIN (pack))
13162     {
13163       tree parm_pack = TREE_VALUE (pack);
13164       int idx, level;
13165
13166       /* Determine the index and level of this parameter pack.  */
13167       template_parm_level_and_index (parm_pack, &level, &idx);
13168
13169       /* Keep track of the parameter packs and their corresponding
13170          argument packs.  */
13171       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
13172       TREE_TYPE (packs) = make_tree_vec (len - start);
13173     }
13174   
13175   /* Loop through all of the arguments that have not yet been
13176      unified and unify each with the pattern.  */
13177   for (i = start; i < len; i++)
13178     {
13179       tree parm = pattern;
13180
13181       /* For each parameter pack, clear out the deduced value so that
13182          we can deduce it again.  */
13183       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13184         {
13185           int idx, level;
13186           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13187
13188           TMPL_ARG (targs, level, idx) = NULL_TREE;
13189         }
13190
13191       /* Unify the pattern with the current argument.  */
13192       {
13193         tree arg = TREE_VEC_ELT (packed_args, i);
13194         tree arg_expr = NULL_TREE;
13195         int arg_strict = strict;
13196         bool skip_arg_p = false;
13197
13198         if (call_args_p)
13199           {
13200             int sub_strict;
13201
13202             /* This mirrors what we do in type_unification_real.  */
13203             switch (strict)
13204               {
13205               case DEDUCE_CALL:
13206                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
13207                               | UNIFY_ALLOW_MORE_CV_QUAL
13208                               | UNIFY_ALLOW_DERIVED);
13209                 break;
13210                 
13211               case DEDUCE_CONV:
13212                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13213                 break;
13214                 
13215               case DEDUCE_EXACT:
13216                 sub_strict = UNIFY_ALLOW_NONE;
13217                 break;
13218                 
13219               default:
13220                 gcc_unreachable ();
13221               }
13222
13223             if (!TYPE_P (arg))
13224               {
13225                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13226                 if (type_unknown_p (arg))
13227                   {
13228                     /* [temp.deduct.type] A template-argument can be
13229                        deduced from a pointer to function or pointer
13230                        to member function argument if the set of
13231                        overloaded functions does not contain function
13232                        templates and at most one of a set of
13233                        overloaded functions provides a unique
13234                        match.  */
13235
13236                     if (resolve_overloaded_unification
13237                         (tparms, targs, parm, arg,
13238                          (unification_kind_t) strict,
13239                          sub_strict)
13240                         != 0)
13241                       return 1;
13242                     skip_arg_p = true;
13243                   }
13244
13245                 if (!skip_arg_p)
13246                   {
13247                     arg_expr = arg;
13248                     arg = unlowered_expr_type (arg);
13249                     if (arg == error_mark_node)
13250                       return 1;
13251                   }
13252               }
13253       
13254             arg_strict = sub_strict;
13255
13256             if (!subr)
13257               arg_strict |= 
13258                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
13259                                                   &parm, &arg, arg_expr);
13260           }
13261
13262         if (!skip_arg_p)
13263           {
13264             if (unify (tparms, targs, parm, arg, arg_strict))
13265               return 1;
13266           }
13267       }
13268
13269       /* For each parameter pack, collect the deduced value.  */
13270       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13271         {
13272           int idx, level;
13273           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13274
13275           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
13276             TMPL_ARG (targs, level, idx);
13277         }
13278     }
13279
13280   /* Verify that the results of unification with the parameter packs
13281      produce results consistent with what we've seen before, and make
13282      the deduced argument packs available.  */
13283   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13284     {
13285       tree old_pack = TREE_VALUE (pack);
13286       tree new_args = TREE_TYPE (pack);
13287       int i, len = TREE_VEC_LENGTH (new_args);
13288       bool nondeduced_p = false;
13289
13290       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
13291          actually deduce anything.  */
13292       for (i = 0; i < len && !nondeduced_p; ++i)
13293         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
13294           nondeduced_p = true;
13295       if (nondeduced_p)
13296         continue;
13297
13298       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
13299         {
13300           /* Prepend the explicit arguments onto NEW_ARGS.  */
13301           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13302           tree old_args = new_args;
13303           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
13304           int len = explicit_len + TREE_VEC_LENGTH (old_args);
13305
13306           /* Copy the explicit arguments.  */
13307           new_args = make_tree_vec (len);
13308           for (i = 0; i < explicit_len; i++)
13309             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
13310
13311           /* Copy the deduced arguments.  */
13312           for (; i < len; i++)
13313             TREE_VEC_ELT (new_args, i) =
13314               TREE_VEC_ELT (old_args, i - explicit_len);
13315         }
13316
13317       if (!old_pack)
13318         {
13319           tree result;
13320           int idx, level;
13321           
13322           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13323
13324           /* Build the deduced *_ARGUMENT_PACK.  */
13325           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
13326             {
13327               result = make_node (NONTYPE_ARGUMENT_PACK);
13328               TREE_TYPE (result) = 
13329                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
13330               TREE_CONSTANT (result) = 1;
13331             }
13332           else
13333             result = make_node (TYPE_ARGUMENT_PACK);
13334
13335           SET_ARGUMENT_PACK_ARGS (result, new_args);
13336
13337           /* Note the deduced argument packs for this parameter
13338              pack.  */
13339           TMPL_ARG (targs, level, idx) = result;
13340         }
13341       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
13342                && (ARGUMENT_PACK_ARGS (old_pack) 
13343                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
13344         {
13345           /* We only had the explicitly-provided arguments before, but
13346              now we have a complete set of arguments.  */
13347           int idx, level;
13348           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13349           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13350
13351           /* Keep the original deduced argument pack.  */
13352           TMPL_ARG (targs, level, idx) = old_pack;
13353
13354           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
13355           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
13356           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
13357         }
13358       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
13359                                     new_args))
13360         /* Inconsistent unification of this parameter pack.  */
13361         return 1;
13362       else
13363         {
13364           int idx, level;
13365           
13366           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13367
13368           /* Keep the original deduced argument pack.  */
13369           TMPL_ARG (targs, level, idx) = old_pack;
13370         }
13371     }
13372
13373   return 0;
13374 }
13375
13376 /* Deduce the value of template parameters.  TPARMS is the (innermost)
13377    set of template parameters to a template.  TARGS is the bindings
13378    for those template parameters, as determined thus far; TARGS may
13379    include template arguments for outer levels of template parameters
13380    as well.  PARM is a parameter to a template function, or a
13381    subcomponent of that parameter; ARG is the corresponding argument.
13382    This function attempts to match PARM with ARG in a manner
13383    consistent with the existing assignments in TARGS.  If more values
13384    are deduced, then TARGS is updated.
13385
13386    Returns 0 if the type deduction succeeds, 1 otherwise.  The
13387    parameter STRICT is a bitwise or of the following flags:
13388
13389      UNIFY_ALLOW_NONE:
13390        Require an exact match between PARM and ARG.
13391      UNIFY_ALLOW_MORE_CV_QUAL:
13392        Allow the deduced ARG to be more cv-qualified (by qualification
13393        conversion) than ARG.
13394      UNIFY_ALLOW_LESS_CV_QUAL:
13395        Allow the deduced ARG to be less cv-qualified than ARG.
13396      UNIFY_ALLOW_DERIVED:
13397        Allow the deduced ARG to be a template base class of ARG,
13398        or a pointer to a template base class of the type pointed to by
13399        ARG.
13400      UNIFY_ALLOW_INTEGER:
13401        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
13402        case for more information.
13403      UNIFY_ALLOW_OUTER_LEVEL:
13404        This is the outermost level of a deduction. Used to determine validity
13405        of qualification conversions. A valid qualification conversion must
13406        have const qualified pointers leading up to the inner type which
13407        requires additional CV quals, except at the outer level, where const
13408        is not required [conv.qual]. It would be normal to set this flag in
13409        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
13410      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
13411        This is the outermost level of a deduction, and PARM can be more CV
13412        qualified at this point.
13413      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
13414        This is the outermost level of a deduction, and PARM can be less CV
13415        qualified at this point.  */
13416
13417 static int
13418 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
13419 {
13420   int idx;
13421   tree targ;
13422   tree tparm;
13423   int strict_in = strict;
13424
13425   /* I don't think this will do the right thing with respect to types.
13426      But the only case I've seen it in so far has been array bounds, where
13427      signedness is the only information lost, and I think that will be
13428      okay.  */
13429   while (TREE_CODE (parm) == NOP_EXPR)
13430     parm = TREE_OPERAND (parm, 0);
13431
13432   if (arg == error_mark_node)
13433     return 1;
13434   if (arg == unknown_type_node
13435       || arg == init_list_type_node)
13436     /* We can't deduce anything from this, but we might get all the
13437        template args from other function args.  */
13438     return 0;
13439
13440   /* If PARM uses template parameters, then we can't bail out here,
13441      even if ARG == PARM, since we won't record unifications for the
13442      template parameters.  We might need them if we're trying to
13443      figure out which of two things is more specialized.  */
13444   if (arg == parm && !uses_template_parms (parm))
13445     return 0;
13446
13447   /* Handle init lists early, so the rest of the function can assume
13448      we're dealing with a type. */
13449   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
13450     {
13451       tree elt, elttype;
13452       unsigned i;
13453
13454       if (!is_std_init_list (parm))
13455         /* We can only deduce from an initializer list argument if the
13456            parameter is std::initializer_list; otherwise this is a
13457            non-deduced context. */
13458         return 0;
13459
13460       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
13461
13462       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
13463         {
13464           int elt_strict = strict;
13465           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
13466             {
13467               tree type = TREE_TYPE (elt);
13468               /* It should only be possible to get here for a call.  */
13469               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
13470               elt_strict |= maybe_adjust_types_for_deduction
13471                 (DEDUCE_CALL, &elttype, &type, elt);
13472               elt = type;
13473             }
13474
13475           if (unify (tparms, targs, elttype, elt, elt_strict))
13476             return 1;
13477         }
13478       return 0;
13479     }
13480
13481   /* Immediately reject some pairs that won't unify because of
13482      cv-qualification mismatches.  */
13483   if (TREE_CODE (arg) == TREE_CODE (parm)
13484       && TYPE_P (arg)
13485       /* It is the elements of the array which hold the cv quals of an array
13486          type, and the elements might be template type parms. We'll check
13487          when we recurse.  */
13488       && TREE_CODE (arg) != ARRAY_TYPE
13489       /* We check the cv-qualifiers when unifying with template type
13490          parameters below.  We want to allow ARG `const T' to unify with
13491          PARM `T' for example, when computing which of two templates
13492          is more specialized, for example.  */
13493       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
13494       && !check_cv_quals_for_unify (strict_in, arg, parm))
13495     return 1;
13496
13497   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
13498       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
13499     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
13500   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
13501   strict &= ~UNIFY_ALLOW_DERIVED;
13502   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13503   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
13504
13505   switch (TREE_CODE (parm))
13506     {
13507     case TYPENAME_TYPE:
13508     case SCOPE_REF:
13509     case UNBOUND_CLASS_TEMPLATE:
13510       /* In a type which contains a nested-name-specifier, template
13511          argument values cannot be deduced for template parameters used
13512          within the nested-name-specifier.  */
13513       return 0;
13514
13515     case TEMPLATE_TYPE_PARM:
13516     case TEMPLATE_TEMPLATE_PARM:
13517     case BOUND_TEMPLATE_TEMPLATE_PARM:
13518       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13519       if (tparm == error_mark_node)
13520         return 1;
13521
13522       if (TEMPLATE_TYPE_LEVEL (parm)
13523           != template_decl_level (tparm))
13524         /* The PARM is not one we're trying to unify.  Just check
13525            to see if it matches ARG.  */
13526         return (TREE_CODE (arg) == TREE_CODE (parm)
13527                 && same_type_p (parm, arg)) ? 0 : 1;
13528       idx = TEMPLATE_TYPE_IDX (parm);
13529       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13530       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
13531
13532       /* Check for mixed types and values.  */
13533       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13534            && TREE_CODE (tparm) != TYPE_DECL)
13535           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13536               && TREE_CODE (tparm) != TEMPLATE_DECL))
13537         return 1;
13538
13539       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13540         {
13541           /* ARG must be constructed from a template class or a template
13542              template parameter.  */
13543           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
13544               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
13545             return 1;
13546
13547           {
13548             tree parmvec = TYPE_TI_ARGS (parm);
13549             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
13550             tree parm_parms 
13551               = DECL_INNERMOST_TEMPLATE_PARMS
13552                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
13553             int i, len;
13554             int parm_variadic_p = 0;
13555
13556             /* The resolution to DR150 makes clear that default
13557                arguments for an N-argument may not be used to bind T
13558                to a template template parameter with fewer than N
13559                parameters.  It is not safe to permit the binding of
13560                default arguments as an extension, as that may change
13561                the meaning of a conforming program.  Consider:
13562
13563                   struct Dense { static const unsigned int dim = 1; };
13564
13565                   template <template <typename> class View,
13566                             typename Block>
13567                   void operator+(float, View<Block> const&);
13568
13569                   template <typename Block,
13570                             unsigned int Dim = Block::dim>
13571                   struct Lvalue_proxy { operator float() const; };
13572
13573                   void
13574                   test_1d (void) {
13575                     Lvalue_proxy<Dense> p;
13576                     float b;
13577                     b + p;
13578                   }
13579
13580               Here, if Lvalue_proxy is permitted to bind to View, then
13581               the global operator+ will be used; if they are not, the
13582               Lvalue_proxy will be converted to float.  */
13583             if (coerce_template_parms (parm_parms,
13584                                        argvec,
13585                                        TYPE_TI_TEMPLATE (parm),
13586                                        tf_none,
13587                                        /*require_all_args=*/true,
13588                                        /*use_default_args=*/false)
13589                 == error_mark_node)
13590               return 1;
13591
13592             /* Deduce arguments T, i from TT<T> or TT<i>.
13593                We check each element of PARMVEC and ARGVEC individually
13594                rather than the whole TREE_VEC since they can have
13595                different number of elements.  */
13596
13597             parmvec = expand_template_argument_pack (parmvec);
13598             argvec = expand_template_argument_pack (argvec);
13599
13600             len = TREE_VEC_LENGTH (parmvec);
13601
13602             /* Check if the parameters end in a pack, making them
13603                variadic.  */
13604             if (len > 0
13605                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
13606               parm_variadic_p = 1;
13607             
13608             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
13609               return 1;
13610
13611              for (i = 0; i < len - parm_variadic_p; ++i)
13612               {
13613                 if (unify (tparms, targs,
13614                            TREE_VEC_ELT (parmvec, i),
13615                            TREE_VEC_ELT (argvec, i),
13616                            UNIFY_ALLOW_NONE))
13617                   return 1;
13618               }
13619
13620             if (parm_variadic_p
13621                 && unify_pack_expansion (tparms, targs,
13622                                          parmvec, argvec,
13623                                          UNIFY_ALLOW_NONE,
13624                                          /*call_args_p=*/false,
13625                                          /*subr=*/false))
13626               return 1;
13627           }
13628           arg = TYPE_TI_TEMPLATE (arg);
13629
13630           /* Fall through to deduce template name.  */
13631         }
13632
13633       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13634           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13635         {
13636           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
13637
13638           /* Simple cases: Value already set, does match or doesn't.  */
13639           if (targ != NULL_TREE && template_args_equal (targ, arg))
13640             return 0;
13641           else if (targ)
13642             return 1;
13643         }
13644       else
13645         {
13646           /* If PARM is `const T' and ARG is only `int', we don't have
13647              a match unless we are allowing additional qualification.
13648              If ARG is `const int' and PARM is just `T' that's OK;
13649              that binds `const int' to `T'.  */
13650           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
13651                                          arg, parm))
13652             return 1;
13653
13654           /* Consider the case where ARG is `const volatile int' and
13655              PARM is `const T'.  Then, T should be `volatile int'.  */
13656           arg = cp_build_qualified_type_real
13657             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
13658           if (arg == error_mark_node)
13659             return 1;
13660
13661           /* Simple cases: Value already set, does match or doesn't.  */
13662           if (targ != NULL_TREE && same_type_p (targ, arg))
13663             return 0;
13664           else if (targ)
13665             return 1;
13666
13667           /* Make sure that ARG is not a variable-sized array.  (Note
13668              that were talking about variable-sized arrays (like
13669              `int[n]'), rather than arrays of unknown size (like
13670              `int[]').)  We'll get very confused by such a type since
13671              the bound of the array will not be computable in an
13672              instantiation.  Besides, such types are not allowed in
13673              ISO C++, so we can do as we please here.  */
13674           if (variably_modified_type_p (arg, NULL_TREE))
13675             return 1;
13676
13677           /* Strip typedefs as in convert_template_argument.  */
13678           arg = strip_typedefs (arg);
13679         }
13680
13681       /* If ARG is a parameter pack or an expansion, we cannot unify
13682          against it unless PARM is also a parameter pack.  */
13683       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13684           && !template_parameter_pack_p (parm))
13685         return 1;
13686
13687       /* If the argument deduction results is a METHOD_TYPE,
13688          then there is a problem.
13689          METHOD_TYPE doesn't map to any real C++ type the result of
13690          the deduction can not be of that type.  */
13691       if (TREE_CODE (arg) == METHOD_TYPE)
13692         return 1;
13693
13694       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13695       return 0;
13696
13697     case TEMPLATE_PARM_INDEX:
13698       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13699       if (tparm == error_mark_node)
13700         return 1;
13701
13702       if (TEMPLATE_PARM_LEVEL (parm)
13703           != template_decl_level (tparm))
13704         /* The PARM is not one we're trying to unify.  Just check
13705            to see if it matches ARG.  */
13706         return !(TREE_CODE (arg) == TREE_CODE (parm)
13707                  && cp_tree_equal (parm, arg));
13708
13709       idx = TEMPLATE_PARM_IDX (parm);
13710       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13711
13712       if (targ)
13713         return !cp_tree_equal (targ, arg);
13714
13715       /* [temp.deduct.type] If, in the declaration of a function template
13716          with a non-type template-parameter, the non-type
13717          template-parameter is used in an expression in the function
13718          parameter-list and, if the corresponding template-argument is
13719          deduced, the template-argument type shall match the type of the
13720          template-parameter exactly, except that a template-argument
13721          deduced from an array bound may be of any integral type.
13722          The non-type parameter might use already deduced type parameters.  */
13723       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
13724       if (!TREE_TYPE (arg))
13725         /* Template-parameter dependent expression.  Just accept it for now.
13726            It will later be processed in convert_template_argument.  */
13727         ;
13728       else if (same_type_p (TREE_TYPE (arg), tparm))
13729         /* OK */;
13730       else if ((strict & UNIFY_ALLOW_INTEGER)
13731                && (TREE_CODE (tparm) == INTEGER_TYPE
13732                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
13733         /* Convert the ARG to the type of PARM; the deduced non-type
13734            template argument must exactly match the types of the
13735            corresponding parameter.  */
13736         arg = fold (build_nop (tparm, arg));
13737       else if (uses_template_parms (tparm))
13738         /* We haven't deduced the type of this parameter yet.  Try again
13739            later.  */
13740         return 0;
13741       else
13742         return 1;
13743
13744       /* If ARG is a parameter pack or an expansion, we cannot unify
13745          against it unless PARM is also a parameter pack.  */
13746       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13747           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
13748         return 1;
13749
13750       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13751       return 0;
13752
13753     case PTRMEM_CST:
13754      {
13755         /* A pointer-to-member constant can be unified only with
13756          another constant.  */
13757       if (TREE_CODE (arg) != PTRMEM_CST)
13758         return 1;
13759
13760       /* Just unify the class member. It would be useless (and possibly
13761          wrong, depending on the strict flags) to unify also
13762          PTRMEM_CST_CLASS, because we want to be sure that both parm and
13763          arg refer to the same variable, even if through different
13764          classes. For instance:
13765
13766          struct A { int x; };
13767          struct B : A { };
13768
13769          Unification of &A::x and &B::x must succeed.  */
13770       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
13771                     PTRMEM_CST_MEMBER (arg), strict);
13772      }
13773
13774     case POINTER_TYPE:
13775       {
13776         if (TREE_CODE (arg) != POINTER_TYPE)
13777           return 1;
13778
13779         /* [temp.deduct.call]
13780
13781            A can be another pointer or pointer to member type that can
13782            be converted to the deduced A via a qualification
13783            conversion (_conv.qual_).
13784
13785            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
13786            This will allow for additional cv-qualification of the
13787            pointed-to types if appropriate.  */
13788
13789         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
13790           /* The derived-to-base conversion only persists through one
13791              level of pointers.  */
13792           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
13793
13794         return unify (tparms, targs, TREE_TYPE (parm),
13795                       TREE_TYPE (arg), strict);
13796       }
13797
13798     case REFERENCE_TYPE:
13799       if (TREE_CODE (arg) != REFERENCE_TYPE)
13800         return 1;
13801       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13802                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13803
13804     case ARRAY_TYPE:
13805       if (TREE_CODE (arg) != ARRAY_TYPE)
13806         return 1;
13807       if ((TYPE_DOMAIN (parm) == NULL_TREE)
13808           != (TYPE_DOMAIN (arg) == NULL_TREE))
13809         return 1;
13810       if (TYPE_DOMAIN (parm) != NULL_TREE)
13811         {
13812           tree parm_max;
13813           tree arg_max;
13814           bool parm_cst;
13815           bool arg_cst;
13816
13817           /* Our representation of array types uses "N - 1" as the
13818              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
13819              not an integer constant.  We cannot unify arbitrarily
13820              complex expressions, so we eliminate the MINUS_EXPRs
13821              here.  */
13822           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
13823           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
13824           if (!parm_cst)
13825             {
13826               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
13827               parm_max = TREE_OPERAND (parm_max, 0);
13828             }
13829           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
13830           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
13831           if (!arg_cst)
13832             {
13833               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
13834                  trying to unify the type of a variable with the type
13835                  of a template parameter.  For example:
13836
13837                    template <unsigned int N>
13838                    void f (char (&) [N]);
13839                    int g(); 
13840                    void h(int i) {
13841                      char a[g(i)];
13842                      f(a); 
13843                    }
13844
13845                 Here, the type of the ARG will be "int [g(i)]", and
13846                 may be a SAVE_EXPR, etc.  */
13847               if (TREE_CODE (arg_max) != MINUS_EXPR)
13848                 return 1;
13849               arg_max = TREE_OPERAND (arg_max, 0);
13850             }
13851
13852           /* If only one of the bounds used a MINUS_EXPR, compensate
13853              by adding one to the other bound.  */
13854           if (parm_cst && !arg_cst)
13855             parm_max = fold_build2 (PLUS_EXPR,
13856                                     integer_type_node,
13857                                     parm_max,
13858                                     integer_one_node);
13859           else if (arg_cst && !parm_cst)
13860             arg_max = fold_build2 (PLUS_EXPR,
13861                                    integer_type_node,
13862                                    arg_max,
13863                                    integer_one_node);
13864
13865           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
13866             return 1;
13867         }
13868       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13869                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13870
13871     case REAL_TYPE:
13872     case COMPLEX_TYPE:
13873     case VECTOR_TYPE:
13874     case INTEGER_TYPE:
13875     case BOOLEAN_TYPE:
13876     case ENUMERAL_TYPE:
13877     case VOID_TYPE:
13878       if (TREE_CODE (arg) != TREE_CODE (parm))
13879         return 1;
13880
13881       /* We have already checked cv-qualification at the top of the
13882          function.  */
13883       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
13884         return 1;
13885
13886       /* As far as unification is concerned, this wins.  Later checks
13887          will invalidate it if necessary.  */
13888       return 0;
13889
13890       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
13891       /* Type INTEGER_CST can come from ordinary constant template args.  */
13892     case INTEGER_CST:
13893       while (TREE_CODE (arg) == NOP_EXPR)
13894         arg = TREE_OPERAND (arg, 0);
13895
13896       if (TREE_CODE (arg) != INTEGER_CST)
13897         return 1;
13898       return !tree_int_cst_equal (parm, arg);
13899
13900     case TREE_VEC:
13901       {
13902         int i;
13903         if (TREE_CODE (arg) != TREE_VEC)
13904           return 1;
13905         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
13906           return 1;
13907         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
13908           if (unify (tparms, targs,
13909                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
13910                      UNIFY_ALLOW_NONE))
13911             return 1;
13912         return 0;
13913       }
13914
13915     case RECORD_TYPE:
13916     case UNION_TYPE:
13917       if (TREE_CODE (arg) != TREE_CODE (parm))
13918         return 1;
13919
13920       if (TYPE_PTRMEMFUNC_P (parm))
13921         {
13922           if (!TYPE_PTRMEMFUNC_P (arg))
13923             return 1;
13924
13925           return unify (tparms, targs,
13926                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
13927                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
13928                         strict);
13929         }
13930
13931       if (CLASSTYPE_TEMPLATE_INFO (parm))
13932         {
13933           tree t = NULL_TREE;
13934
13935           if (strict_in & UNIFY_ALLOW_DERIVED)
13936             {
13937               /* First, we try to unify the PARM and ARG directly.  */
13938               t = try_class_unification (tparms, targs,
13939                                          parm, arg);
13940
13941               if (!t)
13942                 {
13943                   /* Fallback to the special case allowed in
13944                      [temp.deduct.call]:
13945
13946                        If P is a class, and P has the form
13947                        template-id, then A can be a derived class of
13948                        the deduced A.  Likewise, if P is a pointer to
13949                        a class of the form template-id, A can be a
13950                        pointer to a derived class pointed to by the
13951                        deduced A.  */
13952                   t = get_template_base (tparms, targs, parm, arg);
13953
13954                   if (!t)
13955                     return 1;
13956                 }
13957             }
13958           else if (CLASSTYPE_TEMPLATE_INFO (arg)
13959                    && (CLASSTYPE_TI_TEMPLATE (parm)
13960                        == CLASSTYPE_TI_TEMPLATE (arg)))
13961             /* Perhaps PARM is something like S<U> and ARG is S<int>.
13962                Then, we should unify `int' and `U'.  */
13963             t = arg;
13964           else
13965             /* There's no chance of unification succeeding.  */
13966             return 1;
13967
13968           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
13969                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
13970         }
13971       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
13972         return 1;
13973       return 0;
13974
13975     case METHOD_TYPE:
13976     case FUNCTION_TYPE:
13977       {
13978         unsigned int nargs;
13979         tree *args;
13980         tree a;
13981         unsigned int i;
13982
13983         if (TREE_CODE (arg) != TREE_CODE (parm))
13984           return 1;
13985
13986         /* CV qualifications for methods can never be deduced, they must
13987            match exactly.  We need to check them explicitly here,
13988            because type_unification_real treats them as any other
13989            cv-qualified parameter.  */
13990         if (TREE_CODE (parm) == METHOD_TYPE
13991             && (!check_cv_quals_for_unify
13992                 (UNIFY_ALLOW_NONE,
13993                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
13994                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
13995           return 1;
13996
13997         if (unify (tparms, targs, TREE_TYPE (parm),
13998                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
13999           return 1;
14000
14001         nargs = list_length (TYPE_ARG_TYPES (arg));
14002         args = XALLOCAVEC (tree, nargs);
14003         for (a = TYPE_ARG_TYPES (arg), i = 0;
14004              a != NULL_TREE && a != void_list_node;
14005              a = TREE_CHAIN (a), ++i)
14006           args[i] = TREE_VALUE (a);
14007         nargs = i;
14008
14009         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
14010                                       args, nargs, 1, DEDUCE_EXACT,
14011                                       LOOKUP_NORMAL);
14012       }
14013
14014     case OFFSET_TYPE:
14015       /* Unify a pointer to member with a pointer to member function, which
14016          deduces the type of the member as a function type. */
14017       if (TYPE_PTRMEMFUNC_P (arg))
14018         {
14019           tree method_type;
14020           tree fntype;
14021           cp_cv_quals cv_quals;
14022
14023           /* Check top-level cv qualifiers */
14024           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
14025             return 1;
14026
14027           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14028                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
14029             return 1;
14030
14031           /* Determine the type of the function we are unifying against. */
14032           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
14033           fntype =
14034             build_function_type (TREE_TYPE (method_type),
14035                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
14036
14037           /* Extract the cv-qualifiers of the member function from the
14038              implicit object parameter and place them on the function
14039              type to be restored later. */
14040           cv_quals =
14041             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
14042           fntype = build_qualified_type (fntype, cv_quals);
14043           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
14044         }
14045
14046       if (TREE_CODE (arg) != OFFSET_TYPE)
14047         return 1;
14048       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14049                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
14050         return 1;
14051       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14052                     strict);
14053
14054     case CONST_DECL:
14055       if (DECL_TEMPLATE_PARM_P (parm))
14056         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
14057       if (arg != integral_constant_value (parm))
14058         return 1;
14059       return 0;
14060
14061     case FIELD_DECL:
14062     case TEMPLATE_DECL:
14063       /* Matched cases are handled by the ARG == PARM test above.  */
14064       return 1;
14065
14066     case TYPE_ARGUMENT_PACK:
14067     case NONTYPE_ARGUMENT_PACK:
14068       {
14069         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
14070         tree packed_args = ARGUMENT_PACK_ARGS (arg);
14071         int i, len = TREE_VEC_LENGTH (packed_parms);
14072         int argslen = TREE_VEC_LENGTH (packed_args);
14073         int parm_variadic_p = 0;
14074
14075         for (i = 0; i < len; ++i)
14076           {
14077             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
14078               {
14079                 if (i == len - 1)
14080                   /* We can unify against something with a trailing
14081                      parameter pack.  */
14082                   parm_variadic_p = 1;
14083                 else
14084                   /* Since there is something following the pack
14085                      expansion, we cannot unify this template argument
14086                      list.  */
14087                   return 0;
14088               }
14089           }
14090           
14091
14092         /* If we don't have enough arguments to satisfy the parameters
14093            (not counting the pack expression at the end), or we have
14094            too many arguments for a parameter list that doesn't end in
14095            a pack expression, we can't unify.  */
14096         if (argslen < (len - parm_variadic_p)
14097             || (argslen > len && !parm_variadic_p))
14098           return 1;
14099
14100         /* Unify all of the parameters that precede the (optional)
14101            pack expression.  */
14102         for (i = 0; i < len - parm_variadic_p; ++i)
14103           {
14104             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
14105                        TREE_VEC_ELT (packed_args, i), strict))
14106               return 1;
14107           }
14108
14109         if (parm_variadic_p)
14110           return unify_pack_expansion (tparms, targs, 
14111                                        packed_parms, packed_args,
14112                                        strict, /*call_args_p=*/false,
14113                                        /*subr=*/false);
14114         return 0;
14115       }
14116
14117       break;
14118
14119     case TYPEOF_TYPE:
14120     case DECLTYPE_TYPE:
14121       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
14122          nodes.  */
14123       return 0;
14124
14125     case ERROR_MARK:
14126       /* Unification fails if we hit an error node.  */
14127       return 1;
14128
14129     default:
14130       gcc_assert (EXPR_P (parm));
14131
14132       /* We must be looking at an expression.  This can happen with
14133          something like:
14134
14135            template <int I>
14136            void foo(S<I>, S<I + 2>);
14137
14138          This is a "nondeduced context":
14139
14140            [deduct.type]
14141
14142            The nondeduced contexts are:
14143
14144            --A type that is a template-id in which one or more of
14145              the template-arguments is an expression that references
14146              a template-parameter.
14147
14148          In these cases, we assume deduction succeeded, but don't
14149          actually infer any unifications.  */
14150
14151       if (!uses_template_parms (parm)
14152           && !template_args_equal (parm, arg))
14153         return 1;
14154       else
14155         return 0;
14156     }
14157 }
14158 \f
14159 /* Note that DECL can be defined in this translation unit, if
14160    required.  */
14161
14162 static void
14163 mark_definable (tree decl)
14164 {
14165   tree clone;
14166   DECL_NOT_REALLY_EXTERN (decl) = 1;
14167   FOR_EACH_CLONE (clone, decl)
14168     DECL_NOT_REALLY_EXTERN (clone) = 1;
14169 }
14170
14171 /* Called if RESULT is explicitly instantiated, or is a member of an
14172    explicitly instantiated class.  */
14173
14174 void
14175 mark_decl_instantiated (tree result, int extern_p)
14176 {
14177   SET_DECL_EXPLICIT_INSTANTIATION (result);
14178
14179   /* If this entity has already been written out, it's too late to
14180      make any modifications.  */
14181   if (TREE_ASM_WRITTEN (result))
14182     return;
14183
14184   if (TREE_CODE (result) != FUNCTION_DECL)
14185     /* The TREE_PUBLIC flag for function declarations will have been
14186        set correctly by tsubst.  */
14187     TREE_PUBLIC (result) = 1;
14188
14189   /* This might have been set by an earlier implicit instantiation.  */
14190   DECL_COMDAT (result) = 0;
14191
14192   if (extern_p)
14193     DECL_NOT_REALLY_EXTERN (result) = 0;
14194   else
14195     {
14196       mark_definable (result);
14197       /* Always make artificials weak.  */
14198       if (DECL_ARTIFICIAL (result) && flag_weak)
14199         comdat_linkage (result);
14200       /* For WIN32 we also want to put explicit instantiations in
14201          linkonce sections.  */
14202       else if (TREE_PUBLIC (result))
14203         maybe_make_one_only (result);
14204     }
14205
14206   /* If EXTERN_P, then this function will not be emitted -- unless
14207      followed by an explicit instantiation, at which point its linkage
14208      will be adjusted.  If !EXTERN_P, then this function will be
14209      emitted here.  In neither circumstance do we want
14210      import_export_decl to adjust the linkage.  */
14211   DECL_INTERFACE_KNOWN (result) = 1;
14212 }
14213
14214 /* Given two function templates PAT1 and PAT2, return:
14215
14216    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
14217    -1 if PAT2 is more specialized than PAT1.
14218    0 if neither is more specialized.
14219
14220    LEN indicates the number of parameters we should consider
14221    (defaulted parameters should not be considered).
14222
14223    The 1998 std underspecified function template partial ordering, and
14224    DR214 addresses the issue.  We take pairs of arguments, one from
14225    each of the templates, and deduce them against each other.  One of
14226    the templates will be more specialized if all the *other*
14227    template's arguments deduce against its arguments and at least one
14228    of its arguments *does* *not* deduce against the other template's
14229    corresponding argument.  Deduction is done as for class templates.
14230    The arguments used in deduction have reference and top level cv
14231    qualifiers removed.  Iff both arguments were originally reference
14232    types *and* deduction succeeds in both directions, the template
14233    with the more cv-qualified argument wins for that pairing (if
14234    neither is more cv-qualified, they both are equal).  Unlike regular
14235    deduction, after all the arguments have been deduced in this way,
14236    we do *not* verify the deduced template argument values can be
14237    substituted into non-deduced contexts, nor do we have to verify
14238    that all template arguments have been deduced.  */
14239
14240 int
14241 more_specialized_fn (tree pat1, tree pat2, int len)
14242 {
14243   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
14244   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
14245   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
14246   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
14247   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
14248   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
14249   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
14250   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
14251   int better1 = 0;
14252   int better2 = 0;
14253
14254   /* Remove the this parameter from non-static member functions.  If
14255      one is a non-static member function and the other is not a static
14256      member function, remove the first parameter from that function
14257      also.  This situation occurs for operator functions where we
14258      locate both a member function (with this pointer) and non-member
14259      operator (with explicit first operand).  */
14260   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
14261     {
14262       len--; /* LEN is the number of significant arguments for DECL1 */
14263       args1 = TREE_CHAIN (args1);
14264       if (!DECL_STATIC_FUNCTION_P (decl2))
14265         args2 = TREE_CHAIN (args2);
14266     }
14267   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
14268     {
14269       args2 = TREE_CHAIN (args2);
14270       if (!DECL_STATIC_FUNCTION_P (decl1))
14271         {
14272           len--;
14273           args1 = TREE_CHAIN (args1);
14274         }
14275     }
14276
14277   /* If only one is a conversion operator, they are unordered.  */
14278   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
14279     return 0;
14280
14281   /* Consider the return type for a conversion function */
14282   if (DECL_CONV_FN_P (decl1))
14283     {
14284       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
14285       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
14286       len++;
14287     }
14288
14289   processing_template_decl++;
14290
14291   while (len--
14292          /* Stop when an ellipsis is seen.  */
14293          && args1 != NULL_TREE && args2 != NULL_TREE)
14294     {
14295       tree arg1 = TREE_VALUE (args1);
14296       tree arg2 = TREE_VALUE (args2);
14297       int deduce1, deduce2;
14298       int quals1 = -1;
14299       int quals2 = -1;
14300
14301       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14302           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14303         {
14304           /* When both arguments are pack expansions, we need only
14305              unify the patterns themselves.  */
14306           arg1 = PACK_EXPANSION_PATTERN (arg1);
14307           arg2 = PACK_EXPANSION_PATTERN (arg2);
14308
14309           /* This is the last comparison we need to do.  */
14310           len = 0;
14311         }
14312
14313       if (TREE_CODE (arg1) == REFERENCE_TYPE)
14314         {
14315           arg1 = TREE_TYPE (arg1);
14316           quals1 = cp_type_quals (arg1);
14317         }
14318
14319       if (TREE_CODE (arg2) == REFERENCE_TYPE)
14320         {
14321           arg2 = TREE_TYPE (arg2);
14322           quals2 = cp_type_quals (arg2);
14323         }
14324
14325       if ((quals1 < 0) != (quals2 < 0))
14326         {
14327           /* Only of the args is a reference, see if we should apply
14328              array/function pointer decay to it.  This is not part of
14329              DR214, but is, IMHO, consistent with the deduction rules
14330              for the function call itself, and with our earlier
14331              implementation of the underspecified partial ordering
14332              rules.  (nathan).  */
14333           if (quals1 >= 0)
14334             {
14335               switch (TREE_CODE (arg1))
14336                 {
14337                 case ARRAY_TYPE:
14338                   arg1 = TREE_TYPE (arg1);
14339                   /* FALLTHROUGH. */
14340                 case FUNCTION_TYPE:
14341                   arg1 = build_pointer_type (arg1);
14342                   break;
14343
14344                 default:
14345                   break;
14346                 }
14347             }
14348           else
14349             {
14350               switch (TREE_CODE (arg2))
14351                 {
14352                 case ARRAY_TYPE:
14353                   arg2 = TREE_TYPE (arg2);
14354                   /* FALLTHROUGH. */
14355                 case FUNCTION_TYPE:
14356                   arg2 = build_pointer_type (arg2);
14357                   break;
14358
14359                 default:
14360                   break;
14361                 }
14362             }
14363         }
14364
14365       arg1 = TYPE_MAIN_VARIANT (arg1);
14366       arg2 = TYPE_MAIN_VARIANT (arg2);
14367
14368       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
14369         {
14370           int i, len2 = list_length (args2);
14371           tree parmvec = make_tree_vec (1);
14372           tree argvec = make_tree_vec (len2);
14373           tree ta = args2;
14374
14375           /* Setup the parameter vector, which contains only ARG1.  */
14376           TREE_VEC_ELT (parmvec, 0) = arg1;
14377
14378           /* Setup the argument vector, which contains the remaining
14379              arguments.  */
14380           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
14381             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14382
14383           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
14384                                            argvec, UNIFY_ALLOW_NONE, 
14385                                            /*call_args_p=*/false, 
14386                                            /*subr=*/0);
14387
14388           /* We cannot deduce in the other direction, because ARG1 is
14389              a pack expansion but ARG2 is not.  */
14390           deduce2 = 0;
14391         }
14392       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14393         {
14394           int i, len1 = list_length (args1);
14395           tree parmvec = make_tree_vec (1);
14396           tree argvec = make_tree_vec (len1);
14397           tree ta = args1;
14398
14399           /* Setup the parameter vector, which contains only ARG1.  */
14400           TREE_VEC_ELT (parmvec, 0) = arg2;
14401
14402           /* Setup the argument vector, which contains the remaining
14403              arguments.  */
14404           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
14405             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14406
14407           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
14408                                            argvec, UNIFY_ALLOW_NONE, 
14409                                            /*call_args_p=*/false, 
14410                                            /*subr=*/0);
14411
14412           /* We cannot deduce in the other direction, because ARG2 is
14413              a pack expansion but ARG1 is not.*/
14414           deduce1 = 0;
14415         }
14416
14417       else
14418         {
14419           /* The normal case, where neither argument is a pack
14420              expansion.  */
14421           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
14422           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
14423         }
14424
14425       if (!deduce1)
14426         better2 = -1;
14427       if (!deduce2)
14428         better1 = -1;
14429       if (better1 < 0 && better2 < 0)
14430         /* We've failed to deduce something in either direction.
14431            These must be unordered.  */
14432         break;
14433
14434       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
14435         {
14436           /* Deduces in both directions, see if quals can
14437              disambiguate.  Pretend the worse one failed to deduce. */
14438           if ((quals1 & quals2) == quals2)
14439             deduce1 = 0;
14440           if ((quals1 & quals2) == quals1)
14441             deduce2 = 0;
14442         }
14443       if (deduce1 && !deduce2 && !better2)
14444         better2 = 1;
14445       if (deduce2 && !deduce1 && !better1)
14446         better1 = 1;
14447
14448       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14449           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14450         /* We have already processed all of the arguments in our
14451            handing of the pack expansion type.  */
14452         len = 0;
14453
14454       args1 = TREE_CHAIN (args1);
14455       args2 = TREE_CHAIN (args2);
14456     }
14457
14458   processing_template_decl--;
14459
14460   /* All things being equal, if the next argument is a pack expansion
14461      for one function but not for the other, prefer the
14462      non-variadic function.  */
14463   if ((better1 > 0) - (better2 > 0) == 0
14464       && args1 && TREE_VALUE (args1)
14465       && args2 && TREE_VALUE (args2))
14466     {
14467       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
14468         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
14469       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
14470         return 1;
14471     }
14472
14473   return (better1 > 0) - (better2 > 0);
14474 }
14475
14476 /* Determine which of two partial specializations is more specialized.
14477
14478    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
14479    to the first partial specialization.  The TREE_VALUE is the
14480    innermost set of template parameters for the partial
14481    specialization.  PAT2 is similar, but for the second template.
14482
14483    Return 1 if the first partial specialization is more specialized;
14484    -1 if the second is more specialized; 0 if neither is more
14485    specialized.
14486
14487    See [temp.class.order] for information about determining which of
14488    two templates is more specialized.  */
14489
14490 static int
14491 more_specialized_class (tree pat1, tree pat2)
14492 {
14493   tree targs;
14494   tree tmpl1, tmpl2;
14495   int winner = 0;
14496   bool any_deductions = false;
14497
14498   tmpl1 = TREE_TYPE (pat1);
14499   tmpl2 = TREE_TYPE (pat2);
14500
14501   /* Just like what happens for functions, if we are ordering between
14502      different class template specializations, we may encounter dependent
14503      types in the arguments, and we need our dependency check functions
14504      to behave correctly.  */
14505   ++processing_template_decl;
14506   targs = get_class_bindings (TREE_VALUE (pat1),
14507                               CLASSTYPE_TI_ARGS (tmpl1),
14508                               CLASSTYPE_TI_ARGS (tmpl2));
14509   if (targs)
14510     {
14511       --winner;
14512       any_deductions = true;
14513     }
14514
14515   targs = get_class_bindings (TREE_VALUE (pat2),
14516                               CLASSTYPE_TI_ARGS (tmpl2),
14517                               CLASSTYPE_TI_ARGS (tmpl1));
14518   if (targs)
14519     {
14520       ++winner;
14521       any_deductions = true;
14522     }
14523   --processing_template_decl;
14524
14525   /* In the case of a tie where at least one of the class templates
14526      has a parameter pack at the end, the template with the most
14527      non-packed parameters wins.  */
14528   if (winner == 0
14529       && any_deductions
14530       && (template_args_variadic_p (TREE_PURPOSE (pat1))
14531           || template_args_variadic_p (TREE_PURPOSE (pat2))))
14532     {
14533       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
14534       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
14535       int len1 = TREE_VEC_LENGTH (args1);
14536       int len2 = TREE_VEC_LENGTH (args2);
14537
14538       /* We don't count the pack expansion at the end.  */
14539       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
14540         --len1;
14541       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
14542         --len2;
14543
14544       if (len1 > len2)
14545         return 1;
14546       else if (len1 < len2)
14547         return -1;
14548     }
14549
14550   return winner;
14551 }
14552
14553 /* Return the template arguments that will produce the function signature
14554    DECL from the function template FN, with the explicit template
14555    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
14556    also match.  Return NULL_TREE if no satisfactory arguments could be
14557    found.  */
14558
14559 static tree
14560 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
14561 {
14562   int ntparms = DECL_NTPARMS (fn);
14563   tree targs = make_tree_vec (ntparms);
14564   tree decl_type;
14565   tree decl_arg_types;
14566   tree *args;
14567   unsigned int nargs, ix;
14568   tree arg;
14569
14570   /* Substitute the explicit template arguments into the type of DECL.
14571      The call to fn_type_unification will handle substitution into the
14572      FN.  */
14573   decl_type = TREE_TYPE (decl);
14574   if (explicit_args && uses_template_parms (decl_type))
14575     {
14576       tree tmpl;
14577       tree converted_args;
14578
14579       if (DECL_TEMPLATE_INFO (decl))
14580         tmpl = DECL_TI_TEMPLATE (decl);
14581       else
14582         /* We can get here for some invalid specializations.  */
14583         return NULL_TREE;
14584
14585       converted_args
14586         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
14587                                  explicit_args, NULL_TREE,
14588                                  tf_none,
14589                                  /*require_all_args=*/false,
14590                                  /*use_default_args=*/false);
14591       if (converted_args == error_mark_node)
14592         return NULL_TREE;
14593
14594       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
14595       if (decl_type == error_mark_node)
14596         return NULL_TREE;
14597     }
14598
14599   /* Never do unification on the 'this' parameter.  */
14600   decl_arg_types = skip_artificial_parms_for (decl, 
14601                                               TYPE_ARG_TYPES (decl_type));
14602
14603   nargs = list_length (decl_arg_types);
14604   args = XALLOCAVEC (tree, nargs);
14605   for (arg = decl_arg_types, ix = 0;
14606        arg != NULL_TREE && arg != void_list_node;
14607        arg = TREE_CHAIN (arg), ++ix)
14608     args[ix] = TREE_VALUE (arg);
14609
14610   if (fn_type_unification (fn, explicit_args, targs,
14611                            args, ix,
14612                            (check_rettype || DECL_CONV_FN_P (fn)
14613                             ? TREE_TYPE (decl_type) : NULL_TREE),
14614                            DEDUCE_EXACT, LOOKUP_NORMAL))
14615     return NULL_TREE;
14616
14617   return targs;
14618 }
14619
14620 /* Return the innermost template arguments that, when applied to a
14621    template specialization whose innermost template parameters are
14622    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
14623    ARGS.
14624
14625    For example, suppose we have:
14626
14627      template <class T, class U> struct S {};
14628      template <class T> struct S<T*, int> {};
14629
14630    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
14631    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
14632    int}.  The resulting vector will be {double}, indicating that `T'
14633    is bound to `double'.  */
14634
14635 static tree
14636 get_class_bindings (tree tparms, tree spec_args, tree args)
14637 {
14638   int i, ntparms = TREE_VEC_LENGTH (tparms);
14639   tree deduced_args;
14640   tree innermost_deduced_args;
14641
14642   innermost_deduced_args = make_tree_vec (ntparms);
14643   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14644     {
14645       deduced_args = copy_node (args);
14646       SET_TMPL_ARGS_LEVEL (deduced_args,
14647                            TMPL_ARGS_DEPTH (deduced_args),
14648                            innermost_deduced_args);
14649     }
14650   else
14651     deduced_args = innermost_deduced_args;
14652
14653   if (unify (tparms, deduced_args,
14654              INNERMOST_TEMPLATE_ARGS (spec_args),
14655              INNERMOST_TEMPLATE_ARGS (args),
14656              UNIFY_ALLOW_NONE))
14657     return NULL_TREE;
14658
14659   for (i =  0; i < ntparms; ++i)
14660     if (! TREE_VEC_ELT (innermost_deduced_args, i))
14661       return NULL_TREE;
14662
14663   /* Verify that nondeduced template arguments agree with the type
14664      obtained from argument deduction.
14665
14666      For example:
14667
14668        struct A { typedef int X; };
14669        template <class T, class U> struct C {};
14670        template <class T> struct C<T, typename T::X> {};
14671
14672      Then with the instantiation `C<A, int>', we can deduce that
14673      `T' is `A' but unify () does not check whether `typename T::X'
14674      is `int'.  */
14675   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
14676   if (spec_args == error_mark_node
14677       /* We only need to check the innermost arguments; the other
14678          arguments will always agree.  */
14679       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
14680                               INNERMOST_TEMPLATE_ARGS (args)))
14681     return NULL_TREE;
14682
14683   /* Now that we have bindings for all of the template arguments,
14684      ensure that the arguments deduced for the template template
14685      parameters have compatible template parameter lists.  See the use
14686      of template_template_parm_bindings_ok_p in fn_type_unification
14687      for more information.  */
14688   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
14689     return NULL_TREE;
14690
14691   return deduced_args;
14692 }
14693
14694 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
14695    Return the TREE_LIST node with the most specialized template, if
14696    any.  If there is no most specialized template, the error_mark_node
14697    is returned.
14698
14699    Note that this function does not look at, or modify, the
14700    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
14701    returned is one of the elements of INSTANTIATIONS, callers may
14702    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
14703    and retrieve it from the value returned.  */
14704
14705 tree
14706 most_specialized_instantiation (tree templates)
14707 {
14708   tree fn, champ;
14709
14710   ++processing_template_decl;
14711
14712   champ = templates;
14713   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
14714     {
14715       int fate = 0;
14716
14717       if (get_bindings (TREE_VALUE (champ),
14718                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14719                         NULL_TREE, /*check_ret=*/false))
14720         fate--;
14721
14722       if (get_bindings (TREE_VALUE (fn),
14723                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14724                         NULL_TREE, /*check_ret=*/false))
14725         fate++;
14726
14727       if (fate == -1)
14728         champ = fn;
14729       else if (!fate)
14730         {
14731           /* Equally specialized, move to next function.  If there
14732              is no next function, nothing's most specialized.  */
14733           fn = TREE_CHAIN (fn);
14734           champ = fn;
14735           if (!fn)
14736             break;
14737         }
14738     }
14739
14740   if (champ)
14741     /* Now verify that champ is better than everything earlier in the
14742        instantiation list.  */
14743     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
14744       if (get_bindings (TREE_VALUE (champ),
14745                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14746                         NULL_TREE, /*check_ret=*/false)
14747           || !get_bindings (TREE_VALUE (fn),
14748                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14749                             NULL_TREE, /*check_ret=*/false))
14750         {
14751           champ = NULL_TREE;
14752           break;
14753         }
14754
14755   processing_template_decl--;
14756
14757   if (!champ)
14758     return error_mark_node;
14759
14760   return champ;
14761 }
14762
14763 /* If DECL is a specialization of some template, return the most
14764    general such template.  Otherwise, returns NULL_TREE.
14765
14766    For example, given:
14767
14768      template <class T> struct S { template <class U> void f(U); };
14769
14770    if TMPL is `template <class U> void S<int>::f(U)' this will return
14771    the full template.  This function will not trace past partial
14772    specializations, however.  For example, given in addition:
14773
14774      template <class T> struct S<T*> { template <class U> void f(U); };
14775
14776    if TMPL is `template <class U> void S<int*>::f(U)' this will return
14777    `template <class T> template <class U> S<T*>::f(U)'.  */
14778
14779 tree
14780 most_general_template (tree decl)
14781 {
14782   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
14783      an immediate specialization.  */
14784   if (TREE_CODE (decl) == FUNCTION_DECL)
14785     {
14786       if (DECL_TEMPLATE_INFO (decl)) {
14787         decl = DECL_TI_TEMPLATE (decl);
14788
14789         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
14790            template friend.  */
14791         if (TREE_CODE (decl) != TEMPLATE_DECL)
14792           return NULL_TREE;
14793       } else
14794         return NULL_TREE;
14795     }
14796
14797   /* Look for more and more general templates.  */
14798   while (DECL_TEMPLATE_INFO (decl))
14799     {
14800       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
14801          (See cp-tree.h for details.)  */
14802       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
14803         break;
14804
14805       if (CLASS_TYPE_P (TREE_TYPE (decl))
14806           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
14807         break;
14808
14809       /* Stop if we run into an explicitly specialized class template.  */
14810       if (!DECL_NAMESPACE_SCOPE_P (decl)
14811           && DECL_CONTEXT (decl)
14812           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
14813         break;
14814
14815       decl = DECL_TI_TEMPLATE (decl);
14816     }
14817
14818   return decl;
14819 }
14820
14821 /* Return the most specialized of the class template partial
14822    specializations of TMPL which can produce TYPE, a specialization of
14823    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
14824    a _TYPE node corresponding to the partial specialization, while the
14825    TREE_PURPOSE is the set of template arguments that must be
14826    substituted into the TREE_TYPE in order to generate TYPE.
14827
14828    If the choice of partial specialization is ambiguous, a diagnostic
14829    is issued, and the error_mark_node is returned.  If there are no
14830    partial specializations of TMPL matching TYPE, then NULL_TREE is
14831    returned.  */
14832
14833 static tree
14834 most_specialized_class (tree type, tree tmpl)
14835 {
14836   tree list = NULL_TREE;
14837   tree t;
14838   tree champ;
14839   int fate;
14840   bool ambiguous_p;
14841   tree args;
14842   tree outer_args = NULL_TREE;
14843
14844   tmpl = most_general_template (tmpl);
14845   args = CLASSTYPE_TI_ARGS (type);
14846
14847   /* For determining which partial specialization to use, only the
14848      innermost args are interesting.  */
14849   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14850     {
14851       outer_args = strip_innermost_template_args (args, 1);
14852       args = INNERMOST_TEMPLATE_ARGS (args);
14853     }
14854
14855   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
14856     {
14857       tree partial_spec_args;
14858       tree spec_args;
14859       tree parms = TREE_VALUE (t);
14860
14861       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
14862       if (outer_args)
14863         {
14864           int i;
14865
14866           ++processing_template_decl;
14867
14868           /* Discard the outer levels of args, and then substitute in the
14869              template args from the enclosing class.  */
14870           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
14871           partial_spec_args = tsubst_template_args
14872             (partial_spec_args, outer_args, tf_none, NULL_TREE);
14873
14874           /* PARMS already refers to just the innermost parms, but the
14875              template parms in partial_spec_args had their levels lowered
14876              by tsubst, so we need to do the same for the parm list.  We
14877              can't just tsubst the TREE_VEC itself, as tsubst wants to
14878              treat a TREE_VEC as an argument vector.  */
14879           parms = copy_node (parms);
14880           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
14881             TREE_VEC_ELT (parms, i) =
14882               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
14883
14884           --processing_template_decl;
14885         }
14886       spec_args = get_class_bindings (parms,
14887                                       partial_spec_args,
14888                                       args);
14889       if (spec_args)
14890         {
14891           if (outer_args)
14892             spec_args = add_to_template_args (outer_args, spec_args);
14893           list = tree_cons (spec_args, TREE_VALUE (t), list);
14894           TREE_TYPE (list) = TREE_TYPE (t);
14895         }
14896     }
14897
14898   if (! list)
14899     return NULL_TREE;
14900
14901   ambiguous_p = false;
14902   t = list;
14903   champ = t;
14904   t = TREE_CHAIN (t);
14905   for (; t; t = TREE_CHAIN (t))
14906     {
14907       fate = more_specialized_class (champ, t);
14908       if (fate == 1)
14909         ;
14910       else
14911         {
14912           if (fate == 0)
14913             {
14914               t = TREE_CHAIN (t);
14915               if (! t)
14916                 {
14917                   ambiguous_p = true;
14918                   break;
14919                 }
14920             }
14921           champ = t;
14922         }
14923     }
14924
14925   if (!ambiguous_p)
14926     for (t = list; t && t != champ; t = TREE_CHAIN (t))
14927       {
14928         fate = more_specialized_class (champ, t);
14929         if (fate != 1)
14930           {
14931             ambiguous_p = true;
14932             break;
14933           }
14934       }
14935
14936   if (ambiguous_p)
14937     {
14938       const char *str = "candidates are:";
14939       error ("ambiguous class template instantiation for %q#T", type);
14940       for (t = list; t; t = TREE_CHAIN (t))
14941         {
14942           error ("%s %+#T", str, TREE_TYPE (t));
14943           str = "               ";
14944         }
14945       return error_mark_node;
14946     }
14947
14948   return champ;
14949 }
14950
14951 /* Explicitly instantiate DECL.  */
14952
14953 void
14954 do_decl_instantiation (tree decl, tree storage)
14955 {
14956   tree result = NULL_TREE;
14957   int extern_p = 0;
14958
14959   if (!decl || decl == error_mark_node)
14960     /* An error occurred, for which grokdeclarator has already issued
14961        an appropriate message.  */
14962     return;
14963   else if (! DECL_LANG_SPECIFIC (decl))
14964     {
14965       error ("explicit instantiation of non-template %q#D", decl);
14966       return;
14967     }
14968   else if (TREE_CODE (decl) == VAR_DECL)
14969     {
14970       /* There is an asymmetry here in the way VAR_DECLs and
14971          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
14972          the latter, the DECL we get back will be marked as a
14973          template instantiation, and the appropriate
14974          DECL_TEMPLATE_INFO will be set up.  This does not happen for
14975          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
14976          should handle VAR_DECLs as it currently handles
14977          FUNCTION_DECLs.  */
14978       if (!DECL_CLASS_SCOPE_P (decl))
14979         {
14980           error ("%qD is not a static data member of a class template", decl);
14981           return;
14982         }
14983       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
14984       if (!result || TREE_CODE (result) != VAR_DECL)
14985         {
14986           error ("no matching template for %qD found", decl);
14987           return;
14988         }
14989       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
14990         {
14991           error ("type %qT for explicit instantiation %qD does not match "
14992                  "declared type %qT", TREE_TYPE (result), decl,
14993                  TREE_TYPE (decl));
14994           return;
14995         }
14996     }
14997   else if (TREE_CODE (decl) != FUNCTION_DECL)
14998     {
14999       error ("explicit instantiation of %q#D", decl);
15000       return;
15001     }
15002   else
15003     result = decl;
15004
15005   /* Check for various error cases.  Note that if the explicit
15006      instantiation is valid the RESULT will currently be marked as an
15007      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
15008      until we get here.  */
15009
15010   if (DECL_TEMPLATE_SPECIALIZATION (result))
15011     {
15012       /* DR 259 [temp.spec].
15013
15014          Both an explicit instantiation and a declaration of an explicit
15015          specialization shall not appear in a program unless the explicit
15016          instantiation follows a declaration of the explicit specialization.
15017
15018          For a given set of template parameters, if an explicit
15019          instantiation of a template appears after a declaration of an
15020          explicit specialization for that template, the explicit
15021          instantiation has no effect.  */
15022       return;
15023     }
15024   else if (DECL_EXPLICIT_INSTANTIATION (result))
15025     {
15026       /* [temp.spec]
15027
15028          No program shall explicitly instantiate any template more
15029          than once.
15030
15031          We check DECL_NOT_REALLY_EXTERN so as not to complain when
15032          the first instantiation was `extern' and the second is not,
15033          and EXTERN_P for the opposite case.  */
15034       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
15035         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
15036       /* If an "extern" explicit instantiation follows an ordinary
15037          explicit instantiation, the template is instantiated.  */
15038       if (extern_p)
15039         return;
15040     }
15041   else if (!DECL_IMPLICIT_INSTANTIATION (result))
15042     {
15043       error ("no matching template for %qD found", result);
15044       return;
15045     }
15046   else if (!DECL_TEMPLATE_INFO (result))
15047     {
15048       permerror (input_location, "explicit instantiation of non-template %q#D", result);
15049       return;
15050     }
15051
15052   if (storage == NULL_TREE)
15053     ;
15054   else if (storage == ridpointers[(int) RID_EXTERN])
15055     {
15056       if (!in_system_header && (cxx_dialect == cxx98))
15057         pedwarn (input_location, OPT_pedantic, 
15058                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
15059                  "instantiations");
15060       extern_p = 1;
15061     }
15062   else
15063     error ("storage class %qD applied to template instantiation", storage);
15064
15065   check_explicit_instantiation_namespace (result);
15066   mark_decl_instantiated (result, extern_p);
15067   if (! extern_p)
15068     instantiate_decl (result, /*defer_ok=*/1,
15069                       /*expl_inst_class_mem_p=*/false);
15070 }
15071
15072 static void
15073 mark_class_instantiated (tree t, int extern_p)
15074 {
15075   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
15076   SET_CLASSTYPE_INTERFACE_KNOWN (t);
15077   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
15078   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
15079   if (! extern_p)
15080     {
15081       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
15082       rest_of_type_compilation (t, 1);
15083     }
15084 }
15085
15086 /* Called from do_type_instantiation through binding_table_foreach to
15087    do recursive instantiation for the type bound in ENTRY.  */
15088 static void
15089 bt_instantiate_type_proc (binding_entry entry, void *data)
15090 {
15091   tree storage = *(tree *) data;
15092
15093   if (MAYBE_CLASS_TYPE_P (entry->type)
15094       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
15095     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
15096 }
15097
15098 /* Called from do_type_instantiation to instantiate a member
15099    (a member function or a static member variable) of an
15100    explicitly instantiated class template.  */
15101 static void
15102 instantiate_class_member (tree decl, int extern_p)
15103 {
15104   mark_decl_instantiated (decl, extern_p);
15105   if (! extern_p)
15106     instantiate_decl (decl, /*defer_ok=*/1,
15107                       /*expl_inst_class_mem_p=*/true);
15108 }
15109
15110 /* Perform an explicit instantiation of template class T.  STORAGE, if
15111    non-null, is the RID for extern, inline or static.  COMPLAIN is
15112    nonzero if this is called from the parser, zero if called recursively,
15113    since the standard is unclear (as detailed below).  */
15114
15115 void
15116 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
15117 {
15118   int extern_p = 0;
15119   int nomem_p = 0;
15120   int static_p = 0;
15121   int previous_instantiation_extern_p = 0;
15122
15123   if (TREE_CODE (t) == TYPE_DECL)
15124     t = TREE_TYPE (t);
15125
15126   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
15127     {
15128       error ("explicit instantiation of non-template type %qT", t);
15129       return;
15130     }
15131
15132   complete_type (t);
15133
15134   if (!COMPLETE_TYPE_P (t))
15135     {
15136       if (complain & tf_error)
15137         error ("explicit instantiation of %q#T before definition of template",
15138                t);
15139       return;
15140     }
15141
15142   if (storage != NULL_TREE)
15143     {
15144       if (!in_system_header)
15145         {
15146           if (storage == ridpointers[(int) RID_EXTERN])
15147             {
15148               if (cxx_dialect == cxx98)
15149                 pedwarn (input_location, OPT_pedantic, 
15150                          "ISO C++ 1998 forbids the use of %<extern%> on "
15151                          "explicit instantiations");
15152             }
15153           else
15154             pedwarn (input_location, OPT_pedantic, 
15155                      "ISO C++ forbids the use of %qE"
15156                      " on explicit instantiations", storage);
15157         }
15158
15159       if (storage == ridpointers[(int) RID_INLINE])
15160         nomem_p = 1;
15161       else if (storage == ridpointers[(int) RID_EXTERN])
15162         extern_p = 1;
15163       else if (storage == ridpointers[(int) RID_STATIC])
15164         static_p = 1;
15165       else
15166         {
15167           error ("storage class %qD applied to template instantiation",
15168                  storage);
15169           extern_p = 0;
15170         }
15171     }
15172
15173   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
15174     {
15175       /* DR 259 [temp.spec].
15176
15177          Both an explicit instantiation and a declaration of an explicit
15178          specialization shall not appear in a program unless the explicit
15179          instantiation follows a declaration of the explicit specialization.
15180
15181          For a given set of template parameters, if an explicit
15182          instantiation of a template appears after a declaration of an
15183          explicit specialization for that template, the explicit
15184          instantiation has no effect.  */
15185       return;
15186     }
15187   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
15188     {
15189       /* [temp.spec]
15190
15191          No program shall explicitly instantiate any template more
15192          than once.
15193
15194          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
15195          instantiation was `extern'.  If EXTERN_P then the second is.
15196          These cases are OK.  */
15197       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
15198
15199       if (!previous_instantiation_extern_p && !extern_p
15200           && (complain & tf_error))
15201         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
15202
15203       /* If we've already instantiated the template, just return now.  */
15204       if (!CLASSTYPE_INTERFACE_ONLY (t))
15205         return;
15206     }
15207
15208   check_explicit_instantiation_namespace (TYPE_NAME (t));
15209   mark_class_instantiated (t, extern_p);
15210
15211   if (nomem_p)
15212     return;
15213
15214   {
15215     tree tmp;
15216
15217     /* In contrast to implicit instantiation, where only the
15218        declarations, and not the definitions, of members are
15219        instantiated, we have here:
15220
15221          [temp.explicit]
15222
15223          The explicit instantiation of a class template specialization
15224          implies the instantiation of all of its members not
15225          previously explicitly specialized in the translation unit
15226          containing the explicit instantiation.
15227
15228        Of course, we can't instantiate member template classes, since
15229        we don't have any arguments for them.  Note that the standard
15230        is unclear on whether the instantiation of the members are
15231        *explicit* instantiations or not.  However, the most natural
15232        interpretation is that it should be an explicit instantiation.  */
15233
15234     if (! static_p)
15235       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
15236         if (TREE_CODE (tmp) == FUNCTION_DECL
15237             && DECL_TEMPLATE_INSTANTIATION (tmp))
15238           instantiate_class_member (tmp, extern_p);
15239
15240     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
15241       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
15242         instantiate_class_member (tmp, extern_p);
15243
15244     if (CLASSTYPE_NESTED_UTDS (t))
15245       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
15246                              bt_instantiate_type_proc, &storage);
15247   }
15248 }
15249
15250 /* Given a function DECL, which is a specialization of TMPL, modify
15251    DECL to be a re-instantiation of TMPL with the same template
15252    arguments.  TMPL should be the template into which tsubst'ing
15253    should occur for DECL, not the most general template.
15254
15255    One reason for doing this is a scenario like this:
15256
15257      template <class T>
15258      void f(const T&, int i);
15259
15260      void g() { f(3, 7); }
15261
15262      template <class T>
15263      void f(const T& t, const int i) { }
15264
15265    Note that when the template is first instantiated, with
15266    instantiate_template, the resulting DECL will have no name for the
15267    first parameter, and the wrong type for the second.  So, when we go
15268    to instantiate the DECL, we regenerate it.  */
15269
15270 static void
15271 regenerate_decl_from_template (tree decl, tree tmpl)
15272 {
15273   /* The arguments used to instantiate DECL, from the most general
15274      template.  */
15275   tree args;
15276   tree code_pattern;
15277
15278   args = DECL_TI_ARGS (decl);
15279   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
15280
15281   /* Make sure that we can see identifiers, and compute access
15282      correctly.  */
15283   push_access_scope (decl);
15284
15285   if (TREE_CODE (decl) == FUNCTION_DECL)
15286     {
15287       tree decl_parm;
15288       tree pattern_parm;
15289       tree specs;
15290       int args_depth;
15291       int parms_depth;
15292
15293       args_depth = TMPL_ARGS_DEPTH (args);
15294       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
15295       if (args_depth > parms_depth)
15296         args = get_innermost_template_args (args, parms_depth);
15297
15298       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
15299                                               args, tf_error, NULL_TREE);
15300       if (specs)
15301         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
15302                                                     specs);
15303
15304       /* Merge parameter declarations.  */
15305       decl_parm = skip_artificial_parms_for (decl,
15306                                              DECL_ARGUMENTS (decl));
15307       pattern_parm
15308         = skip_artificial_parms_for (code_pattern,
15309                                      DECL_ARGUMENTS (code_pattern));
15310       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
15311         {
15312           tree parm_type;
15313           tree attributes;
15314           
15315           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15316             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
15317           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
15318                               NULL_TREE);
15319           parm_type = type_decays_to (parm_type);
15320           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15321             TREE_TYPE (decl_parm) = parm_type;
15322           attributes = DECL_ATTRIBUTES (pattern_parm);
15323           if (DECL_ATTRIBUTES (decl_parm) != attributes)
15324             {
15325               DECL_ATTRIBUTES (decl_parm) = attributes;
15326               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15327             }
15328           decl_parm = TREE_CHAIN (decl_parm);
15329           pattern_parm = TREE_CHAIN (pattern_parm);
15330         }
15331       /* Merge any parameters that match with the function parameter
15332          pack.  */
15333       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
15334         {
15335           int i, len;
15336           tree expanded_types;
15337           /* Expand the TYPE_PACK_EXPANSION that provides the types for
15338              the parameters in this function parameter pack.  */
15339           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
15340                                                  args, tf_error, NULL_TREE);
15341           len = TREE_VEC_LENGTH (expanded_types);
15342           for (i = 0; i < len; i++)
15343             {
15344               tree parm_type;
15345               tree attributes;
15346           
15347               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15348                 /* Rename the parameter to include the index.  */
15349                 DECL_NAME (decl_parm) = 
15350                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
15351               parm_type = TREE_VEC_ELT (expanded_types, i);
15352               parm_type = type_decays_to (parm_type);
15353               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15354                 TREE_TYPE (decl_parm) = parm_type;
15355               attributes = DECL_ATTRIBUTES (pattern_parm);
15356               if (DECL_ATTRIBUTES (decl_parm) != attributes)
15357                 {
15358                   DECL_ATTRIBUTES (decl_parm) = attributes;
15359                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15360                 }
15361               decl_parm = TREE_CHAIN (decl_parm);
15362             }
15363         }
15364       /* Merge additional specifiers from the CODE_PATTERN.  */
15365       if (DECL_DECLARED_INLINE_P (code_pattern)
15366           && !DECL_DECLARED_INLINE_P (decl))
15367         DECL_DECLARED_INLINE_P (decl) = 1;
15368     }
15369   else if (TREE_CODE (decl) == VAR_DECL)
15370     DECL_INITIAL (decl) =
15371       tsubst_expr (DECL_INITIAL (code_pattern), args,
15372                    tf_error, DECL_TI_TEMPLATE (decl),
15373                    /*integral_constant_expression_p=*/false);
15374   else
15375     gcc_unreachable ();
15376
15377   pop_access_scope (decl);
15378 }
15379
15380 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
15381    substituted to get DECL.  */
15382
15383 tree
15384 template_for_substitution (tree decl)
15385 {
15386   tree tmpl = DECL_TI_TEMPLATE (decl);
15387
15388   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
15389      for the instantiation.  This is not always the most general
15390      template.  Consider, for example:
15391
15392         template <class T>
15393         struct S { template <class U> void f();
15394                    template <> void f<int>(); };
15395
15396      and an instantiation of S<double>::f<int>.  We want TD to be the
15397      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
15398   while (/* An instantiation cannot have a definition, so we need a
15399             more general template.  */
15400          DECL_TEMPLATE_INSTANTIATION (tmpl)
15401            /* We must also deal with friend templates.  Given:
15402
15403                 template <class T> struct S {
15404                   template <class U> friend void f() {};
15405                 };
15406
15407               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
15408               so far as the language is concerned, but that's still
15409               where we get the pattern for the instantiation from.  On
15410               other hand, if the definition comes outside the class, say:
15411
15412                 template <class T> struct S {
15413                   template <class U> friend void f();
15414                 };
15415                 template <class U> friend void f() {}
15416
15417               we don't need to look any further.  That's what the check for
15418               DECL_INITIAL is for.  */
15419           || (TREE_CODE (decl) == FUNCTION_DECL
15420               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
15421               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
15422     {
15423       /* The present template, TD, should not be a definition.  If it
15424          were a definition, we should be using it!  Note that we
15425          cannot restructure the loop to just keep going until we find
15426          a template with a definition, since that might go too far if
15427          a specialization was declared, but not defined.  */
15428       gcc_assert (TREE_CODE (decl) != VAR_DECL
15429                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
15430
15431       /* Fetch the more general template.  */
15432       tmpl = DECL_TI_TEMPLATE (tmpl);
15433     }
15434
15435   return tmpl;
15436 }
15437
15438 /* Produce the definition of D, a _DECL generated from a template.  If
15439    DEFER_OK is nonzero, then we don't have to actually do the
15440    instantiation now; we just have to do it sometime.  Normally it is
15441    an error if this is an explicit instantiation but D is undefined.
15442    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
15443    explicitly instantiated class template.  */
15444
15445 tree
15446 instantiate_decl (tree d, int defer_ok,
15447                   bool expl_inst_class_mem_p)
15448 {
15449   tree tmpl = DECL_TI_TEMPLATE (d);
15450   tree gen_args;
15451   tree args;
15452   tree td;
15453   tree code_pattern;
15454   tree spec;
15455   tree gen_tmpl;
15456   bool pattern_defined;
15457   int need_push;
15458   location_t saved_loc = input_location;
15459   bool external_p;
15460
15461   /* This function should only be used to instantiate templates for
15462      functions and static member variables.  */
15463   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
15464               || TREE_CODE (d) == VAR_DECL);
15465
15466   /* Variables are never deferred; if instantiation is required, they
15467      are instantiated right away.  That allows for better code in the
15468      case that an expression refers to the value of the variable --
15469      if the variable has a constant value the referring expression can
15470      take advantage of that fact.  */
15471   if (TREE_CODE (d) == VAR_DECL)
15472     defer_ok = 0;
15473
15474   /* Don't instantiate cloned functions.  Instead, instantiate the
15475      functions they cloned.  */
15476   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
15477     d = DECL_CLONED_FUNCTION (d);
15478
15479   if (DECL_TEMPLATE_INSTANTIATED (d))
15480     /* D has already been instantiated.  It might seem reasonable to
15481        check whether or not D is an explicit instantiation, and, if so,
15482        stop here.  But when an explicit instantiation is deferred
15483        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
15484        is set, even though we still need to do the instantiation.  */
15485     return d;
15486
15487   /* If we already have a specialization of this declaration, then
15488      there's no reason to instantiate it.  Note that
15489      retrieve_specialization gives us both instantiations and
15490      specializations, so we must explicitly check
15491      DECL_TEMPLATE_SPECIALIZATION.  */
15492   gen_tmpl = most_general_template (tmpl);
15493   gen_args = DECL_TI_ARGS (d);
15494   spec = retrieve_specialization (gen_tmpl, gen_args,
15495                                   /*class_specializations_p=*/false);
15496   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
15497     return spec;
15498
15499   /* This needs to happen before any tsubsting.  */
15500   if (! push_tinst_level (d))
15501     return d;
15502
15503   timevar_push (TV_PARSE);
15504
15505   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
15506      for the instantiation.  */
15507   td = template_for_substitution (d);
15508   code_pattern = DECL_TEMPLATE_RESULT (td);
15509
15510   /* We should never be trying to instantiate a member of a class
15511      template or partial specialization.  */
15512   gcc_assert (d != code_pattern);
15513
15514   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
15515       || DECL_TEMPLATE_SPECIALIZATION (td))
15516     /* In the case of a friend template whose definition is provided
15517        outside the class, we may have too many arguments.  Drop the
15518        ones we don't need.  The same is true for specializations.  */
15519     args = get_innermost_template_args
15520       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
15521   else
15522     args = gen_args;
15523
15524   if (TREE_CODE (d) == FUNCTION_DECL)
15525     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
15526   else
15527     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
15528
15529   /* We may be in the middle of deferred access check.  Disable it now.  */
15530   push_deferring_access_checks (dk_no_deferred);
15531
15532   /* Unless an explicit instantiation directive has already determined
15533      the linkage of D, remember that a definition is available for
15534      this entity.  */
15535   if (pattern_defined
15536       && !DECL_INTERFACE_KNOWN (d)
15537       && !DECL_NOT_REALLY_EXTERN (d))
15538     mark_definable (d);
15539
15540   input_location = DECL_SOURCE_LOCATION (d);
15541
15542   /* If D is a member of an explicitly instantiated class template,
15543      and no definition is available, treat it like an implicit
15544      instantiation.  */
15545   if (!pattern_defined && expl_inst_class_mem_p
15546       && DECL_EXPLICIT_INSTANTIATION (d))
15547     {
15548       DECL_NOT_REALLY_EXTERN (d) = 0;
15549       DECL_INTERFACE_KNOWN (d) = 0;
15550       SET_DECL_IMPLICIT_INSTANTIATION (d);
15551     }
15552
15553   if (!defer_ok)
15554     {
15555       /* Recheck the substitutions to obtain any warning messages
15556          about ignoring cv qualifiers.  */
15557       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
15558       tree type = TREE_TYPE (gen);
15559
15560       /* Make sure that we can see identifiers, and compute access
15561          correctly.  D is already the target FUNCTION_DECL with the
15562          right context.  */
15563       push_access_scope (d);
15564
15565       if (TREE_CODE (gen) == FUNCTION_DECL)
15566         {
15567           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
15568           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
15569                                           d);
15570           /* Don't simply tsubst the function type, as that will give
15571              duplicate warnings about poor parameter qualifications.
15572              The function arguments are the same as the decl_arguments
15573              without the top level cv qualifiers.  */
15574           type = TREE_TYPE (type);
15575         }
15576       tsubst (type, gen_args, tf_warning_or_error, d);
15577
15578       pop_access_scope (d);
15579     }
15580
15581   /* Check to see whether we know that this template will be
15582      instantiated in some other file, as with "extern template"
15583      extension.  */
15584   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
15585   /* In general, we do not instantiate such templates...  */
15586   if (external_p
15587       /* ... but we instantiate inline functions so that we can inline
15588          them.  An explicit instantiation declaration prohibits implicit
15589          instantiation of non-inline functions.  With high levels of
15590          optimization, we would normally inline non-inline functions
15591          -- but we're not allowed to do that for "extern template" functions.
15592          Therefore, we check DECL_DECLARED_INLINE_P, rather than
15593          possibly_inlined_p.  And ...  */
15594       && ! (TREE_CODE (d) == FUNCTION_DECL
15595             && DECL_DECLARED_INLINE_P (d))
15596       /* ... we instantiate static data members whose values are
15597          needed in integral constant expressions.  */
15598       && ! (TREE_CODE (d) == VAR_DECL
15599             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
15600     goto out;
15601   /* Defer all other templates, unless we have been explicitly
15602      forbidden from doing so.  */
15603   if (/* If there is no definition, we cannot instantiate the
15604          template.  */
15605       ! pattern_defined
15606       /* If it's OK to postpone instantiation, do so.  */
15607       || defer_ok
15608       /* If this is a static data member that will be defined
15609          elsewhere, we don't want to instantiate the entire data
15610          member, but we do want to instantiate the initializer so that
15611          we can substitute that elsewhere.  */
15612       || (external_p && TREE_CODE (d) == VAR_DECL))
15613     {
15614       /* The definition of the static data member is now required so
15615          we must substitute the initializer.  */
15616       if (TREE_CODE (d) == VAR_DECL
15617           && !DECL_INITIAL (d)
15618           && DECL_INITIAL (code_pattern))
15619         {
15620           tree ns;
15621           tree init;
15622
15623           ns = decl_namespace_context (d);
15624           push_nested_namespace (ns);
15625           push_nested_class (DECL_CONTEXT (d));
15626           init = tsubst_expr (DECL_INITIAL (code_pattern),
15627                               args,
15628                               tf_warning_or_error, NULL_TREE,
15629                               /*integral_constant_expression_p=*/false);
15630           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
15631                           /*asmspec_tree=*/NULL_TREE,
15632                           LOOKUP_ONLYCONVERTING);
15633           pop_nested_class ();
15634           pop_nested_namespace (ns);
15635         }
15636
15637       /* We restore the source position here because it's used by
15638          add_pending_template.  */
15639       input_location = saved_loc;
15640
15641       if (at_eof && !pattern_defined
15642           && DECL_EXPLICIT_INSTANTIATION (d)
15643           && DECL_NOT_REALLY_EXTERN (d))
15644         /* [temp.explicit]
15645
15646            The definition of a non-exported function template, a
15647            non-exported member function template, or a non-exported
15648            member function or static data member of a class template
15649            shall be present in every translation unit in which it is
15650            explicitly instantiated.  */
15651         permerror (input_location,  "explicit instantiation of %qD "
15652                    "but no definition available", d);
15653
15654       /* ??? Historically, we have instantiated inline functions, even
15655          when marked as "extern template".  */
15656       if (!(external_p && TREE_CODE (d) == VAR_DECL))
15657         add_pending_template (d);
15658       goto out;
15659     }
15660   /* Tell the repository that D is available in this translation unit
15661      -- and see if it is supposed to be instantiated here.  */
15662   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
15663     {
15664       /* In a PCH file, despite the fact that the repository hasn't
15665          requested instantiation in the PCH it is still possible that
15666          an instantiation will be required in a file that includes the
15667          PCH.  */
15668       if (pch_file)
15669         add_pending_template (d);
15670       /* Instantiate inline functions so that the inliner can do its
15671          job, even though we'll not be emitting a copy of this
15672          function.  */
15673       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
15674         goto out;
15675     }
15676
15677   need_push = !cfun || !global_bindings_p ();
15678   if (need_push)
15679     push_to_top_level ();
15680
15681   /* Mark D as instantiated so that recursive calls to
15682      instantiate_decl do not try to instantiate it again.  */
15683   DECL_TEMPLATE_INSTANTIATED (d) = 1;
15684
15685   /* Regenerate the declaration in case the template has been modified
15686      by a subsequent redeclaration.  */
15687   regenerate_decl_from_template (d, td);
15688
15689   /* We already set the file and line above.  Reset them now in case
15690      they changed as a result of calling regenerate_decl_from_template.  */
15691   input_location = DECL_SOURCE_LOCATION (d);
15692
15693   if (TREE_CODE (d) == VAR_DECL)
15694     {
15695       tree init;
15696
15697       /* Clear out DECL_RTL; whatever was there before may not be right
15698          since we've reset the type of the declaration.  */
15699       SET_DECL_RTL (d, NULL_RTX);
15700       DECL_IN_AGGR_P (d) = 0;
15701
15702       /* The initializer is placed in DECL_INITIAL by
15703          regenerate_decl_from_template.  Pull it out so that
15704          finish_decl can process it.  */
15705       init = DECL_INITIAL (d);
15706       DECL_INITIAL (d) = NULL_TREE;
15707       DECL_INITIALIZED_P (d) = 0;
15708
15709       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
15710          initializer.  That function will defer actual emission until
15711          we have a chance to determine linkage.  */
15712       DECL_EXTERNAL (d) = 0;
15713
15714       /* Enter the scope of D so that access-checking works correctly.  */
15715       push_nested_class (DECL_CONTEXT (d));
15716       finish_decl (d, init, NULL_TREE, NULL_TREE);
15717       pop_nested_class ();
15718     }
15719   else if (TREE_CODE (d) == FUNCTION_DECL)
15720     {
15721       htab_t saved_local_specializations;
15722       tree subst_decl;
15723       tree tmpl_parm;
15724       tree spec_parm;
15725
15726       /* Save away the current list, in case we are instantiating one
15727          template from within the body of another.  */
15728       saved_local_specializations = local_specializations;
15729
15730       /* Set up the list of local specializations.  */
15731       local_specializations = htab_create (37,
15732                                            hash_local_specialization,
15733                                            eq_local_specializations,
15734                                            NULL);
15735
15736       /* Set up context.  */
15737       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
15738
15739       /* Create substitution entries for the parameters.  */
15740       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
15741       tmpl_parm = DECL_ARGUMENTS (subst_decl);
15742       spec_parm = DECL_ARGUMENTS (d);
15743       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
15744         {
15745           register_local_specialization (spec_parm, tmpl_parm);
15746           spec_parm = skip_artificial_parms_for (d, spec_parm);
15747           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
15748         }
15749       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15750         {
15751           register_local_specialization (spec_parm, tmpl_parm);
15752           tmpl_parm = TREE_CHAIN (tmpl_parm);
15753           spec_parm = TREE_CHAIN (spec_parm);
15754         }
15755       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15756         {
15757           /* Register the (value) argument pack as a specialization of
15758              TMPL_PARM, then move on.  */
15759           tree argpack = make_fnparm_pack (spec_parm);
15760           register_local_specialization (argpack, tmpl_parm);
15761           tmpl_parm = TREE_CHAIN (tmpl_parm);
15762           spec_parm = NULL_TREE;
15763         }
15764       gcc_assert (!spec_parm);
15765
15766       /* Substitute into the body of the function.  */
15767       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
15768                    tf_warning_or_error, tmpl,
15769                    /*integral_constant_expression_p=*/false);
15770
15771       /* Set the current input_location to the end of the function
15772          so that finish_function knows where we are.  */
15773       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
15774
15775       /* We don't need the local specializations any more.  */
15776       htab_delete (local_specializations);
15777       local_specializations = saved_local_specializations;
15778
15779       /* Finish the function.  */
15780       d = finish_function (0);
15781       expand_or_defer_fn (d);
15782     }
15783
15784   /* We're not deferring instantiation any more.  */
15785   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
15786
15787   if (need_push)
15788     pop_from_top_level ();
15789
15790 out:
15791   input_location = saved_loc;
15792   pop_deferring_access_checks ();
15793   pop_tinst_level ();
15794
15795   timevar_pop (TV_PARSE);
15796
15797   return d;
15798 }
15799
15800 /* Run through the list of templates that we wish we could
15801    instantiate, and instantiate any we can.  RETRIES is the
15802    number of times we retry pending template instantiation.  */
15803
15804 void
15805 instantiate_pending_templates (int retries)
15806 {
15807   int reconsider;
15808   location_t saved_loc = input_location;
15809
15810   /* Instantiating templates may trigger vtable generation.  This in turn
15811      may require further template instantiations.  We place a limit here
15812      to avoid infinite loop.  */
15813   if (pending_templates && retries >= max_tinst_depth)
15814     {
15815       tree decl = pending_templates->tinst->decl;
15816
15817       error ("template instantiation depth exceeds maximum of %d"
15818              " instantiating %q+D, possibly from virtual table generation"
15819              " (use -ftemplate-depth-NN to increase the maximum)",
15820              max_tinst_depth, decl);
15821       if (TREE_CODE (decl) == FUNCTION_DECL)
15822         /* Pretend that we defined it.  */
15823         DECL_INITIAL (decl) = error_mark_node;
15824       return;
15825     }
15826
15827   do
15828     {
15829       struct pending_template **t = &pending_templates;
15830       struct pending_template *last = NULL;
15831       reconsider = 0;
15832       while (*t)
15833         {
15834           tree instantiation = reopen_tinst_level ((*t)->tinst);
15835           bool complete = false;
15836
15837           if (TYPE_P (instantiation))
15838             {
15839               tree fn;
15840
15841               if (!COMPLETE_TYPE_P (instantiation))
15842                 {
15843                   instantiate_class_template (instantiation);
15844                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
15845                     for (fn = TYPE_METHODS (instantiation);
15846                          fn;
15847                          fn = TREE_CHAIN (fn))
15848                       if (! DECL_ARTIFICIAL (fn))
15849                         instantiate_decl (fn,
15850                                           /*defer_ok=*/0,
15851                                           /*expl_inst_class_mem_p=*/false);
15852                   if (COMPLETE_TYPE_P (instantiation))
15853                     reconsider = 1;
15854                 }
15855
15856               complete = COMPLETE_TYPE_P (instantiation);
15857             }
15858           else
15859             {
15860               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
15861                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
15862                 {
15863                   instantiation
15864                     = instantiate_decl (instantiation,
15865                                         /*defer_ok=*/0,
15866                                         /*expl_inst_class_mem_p=*/false);
15867                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
15868                     reconsider = 1;
15869                 }
15870
15871               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
15872                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
15873             }
15874
15875           if (complete)
15876             /* If INSTANTIATION has been instantiated, then we don't
15877                need to consider it again in the future.  */
15878             *t = (*t)->next;
15879           else
15880             {
15881               last = *t;
15882               t = &(*t)->next;
15883             }
15884           tinst_depth = 0;
15885           current_tinst_level = NULL;
15886         }
15887       last_pending_template = last;
15888     }
15889   while (reconsider);
15890
15891   input_location = saved_loc;
15892 }
15893
15894 /* Substitute ARGVEC into T, which is a list of initializers for
15895    either base class or a non-static data member.  The TREE_PURPOSEs
15896    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
15897    instantiate_decl.  */
15898
15899 static tree
15900 tsubst_initializer_list (tree t, tree argvec)
15901 {
15902   tree inits = NULL_TREE;
15903
15904   for (; t; t = TREE_CHAIN (t))
15905     {
15906       tree decl;
15907       tree init;
15908       tree expanded_bases = NULL_TREE;
15909       tree expanded_arguments = NULL_TREE;
15910       int i, len = 1;
15911
15912       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
15913         {
15914           tree expr;
15915           tree arg;
15916
15917           /* Expand the base class expansion type into separate base
15918              classes.  */
15919           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
15920                                                  tf_warning_or_error,
15921                                                  NULL_TREE);
15922           if (expanded_bases == error_mark_node)
15923             continue;
15924           
15925           /* We'll be building separate TREE_LISTs of arguments for
15926              each base.  */
15927           len = TREE_VEC_LENGTH (expanded_bases);
15928           expanded_arguments = make_tree_vec (len);
15929           for (i = 0; i < len; i++)
15930             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
15931
15932           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
15933              expand each argument in the TREE_VALUE of t.  */
15934           expr = make_node (EXPR_PACK_EXPANSION);
15935           PACK_EXPANSION_PARAMETER_PACKS (expr) =
15936             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
15937
15938           if (TREE_VALUE (t) == void_type_node)
15939             /* VOID_TYPE_NODE is used to indicate
15940                value-initialization.  */
15941             {
15942               for (i = 0; i < len; i++)
15943                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
15944             }
15945           else
15946             {
15947               /* Substitute parameter packs into each argument in the
15948                  TREE_LIST.  */
15949               in_base_initializer = 1;
15950               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
15951                 {
15952                   tree expanded_exprs;
15953
15954                   /* Expand the argument.  */
15955                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
15956                   expanded_exprs 
15957                     = tsubst_pack_expansion (expr, argvec,
15958                                              tf_warning_or_error,
15959                                              NULL_TREE);
15960                   if (expanded_exprs == error_mark_node)
15961                     continue;
15962
15963                   /* Prepend each of the expanded expressions to the
15964                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
15965                   for (i = 0; i < len; i++)
15966                     {
15967                       TREE_VEC_ELT (expanded_arguments, i) = 
15968                         tree_cons (NULL_TREE, 
15969                                    TREE_VEC_ELT (expanded_exprs, i),
15970                                    TREE_VEC_ELT (expanded_arguments, i));
15971                     }
15972                 }
15973               in_base_initializer = 0;
15974
15975               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
15976                  since we built them backwards.  */
15977               for (i = 0; i < len; i++)
15978                 {
15979                   TREE_VEC_ELT (expanded_arguments, i) = 
15980                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
15981                 }
15982             }
15983         }
15984
15985       for (i = 0; i < len; ++i)
15986         {
15987           if (expanded_bases)
15988             {
15989               decl = TREE_VEC_ELT (expanded_bases, i);
15990               decl = expand_member_init (decl);
15991               init = TREE_VEC_ELT (expanded_arguments, i);
15992             }
15993           else
15994             {
15995               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
15996                                   tf_warning_or_error, NULL_TREE);
15997
15998               decl = expand_member_init (decl);
15999               if (decl && !DECL_P (decl))
16000                 in_base_initializer = 1;
16001
16002               init = tsubst_expr (TREE_VALUE (t), argvec, 
16003                                   tf_warning_or_error, NULL_TREE,
16004                                   /*integral_constant_expression_p=*/false);
16005               in_base_initializer = 0;
16006             }
16007
16008           if (decl)
16009             {
16010               init = build_tree_list (decl, init);
16011               TREE_CHAIN (init) = inits;
16012               inits = init;
16013             }
16014         }
16015     }
16016   return inits;
16017 }
16018
16019 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
16020
16021 static void
16022 set_current_access_from_decl (tree decl)
16023 {
16024   if (TREE_PRIVATE (decl))
16025     current_access_specifier = access_private_node;
16026   else if (TREE_PROTECTED (decl))
16027     current_access_specifier = access_protected_node;
16028   else
16029     current_access_specifier = access_public_node;
16030 }
16031
16032 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
16033    is the instantiation (which should have been created with
16034    start_enum) and ARGS are the template arguments to use.  */
16035
16036 static void
16037 tsubst_enum (tree tag, tree newtag, tree args)
16038 {
16039   tree e;
16040
16041   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
16042     {
16043       tree value;
16044       tree decl;
16045
16046       decl = TREE_VALUE (e);
16047       /* Note that in a template enum, the TREE_VALUE is the
16048          CONST_DECL, not the corresponding INTEGER_CST.  */
16049       value = tsubst_expr (DECL_INITIAL (decl),
16050                            args, tf_warning_or_error, NULL_TREE,
16051                            /*integral_constant_expression_p=*/true);
16052
16053       /* Give this enumeration constant the correct access.  */
16054       set_current_access_from_decl (decl);
16055
16056       /* Actually build the enumerator itself.  */
16057       build_enumerator (DECL_NAME (decl), value, newtag);
16058     }
16059
16060   finish_enum (newtag);
16061   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
16062     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
16063 }
16064
16065 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
16066    its type -- but without substituting the innermost set of template
16067    arguments.  So, innermost set of template parameters will appear in
16068    the type.  */
16069
16070 tree
16071 get_mostly_instantiated_function_type (tree decl)
16072 {
16073   tree fn_type;
16074   tree tmpl;
16075   tree targs;
16076   tree tparms;
16077   int parm_depth;
16078
16079   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16080   targs = DECL_TI_ARGS (decl);
16081   tparms = DECL_TEMPLATE_PARMS (tmpl);
16082   parm_depth = TMPL_PARMS_DEPTH (tparms);
16083
16084   /* There should be as many levels of arguments as there are levels
16085      of parameters.  */
16086   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
16087
16088   fn_type = TREE_TYPE (tmpl);
16089
16090   if (parm_depth == 1)
16091     /* No substitution is necessary.  */
16092     ;
16093   else
16094     {
16095       int i, save_access_control;
16096       tree partial_args;
16097
16098       /* Replace the innermost level of the TARGS with NULL_TREEs to
16099          let tsubst know not to substitute for those parameters.  */
16100       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
16101       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
16102         SET_TMPL_ARGS_LEVEL (partial_args, i,
16103                              TMPL_ARGS_LEVEL (targs, i));
16104       SET_TMPL_ARGS_LEVEL (partial_args,
16105                            TMPL_ARGS_DEPTH (targs),
16106                            make_tree_vec (DECL_NTPARMS (tmpl)));
16107
16108       /* Disable access control as this function is used only during
16109          name-mangling.  */
16110       save_access_control = flag_access_control;
16111       flag_access_control = 0;
16112
16113       ++processing_template_decl;
16114       /* Now, do the (partial) substitution to figure out the
16115          appropriate function type.  */
16116       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
16117       --processing_template_decl;
16118
16119       /* Substitute into the template parameters to obtain the real
16120          innermost set of parameters.  This step is important if the
16121          innermost set of template parameters contains value
16122          parameters whose types depend on outer template parameters.  */
16123       TREE_VEC_LENGTH (partial_args)--;
16124       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
16125
16126       flag_access_control = save_access_control;
16127     }
16128
16129   return fn_type;
16130 }
16131
16132 /* Return truthvalue if we're processing a template different from
16133    the last one involved in diagnostics.  */
16134 int
16135 problematic_instantiation_changed (void)
16136 {
16137   return last_template_error_tick != tinst_level_tick;
16138 }
16139
16140 /* Remember current template involved in diagnostics.  */
16141 void
16142 record_last_problematic_instantiation (void)
16143 {
16144   last_template_error_tick = tinst_level_tick;
16145 }
16146
16147 struct tinst_level *
16148 current_instantiation (void)
16149 {
16150   return current_tinst_level;
16151 }
16152
16153 /* [temp.param] Check that template non-type parm TYPE is of an allowable
16154    type. Return zero for ok, nonzero for disallowed. Issue error and
16155    warning messages under control of COMPLAIN.  */
16156
16157 static int
16158 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
16159 {
16160   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
16161     return 0;
16162   else if (POINTER_TYPE_P (type))
16163     return 0;
16164   else if (TYPE_PTR_TO_MEMBER_P (type))
16165     return 0;
16166   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16167     return 0;
16168   else if (TREE_CODE (type) == TYPENAME_TYPE)
16169     return 0;
16170
16171   if (complain & tf_error)
16172     error ("%q#T is not a valid type for a template constant parameter", type);
16173   return 1;
16174 }
16175
16176 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
16177    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
16178
16179 static bool
16180 dependent_type_p_r (tree type)
16181 {
16182   tree scope;
16183
16184   /* [temp.dep.type]
16185
16186      A type is dependent if it is:
16187
16188      -- a template parameter. Template template parameters are types
16189         for us (since TYPE_P holds true for them) so we handle
16190         them here.  */
16191   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16192       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
16193     return true;
16194   /* -- a qualified-id with a nested-name-specifier which contains a
16195         class-name that names a dependent type or whose unqualified-id
16196         names a dependent type.  */
16197   if (TREE_CODE (type) == TYPENAME_TYPE)
16198     return true;
16199   /* -- a cv-qualified type where the cv-unqualified type is
16200         dependent.  */
16201   type = TYPE_MAIN_VARIANT (type);
16202   /* -- a compound type constructed from any dependent type.  */
16203   if (TYPE_PTR_TO_MEMBER_P (type))
16204     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
16205             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
16206                                            (type)));
16207   else if (TREE_CODE (type) == POINTER_TYPE
16208            || TREE_CODE (type) == REFERENCE_TYPE)
16209     return dependent_type_p (TREE_TYPE (type));
16210   else if (TREE_CODE (type) == FUNCTION_TYPE
16211            || TREE_CODE (type) == METHOD_TYPE)
16212     {
16213       tree arg_type;
16214
16215       if (dependent_type_p (TREE_TYPE (type)))
16216         return true;
16217       for (arg_type = TYPE_ARG_TYPES (type);
16218            arg_type;
16219            arg_type = TREE_CHAIN (arg_type))
16220         if (dependent_type_p (TREE_VALUE (arg_type)))
16221           return true;
16222       return false;
16223     }
16224   /* -- an array type constructed from any dependent type or whose
16225         size is specified by a constant expression that is
16226         value-dependent.  */
16227   if (TREE_CODE (type) == ARRAY_TYPE)
16228     {
16229       if (TYPE_DOMAIN (type)
16230           && dependent_type_p (TYPE_DOMAIN (type)))
16231         return true;
16232       return dependent_type_p (TREE_TYPE (type));
16233     }
16234   else if (TREE_CODE (type) == INTEGER_TYPE
16235            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
16236     {
16237       /* If this is the TYPE_DOMAIN of an array type, consider it
16238          dependent.  We already checked for value-dependence in
16239          compute_array_index_type.  */
16240       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
16241     }
16242
16243   /* -- a template-id in which either the template name is a template
16244      parameter ...  */
16245   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
16246     return true;
16247   /* ... or any of the template arguments is a dependent type or
16248         an expression that is type-dependent or value-dependent.  */
16249   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
16250            && (any_dependent_template_arguments_p
16251                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
16252     return true;
16253
16254   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
16255      argument of the `typeof' expression is not type-dependent, then
16256      it should already been have resolved.  */
16257   if (TREE_CODE (type) == TYPEOF_TYPE
16258       || TREE_CODE (type) == DECLTYPE_TYPE)
16259     return true;
16260
16261   /* A template argument pack is dependent if any of its packed
16262      arguments are.  */
16263   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
16264     {
16265       tree args = ARGUMENT_PACK_ARGS (type);
16266       int i, len = TREE_VEC_LENGTH (args);
16267       for (i = 0; i < len; ++i)
16268         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16269           return true;
16270     }
16271
16272   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
16273      be template parameters.  */
16274   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
16275     return true;
16276
16277   /* The standard does not specifically mention types that are local
16278      to template functions or local classes, but they should be
16279      considered dependent too.  For example:
16280
16281        template <int I> void f() {
16282          enum E { a = I };
16283          S<sizeof (E)> s;
16284        }
16285
16286      The size of `E' cannot be known until the value of `I' has been
16287      determined.  Therefore, `E' must be considered dependent.  */
16288   scope = TYPE_CONTEXT (type);
16289   if (scope && TYPE_P (scope))
16290     return dependent_type_p (scope);
16291   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
16292     return type_dependent_expression_p (scope);
16293
16294   /* Other types are non-dependent.  */
16295   return false;
16296 }
16297
16298 /* Returns TRUE if TYPE is dependent, in the sense of
16299    [temp.dep.type].  */
16300
16301 bool
16302 dependent_type_p (tree type)
16303 {
16304   /* If there are no template parameters in scope, then there can't be
16305      any dependent types.  */
16306   if (!processing_template_decl)
16307     {
16308       /* If we are not processing a template, then nobody should be
16309          providing us with a dependent type.  */
16310       gcc_assert (type);
16311       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
16312       return false;
16313     }
16314
16315   /* If the type is NULL, we have not computed a type for the entity
16316      in question; in that case, the type is dependent.  */
16317   if (!type)
16318     return true;
16319
16320   /* Erroneous types can be considered non-dependent.  */
16321   if (type == error_mark_node)
16322     return false;
16323
16324   /* If we have not already computed the appropriate value for TYPE,
16325      do so now.  */
16326   if (!TYPE_DEPENDENT_P_VALID (type))
16327     {
16328       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
16329       TYPE_DEPENDENT_P_VALID (type) = 1;
16330     }
16331
16332   return TYPE_DEPENDENT_P (type);
16333 }
16334
16335 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
16336    lookup.  In other words, a dependent type that is not the current
16337    instantiation.  */
16338
16339 bool
16340 dependent_scope_p (tree scope)
16341 {
16342   return (scope && TYPE_P (scope) && dependent_type_p (scope)
16343           && !currently_open_class (scope));
16344 }
16345
16346 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
16347
16348 static bool
16349 dependent_scope_ref_p (tree expression, bool criterion (tree))
16350 {
16351   tree scope;
16352   tree name;
16353
16354   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
16355
16356   if (!TYPE_P (TREE_OPERAND (expression, 0)))
16357     return true;
16358
16359   scope = TREE_OPERAND (expression, 0);
16360   name = TREE_OPERAND (expression, 1);
16361
16362   /* [temp.dep.expr]
16363
16364      An id-expression is type-dependent if it contains a
16365      nested-name-specifier that contains a class-name that names a
16366      dependent type.  */
16367   /* The suggested resolution to Core Issue 224 implies that if the
16368      qualifying type is the current class, then we must peek
16369      inside it.  */
16370   if (DECL_P (name)
16371       && currently_open_class (scope)
16372       && !criterion (name))
16373     return false;
16374   if (dependent_type_p (scope))
16375     return true;
16376
16377   return false;
16378 }
16379
16380 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
16381    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
16382    expression.  */
16383
16384 bool
16385 value_dependent_expression_p (tree expression)
16386 {
16387   if (!processing_template_decl)
16388     return false;
16389
16390   /* A name declared with a dependent type.  */
16391   if (DECL_P (expression) && type_dependent_expression_p (expression))
16392     return true;
16393
16394   switch (TREE_CODE (expression))
16395     {
16396     case IDENTIFIER_NODE:
16397       /* A name that has not been looked up -- must be dependent.  */
16398       return true;
16399
16400     case TEMPLATE_PARM_INDEX:
16401       /* A non-type template parm.  */
16402       return true;
16403
16404     case CONST_DECL:
16405       /* A non-type template parm.  */
16406       if (DECL_TEMPLATE_PARM_P (expression))
16407         return true;
16408       return value_dependent_expression_p (DECL_INITIAL (expression));
16409
16410     case VAR_DECL:
16411        /* A constant with integral or enumeration type and is initialized
16412           with an expression that is value-dependent.  */
16413       if (DECL_INITIAL (expression)
16414           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
16415           && value_dependent_expression_p (DECL_INITIAL (expression)))
16416         return true;
16417       return false;
16418
16419     case DYNAMIC_CAST_EXPR:
16420     case STATIC_CAST_EXPR:
16421     case CONST_CAST_EXPR:
16422     case REINTERPRET_CAST_EXPR:
16423     case CAST_EXPR:
16424       /* These expressions are value-dependent if the type to which
16425          the cast occurs is dependent or the expression being casted
16426          is value-dependent.  */
16427       {
16428         tree type = TREE_TYPE (expression);
16429
16430         if (dependent_type_p (type))
16431           return true;
16432
16433         /* A functional cast has a list of operands.  */
16434         expression = TREE_OPERAND (expression, 0);
16435         if (!expression)
16436           {
16437             /* If there are no operands, it must be an expression such
16438                as "int()". This should not happen for aggregate types
16439                because it would form non-constant expressions.  */
16440             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
16441
16442             return false;
16443           }
16444
16445         if (TREE_CODE (expression) == TREE_LIST)
16446           return any_value_dependent_elements_p (expression);
16447
16448         return value_dependent_expression_p (expression);
16449       }
16450
16451     case SIZEOF_EXPR:
16452     case ALIGNOF_EXPR:
16453       /* A `sizeof' expression is value-dependent if the operand is
16454          type-dependent or is a pack expansion.  */
16455       expression = TREE_OPERAND (expression, 0);
16456       if (PACK_EXPANSION_P (expression))
16457         return true;
16458       else if (TYPE_P (expression))
16459         return dependent_type_p (expression);
16460       return type_dependent_expression_p (expression);
16461
16462     case SCOPE_REF:
16463       return dependent_scope_ref_p (expression, value_dependent_expression_p);
16464
16465     case COMPONENT_REF:
16466       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
16467               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
16468
16469     case CALL_EXPR:
16470       /* A CALL_EXPR may appear in a constant expression if it is a
16471          call to a builtin function, e.g., __builtin_constant_p.  All
16472          such calls are value-dependent.  */
16473       return true;
16474
16475     case NONTYPE_ARGUMENT_PACK:
16476       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
16477          is value-dependent.  */
16478       {
16479         tree values = ARGUMENT_PACK_ARGS (expression);
16480         int i, len = TREE_VEC_LENGTH (values);
16481         
16482         for (i = 0; i < len; ++i)
16483           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
16484             return true;
16485         
16486         return false;
16487       }
16488
16489     case TRAIT_EXPR:
16490       {
16491         tree type2 = TRAIT_EXPR_TYPE2 (expression);
16492         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
16493                 || (type2 ? dependent_type_p (type2) : false));
16494       }
16495
16496     case MODOP_EXPR:
16497       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
16498               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
16499
16500     default:
16501       /* A constant expression is value-dependent if any subexpression is
16502          value-dependent.  */
16503       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
16504         {
16505         case tcc_reference:
16506         case tcc_unary:
16507           return (value_dependent_expression_p
16508                   (TREE_OPERAND (expression, 0)));
16509
16510         case tcc_comparison:
16511         case tcc_binary:
16512           return ((value_dependent_expression_p
16513                    (TREE_OPERAND (expression, 0)))
16514                   || (value_dependent_expression_p
16515                       (TREE_OPERAND (expression, 1))));
16516
16517         case tcc_expression:
16518         case tcc_vl_exp:
16519           {
16520             int i;
16521             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
16522               /* In some cases, some of the operands may be missing.
16523                  (For example, in the case of PREDECREMENT_EXPR, the
16524                  amount to increment by may be missing.)  That doesn't
16525                  make the expression dependent.  */
16526               if (TREE_OPERAND (expression, i)
16527                   && (value_dependent_expression_p
16528                       (TREE_OPERAND (expression, i))))
16529                 return true;
16530             return false;
16531           }
16532
16533         default:
16534           break;
16535         }
16536     }
16537
16538   /* The expression is not value-dependent.  */
16539   return false;
16540 }
16541
16542 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
16543    [temp.dep.expr].  */
16544
16545 bool
16546 type_dependent_expression_p (tree expression)
16547 {
16548   if (!processing_template_decl)
16549     return false;
16550
16551   if (expression == error_mark_node)
16552     return false;
16553
16554   /* An unresolved name is always dependent.  */
16555   if (TREE_CODE (expression) == IDENTIFIER_NODE
16556       || TREE_CODE (expression) == USING_DECL)
16557     return true;
16558
16559   /* Some expression forms are never type-dependent.  */
16560   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
16561       || TREE_CODE (expression) == SIZEOF_EXPR
16562       || TREE_CODE (expression) == ALIGNOF_EXPR
16563       || TREE_CODE (expression) == TRAIT_EXPR
16564       || TREE_CODE (expression) == TYPEID_EXPR
16565       || TREE_CODE (expression) == DELETE_EXPR
16566       || TREE_CODE (expression) == VEC_DELETE_EXPR
16567       || TREE_CODE (expression) == THROW_EXPR)
16568     return false;
16569
16570   /* The types of these expressions depends only on the type to which
16571      the cast occurs.  */
16572   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
16573       || TREE_CODE (expression) == STATIC_CAST_EXPR
16574       || TREE_CODE (expression) == CONST_CAST_EXPR
16575       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
16576       || TREE_CODE (expression) == CAST_EXPR)
16577     return dependent_type_p (TREE_TYPE (expression));
16578
16579   /* The types of these expressions depends only on the type created
16580      by the expression.  */
16581   if (TREE_CODE (expression) == NEW_EXPR
16582       || TREE_CODE (expression) == VEC_NEW_EXPR)
16583     {
16584       /* For NEW_EXPR tree nodes created inside a template, either
16585          the object type itself or a TREE_LIST may appear as the
16586          operand 1.  */
16587       tree type = TREE_OPERAND (expression, 1);
16588       if (TREE_CODE (type) == TREE_LIST)
16589         /* This is an array type.  We need to check array dimensions
16590            as well.  */
16591         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
16592                || value_dependent_expression_p
16593                     (TREE_OPERAND (TREE_VALUE (type), 1));
16594       else
16595         return dependent_type_p (type);
16596     }
16597
16598   if (TREE_CODE (expression) == SCOPE_REF
16599       && dependent_scope_ref_p (expression,
16600                                 type_dependent_expression_p))
16601     return true;
16602
16603   if (TREE_CODE (expression) == FUNCTION_DECL
16604       && DECL_LANG_SPECIFIC (expression)
16605       && DECL_TEMPLATE_INFO (expression)
16606       && (any_dependent_template_arguments_p
16607           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
16608     return true;
16609
16610   if (TREE_CODE (expression) == TEMPLATE_DECL
16611       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
16612     return false;
16613
16614   if (TREE_CODE (expression) == STMT_EXPR)
16615     expression = stmt_expr_value_expr (expression);
16616
16617   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
16618     {
16619       tree elt;
16620       unsigned i;
16621
16622       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
16623         {
16624           if (type_dependent_expression_p (elt))
16625             return true;
16626         }
16627       return false;
16628     }
16629
16630   if (TREE_TYPE (expression) == unknown_type_node)
16631     {
16632       if (TREE_CODE (expression) == ADDR_EXPR)
16633         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
16634       if (TREE_CODE (expression) == COMPONENT_REF
16635           || TREE_CODE (expression) == OFFSET_REF)
16636         {
16637           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
16638             return true;
16639           expression = TREE_OPERAND (expression, 1);
16640           if (TREE_CODE (expression) == IDENTIFIER_NODE)
16641             return false;
16642         }
16643       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
16644       if (TREE_CODE (expression) == SCOPE_REF)
16645         return false;
16646
16647       if (TREE_CODE (expression) == BASELINK)
16648         expression = BASELINK_FUNCTIONS (expression);
16649
16650       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
16651         {
16652           if (any_dependent_template_arguments_p
16653               (TREE_OPERAND (expression, 1)))
16654             return true;
16655           expression = TREE_OPERAND (expression, 0);
16656         }
16657       gcc_assert (TREE_CODE (expression) == OVERLOAD
16658                   || TREE_CODE (expression) == FUNCTION_DECL);
16659
16660       while (expression)
16661         {
16662           if (type_dependent_expression_p (OVL_CURRENT (expression)))
16663             return true;
16664           expression = OVL_NEXT (expression);
16665         }
16666       return false;
16667     }
16668
16669   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
16670
16671   return (dependent_type_p (TREE_TYPE (expression)));
16672 }
16673
16674 /* Like type_dependent_expression_p, but it also works while not processing
16675    a template definition, i.e. during substitution or mangling.  */
16676
16677 bool
16678 type_dependent_expression_p_push (tree expr)
16679 {
16680   bool b;
16681   ++processing_template_decl;
16682   b = type_dependent_expression_p (expr);
16683   --processing_template_decl;
16684   return b;
16685 }
16686
16687 /* Returns TRUE if ARGS contains a type-dependent expression.  */
16688
16689 bool
16690 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
16691 {
16692   unsigned int i;
16693   tree arg;
16694
16695   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
16696     {
16697       if (type_dependent_expression_p (arg))
16698         return true;
16699     }
16700   return false;
16701 }
16702
16703 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
16704    expressions) contains any value-dependent expressions.  */
16705
16706 bool
16707 any_value_dependent_elements_p (const_tree list)
16708 {
16709   for (; list; list = TREE_CHAIN (list))
16710     if (value_dependent_expression_p (TREE_VALUE (list)))
16711       return true;
16712
16713   return false;
16714 }
16715
16716 /* Returns TRUE if the ARG (a template argument) is dependent.  */
16717
16718 bool
16719 dependent_template_arg_p (tree arg)
16720 {
16721   if (!processing_template_decl)
16722     return false;
16723
16724   if (TREE_CODE (arg) == TEMPLATE_DECL
16725       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16726     return dependent_template_p (arg);
16727   else if (ARGUMENT_PACK_P (arg))
16728     {
16729       tree args = ARGUMENT_PACK_ARGS (arg);
16730       int i, len = TREE_VEC_LENGTH (args);
16731       for (i = 0; i < len; ++i)
16732         {
16733           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16734             return true;
16735         }
16736
16737       return false;
16738     }
16739   else if (TYPE_P (arg))
16740     return dependent_type_p (arg);
16741   else
16742     return (type_dependent_expression_p (arg)
16743             || value_dependent_expression_p (arg));
16744 }
16745
16746 /* Returns true if ARGS (a collection of template arguments) contains
16747    any types that require structural equality testing.  */
16748
16749 bool
16750 any_template_arguments_need_structural_equality_p (tree args)
16751 {
16752   int i;
16753   int j;
16754
16755   if (!args)
16756     return false;
16757   if (args == error_mark_node)
16758     return true;
16759
16760   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16761     {
16762       tree level = TMPL_ARGS_LEVEL (args, i + 1);
16763       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16764         {
16765           tree arg = TREE_VEC_ELT (level, j);
16766           tree packed_args = NULL_TREE;
16767           int k, len = 1;
16768
16769           if (ARGUMENT_PACK_P (arg))
16770             {
16771               /* Look inside the argument pack.  */
16772               packed_args = ARGUMENT_PACK_ARGS (arg);
16773               len = TREE_VEC_LENGTH (packed_args);
16774             }
16775
16776           for (k = 0; k < len; ++k)
16777             {
16778               if (packed_args)
16779                 arg = TREE_VEC_ELT (packed_args, k);
16780
16781               if (error_operand_p (arg))
16782                 return true;
16783               else if (TREE_CODE (arg) == TEMPLATE_DECL
16784                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16785                 continue;
16786               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
16787                 return true;
16788               else if (!TYPE_P (arg) && TREE_TYPE (arg)
16789                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
16790                 return true;
16791             }
16792         }
16793     }
16794
16795   return false;
16796 }
16797
16798 /* Returns true if ARGS (a collection of template arguments) contains
16799    any dependent arguments.  */
16800
16801 bool
16802 any_dependent_template_arguments_p (const_tree args)
16803 {
16804   int i;
16805   int j;
16806
16807   if (!args)
16808     return false;
16809   if (args == error_mark_node)
16810     return true;
16811
16812   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16813     {
16814       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
16815       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16816         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
16817           return true;
16818     }
16819
16820   return false;
16821 }
16822
16823 /* Returns TRUE if the template TMPL is dependent.  */
16824
16825 bool
16826 dependent_template_p (tree tmpl)
16827 {
16828   if (TREE_CODE (tmpl) == OVERLOAD)
16829     {
16830       while (tmpl)
16831         {
16832           if (dependent_template_p (OVL_FUNCTION (tmpl)))
16833             return true;
16834           tmpl = OVL_CHAIN (tmpl);
16835         }
16836       return false;
16837     }
16838
16839   /* Template template parameters are dependent.  */
16840   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
16841       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16842     return true;
16843   /* So are names that have not been looked up.  */
16844   if (TREE_CODE (tmpl) == SCOPE_REF
16845       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
16846     return true;
16847   /* So are member templates of dependent classes.  */
16848   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
16849     return dependent_type_p (DECL_CONTEXT (tmpl));
16850   return false;
16851 }
16852
16853 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
16854
16855 bool
16856 dependent_template_id_p (tree tmpl, tree args)
16857 {
16858   return (dependent_template_p (tmpl)
16859           || any_dependent_template_arguments_p (args));
16860 }
16861
16862 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
16863    is dependent.  */
16864
16865 bool
16866 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
16867 {
16868   int i;
16869
16870   if (!processing_template_decl)
16871     return false;
16872
16873   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
16874     {
16875       tree decl = TREE_VEC_ELT (declv, i);
16876       tree init = TREE_VEC_ELT (initv, i);
16877       tree cond = TREE_VEC_ELT (condv, i);
16878       tree incr = TREE_VEC_ELT (incrv, i);
16879
16880       if (type_dependent_expression_p (decl))
16881         return true;
16882
16883       if (init && type_dependent_expression_p (init))
16884         return true;
16885
16886       if (type_dependent_expression_p (cond))
16887         return true;
16888
16889       if (COMPARISON_CLASS_P (cond)
16890           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
16891               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
16892         return true;
16893
16894       if (TREE_CODE (incr) == MODOP_EXPR)
16895         {
16896           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
16897               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
16898             return true;
16899         }
16900       else if (type_dependent_expression_p (incr))
16901         return true;
16902       else if (TREE_CODE (incr) == MODIFY_EXPR)
16903         {
16904           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
16905             return true;
16906           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
16907             {
16908               tree t = TREE_OPERAND (incr, 1);
16909               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
16910                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
16911                 return true;
16912             }
16913         }
16914     }
16915
16916   return false;
16917 }
16918
16919 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
16920    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
16921    no such TYPE can be found.  Note that this function peers inside
16922    uninstantiated templates and therefore should be used only in
16923    extremely limited situations.  ONLY_CURRENT_P restricts this
16924    peering to the currently open classes hierarchy (which is required
16925    when comparing types).  */
16926
16927 tree
16928 resolve_typename_type (tree type, bool only_current_p)
16929 {
16930   tree scope;
16931   tree name;
16932   tree decl;
16933   int quals;
16934   tree pushed_scope;
16935   tree result;
16936
16937   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
16938
16939   scope = TYPE_CONTEXT (type);
16940   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
16941      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
16942      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
16943      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
16944      identifier  of the TYPENAME_TYPE anymore.
16945      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
16946      TYPENAME_TYPE instead, we avoid messing up with a possible
16947      typedef variant case.  */
16948   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
16949
16950   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
16951      it first before we can figure out what NAME refers to.  */
16952   if (TREE_CODE (scope) == TYPENAME_TYPE)
16953     scope = resolve_typename_type (scope, only_current_p);
16954   /* If we don't know what SCOPE refers to, then we cannot resolve the
16955      TYPENAME_TYPE.  */
16956   if (TREE_CODE (scope) == TYPENAME_TYPE)
16957     return type;
16958   /* If the SCOPE is a template type parameter, we have no way of
16959      resolving the name.  */
16960   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
16961     return type;
16962   /* If the SCOPE is not the current instantiation, there's no reason
16963      to look inside it.  */
16964   if (only_current_p && !currently_open_class (scope))
16965     return type;
16966   /* If SCOPE isn't the template itself, it will not have a valid
16967      TYPE_FIELDS list.  */
16968   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
16969     /* scope is either the template itself or a compatible instantiation
16970        like X<T>, so look up the name in the original template.  */
16971     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
16972   else
16973     /* scope is a partial instantiation, so we can't do the lookup or we
16974        will lose the template arguments.  */
16975     return type;
16976   /* Enter the SCOPE so that name lookup will be resolved as if we
16977      were in the class definition.  In particular, SCOPE will no
16978      longer be considered a dependent type.  */
16979   pushed_scope = push_scope (scope);
16980   /* Look up the declaration.  */
16981   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
16982
16983   result = NULL_TREE;
16984   
16985   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
16986      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
16987   if (!decl)
16988     /*nop*/;
16989   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
16990            && TREE_CODE (decl) == TYPE_DECL)
16991     {
16992       result = TREE_TYPE (decl);
16993       if (result == error_mark_node)
16994         result = NULL_TREE;
16995     }
16996   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
16997            && DECL_CLASS_TEMPLATE_P (decl))
16998     {
16999       tree tmpl;
17000       tree args;
17001       /* Obtain the template and the arguments.  */
17002       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
17003       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
17004       /* Instantiate the template.  */
17005       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
17006                                       /*entering_scope=*/0,
17007                                       tf_error | tf_user);
17008       if (result == error_mark_node)
17009         result = NULL_TREE;
17010     }
17011   
17012   /* Leave the SCOPE.  */
17013   if (pushed_scope)
17014     pop_scope (pushed_scope);
17015
17016   /* If we failed to resolve it, return the original typename.  */
17017   if (!result)
17018     return type;
17019   
17020   /* If lookup found a typename type, resolve that too.  */
17021   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
17022     {
17023       /* Ill-formed programs can cause infinite recursion here, so we
17024          must catch that.  */
17025       TYPENAME_IS_RESOLVING_P (type) = 1;
17026       result = resolve_typename_type (result, only_current_p);
17027       TYPENAME_IS_RESOLVING_P (type) = 0;
17028     }
17029   
17030   /* Qualify the resulting type.  */
17031   quals = cp_type_quals (type);
17032   if (quals)
17033     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
17034
17035   return result;
17036 }
17037
17038 /* EXPR is an expression which is not type-dependent.  Return a proxy
17039    for EXPR that can be used to compute the types of larger
17040    expressions containing EXPR.  */
17041
17042 tree
17043 build_non_dependent_expr (tree expr)
17044 {
17045   tree inner_expr;
17046
17047   /* Preserve null pointer constants so that the type of things like
17048      "p == 0" where "p" is a pointer can be determined.  */
17049   if (null_ptr_cst_p (expr))
17050     return expr;
17051   /* Preserve OVERLOADs; the functions must be available to resolve
17052      types.  */
17053   inner_expr = expr;
17054   if (TREE_CODE (inner_expr) == STMT_EXPR)
17055     inner_expr = stmt_expr_value_expr (inner_expr);
17056   if (TREE_CODE (inner_expr) == ADDR_EXPR)
17057     inner_expr = TREE_OPERAND (inner_expr, 0);
17058   if (TREE_CODE (inner_expr) == COMPONENT_REF)
17059     inner_expr = TREE_OPERAND (inner_expr, 1);
17060   if (is_overloaded_fn (inner_expr)
17061       || TREE_CODE (inner_expr) == OFFSET_REF)
17062     return expr;
17063   /* There is no need to return a proxy for a variable.  */
17064   if (TREE_CODE (expr) == VAR_DECL)
17065     return expr;
17066   /* Preserve string constants; conversions from string constants to
17067      "char *" are allowed, even though normally a "const char *"
17068      cannot be used to initialize a "char *".  */
17069   if (TREE_CODE (expr) == STRING_CST)
17070     return expr;
17071   /* Preserve arithmetic constants, as an optimization -- there is no
17072      reason to create a new node.  */
17073   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
17074     return expr;
17075   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
17076      There is at least one place where we want to know that a
17077      particular expression is a throw-expression: when checking a ?:
17078      expression, there are special rules if the second or third
17079      argument is a throw-expression.  */
17080   if (TREE_CODE (expr) == THROW_EXPR)
17081     return expr;
17082
17083   if (TREE_CODE (expr) == COND_EXPR)
17084     return build3 (COND_EXPR,
17085                    TREE_TYPE (expr),
17086                    TREE_OPERAND (expr, 0),
17087                    (TREE_OPERAND (expr, 1)
17088                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
17089                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
17090                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
17091   if (TREE_CODE (expr) == COMPOUND_EXPR
17092       && !COMPOUND_EXPR_OVERLOADED (expr))
17093     return build2 (COMPOUND_EXPR,
17094                    TREE_TYPE (expr),
17095                    TREE_OPERAND (expr, 0),
17096                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
17097
17098   /* If the type is unknown, it can't really be non-dependent */
17099   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
17100
17101   /* Otherwise, build a NON_DEPENDENT_EXPR.
17102
17103      REFERENCE_TYPEs are not stripped for expressions in templates
17104      because doing so would play havoc with mangling.  Consider, for
17105      example:
17106
17107        template <typename T> void f<T& g>() { g(); }
17108
17109      In the body of "f", the expression for "g" will have
17110      REFERENCE_TYPE, even though the standard says that it should
17111      not.  The reason is that we must preserve the syntactic form of
17112      the expression so that mangling (say) "f<g>" inside the body of
17113      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
17114      stripped here.  */
17115   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
17116 }
17117
17118 /* ARGS is a vector of expressions as arguments to a function call.
17119    Replace the arguments with equivalent non-dependent expressions.
17120    This modifies ARGS in place.  */
17121
17122 void
17123 make_args_non_dependent (VEC(tree,gc) *args)
17124 {
17125   unsigned int ix;
17126   tree arg;
17127
17128   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
17129     {
17130       tree newarg = build_non_dependent_expr (arg);
17131       if (newarg != arg)
17132         VEC_replace (tree, args, ix, newarg);
17133     }
17134 }
17135
17136 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
17137    with a level one deeper than the actual template parms.  */
17138
17139 tree
17140 make_auto (void)
17141 {
17142   tree au;
17143
17144   /* ??? Is it worth caching this for multiple autos at the same level?  */
17145   au = cxx_make_type (TEMPLATE_TYPE_PARM);
17146   TYPE_NAME (au) = build_decl (TYPE_DECL, get_identifier ("auto"), au);
17147   TYPE_STUB_DECL (au) = TYPE_NAME (au);
17148   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
17149     (0, processing_template_decl + 1, processing_template_decl + 1,
17150      TYPE_NAME (au), NULL_TREE);
17151   TYPE_CANONICAL (au) = canonical_type_parameter (au);
17152   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
17153   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
17154
17155   return au;
17156 }
17157
17158 /* Replace auto in TYPE with std::initializer_list<auto>.  */
17159
17160 static tree
17161 listify_autos (tree type, tree auto_node)
17162 {
17163   tree std_init_list = namespace_binding
17164     (get_identifier ("initializer_list"), std_node);
17165   tree argvec;
17166   tree init_auto;
17167   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
17168     {    
17169       error ("deducing auto from brace-enclosed initializer list requires "
17170              "#include <initializer_list>");
17171       return error_mark_node;
17172     }
17173   argvec = make_tree_vec (1);
17174   TREE_VEC_ELT (argvec, 0) = auto_node;
17175   init_auto = lookup_template_class (std_init_list, argvec, NULL_TREE,
17176                                      NULL_TREE, 0, tf_warning_or_error);
17177
17178   TREE_VEC_ELT (argvec, 0) = init_auto;
17179   if (processing_template_decl)
17180     argvec = add_to_template_args (current_template_args (), argvec);
17181   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17182 }
17183
17184 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
17185    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
17186
17187 tree
17188 do_auto_deduction (tree type, tree init, tree auto_node)
17189 {
17190   tree parms, tparms, targs;
17191   tree args[1];
17192   int val;
17193
17194   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
17195      with either a new invented type template parameter U or, if the
17196      initializer is a braced-init-list (8.5.4), with
17197      std::initializer_list<U>.  */
17198   if (BRACE_ENCLOSED_INITIALIZER_P (init))
17199     type = listify_autos (type, auto_node);
17200
17201   parms = build_tree_list (NULL_TREE, type);
17202   args[0] = init;
17203   tparms = make_tree_vec (1);
17204   targs = make_tree_vec (1);
17205   TREE_VEC_ELT (tparms, 0)
17206     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
17207   val = type_unification_real (tparms, targs, parms, args, 1, 0,
17208                                DEDUCE_CALL, LOOKUP_NORMAL);
17209   if (val > 0)
17210     {
17211       error ("unable to deduce %qT from %qE", type, init);
17212       return error_mark_node;
17213     }
17214
17215   if (processing_template_decl)
17216     targs = add_to_template_args (current_template_args (), targs);
17217   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
17218 }
17219
17220 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
17221    result.  */
17222
17223 tree
17224 splice_late_return_type (tree type, tree late_return_type)
17225 {
17226   tree argvec;
17227
17228   if (late_return_type == NULL_TREE)
17229     return type;
17230   argvec = make_tree_vec (1);
17231   TREE_VEC_ELT (argvec, 0) = late_return_type;
17232   if (processing_template_decl)
17233     argvec = add_to_template_args (current_template_args (), argvec);
17234   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17235 }
17236
17237 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
17238
17239 bool
17240 is_auto (const_tree type)
17241 {
17242   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17243       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
17244     return true;
17245   else
17246     return false;
17247 }
17248
17249 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
17250    appear as a type-specifier for the declaration in question, we don't
17251    have to look through the whole type.  */
17252
17253 tree
17254 type_uses_auto (tree type)
17255 {
17256   enum tree_code code;
17257   if (is_auto (type))
17258     return type;
17259
17260   code = TREE_CODE (type);
17261
17262   if (code == POINTER_TYPE || code == REFERENCE_TYPE
17263       || code == OFFSET_TYPE || code == FUNCTION_TYPE
17264       || code == METHOD_TYPE || code == ARRAY_TYPE)
17265     return type_uses_auto (TREE_TYPE (type));
17266
17267   if (TYPE_PTRMEMFUNC_P (type))
17268     return type_uses_auto (TREE_TYPE (TREE_TYPE
17269                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
17270
17271   return NULL_TREE;
17272 }
17273
17274 /* For a given template T, return the list of typedefs referenced
17275    in T for which access check is needed at T instantiation time.
17276    T is either  a FUNCTION_DECL or a RECORD_TYPE.
17277    Those typedefs were added to T by the function
17278    append_type_to_template_for_access_check.  */
17279
17280 tree
17281 get_types_needing_access_check (tree t)
17282 {
17283   tree ti, result = NULL_TREE;
17284
17285   if (!t || t == error_mark_node)
17286     return t;
17287
17288   if (!(ti = get_template_info (t)))
17289     return NULL_TREE;
17290
17291   if (TREE_CODE (t) == RECORD_TYPE || TREE_CODE (t) == FUNCTION_DECL)
17292     {
17293       if (!TI_TEMPLATE (ti))
17294         return NULL_TREE;
17295
17296       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
17297     }
17298
17299   return result;
17300 }
17301
17302 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
17303    tied to T. That list of typedefs will be access checked at
17304    T instantiation time.
17305    T is either a FUNCTION_DECL or a RECORD_TYPE.
17306    TYPE_DECL is a TYPE_DECL node representing a typedef.
17307    SCOPE is the scope through which TYPE_DECL is accessed.
17308
17309    This function is a subroutine of
17310    append_type_to_template_for_access_check.  */
17311
17312 static void
17313 append_type_to_template_for_access_check_1 (tree t,
17314                                             tree type_decl,
17315                                             tree scope)
17316 {
17317   tree ti;
17318
17319   if (!t || t == error_mark_node)
17320     return;
17321
17322   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
17323                || TREE_CODE (t) == RECORD_TYPE)
17324               && type_decl
17325               && TREE_CODE (type_decl) == TYPE_DECL
17326               && scope);
17327
17328   if (!(ti = get_template_info (t)))
17329     return;
17330
17331   gcc_assert (TI_TEMPLATE (ti));
17332
17333   TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti) =
17334     tree_cons (type_decl, scope, TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti));
17335 }
17336
17337 /* Append TYPE_DECL to the template TEMPL.
17338    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
17339    At TEMPL instanciation time, TYPE_DECL will be checked to see
17340    if it can be accessed through SCOPE.
17341
17342    e.g. consider the following code snippet:
17343
17344      class C
17345      {
17346        typedef int myint;
17347      };
17348
17349      template<class U> struct S
17350      {
17351        C::myint mi;
17352      };
17353
17354      S<char> s;
17355
17356    At S<char> instantiation time, we need to check the access of C::myint
17357    In other words, we need to check the access of the myint typedef through
17358    the C scope. For that purpose, this function will add the myint typedef
17359    and the scope C through which its being accessed to a list of typedefs
17360    tied to the template S. That list will be walked at template instantiation
17361    time and access check performed on each typedefs it contains.
17362    Note that this particular code snippet should yield an error because
17363    myint is private to C.  */
17364
17365 void
17366 append_type_to_template_for_access_check (tree templ,
17367                                           tree type_decl,
17368                                           tree scope)
17369 {
17370   tree node;
17371
17372   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
17373
17374   /* Make sure we don't append the type to the template twice.  */
17375   for (node = get_types_needing_access_check (templ);
17376        node;
17377        node = TREE_CHAIN (node))
17378     {
17379       tree decl = TREE_PURPOSE (node);
17380       tree type_scope = TREE_VALUE (node);
17381
17382       if (decl == type_decl && type_scope == scope)
17383         return;
17384     }
17385
17386   append_type_to_template_for_access_check_1 (templ, type_decl, scope);
17387 }
17388
17389 #include "gt-cp-pt.h"