OSDN Git Service

PR c++/34950
[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  Free Software Foundation, Inc.
4    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
5    Rewritten by Jason Merrill (jason@cygnus.com).
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 /* Known bugs or deficiencies include:
24
25      all methods must be provided in header files; can't use a source
26      file that contains only the method templates and "just win".  */
27
28 #include "config.h"
29 #include "system.h"
30 #include "coretypes.h"
31 #include "tm.h"
32 #include "obstack.h"
33 #include "tree.h"
34 #include "pointer-set.h"
35 #include "flags.h"
36 #include "c-common.h"
37 #include "cp-tree.h"
38 #include "cp-objcp-common.h"
39 #include "tree-inline.h"
40 #include "decl.h"
41 #include "output.h"
42 #include "except.h"
43 #include "toplev.h"
44 #include "rtl.h"
45 #include "timevar.h"
46 #include "tree-iterator.h"
47 #include "vecprim.h"
48
49 /* The type of functions taking a tree, and some additional data, and
50    returning an int.  */
51 typedef int (*tree_fn_t) (tree, void*);
52
53 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
54    instantiations have been deferred, either because their definitions
55    were not yet available, or because we were putting off doing the work.  */
56 struct pending_template GTY (()) {
57   struct pending_template *next;
58   struct tinst_level *tinst;
59 };
60
61 static GTY(()) struct pending_template *pending_templates;
62 static GTY(()) struct pending_template *last_pending_template;
63
64 int processing_template_parmlist;
65 static int template_header_count;
66
67 static GTY(()) tree saved_trees;
68 static VEC(int,heap) *inline_parm_levels;
69
70 static GTY(()) struct tinst_level *current_tinst_level;
71
72 static GTY(()) tree saved_access_scope;
73
74 /* Live only within one (recursive) call to tsubst_expr.  We use
75    this to pass the statement expression node from the STMT_EXPR
76    to the EXPR_STMT that is its result.  */
77 static tree cur_stmt_expr;
78
79 /* A map from local variable declarations in the body of the template
80    presently being instantiated to the corresponding instantiated
81    local variables.  */
82 static htab_t local_specializations;
83
84 /* Contains canonical template parameter types. The vector is indexed by
85    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
86    TREE_LIST, whose TREE_VALUEs contain the canonical template
87    parameters of various types and levels.  */
88 static GTY(()) VEC(tree,gc) *canonical_template_parms;
89
90 #define UNIFY_ALLOW_NONE 0
91 #define UNIFY_ALLOW_MORE_CV_QUAL 1
92 #define UNIFY_ALLOW_LESS_CV_QUAL 2
93 #define UNIFY_ALLOW_DERIVED 4
94 #define UNIFY_ALLOW_INTEGER 8
95 #define UNIFY_ALLOW_OUTER_LEVEL 16
96 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
97 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
98
99 static void push_access_scope (tree);
100 static void pop_access_scope (tree);
101 static bool resolve_overloaded_unification (tree, tree, tree, tree,
102                                             unification_kind_t, int);
103 static int try_one_overload (tree, tree, tree, tree, tree,
104                              unification_kind_t, int, bool);
105 static int unify (tree, tree, tree, tree, int);
106 static void add_pending_template (tree);
107 static int push_tinst_level (tree);
108 static void pop_tinst_level (void);
109 static tree reopen_tinst_level (struct tinst_level *);
110 static tree tsubst_initializer_list (tree, tree);
111 static tree get_class_bindings (tree, tree, tree);
112 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
113                                    bool, bool);
114 static void tsubst_enum (tree, tree, tree);
115 static tree add_to_template_args (tree, tree);
116 static tree add_outermost_template_args (tree, tree);
117 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
118 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
119                                              tree);
120 static int  type_unification_real (tree, tree, tree, tree,
121                                    int, unification_kind_t, int);
122 static void note_template_header (int);
123 static tree convert_nontype_argument_function (tree, tree);
124 static tree convert_nontype_argument (tree, tree);
125 static tree convert_template_argument (tree, tree, tree,
126                                        tsubst_flags_t, int, tree);
127 static int for_each_template_parm (tree, tree_fn_t, void*,
128                                    struct pointer_set_t*, bool);
129 static tree expand_template_argument_pack (tree);
130 static tree build_template_parm_index (int, int, int, tree, tree);
131 static bool inline_needs_template_parms (tree);
132 static void push_inline_template_parms_recursive (tree, int);
133 static tree retrieve_local_specialization (tree);
134 static void register_local_specialization (tree, tree);
135 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
136 static int mark_template_parm (tree, void *);
137 static int template_parm_this_level_p (tree, void *);
138 static tree tsubst_friend_function (tree, tree);
139 static tree tsubst_friend_class (tree, tree);
140 static int can_complete_type_without_circularity (tree);
141 static tree get_bindings (tree, tree, tree, bool);
142 static int template_decl_level (tree);
143 static int check_cv_quals_for_unify (int, tree, tree);
144 static void template_parm_level_and_index (tree, int*, int*);
145 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
146 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
147 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
148 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
149 static void regenerate_decl_from_template (tree, tree);
150 static tree most_specialized_class (tree, tree);
151 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
152 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
153 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
154 static bool check_specialization_scope (void);
155 static tree process_partial_specialization (tree);
156 static void set_current_access_from_decl (tree);
157 static tree get_template_base (tree, tree, tree, tree);
158 static tree try_class_unification (tree, tree, tree, tree);
159 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
160                                            tree, tree);
161 static bool template_template_parm_bindings_ok_p (tree, tree);
162 static int template_args_equal (tree, tree);
163 static void tsubst_default_arguments (tree);
164 static tree for_each_template_parm_r (tree *, int *, void *);
165 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
166 static void copy_default_args_to_explicit_spec (tree);
167 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
168 static int eq_local_specializations (const void *, const void *);
169 static bool dependent_template_arg_p (tree);
170 static bool any_template_arguments_need_structural_equality_p (tree);
171 static bool dependent_type_p_r (tree);
172 static tree tsubst (tree, tree, tsubst_flags_t, 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
177 /* Make the current scope suitable for access checking when we are
178    processing T.  T can be FUNCTION_DECL for instantiated function
179    template, or VAR_DECL for static member variable (need by
180    instantiate_decl).  */
181
182 static void
183 push_access_scope (tree t)
184 {
185   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
186               || TREE_CODE (t) == VAR_DECL);
187
188   if (DECL_FRIEND_CONTEXT (t))
189     push_nested_class (DECL_FRIEND_CONTEXT (t));
190   else if (DECL_CLASS_SCOPE_P (t))
191     push_nested_class (DECL_CONTEXT (t));
192   else
193     push_to_top_level ();
194
195   if (TREE_CODE (t) == FUNCTION_DECL)
196     {
197       saved_access_scope = tree_cons
198         (NULL_TREE, current_function_decl, saved_access_scope);
199       current_function_decl = t;
200     }
201 }
202
203 /* Restore the scope set up by push_access_scope.  T is the node we
204    are processing.  */
205
206 static void
207 pop_access_scope (tree t)
208 {
209   if (TREE_CODE (t) == FUNCTION_DECL)
210     {
211       current_function_decl = TREE_VALUE (saved_access_scope);
212       saved_access_scope = TREE_CHAIN (saved_access_scope);
213     }
214
215   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
216     pop_nested_class ();
217   else
218     pop_from_top_level ();
219 }
220
221 /* Do any processing required when DECL (a member template
222    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
223    to DECL, unless it is a specialization, in which case the DECL
224    itself is returned.  */
225
226 tree
227 finish_member_template_decl (tree decl)
228 {
229   if (decl == error_mark_node)
230     return error_mark_node;
231
232   gcc_assert (DECL_P (decl));
233
234   if (TREE_CODE (decl) == TYPE_DECL)
235     {
236       tree type;
237
238       type = TREE_TYPE (decl);
239       if (type == error_mark_node)
240         return error_mark_node;
241       if (IS_AGGR_TYPE (type)
242           && CLASSTYPE_TEMPLATE_INFO (type)
243           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
244         {
245           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
246           check_member_template (tmpl);
247           return tmpl;
248         }
249       return NULL_TREE;
250     }
251   else if (TREE_CODE (decl) == FIELD_DECL)
252     error ("data member %qD cannot be a member template", decl);
253   else if (DECL_TEMPLATE_INFO (decl))
254     {
255       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
256         {
257           check_member_template (DECL_TI_TEMPLATE (decl));
258           return DECL_TI_TEMPLATE (decl);
259         }
260       else
261         return decl;
262     }
263   else
264     error ("invalid member template declaration %qD", decl);
265
266   return error_mark_node;
267 }
268
269 /* Return the template info node corresponding to T, whatever T is.  */
270
271 tree
272 get_template_info (tree t)
273 {
274   tree tinfo = NULL_TREE;
275
276   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
277     tinfo = DECL_TEMPLATE_INFO (t);
278
279   if (!tinfo && TREE_CODE (t) == TYPE_DECL)
280     t = TREE_TYPE (t);
281
282   if (TAGGED_TYPE_P (t))
283     tinfo = TYPE_TEMPLATE_INFO (t);
284
285   return tinfo;
286 }
287
288 /* Returns the template nesting level of the indicated class TYPE.
289
290    For example, in:
291      template <class T>
292      struct A
293      {
294        template <class U>
295        struct B {};
296      };
297
298    A<T>::B<U> has depth two, while A<T> has depth one.
299    Both A<T>::B<int> and A<int>::B<U> have depth one, if
300    they are instantiations, not specializations.
301
302    This function is guaranteed to return 0 if passed NULL_TREE so
303    that, for example, `template_class_depth (current_class_type)' is
304    always safe.  */
305
306 int
307 template_class_depth (tree type)
308 {
309   int depth;
310
311   for (depth = 0;
312        type && TREE_CODE (type) != NAMESPACE_DECL;
313        type = (TREE_CODE (type) == FUNCTION_DECL)
314          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
315     {
316       tree tinfo = get_template_info (type);
317
318       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
319           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
320         ++depth;
321     }
322
323   return depth;
324 }
325
326 /* Subroutine of maybe_begin_member_template_processing.
327    Returns true if processing DECL needs us to push template parms.  */
328
329 static bool
330 inline_needs_template_parms (tree decl)
331 {
332   if (! DECL_TEMPLATE_INFO (decl))
333     return false;
334
335   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
336           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
337 }
338
339 /* Subroutine of maybe_begin_member_template_processing.
340    Push the template parms in PARMS, starting from LEVELS steps into the
341    chain, and ending at the beginning, since template parms are listed
342    innermost first.  */
343
344 static void
345 push_inline_template_parms_recursive (tree parmlist, int levels)
346 {
347   tree parms = TREE_VALUE (parmlist);
348   int i;
349
350   if (levels > 1)
351     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
352
353   ++processing_template_decl;
354   current_template_parms
355     = tree_cons (size_int (processing_template_decl),
356                  parms, current_template_parms);
357   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
358
359   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
360                NULL);
361   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
362     {
363       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
364
365       if (parm == error_mark_node)
366         continue;
367
368       gcc_assert (DECL_P (parm));
369
370       switch (TREE_CODE (parm))
371         {
372         case TYPE_DECL:
373         case TEMPLATE_DECL:
374           pushdecl (parm);
375           break;
376
377         case PARM_DECL:
378           {
379             /* Make a CONST_DECL as is done in process_template_parm.
380                It is ugly that we recreate this here; the original
381                version built in process_template_parm is no longer
382                available.  */
383             tree decl = build_decl (CONST_DECL, DECL_NAME (parm),
384                                     TREE_TYPE (parm));
385             DECL_ARTIFICIAL (decl) = 1;
386             TREE_CONSTANT (decl) = 1;
387             TREE_INVARIANT (decl) = 1;
388             TREE_READONLY (decl) = 1;
389             DECL_INITIAL (decl) = DECL_INITIAL (parm);
390             SET_DECL_TEMPLATE_PARM_P (decl);
391             pushdecl (decl);
392           }
393           break;
394
395         default:
396           gcc_unreachable ();
397         }
398     }
399 }
400
401 /* Restore the template parameter context for a member template or
402    a friend template defined in a class definition.  */
403
404 void
405 maybe_begin_member_template_processing (tree decl)
406 {
407   tree parms;
408   int levels = 0;
409
410   if (inline_needs_template_parms (decl))
411     {
412       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
413       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
414
415       if (DECL_TEMPLATE_SPECIALIZATION (decl))
416         {
417           --levels;
418           parms = TREE_CHAIN (parms);
419         }
420
421       push_inline_template_parms_recursive (parms, levels);
422     }
423
424   /* Remember how many levels of template parameters we pushed so that
425      we can pop them later.  */
426   VEC_safe_push (int, heap, inline_parm_levels, levels);
427 }
428
429 /* Undo the effects of maybe_begin_member_template_processing.  */
430
431 void
432 maybe_end_member_template_processing (void)
433 {
434   int i;
435   int last;
436
437   if (VEC_length (int, inline_parm_levels) == 0)
438     return;
439
440   last = VEC_pop (int, inline_parm_levels);
441   for (i = 0; i < last; ++i)
442     {
443       --processing_template_decl;
444       current_template_parms = TREE_CHAIN (current_template_parms);
445       poplevel (0, 0, 0);
446     }
447 }
448
449 /* Return a new template argument vector which contains all of ARGS,
450    but has as its innermost set of arguments the EXTRA_ARGS.  */
451
452 static tree
453 add_to_template_args (tree args, tree extra_args)
454 {
455   tree new_args;
456   int extra_depth;
457   int i;
458   int j;
459
460   extra_depth = TMPL_ARGS_DEPTH (extra_args);
461   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
462
463   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
464     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
465
466   for (j = 1; j <= extra_depth; ++j, ++i)
467     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
468
469   return new_args;
470 }
471
472 /* Like add_to_template_args, but only the outermost ARGS are added to
473    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
474    (EXTRA_ARGS) levels are added.  This function is used to combine
475    the template arguments from a partial instantiation with the
476    template arguments used to attain the full instantiation from the
477    partial instantiation.  */
478
479 static tree
480 add_outermost_template_args (tree args, tree extra_args)
481 {
482   tree new_args;
483
484   /* If there are more levels of EXTRA_ARGS than there are ARGS,
485      something very fishy is going on.  */
486   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
487
488   /* If *all* the new arguments will be the EXTRA_ARGS, just return
489      them.  */
490   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
491     return extra_args;
492
493   /* For the moment, we make ARGS look like it contains fewer levels.  */
494   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
495
496   new_args = add_to_template_args (args, extra_args);
497
498   /* Now, we restore ARGS to its full dimensions.  */
499   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
500
501   return new_args;
502 }
503
504 /* Return the N levels of innermost template arguments from the ARGS.  */
505
506 tree
507 get_innermost_template_args (tree args, int n)
508 {
509   tree new_args;
510   int extra_levels;
511   int i;
512
513   gcc_assert (n >= 0);
514
515   /* If N is 1, just return the innermost set of template arguments.  */
516   if (n == 1)
517     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
518
519   /* If we're not removing anything, just return the arguments we were
520      given.  */
521   extra_levels = TMPL_ARGS_DEPTH (args) - n;
522   gcc_assert (extra_levels >= 0);
523   if (extra_levels == 0)
524     return args;
525
526   /* Make a new set of arguments, not containing the outer arguments.  */
527   new_args = make_tree_vec (n);
528   for (i = 1; i <= n; ++i)
529     SET_TMPL_ARGS_LEVEL (new_args, i,
530                          TMPL_ARGS_LEVEL (args, i + extra_levels));
531
532   return new_args;
533 }
534
535 /* The inverse of get_innermost_template_args: Return all but the innermost
536    EXTRA_LEVELS levels of template arguments from the ARGS.  */
537
538 static tree
539 strip_innermost_template_args (tree args, int extra_levels)
540 {
541   tree new_args;
542   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
543   int i;
544
545   gcc_assert (n >= 0);
546
547   /* If N is 1, just return the outermost set of template arguments.  */
548   if (n == 1)
549     return TMPL_ARGS_LEVEL (args, 1);
550
551   /* If we're not removing anything, just return the arguments we were
552      given.  */
553   gcc_assert (extra_levels >= 0);
554   if (extra_levels == 0)
555     return args;
556
557   /* Make a new set of arguments, not containing the inner arguments.  */
558   new_args = make_tree_vec (n);
559   for (i = 1; i <= n; ++i)
560     SET_TMPL_ARGS_LEVEL (new_args, i,
561                          TMPL_ARGS_LEVEL (args, i));
562
563   return new_args;
564 }
565
566 /* We've got a template header coming up; push to a new level for storing
567    the parms.  */
568
569 void
570 begin_template_parm_list (void)
571 {
572   /* We use a non-tag-transparent scope here, which causes pushtag to
573      put tags in this scope, rather than in the enclosing class or
574      namespace scope.  This is the right thing, since we want
575      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
576      global template class, push_template_decl handles putting the
577      TEMPLATE_DECL into top-level scope.  For a nested template class,
578      e.g.:
579
580        template <class T> struct S1 {
581          template <class T> struct S2 {};
582        };
583
584      pushtag contains special code to call pushdecl_with_scope on the
585      TEMPLATE_DECL for S2.  */
586   begin_scope (sk_template_parms, NULL);
587   ++processing_template_decl;
588   ++processing_template_parmlist;
589   note_template_header (0);
590 }
591
592 /* This routine is called when a specialization is declared.  If it is
593    invalid to declare a specialization here, an error is reported and
594    false is returned, otherwise this routine will return true.  */
595
596 static bool
597 check_specialization_scope (void)
598 {
599   tree scope = current_scope ();
600
601   /* [temp.expl.spec]
602
603      An explicit specialization shall be declared in the namespace of
604      which the template is a member, or, for member templates, in the
605      namespace of which the enclosing class or enclosing class
606      template is a member.  An explicit specialization of a member
607      function, member class or static data member of a class template
608      shall be declared in the namespace of which the class template
609      is a member.  */
610   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
611     {
612       error ("explicit specialization in non-namespace scope %qD", scope);
613       return false;
614     }
615
616   /* [temp.expl.spec]
617
618      In an explicit specialization declaration for a member of a class
619      template or a member template that appears in namespace scope,
620      the member template and some of its enclosing class templates may
621      remain unspecialized, except that the declaration shall not
622      explicitly specialize a class member template if its enclosing
623      class templates are not explicitly specialized as well.  */
624   if (current_template_parms)
625     {
626       error ("enclosing class templates are not explicitly specialized");
627       return false;
628     }
629
630   return true;
631 }
632
633 /* We've just seen template <>.  */
634
635 bool
636 begin_specialization (void)
637 {
638   begin_scope (sk_template_spec, NULL);
639   note_template_header (1);
640   return check_specialization_scope ();
641 }
642
643 /* Called at then end of processing a declaration preceded by
644    template<>.  */
645
646 void
647 end_specialization (void)
648 {
649   finish_scope ();
650   reset_specialization ();
651 }
652
653 /* Any template <>'s that we have seen thus far are not referring to a
654    function specialization.  */
655
656 void
657 reset_specialization (void)
658 {
659   processing_specialization = 0;
660   template_header_count = 0;
661 }
662
663 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
664    it was of the form template <>.  */
665
666 static void
667 note_template_header (int specialization)
668 {
669   processing_specialization = specialization;
670   template_header_count++;
671 }
672
673 /* We're beginning an explicit instantiation.  */
674
675 void
676 begin_explicit_instantiation (void)
677 {
678   gcc_assert (!processing_explicit_instantiation);
679   processing_explicit_instantiation = true;
680 }
681
682
683 void
684 end_explicit_instantiation (void)
685 {
686   gcc_assert (processing_explicit_instantiation);
687   processing_explicit_instantiation = false;
688 }
689
690 /* An explicit specialization or partial specialization TMPL is being
691    declared.  Check that the namespace in which the specialization is
692    occurring is permissible.  Returns false iff it is invalid to
693    specialize TMPL in the current namespace.  */
694
695 static bool
696 check_specialization_namespace (tree tmpl)
697 {
698   tree tpl_ns = decl_namespace_context (tmpl);
699
700   /* [tmpl.expl.spec]
701
702      An explicit specialization shall be declared in the namespace of
703      which the template is a member, or, for member templates, in the
704      namespace of which the enclosing class or enclosing class
705      template is a member.  An explicit specialization of a member
706      function, member class or static data member of a class template
707      shall be declared in the namespace of which the class template is
708      a member.  */
709   if (is_associated_namespace (current_namespace, tpl_ns))
710     /* Same or super-using namespace.  */
711     return true;
712   else
713     {
714       pedwarn ("specialization of %qD in different namespace", tmpl);
715       pedwarn ("  from definition of %q+#D", tmpl);
716       return false;
717     }
718 }
719
720 /* SPEC is an explicit instantiation.  Check that it is valid to
721    perform this explicit instantiation in the current namespace.  */
722
723 static void
724 check_explicit_instantiation_namespace (tree spec)
725 {
726   tree ns;
727
728   /* DR 275: An explicit instantiation shall appear in an enclosing
729      namespace of its template.  */
730   ns = decl_namespace_context (spec);
731   if (!is_ancestor (current_namespace, ns))
732     pedwarn ("explicit instantiation of %qD in namespace %qD "
733              "(which does not enclose namespace %qD)",
734              spec, current_namespace, ns);
735 }
736
737 /* The TYPE is being declared.  If it is a template type, that means it
738    is a partial specialization.  Do appropriate error-checking.  */
739
740 tree
741 maybe_process_partial_specialization (tree type)
742 {
743   tree context;
744
745   if (type == error_mark_node)
746     return error_mark_node;
747
748   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
749     {
750       error ("name of class shadows template template parameter %qD",
751              TYPE_NAME (type));
752       return error_mark_node;
753     }
754
755   context = TYPE_CONTEXT (type);
756
757   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
758     {
759       /* This is for ordinary explicit specialization and partial
760          specialization of a template class such as:
761
762            template <> class C<int>;
763
764          or:
765
766            template <class T> class C<T*>;
767
768          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
769
770       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
771           && !COMPLETE_TYPE_P (type))
772         {
773           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
774           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
775           if (processing_template_decl)
776             push_template_decl (TYPE_MAIN_DECL (type));
777         }
778       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
779         error ("specialization of %qT after instantiation", type);
780     }
781   else if (CLASS_TYPE_P (type)
782            && !CLASSTYPE_USE_TEMPLATE (type)
783            && CLASSTYPE_TEMPLATE_INFO (type)
784            && context && CLASS_TYPE_P (context)
785            && CLASSTYPE_TEMPLATE_INFO (context))
786     {
787       /* This is for an explicit specialization of member class
788          template according to [temp.expl.spec/18]:
789
790            template <> template <class U> class C<int>::D;
791
792          The context `C<int>' must be an implicit instantiation.
793          Otherwise this is just a member class template declared
794          earlier like:
795
796            template <> class C<int> { template <class U> class D; };
797            template <> template <class U> class C<int>::D;
798
799          In the first case, `C<int>::D' is a specialization of `C<T>::D'
800          while in the second case, `C<int>::D' is a primary template
801          and `C<T>::D' may not exist.  */
802
803       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
804           && !COMPLETE_TYPE_P (type))
805         {
806           tree t;
807
808           if (current_namespace
809               != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
810             {
811               pedwarn ("specializing %q#T in different namespace", type);
812               pedwarn ("  from definition of %q+#D",
813                        CLASSTYPE_TI_TEMPLATE (type));
814             }
815
816           /* Check for invalid specialization after instantiation:
817
818                template <> template <> class C<int>::D<int>;
819                template <> template <class U> class C<int>::D;  */
820
821           for (t = DECL_TEMPLATE_INSTANTIATIONS
822                  (most_general_template (CLASSTYPE_TI_TEMPLATE (type)));
823                t; t = TREE_CHAIN (t))
824             if (TREE_VALUE (t) != type
825                 && TYPE_CONTEXT (TREE_VALUE (t)) == context)
826               error ("specialization %qT after instantiation %qT",
827                      type, TREE_VALUE (t));
828
829           /* Mark TYPE as a specialization.  And as a result, we only
830              have one level of template argument for the innermost
831              class template.  */
832           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
833           CLASSTYPE_TI_ARGS (type)
834             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
835         }
836     }
837   else if (processing_specialization)
838     {
839       error ("explicit specialization of non-template %qT", type);
840       return error_mark_node;
841     }
842
843   return type;
844 }
845
846 /* Returns nonzero if we can optimize the retrieval of specializations
847    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
848    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
849
850 static inline bool
851 optimize_specialization_lookup_p (tree tmpl)
852 {
853   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
854           && DECL_CLASS_SCOPE_P (tmpl)
855           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
856              parameter.  */
857           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
858           /* The optimized lookup depends on the fact that the
859              template arguments for the member function template apply
860              purely to the containing class, which is not true if the
861              containing class is an explicit or partial
862              specialization.  */
863           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
864           && !DECL_MEMBER_TEMPLATE_P (tmpl)
865           && !DECL_CONV_FN_P (tmpl)
866           /* It is possible to have a template that is not a member
867              template and is not a member of a template class:
868
869              template <typename T>
870              struct S { friend A::f(); };
871
872              Here, the friend function is a template, but the context does
873              not have template information.  The optimized lookup relies
874              on having ARGS be the template arguments for both the class
875              and the function template.  */
876           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
877 }
878
879 /* Retrieve the specialization (in the sense of [temp.spec] - a
880    specialization is either an instantiation or an explicit
881    specialization) of TMPL for the given template ARGS.  If there is
882    no such specialization, return NULL_TREE.  The ARGS are a vector of
883    arguments, or a vector of vectors of arguments, in the case of
884    templates with more than one level of parameters.
885
886    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
887    then we search for a partial specialization matching ARGS.  This
888    parameter is ignored if TMPL is not a class template.  */
889
890 static tree
891 retrieve_specialization (tree tmpl, tree args,
892                          bool class_specializations_p)
893 {
894   if (args == error_mark_node)
895     return NULL_TREE;
896
897   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
898
899   /* There should be as many levels of arguments as there are
900      levels of parameters.  */
901   gcc_assert (TMPL_ARGS_DEPTH (args)
902               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
903
904   if (optimize_specialization_lookup_p (tmpl))
905     {
906       tree class_template;
907       tree class_specialization;
908       VEC(tree,gc) *methods;
909       tree fns;
910       int idx;
911
912       /* The template arguments actually apply to the containing
913          class.  Find the class specialization with those
914          arguments.  */
915       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
916       class_specialization
917         = retrieve_specialization (class_template, args,
918                                    /*class_specializations_p=*/false);
919       if (!class_specialization)
920         return NULL_TREE;
921       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
922          for the specialization.  */
923       idx = class_method_index_for_fn (class_specialization, tmpl);
924       if (idx == -1)
925         return NULL_TREE;
926       /* Iterate through the methods with the indicated name, looking
927          for the one that has an instance of TMPL.  */
928       methods = CLASSTYPE_METHOD_VEC (class_specialization);
929       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
930         {
931           tree fn = OVL_CURRENT (fns);
932           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl)
933             return fn;
934         }
935       return NULL_TREE;
936     }
937   else
938     {
939       tree *sp;
940       tree *head;
941
942       /* Class templates store their instantiations on the
943          DECL_TEMPLATE_INSTANTIATIONS list; other templates use the
944          DECL_TEMPLATE_SPECIALIZATIONS list.  */
945       if (!class_specializations_p
946           && TREE_CODE (DECL_TEMPLATE_RESULT (tmpl)) == TYPE_DECL
947           && TAGGED_TYPE_P (TREE_TYPE (tmpl)))
948         sp = &DECL_TEMPLATE_INSTANTIATIONS (tmpl);
949       else
950         sp = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
951       head = sp;
952       /* Iterate through the list until we find a matching template.  */
953       while (*sp != NULL_TREE)
954         {
955           tree spec = *sp;
956
957           if (comp_template_args (TREE_PURPOSE (spec), args))
958             {
959               /* Use the move-to-front heuristic to speed up future
960                  searches.  */
961               if (spec != *head)
962                 {
963                   *sp = TREE_CHAIN (*sp);
964                   TREE_CHAIN (spec) = *head;
965                   *head = spec;
966                 }
967               return TREE_VALUE (spec);
968             }
969           sp = &TREE_CHAIN (spec);
970         }
971     }
972
973   return NULL_TREE;
974 }
975
976 /* Like retrieve_specialization, but for local declarations.  */
977
978 static tree
979 retrieve_local_specialization (tree tmpl)
980 {
981   tree spec;
982
983   if (local_specializations == NULL)
984     return NULL_TREE;
985
986   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
987                                      htab_hash_pointer (tmpl));
988   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
989 }
990
991 /* Returns nonzero iff DECL is a specialization of TMPL.  */
992
993 int
994 is_specialization_of (tree decl, tree tmpl)
995 {
996   tree t;
997
998   if (TREE_CODE (decl) == FUNCTION_DECL)
999     {
1000       for (t = decl;
1001            t != NULL_TREE;
1002            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1003         if (t == tmpl)
1004           return 1;
1005     }
1006   else
1007     {
1008       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1009
1010       for (t = TREE_TYPE (decl);
1011            t != NULL_TREE;
1012            t = CLASSTYPE_USE_TEMPLATE (t)
1013              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1014         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1015           return 1;
1016     }
1017
1018   return 0;
1019 }
1020
1021 /* Returns nonzero iff DECL is a specialization of friend declaration
1022    FRIEND according to [temp.friend].  */
1023
1024 bool
1025 is_specialization_of_friend (tree decl, tree friend)
1026 {
1027   bool need_template = true;
1028   int template_depth;
1029
1030   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1031               || TREE_CODE (decl) == TYPE_DECL);
1032
1033   /* For [temp.friend/6] when FRIEND is an ordinary member function
1034      of a template class, we want to check if DECL is a specialization
1035      if this.  */
1036   if (TREE_CODE (friend) == FUNCTION_DECL
1037       && DECL_TEMPLATE_INFO (friend)
1038       && !DECL_USE_TEMPLATE (friend))
1039     {
1040       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1041       friend = DECL_TI_TEMPLATE (friend);
1042       need_template = false;
1043     }
1044   else if (TREE_CODE (friend) == TEMPLATE_DECL
1045            && !PRIMARY_TEMPLATE_P (friend))
1046     need_template = false;
1047
1048   /* There is nothing to do if this is not a template friend.  */
1049   if (TREE_CODE (friend) != TEMPLATE_DECL)
1050     return false;
1051
1052   if (is_specialization_of (decl, friend))
1053     return true;
1054
1055   /* [temp.friend/6]
1056      A member of a class template may be declared to be a friend of a
1057      non-template class.  In this case, the corresponding member of
1058      every specialization of the class template is a friend of the
1059      class granting friendship.
1060
1061      For example, given a template friend declaration
1062
1063        template <class T> friend void A<T>::f();
1064
1065      the member function below is considered a friend
1066
1067        template <> struct A<int> {
1068          void f();
1069        };
1070
1071      For this type of template friend, TEMPLATE_DEPTH below will be
1072      nonzero.  To determine if DECL is a friend of FRIEND, we first
1073      check if the enclosing class is a specialization of another.  */
1074
1075   template_depth = template_class_depth (DECL_CONTEXT (friend));
1076   if (template_depth
1077       && DECL_CLASS_SCOPE_P (decl)
1078       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1079                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend))))
1080     {
1081       /* Next, we check the members themselves.  In order to handle
1082          a few tricky cases, such as when FRIEND's are
1083
1084            template <class T> friend void A<T>::g(T t);
1085            template <class T> template <T t> friend void A<T>::h();
1086
1087          and DECL's are
1088
1089            void A<int>::g(int);
1090            template <int> void A<int>::h();
1091
1092          we need to figure out ARGS, the template arguments from
1093          the context of DECL.  This is required for template substitution
1094          of `T' in the function parameter of `g' and template parameter
1095          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1096
1097       tree context = DECL_CONTEXT (decl);
1098       tree args = NULL_TREE;
1099       int current_depth = 0;
1100
1101       while (current_depth < template_depth)
1102         {
1103           if (CLASSTYPE_TEMPLATE_INFO (context))
1104             {
1105               if (current_depth == 0)
1106                 args = TYPE_TI_ARGS (context);
1107               else
1108                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1109               current_depth++;
1110             }
1111           context = TYPE_CONTEXT (context);
1112         }
1113
1114       if (TREE_CODE (decl) == FUNCTION_DECL)
1115         {
1116           bool is_template;
1117           tree friend_type;
1118           tree decl_type;
1119           tree friend_args_type;
1120           tree decl_args_type;
1121
1122           /* Make sure that both DECL and FRIEND are templates or
1123              non-templates.  */
1124           is_template = DECL_TEMPLATE_INFO (decl)
1125                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1126           if (need_template ^ is_template)
1127             return false;
1128           else if (is_template)
1129             {
1130               /* If both are templates, check template parameter list.  */
1131               tree friend_parms
1132                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend),
1133                                          args, tf_none);
1134               if (!comp_template_parms
1135                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1136                       friend_parms))
1137                 return false;
1138
1139               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1140             }
1141           else
1142             decl_type = TREE_TYPE (decl);
1143
1144           friend_type = tsubst_function_type (TREE_TYPE (friend), args,
1145                                               tf_none, NULL_TREE);
1146           if (friend_type == error_mark_node)
1147             return false;
1148
1149           /* Check if return types match.  */
1150           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1151             return false;
1152
1153           /* Check if function parameter types match, ignoring the
1154              `this' parameter.  */
1155           friend_args_type = TYPE_ARG_TYPES (friend_type);
1156           decl_args_type = TYPE_ARG_TYPES (decl_type);
1157           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend))
1158             friend_args_type = TREE_CHAIN (friend_args_type);
1159           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1160             decl_args_type = TREE_CHAIN (decl_args_type);
1161
1162           return compparms (decl_args_type, friend_args_type);
1163         }
1164       else
1165         {
1166           /* DECL is a TYPE_DECL */
1167           bool is_template;
1168           tree decl_type = TREE_TYPE (decl);
1169
1170           /* Make sure that both DECL and FRIEND are templates or
1171              non-templates.  */
1172           is_template
1173             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1174               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1175
1176           if (need_template ^ is_template)
1177             return false;
1178           else if (is_template)
1179             {
1180               tree friend_parms;
1181               /* If both are templates, check the name of the two
1182                  TEMPLATE_DECL's first because is_friend didn't.  */
1183               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1184                   != DECL_NAME (friend))
1185                 return false;
1186
1187               /* Now check template parameter list.  */
1188               friend_parms
1189                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend),
1190                                          args, tf_none);
1191               return comp_template_parms
1192                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1193                  friend_parms);
1194             }
1195           else
1196             return (DECL_NAME (decl)
1197                     == DECL_NAME (friend));
1198         }
1199     }
1200   return false;
1201 }
1202
1203 /* Register the specialization SPEC as a specialization of TMPL with
1204    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1205    is actually just a friend declaration.  Returns SPEC, or an
1206    equivalent prior declaration, if available.  */
1207
1208 static tree
1209 register_specialization (tree spec, tree tmpl, tree args, bool is_friend)
1210 {
1211   tree fn;
1212
1213   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1214
1215   if (TREE_CODE (spec) == FUNCTION_DECL
1216       && uses_template_parms (DECL_TI_ARGS (spec)))
1217     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1218        register it; we want the corresponding TEMPLATE_DECL instead.
1219        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1220        the more obvious `uses_template_parms (spec)' to avoid problems
1221        with default function arguments.  In particular, given
1222        something like this:
1223
1224           template <class T> void f(T t1, T t = T())
1225
1226        the default argument expression is not substituted for in an
1227        instantiation unless and until it is actually needed.  */
1228     return spec;
1229
1230   fn = retrieve_specialization (tmpl, args,
1231                                 /*class_specializations_p=*/false);
1232   /* We can sometimes try to re-register a specialization that we've
1233      already got.  In particular, regenerate_decl_from_template calls
1234      duplicate_decls which will update the specialization list.  But,
1235      we'll still get called again here anyhow.  It's more convenient
1236      to simply allow this than to try to prevent it.  */
1237   if (fn == spec)
1238     return spec;
1239   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1240     {
1241       if (DECL_TEMPLATE_INSTANTIATION (fn))
1242         {
1243           if (TREE_USED (fn)
1244               || DECL_EXPLICIT_INSTANTIATION (fn))
1245             {
1246               error ("specialization of %qD after instantiation",
1247                      fn);
1248               return error_mark_node;
1249             }
1250           else
1251             {
1252               tree clone;
1253               /* This situation should occur only if the first
1254                  specialization is an implicit instantiation, the
1255                  second is an explicit specialization, and the
1256                  implicit instantiation has not yet been used.  That
1257                  situation can occur if we have implicitly
1258                  instantiated a member function and then specialized
1259                  it later.
1260
1261                  We can also wind up here if a friend declaration that
1262                  looked like an instantiation turns out to be a
1263                  specialization:
1264
1265                    template <class T> void foo(T);
1266                    class S { friend void foo<>(int) };
1267                    template <> void foo(int);
1268
1269                  We transform the existing DECL in place so that any
1270                  pointers to it become pointers to the updated
1271                  declaration.
1272
1273                  If there was a definition for the template, but not
1274                  for the specialization, we want this to look as if
1275                  there were no definition, and vice versa.  */
1276               DECL_INITIAL (fn) = NULL_TREE;
1277               duplicate_decls (spec, fn, is_friend);
1278               /* The call to duplicate_decls will have applied
1279                  [temp.expl.spec]:
1280
1281                    An explicit specialization of a function template
1282                    is inline only if it is explicitly declared to be,
1283                    and independently of whether its function template
1284                    is.
1285
1286                 to the primary function; now copy the inline bits to
1287                 the various clones.  */
1288               FOR_EACH_CLONE (clone, fn)
1289                 {
1290                   DECL_DECLARED_INLINE_P (clone)
1291                     = DECL_DECLARED_INLINE_P (fn);
1292                   DECL_INLINE (clone)
1293                     = DECL_INLINE (fn);
1294                 }
1295               check_specialization_namespace (fn);
1296
1297               return fn;
1298             }
1299         }
1300       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1301         {
1302           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1303             /* Dup decl failed, but this is a new definition. Set the
1304                line number so any errors match this new
1305                definition.  */
1306             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1307
1308           return fn;
1309         }
1310     }
1311
1312   /* A specialization must be declared in the same namespace as the
1313      template it is specializing.  */
1314   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1315       && !check_specialization_namespace (tmpl))
1316     DECL_CONTEXT (spec) = FROB_CONTEXT (decl_namespace_context (tmpl));
1317
1318   if (!optimize_specialization_lookup_p (tmpl))
1319     DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
1320       = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
1321
1322   return spec;
1323 }
1324
1325 /* Unregister the specialization SPEC as a specialization of TMPL.
1326    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1327    if the SPEC was listed as a specialization of TMPL.  */
1328
1329 bool
1330 reregister_specialization (tree spec, tree tmpl, tree new_spec)
1331 {
1332   tree* s;
1333
1334   for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
1335        *s != NULL_TREE;
1336        s = &TREE_CHAIN (*s))
1337     if (TREE_VALUE (*s) == spec)
1338       {
1339         if (!new_spec)
1340           *s = TREE_CHAIN (*s);
1341         else
1342           TREE_VALUE (*s) = new_spec;
1343         return 1;
1344       }
1345
1346   return 0;
1347 }
1348
1349 /* Compare an entry in the local specializations hash table P1 (which
1350    is really a pointer to a TREE_LIST) with P2 (which is really a
1351    DECL).  */
1352
1353 static int
1354 eq_local_specializations (const void *p1, const void *p2)
1355 {
1356   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1357 }
1358
1359 /* Hash P1, an entry in the local specializations table.  */
1360
1361 static hashval_t
1362 hash_local_specialization (const void* p1)
1363 {
1364   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1365 }
1366
1367 /* Like register_specialization, but for local declarations.  We are
1368    registering SPEC, an instantiation of TMPL.  */
1369
1370 static void
1371 register_local_specialization (tree spec, tree tmpl)
1372 {
1373   void **slot;
1374
1375   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1376                                    htab_hash_pointer (tmpl), INSERT);
1377   *slot = build_tree_list (spec, tmpl);
1378 }
1379
1380 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1381    specialized class.  */
1382
1383 bool
1384 explicit_class_specialization_p (tree type)
1385 {
1386   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1387     return false;
1388   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1389 }
1390
1391 /* Print the list of candidate FNS in an error message.  */
1392
1393 void
1394 print_candidates (tree fns)
1395 {
1396   tree fn;
1397
1398   const char *str = "candidates are:";
1399
1400   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1401     {
1402       tree f;
1403
1404       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1405         error ("%s %+#D", str, OVL_CURRENT (f));
1406       str = "               ";
1407     }
1408 }
1409
1410 /* Returns the template (one of the functions given by TEMPLATE_ID)
1411    which can be specialized to match the indicated DECL with the
1412    explicit template args given in TEMPLATE_ID.  The DECL may be
1413    NULL_TREE if none is available.  In that case, the functions in
1414    TEMPLATE_ID are non-members.
1415
1416    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1417    specialization of a member template.
1418
1419    The TEMPLATE_COUNT is the number of references to qualifying
1420    template classes that appeared in the name of the function. See
1421    check_explicit_specialization for a more accurate description.
1422
1423    TSK indicates what kind of template declaration (if any) is being
1424    declared.  TSK_TEMPLATE indicates that the declaration given by
1425    DECL, though a FUNCTION_DECL, has template parameters, and is
1426    therefore a template function.
1427
1428    The template args (those explicitly specified and those deduced)
1429    are output in a newly created vector *TARGS_OUT.
1430
1431    If it is impossible to determine the result, an error message is
1432    issued.  The error_mark_node is returned to indicate failure.  */
1433
1434 static tree
1435 determine_specialization (tree template_id,
1436                           tree decl,
1437                           tree* targs_out,
1438                           int need_member_template,
1439                           int template_count,
1440                           tmpl_spec_kind tsk)
1441 {
1442   tree fns;
1443   tree targs;
1444   tree explicit_targs;
1445   tree candidates = NULL_TREE;
1446   /* A TREE_LIST of templates of which DECL may be a specialization.
1447      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1448      corresponding TREE_PURPOSE is the set of template arguments that,
1449      when used to instantiate the template, would produce a function
1450      with the signature of DECL.  */
1451   tree templates = NULL_TREE;
1452   int header_count;
1453   struct cp_binding_level *b;
1454
1455   *targs_out = NULL_TREE;
1456
1457   if (template_id == error_mark_node || decl == error_mark_node)
1458     return error_mark_node;
1459
1460   fns = TREE_OPERAND (template_id, 0);
1461   explicit_targs = TREE_OPERAND (template_id, 1);
1462
1463   if (fns == error_mark_node)
1464     return error_mark_node;
1465
1466   /* Check for baselinks.  */
1467   if (BASELINK_P (fns))
1468     fns = BASELINK_FUNCTIONS (fns);
1469
1470   if (!is_overloaded_fn (fns))
1471     {
1472       error ("%qD is not a function template", fns);
1473       return error_mark_node;
1474     }
1475
1476   /* Count the number of template headers specified for this
1477      specialization.  */
1478   header_count = 0;
1479   for (b = current_binding_level;
1480        b->kind == sk_template_parms;
1481        b = b->level_chain)
1482     ++header_count;
1483
1484   for (; fns; fns = OVL_NEXT (fns))
1485     {
1486       tree fn = OVL_CURRENT (fns);
1487
1488       if (TREE_CODE (fn) == TEMPLATE_DECL)
1489         {
1490           tree decl_arg_types;
1491           tree fn_arg_types;
1492
1493           /* In case of explicit specialization, we need to check if
1494              the number of template headers appearing in the specialization
1495              is correct. This is usually done in check_explicit_specialization,
1496              but the check done there cannot be exhaustive when specializing
1497              member functions. Consider the following code:
1498
1499              template <> void A<int>::f(int);
1500              template <> template <> void A<int>::f(int);
1501
1502              Assuming that A<int> is not itself an explicit specialization
1503              already, the first line specializes "f" which is a non-template
1504              member function, whilst the second line specializes "f" which
1505              is a template member function. So both lines are syntactically
1506              correct, and check_explicit_specialization does not reject
1507              them.
1508
1509              Here, we can do better, as we are matching the specialization
1510              against the declarations. We count the number of template
1511              headers, and we check if they match TEMPLATE_COUNT + 1
1512              (TEMPLATE_COUNT is the number of qualifying template classes,
1513              plus there must be another header for the member template
1514              itself).
1515
1516              Notice that if header_count is zero, this is not a
1517              specialization but rather a template instantiation, so there
1518              is no check we can perform here.  */
1519           if (header_count && header_count != template_count + 1)
1520             continue;
1521
1522           /* Check that the number of template arguments at the
1523              innermost level for DECL is the same as for FN.  */
1524           if (current_binding_level->kind == sk_template_parms
1525               && !current_binding_level->explicit_spec_p
1526               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1527                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1528                                       (current_template_parms))))
1529             continue;
1530
1531           /* DECL might be a specialization of FN.  */
1532           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1533           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1534
1535           /* For a non-static member function, we need to make sure
1536              that the const qualification is the same.  Since
1537              get_bindings does not try to merge the "this" parameter,
1538              we must do the comparison explicitly.  */
1539           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1540               && !same_type_p (TREE_VALUE (fn_arg_types),
1541                                TREE_VALUE (decl_arg_types)))
1542             continue;
1543
1544           /* Skip the "this" parameter and, for constructors of
1545              classes with virtual bases, the VTT parameter.  A
1546              full specialization of a constructor will have a VTT
1547              parameter, but a template never will.  */ 
1548           decl_arg_types 
1549             = skip_artificial_parms_for (decl, decl_arg_types);
1550           fn_arg_types 
1551             = skip_artificial_parms_for (fn, fn_arg_types);
1552
1553           /* Check that the number of function parameters matches.
1554              For example,
1555                template <class T> void f(int i = 0);
1556                template <> void f<int>();
1557              The specialization f<int> is invalid but is not caught
1558              by get_bindings below.  */
1559           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1560             continue;
1561
1562           /* Function templates cannot be specializations; there are
1563              no partial specializations of functions.  Therefore, if
1564              the type of DECL does not match FN, there is no
1565              match.  */
1566           if (tsk == tsk_template
1567               && !compparms (fn_arg_types, decl_arg_types))
1568             continue;
1569
1570           /* See whether this function might be a specialization of this
1571              template.  */
1572           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1573
1574           if (!targs)
1575             /* We cannot deduce template arguments that when used to
1576                specialize TMPL will produce DECL.  */
1577             continue;
1578
1579           /* Save this template, and the arguments deduced.  */
1580           templates = tree_cons (targs, fn, templates);
1581         }
1582       else if (need_member_template)
1583         /* FN is an ordinary member function, and we need a
1584            specialization of a member template.  */
1585         ;
1586       else if (TREE_CODE (fn) != FUNCTION_DECL)
1587         /* We can get IDENTIFIER_NODEs here in certain erroneous
1588            cases.  */
1589         ;
1590       else if (!DECL_FUNCTION_MEMBER_P (fn))
1591         /* This is just an ordinary non-member function.  Nothing can
1592            be a specialization of that.  */
1593         ;
1594       else if (DECL_ARTIFICIAL (fn))
1595         /* Cannot specialize functions that are created implicitly.  */
1596         ;
1597       else
1598         {
1599           tree decl_arg_types;
1600
1601           /* This is an ordinary member function.  However, since
1602              we're here, we can assume it's enclosing class is a
1603              template class.  For example,
1604
1605                template <typename T> struct S { void f(); };
1606                template <> void S<int>::f() {}
1607
1608              Here, S<int>::f is a non-template, but S<int> is a
1609              template class.  If FN has the same type as DECL, we
1610              might be in business.  */
1611
1612           if (!DECL_TEMPLATE_INFO (fn))
1613             /* Its enclosing class is an explicit specialization
1614                of a template class.  This is not a candidate.  */
1615             continue;
1616
1617           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1618                             TREE_TYPE (TREE_TYPE (fn))))
1619             /* The return types differ.  */
1620             continue;
1621
1622           /* Adjust the type of DECL in case FN is a static member.  */
1623           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1624           if (DECL_STATIC_FUNCTION_P (fn)
1625               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1626             decl_arg_types = TREE_CHAIN (decl_arg_types);
1627
1628           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1629                          decl_arg_types))
1630             /* They match!  */
1631             candidates = tree_cons (NULL_TREE, fn, candidates);
1632         }
1633     }
1634
1635   if (templates && TREE_CHAIN (templates))
1636     {
1637       /* We have:
1638
1639            [temp.expl.spec]
1640
1641            It is possible for a specialization with a given function
1642            signature to be instantiated from more than one function
1643            template.  In such cases, explicit specification of the
1644            template arguments must be used to uniquely identify the
1645            function template specialization being specialized.
1646
1647          Note that here, there's no suggestion that we're supposed to
1648          determine which of the candidate templates is most
1649          specialized.  However, we, also have:
1650
1651            [temp.func.order]
1652
1653            Partial ordering of overloaded function template
1654            declarations is used in the following contexts to select
1655            the function template to which a function template
1656            specialization refers:
1657
1658            -- when an explicit specialization refers to a function
1659               template.
1660
1661          So, we do use the partial ordering rules, at least for now.
1662          This extension can only serve to make invalid programs valid,
1663          so it's safe.  And, there is strong anecdotal evidence that
1664          the committee intended the partial ordering rules to apply;
1665          the EDG front end has that behavior, and John Spicer claims
1666          that the committee simply forgot to delete the wording in
1667          [temp.expl.spec].  */
1668       tree tmpl = most_specialized_instantiation (templates);
1669       if (tmpl != error_mark_node)
1670         {
1671           templates = tmpl;
1672           TREE_CHAIN (templates) = NULL_TREE;
1673         }
1674     }
1675
1676   if (templates == NULL_TREE && candidates == NULL_TREE)
1677     {
1678       error ("template-id %qD for %q+D does not match any template "
1679              "declaration", template_id, decl);
1680       return error_mark_node;
1681     }
1682   else if ((templates && TREE_CHAIN (templates))
1683            || (candidates && TREE_CHAIN (candidates))
1684            || (templates && candidates))
1685     {
1686       error ("ambiguous template specialization %qD for %q+D",
1687              template_id, decl);
1688       chainon (candidates, templates);
1689       print_candidates (candidates);
1690       return error_mark_node;
1691     }
1692
1693   /* We have one, and exactly one, match.  */
1694   if (candidates)
1695     {
1696       tree fn = TREE_VALUE (candidates);
1697       /* DECL is a re-declaration of a template function.  */
1698       if (TREE_CODE (fn) == TEMPLATE_DECL)
1699         return fn;
1700       /* It was a specialization of an ordinary member function in a
1701          template class.  */
1702       *targs_out = copy_node (DECL_TI_ARGS (fn));
1703       return DECL_TI_TEMPLATE (fn);
1704     }
1705
1706   /* It was a specialization of a template.  */
1707   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1708   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1709     {
1710       *targs_out = copy_node (targs);
1711       SET_TMPL_ARGS_LEVEL (*targs_out,
1712                            TMPL_ARGS_DEPTH (*targs_out),
1713                            TREE_PURPOSE (templates));
1714     }
1715   else
1716     *targs_out = TREE_PURPOSE (templates);
1717   return TREE_VALUE (templates);
1718 }
1719
1720 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1721    but with the default argument values filled in from those in the
1722    TMPL_TYPES.  */
1723
1724 static tree
1725 copy_default_args_to_explicit_spec_1 (tree spec_types,
1726                                       tree tmpl_types)
1727 {
1728   tree new_spec_types;
1729
1730   if (!spec_types)
1731     return NULL_TREE;
1732
1733   if (spec_types == void_list_node)
1734     return void_list_node;
1735
1736   /* Substitute into the rest of the list.  */
1737   new_spec_types =
1738     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1739                                           TREE_CHAIN (tmpl_types));
1740
1741   /* Add the default argument for this parameter.  */
1742   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1743                          TREE_VALUE (spec_types),
1744                          new_spec_types);
1745 }
1746
1747 /* DECL is an explicit specialization.  Replicate default arguments
1748    from the template it specializes.  (That way, code like:
1749
1750      template <class T> void f(T = 3);
1751      template <> void f(double);
1752      void g () { f (); }
1753
1754    works, as required.)  An alternative approach would be to look up
1755    the correct default arguments at the call-site, but this approach
1756    is consistent with how implicit instantiations are handled.  */
1757
1758 static void
1759 copy_default_args_to_explicit_spec (tree decl)
1760 {
1761   tree tmpl;
1762   tree spec_types;
1763   tree tmpl_types;
1764   tree new_spec_types;
1765   tree old_type;
1766   tree new_type;
1767   tree t;
1768   tree object_type = NULL_TREE;
1769   tree in_charge = NULL_TREE;
1770   tree vtt = NULL_TREE;
1771
1772   /* See if there's anything we need to do.  */
1773   tmpl = DECL_TI_TEMPLATE (decl);
1774   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
1775   for (t = tmpl_types; t; t = TREE_CHAIN (t))
1776     if (TREE_PURPOSE (t))
1777       break;
1778   if (!t)
1779     return;
1780
1781   old_type = TREE_TYPE (decl);
1782   spec_types = TYPE_ARG_TYPES (old_type);
1783
1784   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1785     {
1786       /* Remove the this pointer, but remember the object's type for
1787          CV quals.  */
1788       object_type = TREE_TYPE (TREE_VALUE (spec_types));
1789       spec_types = TREE_CHAIN (spec_types);
1790       tmpl_types = TREE_CHAIN (tmpl_types);
1791
1792       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
1793         {
1794           /* DECL may contain more parameters than TMPL due to the extra
1795              in-charge parameter in constructors and destructors.  */
1796           in_charge = spec_types;
1797           spec_types = TREE_CHAIN (spec_types);
1798         }
1799       if (DECL_HAS_VTT_PARM_P (decl))
1800         {
1801           vtt = spec_types;
1802           spec_types = TREE_CHAIN (spec_types);
1803         }
1804     }
1805
1806   /* Compute the merged default arguments.  */
1807   new_spec_types =
1808     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
1809
1810   /* Compute the new FUNCTION_TYPE.  */
1811   if (object_type)
1812     {
1813       if (vtt)
1814         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
1815                                          TREE_VALUE (vtt),
1816                                          new_spec_types);
1817
1818       if (in_charge)
1819         /* Put the in-charge parameter back.  */
1820         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
1821                                          TREE_VALUE (in_charge),
1822                                          new_spec_types);
1823
1824       new_type = build_method_type_directly (object_type,
1825                                              TREE_TYPE (old_type),
1826                                              new_spec_types);
1827     }
1828   else
1829     new_type = build_function_type (TREE_TYPE (old_type),
1830                                     new_spec_types);
1831   new_type = cp_build_type_attribute_variant (new_type,
1832                                               TYPE_ATTRIBUTES (old_type));
1833   new_type = build_exception_variant (new_type,
1834                                       TYPE_RAISES_EXCEPTIONS (old_type));
1835   TREE_TYPE (decl) = new_type;
1836 }
1837
1838 /* Check to see if the function just declared, as indicated in
1839    DECLARATOR, and in DECL, is a specialization of a function
1840    template.  We may also discover that the declaration is an explicit
1841    instantiation at this point.
1842
1843    Returns DECL, or an equivalent declaration that should be used
1844    instead if all goes well.  Issues an error message if something is
1845    amiss.  Returns error_mark_node if the error is not easily
1846    recoverable.
1847
1848    FLAGS is a bitmask consisting of the following flags:
1849
1850    2: The function has a definition.
1851    4: The function is a friend.
1852
1853    The TEMPLATE_COUNT is the number of references to qualifying
1854    template classes that appeared in the name of the function.  For
1855    example, in
1856
1857      template <class T> struct S { void f(); };
1858      void S<int>::f();
1859
1860    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
1861    classes are not counted in the TEMPLATE_COUNT, so that in
1862
1863      template <class T> struct S {};
1864      template <> struct S<int> { void f(); }
1865      template <> void S<int>::f();
1866
1867    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
1868    invalid; there should be no template <>.)
1869
1870    If the function is a specialization, it is marked as such via
1871    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
1872    is set up correctly, and it is added to the list of specializations
1873    for that template.  */
1874
1875 tree
1876 check_explicit_specialization (tree declarator,
1877                                tree decl,
1878                                int template_count,
1879                                int flags)
1880 {
1881   int have_def = flags & 2;
1882   int is_friend = flags & 4;
1883   int specialization = 0;
1884   int explicit_instantiation = 0;
1885   int member_specialization = 0;
1886   tree ctype = DECL_CLASS_CONTEXT (decl);
1887   tree dname = DECL_NAME (decl);
1888   tmpl_spec_kind tsk;
1889
1890   if (is_friend)
1891     {
1892       if (!processing_specialization)
1893         tsk = tsk_none;
1894       else
1895         tsk = tsk_excessive_parms;
1896     }
1897   else
1898     tsk = current_tmpl_spec_kind (template_count);
1899
1900   switch (tsk)
1901     {
1902     case tsk_none:
1903       if (processing_specialization)
1904         {
1905           specialization = 1;
1906           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1907         }
1908       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1909         {
1910           if (is_friend)
1911             /* This could be something like:
1912
1913                template <class T> void f(T);
1914                class S { friend void f<>(int); }  */
1915             specialization = 1;
1916           else
1917             {
1918               /* This case handles bogus declarations like template <>
1919                  template <class T> void f<int>(); */
1920
1921               error ("template-id %qD in declaration of primary template",
1922                      declarator);
1923               return decl;
1924             }
1925         }
1926       break;
1927
1928     case tsk_invalid_member_spec:
1929       /* The error has already been reported in
1930          check_specialization_scope.  */
1931       return error_mark_node;
1932
1933     case tsk_invalid_expl_inst:
1934       error ("template parameter list used in explicit instantiation");
1935
1936       /* Fall through.  */
1937
1938     case tsk_expl_inst:
1939       if (have_def)
1940         error ("definition provided for explicit instantiation");
1941
1942       explicit_instantiation = 1;
1943       break;
1944
1945     case tsk_excessive_parms:
1946     case tsk_insufficient_parms:
1947       if (tsk == tsk_excessive_parms)
1948         error ("too many template parameter lists in declaration of %qD",
1949                decl);
1950       else if (template_header_count)
1951         error("too few template parameter lists in declaration of %qD", decl);
1952       else
1953         error("explicit specialization of %qD must be introduced by "
1954               "%<template <>%>", decl);
1955
1956       /* Fall through.  */
1957     case tsk_expl_spec:
1958       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1959       if (ctype)
1960         member_specialization = 1;
1961       else
1962         specialization = 1;
1963       break;
1964
1965     case tsk_template:
1966       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1967         {
1968           /* This case handles bogus declarations like template <>
1969              template <class T> void f<int>(); */
1970
1971           if (uses_template_parms (declarator))
1972             error ("function template partial specialization %qD "
1973                    "is not allowed", declarator);
1974           else
1975             error ("template-id %qD in declaration of primary template",
1976                    declarator);
1977           return decl;
1978         }
1979
1980       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
1981         /* This is a specialization of a member template, without
1982            specialization the containing class.  Something like:
1983
1984              template <class T> struct S {
1985                template <class U> void f (U);
1986              };
1987              template <> template <class U> void S<int>::f(U) {}
1988
1989            That's a specialization -- but of the entire template.  */
1990         specialization = 1;
1991       break;
1992
1993     default:
1994       gcc_unreachable ();
1995     }
1996
1997   if (specialization || member_specialization)
1998     {
1999       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2000       for (; t; t = TREE_CHAIN (t))
2001         if (TREE_PURPOSE (t))
2002           {
2003             pedwarn
2004               ("default argument specified in explicit specialization");
2005             break;
2006           }
2007     }
2008
2009   if (specialization || member_specialization || explicit_instantiation)
2010     {
2011       tree tmpl = NULL_TREE;
2012       tree targs = NULL_TREE;
2013
2014       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2015       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2016         {
2017           tree fns;
2018
2019           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2020           if (ctype)
2021             fns = dname;
2022           else
2023             {
2024               /* If there is no class context, the explicit instantiation
2025                  must be at namespace scope.  */
2026               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2027
2028               /* Find the namespace binding, using the declaration
2029                  context.  */
2030               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2031                                            false, true);
2032               if (fns == error_mark_node || !is_overloaded_fn (fns))
2033                 {
2034                   error ("%qD is not a template function", dname);
2035                   fns = error_mark_node;
2036                 }
2037               else
2038                 {
2039                   tree fn = OVL_CURRENT (fns);
2040                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2041                                                 CP_DECL_CONTEXT (fn)))
2042                     error ("%qD is not declared in %qD",
2043                            decl, current_namespace);
2044                 }
2045             }
2046
2047           declarator = lookup_template_function (fns, NULL_TREE);
2048         }
2049
2050       if (declarator == error_mark_node)
2051         return error_mark_node;
2052
2053       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2054         {
2055           if (!explicit_instantiation)
2056             /* A specialization in class scope.  This is invalid,
2057                but the error will already have been flagged by
2058                check_specialization_scope.  */
2059             return error_mark_node;
2060           else
2061             {
2062               /* It's not valid to write an explicit instantiation in
2063                  class scope, e.g.:
2064
2065                    class C { template void f(); }
2066
2067                    This case is caught by the parser.  However, on
2068                    something like:
2069
2070                    template class C { void f(); };
2071
2072                    (which is invalid) we can get here.  The error will be
2073                    issued later.  */
2074               ;
2075             }
2076
2077           return decl;
2078         }
2079       else if (ctype != NULL_TREE
2080                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2081                    IDENTIFIER_NODE))
2082         {
2083           /* Find the list of functions in ctype that have the same
2084              name as the declared function.  */
2085           tree name = TREE_OPERAND (declarator, 0);
2086           tree fns = NULL_TREE;
2087           int idx;
2088
2089           if (constructor_name_p (name, ctype))
2090             {
2091               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2092
2093               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2094                   : !CLASSTYPE_DESTRUCTORS (ctype))
2095                 {
2096                   /* From [temp.expl.spec]:
2097
2098                      If such an explicit specialization for the member
2099                      of a class template names an implicitly-declared
2100                      special member function (clause _special_), the
2101                      program is ill-formed.
2102
2103                      Similar language is found in [temp.explicit].  */
2104                   error ("specialization of implicitly-declared special member function");
2105                   return error_mark_node;
2106                 }
2107
2108               name = is_constructor ? ctor_identifier : dtor_identifier;
2109             }
2110
2111           if (!DECL_CONV_FN_P (decl))
2112             {
2113               idx = lookup_fnfields_1 (ctype, name);
2114               if (idx >= 0)
2115                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2116             }
2117           else
2118             {
2119               VEC(tree,gc) *methods;
2120               tree ovl;
2121
2122               /* For a type-conversion operator, we cannot do a
2123                  name-based lookup.  We might be looking for `operator
2124                  int' which will be a specialization of `operator T'.
2125                  So, we find *all* the conversion operators, and then
2126                  select from them.  */
2127               fns = NULL_TREE;
2128
2129               methods = CLASSTYPE_METHOD_VEC (ctype);
2130               if (methods)
2131                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2132                      VEC_iterate (tree, methods, idx, ovl);
2133                      ++idx)
2134                   {
2135                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2136                       /* There are no more conversion functions.  */
2137                       break;
2138
2139                     /* Glue all these conversion functions together
2140                        with those we already have.  */
2141                     for (; ovl; ovl = OVL_NEXT (ovl))
2142                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2143                   }
2144             }
2145
2146           if (fns == NULL_TREE)
2147             {
2148               error ("no member function %qD declared in %qT", name, ctype);
2149               return error_mark_node;
2150             }
2151           else
2152             TREE_OPERAND (declarator, 0) = fns;
2153         }
2154
2155       /* Figure out what exactly is being specialized at this point.
2156          Note that for an explicit instantiation, even one for a
2157          member function, we cannot tell apriori whether the
2158          instantiation is for a member template, or just a member
2159          function of a template class.  Even if a member template is
2160          being instantiated, the member template arguments may be
2161          elided if they can be deduced from the rest of the
2162          declaration.  */
2163       tmpl = determine_specialization (declarator, decl,
2164                                        &targs,
2165                                        member_specialization,
2166                                        template_count,
2167                                        tsk);
2168
2169       if (!tmpl || tmpl == error_mark_node)
2170         /* We couldn't figure out what this declaration was
2171            specializing.  */
2172         return error_mark_node;
2173       else
2174         {
2175           tree gen_tmpl = most_general_template (tmpl);
2176
2177           if (explicit_instantiation)
2178             {
2179               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2180                  is done by do_decl_instantiation later.  */
2181
2182               int arg_depth = TMPL_ARGS_DEPTH (targs);
2183               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2184
2185               if (arg_depth > parm_depth)
2186                 {
2187                   /* If TMPL is not the most general template (for
2188                      example, if TMPL is a friend template that is
2189                      injected into namespace scope), then there will
2190                      be too many levels of TARGS.  Remove some of them
2191                      here.  */
2192                   int i;
2193                   tree new_targs;
2194
2195                   new_targs = make_tree_vec (parm_depth);
2196                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2197                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2198                       = TREE_VEC_ELT (targs, i);
2199                   targs = new_targs;
2200                 }
2201
2202               return instantiate_template (tmpl, targs, tf_error);
2203             }
2204
2205           /* If we thought that the DECL was a member function, but it
2206              turns out to be specializing a static member function,
2207              make DECL a static member function as well.  */
2208           if (DECL_STATIC_FUNCTION_P (tmpl)
2209               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2210             revert_static_member_fn (decl);
2211
2212           /* If this is a specialization of a member template of a
2213              template class, we want to return the TEMPLATE_DECL, not
2214              the specialization of it.  */
2215           if (tsk == tsk_template)
2216             {
2217               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2218               DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl)) = NULL_TREE;
2219               if (have_def)
2220                 {
2221                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2222                   DECL_SOURCE_LOCATION (DECL_TEMPLATE_RESULT (tmpl))
2223                     = DECL_SOURCE_LOCATION (decl);
2224                   /* We want to use the argument list specified in the
2225                      definition, not in the original declaration.  */
2226                   DECL_ARGUMENTS (DECL_TEMPLATE_RESULT (tmpl))
2227                     = DECL_ARGUMENTS (decl);
2228                 }
2229               return tmpl;
2230             }
2231
2232           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2233           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2234
2235           /* Inherit default function arguments from the template
2236              DECL is specializing.  */
2237           copy_default_args_to_explicit_spec (decl);
2238
2239           /* This specialization has the same protection as the
2240              template it specializes.  */
2241           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2242           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2243
2244           /* 7.1.1-1 [dcl.stc]
2245
2246              A storage-class-specifier shall not be specified in an
2247              explicit specialization...
2248
2249              The parser rejects these, so unless action is taken here,
2250              explicit function specializations will always appear with
2251              global linkage.
2252
2253              The action recommended by the C++ CWG in response to C++
2254              defect report 605 is to make the storage class and linkage
2255              of the explicit specialization match the templated function:
2256
2257              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2258            */
2259           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2260             {
2261               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2262               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2263
2264               /* This specialization has the same linkage and visibility as
2265                  the function template it specializes.  */
2266               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2267               if (! TREE_PUBLIC (decl))
2268                 {
2269                   DECL_INTERFACE_KNOWN (decl) = 1;
2270                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2271                 }
2272               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2273               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2274                 {
2275                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2276                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2277                 }
2278             }
2279
2280           /* If DECL is a friend declaration, declared using an
2281              unqualified name, the namespace associated with DECL may
2282              have been set incorrectly.  For example, in:
2283
2284                template <typename T> void f(T);
2285                namespace N {
2286                  struct S { friend void f<int>(int); }
2287                }
2288
2289              we will have set the DECL_CONTEXT for the friend
2290              declaration to N, rather than to the global namespace.  */
2291           if (DECL_NAMESPACE_SCOPE_P (decl))
2292             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2293
2294           if (is_friend && !have_def)
2295             /* This is not really a declaration of a specialization.
2296                It's just the name of an instantiation.  But, it's not
2297                a request for an instantiation, either.  */
2298             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2299           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2300             /* This is indeed a specialization.  In case of constructors
2301                and destructors, we need in-charge and not-in-charge
2302                versions in V3 ABI.  */
2303             clone_function_decl (decl, /*update_method_vec_p=*/0);
2304
2305           /* Register this specialization so that we can find it
2306              again.  */
2307           decl = register_specialization (decl, gen_tmpl, targs, is_friend);
2308         }
2309     }
2310
2311   return decl;
2312 }
2313
2314 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2315    parameters.  These are represented in the same format used for
2316    DECL_TEMPLATE_PARMS.  */
2317
2318 int
2319 comp_template_parms (const_tree parms1, const_tree parms2)
2320 {
2321   const_tree p1;
2322   const_tree p2;
2323
2324   if (parms1 == parms2)
2325     return 1;
2326
2327   for (p1 = parms1, p2 = parms2;
2328        p1 != NULL_TREE && p2 != NULL_TREE;
2329        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2330     {
2331       tree t1 = TREE_VALUE (p1);
2332       tree t2 = TREE_VALUE (p2);
2333       int i;
2334
2335       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2336       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2337
2338       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2339         return 0;
2340
2341       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2342         {
2343           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2344           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2345
2346           /* If either of the template parameters are invalid, assume
2347              they match for the sake of error recovery. */
2348           if (parm1 == error_mark_node || parm2 == error_mark_node)
2349             return 1;
2350
2351           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2352             return 0;
2353
2354           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2355               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2356                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2357             continue;
2358           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2359             return 0;
2360         }
2361     }
2362
2363   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2364     /* One set of parameters has more parameters lists than the
2365        other.  */
2366     return 0;
2367
2368   return 1;
2369 }
2370
2371 /* Determine whether PARM is a parameter pack.  */
2372 bool 
2373 template_parameter_pack_p (const_tree parm)
2374 {
2375   /* Determine if we have a non-type template parameter pack.  */
2376   if (TREE_CODE (parm) == PARM_DECL)
2377     return (DECL_TEMPLATE_PARM_P (parm) 
2378             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2379
2380   /* If this is a list of template parameters, we could get a
2381      TYPE_DECL or a TEMPLATE_DECL.  */ 
2382   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2383     parm = TREE_TYPE (parm);
2384
2385   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2386            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2387           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2388 }
2389
2390 /* Determine whether ARGS describes a variadic template args list,
2391    i.e., one that is terminated by a template argument pack.  */
2392 static bool 
2393 template_args_variadic_p (tree args)
2394 {
2395   int nargs;
2396   tree last_parm;
2397
2398   if (args == NULL_TREE)
2399     return false;
2400
2401   args = INNERMOST_TEMPLATE_ARGS (args);
2402   nargs = TREE_VEC_LENGTH (args);
2403
2404   if (nargs == 0)
2405     return false;
2406
2407   last_parm = TREE_VEC_ELT (args, nargs - 1);
2408
2409   return ARGUMENT_PACK_P (last_parm);
2410 }
2411
2412 /* Generate a new name for the parameter pack name NAME (an
2413    IDENTIFIER_NODE) that incorporates its */
2414 static tree
2415 make_ith_pack_parameter_name (tree name, int i)
2416 {
2417   /* Munge the name to include the parameter index.  */
2418   char numbuf[128];
2419   char* newname;
2420   
2421   sprintf(numbuf, "%i", i);
2422   newname = (char*)alloca (IDENTIFIER_LENGTH (name) + strlen(numbuf) + 2);
2423   sprintf(newname, "%s#%i", IDENTIFIER_POINTER (name), i);
2424   return get_identifier (newname);
2425 }
2426
2427 /* Structure used to track the progress of find_parameter_packs_r.  */
2428 struct find_parameter_pack_data 
2429 {
2430   /* TREE_LIST that will contain all of the parameter packs found by
2431      the traversal.  */
2432   tree* parameter_packs;
2433
2434   /* Set of AST nodes that have been visited by the traversal.  */
2435   struct pointer_set_t *visited;
2436 };
2437
2438 /* Identifies all of the argument packs that occur in a template
2439    argument and appends them to the TREE_LIST inside DATA, which is a
2440    find_parameter_pack_data structure. This is a subroutine of
2441    make_pack_expansion and uses_parameter_packs.  */
2442 static tree
2443 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2444 {
2445   tree t = *tp;
2446   struct find_parameter_pack_data* ppd = 
2447     (struct find_parameter_pack_data*)data;
2448   bool parameter_pack_p = false;
2449
2450   /* Identify whether this is a parameter pack or not.  */
2451   switch (TREE_CODE (t))
2452     {
2453     case TEMPLATE_PARM_INDEX:
2454       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2455         parameter_pack_p = true;
2456       break;
2457
2458     case TEMPLATE_TYPE_PARM:
2459     case TEMPLATE_TEMPLATE_PARM:
2460       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2461         parameter_pack_p = true;
2462       break;
2463
2464     case PARM_DECL:
2465       if (FUNCTION_PARAMETER_PACK_P (t))
2466         {
2467           /* We don't want to walk into the type of a PARM_DECL,
2468              because we don't want to see the type parameter pack.  */
2469           *walk_subtrees = 0;
2470           parameter_pack_p = true;
2471         }
2472       break;
2473
2474     default:
2475       /* Not a parameter pack.  */
2476       break;
2477     }
2478
2479   if (parameter_pack_p)
2480     {
2481       /* Add this parameter pack to the list.  */
2482       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2483     }
2484
2485   if (TYPE_P (t))
2486     cp_walk_tree (&TYPE_CONTEXT (t), 
2487                   &find_parameter_packs_r, ppd, ppd->visited);
2488
2489   /* This switch statement will return immediately if we don't find a
2490      parameter pack.  */
2491   switch (TREE_CODE (t)) 
2492     {
2493     case TEMPLATE_PARM_INDEX:
2494       return NULL_TREE;
2495
2496     case BOUND_TEMPLATE_TEMPLATE_PARM:
2497       /* Check the template itself.  */
2498       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2499                     &find_parameter_packs_r, ppd, ppd->visited);
2500       /* Check the template arguments.  */
2501       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2502                     ppd->visited);
2503       *walk_subtrees = 0;
2504       return NULL_TREE;
2505
2506     case TEMPLATE_TYPE_PARM:
2507     case TEMPLATE_TEMPLATE_PARM:
2508       return NULL_TREE;
2509
2510     case PARM_DECL:
2511       return NULL_TREE;
2512
2513     case RECORD_TYPE:
2514       if (TYPE_PTRMEMFUNC_P (t))
2515         return NULL_TREE;
2516       /* Fall through.  */
2517
2518     case UNION_TYPE:
2519     case ENUMERAL_TYPE:
2520       if (TYPE_TEMPLATE_INFO (t))
2521         cp_walk_tree (&TREE_VALUE (TYPE_TEMPLATE_INFO (t)), 
2522                       &find_parameter_packs_r, ppd, ppd->visited);
2523
2524       *walk_subtrees = 0;
2525       return NULL_TREE;
2526
2527     case TEMPLATE_DECL:
2528       cp_walk_tree (&TREE_TYPE (t),
2529                     &find_parameter_packs_r, ppd, ppd->visited);
2530       return NULL_TREE;
2531  
2532     case TYPENAME_TYPE:
2533       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2534                    ppd, ppd->visited);
2535       *walk_subtrees = 0;
2536       return NULL_TREE;
2537       
2538     case TYPE_PACK_EXPANSION:
2539     case EXPR_PACK_EXPANSION:
2540       *walk_subtrees = 0;
2541       return NULL_TREE;
2542
2543     case INTEGER_TYPE:
2544       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2545                     ppd, ppd->visited);
2546       *walk_subtrees = 0;
2547       return NULL_TREE;
2548
2549     case IDENTIFIER_NODE:
2550       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2551                     ppd->visited);
2552       *walk_subtrees = 0;
2553       return NULL_TREE;
2554
2555     default:
2556       return NULL_TREE;
2557     }
2558
2559   return NULL_TREE;
2560 }
2561
2562 /* Determines if the expression or type T uses any parameter packs.  */
2563 bool
2564 uses_parameter_packs (tree t)
2565 {
2566   tree parameter_packs = NULL_TREE;
2567   struct find_parameter_pack_data ppd;
2568   ppd.parameter_packs = &parameter_packs;
2569   ppd.visited = pointer_set_create ();
2570   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2571   pointer_set_destroy (ppd.visited);
2572   return parameter_packs != NULL_TREE;
2573 }
2574
2575 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2576    representation a base-class initializer into a parameter pack
2577    expansion. If all goes well, the resulting node will be an
2578    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2579    respectively.  */
2580 tree 
2581 make_pack_expansion (tree arg)
2582 {
2583   tree result;
2584   tree parameter_packs = NULL_TREE;
2585   bool for_types = false;
2586   struct find_parameter_pack_data ppd;
2587
2588   if (!arg || arg == error_mark_node)
2589     return arg;
2590
2591   if (TREE_CODE (arg) == TREE_LIST)
2592     {
2593       /* The only time we will see a TREE_LIST here is for a base
2594          class initializer.  In this case, the TREE_PURPOSE will be a
2595          _TYPE node (representing the base class expansion we're
2596          initializing) and the TREE_VALUE will be a TREE_LIST
2597          containing the initialization arguments. 
2598
2599          The resulting expansion looks somewhat different from most
2600          expansions. Rather than returning just one _EXPANSION, we
2601          return a TREE_LIST whose TREE_PURPOSE is a
2602          TYPE_PACK_EXPANSION containing the bases that will be
2603          initialized.  The TREE_VALUE will be identical to the
2604          original TREE_VALUE, which is a list of arguments that will
2605          be passed to each base.  We do not introduce any new pack
2606          expansion nodes into the TREE_VALUE (although it is possible
2607          that some already exist), because the TREE_PURPOSE and
2608          TREE_VALUE all need to be expanded together with the same
2609          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2610          resulting TREE_PURPOSE will mention the parameter packs in
2611          both the bases and the arguments to the bases.  */
2612       tree purpose;
2613       tree value;
2614       tree parameter_packs = NULL_TREE;
2615
2616       /* Determine which parameter packs will be used by the base
2617          class expansion.  */
2618       ppd.visited = pointer_set_create ();
2619       ppd.parameter_packs = &parameter_packs;
2620       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
2621                     &ppd, ppd.visited);
2622
2623       if (parameter_packs == NULL_TREE)
2624         {
2625           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
2626           pointer_set_destroy (ppd.visited);
2627           return error_mark_node;
2628         }
2629
2630       if (TREE_VALUE (arg) != void_type_node)
2631         {
2632           /* Collect the sets of parameter packs used in each of the
2633              initialization arguments.  */
2634           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
2635             {
2636               /* Determine which parameter packs will be expanded in this
2637                  argument.  */
2638               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
2639                             &ppd, ppd.visited);
2640             }
2641         }
2642
2643       pointer_set_destroy (ppd.visited);
2644
2645       /* Create the pack expansion type for the base type.  */
2646       purpose = make_node (TYPE_PACK_EXPANSION);
2647       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
2648       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
2649
2650       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2651          they will rarely be compared to anything.  */
2652       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
2653
2654       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
2655     }
2656
2657   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
2658     for_types = true;
2659
2660   /* Build the PACK_EXPANSION_* node.  */
2661   result = make_node (for_types ? TYPE_PACK_EXPANSION : EXPR_PACK_EXPANSION);
2662   SET_PACK_EXPANSION_PATTERN (result, arg);
2663   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
2664     {
2665       /* Propagate type and const-expression information.  */
2666       TREE_TYPE (result) = TREE_TYPE (arg);
2667       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
2668     }
2669   else
2670     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2671        they will rarely be compared to anything.  */
2672     SET_TYPE_STRUCTURAL_EQUALITY (result);
2673
2674   /* Determine which parameter packs will be expanded.  */
2675   ppd.parameter_packs = &parameter_packs;
2676   ppd.visited = pointer_set_create ();
2677   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
2678   pointer_set_destroy (ppd.visited);
2679
2680   /* Make sure we found some parameter packs.  */
2681   if (parameter_packs == NULL_TREE)
2682     {
2683       if (TYPE_P (arg))
2684         error ("expansion pattern %<%T%> contains no argument packs", arg);
2685       else
2686         error ("expansion pattern %<%E%> contains no argument packs", arg);
2687       return error_mark_node;
2688     }
2689   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
2690
2691   return result;
2692 }
2693
2694 /* Checks T for any "bare" parameter packs, which have not yet been
2695    expanded, and issues an error if any are found. This operation can
2696    only be done on full expressions or types (e.g., an expression
2697    statement, "if" condition, etc.), because we could have expressions like:
2698
2699      foo(f(g(h(args)))...)
2700
2701    where "args" is a parameter pack. check_for_bare_parameter_packs
2702    should not be called for the subexpressions args, h(args),
2703    g(h(args)), or f(g(h(args))), because we would produce erroneous
2704    error messages. 
2705
2706    Returns TRUE and emits an error if there were bare parameter packs,
2707    returns FALSE otherwise.  */
2708 bool 
2709 check_for_bare_parameter_packs (tree t)
2710 {
2711   tree parameter_packs = NULL_TREE;
2712   struct find_parameter_pack_data ppd;
2713
2714   if (!processing_template_decl || !t || t == error_mark_node)
2715     return false;
2716
2717   if (TREE_CODE (t) == TYPE_DECL)
2718     t = TREE_TYPE (t);
2719
2720   ppd.parameter_packs = &parameter_packs;
2721   ppd.visited = pointer_set_create ();
2722   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2723   pointer_set_destroy (ppd.visited);
2724
2725   if (parameter_packs) 
2726     {
2727       error ("parameter packs not expanded with `...':");
2728       while (parameter_packs)
2729         {
2730           tree pack = TREE_VALUE (parameter_packs);
2731           tree name = NULL_TREE;
2732
2733           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
2734               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
2735             name = TYPE_NAME (pack);
2736           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
2737             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
2738           else
2739             name = DECL_NAME (pack);
2740
2741           if (name)
2742             inform ("        %qD", name);
2743           else
2744             inform ("        <anonymous>");
2745
2746           parameter_packs = TREE_CHAIN (parameter_packs);
2747         }
2748
2749       return true;
2750     }
2751
2752   return false;
2753 }
2754
2755 /* Expand any parameter packs that occur in the template arguments in
2756    ARGS.  */
2757 tree
2758 expand_template_argument_pack (tree args)
2759 {
2760   tree result_args = NULL_TREE;
2761   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
2762   int num_result_args = -1;
2763
2764   /* First, determine if we need to expand anything, and the number of
2765      slots we'll need.  */
2766   for (in_arg = 0; in_arg < nargs; ++in_arg)
2767     {
2768       tree arg = TREE_VEC_ELT (args, in_arg);
2769       if (ARGUMENT_PACK_P (arg))
2770         {
2771           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
2772           if (num_result_args < 0)
2773             num_result_args = in_arg + num_packed;
2774           else
2775             num_result_args += num_packed;
2776         }
2777       else
2778         {
2779           if (num_result_args >= 0)
2780             num_result_args++;
2781         }
2782     }
2783
2784   /* If no expansion is necessary, we're done.  */
2785   if (num_result_args < 0)
2786     return args;
2787
2788   /* Expand arguments.  */
2789   result_args = make_tree_vec (num_result_args);
2790   for (in_arg = 0; in_arg < nargs; ++in_arg)
2791     {
2792       tree arg = TREE_VEC_ELT (args, in_arg);
2793       if (ARGUMENT_PACK_P (arg))
2794         {
2795           tree packed = ARGUMENT_PACK_ARGS (arg);
2796           int i, num_packed = TREE_VEC_LENGTH (packed);
2797           for (i = 0; i < num_packed; ++i, ++out_arg)
2798             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
2799         }
2800       else
2801         {
2802           TREE_VEC_ELT (result_args, out_arg) = arg;
2803           ++out_arg;
2804         }
2805     }
2806
2807   return result_args;
2808 }
2809
2810 /* Complain if DECL shadows a template parameter.
2811
2812    [temp.local]: A template-parameter shall not be redeclared within its
2813    scope (including nested scopes).  */
2814
2815 void
2816 check_template_shadow (tree decl)
2817 {
2818   tree olddecl;
2819
2820   /* If we're not in a template, we can't possibly shadow a template
2821      parameter.  */
2822   if (!current_template_parms)
2823     return;
2824
2825   /* Figure out what we're shadowing.  */
2826   if (TREE_CODE (decl) == OVERLOAD)
2827     decl = OVL_CURRENT (decl);
2828   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
2829
2830   /* If there's no previous binding for this name, we're not shadowing
2831      anything, let alone a template parameter.  */
2832   if (!olddecl)
2833     return;
2834
2835   /* If we're not shadowing a template parameter, we're done.  Note
2836      that OLDDECL might be an OVERLOAD (or perhaps even an
2837      ERROR_MARK), so we can't just blithely assume it to be a _DECL
2838      node.  */
2839   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
2840     return;
2841
2842   /* We check for decl != olddecl to avoid bogus errors for using a
2843      name inside a class.  We check TPFI to avoid duplicate errors for
2844      inline member templates.  */
2845   if (decl == olddecl
2846       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
2847     return;
2848
2849   error ("declaration of %q+#D", decl);
2850   error (" shadows template parm %q+#D", olddecl);
2851 }
2852
2853 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
2854    ORIG_LEVEL, DECL, and TYPE.  */
2855
2856 static tree
2857 build_template_parm_index (int index,
2858                            int level,
2859                            int orig_level,
2860                            tree decl,
2861                            tree type)
2862 {
2863   tree t = make_node (TEMPLATE_PARM_INDEX);
2864   TEMPLATE_PARM_IDX (t) = index;
2865   TEMPLATE_PARM_LEVEL (t) = level;
2866   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
2867   TEMPLATE_PARM_DECL (t) = decl;
2868   TREE_TYPE (t) = type;
2869   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
2870   TREE_INVARIANT (t) = TREE_INVARIANT (decl);
2871   TREE_READONLY (t) = TREE_READONLY (decl);
2872
2873   return t;
2874 }
2875
2876 /* Find the canonical type parameter for the given template type
2877    parameter.  Returns the canonical type parameter, which may be TYPE
2878    if no such parameter existed.  */
2879 static tree
2880 canonical_type_parameter (tree type)
2881 {
2882   tree list;
2883   int idx = TEMPLATE_TYPE_IDX (type);
2884   if (!canonical_template_parms)
2885     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
2886
2887   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
2888     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
2889
2890   list = VEC_index (tree, canonical_template_parms, idx);
2891   while (list && !cp_comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
2892     list = TREE_CHAIN (list);
2893
2894   if (list)
2895     return TREE_VALUE (list);
2896   else
2897     {
2898       VEC_replace(tree, canonical_template_parms, idx,
2899                   tree_cons (NULL_TREE, type, 
2900                              VEC_index (tree, canonical_template_parms, idx)));
2901       return type;
2902     }
2903 }
2904
2905 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
2906    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
2907    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
2908    new one is created.  */
2909
2910 static tree
2911 reduce_template_parm_level (tree index, tree type, int levels, tree args,
2912                             tsubst_flags_t complain)
2913 {
2914   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
2915       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
2916           != TEMPLATE_PARM_LEVEL (index) - levels))
2917     {
2918       tree orig_decl = TEMPLATE_PARM_DECL (index);
2919       tree decl, t;
2920
2921       decl = build_decl (TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
2922       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
2923       TREE_INVARIANT (decl) = TREE_INVARIANT (orig_decl);
2924       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
2925       DECL_ARTIFICIAL (decl) = 1;
2926       SET_DECL_TEMPLATE_PARM_P (decl);
2927
2928       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
2929                                      TEMPLATE_PARM_LEVEL (index) - levels,
2930                                      TEMPLATE_PARM_ORIG_LEVEL (index),
2931                                      decl, type);
2932       TEMPLATE_PARM_DESCENDANTS (index) = t;
2933       TEMPLATE_PARM_PARAMETER_PACK (t) 
2934         = TEMPLATE_PARM_PARAMETER_PACK (index);
2935
2936         /* Template template parameters need this.  */
2937       if (TREE_CODE (decl) == TEMPLATE_DECL)
2938         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
2939           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
2940            args, complain);
2941     }
2942
2943   return TEMPLATE_PARM_DESCENDANTS (index);
2944 }
2945
2946 /* Process information from new template parameter PARM and append it to the
2947    LIST being built.  This new parameter is a non-type parameter iff
2948    IS_NON_TYPE is true. This new parameter is a parameter
2949    pack iff IS_PARAMETER_PACK is true.  */
2950
2951 tree
2952 process_template_parm (tree list, tree parm, bool is_non_type, 
2953                        bool is_parameter_pack)
2954 {
2955   tree decl = 0;
2956   tree defval;
2957   tree err_parm_list;
2958   int idx = 0;
2959
2960   gcc_assert (TREE_CODE (parm) == TREE_LIST);
2961   defval = TREE_PURPOSE (parm);
2962
2963   if (list)
2964     {
2965       tree p = tree_last (list);
2966
2967       if (p && TREE_VALUE (p) != error_mark_node)
2968         {
2969           p = TREE_VALUE (p);
2970           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
2971             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
2972           else
2973             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
2974         }
2975
2976       ++idx;
2977     }
2978   else
2979     idx = 0;
2980
2981   if (is_non_type)
2982     {
2983       parm = TREE_VALUE (parm);
2984
2985       SET_DECL_TEMPLATE_PARM_P (parm);
2986
2987       if (TREE_TYPE (parm) == error_mark_node)
2988         {
2989           err_parm_list = build_tree_list (defval, parm);
2990           TREE_VALUE (err_parm_list) = error_mark_node;
2991            return chainon (list, err_parm_list);
2992         }
2993       else
2994       {
2995         /* [temp.param]
2996
2997            The top-level cv-qualifiers on the template-parameter are
2998            ignored when determining its type.  */
2999         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3000         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3001           {
3002             err_parm_list = build_tree_list (defval, parm);
3003             TREE_VALUE (err_parm_list) = error_mark_node;
3004              return chainon (list, err_parm_list);
3005           }
3006
3007         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3008           {
3009             /* This template parameter is not a parameter pack, but it
3010                should be. Complain about "bare" parameter packs.  */
3011             check_for_bare_parameter_packs (TREE_TYPE (parm));
3012             
3013             /* Recover by calling this a parameter pack.  */
3014             is_parameter_pack = true;
3015           }
3016       }
3017
3018       /* A template parameter is not modifiable.  */
3019       TREE_CONSTANT (parm) = 1;
3020       TREE_INVARIANT (parm) = 1;
3021       TREE_READONLY (parm) = 1;
3022       decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3023       TREE_CONSTANT (decl) = 1;
3024       TREE_INVARIANT (decl) = 1;
3025       TREE_READONLY (decl) = 1;
3026       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3027         = build_template_parm_index (idx, processing_template_decl,
3028                                      processing_template_decl,
3029                                      decl, TREE_TYPE (parm));
3030
3031       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3032         = is_parameter_pack;
3033     }
3034   else
3035     {
3036       tree t;
3037       parm = TREE_VALUE (TREE_VALUE (parm));
3038
3039       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3040         {
3041           t = make_aggr_type (TEMPLATE_TEMPLATE_PARM);
3042           /* This is for distinguishing between real templates and template
3043              template parameters */
3044           TREE_TYPE (parm) = t;
3045           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3046           decl = parm;
3047         }
3048       else
3049         {
3050           t = make_aggr_type (TEMPLATE_TYPE_PARM);
3051           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3052           decl = build_decl (TYPE_DECL, parm, t);
3053         }
3054
3055       TYPE_NAME (t) = decl;
3056       TYPE_STUB_DECL (t) = decl;
3057       parm = decl;
3058       TEMPLATE_TYPE_PARM_INDEX (t)
3059         = build_template_parm_index (idx, processing_template_decl,
3060                                      processing_template_decl,
3061                                      decl, TREE_TYPE (parm));
3062       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3063       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3064     }
3065   DECL_ARTIFICIAL (decl) = 1;
3066   SET_DECL_TEMPLATE_PARM_P (decl);
3067   pushdecl (decl);
3068   parm = build_tree_list (defval, parm);
3069   return chainon (list, parm);
3070 }
3071
3072 /* The end of a template parameter list has been reached.  Process the
3073    tree list into a parameter vector, converting each parameter into a more
3074    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3075    as PARM_DECLs.  */
3076
3077 tree
3078 end_template_parm_list (tree parms)
3079 {
3080   int nparms;
3081   tree parm, next;
3082   tree saved_parmlist = make_tree_vec (list_length (parms));
3083
3084   current_template_parms
3085     = tree_cons (size_int (processing_template_decl),
3086                  saved_parmlist, current_template_parms);
3087
3088   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3089     {
3090       next = TREE_CHAIN (parm);
3091       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3092       TREE_CHAIN (parm) = NULL_TREE;
3093     }
3094
3095   --processing_template_parmlist;
3096
3097   return saved_parmlist;
3098 }
3099
3100 /* end_template_decl is called after a template declaration is seen.  */
3101
3102 void
3103 end_template_decl (void)
3104 {
3105   reset_specialization ();
3106
3107   if (! processing_template_decl)
3108     return;
3109
3110   /* This matches the pushlevel in begin_template_parm_list.  */
3111   finish_scope ();
3112
3113   --processing_template_decl;
3114   current_template_parms = TREE_CHAIN (current_template_parms);
3115 }
3116
3117 /* Within the declaration of a template, return all levels of template
3118    parameters that apply.  The template parameters are represented as
3119    a TREE_VEC, in the form documented in cp-tree.h for template
3120    arguments.  */
3121
3122 static tree
3123 current_template_args (void)
3124 {
3125   tree header;
3126   tree args = NULL_TREE;
3127   int length = TMPL_PARMS_DEPTH (current_template_parms);
3128   int l = length;
3129
3130   /* If there is only one level of template parameters, we do not
3131      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3132      TREE_VEC containing the arguments.  */
3133   if (length > 1)
3134     args = make_tree_vec (length);
3135
3136   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3137     {
3138       tree a = copy_node (TREE_VALUE (header));
3139       int i;
3140
3141       TREE_TYPE (a) = NULL_TREE;
3142       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3143         {
3144           tree t = TREE_VEC_ELT (a, i);
3145
3146           /* T will be a list if we are called from within a
3147              begin/end_template_parm_list pair, but a vector directly
3148              if within a begin/end_member_template_processing pair.  */
3149           if (TREE_CODE (t) == TREE_LIST)
3150             {
3151               t = TREE_VALUE (t);
3152
3153               if (!error_operand_p (t))
3154                 {
3155                   if (TREE_CODE (t) == TYPE_DECL
3156                       || TREE_CODE (t) == TEMPLATE_DECL)
3157                     {
3158                       t = TREE_TYPE (t);
3159                       
3160                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3161                         {
3162                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3163                              with a single element, which expands T.  */
3164                           tree vec = make_tree_vec (1);
3165                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3166                           
3167                           t = make_node (TYPE_ARGUMENT_PACK);
3168                           SET_ARGUMENT_PACK_ARGS (t, vec);
3169                         }
3170                     }
3171                   else
3172                     {
3173                       t = DECL_INITIAL (t);
3174                       
3175                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3176                         {
3177                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3178                              with a single element, which expands T.  */
3179                           tree vec = make_tree_vec (1);
3180                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3181                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3182                           
3183                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3184                           SET_ARGUMENT_PACK_ARGS (t, vec);
3185                           TREE_TYPE (t) = type;
3186                         }
3187                     }
3188                   TREE_VEC_ELT (a, i) = t;
3189                 }
3190             }
3191         }
3192
3193       if (length > 1)
3194         TREE_VEC_ELT (args, --l) = a;
3195       else
3196         args = a;
3197     }
3198
3199   return args;
3200 }
3201
3202 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3203    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3204    a member template.  Used by push_template_decl below.  */
3205
3206 static tree
3207 build_template_decl (tree decl, tree parms, bool member_template_p)
3208 {
3209   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3210   DECL_TEMPLATE_PARMS (tmpl) = parms;
3211   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3212   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3213   if (DECL_LANG_SPECIFIC (decl))
3214     {
3215       DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
3216       DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
3217       DECL_DESTRUCTOR_P (tmpl) = DECL_DESTRUCTOR_P (decl);
3218       DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
3219       DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
3220       if (DECL_OVERLOADED_OPERATOR_P (decl))
3221         SET_OVERLOADED_OPERATOR_CODE (tmpl,
3222                                       DECL_OVERLOADED_OPERATOR_P (decl));
3223     }
3224
3225   return tmpl;
3226 }
3227
3228 struct template_parm_data
3229 {
3230   /* The level of the template parameters we are currently
3231      processing.  */
3232   int level;
3233
3234   /* The index of the specialization argument we are currently
3235      processing.  */
3236   int current_arg;
3237
3238   /* An array whose size is the number of template parameters.  The
3239      elements are nonzero if the parameter has been used in any one
3240      of the arguments processed so far.  */
3241   int* parms;
3242
3243   /* An array whose size is the number of template arguments.  The
3244      elements are nonzero if the argument makes use of template
3245      parameters of this level.  */
3246   int* arg_uses_template_parms;
3247 };
3248
3249 /* Subroutine of push_template_decl used to see if each template
3250    parameter in a partial specialization is used in the explicit
3251    argument list.  If T is of the LEVEL given in DATA (which is
3252    treated as a template_parm_data*), then DATA->PARMS is marked
3253    appropriately.  */
3254
3255 static int
3256 mark_template_parm (tree t, void* data)
3257 {
3258   int level;
3259   int idx;
3260   struct template_parm_data* tpd = (struct template_parm_data*) data;
3261
3262   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3263     {
3264       level = TEMPLATE_PARM_LEVEL (t);
3265       idx = TEMPLATE_PARM_IDX (t);
3266     }
3267   else
3268     {
3269       level = TEMPLATE_TYPE_LEVEL (t);
3270       idx = TEMPLATE_TYPE_IDX (t);
3271     }
3272
3273   if (level == tpd->level)
3274     {
3275       tpd->parms[idx] = 1;
3276       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3277     }
3278
3279   /* Return zero so that for_each_template_parm will continue the
3280      traversal of the tree; we want to mark *every* template parm.  */
3281   return 0;
3282 }
3283
3284 /* Process the partial specialization DECL.  */
3285
3286 static tree
3287 process_partial_specialization (tree decl)
3288 {
3289   tree type = TREE_TYPE (decl);
3290   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3291   tree specargs = CLASSTYPE_TI_ARGS (type);
3292   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3293   tree inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3294   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3295   int nargs = TREE_VEC_LENGTH (inner_args);
3296   int ntparms = TREE_VEC_LENGTH (inner_parms);
3297   int  i;
3298   int did_error_intro = 0;
3299   struct template_parm_data tpd;
3300   struct template_parm_data tpd2;
3301
3302   /* We check that each of the template parameters given in the
3303      partial specialization is used in the argument list to the
3304      specialization.  For example:
3305
3306        template <class T> struct S;
3307        template <class T> struct S<T*>;
3308
3309      The second declaration is OK because `T*' uses the template
3310      parameter T, whereas
3311
3312        template <class T> struct S<int>;
3313
3314      is no good.  Even trickier is:
3315
3316        template <class T>
3317        struct S1
3318        {
3319           template <class U>
3320           struct S2;
3321           template <class U>
3322           struct S2<T>;
3323        };
3324
3325      The S2<T> declaration is actually invalid; it is a
3326      full-specialization.  Of course,
3327
3328           template <class U>
3329           struct S2<T (*)(U)>;
3330
3331      or some such would have been OK.  */
3332   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3333   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3334   memset (tpd.parms, 0, sizeof (int) * ntparms);
3335
3336   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3337   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3338   for (i = 0; i < nargs; ++i)
3339     {
3340       tpd.current_arg = i;
3341       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3342                               &mark_template_parm,
3343                               &tpd,
3344                               NULL,
3345                               /*include_nondeduced_p=*/false);
3346     }
3347   for (i = 0; i < ntparms; ++i)
3348     if (tpd.parms[i] == 0)
3349       {
3350         /* One of the template parms was not used in the
3351            specialization.  */
3352         if (!did_error_intro)
3353           {
3354             error ("template parameters not used in partial specialization:");
3355             did_error_intro = 1;
3356           }
3357
3358         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3359       }
3360
3361   /* [temp.class.spec]
3362
3363      The argument list of the specialization shall not be identical to
3364      the implicit argument list of the primary template.  */
3365   if (comp_template_args
3366       (inner_args,
3367        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3368                                                    (maintmpl)))))
3369     error ("partial specialization %qT does not specialize any template arguments", type);
3370
3371   /* [temp.class.spec]
3372
3373      A partially specialized non-type argument expression shall not
3374      involve template parameters of the partial specialization except
3375      when the argument expression is a simple identifier.
3376
3377      The type of a template parameter corresponding to a specialized
3378      non-type argument shall not be dependent on a parameter of the
3379      specialization. 
3380
3381      Also, we verify that pack expansions only occur at the
3382      end of the argument list.  */
3383   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3384   tpd2.parms = 0;
3385   for (i = 0; i < nargs; ++i)
3386     {
3387       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3388       tree arg = TREE_VEC_ELT (inner_args, i);
3389       tree packed_args = NULL_TREE;
3390       int j, len = 1;
3391
3392       if (ARGUMENT_PACK_P (arg))
3393         {
3394           /* Extract the arguments from the argument pack. We'll be
3395              iterating over these in the following loop.  */
3396           packed_args = ARGUMENT_PACK_ARGS (arg);
3397           len = TREE_VEC_LENGTH (packed_args);
3398         }
3399
3400       for (j = 0; j < len; j++)
3401         {
3402           if (packed_args)
3403             /* Get the Jth argument in the parameter pack.  */
3404             arg = TREE_VEC_ELT (packed_args, j);
3405
3406           if (PACK_EXPANSION_P (arg))
3407             {
3408               /* Pack expansions must come at the end of the
3409                  argument list.  */
3410               if ((packed_args && j < len - 1)
3411                   || (!packed_args && i < nargs - 1))
3412                 {
3413                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3414                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3415                   else
3416                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3417
3418                   if (packed_args)
3419                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3420                 }
3421             }
3422
3423           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3424             /* We only care about the pattern.  */
3425             arg = PACK_EXPANSION_PATTERN (arg);
3426
3427           if (/* These first two lines are the `non-type' bit.  */
3428               !TYPE_P (arg)
3429               && TREE_CODE (arg) != TEMPLATE_DECL
3430               /* This next line is the `argument expression is not just a
3431                  simple identifier' condition and also the `specialized
3432                  non-type argument' bit.  */
3433               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3434             {
3435               if ((!packed_args && tpd.arg_uses_template_parms[i])
3436                   || (packed_args && uses_template_parms (arg)))
3437                 error ("template argument %qE involves template parameter(s)",
3438                        arg);
3439               else 
3440                 {
3441                   /* Look at the corresponding template parameter,
3442                      marking which template parameters its type depends
3443                      upon.  */
3444                   tree type = TREE_TYPE (parm);
3445
3446                   if (!tpd2.parms)
3447                     {
3448                       /* We haven't yet initialized TPD2.  Do so now.  */
3449                       tpd2.arg_uses_template_parms 
3450                         = (int *) alloca (sizeof (int) * nargs);
3451                       /* The number of parameters here is the number in the
3452                          main template, which, as checked in the assertion
3453                          above, is NARGS.  */
3454                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3455                       tpd2.level = 
3456                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3457                     }
3458
3459                   /* Mark the template parameters.  But this time, we're
3460                      looking for the template parameters of the main
3461                      template, not in the specialization.  */
3462                   tpd2.current_arg = i;
3463                   tpd2.arg_uses_template_parms[i] = 0;
3464                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3465                   for_each_template_parm (type,
3466                                           &mark_template_parm,
3467                                           &tpd2,
3468                                           NULL,
3469                                           /*include_nondeduced_p=*/false);
3470
3471                   if (tpd2.arg_uses_template_parms [i])
3472                     {
3473                       /* The type depended on some template parameters.
3474                          If they are fully specialized in the
3475                          specialization, that's OK.  */
3476                       int j;
3477                       for (j = 0; j < nargs; ++j)
3478                         if (tpd2.parms[j] != 0
3479                             && tpd.arg_uses_template_parms [j])
3480                           {
3481                             error ("type %qT of template argument %qE depends "
3482                                    "on template parameter(s)", 
3483                                    type,
3484                                    arg);
3485                             break;
3486                           }
3487                     }
3488                 }
3489             }
3490         }
3491     }
3492
3493   if (retrieve_specialization (maintmpl, specargs,
3494                                /*class_specializations_p=*/true))
3495     /* We've already got this specialization.  */
3496     return decl;
3497
3498   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3499     = tree_cons (specargs, inner_parms,
3500                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3501   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3502   return decl;
3503 }
3504
3505 /* Check that a template declaration's use of default arguments and
3506    parameter packs is not invalid.  Here, PARMS are the template
3507    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3508    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3509    specialization.
3510    
3511
3512    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3513    declaration (but not a definition); 1 indicates a declaration, 2
3514    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3515    emitted for extraneous default arguments.
3516
3517    Returns TRUE if there were no errors found, FALSE otherwise. */
3518
3519 bool
3520 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3521                          int is_partial, int is_friend_decl)
3522 {
3523   const char *msg;
3524   int last_level_to_check;
3525   tree parm_level;
3526   bool no_errors = true;
3527
3528   /* [temp.param]
3529
3530      A default template-argument shall not be specified in a
3531      function template declaration or a function template definition, nor
3532      in the template-parameter-list of the definition of a member of a
3533      class template.  */
3534
3535   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3536     /* You can't have a function template declaration in a local
3537        scope, nor you can you define a member of a class template in a
3538        local scope.  */
3539     return true;
3540
3541   if (current_class_type
3542       && !TYPE_BEING_DEFINED (current_class_type)
3543       && DECL_LANG_SPECIFIC (decl)
3544       /* If this is either a friend defined in the scope of the class
3545          or a member function.  */
3546       && (DECL_FUNCTION_MEMBER_P (decl)
3547           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3548           : DECL_FRIEND_CONTEXT (decl)
3549           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3550           : false)
3551       /* And, if it was a member function, it really was defined in
3552          the scope of the class.  */
3553       && (!DECL_FUNCTION_MEMBER_P (decl)
3554           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3555     /* We already checked these parameters when the template was
3556        declared, so there's no need to do it again now.  This function
3557        was defined in class scope, but we're processing it's body now
3558        that the class is complete.  */
3559     return true;
3560
3561   /* Core issue 226 (C++0x only): the following only applies to class
3562      templates.  */
3563   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3564     {
3565       /* [temp.param]
3566
3567          If a template-parameter has a default template-argument, all
3568          subsequent template-parameters shall have a default
3569          template-argument supplied.  */
3570       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3571         {
3572           tree inner_parms = TREE_VALUE (parm_level);
3573           int ntparms = TREE_VEC_LENGTH (inner_parms);
3574           int seen_def_arg_p = 0;
3575           int i;
3576
3577           for (i = 0; i < ntparms; ++i)
3578             {
3579               tree parm = TREE_VEC_ELT (inner_parms, i);
3580
3581               if (parm == error_mark_node)
3582                 continue;
3583
3584               if (TREE_PURPOSE (parm))
3585                 seen_def_arg_p = 1;
3586               else if (seen_def_arg_p)
3587                 {
3588                   error ("no default argument for %qD", TREE_VALUE (parm));
3589                   /* For better subsequent error-recovery, we indicate that
3590                      there should have been a default argument.  */
3591                   TREE_PURPOSE (parm) = error_mark_node;
3592                   no_errors = false;
3593                 }
3594               else if (is_primary
3595                        && !is_partial
3596                        && !is_friend_decl
3597                        && TREE_CODE (decl) == TYPE_DECL
3598                        && i < ntparms - 1
3599                        && template_parameter_pack_p (TREE_VALUE (parm)))
3600                 {
3601                   /* A primary class template can only have one
3602                      parameter pack, at the end of the template
3603                      parameter list.  */
3604
3605                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
3606                     error ("parameter pack %qE must be at the end of the"
3607                            " template parameter list", TREE_VALUE (parm));
3608                   else
3609                     error ("parameter pack %qT must be at the end of the"
3610                            " template parameter list", 
3611                            TREE_TYPE (TREE_VALUE (parm)));
3612
3613                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
3614                     = error_mark_node;
3615                   no_errors = false;
3616                 }
3617             }
3618         }
3619     }
3620
3621   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
3622       || is_partial 
3623       || !is_primary
3624       || is_friend_decl)
3625     /* For an ordinary class template, default template arguments are
3626        allowed at the innermost level, e.g.:
3627          template <class T = int>
3628          struct S {};
3629        but, in a partial specialization, they're not allowed even
3630        there, as we have in [temp.class.spec]:
3631
3632          The template parameter list of a specialization shall not
3633          contain default template argument values.
3634
3635        So, for a partial specialization, or for a function template
3636        (in C++98/C++03), we look at all of them.  */
3637     ;
3638   else
3639     /* But, for a primary class template that is not a partial
3640        specialization we look at all template parameters except the
3641        innermost ones.  */
3642     parms = TREE_CHAIN (parms);
3643
3644   /* Figure out what error message to issue.  */
3645   if (is_friend_decl == 2)
3646     msg = "default template arguments may not be used in function template friend re-declaration";
3647   else if (is_friend_decl)
3648     msg = "default template arguments may not be used in function template friend declarations";
3649   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
3650     msg = "default template arguments may not be used in function templates";
3651   else if (is_partial)
3652     msg = "default template arguments may not be used in partial specializations";
3653   else
3654     msg = "default argument for template parameter for class enclosing %qD";
3655
3656   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
3657     /* If we're inside a class definition, there's no need to
3658        examine the parameters to the class itself.  On the one
3659        hand, they will be checked when the class is defined, and,
3660        on the other, default arguments are valid in things like:
3661          template <class T = double>
3662          struct S { template <class U> void f(U); };
3663        Here the default argument for `S' has no bearing on the
3664        declaration of `f'.  */
3665     last_level_to_check = template_class_depth (current_class_type) + 1;
3666   else
3667     /* Check everything.  */
3668     last_level_to_check = 0;
3669
3670   for (parm_level = parms;
3671        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
3672        parm_level = TREE_CHAIN (parm_level))
3673     {
3674       tree inner_parms = TREE_VALUE (parm_level);
3675       int i;
3676       int ntparms;
3677
3678       ntparms = TREE_VEC_LENGTH (inner_parms);
3679       for (i = 0; i < ntparms; ++i)
3680         {
3681           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
3682             continue;
3683
3684           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
3685             {
3686               if (msg)
3687                 {
3688                   no_errors = false;
3689                   if (is_friend_decl == 2)
3690                     return no_errors;
3691
3692                   error (msg, decl);
3693                   msg = 0;
3694                 }
3695
3696               /* Clear out the default argument so that we are not
3697                  confused later.  */
3698               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
3699             }
3700         }
3701
3702       /* At this point, if we're still interested in issuing messages,
3703          they must apply to classes surrounding the object declared.  */
3704       if (msg)
3705         msg = "default argument for template parameter for class enclosing %qD";
3706     }
3707
3708   return no_errors;
3709 }
3710
3711 /* Worker for push_template_decl_real, called via
3712    for_each_template_parm.  DATA is really an int, indicating the
3713    level of the parameters we are interested in.  If T is a template
3714    parameter of that level, return nonzero.  */
3715
3716 static int
3717 template_parm_this_level_p (tree t, void* data)
3718 {
3719   int this_level = *(int *)data;
3720   int level;
3721
3722   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3723     level = TEMPLATE_PARM_LEVEL (t);
3724   else
3725     level = TEMPLATE_TYPE_LEVEL (t);
3726   return level == this_level;
3727 }
3728
3729 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
3730    parameters given by current_template_args, or reuses a
3731    previously existing one, if appropriate.  Returns the DECL, or an
3732    equivalent one, if it is replaced via a call to duplicate_decls.
3733
3734    If IS_FRIEND is true, DECL is a friend declaration.  */
3735
3736 tree
3737 push_template_decl_real (tree decl, bool is_friend)
3738 {
3739   tree tmpl;
3740   tree args;
3741   tree info;
3742   tree ctx;
3743   int primary;
3744   int is_partial;
3745   int new_template_p = 0;
3746   /* True if the template is a member template, in the sense of
3747      [temp.mem].  */
3748   bool member_template_p = false;
3749
3750   if (decl == error_mark_node)
3751     return decl;
3752
3753   /* See if this is a partial specialization.  */
3754   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
3755                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3756                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
3757
3758   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
3759     is_friend = true;
3760
3761   if (is_friend)
3762     /* For a friend, we want the context of the friend function, not
3763        the type of which it is a friend.  */
3764     ctx = DECL_CONTEXT (decl);
3765   else if (CP_DECL_CONTEXT (decl)
3766            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
3767     /* In the case of a virtual function, we want the class in which
3768        it is defined.  */
3769     ctx = CP_DECL_CONTEXT (decl);
3770   else
3771     /* Otherwise, if we're currently defining some class, the DECL
3772        is assumed to be a member of the class.  */
3773     ctx = current_scope ();
3774
3775   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
3776     ctx = NULL_TREE;
3777
3778   if (!DECL_CONTEXT (decl))
3779     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
3780
3781   /* See if this is a primary template.  */
3782   if (is_friend && ctx)
3783     /* A friend template that specifies a class context, i.e.
3784          template <typename T> friend void A<T>::f();
3785        is not primary.  */
3786     primary = 0;
3787   else
3788     primary = template_parm_scope_p ();
3789
3790   if (primary)
3791     {
3792       if (DECL_CLASS_SCOPE_P (decl))
3793         member_template_p = true;
3794       if (TREE_CODE (decl) == TYPE_DECL
3795           && ANON_AGGRNAME_P (DECL_NAME (decl)))
3796         error ("template class without a name");
3797       else if (TREE_CODE (decl) == FUNCTION_DECL)
3798         {
3799           if (DECL_DESTRUCTOR_P (decl))
3800             {
3801               /* [temp.mem]
3802
3803                  A destructor shall not be a member template.  */
3804               error ("destructor %qD declared as member template", decl);
3805               return error_mark_node;
3806             }
3807           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
3808               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
3809                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
3810                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
3811                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
3812                       == void_list_node)))
3813             {
3814               /* [basic.stc.dynamic.allocation]
3815
3816                  An allocation function can be a function
3817                  template. ... Template allocation functions shall
3818                  have two or more parameters.  */
3819               error ("invalid template declaration of %qD", decl);
3820               return error_mark_node;
3821             }
3822         }
3823       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3824                && CLASS_TYPE_P (TREE_TYPE (decl)))
3825         /* OK */;
3826       else
3827         {
3828           error ("template declaration of %q#D", decl);
3829           return error_mark_node;
3830         }
3831     }
3832
3833   /* Check to see that the rules regarding the use of default
3834      arguments are not being violated.  */
3835   check_default_tmpl_args (decl, current_template_parms,
3836                            primary, is_partial, /*is_friend_decl=*/0);
3837
3838   /* Ensure that there are no parameter packs in the type of this
3839      declaration that have not been expanded.  */
3840   if (TREE_CODE (decl) == FUNCTION_DECL)
3841     {
3842       /* Check each of the arguments individually to see if there are
3843          any bare parameter packs.  */
3844       tree type = TREE_TYPE (decl);
3845       tree arg = DECL_ARGUMENTS (decl);
3846       tree argtype = TYPE_ARG_TYPES (type);
3847
3848       while (arg && argtype)
3849         {
3850           if (!FUNCTION_PARAMETER_PACK_P (arg)
3851               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
3852             {
3853             /* This is a PARM_DECL that contains unexpanded parameter
3854                packs. We have already complained about this in the
3855                check_for_bare_parameter_packs call, so just replace
3856                these types with ERROR_MARK_NODE.  */
3857               TREE_TYPE (arg) = error_mark_node;
3858               TREE_VALUE (argtype) = error_mark_node;
3859             }
3860
3861           arg = TREE_CHAIN (arg);
3862           argtype = TREE_CHAIN (argtype);
3863         }
3864
3865       /* Check for bare parameter packs in the return type and the
3866          exception specifiers.  */
3867       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
3868         /* Errors were already issued, set return type to int
3869            as the frontend doesn't expect error_mark_node as
3870            the return type.  */
3871         TREE_TYPE (type) = integer_type_node;
3872       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
3873         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
3874     }
3875   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
3876     {
3877       TREE_TYPE (decl) = error_mark_node;
3878       return error_mark_node;
3879     }
3880
3881   if (is_partial)
3882     return process_partial_specialization (decl);
3883
3884   args = current_template_args ();
3885
3886   if (!ctx
3887       || TREE_CODE (ctx) == FUNCTION_DECL
3888       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
3889       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
3890     {
3891       if (DECL_LANG_SPECIFIC (decl)
3892           && DECL_TEMPLATE_INFO (decl)
3893           && DECL_TI_TEMPLATE (decl))
3894         tmpl = DECL_TI_TEMPLATE (decl);
3895       /* If DECL is a TYPE_DECL for a class-template, then there won't
3896          be DECL_LANG_SPECIFIC.  The information equivalent to
3897          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
3898       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3899                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3900                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3901         {
3902           /* Since a template declaration already existed for this
3903              class-type, we must be redeclaring it here.  Make sure
3904              that the redeclaration is valid.  */
3905           redeclare_class_template (TREE_TYPE (decl),
3906                                     current_template_parms);
3907           /* We don't need to create a new TEMPLATE_DECL; just use the
3908              one we already had.  */
3909           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3910         }
3911       else
3912         {
3913           tmpl = build_template_decl (decl, current_template_parms,
3914                                       member_template_p);
3915           new_template_p = 1;
3916
3917           if (DECL_LANG_SPECIFIC (decl)
3918               && DECL_TEMPLATE_SPECIALIZATION (decl))
3919             {
3920               /* A specialization of a member template of a template
3921                  class.  */
3922               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3923               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
3924               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
3925             }
3926         }
3927     }
3928   else
3929     {
3930       tree a, t, current, parms;
3931       int i;
3932       tree tinfo = get_template_info (decl);
3933
3934       if (!tinfo)
3935         {
3936           error ("template definition of non-template %q#D", decl);
3937           return error_mark_node;
3938         }
3939
3940       tmpl = TI_TEMPLATE (tinfo);
3941
3942       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3943           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
3944           && DECL_TEMPLATE_SPECIALIZATION (decl)
3945           && DECL_MEMBER_TEMPLATE_P (tmpl))
3946         {
3947           tree new_tmpl;
3948
3949           /* The declaration is a specialization of a member
3950              template, declared outside the class.  Therefore, the
3951              innermost template arguments will be NULL, so we
3952              replace them with the arguments determined by the
3953              earlier call to check_explicit_specialization.  */
3954           args = DECL_TI_ARGS (decl);
3955
3956           new_tmpl
3957             = build_template_decl (decl, current_template_parms,
3958                                    member_template_p);
3959           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
3960           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
3961           DECL_TI_TEMPLATE (decl) = new_tmpl;
3962           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
3963           DECL_TEMPLATE_INFO (new_tmpl)
3964             = tree_cons (tmpl, args, NULL_TREE);
3965
3966           register_specialization (new_tmpl,
3967                                    most_general_template (tmpl),
3968                                    args,
3969                                    is_friend);
3970           return decl;
3971         }
3972
3973       /* Make sure the template headers we got make sense.  */
3974
3975       parms = DECL_TEMPLATE_PARMS (tmpl);
3976       i = TMPL_PARMS_DEPTH (parms);
3977       if (TMPL_ARGS_DEPTH (args) != i)
3978         {
3979           error ("expected %d levels of template parms for %q#D, got %d",
3980                  i, decl, TMPL_ARGS_DEPTH (args));
3981         }
3982       else
3983         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
3984           {
3985             a = TMPL_ARGS_LEVEL (args, i);
3986             t = INNERMOST_TEMPLATE_PARMS (parms);
3987
3988             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
3989               {
3990                 if (current == decl)
3991                   error ("got %d template parameters for %q#D",
3992                          TREE_VEC_LENGTH (a), decl);
3993                 else
3994                   error ("got %d template parameters for %q#T",
3995                          TREE_VEC_LENGTH (a), current);
3996                 error ("  but %d required", TREE_VEC_LENGTH (t));
3997                 return error_mark_node;
3998               }
3999
4000             if (current == decl)
4001               current = ctx;
4002             else
4003               current = (TYPE_P (current)
4004                          ? TYPE_CONTEXT (current)
4005                          : DECL_CONTEXT (current));
4006           }
4007
4008       /* Check that the parms are used in the appropriate qualifying scopes
4009          in the declarator.  */
4010       if (!comp_template_args
4011           (TI_ARGS (tinfo),
4012            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4013         {
4014           error ("\
4015 template arguments to %qD do not match original template %qD",
4016                  decl, DECL_TEMPLATE_RESULT (tmpl));
4017           if (!uses_template_parms (TI_ARGS (tinfo)))
4018             inform ("use template<> for an explicit specialization");
4019           /* Avoid crash in import_export_decl.  */
4020           DECL_INTERFACE_KNOWN (decl) = 1;
4021           return error_mark_node;
4022         }
4023     }
4024
4025   DECL_TEMPLATE_RESULT (tmpl) = decl;
4026   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4027
4028   /* Push template declarations for global functions and types.  Note
4029      that we do not try to push a global template friend declared in a
4030      template class; such a thing may well depend on the template
4031      parameters of the class.  */
4032   if (new_template_p && !ctx
4033       && !(is_friend && template_class_depth (current_class_type) > 0))
4034     {
4035       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4036       if (tmpl == error_mark_node)
4037         return error_mark_node;
4038
4039       /* Hide template friend classes that haven't been declared yet.  */
4040       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4041         {
4042           DECL_ANTICIPATED (tmpl) = 1;
4043           DECL_FRIEND_P (tmpl) = 1;
4044         }
4045     }
4046
4047   if (primary)
4048     {
4049       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4050       int i;
4051
4052       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4053       if (DECL_CONV_FN_P (tmpl))
4054         {
4055           int depth = TMPL_PARMS_DEPTH (parms);
4056
4057           /* It is a conversion operator. See if the type converted to
4058              depends on innermost template operands.  */
4059
4060           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4061                                          depth))
4062             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4063         }
4064
4065       /* Give template template parms a DECL_CONTEXT of the template
4066          for which they are a parameter.  */
4067       parms = INNERMOST_TEMPLATE_PARMS (parms);
4068       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4069         {
4070           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4071           if (TREE_CODE (parm) == TEMPLATE_DECL)
4072             DECL_CONTEXT (parm) = tmpl;
4073         }
4074     }
4075
4076   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4077      back to its most general template.  If TMPL is a specialization,
4078      ARGS may only have the innermost set of arguments.  Add the missing
4079      argument levels if necessary.  */
4080   if (DECL_TEMPLATE_INFO (tmpl))
4081     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4082
4083   info = tree_cons (tmpl, args, NULL_TREE);
4084
4085   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4086     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4087   else if (DECL_LANG_SPECIFIC (decl))
4088     DECL_TEMPLATE_INFO (decl) = info;
4089
4090   return DECL_TEMPLATE_RESULT (tmpl);
4091 }
4092
4093 tree
4094 push_template_decl (tree decl)
4095 {
4096   return push_template_decl_real (decl, false);
4097 }
4098
4099 /* Called when a class template TYPE is redeclared with the indicated
4100    template PARMS, e.g.:
4101
4102      template <class T> struct S;
4103      template <class T> struct S {};  */
4104
4105 bool
4106 redeclare_class_template (tree type, tree parms)
4107 {
4108   tree tmpl;
4109   tree tmpl_parms;
4110   int i;
4111
4112   if (!TYPE_TEMPLATE_INFO (type))
4113     {
4114       error ("%qT is not a template type", type);
4115       return false;
4116     }
4117
4118   tmpl = TYPE_TI_TEMPLATE (type);
4119   if (!PRIMARY_TEMPLATE_P (tmpl))
4120     /* The type is nested in some template class.  Nothing to worry
4121        about here; there are no new template parameters for the nested
4122        type.  */
4123     return true;
4124
4125   if (!parms)
4126     {
4127       error ("template specifiers not specified in declaration of %qD",
4128              tmpl);
4129       return false;
4130     }
4131
4132   parms = INNERMOST_TEMPLATE_PARMS (parms);
4133   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4134
4135   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4136     {
4137       error ("redeclared with %d template parameter(s)", 
4138              TREE_VEC_LENGTH (parms));
4139       inform ("previous declaration %q+D used %d template parameter(s)", 
4140              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4141       return false;
4142     }
4143
4144   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4145     {
4146       tree tmpl_parm;
4147       tree parm;
4148       tree tmpl_default;
4149       tree parm_default;
4150
4151       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4152           || TREE_VEC_ELT (parms, i) == error_mark_node)
4153         continue;
4154
4155       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4156       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4157       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4158       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4159
4160       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4161          TEMPLATE_DECL.  */
4162       if (tmpl_parm != error_mark_node
4163           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4164               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4165                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4166               || (TREE_CODE (tmpl_parm) != PARM_DECL
4167                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4168                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4169               || (TREE_CODE (tmpl_parm) == PARM_DECL
4170                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4171                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4172         {
4173           error ("template parameter %q+#D", tmpl_parm);
4174           error ("redeclared here as %q#D", parm);
4175           return false;
4176         }
4177
4178       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4179         {
4180           /* We have in [temp.param]:
4181
4182              A template-parameter may not be given default arguments
4183              by two different declarations in the same scope.  */
4184           error ("redefinition of default argument for %q#D", parm);
4185           inform ("%Joriginal definition appeared here", tmpl_parm);
4186           return false;
4187         }
4188
4189       if (parm_default != NULL_TREE)
4190         /* Update the previous template parameters (which are the ones
4191            that will really count) with the new default value.  */
4192         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4193       else if (tmpl_default != NULL_TREE)
4194         /* Update the new parameters, too; they'll be used as the
4195            parameters for any members.  */
4196         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4197     }
4198
4199     return true;
4200 }
4201
4202 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4203    (possibly simplified) expression.  */
4204
4205 tree
4206 fold_non_dependent_expr (tree expr)
4207 {
4208   if (expr == NULL_TREE)
4209     return NULL_TREE;
4210
4211   /* If we're in a template, but EXPR isn't value dependent, simplify
4212      it.  We're supposed to treat:
4213
4214        template <typename T> void f(T[1 + 1]);
4215        template <typename T> void f(T[2]);
4216
4217      as two declarations of the same function, for example.  */
4218   if (processing_template_decl
4219       && !type_dependent_expression_p (expr)
4220       && !value_dependent_expression_p (expr))
4221     {
4222       HOST_WIDE_INT saved_processing_template_decl;
4223
4224       saved_processing_template_decl = processing_template_decl;
4225       processing_template_decl = 0;
4226       expr = tsubst_copy_and_build (expr,
4227                                     /*args=*/NULL_TREE,
4228                                     tf_error,
4229                                     /*in_decl=*/NULL_TREE,
4230                                     /*function_p=*/false,
4231                                     /*integral_constant_expression_p=*/true);
4232       processing_template_decl = saved_processing_template_decl;
4233     }
4234   return expr;
4235 }
4236
4237 /* EXPR is an expression which is used in a constant-expression context.
4238    For instance, it could be a VAR_DECL with a constant initializer.
4239    Extract the innest constant expression.
4240
4241    This is basically a more powerful version of
4242    integral_constant_value, which can be used also in templates where
4243    initializers can maintain a syntactic rather than semantic form
4244    (even if they are non-dependent, for access-checking purposes).  */
4245
4246 static tree
4247 fold_decl_constant_value (tree expr)
4248 {
4249   tree const_expr = expr;
4250   do
4251     {
4252       expr = fold_non_dependent_expr (const_expr);
4253       const_expr = integral_constant_value (expr);
4254     }
4255   while (expr != const_expr);
4256
4257   return expr;
4258 }
4259
4260 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4261    must be a function or a pointer-to-function type, as specified
4262    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4263    and check that the resulting function has external linkage.  */
4264
4265 static tree
4266 convert_nontype_argument_function (tree type, tree expr)
4267 {
4268   tree fns = expr;
4269   tree fn, fn_no_ptr;
4270
4271   fn = instantiate_type (type, fns, tf_none);
4272   if (fn == error_mark_node)
4273     return error_mark_node;
4274
4275   fn_no_ptr = fn;
4276   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4277     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4278   if (TREE_CODE (fn_no_ptr) == BASELINK)
4279     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4280  
4281   /* [temp.arg.nontype]/1
4282
4283      A template-argument for a non-type, non-template template-parameter
4284      shall be one of:
4285      [...]
4286      -- the address of an object or function with external linkage.  */
4287   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4288     {
4289       error ("%qE is not a valid template argument for type %qT "
4290              "because function %qD has not external linkage",
4291              expr, type, fn_no_ptr);
4292       return NULL_TREE;
4293     }
4294
4295   return fn;
4296 }
4297
4298 /* Attempt to convert the non-type template parameter EXPR to the
4299    indicated TYPE.  If the conversion is successful, return the
4300    converted value.  If the conversion is unsuccessful, return
4301    NULL_TREE if we issued an error message, or error_mark_node if we
4302    did not.  We issue error messages for out-and-out bad template
4303    parameters, but not simply because the conversion failed, since we
4304    might be just trying to do argument deduction.  Both TYPE and EXPR
4305    must be non-dependent.
4306
4307    The conversion follows the special rules described in
4308    [temp.arg.nontype], and it is much more strict than an implicit
4309    conversion.
4310
4311    This function is called twice for each template argument (see
4312    lookup_template_class for a more accurate description of this
4313    problem). This means that we need to handle expressions which
4314    are not valid in a C++ source, but can be created from the
4315    first call (for instance, casts to perform conversions). These
4316    hacks can go away after we fix the double coercion problem.  */
4317
4318 static tree
4319 convert_nontype_argument (tree type, tree expr)
4320 {
4321   tree expr_type;
4322
4323   /* Detect immediately string literals as invalid non-type argument.
4324      This special-case is not needed for correctness (we would easily
4325      catch this later), but only to provide better diagnostic for this
4326      common user mistake. As suggested by DR 100, we do not mention
4327      linkage issues in the diagnostic as this is not the point.  */
4328   if (TREE_CODE (expr) == STRING_CST)
4329     {
4330       error ("%qE is not a valid template argument for type %qT "
4331              "because string literals can never be used in this context",
4332              expr, type);
4333       return NULL_TREE;
4334     }
4335
4336   /* If we are in a template, EXPR may be non-dependent, but still
4337      have a syntactic, rather than semantic, form.  For example, EXPR
4338      might be a SCOPE_REF, rather than the VAR_DECL to which the
4339      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4340      so that access checking can be performed when the template is
4341      instantiated -- but here we need the resolved form so that we can
4342      convert the argument.  */
4343   expr = fold_non_dependent_expr (expr);
4344   if (error_operand_p (expr))
4345     return error_mark_node;
4346   expr_type = TREE_TYPE (expr);
4347
4348   /* HACK: Due to double coercion, we can get a
4349      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4350      which is the tree that we built on the first call (see
4351      below when coercing to reference to object or to reference to
4352      function). We just strip everything and get to the arg.
4353      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4354      for examples.  */
4355   if (TREE_CODE (expr) == NOP_EXPR)
4356     {
4357       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4358         {
4359           /* ??? Maybe we could use convert_from_reference here, but we
4360              would need to relax its constraints because the NOP_EXPR
4361              could actually change the type to something more cv-qualified,
4362              and this is not folded by convert_from_reference.  */
4363           tree addr = TREE_OPERAND (expr, 0);
4364           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4365           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4366           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4367           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4368                       (TREE_TYPE (expr_type),
4369                        TREE_TYPE (TREE_TYPE (addr))));
4370
4371           expr = TREE_OPERAND (addr, 0);
4372           expr_type = TREE_TYPE (expr);
4373         }
4374
4375       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4376          parameter is a pointer to object, through decay and
4377          qualification conversion. Let's strip everything.  */
4378       else if (TYPE_PTROBV_P (type))
4379         {
4380           STRIP_NOPS (expr);
4381           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4382           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4383           /* Skip the ADDR_EXPR only if it is part of the decay for
4384              an array. Otherwise, it is part of the original argument
4385              in the source code.  */
4386           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4387             expr = TREE_OPERAND (expr, 0);
4388           expr_type = TREE_TYPE (expr);
4389         }
4390     }
4391
4392   /* [temp.arg.nontype]/5, bullet 1
4393
4394      For a non-type template-parameter of integral or enumeration type,
4395      integral promotions (_conv.prom_) and integral conversions
4396      (_conv.integral_) are applied.  */
4397   if (INTEGRAL_TYPE_P (type))
4398     {
4399       if (!INTEGRAL_TYPE_P (expr_type))
4400         return error_mark_node;
4401
4402       expr = fold_decl_constant_value (expr);
4403       /* Notice that there are constant expressions like '4 % 0' which
4404          do not fold into integer constants.  */
4405       if (TREE_CODE (expr) != INTEGER_CST)
4406         {
4407           error ("%qE is not a valid template argument for type %qT "
4408                  "because it is a non-constant expression", expr, type);
4409           return NULL_TREE;
4410         }
4411
4412       /* At this point, an implicit conversion does what we want,
4413          because we already know that the expression is of integral
4414          type.  */
4415       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4416       if (expr == error_mark_node)
4417         return error_mark_node;
4418
4419       /* Conversion was allowed: fold it to a bare integer constant.  */
4420       expr = fold (expr);
4421     }
4422   /* [temp.arg.nontype]/5, bullet 2
4423
4424      For a non-type template-parameter of type pointer to object,
4425      qualification conversions (_conv.qual_) and the array-to-pointer
4426      conversion (_conv.array_) are applied.  */
4427   else if (TYPE_PTROBV_P (type))
4428     {
4429       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4430
4431          A template-argument for a non-type, non-template template-parameter
4432          shall be one of: [...]
4433
4434          -- the name of a non-type template-parameter;
4435          -- the address of an object or function with external linkage, [...]
4436             expressed as "& id-expression" where the & is optional if the name
4437             refers to a function or array, or if the corresponding
4438             template-parameter is a reference.
4439
4440         Here, we do not care about functions, as they are invalid anyway
4441         for a parameter of type pointer-to-object.  */
4442
4443       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4444         /* Non-type template parameters are OK.  */
4445         ;
4446       else if (TREE_CODE (expr) != ADDR_EXPR
4447                && TREE_CODE (expr_type) != ARRAY_TYPE)
4448         {
4449           if (TREE_CODE (expr) == VAR_DECL)
4450             {
4451               error ("%qD is not a valid template argument "
4452                      "because %qD is a variable, not the address of "
4453                      "a variable",
4454                      expr, expr);
4455               return NULL_TREE;
4456             }
4457           /* Other values, like integer constants, might be valid
4458              non-type arguments of some other type.  */
4459           return error_mark_node;
4460         }
4461       else
4462         {
4463           tree decl;
4464
4465           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4466                   ? TREE_OPERAND (expr, 0) : expr);
4467           if (TREE_CODE (decl) != VAR_DECL)
4468             {
4469               error ("%qE is not a valid template argument of type %qT "
4470                      "because %qE is not a variable",
4471                      expr, type, decl);
4472               return NULL_TREE;
4473             }
4474           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4475             {
4476               error ("%qE is not a valid template argument of type %qT "
4477                      "because %qD does not have external linkage",
4478                      expr, type, decl);
4479               return NULL_TREE;
4480             }
4481         }
4482
4483       expr = decay_conversion (expr);
4484       if (expr == error_mark_node)
4485         return error_mark_node;
4486
4487       expr = perform_qualification_conversions (type, expr);
4488       if (expr == error_mark_node)
4489         return error_mark_node;
4490     }
4491   /* [temp.arg.nontype]/5, bullet 3
4492
4493      For a non-type template-parameter of type reference to object, no
4494      conversions apply. The type referred to by the reference may be more
4495      cv-qualified than the (otherwise identical) type of the
4496      template-argument. The template-parameter is bound directly to the
4497      template-argument, which must be an lvalue.  */
4498   else if (TYPE_REF_OBJ_P (type))
4499     {
4500       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4501                                                       expr_type))
4502         return error_mark_node;
4503
4504       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4505         {
4506           error ("%qE is not a valid template argument for type %qT "
4507                  "because of conflicts in cv-qualification", expr, type);
4508           return NULL_TREE;
4509         }
4510
4511       if (!real_lvalue_p (expr))
4512         {
4513           error ("%qE is not a valid template argument for type %qT "
4514                  "because it is not an lvalue", expr, type);
4515           return NULL_TREE;
4516         }
4517
4518       /* [temp.arg.nontype]/1
4519
4520          A template-argument for a non-type, non-template template-parameter
4521          shall be one of: [...]
4522
4523          -- the address of an object or function with external linkage.  */
4524       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4525         {
4526           error ("%qE is not a valid template argument for type %qT "
4527                  "because object %qD has not external linkage",
4528                  expr, type, expr);
4529           return NULL_TREE;
4530         }
4531
4532       expr = build_nop (type, build_address (expr));
4533     }
4534   /* [temp.arg.nontype]/5, bullet 4
4535
4536      For a non-type template-parameter of type pointer to function, only
4537      the function-to-pointer conversion (_conv.func_) is applied. If the
4538      template-argument represents a set of overloaded functions (or a
4539      pointer to such), the matching function is selected from the set
4540      (_over.over_).  */
4541   else if (TYPE_PTRFN_P (type))
4542     {
4543       /* If the argument is a template-id, we might not have enough
4544          context information to decay the pointer.  */
4545       if (!type_unknown_p (expr_type))
4546         {
4547           expr = decay_conversion (expr);
4548           if (expr == error_mark_node)
4549             return error_mark_node;
4550         }
4551
4552       expr = convert_nontype_argument_function (type, expr);
4553       if (!expr || expr == error_mark_node)
4554         return expr;
4555     }
4556   /* [temp.arg.nontype]/5, bullet 5
4557
4558      For a non-type template-parameter of type reference to function, no
4559      conversions apply. If the template-argument represents a set of
4560      overloaded functions, the matching function is selected from the set
4561      (_over.over_).  */
4562   else if (TYPE_REFFN_P (type))
4563     {
4564       if (TREE_CODE (expr) == ADDR_EXPR)
4565         {
4566           error ("%qE is not a valid template argument for type %qT "
4567                  "because it is a pointer", expr, type);
4568           inform ("try using %qE instead", TREE_OPERAND (expr, 0));
4569           return NULL_TREE;
4570         }
4571
4572       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4573       if (!expr || expr == error_mark_node)
4574         return expr;
4575
4576       expr = build_nop (type, build_address (expr));
4577     }
4578   /* [temp.arg.nontype]/5, bullet 6
4579
4580      For a non-type template-parameter of type pointer to member function,
4581      no conversions apply. If the template-argument represents a set of
4582      overloaded member functions, the matching member function is selected
4583      from the set (_over.over_).  */
4584   else if (TYPE_PTRMEMFUNC_P (type))
4585     {
4586       expr = instantiate_type (type, expr, tf_none);
4587       if (expr == error_mark_node)
4588         return error_mark_node;
4589
4590       /* There is no way to disable standard conversions in
4591          resolve_address_of_overloaded_function (called by
4592          instantiate_type). It is possible that the call succeeded by
4593          converting &B::I to &D::I (where B is a base of D), so we need
4594          to reject this conversion here.
4595
4596          Actually, even if there was a way to disable standard conversions,
4597          it would still be better to reject them here so that we can
4598          provide a superior diagnostic.  */
4599       if (!same_type_p (TREE_TYPE (expr), type))
4600         {
4601           /* Make sure we are just one standard conversion off.  */
4602           gcc_assert (can_convert (type, TREE_TYPE (expr)));
4603           error ("%qE is not a valid template argument for type %qT "
4604                  "because it is of type %qT", expr, type,
4605                  TREE_TYPE (expr));
4606           inform ("standard conversions are not allowed in this context");
4607           return NULL_TREE;
4608         }
4609     }
4610   /* [temp.arg.nontype]/5, bullet 7
4611
4612      For a non-type template-parameter of type pointer to data member,
4613      qualification conversions (_conv.qual_) are applied.  */
4614   else if (TYPE_PTRMEM_P (type))
4615     {
4616       expr = perform_qualification_conversions (type, expr);
4617       if (expr == error_mark_node)
4618         return expr;
4619     }
4620   /* A template non-type parameter must be one of the above.  */
4621   else
4622     gcc_unreachable ();
4623
4624   /* Sanity check: did we actually convert the argument to the
4625      right type?  */
4626   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
4627   return expr;
4628 }
4629
4630
4631 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
4632    template template parameters.  Both PARM_PARMS and ARG_PARMS are
4633    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
4634    or PARM_DECL.
4635
4636    Consider the example:
4637      template <class T> class A;
4638      template<template <class U> class TT> class B;
4639
4640    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
4641    the parameters to A, and OUTER_ARGS contains A.  */
4642
4643 static int
4644 coerce_template_template_parms (tree parm_parms,
4645                                 tree arg_parms,
4646                                 tsubst_flags_t complain,
4647                                 tree in_decl,
4648                                 tree outer_args)
4649 {
4650   int nparms, nargs, i;
4651   tree parm, arg;
4652
4653   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
4654   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
4655
4656   nparms = TREE_VEC_LENGTH (parm_parms);
4657   nargs = TREE_VEC_LENGTH (arg_parms);
4658
4659   if (nargs != nparms)
4660     return 0;
4661
4662   for (i = 0; i < nparms; ++i)
4663     {
4664       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
4665           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4666         continue;
4667
4668       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4669       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4670
4671       if (arg == NULL_TREE || arg == error_mark_node
4672           || parm == NULL_TREE || parm == error_mark_node)
4673         return 0;
4674
4675       if (TREE_CODE (arg) != TREE_CODE (parm))
4676         return 0;
4677
4678       switch (TREE_CODE (parm))
4679         {
4680         case TEMPLATE_DECL:
4681           /* We encounter instantiations of templates like
4682                template <template <template <class> class> class TT>
4683                class C;  */
4684           {
4685             tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4686             tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4687
4688             if (!coerce_template_template_parms
4689                 (parmparm, argparm, complain, in_decl, outer_args))
4690               return 0;
4691           }
4692           /* Fall through.  */
4693
4694         case TYPE_DECL:
4695           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))
4696               != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg)))
4697             /* One is a parameter pack, the other is not.  */
4698             return 0;
4699           break;
4700
4701         case PARM_DECL:
4702           /* The tsubst call is used to handle cases such as
4703
4704                template <int> class C {};
4705                template <class T, template <T> class TT> class D {};
4706                D<int, C> d;
4707
4708              i.e. the parameter list of TT depends on earlier parameters.  */
4709           if (!dependent_type_p (TREE_TYPE (arg))
4710               && !same_type_p
4711                     (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
4712                              TREE_TYPE (arg)))
4713             return 0;
4714
4715           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4716               != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg)))
4717             /* One is a parameter pack, the other is not.  */
4718             return 0;
4719           break;
4720
4721         default:
4722           gcc_unreachable ();
4723         }
4724     }
4725   return 1;
4726 }
4727
4728 /* Verifies that the deduced template arguments (in TARGS) for the
4729    template template parameters (in TPARMS) represent valid bindings,
4730    by comparing the template parameter list of each template argument
4731    to the template parameter list of its corresponding template
4732    template parameter, in accordance with DR150. This
4733    routine can only be called after all template arguments have been
4734    deduced. It will return TRUE if all of the template template
4735    parameter bindings are okay, FALSE otherwise.  */
4736 bool 
4737 template_template_parm_bindings_ok_p (tree tparms, tree targs)
4738 {
4739   int i, ntparms = TREE_VEC_LENGTH (tparms);
4740
4741   targs = INNERMOST_TEMPLATE_ARGS (targs);
4742
4743   for (i = 0; i < ntparms; ++i)
4744     {
4745       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
4746       tree targ = TREE_VEC_ELT (targs, i);
4747
4748       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
4749         {
4750           tree packed_args = NULL_TREE;
4751           int idx, len = 1;
4752
4753           if (ARGUMENT_PACK_P (targ))
4754             {
4755               /* Look inside the argument pack.  */
4756               packed_args = ARGUMENT_PACK_ARGS (targ);
4757               len = TREE_VEC_LENGTH (packed_args);
4758             }
4759
4760           for (idx = 0; idx < len; ++idx)
4761             {
4762               tree targ_parms = NULL_TREE;
4763
4764               if (packed_args)
4765                 /* Extract the next argument from the argument
4766                    pack.  */
4767                 targ = TREE_VEC_ELT (packed_args, idx);
4768
4769               if (PACK_EXPANSION_P (targ))
4770                 /* Look at the pattern of the pack expansion.  */
4771                 targ = PACK_EXPANSION_PATTERN (targ);
4772
4773               /* Extract the template parameters from the template
4774                  argument.  */
4775               if (TREE_CODE (targ) == TEMPLATE_DECL)
4776                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
4777               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
4778                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
4779
4780               /* Verify that we can coerce the template template
4781                  parameters from the template argument to the template
4782                  parameter.  This requires an exact match.  */
4783               if (targ_parms
4784                   && !coerce_template_template_parms
4785                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
4786                         targ_parms,
4787                         tf_none,
4788                         tparm,
4789                         targs))
4790                 return false;
4791             }
4792         }
4793     }
4794
4795   /* Everything is okay.  */
4796   return true;
4797 }
4798
4799 /* Convert the indicated template ARG as necessary to match the
4800    indicated template PARM.  Returns the converted ARG, or
4801    error_mark_node if the conversion was unsuccessful.  Error and
4802    warning messages are issued under control of COMPLAIN.  This
4803    conversion is for the Ith parameter in the parameter list.  ARGS is
4804    the full set of template arguments deduced so far.  */
4805
4806 static tree
4807 convert_template_argument (tree parm,
4808                            tree arg,
4809                            tree args,
4810                            tsubst_flags_t complain,
4811                            int i,
4812                            tree in_decl)
4813 {
4814   tree orig_arg;
4815   tree val;
4816   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
4817
4818   if (TREE_CODE (arg) == TREE_LIST
4819       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
4820     {
4821       /* The template argument was the name of some
4822          member function.  That's usually
4823          invalid, but static members are OK.  In any
4824          case, grab the underlying fields/functions
4825          and issue an error later if required.  */
4826       orig_arg = TREE_VALUE (arg);
4827       TREE_TYPE (arg) = unknown_type_node;
4828     }
4829
4830   orig_arg = arg;
4831
4832   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
4833   requires_type = (TREE_CODE (parm) == TYPE_DECL
4834                    || requires_tmpl_type);
4835
4836   /* When determining whether an argument pack expansion is a template,
4837      look at the pattern.  */
4838   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
4839     arg = PACK_EXPANSION_PATTERN (arg);
4840
4841   is_tmpl_type = 
4842     ((TREE_CODE (arg) == TEMPLATE_DECL
4843       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
4844      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4845      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
4846
4847   if (is_tmpl_type
4848       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4849           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
4850     arg = TYPE_STUB_DECL (arg);
4851
4852   is_type = TYPE_P (arg) || is_tmpl_type;
4853
4854   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
4855       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
4856     {
4857       pedwarn ("to refer to a type member of a template parameter, "
4858                "use %<typename %E%>", orig_arg);
4859
4860       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
4861                                      TREE_OPERAND (arg, 1),
4862                                      typename_type,
4863                                      complain & tf_error);
4864       arg = orig_arg;
4865       is_type = 1;
4866     }
4867   if (is_type != requires_type)
4868     {
4869       if (in_decl)
4870         {
4871           if (complain & tf_error)
4872             {
4873               error ("type/value mismatch at argument %d in template "
4874                      "parameter list for %qD",
4875                      i + 1, in_decl);
4876               if (is_type)
4877                 error ("  expected a constant of type %qT, got %qT",
4878                        TREE_TYPE (parm),
4879                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
4880               else if (requires_tmpl_type)
4881                 error ("  expected a class template, got %qE", orig_arg);
4882               else
4883                 error ("  expected a type, got %qE", orig_arg);
4884             }
4885         }
4886       return error_mark_node;
4887     }
4888   if (is_tmpl_type ^ requires_tmpl_type)
4889     {
4890       if (in_decl && (complain & tf_error))
4891         {
4892           error ("type/value mismatch at argument %d in template "
4893                  "parameter list for %qD",
4894                  i + 1, in_decl);
4895           if (is_tmpl_type)
4896             error ("  expected a type, got %qT", DECL_NAME (arg));
4897           else
4898             error ("  expected a class template, got %qT", orig_arg);
4899         }
4900       return error_mark_node;
4901     }
4902
4903   if (is_type)
4904     {
4905       if (requires_tmpl_type)
4906         {
4907           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
4908             /* The number of argument required is not known yet.
4909                Just accept it for now.  */
4910             val = TREE_TYPE (arg);
4911           else
4912             {
4913               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4914               tree argparm;
4915
4916               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4917
4918               if (coerce_template_template_parms (parmparm, argparm,
4919                                                   complain, in_decl,
4920                                                   args))
4921                 {
4922                   val = orig_arg;
4923
4924                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
4925                      TEMPLATE_DECL.  */
4926                   if (val != error_mark_node)
4927                     {
4928                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
4929                         val = TREE_TYPE (val);
4930                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
4931                                && DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
4932                         {
4933                           val = TREE_TYPE (arg);
4934                           val = make_pack_expansion (val);
4935                         }
4936                     }
4937                 }
4938               else
4939                 {
4940                   if (in_decl && (complain & tf_error))
4941                     {
4942                       error ("type/value mismatch at argument %d in "
4943                              "template parameter list for %qD",
4944                              i + 1, in_decl);
4945                       error ("  expected a template of type %qD, got %qD",
4946                              parm, orig_arg);
4947                     }
4948
4949                   val = error_mark_node;
4950                 }
4951             }
4952         }
4953       else
4954         val = orig_arg;
4955       /* We only form one instance of each template specialization.
4956          Therefore, if we use a non-canonical variant (i.e., a
4957          typedef), any future messages referring to the type will use
4958          the typedef, which is confusing if those future uses do not
4959          themselves also use the typedef.  */
4960       if (TYPE_P (val))
4961         val = canonical_type_variant (val);
4962     }
4963   else
4964     {
4965       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
4966
4967       if (invalid_nontype_parm_type_p (t, complain))
4968         return error_mark_node;
4969
4970       if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
4971         /* We used to call digest_init here.  However, digest_init
4972            will report errors, which we don't want when complain
4973            is zero.  More importantly, digest_init will try too
4974            hard to convert things: for example, `0' should not be
4975            converted to pointer type at this point according to
4976            the standard.  Accepting this is not merely an
4977            extension, since deciding whether or not these
4978            conversions can occur is part of determining which
4979            function template to call, or whether a given explicit
4980            argument specification is valid.  */
4981         val = convert_nontype_argument (t, orig_arg);
4982       else
4983         val = orig_arg;
4984
4985       if (val == NULL_TREE)
4986         val = error_mark_node;
4987       else if (val == error_mark_node && (complain & tf_error))
4988         error ("could not convert template argument %qE to %qT",  orig_arg, t);
4989     }
4990
4991   return val;
4992 }
4993
4994 /* Coerces the remaining template arguments in INNER_ARGS (from
4995    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
4996    Returns the coerced argument pack. PARM_IDX is the position of this
4997    parameter in the template parameter list. ARGS is the original
4998    template argument list.  */
4999 static tree
5000 coerce_template_parameter_pack (tree parms,
5001                                 int parm_idx,
5002                                 tree args,
5003                                 tree inner_args,
5004                                 int arg_idx,
5005                                 tree new_args,
5006                                 int* lost,
5007                                 tree in_decl,
5008                                 tsubst_flags_t complain)
5009 {
5010   tree parm = TREE_VEC_ELT (parms, parm_idx);
5011   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5012   tree packed_args;
5013   tree argument_pack;
5014   tree packed_types = NULL_TREE;
5015
5016   if (arg_idx > nargs)
5017     arg_idx = nargs;
5018
5019   packed_args = make_tree_vec (nargs - arg_idx);
5020
5021   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5022       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5023     {
5024       /* When the template parameter is a non-type template
5025          parameter pack whose type uses parameter packs, we need
5026          to look at each of the template arguments
5027          separately. Build a vector of the types for these
5028          non-type template parameters in PACKED_TYPES.  */
5029       tree expansion 
5030         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5031       packed_types = tsubst_pack_expansion (expansion, args,
5032                                             complain, in_decl);
5033
5034       if (packed_types == error_mark_node)
5035         return error_mark_node;
5036
5037       /* Check that we have the right number of arguments.  */
5038       if (arg_idx < nargs
5039           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5040           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5041         {
5042           int needed_parms 
5043             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5044           error ("wrong number of template arguments (%d, should be %d)",
5045                  nargs, needed_parms);
5046           return error_mark_node;
5047         }
5048
5049       /* If we aren't able to check the actual arguments now
5050          (because they haven't been expanded yet), we can at least
5051          verify that all of the types used for the non-type
5052          template parameter pack are, in fact, valid for non-type
5053          template parameters.  */
5054       if (arg_idx < nargs 
5055           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5056         {
5057           int j, len = TREE_VEC_LENGTH (packed_types);
5058           for (j = 0; j < len; ++j)
5059             {
5060               tree t = TREE_VEC_ELT (packed_types, j);
5061               if (invalid_nontype_parm_type_p (t, complain))
5062                 return error_mark_node;
5063             }
5064         }
5065     }
5066
5067   /* Convert the remaining arguments, which will be a part of the
5068      parameter pack "parm".  */
5069   for (; arg_idx < nargs; ++arg_idx)
5070     {
5071       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5072       tree actual_parm = TREE_VALUE (parm);
5073
5074       if (packed_types && !PACK_EXPANSION_P (arg))
5075         {
5076           /* When we have a vector of types (corresponding to the
5077              non-type template parameter pack that uses parameter
5078              packs in its type, as mention above), and the
5079              argument is not an expansion (which expands to a
5080              currently unknown number of arguments), clone the
5081              parm and give it the next type in PACKED_TYPES.  */
5082           actual_parm = copy_node (actual_parm);
5083           TREE_TYPE (actual_parm) = 
5084             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5085         }
5086
5087       if (arg != error_mark_node)
5088         arg = convert_template_argument (actual_parm, 
5089                                          arg, new_args, complain, parm_idx,
5090                                          in_decl);
5091       if (arg == error_mark_node)
5092         (*lost)++;
5093       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5094     }
5095
5096   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5097       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5098     argument_pack = make_node (TYPE_ARGUMENT_PACK);
5099   else
5100     {
5101       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5102       TREE_TYPE (argument_pack) 
5103         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5104       TREE_CONSTANT (argument_pack) = 1;
5105     }
5106
5107   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5108   return argument_pack;
5109 }
5110
5111 /* Convert all template arguments to their appropriate types, and
5112    return a vector containing the innermost resulting template
5113    arguments.  If any error occurs, return error_mark_node. Error and
5114    warning messages are issued under control of COMPLAIN.
5115
5116    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5117    for arguments not specified in ARGS.  Otherwise, if
5118    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5119    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5120    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5121    ARGS.  */
5122
5123 static tree
5124 coerce_template_parms (tree parms,
5125                        tree args,
5126                        tree in_decl,
5127                        tsubst_flags_t complain,
5128                        bool require_all_args,
5129                        bool use_default_args)
5130 {
5131   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5132   tree inner_args;
5133   tree new_args;
5134   tree new_inner_args;
5135   bool saved_skip_evaluation;
5136
5137   /* When used as a boolean value, indicates whether this is a
5138      variadic template parameter list. Since it's an int, we can also
5139      subtract it from nparms to get the number of non-variadic
5140      parameters.  */
5141   int variadic_p = 0;
5142
5143   inner_args 
5144     = expand_template_argument_pack (INNERMOST_TEMPLATE_ARGS (args));
5145
5146   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5147   nparms = TREE_VEC_LENGTH (parms);
5148
5149   /* Determine if there are any parameter packs.  */
5150   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5151     {
5152       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5153       if (template_parameter_pack_p (tparm))
5154         {
5155           variadic_p = 1;
5156           break;
5157         }
5158     }
5159
5160   if ((nargs > nparms - variadic_p && !variadic_p)
5161       || (nargs < nparms - variadic_p
5162           && require_all_args
5163           && (!use_default_args
5164               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5165                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5166     {
5167       if (complain & tf_error)
5168         {
5169           const char *or_more = "";
5170           if (variadic_p)
5171             {
5172               or_more = " or more";
5173               --nparms;
5174             }
5175
5176           error ("wrong number of template arguments (%d, should be %d%s)",
5177                  nargs, nparms, or_more);
5178
5179           if (in_decl)
5180             error ("provided for %q+D", in_decl);
5181         }
5182
5183       return error_mark_node;
5184     }
5185
5186   /* We need to evaluate the template arguments, even though this
5187      template-id may be nested within a "sizeof".  */
5188   saved_skip_evaluation = skip_evaluation;
5189   skip_evaluation = false;
5190   new_inner_args = make_tree_vec (nparms);
5191   new_args = add_outermost_template_args (args, new_inner_args);
5192   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5193     {
5194       tree arg;
5195       tree parm;
5196
5197       /* Get the Ith template parameter.  */
5198       parm = TREE_VEC_ELT (parms, parm_idx);
5199  
5200       if (parm == error_mark_node)
5201       {
5202         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5203         continue;
5204       }
5205
5206       /* Calculate the next argument.  */
5207       if (template_parameter_pack_p (TREE_VALUE (parm)))
5208         {
5209           /* All remaining arguments will be placed in the
5210              template parameter pack PARM.  */
5211           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5212                                                 inner_args, arg_idx,
5213                                                 new_args, &lost,
5214                                                 in_decl, complain);
5215           
5216           /* Store this argument.  */
5217           if (arg == error_mark_node)
5218             lost++;
5219           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5220
5221           /* We are done with all of the arguments.  */
5222           arg_idx = nargs;
5223
5224           continue;
5225         }
5226       else if (arg_idx < nargs)
5227         {
5228           arg = TREE_VEC_ELT (inner_args, arg_idx);
5229
5230           if (arg && PACK_EXPANSION_P (arg))
5231             {
5232               if (complain & tf_error)
5233                 {
5234                   /* If ARG is a pack expansion, but PARM is not a
5235                      template parameter pack (if it were, we would have
5236                      handled it above), we're trying to expand into a
5237                      fixed-length argument list.  */
5238                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5239                     error ("cannot expand %<%E%> into a fixed-length "
5240                            "argument list", arg);
5241                   else
5242                     error ("cannot expand %<%T%> into a fixed-length "
5243                            "argument list", arg);
5244                 }
5245               return error_mark_node;
5246             }
5247         }
5248       else if (require_all_args)
5249         /* There must be a default arg in this case.  */
5250         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5251                                    complain, in_decl);
5252       else
5253         break;
5254
5255       if (arg == error_mark_node)
5256         {
5257           if (complain & tf_error)
5258             error ("template argument %d is invalid", arg_idx + 1);
5259         }
5260       else if (!arg)
5261         /* This only occurs if there was an error in the template
5262            parameter list itself (which we would already have
5263            reported) that we are trying to recover from, e.g., a class
5264            template with a parameter list such as
5265            template<typename..., typename>.  */
5266         return error_mark_node;
5267       else
5268         arg = convert_template_argument (TREE_VALUE (parm),
5269                                          arg, new_args, complain, 
5270                                          parm_idx, in_decl);
5271
5272       if (arg == error_mark_node)
5273         lost++;
5274       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5275     }
5276   skip_evaluation = saved_skip_evaluation;
5277
5278   if (lost)
5279     return error_mark_node;
5280
5281   return new_inner_args;
5282 }
5283
5284 /* Returns 1 if template args OT and NT are equivalent.  */
5285
5286 static int
5287 template_args_equal (tree ot, tree nt)
5288 {
5289   if (nt == ot)
5290     return 1;
5291
5292   if (TREE_CODE (nt) == TREE_VEC)
5293     /* For member templates */
5294     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5295   else if (PACK_EXPANSION_P (ot))
5296     return PACK_EXPANSION_P (nt) 
5297       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5298                               PACK_EXPANSION_PATTERN (nt));
5299   else if (TYPE_P (nt))
5300     return TYPE_P (ot) && same_type_p (ot, nt);
5301   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5302     return 0;
5303   else
5304     return cp_tree_equal (ot, nt);
5305 }
5306
5307 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5308    of template arguments.  Returns 0 otherwise.  */
5309
5310 int
5311 comp_template_args (tree oldargs, tree newargs)
5312 {
5313   int i;
5314
5315   oldargs = expand_template_argument_pack (oldargs);
5316   newargs = expand_template_argument_pack (newargs);
5317
5318   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5319     return 0;
5320
5321   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5322     {
5323       tree nt = TREE_VEC_ELT (newargs, i);
5324       tree ot = TREE_VEC_ELT (oldargs, i);
5325
5326       if (! template_args_equal (ot, nt))
5327         return 0;
5328     }
5329   return 1;
5330 }
5331
5332 static void
5333 add_pending_template (tree d)
5334 {
5335   tree ti = (TYPE_P (d)
5336              ? CLASSTYPE_TEMPLATE_INFO (d)
5337              : DECL_TEMPLATE_INFO (d));
5338   struct pending_template *pt;
5339   int level;
5340
5341   if (TI_PENDING_TEMPLATE_FLAG (ti))
5342     return;
5343
5344   /* We are called both from instantiate_decl, where we've already had a
5345      tinst_level pushed, and instantiate_template, where we haven't.
5346      Compensate.  */
5347   level = !current_tinst_level || current_tinst_level->decl != d;
5348
5349   if (level)
5350     push_tinst_level (d);
5351
5352   pt = GGC_NEW (struct pending_template);
5353   pt->next = NULL;
5354   pt->tinst = current_tinst_level;
5355   if (last_pending_template)
5356     last_pending_template->next = pt;
5357   else
5358     pending_templates = pt;
5359
5360   last_pending_template = pt;
5361
5362   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5363
5364   if (level)
5365     pop_tinst_level ();
5366 }
5367
5368
5369 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5370    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5371    documentation for TEMPLATE_ID_EXPR.  */
5372
5373 tree
5374 lookup_template_function (tree fns, tree arglist)
5375 {
5376   tree type;
5377
5378   if (fns == error_mark_node || arglist == error_mark_node)
5379     return error_mark_node;
5380
5381   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5382   gcc_assert (fns && (is_overloaded_fn (fns)
5383                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5384
5385   if (BASELINK_P (fns))
5386     {
5387       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5388                                          unknown_type_node,
5389                                          BASELINK_FUNCTIONS (fns),
5390                                          arglist);
5391       return fns;
5392     }
5393
5394   type = TREE_TYPE (fns);
5395   if (TREE_CODE (fns) == OVERLOAD || !type)
5396     type = unknown_type_node;
5397
5398   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5399 }
5400
5401 /* Within the scope of a template class S<T>, the name S gets bound
5402    (in build_self_reference) to a TYPE_DECL for the class, not a
5403    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5404    or one of its enclosing classes, and that type is a template,
5405    return the associated TEMPLATE_DECL.  Otherwise, the original
5406    DECL is returned.  */
5407
5408 tree
5409 maybe_get_template_decl_from_type_decl (tree decl)
5410 {
5411   return (decl != NULL_TREE
5412           && TREE_CODE (decl) == TYPE_DECL
5413           && DECL_ARTIFICIAL (decl)
5414           && CLASS_TYPE_P (TREE_TYPE (decl))
5415           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5416     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5417 }
5418
5419 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5420    parameters, find the desired type.
5421
5422    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5423
5424    IN_DECL, if non-NULL, is the template declaration we are trying to
5425    instantiate.
5426
5427    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5428    the class we are looking up.
5429
5430    Issue error and warning messages under control of COMPLAIN.
5431
5432    If the template class is really a local class in a template
5433    function, then the FUNCTION_CONTEXT is the function in which it is
5434    being instantiated.
5435
5436    ??? Note that this function is currently called *twice* for each
5437    template-id: the first time from the parser, while creating the
5438    incomplete type (finish_template_type), and the second type during the
5439    real instantiation (instantiate_template_class). This is surely something
5440    that we want to avoid. It also causes some problems with argument
5441    coercion (see convert_nontype_argument for more information on this).  */
5442
5443 tree
5444 lookup_template_class (tree d1,
5445                        tree arglist,
5446                        tree in_decl,
5447                        tree context,
5448                        int entering_scope,
5449                        tsubst_flags_t complain)
5450 {
5451   tree template = NULL_TREE, parmlist;
5452   tree t;
5453
5454   timevar_push (TV_NAME_LOOKUP);
5455
5456   if (TREE_CODE (d1) == IDENTIFIER_NODE)
5457     {
5458       tree value = innermost_non_namespace_value (d1);
5459       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
5460         template = value;
5461       else
5462         {
5463           if (context)
5464             push_decl_namespace (context);
5465           template = lookup_name (d1);
5466           template = maybe_get_template_decl_from_type_decl (template);
5467           if (context)
5468             pop_decl_namespace ();
5469         }
5470       if (template)
5471         context = DECL_CONTEXT (template);
5472     }
5473   else if (TREE_CODE (d1) == TYPE_DECL && IS_AGGR_TYPE (TREE_TYPE (d1)))
5474     {
5475       tree type = TREE_TYPE (d1);
5476
5477       /* If we are declaring a constructor, say A<T>::A<T>, we will get
5478          an implicit typename for the second A.  Deal with it.  */
5479       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
5480         type = TREE_TYPE (type);
5481
5482       if (CLASSTYPE_TEMPLATE_INFO (type))
5483         {
5484           template = CLASSTYPE_TI_TEMPLATE (type);
5485           d1 = DECL_NAME (template);
5486         }
5487     }
5488   else if (TREE_CODE (d1) == ENUMERAL_TYPE
5489            || (TYPE_P (d1) && IS_AGGR_TYPE (d1)))
5490     {
5491       template = TYPE_TI_TEMPLATE (d1);
5492       d1 = DECL_NAME (template);
5493     }
5494   else if (TREE_CODE (d1) == TEMPLATE_DECL
5495            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
5496     {
5497       template = d1;
5498       d1 = DECL_NAME (template);
5499       context = DECL_CONTEXT (template);
5500     }
5501
5502   /* Issue an error message if we didn't find a template.  */
5503   if (! template)
5504     {
5505       if (complain & tf_error)
5506         error ("%qT is not a template", d1);
5507       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5508     }
5509
5510   if (TREE_CODE (template) != TEMPLATE_DECL
5511          /* Make sure it's a user visible template, if it was named by
5512             the user.  */
5513       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (template)
5514           && !PRIMARY_TEMPLATE_P (template)))
5515     {
5516       if (complain & tf_error)
5517         {
5518           error ("non-template type %qT used as a template", d1);
5519           if (in_decl)
5520             error ("for template declaration %q+D", in_decl);
5521         }
5522       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5523     }
5524
5525   complain &= ~tf_user;
5526
5527   if (DECL_TEMPLATE_TEMPLATE_PARM_P (template))
5528     {
5529       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
5530          template arguments */
5531
5532       tree parm;
5533       tree arglist2;
5534       tree outer;
5535
5536       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (template);
5537
5538       /* Consider an example where a template template parameter declared as
5539
5540            template <class T, class U = std::allocator<T> > class TT
5541
5542          The template parameter level of T and U are one level larger than
5543          of TT.  To proper process the default argument of U, say when an
5544          instantiation `TT<int>' is seen, we need to build the full
5545          arguments containing {int} as the innermost level.  Outer levels,
5546          available when not appearing as default template argument, can be
5547          obtained from the arguments of the enclosing template.
5548
5549          Suppose that TT is later substituted with std::vector.  The above
5550          instantiation is `TT<int, std::allocator<T> >' with TT at
5551          level 1, and T at level 2, while the template arguments at level 1
5552          becomes {std::vector} and the inner level 2 is {int}.  */
5553
5554       outer = DECL_CONTEXT (template);
5555       if (outer)
5556         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
5557       else if (current_template_parms)
5558         /* This is an argument of the current template, so we haven't set
5559            DECL_CONTEXT yet.  */
5560         outer = current_template_args ();
5561
5562       if (outer)
5563         arglist = add_to_template_args (outer, arglist);
5564
5565       arglist2 = coerce_template_parms (parmlist, arglist, template,
5566                                         complain,
5567                                         /*require_all_args=*/true,
5568                                         /*use_default_args=*/true);
5569       if (arglist2 == error_mark_node
5570           || (!uses_template_parms (arglist2)
5571               && check_instantiated_args (template, arglist2, complain)))
5572         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5573
5574       parm = bind_template_template_parm (TREE_TYPE (template), arglist2);
5575       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
5576     }
5577   else
5578     {
5579       tree template_type = TREE_TYPE (template);
5580       tree gen_tmpl;
5581       tree type_decl;
5582       tree found = NULL_TREE;
5583       int arg_depth;
5584       int parm_depth;
5585       int is_partial_instantiation;
5586
5587       gen_tmpl = most_general_template (template);
5588       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
5589       parm_depth = TMPL_PARMS_DEPTH (parmlist);
5590       arg_depth = TMPL_ARGS_DEPTH (arglist);
5591
5592       if (arg_depth == 1 && parm_depth > 1)
5593         {
5594           /* We've been given an incomplete set of template arguments.
5595              For example, given:
5596
5597                template <class T> struct S1 {
5598                  template <class U> struct S2 {};
5599                  template <class U> struct S2<U*> {};
5600                 };
5601
5602              we will be called with an ARGLIST of `U*', but the
5603              TEMPLATE will be `template <class T> template
5604              <class U> struct S1<T>::S2'.  We must fill in the missing
5605              arguments.  */
5606           arglist
5607             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (template)),
5608                                            arglist);
5609           arg_depth = TMPL_ARGS_DEPTH (arglist);
5610         }
5611
5612       /* Now we should have enough arguments.  */
5613       gcc_assert (parm_depth == arg_depth);
5614
5615       /* From here on, we're only interested in the most general
5616          template.  */
5617       template = gen_tmpl;
5618
5619       /* Calculate the BOUND_ARGS.  These will be the args that are
5620          actually tsubst'd into the definition to create the
5621          instantiation.  */
5622       if (parm_depth > 1)
5623         {
5624           /* We have multiple levels of arguments to coerce, at once.  */
5625           int i;
5626           int saved_depth = TMPL_ARGS_DEPTH (arglist);
5627
5628           tree bound_args = make_tree_vec (parm_depth);
5629
5630           for (i = saved_depth,
5631                  t = DECL_TEMPLATE_PARMS (template);
5632                i > 0 && t != NULL_TREE;
5633                --i, t = TREE_CHAIN (t))
5634             {
5635               tree a = coerce_template_parms (TREE_VALUE (t),
5636                                               arglist, template,
5637                                               complain,
5638                                               /*require_all_args=*/true,
5639                                               /*use_default_args=*/true);
5640
5641               /* Don't process further if one of the levels fails.  */
5642               if (a == error_mark_node)
5643                 {
5644                   /* Restore the ARGLIST to its full size.  */
5645                   TREE_VEC_LENGTH (arglist) = saved_depth;
5646                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5647                 }
5648
5649               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
5650
5651               /* We temporarily reduce the length of the ARGLIST so
5652                  that coerce_template_parms will see only the arguments
5653                  corresponding to the template parameters it is
5654                  examining.  */
5655               TREE_VEC_LENGTH (arglist)--;
5656             }
5657
5658           /* Restore the ARGLIST to its full size.  */
5659           TREE_VEC_LENGTH (arglist) = saved_depth;
5660
5661           arglist = bound_args;
5662         }
5663       else
5664         arglist
5665           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
5666                                    INNERMOST_TEMPLATE_ARGS (arglist),
5667                                    template,
5668                                    complain,
5669                                    /*require_all_args=*/true,
5670                                    /*use_default_args=*/true);
5671
5672       if (arglist == error_mark_node)
5673         /* We were unable to bind the arguments.  */
5674         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5675
5676       /* In the scope of a template class, explicit references to the
5677          template class refer to the type of the template, not any
5678          instantiation of it.  For example, in:
5679
5680            template <class T> class C { void f(C<T>); }
5681
5682          the `C<T>' is just the same as `C'.  Outside of the
5683          class, however, such a reference is an instantiation.  */
5684       if (comp_template_args (TYPE_TI_ARGS (template_type),
5685                               arglist))
5686         {
5687           found = template_type;
5688
5689           if (!entering_scope && PRIMARY_TEMPLATE_P (template))
5690             {
5691               tree ctx;
5692
5693               for (ctx = current_class_type;
5694                    ctx && TREE_CODE (ctx) != NAMESPACE_DECL;
5695                    ctx = (TYPE_P (ctx)
5696                           ? TYPE_CONTEXT (ctx)
5697                           : DECL_CONTEXT (ctx)))
5698                 if (TYPE_P (ctx) && same_type_p (ctx, template_type))
5699                   goto found_ctx;
5700
5701               /* We're not in the scope of the class, so the
5702                  TEMPLATE_TYPE is not the type we want after all.  */
5703               found = NULL_TREE;
5704             found_ctx:;
5705             }
5706         }
5707       if (found)
5708         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5709
5710       /* If we already have this specialization, return it.  */
5711       found = retrieve_specialization (template, arglist,
5712                                        /*class_specializations_p=*/false);
5713       if (found)
5714         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5715
5716       /* This type is a "partial instantiation" if any of the template
5717          arguments still involve template parameters.  Note that we set
5718          IS_PARTIAL_INSTANTIATION for partial specializations as
5719          well.  */
5720       is_partial_instantiation = uses_template_parms (arglist);
5721
5722       /* If the deduced arguments are invalid, then the binding
5723          failed.  */
5724       if (!is_partial_instantiation
5725           && check_instantiated_args (template,
5726                                       INNERMOST_TEMPLATE_ARGS (arglist),
5727                                       complain))
5728         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5729
5730       if (!is_partial_instantiation
5731           && !PRIMARY_TEMPLATE_P (template)
5732           && TREE_CODE (CP_DECL_CONTEXT (template)) == NAMESPACE_DECL)
5733         {
5734           found = xref_tag_from_type (TREE_TYPE (template),
5735                                       DECL_NAME (template),
5736                                       /*tag_scope=*/ts_global);
5737           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5738         }
5739
5740       context = tsubst (DECL_CONTEXT (template), arglist,
5741                         complain, in_decl);
5742       if (!context)
5743         context = global_namespace;
5744
5745       /* Create the type.  */
5746       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
5747         {
5748           if (!is_partial_instantiation)
5749             {
5750               set_current_access_from_decl (TYPE_NAME (template_type));
5751               t = start_enum (TYPE_IDENTIFIER (template_type));
5752             }
5753           else
5754             /* We don't want to call start_enum for this type, since
5755                the values for the enumeration constants may involve
5756                template parameters.  And, no one should be interested
5757                in the enumeration constants for such a type.  */
5758             t = make_node (ENUMERAL_TYPE);
5759         }
5760       else
5761         {
5762           t = make_aggr_type (TREE_CODE (template_type));
5763           CLASSTYPE_DECLARED_CLASS (t)
5764             = CLASSTYPE_DECLARED_CLASS (template_type);
5765           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
5766           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
5767
5768           /* A local class.  Make sure the decl gets registered properly.  */
5769           if (context == current_function_decl)
5770             pushtag (DECL_NAME (template), t, /*tag_scope=*/ts_current);
5771
5772           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
5773             /* This instantiation is another name for the primary
5774                template type. Set the TYPE_CANONICAL field
5775                appropriately. */
5776             TYPE_CANONICAL (t) = template_type;
5777           else if (any_template_arguments_need_structural_equality_p (arglist))
5778             /* Some of the template arguments require structural
5779                equality testing, so this template class requires
5780                structural equality testing. */
5781             SET_TYPE_STRUCTURAL_EQUALITY (t);
5782         }
5783
5784       /* If we called start_enum or pushtag above, this information
5785          will already be set up.  */
5786       if (!TYPE_NAME (t))
5787         {
5788           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
5789
5790           type_decl = create_implicit_typedef (DECL_NAME (template), t);
5791           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
5792           TYPE_STUB_DECL (t) = type_decl;
5793           DECL_SOURCE_LOCATION (type_decl)
5794             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
5795         }
5796       else
5797         type_decl = TYPE_NAME (t);
5798
5799       TREE_PRIVATE (type_decl)
5800         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
5801       TREE_PROTECTED (type_decl)
5802         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
5803       DECL_IN_SYSTEM_HEADER (type_decl)
5804         = DECL_IN_SYSTEM_HEADER (template);
5805       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
5806         {
5807           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
5808           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
5809         }
5810
5811       /* Set up the template information.  We have to figure out which
5812          template is the immediate parent if this is a full
5813          instantiation.  */
5814       if (parm_depth == 1 || is_partial_instantiation
5815           || !PRIMARY_TEMPLATE_P (template))
5816         /* This case is easy; there are no member templates involved.  */
5817         found = template;
5818       else
5819         {
5820           /* This is a full instantiation of a member template.  Look
5821              for a partial instantiation of which this is an instance.  */
5822
5823           for (found = DECL_TEMPLATE_INSTANTIATIONS (template);
5824                found; found = TREE_CHAIN (found))
5825             {
5826               int success;
5827               tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
5828
5829               /* We only want partial instantiations, here, not
5830                  specializations or full instantiations.  */
5831               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
5832                   || !uses_template_parms (TREE_VALUE (found)))
5833                 continue;
5834
5835               /* Temporarily reduce by one the number of levels in the
5836                  ARGLIST and in FOUND so as to avoid comparing the
5837                  last set of arguments.  */
5838               TREE_VEC_LENGTH (arglist)--;
5839               TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
5840
5841               /* See if the arguments match.  If they do, then TMPL is
5842                  the partial instantiation we want.  */
5843               success = comp_template_args (TREE_PURPOSE (found), arglist);
5844
5845               /* Restore the argument vectors to their full size.  */
5846               TREE_VEC_LENGTH (arglist)++;
5847               TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
5848
5849               if (success)
5850                 {
5851                   found = tmpl;
5852                   break;
5853                 }
5854             }
5855
5856           if (!found)
5857             {
5858               /* There was no partial instantiation. This happens
5859                  where C<T> is a member template of A<T> and it's used
5860                  in something like
5861
5862                   template <typename T> struct B { A<T>::C<int> m; };
5863                   B<float>;
5864
5865                  Create the partial instantiation.
5866                */
5867               TREE_VEC_LENGTH (arglist)--;
5868               found = tsubst (template, arglist, complain, NULL_TREE);
5869               TREE_VEC_LENGTH (arglist)++;
5870             }
5871         }
5872
5873       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
5874       DECL_TEMPLATE_INSTANTIATIONS (template)
5875         = tree_cons (arglist, t,
5876                      DECL_TEMPLATE_INSTANTIATIONS (template));
5877
5878       if (TREE_CODE (t) == ENUMERAL_TYPE
5879           && !is_partial_instantiation)
5880         /* Now that the type has been registered on the instantiations
5881            list, we set up the enumerators.  Because the enumeration
5882            constants may involve the enumeration type itself, we make
5883            sure to register the type first, and then create the
5884            constants.  That way, doing tsubst_expr for the enumeration
5885            constants won't result in recursive calls here; we'll find
5886            the instantiation and exit above.  */
5887         tsubst_enum (template_type, t, arglist);
5888
5889       if (is_partial_instantiation)
5890         /* If the type makes use of template parameters, the
5891            code that generates debugging information will crash.  */
5892         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
5893
5894       /* Possibly limit visibility based on template args.  */
5895       TREE_PUBLIC (type_decl) = 1;
5896       determine_visibility (type_decl);
5897
5898       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
5899     }
5900   timevar_pop (TV_NAME_LOOKUP);
5901 }
5902 \f
5903 struct pair_fn_data
5904 {
5905   tree_fn_t fn;
5906   void *data;
5907   /* True when we should also visit template parameters that occur in
5908      non-deduced contexts.  */
5909   bool include_nondeduced_p;
5910   struct pointer_set_t *visited;
5911 };
5912
5913 /* Called from for_each_template_parm via walk_tree.  */
5914
5915 static tree
5916 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
5917 {
5918   tree t = *tp;
5919   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
5920   tree_fn_t fn = pfd->fn;
5921   void *data = pfd->data;
5922
5923   if (TYPE_P (t)
5924       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
5925       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
5926                                  pfd->include_nondeduced_p))
5927     return error_mark_node;
5928
5929   switch (TREE_CODE (t))
5930     {
5931     case RECORD_TYPE:
5932       if (TYPE_PTRMEMFUNC_P (t))
5933         break;
5934       /* Fall through.  */
5935
5936     case UNION_TYPE:
5937     case ENUMERAL_TYPE:
5938       if (!TYPE_TEMPLATE_INFO (t))
5939         *walk_subtrees = 0;
5940       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
5941                                        fn, data, pfd->visited, 
5942                                        pfd->include_nondeduced_p))
5943         return error_mark_node;
5944       break;
5945
5946     case INTEGER_TYPE:
5947       if (for_each_template_parm (TYPE_MIN_VALUE (t),
5948                                   fn, data, pfd->visited, 
5949                                   pfd->include_nondeduced_p)
5950           || for_each_template_parm (TYPE_MAX_VALUE (t),
5951                                      fn, data, pfd->visited,
5952                                      pfd->include_nondeduced_p))
5953         return error_mark_node;
5954       break;
5955
5956     case METHOD_TYPE:
5957       /* Since we're not going to walk subtrees, we have to do this
5958          explicitly here.  */
5959       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
5960                                   pfd->visited, pfd->include_nondeduced_p))
5961         return error_mark_node;
5962       /* Fall through.  */
5963
5964     case FUNCTION_TYPE:
5965       /* Check the return type.  */
5966       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
5967                                   pfd->include_nondeduced_p))
5968         return error_mark_node;
5969
5970       /* Check the parameter types.  Since default arguments are not
5971          instantiated until they are needed, the TYPE_ARG_TYPES may
5972          contain expressions that involve template parameters.  But,
5973          no-one should be looking at them yet.  And, once they're
5974          instantiated, they don't contain template parameters, so
5975          there's no point in looking at them then, either.  */
5976       {
5977         tree parm;
5978
5979         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
5980           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
5981                                       pfd->visited, pfd->include_nondeduced_p))
5982             return error_mark_node;
5983
5984         /* Since we've already handled the TYPE_ARG_TYPES, we don't
5985            want walk_tree walking into them itself.  */
5986         *walk_subtrees = 0;
5987       }
5988       break;
5989
5990     case TYPEOF_TYPE:
5991       if (pfd->include_nondeduced_p
5992           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
5993                                      pfd->visited, 
5994                                      pfd->include_nondeduced_p))
5995         return error_mark_node;
5996       break;
5997
5998     case FUNCTION_DECL:
5999     case VAR_DECL:
6000       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6001           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6002                                      pfd->visited, pfd->include_nondeduced_p))
6003         return error_mark_node;
6004       /* Fall through.  */
6005
6006     case PARM_DECL:
6007     case CONST_DECL:
6008       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6009           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6010                                      pfd->visited, pfd->include_nondeduced_p))
6011         return error_mark_node;
6012       if (DECL_CONTEXT (t)
6013           && pfd->include_nondeduced_p
6014           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6015                                      pfd->visited, pfd->include_nondeduced_p))
6016         return error_mark_node;
6017       break;
6018
6019     case BOUND_TEMPLATE_TEMPLATE_PARM:
6020       /* Record template parameters such as `T' inside `TT<T>'.  */
6021       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6022                                   pfd->include_nondeduced_p))
6023         return error_mark_node;
6024       /* Fall through.  */
6025
6026     case TEMPLATE_TEMPLATE_PARM:
6027     case TEMPLATE_TYPE_PARM:
6028     case TEMPLATE_PARM_INDEX:
6029       if (fn && (*fn)(t, data))
6030         return error_mark_node;
6031       else if (!fn)
6032         return error_mark_node;
6033       break;
6034
6035     case TEMPLATE_DECL:
6036       /* A template template parameter is encountered.  */
6037       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6038           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6039                                      pfd->include_nondeduced_p))
6040         return error_mark_node;
6041
6042       /* Already substituted template template parameter */
6043       *walk_subtrees = 0;
6044       break;
6045
6046     case TYPENAME_TYPE:
6047       if (!fn
6048           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6049                                      data, pfd->visited, 
6050                                      pfd->include_nondeduced_p))
6051         return error_mark_node;
6052       break;
6053
6054     case CONSTRUCTOR:
6055       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6056           && pfd->include_nondeduced_p
6057           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6058                                      (TREE_TYPE (t)), fn, data,
6059                                      pfd->visited, pfd->include_nondeduced_p))
6060         return error_mark_node;
6061       break;
6062
6063     case INDIRECT_REF:
6064     case COMPONENT_REF:
6065       /* If there's no type, then this thing must be some expression
6066          involving template parameters.  */
6067       if (!fn && !TREE_TYPE (t))
6068         return error_mark_node;
6069       break;
6070
6071     case MODOP_EXPR:
6072     case CAST_EXPR:
6073     case REINTERPRET_CAST_EXPR:
6074     case CONST_CAST_EXPR:
6075     case STATIC_CAST_EXPR:
6076     case DYNAMIC_CAST_EXPR:
6077     case ARROW_EXPR:
6078     case DOTSTAR_EXPR:
6079     case TYPEID_EXPR:
6080     case PSEUDO_DTOR_EXPR:
6081       if (!fn)
6082         return error_mark_node;
6083       break;
6084
6085     default:
6086       break;
6087     }
6088
6089   /* We didn't find any template parameters we liked.  */
6090   return NULL_TREE;
6091 }
6092
6093 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6094    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6095    call FN with the parameter and the DATA.
6096    If FN returns nonzero, the iteration is terminated, and
6097    for_each_template_parm returns 1.  Otherwise, the iteration
6098    continues.  If FN never returns a nonzero value, the value
6099    returned by for_each_template_parm is 0.  If FN is NULL, it is
6100    considered to be the function which always returns 1.
6101
6102    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6103    parameters that occur in non-deduced contexts.  When false, only
6104    visits those template parameters that can be deduced.  */
6105
6106 static int
6107 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6108                         struct pointer_set_t *visited,
6109                         bool include_nondeduced_p)
6110 {
6111   struct pair_fn_data pfd;
6112   int result;
6113
6114   /* Set up.  */
6115   pfd.fn = fn;
6116   pfd.data = data;
6117   pfd.include_nondeduced_p = include_nondeduced_p;
6118
6119   /* Walk the tree.  (Conceptually, we would like to walk without
6120      duplicates, but for_each_template_parm_r recursively calls
6121      for_each_template_parm, so we would need to reorganize a fair
6122      bit to use walk_tree_without_duplicates, so we keep our own
6123      visited list.)  */
6124   if (visited)
6125     pfd.visited = visited;
6126   else
6127     pfd.visited = pointer_set_create ();
6128   result = cp_walk_tree (&t,
6129                          for_each_template_parm_r,
6130                          &pfd,
6131                          pfd.visited) != NULL_TREE;
6132
6133   /* Clean up.  */
6134   if (!visited)
6135     {
6136       pointer_set_destroy (pfd.visited);
6137       pfd.visited = 0;
6138     }
6139
6140   return result;
6141 }
6142
6143 /* Returns true if T depends on any template parameter.  */
6144
6145 int
6146 uses_template_parms (tree t)
6147 {
6148   bool dependent_p;
6149   int saved_processing_template_decl;
6150
6151   saved_processing_template_decl = processing_template_decl;
6152   if (!saved_processing_template_decl)
6153     processing_template_decl = 1;
6154   if (TYPE_P (t))
6155     dependent_p = dependent_type_p (t);
6156   else if (TREE_CODE (t) == TREE_VEC)
6157     dependent_p = any_dependent_template_arguments_p (t);
6158   else if (TREE_CODE (t) == TREE_LIST)
6159     dependent_p = (uses_template_parms (TREE_VALUE (t))
6160                    || uses_template_parms (TREE_CHAIN (t)));
6161   else if (TREE_CODE (t) == TYPE_DECL)
6162     dependent_p = dependent_type_p (TREE_TYPE (t));
6163   else if (DECL_P (t)
6164            || EXPR_P (t)
6165            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6166            || TREE_CODE (t) == OVERLOAD
6167            || TREE_CODE (t) == BASELINK
6168            || TREE_CODE (t) == IDENTIFIER_NODE
6169            || TREE_CODE (t) == TRAIT_EXPR
6170            || CONSTANT_CLASS_P (t))
6171     dependent_p = (type_dependent_expression_p (t)
6172                    || value_dependent_expression_p (t));
6173   else
6174     {
6175       gcc_assert (t == error_mark_node);
6176       dependent_p = false;
6177     }
6178
6179   processing_template_decl = saved_processing_template_decl;
6180
6181   return dependent_p;
6182 }
6183
6184 /* Returns true if T depends on any template parameter with level LEVEL.  */
6185
6186 int
6187 uses_template_parms_level (tree t, int level)
6188 {
6189   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6190                                  /*include_nondeduced_p=*/true);
6191 }
6192
6193 static int tinst_depth;
6194 extern int max_tinst_depth;
6195 #ifdef GATHER_STATISTICS
6196 int depth_reached;
6197 #endif
6198 static int tinst_level_tick;
6199 static int last_template_error_tick;
6200
6201 /* We're starting to instantiate D; record the template instantiation context
6202    for diagnostics and to restore it later.  */
6203
6204 static int
6205 push_tinst_level (tree d)
6206 {
6207   struct tinst_level *new;
6208
6209   if (tinst_depth >= max_tinst_depth)
6210     {
6211       /* If the instantiation in question still has unbound template parms,
6212          we don't really care if we can't instantiate it, so just return.
6213          This happens with base instantiation for implicit `typename'.  */
6214       if (uses_template_parms (d))
6215         return 0;
6216
6217       last_template_error_tick = tinst_level_tick;
6218       error ("template instantiation depth exceeds maximum of %d (use "
6219              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6220              max_tinst_depth, d);
6221
6222       print_instantiation_context ();
6223
6224       return 0;
6225     }
6226
6227   new = GGC_NEW (struct tinst_level);
6228   new->decl = d;
6229   new->locus = input_location;
6230   new->in_system_header_p = in_system_header;
6231   new->next = current_tinst_level;
6232   current_tinst_level = new;
6233
6234   ++tinst_depth;
6235 #ifdef GATHER_STATISTICS
6236   if (tinst_depth > depth_reached)
6237     depth_reached = tinst_depth;
6238 #endif
6239
6240   ++tinst_level_tick;
6241   return 1;
6242 }
6243
6244 /* We're done instantiating this template; return to the instantiation
6245    context.  */
6246
6247 static void
6248 pop_tinst_level (void)
6249 {
6250   /* Restore the filename and line number stashed away when we started
6251      this instantiation.  */
6252   input_location = current_tinst_level->locus;
6253   in_system_header = current_tinst_level->in_system_header_p;
6254   current_tinst_level = current_tinst_level->next;
6255   --tinst_depth;
6256   ++tinst_level_tick;
6257 }
6258
6259 /* We're instantiating a deferred template; restore the template
6260    instantiation context in which the instantiation was requested, which
6261    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6262
6263 static tree
6264 reopen_tinst_level (struct tinst_level *level)
6265 {
6266   struct tinst_level *t;
6267
6268   tinst_depth = 0;
6269   for (t = level; t; t = t->next)
6270     ++tinst_depth;
6271
6272   current_tinst_level = level;
6273   pop_tinst_level ();
6274   return level->decl;
6275 }
6276
6277 /* Returns the TINST_LEVEL which gives the original instantiation
6278    context.  */
6279
6280 struct tinst_level *
6281 outermost_tinst_level (void)
6282 {
6283   struct tinst_level *level = current_tinst_level;
6284   if (level)
6285     while (level->next)
6286       level = level->next;
6287   return level;
6288 }
6289
6290 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6291    vector of template arguments, as for tsubst.
6292
6293    Returns an appropriate tsubst'd friend declaration.  */
6294
6295 static tree
6296 tsubst_friend_function (tree decl, tree args)
6297 {
6298   tree new_friend;
6299
6300   if (TREE_CODE (decl) == FUNCTION_DECL
6301       && DECL_TEMPLATE_INSTANTIATION (decl)
6302       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6303     /* This was a friend declared with an explicit template
6304        argument list, e.g.:
6305
6306        friend void f<>(T);
6307
6308        to indicate that f was a template instantiation, not a new
6309        function declaration.  Now, we have to figure out what
6310        instantiation of what template.  */
6311     {
6312       tree template_id, arglist, fns;
6313       tree new_args;
6314       tree tmpl;
6315       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6316
6317       /* Friend functions are looked up in the containing namespace scope.
6318          We must enter that scope, to avoid finding member functions of the
6319          current cless with same name.  */
6320       push_nested_namespace (ns);
6321       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6322                          tf_warning_or_error, NULL_TREE,
6323                          /*integral_constant_expression_p=*/false);
6324       pop_nested_namespace (ns);
6325       arglist = tsubst (DECL_TI_ARGS (decl), args,
6326                         tf_warning_or_error, NULL_TREE);
6327       template_id = lookup_template_function (fns, arglist);
6328
6329       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6330       tmpl = determine_specialization (template_id, new_friend,
6331                                        &new_args,
6332                                        /*need_member_template=*/0,
6333                                        TREE_VEC_LENGTH (args),
6334                                        tsk_none);
6335       return instantiate_template (tmpl, new_args, tf_error);
6336     }
6337
6338   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6339
6340   /* The NEW_FRIEND will look like an instantiation, to the
6341      compiler, but is not an instantiation from the point of view of
6342      the language.  For example, we might have had:
6343
6344      template <class T> struct S {
6345        template <class U> friend void f(T, U);
6346      };
6347
6348      Then, in S<int>, template <class U> void f(int, U) is not an
6349      instantiation of anything.  */
6350   if (new_friend == error_mark_node)
6351     return error_mark_node;
6352
6353   DECL_USE_TEMPLATE (new_friend) = 0;
6354   if (TREE_CODE (decl) == TEMPLATE_DECL)
6355     {
6356       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6357       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6358         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6359     }
6360
6361   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6362      is not a template instantiation and should not be mangled like
6363      one.  Therefore, we forget the mangling here; we'll recompute it
6364      later if we need it.  */
6365   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6366     {
6367       SET_DECL_RTL (new_friend, NULL_RTX);
6368       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6369     }
6370
6371   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6372     {
6373       tree old_decl;
6374       tree new_friend_template_info;
6375       tree new_friend_result_template_info;
6376       tree ns;
6377       int  new_friend_is_defn;
6378
6379       /* We must save some information from NEW_FRIEND before calling
6380          duplicate decls since that function will free NEW_FRIEND if
6381          possible.  */
6382       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6383       new_friend_is_defn =
6384             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6385                            (template_for_substitution (new_friend)))
6386              != NULL_TREE);
6387       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6388         {
6389           /* This declaration is a `primary' template.  */
6390           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6391
6392           new_friend_result_template_info
6393             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6394         }
6395       else
6396         new_friend_result_template_info = NULL_TREE;
6397
6398       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6399       if (new_friend_is_defn)
6400         DECL_INITIAL (new_friend) = error_mark_node;
6401
6402       /* Inside pushdecl_namespace_level, we will push into the
6403          current namespace. However, the friend function should go
6404          into the namespace of the template.  */
6405       ns = decl_namespace_context (new_friend);
6406       push_nested_namespace (ns);
6407       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6408       pop_nested_namespace (ns);
6409
6410       if (old_decl == error_mark_node)
6411         return error_mark_node;
6412
6413       if (old_decl != new_friend)
6414         {
6415           /* This new friend declaration matched an existing
6416              declaration.  For example, given:
6417
6418                template <class T> void f(T);
6419                template <class U> class C {
6420                  template <class T> friend void f(T) {}
6421                };
6422
6423              the friend declaration actually provides the definition
6424              of `f', once C has been instantiated for some type.  So,
6425              old_decl will be the out-of-class template declaration,
6426              while new_friend is the in-class definition.
6427
6428              But, if `f' was called before this point, the
6429              instantiation of `f' will have DECL_TI_ARGS corresponding
6430              to `T' but not to `U', references to which might appear
6431              in the definition of `f'.  Previously, the most general
6432              template for an instantiation of `f' was the out-of-class
6433              version; now it is the in-class version.  Therefore, we
6434              run through all specialization of `f', adding to their
6435              DECL_TI_ARGS appropriately.  In particular, they need a
6436              new set of outer arguments, corresponding to the
6437              arguments for this class instantiation.
6438
6439              The same situation can arise with something like this:
6440
6441                friend void f(int);
6442                template <class T> class C {
6443                  friend void f(T) {}
6444                };
6445
6446              when `C<int>' is instantiated.  Now, `f(int)' is defined
6447              in the class.  */
6448
6449           if (!new_friend_is_defn)
6450             /* On the other hand, if the in-class declaration does
6451                *not* provide a definition, then we don't want to alter
6452                existing definitions.  We can just leave everything
6453                alone.  */
6454             ;
6455           else
6456             {
6457               /* Overwrite whatever template info was there before, if
6458                  any, with the new template information pertaining to
6459                  the declaration.  */
6460               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
6461
6462               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
6463                 reregister_specialization (new_friend,
6464                                            most_general_template (old_decl),
6465                                            old_decl);
6466               else
6467                 {
6468                   tree t;
6469                   tree new_friend_args;
6470
6471                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
6472                     = new_friend_result_template_info;
6473
6474                   new_friend_args = TI_ARGS (new_friend_template_info);
6475                   for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl);
6476                        t != NULL_TREE;
6477                        t = TREE_CHAIN (t))
6478                     {
6479                       tree spec = TREE_VALUE (t);
6480
6481                       DECL_TI_ARGS (spec)
6482                         = add_outermost_template_args (new_friend_args,
6483                                                        DECL_TI_ARGS (spec));
6484                     }
6485
6486                   /* Now, since specializations are always supposed to
6487                      hang off of the most general template, we must move
6488                      them.  */
6489                   t = most_general_template (old_decl);
6490                   if (t != old_decl)
6491                     {
6492                       DECL_TEMPLATE_SPECIALIZATIONS (t)
6493                         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
6494                                    DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
6495                       DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
6496                     }
6497                 }
6498             }
6499
6500           /* The information from NEW_FRIEND has been merged into OLD_DECL
6501              by duplicate_decls.  */
6502           new_friend = old_decl;
6503         }
6504     }
6505   else
6506     {
6507       tree context = DECL_CONTEXT (new_friend);
6508       bool dependent_p;
6509
6510       /* In the code
6511            template <class T> class C {
6512              template <class U> friend void C1<U>::f (); // case 1
6513              friend void C2<T>::f ();                    // case 2
6514            };
6515          we only need to make sure CONTEXT is a complete type for
6516          case 2.  To distinguish between the two cases, we note that
6517          CONTEXT of case 1 remains dependent type after tsubst while
6518          this isn't true for case 2.  */
6519       ++processing_template_decl;
6520       dependent_p = dependent_type_p (context);
6521       --processing_template_decl;
6522
6523       if (!dependent_p
6524           && !complete_type_or_else (context, NULL_TREE))
6525         return error_mark_node;
6526
6527       if (COMPLETE_TYPE_P (context))
6528         {
6529           /* Check to see that the declaration is really present, and,
6530              possibly obtain an improved declaration.  */
6531           tree fn = check_classfn (context,
6532                                    new_friend, NULL_TREE);
6533
6534           if (fn)
6535             new_friend = fn;
6536         }
6537     }
6538
6539   return new_friend;
6540 }
6541
6542 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
6543    template arguments, as for tsubst.
6544
6545    Returns an appropriate tsubst'd friend type or error_mark_node on
6546    failure.  */
6547
6548 static tree
6549 tsubst_friend_class (tree friend_tmpl, tree args)
6550 {
6551   tree friend_type;
6552   tree tmpl;
6553   tree context;
6554
6555   context = DECL_CONTEXT (friend_tmpl);
6556
6557   if (context)
6558     {
6559       if (TREE_CODE (context) == NAMESPACE_DECL)
6560         push_nested_namespace (context);
6561       else
6562         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
6563     }
6564
6565   /* Look for a class template declaration.  We look for hidden names
6566      because two friend declarations of the same template are the
6567      same.  For example, in:
6568
6569        struct A { 
6570          template <typename> friend class F;
6571        };
6572        template <typename> struct B { 
6573          template <typename> friend class F;
6574        };
6575
6576      both F templates are the same.  */
6577   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
6578                            /*block_p=*/true, 0, 
6579                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
6580
6581   /* But, if we don't find one, it might be because we're in a
6582      situation like this:
6583
6584        template <class T>
6585        struct S {
6586          template <class U>
6587          friend struct S;
6588        };
6589
6590      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
6591      for `S<int>', not the TEMPLATE_DECL.  */
6592   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
6593     {
6594       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
6595       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
6596     }
6597
6598   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
6599     {
6600       /* The friend template has already been declared.  Just
6601          check to see that the declarations match, and install any new
6602          default parameters.  We must tsubst the default parameters,
6603          of course.  We only need the innermost template parameters
6604          because that is all that redeclare_class_template will look
6605          at.  */
6606       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
6607           > TMPL_ARGS_DEPTH (args))
6608         {
6609           tree parms;
6610           location_t saved_input_location;
6611           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
6612                                          args, tf_warning_or_error);
6613
6614           saved_input_location = input_location;
6615           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
6616           redeclare_class_template (TREE_TYPE (tmpl), parms);
6617           input_location = saved_input_location;
6618           
6619         }
6620
6621       friend_type = TREE_TYPE (tmpl);
6622     }
6623   else
6624     {
6625       /* The friend template has not already been declared.  In this
6626          case, the instantiation of the template class will cause the
6627          injection of this template into the global scope.  */
6628       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
6629       if (tmpl == error_mark_node)
6630         return error_mark_node;
6631
6632       /* The new TMPL is not an instantiation of anything, so we
6633          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
6634          the new type because that is supposed to be the corresponding
6635          template decl, i.e., TMPL.  */
6636       DECL_USE_TEMPLATE (tmpl) = 0;
6637       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
6638       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
6639       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
6640         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
6641
6642       /* Inject this template into the global scope.  */
6643       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
6644     }
6645
6646   if (context)
6647     {
6648       if (TREE_CODE (context) == NAMESPACE_DECL)
6649         pop_nested_namespace (context);
6650       else
6651         pop_nested_class ();
6652     }
6653
6654   return friend_type;
6655 }
6656
6657 /* Returns zero if TYPE cannot be completed later due to circularity.
6658    Otherwise returns one.  */
6659
6660 static int
6661 can_complete_type_without_circularity (tree type)
6662 {
6663   if (type == NULL_TREE || type == error_mark_node)
6664     return 0;
6665   else if (COMPLETE_TYPE_P (type))
6666     return 1;
6667   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
6668     return can_complete_type_without_circularity (TREE_TYPE (type));
6669   else if (CLASS_TYPE_P (type)
6670            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
6671     return 0;
6672   else
6673     return 1;
6674 }
6675
6676 /* Apply any attributes which had to be deferred until instantiation
6677    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
6678    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
6679
6680 static void
6681 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
6682                                 tree args, tsubst_flags_t complain, tree in_decl)
6683 {
6684   tree last_dep = NULL_TREE;
6685   tree t;
6686   tree *p;
6687
6688   for (t = attributes; t; t = TREE_CHAIN (t))
6689     if (ATTR_IS_DEPENDENT (t))
6690       {
6691         last_dep = t;
6692         attributes = copy_list (attributes);
6693         break;
6694       }
6695
6696   if (DECL_P (*decl_p))
6697     {
6698       if (TREE_TYPE (*decl_p) == error_mark_node)
6699         return;
6700       p = &DECL_ATTRIBUTES (*decl_p);
6701     }
6702   else
6703     p = &TYPE_ATTRIBUTES (*decl_p);
6704
6705   if (last_dep)
6706     {
6707       tree late_attrs = NULL_TREE;
6708       tree *q = &late_attrs;
6709
6710       for (*p = attributes; *p; )
6711         {
6712           t = *p;
6713           if (ATTR_IS_DEPENDENT (t))
6714             {
6715               *p = TREE_CHAIN (t);
6716               TREE_CHAIN (t) = NULL_TREE;
6717               TREE_VALUE (t)
6718                 = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
6719                                /*integral_constant_expression_p=*/false);
6720               *q = t;
6721               q = &TREE_CHAIN (t);
6722             }
6723           else
6724             p = &TREE_CHAIN (t);
6725         }
6726
6727       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
6728     }
6729 }
6730
6731 tree
6732 instantiate_class_template (tree type)
6733 {
6734   tree template, args, pattern, t, member;
6735   tree typedecl;
6736   tree pbinfo;
6737   tree base_list;
6738
6739   if (type == error_mark_node)
6740     return error_mark_node;
6741
6742   if (TYPE_BEING_DEFINED (type)
6743       || COMPLETE_TYPE_P (type)
6744       || dependent_type_p (type))
6745     return type;
6746
6747   /* Figure out which template is being instantiated.  */
6748   template = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
6749   gcc_assert (TREE_CODE (template) == TEMPLATE_DECL);
6750
6751   /* Determine what specialization of the original template to
6752      instantiate.  */
6753   t = most_specialized_class (type, template);
6754   if (t == error_mark_node)
6755     {
6756       TYPE_BEING_DEFINED (type) = 1;
6757       return error_mark_node;
6758     }
6759   else if (t)
6760     {
6761       /* This TYPE is actually an instantiation of a partial
6762          specialization.  We replace the innermost set of ARGS with
6763          the arguments appropriate for substitution.  For example,
6764          given:
6765
6766            template <class T> struct S {};
6767            template <class T> struct S<T*> {};
6768
6769          and supposing that we are instantiating S<int*>, ARGS will
6770          presently be {int*} -- but we need {int}.  */
6771       pattern = TREE_TYPE (t);
6772       args = TREE_PURPOSE (t);
6773     }
6774   else
6775     {
6776       pattern = TREE_TYPE (template);
6777       args = CLASSTYPE_TI_ARGS (type);
6778     }
6779
6780   /* If the template we're instantiating is incomplete, then clearly
6781      there's nothing we can do.  */
6782   if (!COMPLETE_TYPE_P (pattern))
6783     return type;
6784
6785   /* If we've recursively instantiated too many templates, stop.  */
6786   if (! push_tinst_level (type))
6787     return type;
6788
6789   /* Now we're really doing the instantiation.  Mark the type as in
6790      the process of being defined.  */
6791   TYPE_BEING_DEFINED (type) = 1;
6792
6793   /* We may be in the middle of deferred access check.  Disable
6794      it now.  */
6795   push_deferring_access_checks (dk_no_deferred);
6796
6797   push_to_top_level ();
6798
6799   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
6800
6801   /* Set the input location to the template definition. This is needed
6802      if tsubsting causes an error.  */
6803   typedecl = TYPE_MAIN_DECL (type);
6804   input_location = DECL_SOURCE_LOCATION (typedecl);
6805   in_system_header = DECL_IN_SYSTEM_HEADER (typedecl);
6806
6807   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
6808   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
6809   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
6810   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
6811   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
6812   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
6813   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
6814   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
6815   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
6816   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
6817   TYPE_PACKED (type) = TYPE_PACKED (pattern);
6818   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
6819   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
6820   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
6821   if (ANON_AGGR_TYPE_P (pattern))
6822     SET_ANON_AGGR_TYPE_P (type);
6823   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
6824     {
6825       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
6826       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
6827     }
6828
6829   pbinfo = TYPE_BINFO (pattern);
6830
6831   /* We should never instantiate a nested class before its enclosing
6832      class; we need to look up the nested class by name before we can
6833      instantiate it, and that lookup should instantiate the enclosing
6834      class.  */
6835   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
6836               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
6837               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
6838
6839   base_list = NULL_TREE;
6840   if (BINFO_N_BASE_BINFOS (pbinfo))
6841     {
6842       tree pbase_binfo;
6843       tree context = TYPE_CONTEXT (type);
6844       tree pushed_scope;
6845       int i;
6846
6847       /* We must enter the scope containing the type, as that is where
6848          the accessibility of types named in dependent bases are
6849          looked up from.  */
6850       pushed_scope = push_scope (context ? context : global_namespace);
6851
6852       /* Substitute into each of the bases to determine the actual
6853          basetypes.  */
6854       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
6855         {
6856           tree base;
6857           tree access = BINFO_BASE_ACCESS (pbinfo, i);
6858           tree expanded_bases = NULL_TREE;
6859           int idx, len = 1;
6860
6861           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
6862             {
6863               expanded_bases = 
6864                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
6865                                        args, tf_error, NULL_TREE);
6866               if (expanded_bases == error_mark_node)
6867                 continue;
6868
6869               len = TREE_VEC_LENGTH (expanded_bases);
6870             }
6871
6872           for (idx = 0; idx < len; idx++)
6873             {
6874               if (expanded_bases)
6875                 /* Extract the already-expanded base class.  */
6876                 base = TREE_VEC_ELT (expanded_bases, idx);
6877               else
6878                 /* Substitute to figure out the base class.  */
6879                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
6880                                NULL_TREE);
6881
6882               if (base == error_mark_node)
6883                 continue;
6884
6885               base_list = tree_cons (access, base, base_list);
6886               if (BINFO_VIRTUAL_P (pbase_binfo))
6887                 TREE_TYPE (base_list) = integer_type_node;
6888             }
6889         }
6890
6891       /* The list is now in reverse order; correct that.  */
6892       base_list = nreverse (base_list);
6893
6894       if (pushed_scope)
6895         pop_scope (pushed_scope);
6896     }
6897   /* Now call xref_basetypes to set up all the base-class
6898      information.  */
6899   xref_basetypes (type, base_list);
6900
6901   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
6902                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
6903                                   args, tf_error, NULL_TREE);
6904
6905   /* Now that our base classes are set up, enter the scope of the
6906      class, so that name lookups into base classes, etc. will work
6907      correctly.  This is precisely analogous to what we do in
6908      begin_class_definition when defining an ordinary non-template
6909      class, except we also need to push the enclosing classes.  */
6910   push_nested_class (type);
6911
6912   /* Now members are processed in the order of declaration.  */
6913   for (member = CLASSTYPE_DECL_LIST (pattern);
6914        member; member = TREE_CHAIN (member))
6915     {
6916       tree t = TREE_VALUE (member);
6917
6918       if (TREE_PURPOSE (member))
6919         {
6920           if (TYPE_P (t))
6921             {
6922               /* Build new CLASSTYPE_NESTED_UTDS.  */
6923
6924               tree newtag;
6925               bool class_template_p;
6926
6927               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
6928                                   && TYPE_LANG_SPECIFIC (t)
6929                                   && CLASSTYPE_IS_TEMPLATE (t));
6930               /* If the member is a class template, then -- even after
6931                  substitution -- there may be dependent types in the
6932                  template argument list for the class.  We increment
6933                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
6934                  that function will assume that no types are dependent
6935                  when outside of a template.  */
6936               if (class_template_p)
6937                 ++processing_template_decl;
6938               newtag = tsubst (t, args, tf_error, NULL_TREE);
6939               if (class_template_p)
6940                 --processing_template_decl;
6941               if (newtag == error_mark_node)
6942                 continue;
6943
6944               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
6945                 {
6946                   tree name = TYPE_IDENTIFIER (t);
6947
6948                   if (class_template_p)
6949                     /* Unfortunately, lookup_template_class sets
6950                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
6951                        instantiation (i.e., for the type of a member
6952                        template class nested within a template class.)
6953                        This behavior is required for
6954                        maybe_process_partial_specialization to work
6955                        correctly, but is not accurate in this case;
6956                        the TAG is not an instantiation of anything.
6957                        (The corresponding TEMPLATE_DECL is an
6958                        instantiation, but the TYPE is not.) */
6959                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
6960
6961                   /* Now, we call pushtag to put this NEWTAG into the scope of
6962                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
6963                      pushtag calling push_template_decl.  We don't have to do
6964                      this for enums because it will already have been done in
6965                      tsubst_enum.  */
6966                   if (name)
6967                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
6968                   pushtag (name, newtag, /*tag_scope=*/ts_current);
6969                 }
6970             }
6971           else if (TREE_CODE (t) == FUNCTION_DECL
6972                    || DECL_FUNCTION_TEMPLATE_P (t))
6973             {
6974               /* Build new TYPE_METHODS.  */
6975               tree r;
6976
6977               if (TREE_CODE (t) == TEMPLATE_DECL)
6978                 ++processing_template_decl;
6979               r = tsubst (t, args, tf_error, NULL_TREE);
6980               if (TREE_CODE (t) == TEMPLATE_DECL)
6981                 --processing_template_decl;
6982               set_current_access_from_decl (r);
6983               finish_member_declaration (r);
6984             }
6985           else
6986             {
6987               /* Build new TYPE_FIELDS.  */
6988               if (TREE_CODE (t) == STATIC_ASSERT)
6989                 {
6990                   tree condition = 
6991                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
6992                                  tf_warning_or_error, NULL_TREE,
6993                                  /*integral_constant_expression_p=*/true);
6994                   finish_static_assert (condition,
6995                                         STATIC_ASSERT_MESSAGE (t), 
6996                                         STATIC_ASSERT_SOURCE_LOCATION (t),
6997                                         /*member_p=*/true);
6998                 }
6999               else if (TREE_CODE (t) != CONST_DECL)
7000                 {
7001                   tree r;
7002
7003                   /* The the file and line for this declaration, to
7004                      assist in error message reporting.  Since we
7005                      called push_tinst_level above, we don't need to
7006                      restore these.  */
7007                   input_location = DECL_SOURCE_LOCATION (t);
7008
7009                   if (TREE_CODE (t) == TEMPLATE_DECL)
7010                     ++processing_template_decl;
7011                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7012                   if (TREE_CODE (t) == TEMPLATE_DECL)
7013                     --processing_template_decl;
7014                   if (TREE_CODE (r) == VAR_DECL)
7015                     {
7016                       /* In [temp.inst]:
7017
7018                            [t]he initialization (and any associated
7019                            side-effects) of a static data member does
7020                            not occur unless the static data member is
7021                            itself used in a way that requires the
7022                            definition of the static data member to
7023                            exist.
7024
7025                          Therefore, we do not substitute into the
7026                          initialized for the static data member here.  */
7027                       finish_static_data_member_decl
7028                         (r,
7029                          /*init=*/NULL_TREE,
7030                          /*init_const_expr_p=*/false,
7031                          /*asmspec_tree=*/NULL_TREE,
7032                          /*flags=*/0);
7033                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7034                         check_static_variable_definition (r, TREE_TYPE (r));
7035                     }
7036                   else if (TREE_CODE (r) == FIELD_DECL)
7037                     {
7038                       /* Determine whether R has a valid type and can be
7039                          completed later.  If R is invalid, then it is
7040                          replaced by error_mark_node so that it will not be
7041                          added to TYPE_FIELDS.  */
7042                       tree rtype = TREE_TYPE (r);
7043                       if (can_complete_type_without_circularity (rtype))
7044                         complete_type (rtype);
7045
7046                       if (!COMPLETE_TYPE_P (rtype))
7047                         {
7048                           cxx_incomplete_type_error (r, rtype);
7049                           r = error_mark_node;
7050                         }
7051                     }
7052
7053                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7054                      such a thing will already have been added to the field
7055                      list by tsubst_enum in finish_member_declaration in the
7056                      CLASSTYPE_NESTED_UTDS case above.  */
7057                   if (!(TREE_CODE (r) == TYPE_DECL
7058                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7059                         && DECL_ARTIFICIAL (r)))
7060                     {
7061                       set_current_access_from_decl (r);
7062                       finish_member_declaration (r);
7063                     }
7064                 }
7065             }
7066         }
7067       else
7068         {
7069           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7070             {
7071               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7072
7073               tree friend_type = t;
7074               bool adjust_processing_template_decl = false;
7075
7076               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7077                 {
7078                   /* template <class T> friend class C;  */
7079                   friend_type = tsubst_friend_class (friend_type, args);
7080                   adjust_processing_template_decl = true;
7081                 }
7082               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7083                 {
7084                   /* template <class T> friend class C::D;  */
7085                   friend_type = tsubst (friend_type, args,
7086                                         tf_warning_or_error, NULL_TREE);
7087                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7088                     friend_type = TREE_TYPE (friend_type);
7089                   adjust_processing_template_decl = true;
7090                 }
7091               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7092                 {
7093                   /* This could be either
7094
7095                        friend class T::C;
7096
7097                      when dependent_type_p is false or
7098
7099                        template <class U> friend class T::C;
7100
7101                      otherwise.  */
7102                   friend_type = tsubst (friend_type, args,
7103                                         tf_warning_or_error, NULL_TREE);
7104                   /* Bump processing_template_decl for correct
7105                      dependent_type_p calculation.  */
7106                   ++processing_template_decl;
7107                   if (dependent_type_p (friend_type))
7108                     adjust_processing_template_decl = true;
7109                   --processing_template_decl;
7110                 }
7111               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7112                        && hidden_name_p (TYPE_NAME (friend_type)))
7113                 {
7114                   /* friend class C;
7115
7116                      where C hasn't been declared yet.  Let's lookup name
7117                      from namespace scope directly, bypassing any name that
7118                      come from dependent base class.  */
7119                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7120
7121                   /* The call to xref_tag_from_type does injection for friend
7122                      classes.  */
7123                   push_nested_namespace (ns);
7124                   friend_type =
7125                     xref_tag_from_type (friend_type, NULL_TREE,
7126                                         /*tag_scope=*/ts_current);
7127                   pop_nested_namespace (ns);
7128                 }
7129               else if (uses_template_parms (friend_type))
7130                 /* friend class C<T>;  */
7131                 friend_type = tsubst (friend_type, args,
7132                                       tf_warning_or_error, NULL_TREE);
7133               /* Otherwise it's
7134
7135                    friend class C;
7136
7137                  where C is already declared or
7138
7139                    friend class C<int>;
7140
7141                  We don't have to do anything in these cases.  */
7142
7143               if (adjust_processing_template_decl)
7144                 /* Trick make_friend_class into realizing that the friend
7145                    we're adding is a template, not an ordinary class.  It's
7146                    important that we use make_friend_class since it will
7147                    perform some error-checking and output cross-reference
7148                    information.  */
7149                 ++processing_template_decl;
7150
7151               if (friend_type != error_mark_node)
7152                 make_friend_class (type, friend_type, /*complain=*/false);
7153
7154               if (adjust_processing_template_decl)
7155                 --processing_template_decl;
7156             }
7157           else
7158             {
7159               /* Build new DECL_FRIENDLIST.  */
7160               tree r;
7161
7162               /* The the file and line for this declaration, to
7163                  assist in error message reporting.  Since we
7164                  called push_tinst_level above, we don't need to
7165                  restore these.  */
7166               input_location = DECL_SOURCE_LOCATION (t);
7167
7168               if (TREE_CODE (t) == TEMPLATE_DECL)
7169                 {
7170                   ++processing_template_decl;
7171                   push_deferring_access_checks (dk_no_check);
7172                 }
7173
7174               r = tsubst_friend_function (t, args);
7175               add_friend (type, r, /*complain=*/false);
7176               if (TREE_CODE (t) == TEMPLATE_DECL)
7177                 {
7178                   pop_deferring_access_checks ();
7179                   --processing_template_decl;
7180                 }
7181             }
7182         }
7183     }
7184
7185   /* Set the file and line number information to whatever is given for
7186      the class itself.  This puts error messages involving generated
7187      implicit functions at a predictable point, and the same point
7188      that would be used for non-template classes.  */
7189   input_location = DECL_SOURCE_LOCATION (typedecl);
7190
7191   unreverse_member_declarations (type);
7192   finish_struct_1 (type);
7193   TYPE_BEING_DEFINED (type) = 0;
7194
7195   /* Now that the class is complete, instantiate default arguments for
7196      any member functions.  We don't do this earlier because the
7197      default arguments may reference members of the class.  */
7198   if (!PRIMARY_TEMPLATE_P (template))
7199     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7200       if (TREE_CODE (t) == FUNCTION_DECL
7201           /* Implicitly generated member functions will not have template
7202              information; they are not instantiations, but instead are
7203              created "fresh" for each instantiation.  */
7204           && DECL_TEMPLATE_INFO (t))
7205         tsubst_default_arguments (t);
7206
7207   pop_nested_class ();
7208   pop_from_top_level ();
7209   pop_deferring_access_checks ();
7210   pop_tinst_level ();
7211
7212   /* The vtable for a template class can be emitted in any translation
7213      unit in which the class is instantiated.  When there is no key
7214      method, however, finish_struct_1 will already have added TYPE to
7215      the keyed_classes list.  */
7216   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7217     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7218
7219   return type;
7220 }
7221
7222 static tree
7223 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7224 {
7225   tree r;
7226
7227   if (!t)
7228     r = t;
7229   else if (TYPE_P (t))
7230     r = tsubst (t, args, complain, in_decl);
7231   else
7232     {
7233       r = tsubst_expr (t, args, complain, in_decl,
7234                        /*integral_constant_expression_p=*/true);
7235       r = fold_non_dependent_expr (r);
7236     }
7237   return r;
7238 }
7239
7240 /* Substitute ARGS into T, which is an pack expansion
7241    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7242    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7243    (if only a partial substitution could be performed) or
7244    ERROR_MARK_NODE if there was an error.  */
7245 tree
7246 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7247                        tree in_decl)
7248 {
7249   tree pattern;
7250   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7251   tree first_arg_pack; int i, len = -1;
7252   tree result;
7253   int incomplete = 0;
7254
7255   gcc_assert (PACK_EXPANSION_P (t));
7256   pattern = PACK_EXPANSION_PATTERN (t);
7257
7258   /* Determine the argument packs that will instantiate the parameter
7259      packs used in the expansion expression. While we're at it,
7260      compute the number of arguments to be expanded and make sure it
7261      is consistent.  */
7262   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7263        pack = TREE_CHAIN (pack))
7264     {
7265       tree parm_pack = TREE_VALUE (pack);
7266       tree arg_pack = NULL_TREE;
7267       tree orig_arg = NULL_TREE;
7268
7269       if (TREE_CODE (parm_pack) == PARM_DECL)
7270         arg_pack = retrieve_local_specialization (parm_pack);
7271       else
7272         {
7273           int level, idx, levels;
7274           template_parm_level_and_index (parm_pack, &level, &idx);
7275
7276           levels = TMPL_ARGS_DEPTH (args);
7277           if (level <= levels)
7278             arg_pack = TMPL_ARG (args, level, idx);
7279         }
7280
7281       orig_arg = arg_pack;
7282       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7283         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7284       
7285       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7286         /* This can only happen if we forget to expand an argument
7287            pack somewhere else. Just return an error, silently.  */
7288         {
7289           result = make_tree_vec (1);
7290           TREE_VEC_ELT (result, 0) = error_mark_node;
7291           return result;
7292         }
7293
7294       if (arg_pack
7295           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
7296           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
7297         {
7298           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
7299           tree pattern = PACK_EXPANSION_PATTERN (expansion);
7300           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
7301               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
7302             /* The argument pack that the parameter maps to is just an
7303                expansion of the parameter itself, such as one would
7304                find in the implicit typedef of a class inside the
7305                class itself.  Consider this parameter "unsubstituted",
7306                so that we will maintain the outer pack expansion.  */
7307             arg_pack = NULL_TREE;
7308         }
7309           
7310       if (arg_pack)
7311         {
7312           int my_len = 
7313             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7314
7315           /* It's all-or-nothing with incomplete argument packs.  */
7316           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7317             return error_mark_node;
7318           
7319           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7320             incomplete = 1;
7321
7322           if (len < 0)
7323             {
7324               len = my_len;
7325               first_arg_pack = arg_pack;
7326             }
7327           else if (len != my_len)
7328             {
7329               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
7330                 error ("mismatched argument pack lengths while expanding "
7331                        "%<%T%>",
7332                        pattern);
7333               else
7334                 error ("mismatched argument pack lengths while expanding "
7335                        "%<%E%>",
7336                        pattern);
7337               return error_mark_node;
7338             }
7339
7340           /* Keep track of the parameter packs and their corresponding
7341              argument packs.  */
7342           packs = tree_cons (parm_pack, arg_pack, packs);
7343           TREE_TYPE (packs) = orig_arg;
7344         }
7345       else
7346         /* We can't substitute for this parameter pack.  */
7347         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
7348                                          TREE_VALUE (pack),
7349                                          unsubstituted_packs);
7350     }
7351
7352   /* We cannot expand this expansion expression, because we don't have
7353      all of the argument packs we need. Substitute into the pattern
7354      and return a PACK_EXPANSION_*. The caller will need to deal with
7355      that.  */
7356   if (unsubstituted_packs)
7357     return make_pack_expansion (tsubst (pattern, args, complain, 
7358                                         in_decl));
7359
7360   /* We could not find any argument packs that work.  */
7361   if (len < 0)
7362     return error_mark_node;
7363
7364   /* For each argument in each argument pack, substitute into the
7365      pattern.  */
7366   result = make_tree_vec (len + incomplete);
7367   for (i = 0; i < len + incomplete; ++i)
7368     {
7369       /* For parameter pack, change the substitution of the parameter
7370          pack to the ith argument in its argument pack, then expand
7371          the pattern.  */
7372       for (pack = packs; pack; pack = TREE_CHAIN (pack))
7373         {
7374           tree parm = TREE_PURPOSE (pack);
7375
7376           if (TREE_CODE (parm) == PARM_DECL)
7377             {
7378               /* Select the Ith argument from the pack.  */
7379               tree arg = make_node (ARGUMENT_PACK_SELECT);
7380               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
7381               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
7382               mark_used (parm);
7383               register_local_specialization (arg, parm);
7384             }
7385           else
7386             {
7387               tree value = parm;
7388               int idx, level;
7389               template_parm_level_and_index (parm, &level, &idx);
7390               
7391               if (i < len) 
7392                 {
7393                   /* Select the Ith argument from the pack. */
7394                   value = make_node (ARGUMENT_PACK_SELECT);
7395                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
7396                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
7397                 }
7398
7399               /* Update the corresponding argument.  */
7400               TMPL_ARG (args, level, idx) = value;
7401             }
7402         }
7403
7404       /* Substitute into the PATTERN with the altered arguments.  */
7405       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7406         TREE_VEC_ELT (result, i) = 
7407           tsubst_expr (pattern, args, complain, in_decl,
7408                        /*integral_constant_expression_p=*/false);
7409       else
7410         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
7411
7412       if (i == len)
7413         /* When we have incomplete argument packs, the last "expanded"
7414            result is itself a pack expansion, which allows us
7415            to deduce more arguments.  */
7416         TREE_VEC_ELT (result, i) = 
7417           make_pack_expansion (TREE_VEC_ELT (result, i));
7418
7419       if (TREE_VEC_ELT (result, i) == error_mark_node)
7420         {
7421           result = error_mark_node;
7422           break;
7423         }
7424     }
7425   
7426   /* Update ARGS to restore the substitution from parameter packs to
7427      their argument packs.  */
7428   for (pack = packs; pack; pack = TREE_CHAIN (pack))
7429     {
7430       tree parm = TREE_PURPOSE (pack);
7431
7432       if (TREE_CODE (parm) == PARM_DECL)
7433         register_local_specialization (TREE_TYPE (pack), parm);
7434       else
7435         {
7436           int idx, level;
7437           template_parm_level_and_index (parm, &level, &idx);
7438           
7439           /* Update the corresponding argument.  */
7440           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
7441             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
7442               TREE_TYPE (pack);
7443           else
7444             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
7445         }
7446     }
7447
7448   return result;
7449 }
7450
7451 /* Substitute ARGS into the vector or list of template arguments T.  */
7452
7453 static tree
7454 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7455 {
7456   tree orig_t = t;
7457   int len = TREE_VEC_LENGTH (t);
7458   int need_new = 0, i, expanded_len_adjust = 0, out;
7459   tree *elts = (tree *) alloca (len * sizeof (tree));
7460
7461   for (i = 0; i < len; i++)
7462     {
7463       tree orig_arg = TREE_VEC_ELT (t, i);
7464       tree new_arg;
7465
7466       if (TREE_CODE (orig_arg) == TREE_VEC)
7467         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
7468       else if (PACK_EXPANSION_P (orig_arg))
7469         {
7470           /* Substitute into an expansion expression.  */
7471           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
7472
7473           if (TREE_CODE (new_arg) == TREE_VEC)
7474             /* Add to the expanded length adjustment the number of
7475                expanded arguments. We subtract one from this
7476                measurement, because the argument pack expression
7477                itself is already counted as 1 in
7478                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
7479                the argument pack is empty.  */
7480             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
7481         }
7482       else if (ARGUMENT_PACK_P (orig_arg))
7483         {
7484           /* Substitute into each of the arguments.  */
7485           new_arg = make_node (TREE_CODE (orig_arg));
7486           
7487           SET_ARGUMENT_PACK_ARGS (
7488             new_arg,
7489             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
7490                                   args, complain, in_decl));
7491
7492           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
7493             new_arg = error_mark_node;
7494
7495           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
7496             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
7497                                           complain, in_decl);
7498             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
7499
7500             if (TREE_TYPE (new_arg) == error_mark_node)
7501               new_arg = error_mark_node;
7502           }
7503         }
7504       else
7505         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
7506
7507       if (new_arg == error_mark_node)
7508         return error_mark_node;
7509
7510       elts[i] = new_arg;
7511       if (new_arg != orig_arg)
7512         need_new = 1;
7513     }
7514
7515   if (!need_new)
7516     return t;
7517
7518   /* Make space for the expanded arguments coming from template
7519      argument packs.  */
7520   t = make_tree_vec (len + expanded_len_adjust);
7521   for (i = 0, out = 0; i < len; i++)
7522     {
7523       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
7524            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
7525           && TREE_CODE (elts[i]) == TREE_VEC)
7526         {
7527           int idx;
7528
7529           /* Now expand the template argument pack "in place".  */
7530           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
7531             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
7532         }
7533       else
7534         {
7535           TREE_VEC_ELT (t, out) = elts[i];
7536           out++;
7537         }
7538     }
7539
7540   return t;
7541 }
7542
7543 /* Return the result of substituting ARGS into the template parameters
7544    given by PARMS.  If there are m levels of ARGS and m + n levels of
7545    PARMS, then the result will contain n levels of PARMS.  For
7546    example, if PARMS is `template <class T> template <class U>
7547    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
7548    result will be `template <int*, double, class V>'.  */
7549
7550 static tree
7551 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
7552 {
7553   tree r = NULL_TREE;
7554   tree* new_parms;
7555
7556   /* When substituting into a template, we must set
7557      PROCESSING_TEMPLATE_DECL as the template parameters may be
7558      dependent if they are based on one-another, and the dependency
7559      predicates are short-circuit outside of templates.  */
7560   ++processing_template_decl;
7561
7562   for (new_parms = &r;
7563        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
7564        new_parms = &(TREE_CHAIN (*new_parms)),
7565          parms = TREE_CHAIN (parms))
7566     {
7567       tree new_vec =
7568         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
7569       int i;
7570
7571       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
7572         {
7573           tree tuple;
7574           tree default_value;
7575           tree parm_decl;
7576
7577           if (parms == error_mark_node)
7578             continue;
7579
7580           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
7581
7582           if (tuple == error_mark_node)
7583             continue;
7584
7585           default_value = TREE_PURPOSE (tuple);
7586           parm_decl = TREE_VALUE (tuple);
7587
7588           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
7589           if (TREE_CODE (parm_decl) == PARM_DECL
7590               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
7591             parm_decl = error_mark_node;
7592           default_value = tsubst_template_arg (default_value, args,
7593                                                complain, NULL_TREE);
7594
7595           tuple = build_tree_list (default_value, parm_decl);
7596           TREE_VEC_ELT (new_vec, i) = tuple;
7597         }
7598
7599       *new_parms =
7600         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
7601                              - TMPL_ARGS_DEPTH (args)),
7602                    new_vec, NULL_TREE);
7603     }
7604
7605   --processing_template_decl;
7606
7607   return r;
7608 }
7609
7610 /* Substitute the ARGS into the indicated aggregate (or enumeration)
7611    type T.  If T is not an aggregate or enumeration type, it is
7612    handled as if by tsubst.  IN_DECL is as for tsubst.  If
7613    ENTERING_SCOPE is nonzero, T is the context for a template which
7614    we are presently tsubst'ing.  Return the substituted value.  */
7615
7616 static tree
7617 tsubst_aggr_type (tree t,
7618                   tree args,
7619                   tsubst_flags_t complain,
7620                   tree in_decl,
7621                   int entering_scope)
7622 {
7623   if (t == NULL_TREE)
7624     return NULL_TREE;
7625
7626   switch (TREE_CODE (t))
7627     {
7628     case RECORD_TYPE:
7629       if (TYPE_PTRMEMFUNC_P (t))
7630         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
7631
7632       /* Else fall through.  */
7633     case ENUMERAL_TYPE:
7634     case UNION_TYPE:
7635       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
7636         {
7637           tree argvec;
7638           tree context;
7639           tree r;
7640           bool saved_skip_evaluation;
7641
7642           /* In "sizeof(X<I>)" we need to evaluate "I".  */
7643           saved_skip_evaluation = skip_evaluation;
7644           skip_evaluation = false;
7645
7646           /* First, determine the context for the type we are looking
7647              up.  */
7648           context = TYPE_CONTEXT (t);
7649           if (context)
7650             {
7651               context = tsubst_aggr_type (context, args, complain,
7652                                           in_decl, /*entering_scope=*/1);
7653               /* If context is a nested class inside a class template,
7654                  it may still need to be instantiated (c++/33959).  */
7655               if (TYPE_P (context))
7656                 context = complete_type (context);
7657             }
7658
7659           /* Then, figure out what arguments are appropriate for the
7660              type we are trying to find.  For example, given:
7661
7662                template <class T> struct S;
7663                template <class T, class U> void f(T, U) { S<U> su; }
7664
7665              and supposing that we are instantiating f<int, double>,
7666              then our ARGS will be {int, double}, but, when looking up
7667              S we only want {double}.  */
7668           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
7669                                          complain, in_decl);
7670           if (argvec == error_mark_node)
7671             r = error_mark_node;
7672           else
7673             {
7674               r = lookup_template_class (t, argvec, in_decl, context,
7675                                          entering_scope, complain);
7676               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
7677             }
7678
7679           skip_evaluation = saved_skip_evaluation;
7680
7681           return r;
7682         }
7683       else
7684         /* This is not a template type, so there's nothing to do.  */
7685         return t;
7686
7687     default:
7688       return tsubst (t, args, complain, in_decl);
7689     }
7690 }
7691
7692 /* Substitute into the default argument ARG (a default argument for
7693    FN), which has the indicated TYPE.  */
7694
7695 tree
7696 tsubst_default_argument (tree fn, tree type, tree arg)
7697 {
7698   tree saved_class_ptr = NULL_TREE;
7699   tree saved_class_ref = NULL_TREE;
7700
7701   /* This default argument came from a template.  Instantiate the
7702      default argument here, not in tsubst.  In the case of
7703      something like:
7704
7705        template <class T>
7706        struct S {
7707          static T t();
7708          void f(T = t());
7709        };
7710
7711      we must be careful to do name lookup in the scope of S<T>,
7712      rather than in the current class.  */
7713   push_access_scope (fn);
7714   /* The "this" pointer is not valid in a default argument.  */
7715   if (cfun)
7716     {
7717       saved_class_ptr = current_class_ptr;
7718       cp_function_chain->x_current_class_ptr = NULL_TREE;
7719       saved_class_ref = current_class_ref;
7720       cp_function_chain->x_current_class_ref = NULL_TREE;
7721     }
7722
7723   push_deferring_access_checks(dk_no_deferred);
7724   /* The default argument expression may cause implicitly defined
7725      member functions to be synthesized, which will result in garbage
7726      collection.  We must treat this situation as if we were within
7727      the body of function so as to avoid collecting live data on the
7728      stack.  */
7729   ++function_depth;
7730   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
7731                      tf_warning_or_error, NULL_TREE,
7732                      /*integral_constant_expression_p=*/false);
7733   --function_depth;
7734   pop_deferring_access_checks();
7735
7736   /* Restore the "this" pointer.  */
7737   if (cfun)
7738     {
7739       cp_function_chain->x_current_class_ptr = saved_class_ptr;
7740       cp_function_chain->x_current_class_ref = saved_class_ref;
7741     }
7742
7743   pop_access_scope (fn);
7744
7745   /* Make sure the default argument is reasonable.  */
7746   arg = check_default_argument (type, arg);
7747
7748   return arg;
7749 }
7750
7751 /* Substitute into all the default arguments for FN.  */
7752
7753 static void
7754 tsubst_default_arguments (tree fn)
7755 {
7756   tree arg;
7757   tree tmpl_args;
7758
7759   tmpl_args = DECL_TI_ARGS (fn);
7760
7761   /* If this function is not yet instantiated, we certainly don't need
7762      its default arguments.  */
7763   if (uses_template_parms (tmpl_args))
7764     return;
7765
7766   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
7767        arg;
7768        arg = TREE_CHAIN (arg))
7769     if (TREE_PURPOSE (arg))
7770       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
7771                                                     TREE_VALUE (arg),
7772                                                     TREE_PURPOSE (arg));
7773 }
7774
7775 /* Substitute the ARGS into the T, which is a _DECL.  Return the
7776    result of the substitution.  Issue error and warning messages under
7777    control of COMPLAIN.  */
7778
7779 static tree
7780 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
7781 {
7782   location_t saved_loc;
7783   tree r = NULL_TREE;
7784   tree in_decl = t;
7785
7786   /* Set the filename and linenumber to improve error-reporting.  */
7787   saved_loc = input_location;
7788   input_location = DECL_SOURCE_LOCATION (t);
7789
7790   switch (TREE_CODE (t))
7791     {
7792     case TEMPLATE_DECL:
7793       {
7794         /* We can get here when processing a member function template,
7795            member class template, and template template parameter of
7796            a template class.  */
7797         tree decl = DECL_TEMPLATE_RESULT (t);
7798         tree spec;
7799         tree tmpl_args;
7800         tree full_args;
7801
7802         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
7803           {
7804             /* Template template parameter is treated here.  */
7805             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7806             if (new_type == error_mark_node)
7807               return error_mark_node;
7808
7809             r = copy_decl (t);
7810             TREE_CHAIN (r) = NULL_TREE;
7811             TREE_TYPE (r) = new_type;
7812             DECL_TEMPLATE_RESULT (r)
7813               = build_decl (TYPE_DECL, DECL_NAME (decl), new_type);
7814             DECL_TEMPLATE_PARMS (r)
7815               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
7816                                        complain);
7817             TYPE_NAME (new_type) = r;
7818             break;
7819           }
7820
7821         /* We might already have an instance of this template.
7822            The ARGS are for the surrounding class type, so the
7823            full args contain the tsubst'd args for the context,
7824            plus the innermost args from the template decl.  */
7825         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
7826           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
7827           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
7828         /* Because this is a template, the arguments will still be
7829            dependent, even after substitution.  If
7830            PROCESSING_TEMPLATE_DECL is not set, the dependency
7831            predicates will short-circuit.  */
7832         ++processing_template_decl;
7833         full_args = tsubst_template_args (tmpl_args, args,
7834                                           complain, in_decl);
7835         --processing_template_decl;
7836         if (full_args == error_mark_node)
7837           return error_mark_node;
7838
7839         /* tsubst_template_args doesn't copy the vector if
7840            nothing changed.  But, *something* should have
7841            changed.  */
7842         gcc_assert (full_args != tmpl_args);
7843
7844         spec = retrieve_specialization (t, full_args,
7845                                         /*class_specializations_p=*/true);
7846         if (spec != NULL_TREE)
7847           {
7848             r = spec;
7849             break;
7850           }
7851
7852         /* Make a new template decl.  It will be similar to the
7853            original, but will record the current template arguments.
7854            We also create a new function declaration, which is just
7855            like the old one, but points to this new template, rather
7856            than the old one.  */
7857         r = copy_decl (t);
7858         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
7859         TREE_CHAIN (r) = NULL_TREE;
7860
7861         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
7862
7863         if (TREE_CODE (decl) == TYPE_DECL)
7864           {
7865             tree new_type;
7866             ++processing_template_decl;
7867             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7868             --processing_template_decl;
7869             if (new_type == error_mark_node)
7870               return error_mark_node;
7871
7872             TREE_TYPE (r) = new_type;
7873             CLASSTYPE_TI_TEMPLATE (new_type) = r;
7874             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
7875             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
7876             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
7877           }
7878         else
7879           {
7880             tree new_decl;
7881             ++processing_template_decl;
7882             new_decl = tsubst (decl, args, complain, in_decl);
7883             --processing_template_decl;
7884             if (new_decl == error_mark_node)
7885               return error_mark_node;
7886
7887             DECL_TEMPLATE_RESULT (r) = new_decl;
7888             DECL_TI_TEMPLATE (new_decl) = r;
7889             TREE_TYPE (r) = TREE_TYPE (new_decl);
7890             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
7891             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
7892           }
7893
7894         SET_DECL_IMPLICIT_INSTANTIATION (r);
7895         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
7896         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
7897
7898         /* The template parameters for this new template are all the
7899            template parameters for the old template, except the
7900            outermost level of parameters.  */
7901         DECL_TEMPLATE_PARMS (r)
7902           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
7903                                    complain);
7904
7905         if (PRIMARY_TEMPLATE_P (t))
7906           DECL_PRIMARY_TEMPLATE (r) = r;
7907
7908         if (TREE_CODE (decl) != TYPE_DECL)
7909           /* Record this non-type partial instantiation.  */
7910           register_specialization (r, t,
7911                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
7912                                    false);
7913       }
7914       break;
7915
7916     case FUNCTION_DECL:
7917       {
7918         tree ctx;
7919         tree argvec = NULL_TREE;
7920         tree *friends;
7921         tree gen_tmpl;
7922         tree type;
7923         int member;
7924         int args_depth;
7925         int parms_depth;
7926
7927         /* Nobody should be tsubst'ing into non-template functions.  */
7928         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
7929
7930         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
7931           {
7932             tree spec;
7933             bool dependent_p;
7934
7935             /* If T is not dependent, just return it.  We have to
7936                increment PROCESSING_TEMPLATE_DECL because
7937                value_dependent_expression_p assumes that nothing is
7938                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
7939             ++processing_template_decl;
7940             dependent_p = value_dependent_expression_p (t);
7941             --processing_template_decl;
7942             if (!dependent_p)
7943               return t;
7944
7945             /* Calculate the most general template of which R is a
7946                specialization, and the complete set of arguments used to
7947                specialize R.  */
7948             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
7949             argvec = tsubst_template_args (DECL_TI_ARGS
7950                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
7951                                            args, complain, in_decl);
7952
7953             /* Check to see if we already have this specialization.  */
7954             spec = retrieve_specialization (gen_tmpl, argvec,
7955                                             /*class_specializations_p=*/false);
7956
7957             if (spec)
7958               {
7959                 r = spec;
7960                 break;
7961               }
7962
7963             /* We can see more levels of arguments than parameters if
7964                there was a specialization of a member template, like
7965                this:
7966
7967                  template <class T> struct S { template <class U> void f(); }
7968                  template <> template <class U> void S<int>::f(U);
7969
7970                Here, we'll be substituting into the specialization,
7971                because that's where we can find the code we actually
7972                want to generate, but we'll have enough arguments for
7973                the most general template.
7974
7975                We also deal with the peculiar case:
7976
7977                  template <class T> struct S {
7978                    template <class U> friend void f();
7979                  };
7980                  template <class U> void f() {}
7981                  template S<int>;
7982                  template void f<double>();
7983
7984                Here, the ARGS for the instantiation of will be {int,
7985                double}.  But, we only need as many ARGS as there are
7986                levels of template parameters in CODE_PATTERN.  We are
7987                careful not to get fooled into reducing the ARGS in
7988                situations like:
7989
7990                  template <class T> struct S { template <class U> void f(U); }
7991                  template <class T> template <> void S<T>::f(int) {}
7992
7993                which we can spot because the pattern will be a
7994                specialization in this case.  */
7995             args_depth = TMPL_ARGS_DEPTH (args);
7996             parms_depth =
7997               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
7998             if (args_depth > parms_depth
7999                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8000               args = get_innermost_template_args (args, parms_depth);
8001           }
8002         else
8003           {
8004             /* This special case arises when we have something like this:
8005
8006                  template <class T> struct S {
8007                    friend void f<int>(int, double);
8008                  };
8009
8010                Here, the DECL_TI_TEMPLATE for the friend declaration
8011                will be an IDENTIFIER_NODE.  We are being called from
8012                tsubst_friend_function, and we want only to create a
8013                new decl (R) with appropriate types so that we can call
8014                determine_specialization.  */
8015             gen_tmpl = NULL_TREE;
8016           }
8017
8018         if (DECL_CLASS_SCOPE_P (t))
8019           {
8020             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8021               member = 2;
8022             else
8023               member = 1;
8024             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8025                                     complain, t, /*entering_scope=*/1);
8026           }
8027         else
8028           {
8029             member = 0;
8030             ctx = DECL_CONTEXT (t);
8031           }
8032         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8033         if (type == error_mark_node)
8034           return error_mark_node;
8035
8036         /* We do NOT check for matching decls pushed separately at this
8037            point, as they may not represent instantiations of this
8038            template, and in any case are considered separate under the
8039            discrete model.  */
8040         r = copy_decl (t);
8041         DECL_USE_TEMPLATE (r) = 0;
8042         TREE_TYPE (r) = type;
8043         /* Clear out the mangled name and RTL for the instantiation.  */
8044         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8045         SET_DECL_RTL (r, NULL_RTX);
8046         DECL_INITIAL (r) = NULL_TREE;
8047         DECL_CONTEXT (r) = ctx;
8048
8049         if (member && DECL_CONV_FN_P (r))
8050           /* Type-conversion operator.  Reconstruct the name, in
8051              case it's the name of one of the template's parameters.  */
8052           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8053
8054         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8055                                      complain, t);
8056         DECL_RESULT (r) = NULL_TREE;
8057
8058         TREE_STATIC (r) = 0;
8059         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8060         DECL_EXTERNAL (r) = 1;
8061         /* If this is an instantiation of a function with internal
8062            linkage, we already know what object file linkage will be
8063            assigned to the instantiation.  */
8064         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8065         DECL_DEFER_OUTPUT (r) = 0;
8066         TREE_CHAIN (r) = NULL_TREE;
8067         DECL_PENDING_INLINE_INFO (r) = 0;
8068         DECL_PENDING_INLINE_P (r) = 0;
8069         DECL_SAVED_TREE (r) = NULL_TREE;
8070         TREE_USED (r) = 0;
8071         if (DECL_CLONED_FUNCTION (r))
8072           {
8073             DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
8074                                                args, complain, t);
8075             TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
8076             TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
8077           }
8078
8079         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8080            this in the special friend case mentioned above where
8081            GEN_TMPL is NULL.  */
8082         if (gen_tmpl)
8083           {
8084             DECL_TEMPLATE_INFO (r)
8085               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8086             SET_DECL_IMPLICIT_INSTANTIATION (r);
8087             register_specialization (r, gen_tmpl, argvec, false);
8088
8089             /* We're not supposed to instantiate default arguments
8090                until they are called, for a template.  But, for a
8091                declaration like:
8092
8093                  template <class T> void f ()
8094                  { extern void g(int i = T()); }
8095
8096                we should do the substitution when the template is
8097                instantiated.  We handle the member function case in
8098                instantiate_class_template since the default arguments
8099                might refer to other members of the class.  */
8100             if (!member
8101                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8102                 && !uses_template_parms (argvec))
8103               tsubst_default_arguments (r);
8104           }
8105         else
8106           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8107
8108         /* Copy the list of befriending classes.  */
8109         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8110              *friends;
8111              friends = &TREE_CHAIN (*friends))
8112           {
8113             *friends = copy_node (*friends);
8114             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8115                                             args, complain,
8116                                             in_decl);
8117           }
8118
8119         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8120           {
8121             maybe_retrofit_in_chrg (r);
8122             if (DECL_CONSTRUCTOR_P (r))
8123               grok_ctor_properties (ctx, r);
8124             /* If this is an instantiation of a member template, clone it.
8125                If it isn't, that'll be handled by
8126                clone_constructors_and_destructors.  */
8127             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8128               clone_function_decl (r, /*update_method_vec_p=*/0);
8129           }
8130         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r))
8131                  && !grok_op_properties (r, (complain & tf_error) != 0))
8132           return error_mark_node;
8133
8134         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8135           SET_DECL_FRIEND_CONTEXT (r,
8136                                    tsubst (DECL_FRIEND_CONTEXT (t),
8137                                             args, complain, in_decl));
8138
8139         /* Possibly limit visibility based on template args.  */
8140         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8141         if (DECL_VISIBILITY_SPECIFIED (t))
8142           {
8143             DECL_VISIBILITY_SPECIFIED (r) = 0;
8144             DECL_ATTRIBUTES (r)
8145               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8146           }
8147         determine_visibility (r);
8148
8149         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8150                                         args, complain, in_decl);
8151       }
8152       break;
8153
8154     case PARM_DECL:
8155       {
8156         tree type = NULL_TREE;
8157         int i, len = 1;
8158         tree expanded_types = NULL_TREE;
8159         tree prev_r = NULL_TREE;
8160         tree first_r = NULL_TREE;
8161
8162         if (FUNCTION_PARAMETER_PACK_P (t))
8163           {
8164             /* If there is a local specialization that isn't a
8165                parameter pack, it means that we're doing a "simple"
8166                substitution from inside tsubst_pack_expansion. Just
8167                return the local specialization (which will be a single
8168                parm).  */
8169             tree spec = retrieve_local_specialization (t);
8170             if (spec 
8171                 && TREE_CODE (spec) == PARM_DECL
8172                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8173               return spec;
8174
8175             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8176                the parameters in this function parameter pack.  */
8177             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8178                                                     complain, in_decl);
8179             if (TREE_CODE (expanded_types) == TREE_VEC)
8180               {
8181                 len = TREE_VEC_LENGTH (expanded_types);
8182
8183                 /* Zero-length parameter packs are boring. Just substitute
8184                    into the chain.  */
8185                 if (len == 0)
8186                   return tsubst (TREE_CHAIN (t), args, complain, 
8187                                  TREE_CHAIN (t));
8188               }
8189             else
8190               {
8191                 /* All we did was update the type. Make a note of that.  */
8192                 type = expanded_types;
8193                 expanded_types = NULL_TREE;
8194               }
8195           }
8196
8197         /* Loop through all of the parameter's we'll build. When T is
8198            a function parameter pack, LEN is the number of expanded
8199            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8200         r = NULL_TREE;
8201         for (i = 0; i < len; ++i)
8202           {
8203             prev_r = r;
8204             r = copy_node (t);
8205             if (DECL_TEMPLATE_PARM_P (t))
8206               SET_DECL_TEMPLATE_PARM_P (r);
8207
8208             if (expanded_types)
8209               /* We're on the Ith parameter of the function parameter
8210                  pack.  */
8211               {
8212                 /* Get the Ith type.  */
8213                 type = TREE_VEC_ELT (expanded_types, i);
8214
8215                 if (DECL_NAME (r))
8216                   /* Rename the parameter to include the index.  */
8217                   DECL_NAME (r) =
8218                     make_ith_pack_parameter_name (DECL_NAME (r), i);
8219               }
8220             else if (!type)
8221               /* We're dealing with a normal parameter.  */
8222               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8223
8224             type = type_decays_to (type);
8225             TREE_TYPE (r) = type;
8226             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8227
8228             if (DECL_INITIAL (r))
8229               {
8230                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
8231                   DECL_INITIAL (r) = TREE_TYPE (r);
8232                 else
8233                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
8234                                              complain, in_decl);
8235               }
8236
8237             DECL_CONTEXT (r) = NULL_TREE;
8238
8239             if (!DECL_TEMPLATE_PARM_P (r))
8240               DECL_ARG_TYPE (r) = type_passed_as (type);
8241
8242             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8243                                             args, complain, in_decl);
8244
8245             /* Keep track of the first new parameter we
8246                generate. That's what will be returned to the
8247                caller.  */
8248             if (!first_r)
8249               first_r = r;
8250
8251             /* Build a proper chain of parameters when substituting
8252                into a function parameter pack.  */
8253             if (prev_r)
8254               TREE_CHAIN (prev_r) = r;
8255           }
8256
8257         if (TREE_CHAIN (t))
8258           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
8259                                    complain, TREE_CHAIN (t));
8260
8261         /* FIRST_R contains the start of the chain we've built.  */
8262         r = first_r;
8263       }
8264       break;
8265
8266     case FIELD_DECL:
8267       {
8268         tree type;
8269
8270         r = copy_decl (t);
8271         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8272         if (type == error_mark_node)
8273           return error_mark_node;
8274         TREE_TYPE (r) = type;
8275         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8276
8277         /* DECL_INITIAL gives the number of bits in a bit-field.  */
8278         DECL_INITIAL (r)
8279           = tsubst_expr (DECL_INITIAL (t), args,
8280                          complain, in_decl,
8281                          /*integral_constant_expression_p=*/true);
8282         /* We don't have to set DECL_CONTEXT here; it is set by
8283            finish_member_declaration.  */
8284         TREE_CHAIN (r) = NULL_TREE;
8285         if (VOID_TYPE_P (type))
8286           error ("instantiation of %q+D as type %qT", r, type);
8287
8288         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8289                                         args, complain, in_decl);
8290       }
8291       break;
8292
8293     case USING_DECL:
8294       /* We reach here only for member using decls.  */
8295       if (DECL_DEPENDENT_P (t))
8296         {
8297           r = do_class_using_decl
8298             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
8299              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
8300           if (!r)
8301             r = error_mark_node;
8302         }
8303       else
8304         {
8305           r = copy_node (t);
8306           TREE_CHAIN (r) = NULL_TREE;
8307         }
8308       break;
8309
8310     case TYPE_DECL:
8311     case VAR_DECL:
8312       {
8313         tree argvec = NULL_TREE;
8314         tree gen_tmpl = NULL_TREE;
8315         tree spec;
8316         tree tmpl = NULL_TREE;
8317         tree ctx;
8318         tree type = NULL_TREE;
8319         bool local_p;
8320
8321         if (TREE_CODE (t) == TYPE_DECL
8322             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
8323           {
8324             /* If this is the canonical decl, we don't have to
8325                mess with instantiations, and often we can't (for
8326                typename, template type parms and such).  Note that
8327                TYPE_NAME is not correct for the above test if
8328                we've copied the type for a typedef.  */
8329             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8330             if (type == error_mark_node)
8331               return error_mark_node;
8332             r = TYPE_NAME (type);
8333             break;
8334           }
8335
8336         /* Check to see if we already have the specialization we
8337            need.  */
8338         spec = NULL_TREE;
8339         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
8340           {
8341             /* T is a static data member or namespace-scope entity.
8342                We have to substitute into namespace-scope variables
8343                (even though such entities are never templates) because
8344                of cases like:
8345                
8346                  template <class T> void f() { extern T t; }
8347
8348                where the entity referenced is not known until
8349                instantiation time.  */
8350             local_p = false;
8351             ctx = DECL_CONTEXT (t);
8352             if (DECL_CLASS_SCOPE_P (t))
8353               {
8354                 ctx = tsubst_aggr_type (ctx, args,
8355                                         complain,
8356                                         in_decl, /*entering_scope=*/1);
8357                 /* If CTX is unchanged, then T is in fact the
8358                    specialization we want.  That situation occurs when
8359                    referencing a static data member within in its own
8360                    class.  We can use pointer equality, rather than
8361                    same_type_p, because DECL_CONTEXT is always
8362                    canonical.  */
8363                 if (ctx == DECL_CONTEXT (t))
8364                   spec = t;
8365               }
8366
8367             if (!spec)
8368               {
8369                 tmpl = DECL_TI_TEMPLATE (t);
8370                 gen_tmpl = most_general_template (tmpl);
8371                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
8372                 spec = (retrieve_specialization 
8373                         (gen_tmpl, argvec,
8374                          /*class_specializations_p=*/false));
8375               }
8376           }
8377         else
8378           {
8379             /* A local variable.  */
8380             local_p = true;
8381             /* Subsequent calls to pushdecl will fill this in.  */
8382             ctx = NULL_TREE;
8383             spec = retrieve_local_specialization (t);
8384           }
8385         /* If we already have the specialization we need, there is
8386            nothing more to do.  */ 
8387         if (spec)
8388           {
8389             r = spec;
8390             break;
8391           }
8392
8393         /* Create a new node for the specialization we need.  */
8394         r = copy_decl (t);
8395         if (type == NULL_TREE)
8396           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8397         if (TREE_CODE (r) == VAR_DECL)
8398           {
8399             /* Even if the original location is out of scope, the
8400                newly substituted one is not.  */
8401             DECL_DEAD_FOR_LOCAL (r) = 0;
8402             DECL_INITIALIZED_P (r) = 0;
8403             DECL_TEMPLATE_INSTANTIATED (r) = 0;
8404             if (type == error_mark_node)
8405               return error_mark_node;
8406             if (TREE_CODE (type) == FUNCTION_TYPE)
8407               {
8408                 /* It may seem that this case cannot occur, since:
8409
8410                      typedef void f();
8411                      void g() { f x; }
8412
8413                    declares a function, not a variable.  However:
8414       
8415                      typedef void f();
8416                      template <typename T> void g() { T t; }
8417                      template void g<f>();
8418
8419                    is an attempt to declare a variable with function
8420                    type.  */
8421                 error ("variable %qD has function type",
8422                        /* R is not yet sufficiently initialized, so we
8423                           just use its name.  */
8424                        DECL_NAME (r));
8425                 return error_mark_node;
8426               }
8427             type = complete_type (type);
8428             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
8429               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
8430             type = check_var_type (DECL_NAME (r), type);
8431
8432             if (DECL_HAS_VALUE_EXPR_P (t))
8433               {
8434                 tree ve = DECL_VALUE_EXPR (t);
8435                 ve = tsubst_expr (ve, args, complain, in_decl,
8436                                   /*constant_expression_p=*/false);
8437                 SET_DECL_VALUE_EXPR (r, ve);
8438               }
8439           }
8440         else if (DECL_SELF_REFERENCE_P (t))
8441           SET_DECL_SELF_REFERENCE_P (r);
8442         TREE_TYPE (r) = type;
8443         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8444         DECL_CONTEXT (r) = ctx;
8445         /* Clear out the mangled name and RTL for the instantiation.  */
8446         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8447         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8448           SET_DECL_RTL (r, NULL_RTX);
8449         /* The initializer must not be expanded until it is required;
8450            see [temp.inst].  */
8451         DECL_INITIAL (r) = NULL_TREE;
8452         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8453           SET_DECL_RTL (r, NULL_RTX);
8454         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
8455         if (TREE_CODE (r) == VAR_DECL)
8456           {
8457             /* Possibly limit visibility based on template args.  */
8458             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8459             if (DECL_VISIBILITY_SPECIFIED (t))
8460               {
8461                 DECL_VISIBILITY_SPECIFIED (r) = 0;
8462                 DECL_ATTRIBUTES (r)
8463                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8464               }
8465             determine_visibility (r);
8466           }
8467         /* Preserve a typedef that names a type.  */
8468         else if (TREE_CODE (r) == TYPE_DECL
8469                  && DECL_ORIGINAL_TYPE (t)
8470                  && type != error_mark_node)
8471           {
8472             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
8473                                              args, complain, in_decl);
8474             TREE_TYPE (r) = type = build_variant_type_copy (type);
8475             TYPE_NAME (type) = r;
8476           }
8477
8478         if (!local_p)
8479           {
8480             /* A static data member declaration is always marked
8481                external when it is declared in-class, even if an
8482                initializer is present.  We mimic the non-template
8483                processing here.  */
8484             DECL_EXTERNAL (r) = 1;
8485
8486             register_specialization (r, gen_tmpl, argvec, false);
8487             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
8488             SET_DECL_IMPLICIT_INSTANTIATION (r);
8489           }
8490         else
8491           register_local_specialization (r, t);
8492
8493         TREE_CHAIN (r) = NULL_TREE;
8494
8495         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
8496                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
8497                                         args, complain, in_decl);
8498         layout_decl (r, 0);
8499       }
8500       break;
8501
8502     default:
8503       gcc_unreachable ();
8504     }
8505
8506   /* Restore the file and line information.  */
8507   input_location = saved_loc;
8508
8509   return r;
8510 }
8511
8512 /* Substitute into the ARG_TYPES of a function type.  */
8513
8514 static tree
8515 tsubst_arg_types (tree arg_types,
8516                   tree args,
8517                   tsubst_flags_t complain,
8518                   tree in_decl)
8519 {
8520   tree remaining_arg_types;
8521   tree type = NULL_TREE;
8522   int i = 1;
8523   tree expanded_args = NULL_TREE;
8524   tree default_arg;
8525
8526   if (!arg_types || arg_types == void_list_node)
8527     return arg_types;
8528
8529   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
8530                                           args, complain, in_decl);
8531   if (remaining_arg_types == error_mark_node)
8532     return error_mark_node;
8533
8534   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
8535     {
8536       /* For a pack expansion, perform substitution on the
8537          entire expression. Later on, we'll handle the arguments
8538          one-by-one.  */
8539       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
8540                                             args, complain, in_decl);
8541
8542       if (TREE_CODE (expanded_args) == TREE_VEC)
8543         /* So that we'll spin through the parameters, one by one.  */
8544         i = TREE_VEC_LENGTH (expanded_args);
8545       else
8546         {
8547           /* We only partially substituted into the parameter
8548              pack. Our type is TYPE_PACK_EXPANSION.  */
8549           type = expanded_args;
8550           expanded_args = NULL_TREE;
8551         }
8552     }
8553
8554   while (i > 0) {
8555     --i;
8556     
8557     if (expanded_args)
8558       type = TREE_VEC_ELT (expanded_args, i);
8559     else if (!type)
8560       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
8561
8562     if (type == error_mark_node)
8563       return error_mark_node;
8564     if (VOID_TYPE_P (type))
8565       {
8566         if (complain & tf_error)
8567           {
8568             error ("invalid parameter type %qT", type);
8569             if (in_decl)
8570               error ("in declaration %q+D", in_decl);
8571           }
8572         return error_mark_node;
8573     }
8574     
8575     /* Do array-to-pointer, function-to-pointer conversion, and ignore
8576        top-level qualifiers as required.  */
8577     type = TYPE_MAIN_VARIANT (type_decays_to (type));
8578
8579     /* We do not substitute into default arguments here.  The standard
8580        mandates that they be instantiated only when needed, which is
8581        done in build_over_call.  */
8582     default_arg = TREE_PURPOSE (arg_types);
8583
8584     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
8585       {
8586         /* We've instantiated a template before its default arguments
8587            have been parsed.  This can happen for a nested template
8588            class, and is not an error unless we require the default
8589            argument in a call of this function.  */
8590         remaining_arg_types = 
8591           tree_cons (default_arg, type, remaining_arg_types);
8592         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
8593                        remaining_arg_types);
8594       }
8595     else
8596       remaining_arg_types = 
8597         hash_tree_cons (default_arg, type, remaining_arg_types);
8598   }
8599         
8600   return remaining_arg_types;
8601 }
8602
8603 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
8604    *not* handle the exception-specification for FNTYPE, because the
8605    initial substitution of explicitly provided template parameters
8606    during argument deduction forbids substitution into the
8607    exception-specification:
8608
8609      [temp.deduct]
8610
8611      All references in the function type of the function template to  the
8612      corresponding template parameters are replaced by the specified tem-
8613      plate argument values.  If a substitution in a template parameter or
8614      in  the function type of the function template results in an invalid
8615      type, type deduction fails.  [Note: The equivalent  substitution  in
8616      exception specifications is done only when the function is instanti-
8617      ated, at which point a program is  ill-formed  if  the  substitution
8618      results in an invalid type.]  */
8619
8620 static tree
8621 tsubst_function_type (tree t,
8622                       tree args,
8623                       tsubst_flags_t complain,
8624                       tree in_decl)
8625 {
8626   tree return_type;
8627   tree arg_types;
8628   tree fntype;
8629
8630   /* The TYPE_CONTEXT is not used for function/method types.  */
8631   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
8632
8633   /* Substitute the return type.  */
8634   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8635   if (return_type == error_mark_node)
8636     return error_mark_node;
8637   /* The standard does not presently indicate that creation of a
8638      function type with an invalid return type is a deduction failure.
8639      However, that is clearly analogous to creating an array of "void"
8640      or a reference to a reference.  This is core issue #486.  */
8641   if (TREE_CODE (return_type) == ARRAY_TYPE
8642       || TREE_CODE (return_type) == FUNCTION_TYPE)
8643     {
8644       if (complain & tf_error)
8645         {
8646           if (TREE_CODE (return_type) == ARRAY_TYPE)
8647             error ("function returning an array");
8648           else
8649             error ("function returning a function");
8650         }
8651       return error_mark_node;
8652     }
8653
8654   /* Substitute the argument types.  */
8655   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
8656                                 complain, in_decl);
8657   if (arg_types == error_mark_node)
8658     return error_mark_node;
8659
8660   if (TYPE_QUALS (return_type) != TYPE_UNQUALIFIED
8661       && in_decl != NULL_TREE
8662       && !TREE_NO_WARNING (in_decl)
8663       && (SCALAR_TYPE_P (return_type) || VOID_TYPE_P (return_type)))
8664     warning (OPT_Wignored_qualifiers,
8665             "type qualifiers ignored on function return type");
8666
8667   /* Construct a new type node and return it.  */
8668   if (TREE_CODE (t) == FUNCTION_TYPE)
8669     fntype = build_function_type (return_type, arg_types);
8670   else
8671     {
8672       tree r = TREE_TYPE (TREE_VALUE (arg_types));
8673       if (! IS_AGGR_TYPE (r))
8674         {
8675           /* [temp.deduct]
8676
8677              Type deduction may fail for any of the following
8678              reasons:
8679
8680              -- Attempting to create "pointer to member of T" when T
8681              is not a class type.  */
8682           if (complain & tf_error)
8683             error ("creating pointer to member function of non-class type %qT",
8684                       r);
8685           return error_mark_node;
8686         }
8687
8688       fntype = build_method_type_directly (r, return_type,
8689                                            TREE_CHAIN (arg_types));
8690     }
8691   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
8692   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
8693
8694   return fntype;
8695 }
8696
8697 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
8698    ARGS into that specification, and return the substituted
8699    specification.  If there is no specification, return NULL_TREE.  */
8700
8701 static tree
8702 tsubst_exception_specification (tree fntype,
8703                                 tree args,
8704                                 tsubst_flags_t complain,
8705                                 tree in_decl)
8706 {
8707   tree specs;
8708   tree new_specs;
8709
8710   specs = TYPE_RAISES_EXCEPTIONS (fntype);
8711   new_specs = NULL_TREE;
8712   if (specs)
8713     {
8714       if (! TREE_VALUE (specs))
8715         new_specs = specs;
8716       else
8717         while (specs)
8718           {
8719             tree spec;
8720             int i, len = 1;
8721             tree expanded_specs = NULL_TREE;
8722
8723             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
8724               {
8725                 /* Expand the pack expansion type.  */
8726                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
8727                                                        args, complain,
8728                                                        in_decl);
8729
8730                 if (expanded_specs == error_mark_node)
8731                   return error_mark_node;
8732                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
8733                   len = TREE_VEC_LENGTH (expanded_specs);
8734                 else
8735                   {
8736                     /* We're substituting into a member template, so
8737                        we got a TYPE_PACK_EXPANSION back.  Add that
8738                        expansion and move on.  */
8739                     gcc_assert (TREE_CODE (expanded_specs) 
8740                                 == TYPE_PACK_EXPANSION);
8741                     new_specs = add_exception_specifier (new_specs,
8742                                                          expanded_specs,
8743                                                          complain);
8744                     specs = TREE_CHAIN (specs);
8745                     continue;
8746                   }
8747               }
8748
8749             for (i = 0; i < len; ++i)
8750               {
8751                 if (expanded_specs)
8752                   spec = TREE_VEC_ELT (expanded_specs, i);
8753                 else
8754                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
8755                 if (spec == error_mark_node)
8756                   return spec;
8757                 new_specs = add_exception_specifier (new_specs, spec, 
8758                                                      complain);
8759               }
8760
8761             specs = TREE_CHAIN (specs);
8762           }
8763     }
8764   return new_specs;
8765 }
8766
8767 /* Take the tree structure T and replace template parameters used
8768    therein with the argument vector ARGS.  IN_DECL is an associated
8769    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
8770    Issue error and warning messages under control of COMPLAIN.  Note
8771    that we must be relatively non-tolerant of extensions here, in
8772    order to preserve conformance; if we allow substitutions that
8773    should not be allowed, we may allow argument deductions that should
8774    not succeed, and therefore report ambiguous overload situations
8775    where there are none.  In theory, we could allow the substitution,
8776    but indicate that it should have failed, and allow our caller to
8777    make sure that the right thing happens, but we don't try to do this
8778    yet.
8779
8780    This function is used for dealing with types, decls and the like;
8781    for expressions, use tsubst_expr or tsubst_copy.  */
8782
8783 static tree
8784 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8785 {
8786   tree type, r;
8787
8788   if (t == NULL_TREE || t == error_mark_node
8789       || t == integer_type_node
8790       || t == void_type_node
8791       || t == char_type_node
8792       || t == unknown_type_node
8793       || TREE_CODE (t) == NAMESPACE_DECL)
8794     return t;
8795
8796   if (DECL_P (t))
8797     return tsubst_decl (t, args, complain);
8798
8799   if (TREE_CODE (t) == IDENTIFIER_NODE)
8800     type = IDENTIFIER_TYPE_VALUE (t);
8801   else
8802     type = TREE_TYPE (t);
8803
8804   gcc_assert (type != unknown_type_node);
8805
8806   /* Reuse typedefs.  We need to do this to handle dependent attributes,
8807      such as attribute aligned.  */
8808   if (TYPE_P (t)
8809       && TYPE_NAME (t)
8810       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
8811     {
8812       tree decl = TYPE_NAME (t);
8813       
8814       if (DECL_CLASS_SCOPE_P (decl)
8815           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
8816           && uses_template_parms (DECL_CONTEXT (decl)))
8817         {
8818           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
8819           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
8820           r = retrieve_specialization (tmpl, gen_args, false);
8821         }
8822       else if (DECL_FUNCTION_SCOPE_P (decl)
8823                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
8824                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
8825         r = retrieve_local_specialization (decl);
8826       else
8827         /* The typedef is from a non-template context.  */
8828         return t;
8829
8830       if (r)
8831         {
8832           r = TREE_TYPE (r);
8833           r = cp_build_qualified_type_real
8834             (r, cp_type_quals (t) | cp_type_quals (r),
8835              complain | tf_ignore_bad_quals);
8836           return r;
8837         }
8838       /* Else we must be instantiating the typedef, so fall through.  */
8839     }
8840
8841   if (type
8842       && TREE_CODE (t) != TYPENAME_TYPE
8843       && TREE_CODE (t) != IDENTIFIER_NODE
8844       && TREE_CODE (t) != FUNCTION_TYPE
8845       && TREE_CODE (t) != METHOD_TYPE)
8846     type = tsubst (type, args, complain, in_decl);
8847   if (type == error_mark_node)
8848     return error_mark_node;
8849
8850   switch (TREE_CODE (t))
8851     {
8852     case RECORD_TYPE:
8853     case UNION_TYPE:
8854     case ENUMERAL_TYPE:
8855       return tsubst_aggr_type (t, args, complain, in_decl,
8856                                /*entering_scope=*/0);
8857
8858     case ERROR_MARK:
8859     case IDENTIFIER_NODE:
8860     case VOID_TYPE:
8861     case REAL_TYPE:
8862     case COMPLEX_TYPE:
8863     case VECTOR_TYPE:
8864     case BOOLEAN_TYPE:
8865     case INTEGER_CST:
8866     case REAL_CST:
8867     case STRING_CST:
8868       return t;
8869
8870     case INTEGER_TYPE:
8871       if (t == integer_type_node)
8872         return t;
8873
8874       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
8875           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
8876         return t;
8877
8878       {
8879         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
8880
8881         max = tsubst_expr (omax, args, complain, in_decl,
8882                            /*integral_constant_expression_p=*/false);
8883         max = fold_decl_constant_value (max);
8884
8885         if (TREE_CODE (max) != INTEGER_CST
8886             && !at_function_scope_p ()
8887             && !value_dependent_expression_p (max))
8888           {
8889             if (complain & tf_error)
8890               error ("array bound is not an integer constant");
8891             return error_mark_node;
8892           }
8893
8894         /* [temp.deduct]
8895
8896            Type deduction may fail for any of the following
8897            reasons:
8898
8899              Attempting to create an array with a size that is
8900              zero or negative.  */
8901         if (integer_zerop (max) && !(complain & tf_error))
8902           /* We must fail if performing argument deduction (as
8903              indicated by the state of complain), so that
8904              another substitution can be found.  */
8905           return error_mark_node;
8906         else if (TREE_CODE (max) == INTEGER_CST
8907                  && INT_CST_LT (max, integer_zero_node))
8908           {
8909             if (complain & tf_error)
8910               error ("creating array with negative size (%qE)", max);
8911
8912             return error_mark_node;
8913           }
8914
8915         return compute_array_index_type (NULL_TREE, max);
8916       }
8917
8918     case TEMPLATE_TYPE_PARM:
8919     case TEMPLATE_TEMPLATE_PARM:
8920     case BOUND_TEMPLATE_TEMPLATE_PARM:
8921     case TEMPLATE_PARM_INDEX:
8922       {
8923         int idx;
8924         int level;
8925         int levels;
8926         tree arg = NULL_TREE;
8927
8928         r = NULL_TREE;
8929
8930         gcc_assert (TREE_VEC_LENGTH (args) > 0);
8931         template_parm_level_and_index (t, &level, &idx); 
8932
8933         levels = TMPL_ARGS_DEPTH (args);
8934         if (level <= levels)
8935           {
8936             arg = TMPL_ARG (args, level, idx);
8937
8938             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
8939               /* See through ARGUMENT_PACK_SELECT arguments. */
8940               arg = ARGUMENT_PACK_SELECT_ARG (arg);
8941           }
8942
8943         if (arg == error_mark_node)
8944           return error_mark_node;
8945         else if (arg != NULL_TREE)
8946           {
8947             if (ARGUMENT_PACK_P (arg))
8948               /* If ARG is an argument pack, we don't actually want to
8949                  perform a substitution here, because substitutions
8950                  for argument packs are only done
8951                  element-by-element. We can get to this point when
8952                  substituting the type of a non-type template
8953                  parameter pack, when that type actually contains
8954                  template parameter packs from an outer template, e.g.,
8955
8956                  template<typename... Types> struct A {
8957                    template<Types... Values> struct B { };
8958                  };  */
8959               return t;
8960
8961             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
8962               {
8963                 int quals;
8964                 gcc_assert (TYPE_P (arg));
8965
8966                 /* cv-quals from the template are discarded when
8967                    substituting in a function or reference type.  */
8968                 if (TREE_CODE (arg) == FUNCTION_TYPE
8969                     || TREE_CODE (arg) == METHOD_TYPE
8970                     || TREE_CODE (arg) == REFERENCE_TYPE)
8971                   quals = cp_type_quals (arg);
8972                 else
8973                   quals = cp_type_quals (arg) | cp_type_quals (t);
8974                   
8975                 return cp_build_qualified_type_real
8976                   (arg, quals, complain | tf_ignore_bad_quals);
8977               }
8978             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
8979               {
8980                 /* We are processing a type constructed from a
8981                    template template parameter.  */
8982                 tree argvec = tsubst (TYPE_TI_ARGS (t),
8983                                       args, complain, in_decl);
8984                 if (argvec == error_mark_node)
8985                   return error_mark_node;
8986
8987                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
8988                    are resolving nested-types in the signature of a
8989                    member function templates.  Otherwise ARG is a
8990                    TEMPLATE_DECL and is the real template to be
8991                    instantiated.  */
8992                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
8993                   arg = TYPE_NAME (arg);
8994
8995                 r = lookup_template_class (arg,
8996                                            argvec, in_decl,
8997                                            DECL_CONTEXT (arg),
8998                                             /*entering_scope=*/0,
8999                                            complain);
9000                 return cp_build_qualified_type_real
9001                   (r, TYPE_QUALS (t), complain);
9002               }
9003             else
9004               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9005               return arg;
9006           }
9007
9008         if (level == 1)
9009           /* This can happen during the attempted tsubst'ing in
9010              unify.  This means that we don't yet have any information
9011              about the template parameter in question.  */
9012           return t;
9013
9014         /* If we get here, we must have been looking at a parm for a
9015            more deeply nested template.  Make a new version of this
9016            template parameter, but with a lower level.  */
9017         switch (TREE_CODE (t))
9018           {
9019           case TEMPLATE_TYPE_PARM:
9020           case TEMPLATE_TEMPLATE_PARM:
9021           case BOUND_TEMPLATE_TEMPLATE_PARM:
9022             if (cp_type_quals (t))
9023               {
9024                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9025                 r = cp_build_qualified_type_real
9026                   (r, cp_type_quals (t),
9027                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9028                                ? tf_ignore_bad_quals : 0));
9029               }
9030             else
9031               {
9032                 r = copy_type (t);
9033                 TEMPLATE_TYPE_PARM_INDEX (r)
9034                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9035                                                 r, levels, args, complain);
9036                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9037                 TYPE_MAIN_VARIANT (r) = r;
9038                 TYPE_POINTER_TO (r) = NULL_TREE;
9039                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9040
9041                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9042                   /* We have reduced the level of the template
9043                      template parameter, but not the levels of its
9044                      template parameters, so canonical_type_parameter
9045                      will not be able to find the canonical template
9046                      template parameter for this level. Thus, we
9047                      require structural equality checking to compare
9048                      TEMPLATE_TEMPLATE_PARMs. */
9049                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9050                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9051                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9052                 else
9053                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9054
9055                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9056                   {
9057                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9058                                           complain, in_decl);
9059                     if (argvec == error_mark_node)
9060                       return error_mark_node;
9061
9062                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9063                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9064                   }
9065               }
9066             break;
9067
9068           case TEMPLATE_PARM_INDEX:
9069             r = reduce_template_parm_level (t, type, levels, args, complain);
9070             break;
9071
9072           default:
9073             gcc_unreachable ();
9074           }
9075
9076         return r;
9077       }
9078
9079     case TREE_LIST:
9080       {
9081         tree purpose, value, chain;
9082
9083         if (t == void_list_node)
9084           return t;
9085
9086         purpose = TREE_PURPOSE (t);
9087         if (purpose)
9088           {
9089             purpose = tsubst (purpose, args, complain, in_decl);
9090             if (purpose == error_mark_node)
9091               return error_mark_node;
9092           }
9093         value = TREE_VALUE (t);
9094         if (value)
9095           {
9096             value = tsubst (value, args, complain, in_decl);
9097             if (value == error_mark_node)
9098               return error_mark_node;
9099           }
9100         chain = TREE_CHAIN (t);
9101         if (chain && chain != void_type_node)
9102           {
9103             chain = tsubst (chain, args, complain, in_decl);
9104             if (chain == error_mark_node)
9105               return error_mark_node;
9106           }
9107         if (purpose == TREE_PURPOSE (t)
9108             && value == TREE_VALUE (t)
9109             && chain == TREE_CHAIN (t))
9110           return t;
9111         return hash_tree_cons (purpose, value, chain);
9112       }
9113
9114     case TREE_BINFO:
9115       /* We should never be tsubsting a binfo.  */
9116       gcc_unreachable ();
9117
9118     case TREE_VEC:
9119       /* A vector of template arguments.  */
9120       gcc_assert (!type);
9121       return tsubst_template_args (t, args, complain, in_decl);
9122
9123     case POINTER_TYPE:
9124     case REFERENCE_TYPE:
9125       {
9126         enum tree_code code;
9127
9128         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9129           return t;
9130
9131         code = TREE_CODE (t);
9132
9133
9134         /* [temp.deduct]
9135
9136            Type deduction may fail for any of the following
9137            reasons:
9138
9139            -- Attempting to create a pointer to reference type.
9140            -- Attempting to create a reference to a reference type or
9141               a reference to void.
9142
9143           Core issue 106 says that creating a reference to a reference
9144           during instantiation is no longer a cause for failure. We
9145           only enforce this check in strict C++98 mode.  */
9146         if ((TREE_CODE (type) == REFERENCE_TYPE
9147              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9148             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9149           {
9150             static location_t last_loc;
9151
9152             /* We keep track of the last time we issued this error
9153                message to avoid spewing a ton of messages during a
9154                single bad template instantiation.  */
9155             if (complain & tf_error
9156 #ifdef USE_MAPPED_LOCATION
9157                 && last_loc != input_location
9158 #else
9159                 && (last_loc.line != input_line
9160                     || last_loc.file != input_filename)
9161 #endif
9162                   )
9163               {
9164                 if (TREE_CODE (type) == VOID_TYPE)
9165                   error ("forming reference to void");
9166                 else
9167                   error ("forming %s to reference type %qT",
9168                          (code == POINTER_TYPE) ? "pointer" : "reference",
9169                          type);
9170                 last_loc = input_location;
9171               }
9172
9173             return error_mark_node;
9174           }
9175         else if (code == POINTER_TYPE)
9176           {
9177             r = build_pointer_type (type);
9178             if (TREE_CODE (type) == METHOD_TYPE)
9179               r = build_ptrmemfunc_type (r);
9180           }
9181         else if (TREE_CODE (type) == REFERENCE_TYPE)
9182           /* In C++0x, during template argument substitution, when there is an
9183              attempt to create a reference to a reference type, reference
9184              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9185
9186              "If a template-argument for a template-parameter T names a type
9187              that is a reference to a type A, an attempt to create the type
9188              'lvalue reference to cv T' creates the type 'lvalue reference to
9189              A,' while an attempt to create the type type rvalue reference to
9190              cv T' creates the type T"
9191           */
9192           r = cp_build_reference_type
9193               (TREE_TYPE (type),
9194                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9195         else
9196           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9197         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9198
9199         if (r != error_mark_node)
9200           /* Will this ever be needed for TYPE_..._TO values?  */
9201           layout_type (r);
9202
9203         return r;
9204       }
9205     case OFFSET_TYPE:
9206       {
9207         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9208         if (r == error_mark_node || !IS_AGGR_TYPE (r))
9209           {
9210             /* [temp.deduct]
9211
9212                Type deduction may fail for any of the following
9213                reasons:
9214
9215                -- Attempting to create "pointer to member of T" when T
9216                   is not a class type.  */
9217             if (complain & tf_error)
9218               error ("creating pointer to member of non-class type %qT", r);
9219             return error_mark_node;
9220           }
9221         if (TREE_CODE (type) == REFERENCE_TYPE)
9222           {
9223             if (complain & tf_error)
9224               error ("creating pointer to member reference type %qT", type);
9225             return error_mark_node;
9226           }
9227         if (TREE_CODE (type) == VOID_TYPE)
9228           {
9229             if (complain & tf_error)
9230               error ("creating pointer to member of type void");
9231             return error_mark_node;
9232           }
9233         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
9234         if (TREE_CODE (type) == FUNCTION_TYPE)
9235           {
9236             /* The type of the implicit object parameter gets its
9237                cv-qualifiers from the FUNCTION_TYPE. */
9238             tree method_type;
9239             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
9240                                                       cp_type_quals (type));
9241             tree memptr;
9242             method_type = build_method_type_directly (this_type,
9243                                                       TREE_TYPE (type),
9244                                                       TYPE_ARG_TYPES (type));
9245             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
9246             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
9247                                                  complain);
9248           }
9249         else
9250           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
9251                                                TYPE_QUALS (t),
9252                                                complain);
9253       }
9254     case FUNCTION_TYPE:
9255     case METHOD_TYPE:
9256       {
9257         tree fntype;
9258         tree specs;
9259         fntype = tsubst_function_type (t, args, complain, in_decl);
9260         if (fntype == error_mark_node)
9261           return error_mark_node;
9262
9263         /* Substitute the exception specification.  */
9264         specs = tsubst_exception_specification (t, args, complain,
9265                                                 in_decl);
9266         if (specs == error_mark_node)
9267           return error_mark_node;
9268         if (specs)
9269           fntype = build_exception_variant (fntype, specs);
9270         return fntype;
9271       }
9272     case ARRAY_TYPE:
9273       {
9274         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
9275         if (domain == error_mark_node)
9276           return error_mark_node;
9277
9278         /* As an optimization, we avoid regenerating the array type if
9279            it will obviously be the same as T.  */
9280         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
9281           return t;
9282
9283         /* These checks should match the ones in grokdeclarator.
9284
9285            [temp.deduct]
9286
9287            The deduction may fail for any of the following reasons:
9288
9289            -- Attempting to create an array with an element type that
9290               is void, a function type, or a reference type, or [DR337]
9291               an abstract class type.  */
9292         if (TREE_CODE (type) == VOID_TYPE
9293             || TREE_CODE (type) == FUNCTION_TYPE
9294             || TREE_CODE (type) == REFERENCE_TYPE)
9295           {
9296             if (complain & tf_error)
9297               error ("creating array of %qT", type);
9298             return error_mark_node;
9299           }
9300         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
9301           {
9302             if (complain & tf_error)
9303               error ("creating array of %qT, which is an abstract class type",
9304                      type);
9305             return error_mark_node;
9306           }
9307
9308         r = build_cplus_array_type (type, domain);
9309
9310         if (TYPE_USER_ALIGN (t))
9311           {
9312             TYPE_ALIGN (r) = TYPE_ALIGN (t);
9313             TYPE_USER_ALIGN (r) = 1;
9314           }
9315
9316         return r;
9317       }
9318
9319     case PLUS_EXPR:
9320     case MINUS_EXPR:
9321       {
9322         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9323         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9324
9325         if (e1 == error_mark_node || e2 == error_mark_node)
9326           return error_mark_node;
9327
9328         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
9329       }
9330
9331     case NEGATE_EXPR:
9332     case NOP_EXPR:
9333       {
9334         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9335         if (e == error_mark_node)
9336           return error_mark_node;
9337
9338         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
9339       }
9340
9341     case TYPENAME_TYPE:
9342       {
9343         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9344                                      in_decl, /*entering_scope=*/1);
9345         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
9346                               complain, in_decl);
9347
9348         if (ctx == error_mark_node || f == error_mark_node)
9349           return error_mark_node;
9350
9351         if (!IS_AGGR_TYPE (ctx))
9352           {
9353             if (complain & tf_error)
9354               error ("%qT is not a class, struct, or union type", ctx);
9355             return error_mark_node;
9356           }
9357         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
9358           {
9359             /* Normally, make_typename_type does not require that the CTX
9360                have complete type in order to allow things like:
9361
9362                  template <class T> struct S { typename S<T>::X Y; };
9363
9364                But, such constructs have already been resolved by this
9365                point, so here CTX really should have complete type, unless
9366                it's a partial instantiation.  */
9367             ctx = complete_type (ctx);
9368             if (!COMPLETE_TYPE_P (ctx))
9369               {
9370                 if (complain & tf_error)
9371                   cxx_incomplete_type_error (NULL_TREE, ctx);
9372                 return error_mark_node;
9373               }
9374           }
9375
9376         f = make_typename_type (ctx, f, typename_type,
9377                                 (complain & tf_error) | tf_keep_type_decl);
9378         if (f == error_mark_node)
9379           return f;
9380         if (TREE_CODE (f) == TYPE_DECL)
9381           {
9382             complain |= tf_ignore_bad_quals;
9383             f = TREE_TYPE (f);
9384           }
9385
9386         if (TREE_CODE (f) != TYPENAME_TYPE)
9387           {
9388             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
9389               error ("%qT resolves to %qT, which is not an enumeration type",
9390                      t, f);
9391             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
9392               error ("%qT resolves to %qT, which is is not a class type",
9393                      t, f);
9394           }
9395
9396         return cp_build_qualified_type_real
9397           (f, cp_type_quals (f) | cp_type_quals (t), complain);
9398       }
9399
9400     case UNBOUND_CLASS_TEMPLATE:
9401       {
9402         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9403                                      in_decl, /*entering_scope=*/1);
9404         tree name = TYPE_IDENTIFIER (t);
9405         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
9406
9407         if (ctx == error_mark_node || name == error_mark_node)
9408           return error_mark_node;
9409
9410         if (parm_list)
9411           parm_list = tsubst_template_parms (parm_list, args, complain);
9412         return make_unbound_class_template (ctx, name, parm_list, complain);
9413       }
9414
9415     case INDIRECT_REF:
9416     case ADDR_EXPR:
9417     case CALL_EXPR:
9418       gcc_unreachable ();
9419
9420     case ARRAY_REF:
9421       {
9422         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9423         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
9424                                /*integral_constant_expression_p=*/false);
9425         if (e1 == error_mark_node || e2 == error_mark_node)
9426           return error_mark_node;
9427
9428         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
9429       }
9430
9431     case SCOPE_REF:
9432       {
9433         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9434         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9435         if (e1 == error_mark_node || e2 == error_mark_node)
9436           return error_mark_node;
9437
9438         return build_qualified_name (/*type=*/NULL_TREE,
9439                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
9440       }
9441
9442     case TYPEOF_TYPE:
9443       {
9444         tree type;
9445
9446         type = finish_typeof (tsubst_expr 
9447                               (TYPEOF_TYPE_EXPR (t), args,
9448                                complain, in_decl,
9449                                /*integral_constant_expression_p=*/false));
9450         return cp_build_qualified_type_real (type,
9451                                              cp_type_quals (t)
9452                                              | cp_type_quals (type),
9453                                              complain);
9454       }
9455
9456     case DECLTYPE_TYPE:
9457       {
9458         tree type;
9459
9460         type = 
9461           finish_decltype_type (tsubst_expr 
9462                                 (DECLTYPE_TYPE_EXPR (t), args,
9463                                  complain, in_decl,
9464                                  /*integral_constant_expression_p=*/false),
9465                                 DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
9466         return cp_build_qualified_type_real (type,
9467                                              cp_type_quals (t)
9468                                              | cp_type_quals (type),
9469                                              complain);
9470       }
9471
9472     case TYPE_ARGUMENT_PACK:
9473     case NONTYPE_ARGUMENT_PACK:
9474       {
9475         tree r = make_node (TREE_CODE (t));
9476         tree packed_out = 
9477           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
9478                                 args,
9479                                 complain,
9480                                 in_decl);
9481         SET_ARGUMENT_PACK_ARGS (r, packed_out);
9482
9483         /* For template nontype argument packs, also substitute into
9484            the type.  */
9485         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
9486           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
9487
9488         return r;
9489       }
9490       break;
9491
9492     default:
9493       sorry ("use of %qs in template",
9494              tree_code_name [(int) TREE_CODE (t)]);
9495       return error_mark_node;
9496     }
9497 }
9498
9499 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
9500    type of the expression on the left-hand side of the "." or "->"
9501    operator.  */
9502
9503 static tree
9504 tsubst_baselink (tree baselink, tree object_type,
9505                  tree args, tsubst_flags_t complain, tree in_decl)
9506 {
9507     tree name;
9508     tree qualifying_scope;
9509     tree fns;
9510     tree optype;
9511     tree template_args = 0;
9512     bool template_id_p = false;
9513
9514     /* A baselink indicates a function from a base class.  Both the
9515        BASELINK_ACCESS_BINFO and the base class referenced may
9516        indicate bases of the template class, rather than the
9517        instantiated class.  In addition, lookups that were not
9518        ambiguous before may be ambiguous now.  Therefore, we perform
9519        the lookup again.  */
9520     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
9521     qualifying_scope = tsubst (qualifying_scope, args,
9522                                complain, in_decl);
9523     fns = BASELINK_FUNCTIONS (baselink);
9524     optype = BASELINK_OPTYPE (baselink);
9525     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
9526       {
9527         template_id_p = true;
9528         template_args = TREE_OPERAND (fns, 1);
9529         fns = TREE_OPERAND (fns, 0);
9530         if (template_args)
9531           template_args = tsubst_template_args (template_args, args,
9532                                                 complain, in_decl);
9533       }
9534     name = DECL_NAME (get_first_fn (fns));
9535     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
9536
9537     /* If lookup found a single function, mark it as used at this
9538        point.  (If it lookup found multiple functions the one selected
9539        later by overload resolution will be marked as used at that
9540        point.)  */
9541     if (BASELINK_P (baselink))
9542       fns = BASELINK_FUNCTIONS (baselink);
9543     if (!template_id_p && !really_overloaded_fn (fns))
9544       mark_used (OVL_CURRENT (fns));
9545
9546     /* Add back the template arguments, if present.  */
9547     if (BASELINK_P (baselink) && template_id_p)
9548       BASELINK_FUNCTIONS (baselink)
9549         = build_nt (TEMPLATE_ID_EXPR,
9550                     BASELINK_FUNCTIONS (baselink),
9551                     template_args);
9552     /* Update the conversion operator type.  */
9553     BASELINK_OPTYPE (baselink) 
9554       = tsubst (optype, args, complain, in_decl);
9555
9556     if (!object_type)
9557       object_type = current_class_type;
9558     return adjust_result_of_qualified_name_lookup (baselink,
9559                                                    qualifying_scope,
9560                                                    object_type);
9561 }
9562
9563 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
9564    true if the qualified-id will be a postfix-expression in-and-of
9565    itself; false if more of the postfix-expression follows the
9566    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
9567    of "&".  */
9568
9569 static tree
9570 tsubst_qualified_id (tree qualified_id, tree args,
9571                      tsubst_flags_t complain, tree in_decl,
9572                      bool done, bool address_p)
9573 {
9574   tree expr;
9575   tree scope;
9576   tree name;
9577   bool is_template;
9578   tree template_args;
9579
9580   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
9581
9582   /* Figure out what name to look up.  */
9583   name = TREE_OPERAND (qualified_id, 1);
9584   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
9585     {
9586       is_template = true;
9587       template_args = TREE_OPERAND (name, 1);
9588       if (template_args)
9589         template_args = tsubst_template_args (template_args, args,
9590                                               complain, in_decl);
9591       name = TREE_OPERAND (name, 0);
9592     }
9593   else
9594     {
9595       is_template = false;
9596       template_args = NULL_TREE;
9597     }
9598
9599   /* Substitute into the qualifying scope.  When there are no ARGS, we
9600      are just trying to simplify a non-dependent expression.  In that
9601      case the qualifying scope may be dependent, and, in any case,
9602      substituting will not help.  */
9603   scope = TREE_OPERAND (qualified_id, 0);
9604   if (args)
9605     {
9606       scope = tsubst (scope, args, complain, in_decl);
9607       expr = tsubst_copy (name, args, complain, in_decl);
9608     }
9609   else
9610     expr = name;
9611
9612   if (dependent_type_p (scope))
9613     return build_qualified_name (/*type=*/NULL_TREE,
9614                                  scope, expr,
9615                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
9616
9617   if (!BASELINK_P (name) && !DECL_P (expr))
9618     {
9619       if (TREE_CODE (expr) == BIT_NOT_EXPR)
9620         /* If this were actually a destructor call, it would have been
9621            parsed as such by the parser.  */
9622         expr = error_mark_node;
9623       else
9624         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
9625       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
9626                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
9627         {
9628           if (complain & tf_error)
9629             {
9630               error ("dependent-name %qE is parsed as a non-type, but "
9631                      "instantiation yields a type", qualified_id);
9632               inform ("say %<typename %E%> if a type is meant", qualified_id);
9633             }
9634           return error_mark_node;
9635         }
9636     }
9637
9638   if (DECL_P (expr))
9639     {
9640       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
9641                                            scope);
9642       /* Remember that there was a reference to this entity.  */
9643       mark_used (expr);
9644     }
9645
9646   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
9647     {
9648       if (complain & tf_error)
9649         qualified_name_lookup_error (scope,
9650                                      TREE_OPERAND (qualified_id, 1),
9651                                      expr);
9652       return error_mark_node;
9653     }
9654
9655   if (is_template)
9656     expr = lookup_template_function (expr, template_args);
9657
9658   if (expr == error_mark_node && complain & tf_error)
9659     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
9660                                  expr);
9661   else if (TYPE_P (scope))
9662     {
9663       expr = (adjust_result_of_qualified_name_lookup
9664               (expr, scope, current_class_type));
9665       expr = (finish_qualified_id_expr
9666               (scope, expr, done, address_p,
9667                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
9668                /*template_arg_p=*/false));
9669     }
9670
9671   /* Expressions do not generally have reference type.  */
9672   if (TREE_CODE (expr) != SCOPE_REF
9673       /* However, if we're about to form a pointer-to-member, we just
9674          want the referenced member referenced.  */
9675       && TREE_CODE (expr) != OFFSET_REF)
9676     expr = convert_from_reference (expr);
9677
9678   return expr;
9679 }
9680
9681 /* Like tsubst, but deals with expressions.  This function just replaces
9682    template parms; to finish processing the resultant expression, use
9683    tsubst_expr.  */
9684
9685 static tree
9686 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9687 {
9688   enum tree_code code;
9689   tree r;
9690
9691   if (t == NULL_TREE || t == error_mark_node)
9692     return t;
9693
9694   code = TREE_CODE (t);
9695
9696   switch (code)
9697     {
9698     case PARM_DECL:
9699       r = retrieve_local_specialization (t);
9700       gcc_assert (r != NULL);
9701       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
9702         r = ARGUMENT_PACK_SELECT_ARG (r);
9703       mark_used (r);
9704       return r;
9705
9706     case CONST_DECL:
9707       {
9708         tree enum_type;
9709         tree v;
9710
9711         if (DECL_TEMPLATE_PARM_P (t))
9712           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
9713         /* There is no need to substitute into namespace-scope
9714            enumerators.  */
9715         if (DECL_NAMESPACE_SCOPE_P (t))
9716           return t;
9717         /* If ARGS is NULL, then T is known to be non-dependent.  */
9718         if (args == NULL_TREE)
9719           return integral_constant_value (t);
9720
9721         /* Unfortunately, we cannot just call lookup_name here.
9722            Consider:
9723
9724              template <int I> int f() {
9725              enum E { a = I };
9726              struct S { void g() { E e = a; } };
9727              };
9728
9729            When we instantiate f<7>::S::g(), say, lookup_name is not
9730            clever enough to find f<7>::a.  */
9731         enum_type
9732           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
9733                               /*entering_scope=*/0);
9734
9735         for (v = TYPE_VALUES (enum_type);
9736              v != NULL_TREE;
9737              v = TREE_CHAIN (v))
9738           if (TREE_PURPOSE (v) == DECL_NAME (t))
9739             return TREE_VALUE (v);
9740
9741           /* We didn't find the name.  That should never happen; if
9742              name-lookup found it during preliminary parsing, we
9743              should find it again here during instantiation.  */
9744         gcc_unreachable ();
9745       }
9746       return t;
9747
9748     case FIELD_DECL:
9749       if (DECL_CONTEXT (t))
9750         {
9751           tree ctx;
9752
9753           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
9754                                   /*entering_scope=*/1);
9755           if (ctx != DECL_CONTEXT (t))
9756             {
9757               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
9758               if (!r)
9759                 {
9760                   if (complain & tf_error)
9761                     error ("using invalid field %qD", t);
9762                   return error_mark_node;
9763                 }
9764               return r;
9765             }
9766         }
9767
9768       return t;
9769
9770     case VAR_DECL:
9771     case FUNCTION_DECL:
9772       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
9773           || local_variable_p (t))
9774         t = tsubst (t, args, complain, in_decl);
9775       mark_used (t);
9776       return t;
9777
9778     case BASELINK:
9779       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
9780
9781     case TEMPLATE_DECL:
9782       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9783         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
9784                        args, complain, in_decl);
9785       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
9786         return tsubst (t, args, complain, in_decl);
9787       else if (DECL_CLASS_SCOPE_P (t)
9788                && uses_template_parms (DECL_CONTEXT (t)))
9789         {
9790           /* Template template argument like the following example need
9791              special treatment:
9792
9793                template <template <class> class TT> struct C {};
9794                template <class T> struct D {
9795                  template <class U> struct E {};
9796                  C<E> c;                                // #1
9797                };
9798                D<int> d;                                // #2
9799
9800              We are processing the template argument `E' in #1 for
9801              the template instantiation #2.  Originally, `E' is a
9802              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
9803              have to substitute this with one having context `D<int>'.  */
9804
9805           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
9806           return lookup_field (context, DECL_NAME(t), 0, false);
9807         }
9808       else
9809         /* Ordinary template template argument.  */
9810         return t;
9811
9812     case CAST_EXPR:
9813     case REINTERPRET_CAST_EXPR:
9814     case CONST_CAST_EXPR:
9815     case STATIC_CAST_EXPR:
9816     case DYNAMIC_CAST_EXPR:
9817     case NOP_EXPR:
9818       return build1
9819         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
9820          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
9821
9822     case SIZEOF_EXPR:
9823       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
9824         {
9825           /* We only want to compute the number of arguments.  */
9826           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
9827                                                 complain, in_decl);
9828           if (expanded == error_mark_node)
9829             return error_mark_node;
9830           return build_int_cst (size_type_node, TREE_VEC_LENGTH (expanded));
9831         }
9832       /* Fall through */
9833
9834     case INDIRECT_REF:
9835     case NEGATE_EXPR:
9836     case TRUTH_NOT_EXPR:
9837     case BIT_NOT_EXPR:
9838     case ADDR_EXPR:
9839     case UNARY_PLUS_EXPR:      /* Unary + */
9840     case ALIGNOF_EXPR:
9841     case ARROW_EXPR:
9842     case THROW_EXPR:
9843     case TYPEID_EXPR:
9844     case REALPART_EXPR:
9845     case IMAGPART_EXPR:
9846       return build1
9847         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
9848          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
9849
9850     case COMPONENT_REF:
9851       {
9852         tree object;
9853         tree name;
9854
9855         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
9856         name = TREE_OPERAND (t, 1);
9857         if (TREE_CODE (name) == BIT_NOT_EXPR)
9858           {
9859             name = tsubst_copy (TREE_OPERAND (name, 0), args,
9860                                 complain, in_decl);
9861             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
9862           }
9863         else if (TREE_CODE (name) == SCOPE_REF
9864                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
9865           {
9866             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
9867                                      complain, in_decl);
9868             name = TREE_OPERAND (name, 1);
9869             name = tsubst_copy (TREE_OPERAND (name, 0), args,
9870                                 complain, in_decl);
9871             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
9872             name = build_qualified_name (/*type=*/NULL_TREE,
9873                                          base, name,
9874                                          /*template_p=*/false);
9875           }
9876         else if (TREE_CODE (name) == BASELINK)
9877           name = tsubst_baselink (name,
9878                                   non_reference (TREE_TYPE (object)),
9879                                   args, complain,
9880                                   in_decl);
9881         else
9882           name = tsubst_copy (name, args, complain, in_decl);
9883         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
9884       }
9885
9886     case PLUS_EXPR:
9887     case MINUS_EXPR:
9888     case MULT_EXPR:
9889     case TRUNC_DIV_EXPR:
9890     case CEIL_DIV_EXPR:
9891     case FLOOR_DIV_EXPR:
9892     case ROUND_DIV_EXPR:
9893     case EXACT_DIV_EXPR:
9894     case BIT_AND_EXPR:
9895     case BIT_IOR_EXPR:
9896     case BIT_XOR_EXPR:
9897     case TRUNC_MOD_EXPR:
9898     case FLOOR_MOD_EXPR:
9899     case TRUTH_ANDIF_EXPR:
9900     case TRUTH_ORIF_EXPR:
9901     case TRUTH_AND_EXPR:
9902     case TRUTH_OR_EXPR:
9903     case RSHIFT_EXPR:
9904     case LSHIFT_EXPR:
9905     case RROTATE_EXPR:
9906     case LROTATE_EXPR:
9907     case EQ_EXPR:
9908     case NE_EXPR:
9909     case MAX_EXPR:
9910     case MIN_EXPR:
9911     case LE_EXPR:
9912     case GE_EXPR:
9913     case LT_EXPR:
9914     case GT_EXPR:
9915     case COMPOUND_EXPR:
9916     case DOTSTAR_EXPR:
9917     case MEMBER_REF:
9918     case PREDECREMENT_EXPR:
9919     case PREINCREMENT_EXPR:
9920     case POSTDECREMENT_EXPR:
9921     case POSTINCREMENT_EXPR:
9922       return build_nt
9923         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9924          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
9925
9926     case SCOPE_REF:
9927       return build_qualified_name (/*type=*/NULL_TREE,
9928                                    tsubst_copy (TREE_OPERAND (t, 0),
9929                                                 args, complain, in_decl),
9930                                    tsubst_copy (TREE_OPERAND (t, 1),
9931                                                 args, complain, in_decl),
9932                                    QUALIFIED_NAME_IS_TEMPLATE (t));
9933
9934     case ARRAY_REF:
9935       return build_nt
9936         (ARRAY_REF,
9937          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9938          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
9939          NULL_TREE, NULL_TREE);
9940
9941     case CALL_EXPR:
9942       {
9943         int n = VL_EXP_OPERAND_LENGTH (t);
9944         tree result = build_vl_exp (CALL_EXPR, n);
9945         int i;
9946         for (i = 0; i < n; i++)
9947           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
9948                                              complain, in_decl);
9949         return result;
9950       }
9951
9952     case COND_EXPR:
9953     case MODOP_EXPR:
9954     case PSEUDO_DTOR_EXPR:
9955       {
9956         r = build_nt
9957           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9958            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
9959            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
9960         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
9961         return r;
9962       }
9963
9964     case NEW_EXPR:
9965       {
9966         r = build_nt
9967         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9968          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
9969          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
9970         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
9971         return r;
9972       }
9973
9974     case DELETE_EXPR:
9975       {
9976         r = build_nt
9977         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
9978          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
9979         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
9980         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
9981         return r;
9982       }
9983
9984     case TEMPLATE_ID_EXPR:
9985       {
9986         /* Substituted template arguments */
9987         tree fn = TREE_OPERAND (t, 0);
9988         tree targs = TREE_OPERAND (t, 1);
9989
9990         fn = tsubst_copy (fn, args, complain, in_decl);
9991         if (targs)
9992           targs = tsubst_template_args (targs, args, complain, in_decl);
9993
9994         return lookup_template_function (fn, targs);
9995       }
9996
9997     case TREE_LIST:
9998       {
9999         tree purpose, value, chain;
10000
10001         if (t == void_list_node)
10002           return t;
10003
10004         purpose = TREE_PURPOSE (t);
10005         if (purpose)
10006           purpose = tsubst_copy (purpose, args, complain, in_decl);
10007         value = TREE_VALUE (t);
10008         if (value)
10009           value = tsubst_copy (value, args, complain, in_decl);
10010         chain = TREE_CHAIN (t);
10011         if (chain && chain != void_type_node)
10012           chain = tsubst_copy (chain, args, complain, in_decl);
10013         if (purpose == TREE_PURPOSE (t)
10014             && value == TREE_VALUE (t)
10015             && chain == TREE_CHAIN (t))
10016           return t;
10017         return tree_cons (purpose, value, chain);
10018       }
10019
10020     case RECORD_TYPE:
10021     case UNION_TYPE:
10022     case ENUMERAL_TYPE:
10023     case INTEGER_TYPE:
10024     case TEMPLATE_TYPE_PARM:
10025     case TEMPLATE_TEMPLATE_PARM:
10026     case BOUND_TEMPLATE_TEMPLATE_PARM:
10027     case TEMPLATE_PARM_INDEX:
10028     case POINTER_TYPE:
10029     case REFERENCE_TYPE:
10030     case OFFSET_TYPE:
10031     case FUNCTION_TYPE:
10032     case METHOD_TYPE:
10033     case ARRAY_TYPE:
10034     case TYPENAME_TYPE:
10035     case UNBOUND_CLASS_TEMPLATE:
10036     case TYPEOF_TYPE:
10037     case DECLTYPE_TYPE:
10038     case TYPE_DECL:
10039       return tsubst (t, args, complain, in_decl);
10040
10041     case IDENTIFIER_NODE:
10042       if (IDENTIFIER_TYPENAME_P (t))
10043         {
10044           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10045           return mangle_conv_op_name_for_type (new_type);
10046         }
10047       else
10048         return t;
10049
10050     case CONSTRUCTOR:
10051       /* This is handled by tsubst_copy_and_build.  */
10052       gcc_unreachable ();
10053
10054     case VA_ARG_EXPR:
10055       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10056                                           in_decl),
10057                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10058
10059     case CLEANUP_POINT_EXPR:
10060       /* We shouldn't have built any of these during initial template
10061          generation.  Instead, they should be built during instantiation
10062          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10063       gcc_unreachable ();
10064
10065     case OFFSET_REF:
10066       mark_used (TREE_OPERAND (t, 1));
10067       return t;
10068
10069     case EXPR_PACK_EXPANSION:
10070       error ("invalid use of pack expansion expression");
10071       return error_mark_node;
10072
10073     case NONTYPE_ARGUMENT_PACK:
10074       error ("use %<...%> to expand argument pack");
10075       return error_mark_node;
10076
10077     default:
10078       return t;
10079     }
10080 }
10081
10082 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10083
10084 static tree
10085 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10086                     tree in_decl)
10087 {
10088   tree new_clauses = NULL, nc, oc;
10089
10090   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10091     {
10092       nc = copy_node (oc);
10093       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10094       new_clauses = nc;
10095
10096       switch (OMP_CLAUSE_CODE (nc))
10097         {
10098         case OMP_CLAUSE_PRIVATE:
10099         case OMP_CLAUSE_SHARED:
10100         case OMP_CLAUSE_FIRSTPRIVATE:
10101         case OMP_CLAUSE_LASTPRIVATE:
10102         case OMP_CLAUSE_REDUCTION:
10103         case OMP_CLAUSE_COPYIN:
10104         case OMP_CLAUSE_COPYPRIVATE:
10105         case OMP_CLAUSE_IF:
10106         case OMP_CLAUSE_NUM_THREADS:
10107         case OMP_CLAUSE_SCHEDULE:
10108           OMP_CLAUSE_OPERAND (nc, 0)
10109             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10110                            in_decl, /*integral_constant_expression_p=*/false);
10111           break;
10112         case OMP_CLAUSE_NOWAIT:
10113         case OMP_CLAUSE_ORDERED:
10114         case OMP_CLAUSE_DEFAULT:
10115           break;
10116         default:
10117           gcc_unreachable ();
10118         }
10119     }
10120
10121   return finish_omp_clauses (nreverse (new_clauses));
10122 }
10123
10124 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10125
10126 static tree
10127 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10128                           tree in_decl)
10129 {
10130 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10131
10132   tree purpose, value, chain;
10133
10134   if (t == NULL)
10135     return t;
10136
10137   if (TREE_CODE (t) != TREE_LIST)
10138     return tsubst_copy_and_build (t, args, complain, in_decl,
10139                                   /*function_p=*/false,
10140                                   /*integral_constant_expression_p=*/false);
10141
10142   if (t == void_list_node)
10143     return t;
10144
10145   purpose = TREE_PURPOSE (t);
10146   if (purpose)
10147     purpose = RECUR (purpose);
10148   value = TREE_VALUE (t);
10149   if (value)
10150     value = RECUR (value);
10151   chain = TREE_CHAIN (t);
10152   if (chain && chain != void_type_node)
10153     chain = RECUR (chain);
10154   return tree_cons (purpose, value, chain);
10155 #undef RECUR
10156 }
10157
10158 /* Like tsubst_copy for expressions, etc. but also does semantic
10159    processing.  */
10160
10161 static tree
10162 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
10163              bool integral_constant_expression_p)
10164 {
10165 #define RECUR(NODE)                             \
10166   tsubst_expr ((NODE), args, complain, in_decl, \
10167                integral_constant_expression_p)
10168
10169   tree stmt, tmp;
10170
10171   if (t == NULL_TREE || t == error_mark_node)
10172     return t;
10173
10174   if (EXPR_HAS_LOCATION (t))
10175     input_location = EXPR_LOCATION (t);
10176   if (STATEMENT_CODE_P (TREE_CODE (t)))
10177     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
10178
10179   switch (TREE_CODE (t))
10180     {
10181     case STATEMENT_LIST:
10182       {
10183         tree_stmt_iterator i;
10184         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
10185           RECUR (tsi_stmt (i));
10186         break;
10187       }
10188
10189     case CTOR_INITIALIZER:
10190       finish_mem_initializers (tsubst_initializer_list
10191                                (TREE_OPERAND (t, 0), args));
10192       break;
10193
10194     case RETURN_EXPR:
10195       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
10196       break;
10197
10198     case EXPR_STMT:
10199       tmp = RECUR (EXPR_STMT_EXPR (t));
10200       if (EXPR_STMT_STMT_EXPR_RESULT (t))
10201         finish_stmt_expr_expr (tmp, cur_stmt_expr);
10202       else
10203         finish_expr_stmt (tmp);
10204       break;
10205
10206     case USING_STMT:
10207       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
10208       break;
10209
10210     case DECL_EXPR:
10211       {
10212         tree decl;
10213         tree init;
10214
10215         decl = DECL_EXPR_DECL (t);
10216         if (TREE_CODE (decl) == LABEL_DECL)
10217           finish_label_decl (DECL_NAME (decl));
10218         else if (TREE_CODE (decl) == USING_DECL)
10219           {
10220             tree scope = USING_DECL_SCOPE (decl);
10221             tree name = DECL_NAME (decl);
10222             tree decl;
10223
10224             scope = RECUR (scope);
10225             decl = lookup_qualified_name (scope, name,
10226                                           /*is_type_p=*/false,
10227                                           /*complain=*/false);
10228             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
10229               qualified_name_lookup_error (scope, name, decl);
10230             else
10231               do_local_using_decl (decl, scope, name);
10232           }
10233         else
10234           {
10235             init = DECL_INITIAL (decl);
10236             decl = tsubst (decl, args, complain, in_decl);
10237             if (decl != error_mark_node)
10238               {
10239                 /* By marking the declaration as instantiated, we avoid
10240                    trying to instantiate it.  Since instantiate_decl can't
10241                    handle local variables, and since we've already done
10242                    all that needs to be done, that's the right thing to
10243                    do.  */
10244                 if (TREE_CODE (decl) == VAR_DECL)
10245                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10246                 if (TREE_CODE (decl) == VAR_DECL
10247                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
10248                   /* Anonymous aggregates are a special case.  */
10249                   finish_anon_union (decl);
10250                 else
10251                   {
10252                     maybe_push_decl (decl);
10253                     if (TREE_CODE (decl) == VAR_DECL
10254                         && DECL_PRETTY_FUNCTION_P (decl))
10255                       {
10256                         /* For __PRETTY_FUNCTION__ we have to adjust the
10257                            initializer.  */
10258                         const char *const name
10259                           = cxx_printable_name (current_function_decl, 2);
10260                         init = cp_fname_init (name, &TREE_TYPE (decl));
10261                       }
10262                     else
10263                       {
10264                         tree t = RECUR (init);
10265
10266                         if (init && !t)
10267                           /* If we had an initializer but it
10268                              instantiated to nothing,
10269                              value-initialize the object.  This will
10270                              only occur when the initializer was a
10271                              pack expansion where the parameter packs
10272                              used in that expansion were of length
10273                              zero.  */
10274                           init = build_default_init (TREE_TYPE (decl),
10275                                                      NULL_TREE);
10276                         else
10277                           init = t;
10278                       }
10279
10280                     finish_decl (decl, init, NULL_TREE);
10281                   }
10282               }
10283           }
10284
10285         /* A DECL_EXPR can also be used as an expression, in the condition
10286            clause of an if/for/while construct.  */
10287         return decl;
10288       }
10289
10290     case FOR_STMT:
10291       stmt = begin_for_stmt ();
10292                           RECUR (FOR_INIT_STMT (t));
10293       finish_for_init_stmt (stmt);
10294       tmp = RECUR (FOR_COND (t));
10295       finish_for_cond (tmp, stmt);
10296       tmp = RECUR (FOR_EXPR (t));
10297       finish_for_expr (tmp, stmt);
10298       RECUR (FOR_BODY (t));
10299       finish_for_stmt (stmt);
10300       break;
10301
10302     case WHILE_STMT:
10303       stmt = begin_while_stmt ();
10304       tmp = RECUR (WHILE_COND (t));
10305       finish_while_stmt_cond (tmp, stmt);
10306       RECUR (WHILE_BODY (t));
10307       finish_while_stmt (stmt);
10308       break;
10309
10310     case DO_STMT:
10311       stmt = begin_do_stmt ();
10312       RECUR (DO_BODY (t));
10313       finish_do_body (stmt);
10314       tmp = RECUR (DO_COND (t));
10315       finish_do_stmt (tmp, stmt);
10316       break;
10317
10318     case IF_STMT:
10319       stmt = begin_if_stmt ();
10320       tmp = RECUR (IF_COND (t));
10321       finish_if_stmt_cond (tmp, stmt);
10322       RECUR (THEN_CLAUSE (t));
10323       finish_then_clause (stmt);
10324
10325       if (ELSE_CLAUSE (t))
10326         {
10327           begin_else_clause (stmt);
10328           RECUR (ELSE_CLAUSE (t));
10329           finish_else_clause (stmt);
10330         }
10331
10332       finish_if_stmt (stmt);
10333       break;
10334
10335     case BIND_EXPR:
10336       if (BIND_EXPR_BODY_BLOCK (t))
10337         stmt = begin_function_body ();
10338       else
10339         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
10340                                     ? BCS_TRY_BLOCK : 0);
10341
10342       RECUR (BIND_EXPR_BODY (t));
10343
10344       if (BIND_EXPR_BODY_BLOCK (t))
10345         finish_function_body (stmt);
10346       else
10347         finish_compound_stmt (stmt);
10348       break;
10349
10350     case BREAK_STMT:
10351       finish_break_stmt ();
10352       break;
10353
10354     case CONTINUE_STMT:
10355       finish_continue_stmt ();
10356       break;
10357
10358     case SWITCH_STMT:
10359       stmt = begin_switch_stmt ();
10360       tmp = RECUR (SWITCH_STMT_COND (t));
10361       finish_switch_cond (tmp, stmt);
10362       RECUR (SWITCH_STMT_BODY (t));
10363       finish_switch_stmt (stmt);
10364       break;
10365
10366     case CASE_LABEL_EXPR:
10367       finish_case_label (RECUR (CASE_LOW (t)),
10368                          RECUR (CASE_HIGH (t)));
10369       break;
10370
10371     case LABEL_EXPR:
10372       finish_label_stmt (DECL_NAME (LABEL_EXPR_LABEL (t)));
10373       break;
10374
10375     case GOTO_EXPR:
10376       tmp = GOTO_DESTINATION (t);
10377       if (TREE_CODE (tmp) != LABEL_DECL)
10378         /* Computed goto's must be tsubst'd into.  On the other hand,
10379            non-computed gotos must not be; the identifier in question
10380            will have no binding.  */
10381         tmp = RECUR (tmp);
10382       else
10383         tmp = DECL_NAME (tmp);
10384       finish_goto_stmt (tmp);
10385       break;
10386
10387     case ASM_EXPR:
10388       tmp = finish_asm_stmt
10389         (ASM_VOLATILE_P (t),
10390          RECUR (ASM_STRING (t)),
10391          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
10392          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
10393          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
10394       {
10395         tree asm_expr = tmp;
10396         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
10397           asm_expr = TREE_OPERAND (asm_expr, 0);
10398         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
10399       }
10400       break;
10401
10402     case TRY_BLOCK:
10403       if (CLEANUP_P (t))
10404         {
10405           stmt = begin_try_block ();
10406           RECUR (TRY_STMTS (t));
10407           finish_cleanup_try_block (stmt);
10408           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
10409         }
10410       else
10411         {
10412           tree compound_stmt = NULL_TREE;
10413
10414           if (FN_TRY_BLOCK_P (t))
10415             stmt = begin_function_try_block (&compound_stmt);
10416           else
10417             stmt = begin_try_block ();
10418
10419           RECUR (TRY_STMTS (t));
10420
10421           if (FN_TRY_BLOCK_P (t))
10422             finish_function_try_block (stmt);
10423           else
10424             finish_try_block (stmt);
10425
10426           RECUR (TRY_HANDLERS (t));
10427           if (FN_TRY_BLOCK_P (t))
10428             finish_function_handler_sequence (stmt, compound_stmt);
10429           else
10430             finish_handler_sequence (stmt);
10431         }
10432       break;
10433
10434     case HANDLER:
10435       {
10436         tree decl = HANDLER_PARMS (t);
10437
10438         if (decl)
10439           {
10440             decl = tsubst (decl, args, complain, in_decl);
10441             /* Prevent instantiate_decl from trying to instantiate
10442                this variable.  We've already done all that needs to be
10443                done.  */
10444             if (decl != error_mark_node)
10445               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10446           }
10447         stmt = begin_handler ();
10448         finish_handler_parms (decl, stmt);
10449         RECUR (HANDLER_BODY (t));
10450         finish_handler (stmt);
10451       }
10452       break;
10453
10454     case TAG_DEFN:
10455       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
10456       break;
10457
10458     case STATIC_ASSERT:
10459       {
10460         tree condition = 
10461           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
10462                        args,
10463                        complain, in_decl,
10464                        /*integral_constant_expression_p=*/true);
10465         finish_static_assert (condition,
10466                               STATIC_ASSERT_MESSAGE (t),
10467                               STATIC_ASSERT_SOURCE_LOCATION (t),
10468                               /*member_p=*/false);
10469       }
10470       break;
10471
10472     case OMP_PARALLEL:
10473       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
10474                                 args, complain, in_decl);
10475       stmt = begin_omp_parallel ();
10476       RECUR (OMP_PARALLEL_BODY (t));
10477       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
10478         = OMP_PARALLEL_COMBINED (t);
10479       break;
10480
10481     case OMP_FOR:
10482       {
10483         tree clauses, decl, init, cond, incr, body, pre_body;
10484
10485         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
10486                                       args, complain, in_decl);
10487         init = OMP_FOR_INIT (t);
10488         gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10489         decl = RECUR (TREE_OPERAND (init, 0));
10490         init = RECUR (TREE_OPERAND (init, 1));
10491         cond = RECUR (OMP_FOR_COND (t));
10492         incr = RECUR (OMP_FOR_INCR (t));
10493
10494         stmt = begin_omp_structured_block ();
10495
10496         pre_body = push_stmt_list ();
10497         RECUR (OMP_FOR_PRE_BODY (t));
10498         pre_body = pop_stmt_list (pre_body);
10499
10500         body = push_stmt_list ();
10501         RECUR (OMP_FOR_BODY (t));
10502         body = pop_stmt_list (body);
10503
10504         t = finish_omp_for (EXPR_LOCATION (t), decl, init, cond, incr, body,
10505                             pre_body);
10506         if (t)
10507           OMP_FOR_CLAUSES (t) = clauses;
10508
10509         add_stmt (finish_omp_structured_block (stmt));
10510       }
10511       break;
10512
10513     case OMP_SECTIONS:
10514     case OMP_SINGLE:
10515       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
10516       stmt = push_stmt_list ();
10517       RECUR (OMP_BODY (t));
10518       stmt = pop_stmt_list (stmt);
10519
10520       t = copy_node (t);
10521       OMP_BODY (t) = stmt;
10522       OMP_CLAUSES (t) = tmp;
10523       add_stmt (t);
10524       break;
10525
10526     case OMP_SECTION:
10527     case OMP_CRITICAL:
10528     case OMP_MASTER:
10529     case OMP_ORDERED:
10530       stmt = push_stmt_list ();
10531       RECUR (OMP_BODY (t));
10532       stmt = pop_stmt_list (stmt);
10533
10534       t = copy_node (t);
10535       OMP_BODY (t) = stmt;
10536       add_stmt (t);
10537       break;
10538
10539     case OMP_ATOMIC:
10540       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
10541       {
10542         tree op1 = TREE_OPERAND (t, 1);
10543         tree lhs = RECUR (TREE_OPERAND (op1, 0));
10544         tree rhs = RECUR (TREE_OPERAND (op1, 1));
10545         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
10546       }
10547       break;
10548
10549     case EXPR_PACK_EXPANSION:
10550       error ("invalid use of pack expansion expression");
10551       return error_mark_node;
10552
10553     case NONTYPE_ARGUMENT_PACK:
10554       error ("use %<...%> to expand argument pack");
10555       return error_mark_node;
10556
10557     default:
10558       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
10559
10560       return tsubst_copy_and_build (t, args, complain, in_decl,
10561                                     /*function_p=*/false,
10562                                     integral_constant_expression_p);
10563     }
10564
10565   return NULL_TREE;
10566 #undef RECUR
10567 }
10568
10569 /* T is a postfix-expression that is not being used in a function
10570    call.  Return the substituted version of T.  */
10571
10572 static tree
10573 tsubst_non_call_postfix_expression (tree t, tree args,
10574                                     tsubst_flags_t complain,
10575                                     tree in_decl)
10576 {
10577   if (TREE_CODE (t) == SCOPE_REF)
10578     t = tsubst_qualified_id (t, args, complain, in_decl,
10579                              /*done=*/false, /*address_p=*/false);
10580   else
10581     t = tsubst_copy_and_build (t, args, complain, in_decl,
10582                                /*function_p=*/false,
10583                                /*integral_constant_expression_p=*/false);
10584
10585   return t;
10586 }
10587
10588 /* Like tsubst but deals with expressions and performs semantic
10589    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
10590
10591 tree
10592 tsubst_copy_and_build (tree t,
10593                        tree args,
10594                        tsubst_flags_t complain,
10595                        tree in_decl,
10596                        bool function_p,
10597                        bool integral_constant_expression_p)
10598 {
10599 #define RECUR(NODE)                                             \
10600   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
10601                          /*function_p=*/false,                  \
10602                          integral_constant_expression_p)
10603
10604   tree op1;
10605
10606   if (t == NULL_TREE || t == error_mark_node)
10607     return t;
10608
10609   switch (TREE_CODE (t))
10610     {
10611     case USING_DECL:
10612       t = DECL_NAME (t);
10613       /* Fall through.  */
10614     case IDENTIFIER_NODE:
10615       {
10616         tree decl;
10617         cp_id_kind idk;
10618         bool non_integral_constant_expression_p;
10619         const char *error_msg;
10620
10621         if (IDENTIFIER_TYPENAME_P (t))
10622           {
10623             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10624             t = mangle_conv_op_name_for_type (new_type);
10625           }
10626
10627         /* Look up the name.  */
10628         decl = lookup_name (t);
10629
10630         /* By convention, expressions use ERROR_MARK_NODE to indicate
10631            failure, not NULL_TREE.  */
10632         if (decl == NULL_TREE)
10633           decl = error_mark_node;
10634
10635         decl = finish_id_expression (t, decl, NULL_TREE,
10636                                      &idk,
10637                                      integral_constant_expression_p,
10638                                      /*allow_non_integral_constant_expression_p=*/false,
10639                                      &non_integral_constant_expression_p,
10640                                      /*template_p=*/false,
10641                                      /*done=*/true,
10642                                      /*address_p=*/false,
10643                                      /*template_arg_p=*/false,
10644                                      &error_msg);
10645         if (error_msg)
10646           error (error_msg);
10647         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
10648           decl = unqualified_name_lookup_error (decl);
10649         return decl;
10650       }
10651
10652     case TEMPLATE_ID_EXPR:
10653       {
10654         tree object;
10655         tree template = RECUR (TREE_OPERAND (t, 0));
10656         tree targs = TREE_OPERAND (t, 1);
10657
10658         if (targs)
10659           targs = tsubst_template_args (targs, args, complain, in_decl);
10660
10661         if (TREE_CODE (template) == COMPONENT_REF)
10662           {
10663             object = TREE_OPERAND (template, 0);
10664             template = TREE_OPERAND (template, 1);
10665           }
10666         else
10667           object = NULL_TREE;
10668         template = lookup_template_function (template, targs);
10669
10670         if (object)
10671           return build3 (COMPONENT_REF, TREE_TYPE (template),
10672                          object, template, NULL_TREE);
10673         else
10674           return baselink_for_fns (template);
10675       }
10676
10677     case INDIRECT_REF:
10678       {
10679         tree r = RECUR (TREE_OPERAND (t, 0));
10680
10681         if (REFERENCE_REF_P (t))
10682           {
10683             /* A type conversion to reference type will be enclosed in
10684                such an indirect ref, but the substitution of the cast
10685                will have also added such an indirect ref.  */
10686             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
10687               r = convert_from_reference (r);
10688           }
10689         else
10690           r = build_x_indirect_ref (r, "unary *");
10691         return r;
10692       }
10693
10694     case NOP_EXPR:
10695       return build_nop
10696         (tsubst (TREE_TYPE (t), args, complain, in_decl),
10697          RECUR (TREE_OPERAND (t, 0)));
10698
10699     case CAST_EXPR:
10700     case REINTERPRET_CAST_EXPR:
10701     case CONST_CAST_EXPR:
10702     case DYNAMIC_CAST_EXPR:
10703     case STATIC_CAST_EXPR:
10704       {
10705         tree type;
10706         tree op;
10707
10708         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10709         if (integral_constant_expression_p
10710             && !cast_valid_in_integral_constant_expression_p (type))
10711           {
10712             error ("a cast to a type other than an integral or "
10713                    "enumeration type cannot appear in a constant-expression");
10714             return error_mark_node; 
10715           }
10716
10717         op = RECUR (TREE_OPERAND (t, 0));
10718
10719         switch (TREE_CODE (t))
10720           {
10721           case CAST_EXPR:
10722             return build_functional_cast (type, op);
10723           case REINTERPRET_CAST_EXPR:
10724             return build_reinterpret_cast (type, op);
10725           case CONST_CAST_EXPR:
10726             return build_const_cast (type, op);
10727           case DYNAMIC_CAST_EXPR:
10728             return build_dynamic_cast (type, op);
10729           case STATIC_CAST_EXPR:
10730             return build_static_cast (type, op);
10731           default:
10732             gcc_unreachable ();
10733           }
10734       }
10735
10736     case POSTDECREMENT_EXPR:
10737     case POSTINCREMENT_EXPR:
10738       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10739                                                 args, complain, in_decl);
10740       return build_x_unary_op (TREE_CODE (t), op1);
10741
10742     case PREDECREMENT_EXPR:
10743     case PREINCREMENT_EXPR:
10744     case NEGATE_EXPR:
10745     case BIT_NOT_EXPR:
10746     case ABS_EXPR:
10747     case TRUTH_NOT_EXPR:
10748     case UNARY_PLUS_EXPR:  /* Unary + */
10749     case REALPART_EXPR:
10750     case IMAGPART_EXPR:
10751       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)));
10752
10753     case ADDR_EXPR:
10754       op1 = TREE_OPERAND (t, 0);
10755       if (TREE_CODE (op1) == SCOPE_REF)
10756         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
10757                                    /*done=*/true, /*address_p=*/true);
10758       else
10759         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
10760                                                   in_decl);
10761       if (TREE_CODE (op1) == LABEL_DECL)
10762         return finish_label_address_expr (DECL_NAME (op1));
10763       return build_x_unary_op (ADDR_EXPR, op1);
10764
10765     case PLUS_EXPR:
10766     case MINUS_EXPR:
10767     case MULT_EXPR:
10768     case TRUNC_DIV_EXPR:
10769     case CEIL_DIV_EXPR:
10770     case FLOOR_DIV_EXPR:
10771     case ROUND_DIV_EXPR:
10772     case EXACT_DIV_EXPR:
10773     case BIT_AND_EXPR:
10774     case BIT_IOR_EXPR:
10775     case BIT_XOR_EXPR:
10776     case TRUNC_MOD_EXPR:
10777     case FLOOR_MOD_EXPR:
10778     case TRUTH_ANDIF_EXPR:
10779     case TRUTH_ORIF_EXPR:
10780     case TRUTH_AND_EXPR:
10781     case TRUTH_OR_EXPR:
10782     case RSHIFT_EXPR:
10783     case LSHIFT_EXPR:
10784     case RROTATE_EXPR:
10785     case LROTATE_EXPR:
10786     case EQ_EXPR:
10787     case NE_EXPR:
10788     case MAX_EXPR:
10789     case MIN_EXPR:
10790     case LE_EXPR:
10791     case GE_EXPR:
10792     case LT_EXPR:
10793     case GT_EXPR:
10794     case MEMBER_REF:
10795     case DOTSTAR_EXPR:
10796       return build_x_binary_op
10797         (TREE_CODE (t),
10798          RECUR (TREE_OPERAND (t, 0)),
10799          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
10800           ? ERROR_MARK
10801           : TREE_CODE (TREE_OPERAND (t, 0))),
10802          RECUR (TREE_OPERAND (t, 1)),
10803          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
10804           ? ERROR_MARK
10805           : TREE_CODE (TREE_OPERAND (t, 1))),
10806          /*overloaded_p=*/NULL);
10807
10808     case SCOPE_REF:
10809       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
10810                                   /*address_p=*/false);
10811     case ARRAY_REF:
10812       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10813                                                 args, complain, in_decl);
10814       return build_x_binary_op (ARRAY_REF, op1,
10815                                 (TREE_NO_WARNING (TREE_OPERAND (t, 0))
10816                                  ? ERROR_MARK
10817                                  : TREE_CODE (TREE_OPERAND (t, 0))),
10818                                 RECUR (TREE_OPERAND (t, 1)),
10819                                 (TREE_NO_WARNING (TREE_OPERAND (t, 1))
10820                                  ? ERROR_MARK
10821                                  : TREE_CODE (TREE_OPERAND (t, 1))),
10822                                 /*overloaded_p=*/NULL);
10823
10824     case SIZEOF_EXPR:
10825       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10826         {
10827           /* We only want to compute the number of arguments.  */
10828           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10829                                                 complain, in_decl);
10830           if (expanded == error_mark_node)
10831             return error_mark_node;
10832           return build_int_cst (size_type_node, TREE_VEC_LENGTH (expanded));
10833         }
10834       /* Fall through */
10835       
10836     case ALIGNOF_EXPR:
10837       op1 = TREE_OPERAND (t, 0);
10838       if (!args)
10839         {
10840           /* When there are no ARGS, we are trying to evaluate a
10841              non-dependent expression from the parser.  Trying to do
10842              the substitutions may not work.  */
10843           if (!TYPE_P (op1))
10844             op1 = TREE_TYPE (op1);
10845         }
10846       else
10847         {
10848           ++skip_evaluation;
10849           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
10850                                        /*function_p=*/false,
10851                                        /*integral_constant_expression_p=*/false);
10852           --skip_evaluation;
10853         }
10854       if (TYPE_P (op1))
10855         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), true);
10856       else
10857         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t));
10858
10859     case MODOP_EXPR:
10860       {
10861         tree r = build_x_modify_expr
10862           (RECUR (TREE_OPERAND (t, 0)),
10863            TREE_CODE (TREE_OPERAND (t, 1)),
10864            RECUR (TREE_OPERAND (t, 2)));
10865         /* TREE_NO_WARNING must be set if either the expression was
10866            parenthesized or it uses an operator such as >>= rather
10867            than plain assignment.  In the former case, it was already
10868            set and must be copied.  In the latter case,
10869            build_x_modify_expr sets it and it must not be reset
10870            here.  */
10871         if (TREE_NO_WARNING (t))
10872           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10873         return r;
10874       }
10875
10876     case ARROW_EXPR:
10877       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
10878                                                 args, complain, in_decl);
10879       /* Remember that there was a reference to this entity.  */
10880       if (DECL_P (op1))
10881         mark_used (op1);
10882       return build_x_arrow (op1);
10883
10884     case NEW_EXPR:
10885       {
10886         tree init = RECUR (TREE_OPERAND (t, 3));
10887
10888         if (TREE_OPERAND (t, 3) && !init)
10889           /* If there was an initializer in the the original tree, but
10890              it instantiated to an empty list, then we should pass on
10891              VOID_ZERO_NODE to tell build_new that it was an empty
10892              initializer () rather than no initializer.  This can only
10893              happen when the initializer is a pack expansion whose
10894              parameter packs are of length zero.  */
10895           init = void_zero_node;
10896
10897         return build_new
10898           (RECUR (TREE_OPERAND (t, 0)),
10899            RECUR (TREE_OPERAND (t, 1)),
10900            RECUR (TREE_OPERAND (t, 2)),
10901            init,
10902            NEW_EXPR_USE_GLOBAL (t));
10903       }
10904
10905     case DELETE_EXPR:
10906      return delete_sanity
10907        (RECUR (TREE_OPERAND (t, 0)),
10908         RECUR (TREE_OPERAND (t, 1)),
10909         DELETE_EXPR_USE_VEC (t),
10910         DELETE_EXPR_USE_GLOBAL (t));
10911
10912     case COMPOUND_EXPR:
10913       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
10914                                     RECUR (TREE_OPERAND (t, 1)));
10915
10916     case CALL_EXPR:
10917       {
10918         tree function;
10919         tree call_args;
10920         bool qualified_p;
10921         bool koenig_p;
10922
10923         function = CALL_EXPR_FN (t);
10924         /* When we parsed the expression,  we determined whether or
10925            not Koenig lookup should be performed.  */
10926         koenig_p = KOENIG_LOOKUP_P (t);
10927         if (TREE_CODE (function) == SCOPE_REF)
10928           {
10929             qualified_p = true;
10930             function = tsubst_qualified_id (function, args, complain, in_decl,
10931                                             /*done=*/false,
10932                                             /*address_p=*/false);
10933           }
10934         else
10935           {
10936             if (TREE_CODE (function) == COMPONENT_REF)
10937               {
10938                 tree op = TREE_OPERAND (function, 1);
10939
10940                 qualified_p = (TREE_CODE (op) == SCOPE_REF
10941                                || (BASELINK_P (op)
10942                                    && BASELINK_QUALIFIED_P (op)));
10943               }
10944             else
10945               qualified_p = false;
10946
10947             function = tsubst_copy_and_build (function, args, complain,
10948                                               in_decl,
10949                                               !qualified_p,
10950                                               integral_constant_expression_p);
10951
10952             if (BASELINK_P (function))
10953               qualified_p = true;
10954           }
10955
10956         /* FIXME:  Rewrite this so as not to construct an arglist.  */
10957         call_args = RECUR (CALL_EXPR_ARGS (t));
10958
10959         /* We do not perform argument-dependent lookup if normal
10960            lookup finds a non-function, in accordance with the
10961            expected resolution of DR 218.  */
10962         if (koenig_p
10963             && ((is_overloaded_fn (function)
10964                  /* If lookup found a member function, the Koenig lookup is
10965                     not appropriate, even if an unqualified-name was used
10966                     to denote the function.  */
10967                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
10968                 || TREE_CODE (function) == IDENTIFIER_NODE))
10969           function = perform_koenig_lookup (function, call_args);
10970
10971         if (TREE_CODE (function) == IDENTIFIER_NODE)
10972           {
10973             unqualified_name_lookup_error (function);
10974             return error_mark_node;
10975           }
10976
10977         /* Remember that there was a reference to this entity.  */
10978         if (DECL_P (function))
10979           mark_used (function);
10980
10981         if (TREE_CODE (function) == OFFSET_REF)
10982           return build_offset_ref_call_from_tree (function, call_args);
10983         if (TREE_CODE (function) == COMPONENT_REF)
10984           {
10985             if (!BASELINK_P (TREE_OPERAND (function, 1)))
10986               return finish_call_expr (function, call_args,
10987                                        /*disallow_virtual=*/false,
10988                                        /*koenig_p=*/false);
10989             else
10990               return (build_new_method_call
10991                       (TREE_OPERAND (function, 0),
10992                        TREE_OPERAND (function, 1),
10993                        call_args, NULL_TREE,
10994                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
10995                        /*fn_p=*/NULL));
10996           }
10997         return finish_call_expr (function, call_args,
10998                                  /*disallow_virtual=*/qualified_p,
10999                                  koenig_p);
11000       }
11001
11002     case COND_EXPR:
11003       return build_x_conditional_expr
11004         (RECUR (TREE_OPERAND (t, 0)),
11005          RECUR (TREE_OPERAND (t, 1)),
11006          RECUR (TREE_OPERAND (t, 2)));
11007
11008     case PSEUDO_DTOR_EXPR:
11009       return finish_pseudo_destructor_expr
11010         (RECUR (TREE_OPERAND (t, 0)),
11011          RECUR (TREE_OPERAND (t, 1)),
11012          RECUR (TREE_OPERAND (t, 2)));
11013
11014     case TREE_LIST:
11015       {
11016         tree purpose, value, chain;
11017
11018         if (t == void_list_node)
11019           return t;
11020
11021         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
11022             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
11023           {
11024             /* We have pack expansions, so expand those and
11025                create a new list out of it.  */
11026             tree purposevec = NULL_TREE;
11027             tree valuevec = NULL_TREE;
11028             tree chain;
11029             int i, len = -1;
11030
11031             /* Expand the argument expressions.  */
11032             if (TREE_PURPOSE (t))
11033               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
11034                                                  complain, in_decl);
11035             if (TREE_VALUE (t))
11036               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
11037                                                complain, in_decl);
11038
11039             /* Build the rest of the list.  */
11040             chain = TREE_CHAIN (t);
11041             if (chain && chain != void_type_node)
11042               chain = RECUR (chain);
11043
11044             /* Determine the number of arguments.  */
11045             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
11046               {
11047                 len = TREE_VEC_LENGTH (purposevec);
11048                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
11049               }
11050             else if (TREE_CODE (valuevec) == TREE_VEC)
11051               len = TREE_VEC_LENGTH (valuevec);
11052             else
11053               {
11054                 /* Since we only performed a partial substitution into
11055                    the argument pack, we only return a single list
11056                    node.  */
11057                 if (purposevec == TREE_PURPOSE (t)
11058                     && valuevec == TREE_VALUE (t)
11059                     && chain == TREE_CHAIN (t))
11060                   return t;
11061
11062                 return tree_cons (purposevec, valuevec, chain);
11063               }
11064             
11065             /* Convert the argument vectors into a TREE_LIST */
11066             i = len;
11067             while (i > 0)
11068               {
11069                 /* Grab the Ith values.  */
11070                 i--;
11071                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
11072                                      : NULL_TREE;
11073                 value 
11074                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
11075                              : NULL_TREE;
11076
11077                 /* Build the list (backwards).  */
11078                 chain = tree_cons (purpose, value, chain);
11079               }
11080
11081             return chain;
11082           }
11083
11084         purpose = TREE_PURPOSE (t);
11085         if (purpose)
11086           purpose = RECUR (purpose);
11087         value = TREE_VALUE (t);
11088         if (value)
11089           value = RECUR (value);
11090         chain = TREE_CHAIN (t);
11091         if (chain && chain != void_type_node)
11092           chain = RECUR (chain);
11093         if (purpose == TREE_PURPOSE (t)
11094             && value == TREE_VALUE (t)
11095             && chain == TREE_CHAIN (t))
11096           return t;
11097         return tree_cons (purpose, value, chain);
11098       }
11099
11100     case COMPONENT_REF:
11101       {
11102         tree object;
11103         tree object_type;
11104         tree member;
11105
11106         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11107                                                      args, complain, in_decl);
11108         /* Remember that there was a reference to this entity.  */
11109         if (DECL_P (object))
11110           mark_used (object);
11111         object_type = TREE_TYPE (object);
11112
11113         member = TREE_OPERAND (t, 1);
11114         if (BASELINK_P (member))
11115           member = tsubst_baselink (member,
11116                                     non_reference (TREE_TYPE (object)),
11117                                     args, complain, in_decl);
11118         else
11119           member = tsubst_copy (member, args, complain, in_decl);
11120         if (member == error_mark_node)
11121           return error_mark_node;
11122
11123         if (object_type && !CLASS_TYPE_P (object_type))
11124           {
11125             if (SCALAR_TYPE_P (object_type))
11126               {
11127                 tree s = NULL_TREE;
11128                 tree dtor = member;
11129
11130                 if (TREE_CODE (dtor) == SCOPE_REF)
11131                   {
11132                     s = TREE_OPERAND (dtor, 0);
11133                     dtor = TREE_OPERAND (dtor, 1);
11134                   }
11135                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
11136                   {
11137                     dtor = TREE_OPERAND (dtor, 0);
11138                     if (TYPE_P (dtor))
11139                       return finish_pseudo_destructor_expr (object, s, dtor);
11140                   }
11141               }
11142           }
11143         else if (TREE_CODE (member) == SCOPE_REF
11144                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
11145           {
11146             tree tmpl;
11147             tree args;
11148
11149             /* Lookup the template functions now that we know what the
11150                scope is.  */
11151             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
11152             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
11153             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
11154                                             /*is_type_p=*/false,
11155                                             /*complain=*/false);
11156             if (BASELINK_P (member))
11157               {
11158                 BASELINK_FUNCTIONS (member)
11159                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
11160                               args);
11161                 member = (adjust_result_of_qualified_name_lookup
11162                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
11163                            object_type));
11164               }
11165             else
11166               {
11167                 qualified_name_lookup_error (object_type, tmpl, member);
11168                 return error_mark_node;
11169               }
11170           }
11171         else if (TREE_CODE (member) == SCOPE_REF
11172                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
11173                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
11174           {
11175             if (complain & tf_error)
11176               {
11177                 if (TYPE_P (TREE_OPERAND (member, 0)))
11178                   error ("%qT is not a class or namespace",
11179                          TREE_OPERAND (member, 0));
11180                 else
11181                   error ("%qD is not a class or namespace",
11182                          TREE_OPERAND (member, 0));
11183               }
11184             return error_mark_node;
11185           }
11186         else if (TREE_CODE (member) == FIELD_DECL)
11187           return finish_non_static_data_member (member, object, NULL_TREE);
11188
11189         return finish_class_member_access_expr (object, member,
11190                                                 /*template_p=*/false);
11191       }
11192
11193     case THROW_EXPR:
11194       return build_throw
11195         (RECUR (TREE_OPERAND (t, 0)));
11196
11197     case CONSTRUCTOR:
11198       {
11199         VEC(constructor_elt,gc) *n;
11200         constructor_elt *ce;
11201         unsigned HOST_WIDE_INT idx;
11202         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11203         bool process_index_p;
11204         int newlen;
11205         bool need_copy_p = false;
11206
11207         if (type == error_mark_node)
11208           return error_mark_node;
11209
11210         /* digest_init will do the wrong thing if we let it.  */
11211         if (type && TYPE_PTRMEMFUNC_P (type))
11212           return t;
11213
11214         /* We do not want to process the index of aggregate
11215            initializers as they are identifier nodes which will be
11216            looked up by digest_init.  */
11217         process_index_p = !(type && IS_AGGR_TYPE (type));
11218
11219         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
11220         newlen = VEC_length (constructor_elt, n);
11221         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
11222           {
11223             if (ce->index && process_index_p)
11224               ce->index = RECUR (ce->index);
11225
11226             if (PACK_EXPANSION_P (ce->value))
11227               {
11228                 /* Substitute into the pack expansion.  */
11229                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
11230                                                   in_decl);
11231
11232                 if (ce->value == error_mark_node)
11233                   ;
11234                 else if (TREE_VEC_LENGTH (ce->value) == 1)
11235                   /* Just move the argument into place.  */
11236                   ce->value = TREE_VEC_ELT (ce->value, 0);
11237                 else
11238                   {
11239                     /* Update the length of the final CONSTRUCTOR
11240                        arguments vector, and note that we will need to
11241                        copy.*/
11242                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
11243                     need_copy_p = true;
11244                   }
11245               }
11246             else
11247               ce->value = RECUR (ce->value);
11248           }
11249
11250         if (need_copy_p)
11251           {
11252             VEC(constructor_elt,gc) *old_n = n;
11253
11254             n = VEC_alloc (constructor_elt, gc, newlen);
11255             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
11256                  idx++)
11257               {
11258                 if (TREE_CODE (ce->value) == TREE_VEC)
11259                   {
11260                     int i, len = TREE_VEC_LENGTH (ce->value);
11261                     for (i = 0; i < len; ++i)
11262                       CONSTRUCTOR_APPEND_ELT (n, 0,
11263                                               TREE_VEC_ELT (ce->value, i));
11264                   }
11265                 else
11266                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
11267               }
11268           }
11269
11270         if (TREE_HAS_CONSTRUCTOR (t))
11271           return finish_compound_literal (type, n);
11272
11273         return build_constructor (NULL_TREE, n);
11274       }
11275
11276     case TYPEID_EXPR:
11277       {
11278         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
11279         if (TYPE_P (operand_0))
11280           return get_typeid (operand_0);
11281         return build_typeid (operand_0);
11282       }
11283
11284     case VAR_DECL:
11285       if (!args)
11286         return t;
11287       /* Fall through */
11288
11289     case PARM_DECL:
11290       {
11291         tree r = tsubst_copy (t, args, complain, in_decl);
11292
11293         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
11294           /* If the original type was a reference, we'll be wrapped in
11295              the appropriate INDIRECT_REF.  */
11296           r = convert_from_reference (r);
11297         return r;
11298       }
11299
11300     case VA_ARG_EXPR:
11301       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
11302                              tsubst_copy (TREE_TYPE (t), args, complain,
11303                                           in_decl));
11304
11305     case OFFSETOF_EXPR:
11306       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
11307
11308     case TRAIT_EXPR:
11309       {
11310         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
11311                                   complain, in_decl);
11312
11313         tree type2 = TRAIT_EXPR_TYPE2 (t);
11314         if (type2)
11315           type2 = tsubst_copy (type2, args, complain, in_decl);
11316         
11317         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
11318       }
11319
11320     case STMT_EXPR:
11321       {
11322         tree old_stmt_expr = cur_stmt_expr;
11323         tree stmt_expr = begin_stmt_expr ();
11324
11325         cur_stmt_expr = stmt_expr;
11326         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
11327                      integral_constant_expression_p);
11328         stmt_expr = finish_stmt_expr (stmt_expr, false);
11329         cur_stmt_expr = old_stmt_expr;
11330
11331         return stmt_expr;
11332       }
11333
11334     case CONST_DECL:
11335       t = tsubst_copy (t, args, complain, in_decl);
11336       /* As in finish_id_expression, we resolve enumeration constants
11337          to their underlying values.  */
11338       if (TREE_CODE (t) == CONST_DECL)
11339         {
11340           used_types_insert (TREE_TYPE (t));
11341           return DECL_INITIAL (t);
11342         }
11343       return t;
11344
11345     default:
11346       /* Handle Objective-C++ constructs, if appropriate.  */
11347       {
11348         tree subst
11349           = objcp_tsubst_copy_and_build (t, args, complain,
11350                                          in_decl, /*function_p=*/false);
11351         if (subst)
11352           return subst;
11353       }
11354       return tsubst_copy (t, args, complain, in_decl);
11355     }
11356
11357 #undef RECUR
11358 }
11359
11360 /* Verify that the instantiated ARGS are valid. For type arguments,
11361    make sure that the type's linkage is ok. For non-type arguments,
11362    make sure they are constants if they are integral or enumerations.
11363    Emit an error under control of COMPLAIN, and return TRUE on error.  */
11364
11365 static bool
11366 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
11367 {
11368   int ix, len = DECL_NTPARMS (tmpl);
11369   bool result = false;
11370
11371   for (ix = 0; ix != len; ix++)
11372     {
11373       tree t = TREE_VEC_ELT (args, ix);
11374
11375       if (TYPE_P (t))
11376         {
11377           /* [basic.link]: A name with no linkage (notably, the name
11378              of a class or enumeration declared in a local scope)
11379              shall not be used to declare an entity with linkage.
11380              This implies that names with no linkage cannot be used as
11381              template arguments.  */
11382           tree nt = no_linkage_check (t, /*relaxed_p=*/false);
11383
11384           if (nt)
11385             {
11386               /* DR 488 makes use of a type with no linkage cause
11387                  type deduction to fail.  */
11388               if (complain & tf_error)
11389                 {
11390                   if (TYPE_ANONYMOUS_P (nt))
11391                     error ("%qT is/uses anonymous type", t);
11392                   else
11393                     error ("template argument for %qD uses local type %qT",
11394                            tmpl, t);
11395                 }
11396               result = true;
11397             }
11398           /* In order to avoid all sorts of complications, we do not
11399              allow variably-modified types as template arguments.  */
11400           else if (variably_modified_type_p (t, NULL_TREE))
11401             {
11402               if (complain & tf_error)
11403                 error ("%qT is a variably modified type", t);
11404               result = true;
11405             }
11406         }
11407       /* A non-type argument of integral or enumerated type must be a
11408          constant.  */
11409       else if (TREE_TYPE (t)
11410                && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
11411                && !TREE_CONSTANT (t))
11412         {
11413           if (complain & tf_error)
11414             error ("integral expression %qE is not constant", t);
11415           result = true;
11416         }
11417     }
11418   if (result && (complain & tf_error))
11419     error ("  trying to instantiate %qD", tmpl);
11420   return result;
11421 }
11422
11423 /* Instantiate the indicated variable or function template TMPL with
11424    the template arguments in TARG_PTR.  */
11425
11426 tree
11427 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
11428 {
11429   tree fndecl;
11430   tree gen_tmpl;
11431   tree spec;
11432   HOST_WIDE_INT saved_processing_template_decl;
11433
11434   if (tmpl == error_mark_node)
11435     return error_mark_node;
11436
11437   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
11438
11439   /* If this function is a clone, handle it specially.  */
11440   if (DECL_CLONED_FUNCTION_P (tmpl))
11441     {
11442       tree spec;
11443       tree clone;
11444
11445       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
11446                                    complain);
11447       if (spec == error_mark_node)
11448         return error_mark_node;
11449
11450       /* Look for the clone.  */
11451       FOR_EACH_CLONE (clone, spec)
11452         if (DECL_NAME (clone) == DECL_NAME (tmpl))
11453           return clone;
11454       /* We should always have found the clone by now.  */
11455       gcc_unreachable ();
11456       return NULL_TREE;
11457     }
11458
11459   /* Check to see if we already have this specialization.  */
11460   spec = retrieve_specialization (tmpl, targ_ptr,
11461                                   /*class_specializations_p=*/false);
11462   if (spec != NULL_TREE)
11463     return spec;
11464
11465   gen_tmpl = most_general_template (tmpl);
11466   if (tmpl != gen_tmpl)
11467     {
11468       /* The TMPL is a partial instantiation.  To get a full set of
11469          arguments we must add the arguments used to perform the
11470          partial instantiation.  */
11471       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
11472                                               targ_ptr);
11473
11474       /* Check to see if we already have this specialization.  */
11475       spec = retrieve_specialization (gen_tmpl, targ_ptr,
11476                                       /*class_specializations_p=*/false);
11477       if (spec != NULL_TREE)
11478         return spec;
11479     }
11480
11481   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
11482                                complain))
11483     return error_mark_node;
11484
11485   /* We are building a FUNCTION_DECL, during which the access of its
11486      parameters and return types have to be checked.  However this
11487      FUNCTION_DECL which is the desired context for access checking
11488      is not built yet.  We solve this chicken-and-egg problem by
11489      deferring all checks until we have the FUNCTION_DECL.  */
11490   push_deferring_access_checks (dk_deferred);
11491
11492   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
11493      (because, for example, we have encountered a non-dependent
11494      function call in the body of a template function and must now
11495      determine which of several overloaded functions will be called),
11496      within the instantiation itself we are not processing a
11497      template.  */  
11498   saved_processing_template_decl = processing_template_decl;
11499   processing_template_decl = 0;
11500   /* Substitute template parameters to obtain the specialization.  */
11501   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
11502                    targ_ptr, complain, gen_tmpl);
11503   processing_template_decl = saved_processing_template_decl;
11504   if (fndecl == error_mark_node)
11505     return error_mark_node;
11506
11507   /* Now we know the specialization, compute access previously
11508      deferred.  */
11509   push_access_scope (fndecl);
11510   perform_deferred_access_checks ();
11511   pop_access_scope (fndecl);
11512   pop_deferring_access_checks ();
11513
11514   /* The DECL_TI_TEMPLATE should always be the immediate parent
11515      template, not the most general template.  */
11516   DECL_TI_TEMPLATE (fndecl) = tmpl;
11517
11518   /* If we've just instantiated the main entry point for a function,
11519      instantiate all the alternate entry points as well.  We do this
11520      by cloning the instantiation of the main entry point, not by
11521      instantiating the template clones.  */
11522   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
11523     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
11524
11525   return fndecl;
11526 }
11527
11528 /* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
11529    arguments that are being used when calling it.  TARGS is a vector
11530    into which the deduced template arguments are placed.
11531
11532    Return zero for success, 2 for an incomplete match that doesn't resolve
11533    all the types, and 1 for complete failure.  An error message will be
11534    printed only for an incomplete match.
11535
11536    If FN is a conversion operator, or we are trying to produce a specific
11537    specialization, RETURN_TYPE is the return type desired.
11538
11539    The EXPLICIT_TARGS are explicit template arguments provided via a
11540    template-id.
11541
11542    The parameter STRICT is one of:
11543
11544    DEDUCE_CALL:
11545      We are deducing arguments for a function call, as in
11546      [temp.deduct.call].
11547
11548    DEDUCE_CONV:
11549      We are deducing arguments for a conversion function, as in
11550      [temp.deduct.conv].
11551
11552    DEDUCE_EXACT:
11553      We are deducing arguments when doing an explicit instantiation
11554      as in [temp.explicit], when determining an explicit specialization
11555      as in [temp.expl.spec], or when taking the address of a function
11556      template, as in [temp.deduct.funcaddr].  */
11557
11558 int
11559 fn_type_unification (tree fn,
11560                      tree explicit_targs,
11561                      tree targs,
11562                      tree args,
11563                      tree return_type,
11564                      unification_kind_t strict,
11565                      int flags)
11566 {
11567   tree parms;
11568   tree fntype;
11569   int result;
11570   bool incomplete_argument_packs_p = false;
11571
11572   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
11573
11574   fntype = TREE_TYPE (fn);
11575   if (explicit_targs)
11576     {
11577       /* [temp.deduct]
11578
11579          The specified template arguments must match the template
11580          parameters in kind (i.e., type, nontype, template), and there
11581          must not be more arguments than there are parameters;
11582          otherwise type deduction fails.
11583
11584          Nontype arguments must match the types of the corresponding
11585          nontype template parameters, or must be convertible to the
11586          types of the corresponding nontype parameters as specified in
11587          _temp.arg.nontype_, otherwise type deduction fails.
11588
11589          All references in the function type of the function template
11590          to the corresponding template parameters are replaced by the
11591          specified template argument values.  If a substitution in a
11592          template parameter or in the function type of the function
11593          template results in an invalid type, type deduction fails.  */
11594       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
11595       int i, len = TREE_VEC_LENGTH (tparms);
11596       tree converted_args;
11597       bool incomplete = false;
11598
11599       if (explicit_targs == error_mark_node)
11600         return 1;
11601
11602       converted_args
11603         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
11604                                   /*require_all_args=*/false,
11605                                   /*use_default_args=*/false));
11606       if (converted_args == error_mark_node)
11607         return 1;
11608
11609       /* Substitute the explicit args into the function type.  This is
11610          necessary so that, for instance, explicitly declared function
11611          arguments can match null pointed constants.  If we were given
11612          an incomplete set of explicit args, we must not do semantic
11613          processing during substitution as we could create partial
11614          instantiations.  */
11615       for (i = 0; i < len; i++)
11616         {
11617           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
11618           bool parameter_pack = false;
11619
11620           /* Dig out the actual parm.  */
11621           if (TREE_CODE (parm) == TYPE_DECL
11622               || TREE_CODE (parm) == TEMPLATE_DECL)
11623             {
11624               parm = TREE_TYPE (parm);
11625               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
11626             }
11627           else if (TREE_CODE (parm) == PARM_DECL)
11628             {
11629               parm = DECL_INITIAL (parm);
11630               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
11631             }
11632
11633           if (parameter_pack)
11634             {
11635               int level, idx;
11636               tree targ;
11637               template_parm_level_and_index (parm, &level, &idx);
11638
11639               /* Mark the argument pack as "incomplete". We could
11640                  still deduce more arguments during unification.  */
11641               targ = TMPL_ARG (converted_args, level, idx);
11642               if (targ)
11643                 {
11644                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
11645                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
11646                     = ARGUMENT_PACK_ARGS (targ);
11647                 }
11648
11649               /* We have some incomplete argument packs.  */
11650               incomplete_argument_packs_p = true;
11651             }
11652         }
11653
11654       if (incomplete_argument_packs_p)
11655         /* Any substitution is guaranteed to be incomplete if there
11656            are incomplete argument packs, because we can still deduce
11657            more arguments.  */
11658         incomplete = 1;
11659       else
11660         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
11661
11662       processing_template_decl += incomplete;
11663       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
11664       processing_template_decl -= incomplete;
11665
11666       if (fntype == error_mark_node)
11667         return 1;
11668
11669       /* Place the explicitly specified arguments in TARGS.  */
11670       for (i = NUM_TMPL_ARGS (converted_args); i--;)
11671         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
11672     }
11673
11674   /* Never do unification on the 'this' parameter.  */
11675   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
11676
11677   if (return_type)
11678     {
11679       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
11680       args = tree_cons (NULL_TREE, return_type, args);
11681     }
11682
11683   /* We allow incomplete unification without an error message here
11684      because the standard doesn't seem to explicitly prohibit it.  Our
11685      callers must be ready to deal with unification failures in any
11686      event.  */
11687   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
11688                                   targs, parms, args, /*subr=*/0,
11689                                   strict, flags);
11690
11691   if (result == 0 && incomplete_argument_packs_p)
11692     {
11693       int i, len = NUM_TMPL_ARGS (targs);
11694
11695       /* Clear the "incomplete" flags on all argument packs.  */
11696       for (i = 0; i < len; i++)
11697         {
11698           tree arg = TREE_VEC_ELT (targs, i);
11699           if (ARGUMENT_PACK_P (arg))
11700             {
11701               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
11702               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
11703             }
11704         }
11705     }
11706
11707   /* Now that we have bindings for all of the template arguments,
11708      ensure that the arguments deduced for the template template
11709      parameters have compatible template parameter lists.  We cannot
11710      check this property before we have deduced all template
11711      arguments, because the template parameter types of a template
11712      template parameter might depend on prior template parameters
11713      deduced after the template template parameter.  The following
11714      ill-formed example illustrates this issue:
11715
11716        template<typename T, template<T> class C> void f(C<5>, T);
11717
11718        template<int N> struct X {};
11719
11720        void g() {
11721          f(X<5>(), 5l); // error: template argument deduction fails
11722        }
11723
11724      The template parameter list of 'C' depends on the template type
11725      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
11726      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
11727      time that we deduce 'C'.  */
11728   if (result == 0
11729       && !template_template_parm_bindings_ok_p 
11730            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
11731     return 1;
11732
11733   if (result == 0)
11734     /* All is well so far.  Now, check:
11735
11736        [temp.deduct]
11737
11738        When all template arguments have been deduced, all uses of
11739        template parameters in nondeduced contexts are replaced with
11740        the corresponding deduced argument values.  If the
11741        substitution results in an invalid type, as described above,
11742        type deduction fails.  */
11743     if (tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE)
11744         == error_mark_node)
11745       return 1;
11746
11747   return result;
11748 }
11749
11750 /* Adjust types before performing type deduction, as described in
11751    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
11752    sections are symmetric.  PARM is the type of a function parameter
11753    or the return type of the conversion function.  ARG is the type of
11754    the argument passed to the call, or the type of the value
11755    initialized with the result of the conversion function.
11756    ARG_EXPR is the original argument expression, which may be null.  */
11757
11758 static int
11759 maybe_adjust_types_for_deduction (unification_kind_t strict,
11760                                   tree* parm,
11761                                   tree* arg,
11762                                   tree arg_expr)
11763 {
11764   int result = 0;
11765
11766   switch (strict)
11767     {
11768     case DEDUCE_CALL:
11769       break;
11770
11771     case DEDUCE_CONV:
11772       {
11773         /* Swap PARM and ARG throughout the remainder of this
11774            function; the handling is precisely symmetric since PARM
11775            will initialize ARG rather than vice versa.  */
11776         tree* temp = parm;
11777         parm = arg;
11778         arg = temp;
11779         break;
11780       }
11781
11782     case DEDUCE_EXACT:
11783       /* There is nothing to do in this case.  */
11784       return 0;
11785
11786     default:
11787       gcc_unreachable ();
11788     }
11789
11790   if (TREE_CODE (*parm) != REFERENCE_TYPE)
11791     {
11792       /* [temp.deduct.call]
11793
11794          If P is not a reference type:
11795
11796          --If A is an array type, the pointer type produced by the
11797          array-to-pointer standard conversion (_conv.array_) is
11798          used in place of A for type deduction; otherwise,
11799
11800          --If A is a function type, the pointer type produced by
11801          the function-to-pointer standard conversion
11802          (_conv.func_) is used in place of A for type deduction;
11803          otherwise,
11804
11805          --If A is a cv-qualified type, the top level
11806          cv-qualifiers of A's type are ignored for type
11807          deduction.  */
11808       if (TREE_CODE (*arg) == ARRAY_TYPE)
11809         *arg = build_pointer_type (TREE_TYPE (*arg));
11810       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
11811         *arg = build_pointer_type (*arg);
11812       else
11813         *arg = TYPE_MAIN_VARIANT (*arg);
11814     }
11815
11816   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
11817      of the form T&&, where T is a template parameter, and the argument
11818      is an lvalue, T is deduced as A& */
11819   if (TREE_CODE (*parm) == REFERENCE_TYPE
11820       && TYPE_REF_IS_RVALUE (*parm)
11821       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
11822       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
11823       && arg_expr && real_lvalue_p (arg_expr))
11824     *arg = build_reference_type (*arg);
11825
11826   /* [temp.deduct.call]
11827
11828      If P is a cv-qualified type, the top level cv-qualifiers
11829      of P's type are ignored for type deduction.  If P is a
11830      reference type, the type referred to by P is used for
11831      type deduction.  */
11832   *parm = TYPE_MAIN_VARIANT (*parm);
11833   if (TREE_CODE (*parm) == REFERENCE_TYPE)
11834     {
11835       *parm = TREE_TYPE (*parm);
11836       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
11837     }
11838
11839   /* DR 322. For conversion deduction, remove a reference type on parm
11840      too (which has been swapped into ARG).  */
11841   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
11842     *arg = TREE_TYPE (*arg);
11843
11844   return result;
11845 }
11846
11847 /* Most parms like fn_type_unification.
11848
11849    If SUBR is 1, we're being called recursively (to unify the
11850    arguments of a function or method parameter of a function
11851    template). */
11852
11853 static int
11854 type_unification_real (tree tparms,
11855                        tree targs,
11856                        tree xparms,
11857                        tree xargs,
11858                        int subr,
11859                        unification_kind_t strict,
11860                        int flags)
11861 {
11862   tree parm, arg, arg_expr;
11863   int i;
11864   int ntparms = TREE_VEC_LENGTH (tparms);
11865   int sub_strict;
11866   int saw_undeduced = 0;
11867   tree parms, args;
11868
11869   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
11870   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
11871   gcc_assert (!xargs || TREE_CODE (xargs) == TREE_LIST);
11872   gcc_assert (ntparms > 0);
11873
11874   switch (strict)
11875     {
11876     case DEDUCE_CALL:
11877       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
11878                     | UNIFY_ALLOW_DERIVED);
11879       break;
11880
11881     case DEDUCE_CONV:
11882       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
11883       break;
11884
11885     case DEDUCE_EXACT:
11886       sub_strict = UNIFY_ALLOW_NONE;
11887       break;
11888
11889     default:
11890       gcc_unreachable ();
11891     }
11892
11893  again:
11894   parms = xparms;
11895   args = xargs;
11896
11897   while (parms && parms != void_list_node
11898          && args && args != void_list_node)
11899     {
11900       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
11901         break;
11902
11903       parm = TREE_VALUE (parms);
11904       parms = TREE_CHAIN (parms);
11905       arg = TREE_VALUE (args);
11906       args = TREE_CHAIN (args);
11907       arg_expr = NULL;
11908
11909       if (arg == error_mark_node)
11910         return 1;
11911       if (arg == unknown_type_node)
11912         /* We can't deduce anything from this, but we might get all the
11913            template args from other function args.  */
11914         continue;
11915
11916       /* Conversions will be performed on a function argument that
11917          corresponds with a function parameter that contains only
11918          non-deducible template parameters and explicitly specified
11919          template parameters.  */
11920       if (!uses_template_parms (parm))
11921         {
11922           tree type;
11923
11924           if (!TYPE_P (arg))
11925             type = TREE_TYPE (arg);
11926           else
11927             type = arg;
11928
11929           if (same_type_p (parm, type))
11930             continue;
11931           if (strict != DEDUCE_EXACT
11932               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
11933                                   flags))
11934             continue;
11935
11936           return 1;
11937         }
11938
11939       if (!TYPE_P (arg))
11940         {
11941           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
11942           if (type_unknown_p (arg))
11943             {
11944               /* [temp.deduct.type] 
11945
11946                  A template-argument can be deduced from a pointer to
11947                  function or pointer to member function argument if
11948                  the set of overloaded functions does not contain
11949                  function templates and at most one of a set of
11950                  overloaded functions provides a unique match.  */
11951               if (resolve_overloaded_unification
11952                   (tparms, targs, parm, arg, strict, sub_strict))
11953                 continue;
11954
11955               return 1;
11956             }
11957           arg_expr = arg;
11958           arg = unlowered_expr_type (arg);
11959           if (arg == error_mark_node)
11960             return 1;
11961         }
11962
11963       {
11964         int arg_strict = sub_strict;
11965
11966         if (!subr)
11967           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
11968                                                           arg_expr);
11969
11970         if (unify (tparms, targs, parm, arg, arg_strict))
11971           return 1;
11972       }
11973     }
11974
11975
11976   if (parms 
11977       && parms != void_list_node
11978       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
11979     {
11980       /* Unify the remaining arguments with the pack expansion type.  */
11981       tree argvec;
11982       tree parmvec = make_tree_vec (1);
11983       int len = 0;
11984       tree t;
11985
11986       /* Count the number of arguments that remain.  */
11987       for (t = args; t && t != void_list_node; t = TREE_CHAIN (t))
11988         len++;
11989         
11990       /* Allocate a TREE_VEC and copy in all of the arguments */ 
11991       argvec = make_tree_vec (len);
11992       for (i = 0; args && args != void_list_node; args = TREE_CHAIN (args))
11993         {
11994           TREE_VEC_ELT (argvec, i) = TREE_VALUE (args);
11995           ++i;
11996         }
11997
11998       /* Copy the parameter into parmvec.  */
11999       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
12000       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
12001                                 /*call_args_p=*/true, /*subr=*/subr))
12002         return 1;
12003
12004       /* Advance to the end of the list of parameters.  */
12005       parms = TREE_CHAIN (parms);
12006     }
12007
12008   /* Fail if we've reached the end of the parm list, and more args
12009      are present, and the parm list isn't variadic.  */
12010   if (args && args != void_list_node && parms == void_list_node)
12011     return 1;
12012   /* Fail if parms are left and they don't have default values.  */
12013   if (parms && parms != void_list_node
12014       && TREE_PURPOSE (parms) == NULL_TREE)
12015     return 1;
12016
12017   if (!subr)
12018     for (i = 0; i < ntparms; i++)
12019       if (!TREE_VEC_ELT (targs, i))
12020         {
12021           tree tparm;
12022
12023           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
12024             continue;
12025
12026           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12027
12028           /* If this is an undeduced nontype parameter that depends on
12029              a type parameter, try another pass; its type may have been
12030              deduced from a later argument than the one from which
12031              this parameter can be deduced.  */
12032           if (TREE_CODE (tparm) == PARM_DECL
12033               && uses_template_parms (TREE_TYPE (tparm))
12034               && !saw_undeduced++)
12035             goto again;
12036
12037           /* Core issue #226 (C++0x) [temp.deduct]:
12038
12039                If a template argument has not been deduced, its
12040                default template argument, if any, is used. 
12041
12042              When we are in C++98 mode, TREE_PURPOSE will either
12043              be NULL_TREE or ERROR_MARK_NODE, so we do not need
12044              to explicitly check cxx_dialect here.  */
12045           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
12046             {
12047               tree arg = tsubst (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)), 
12048                                  targs, tf_none, NULL_TREE);
12049               if (arg == error_mark_node)
12050                 return 1;
12051               else
12052                 {
12053                   TREE_VEC_ELT (targs, i) = arg;
12054                   continue;
12055                 }
12056             }
12057
12058           /* If the type parameter is a parameter pack, then it will
12059              be deduced to an empty parameter pack.  */
12060           if (template_parameter_pack_p (tparm))
12061             {
12062               tree arg;
12063
12064               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
12065                 {
12066                   arg = make_node (NONTYPE_ARGUMENT_PACK);
12067                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
12068                   TREE_CONSTANT (arg) = 1;
12069                 }
12070               else
12071                 arg = make_node (TYPE_ARGUMENT_PACK);
12072
12073               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
12074
12075               TREE_VEC_ELT (targs, i) = arg;
12076               continue;
12077             }
12078
12079           return 2;
12080         }
12081
12082   return 0;
12083 }
12084
12085 /* Subroutine of type_unification_real.  Args are like the variables
12086    at the call site.  ARG is an overloaded function (or template-id);
12087    we try deducing template args from each of the overloads, and if
12088    only one succeeds, we go with that.  Modifies TARGS and returns
12089    true on success.  */
12090
12091 static bool
12092 resolve_overloaded_unification (tree tparms,
12093                                 tree targs,
12094                                 tree parm,
12095                                 tree arg,
12096                                 unification_kind_t strict,
12097                                 int sub_strict)
12098 {
12099   tree tempargs = copy_node (targs);
12100   int good = 0;
12101   bool addr_p;
12102
12103   if (TREE_CODE (arg) == ADDR_EXPR)
12104     {
12105       arg = TREE_OPERAND (arg, 0);
12106       addr_p = true;
12107     }
12108   else
12109     addr_p = false;
12110
12111   if (TREE_CODE (arg) == COMPONENT_REF)
12112     /* Handle `&x' where `x' is some static or non-static member
12113        function name.  */
12114     arg = TREE_OPERAND (arg, 1);
12115
12116   if (TREE_CODE (arg) == OFFSET_REF)
12117     arg = TREE_OPERAND (arg, 1);
12118
12119   /* Strip baselink information.  */
12120   if (BASELINK_P (arg))
12121     arg = BASELINK_FUNCTIONS (arg);
12122
12123   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
12124     {
12125       /* If we got some explicit template args, we need to plug them into
12126          the affected templates before we try to unify, in case the
12127          explicit args will completely resolve the templates in question.  */
12128
12129       tree expl_subargs = TREE_OPERAND (arg, 1);
12130       arg = TREE_OPERAND (arg, 0);
12131
12132       for (; arg; arg = OVL_NEXT (arg))
12133         {
12134           tree fn = OVL_CURRENT (arg);
12135           tree subargs, elem;
12136
12137           if (TREE_CODE (fn) != TEMPLATE_DECL)
12138             continue;
12139
12140           ++processing_template_decl;
12141           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
12142                                   expl_subargs, /*check_ret=*/false);
12143           if (subargs)
12144             {
12145               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
12146               good += try_one_overload (tparms, targs, tempargs, parm,
12147                                         elem, strict, sub_strict, addr_p);
12148             }
12149           --processing_template_decl;
12150         }
12151     }
12152   else if (TREE_CODE (arg) != OVERLOAD
12153            && TREE_CODE (arg) != FUNCTION_DECL)
12154     /* If ARG is, for example, "(0, &f)" then its type will be unknown
12155        -- but the deduction does not succeed because the expression is
12156        not just the function on its own.  */
12157     return false;
12158   else
12159     for (; arg; arg = OVL_NEXT (arg))
12160       good += try_one_overload (tparms, targs, tempargs, parm,
12161                                 TREE_TYPE (OVL_CURRENT (arg)),
12162                                 strict, sub_strict, addr_p);
12163
12164   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12165      to function or pointer to member function argument if the set of
12166      overloaded functions does not contain function templates and at most
12167      one of a set of overloaded functions provides a unique match.
12168
12169      So if we found multiple possibilities, we return success but don't
12170      deduce anything.  */
12171
12172   if (good == 1)
12173     {
12174       int i = TREE_VEC_LENGTH (targs);
12175       for (; i--; )
12176         if (TREE_VEC_ELT (tempargs, i))
12177           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
12178     }
12179   if (good)
12180     return true;
12181
12182   return false;
12183 }
12184
12185 /* Subroutine of resolve_overloaded_unification; does deduction for a single
12186    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
12187    different overloads deduce different arguments for a given parm.
12188    ADDR_P is true if the expression for which deduction is being
12189    performed was of the form "& fn" rather than simply "fn".
12190
12191    Returns 1 on success.  */
12192
12193 static int
12194 try_one_overload (tree tparms,
12195                   tree orig_targs,
12196                   tree targs,
12197                   tree parm,
12198                   tree arg,
12199                   unification_kind_t strict,
12200                   int sub_strict,
12201                   bool addr_p)
12202 {
12203   int nargs;
12204   tree tempargs;
12205   int i;
12206
12207   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12208      to function or pointer to member function argument if the set of
12209      overloaded functions does not contain function templates and at most
12210      one of a set of overloaded functions provides a unique match.
12211
12212      So if this is a template, just return success.  */
12213
12214   if (uses_template_parms (arg))
12215     return 1;
12216
12217   if (TREE_CODE (arg) == METHOD_TYPE)
12218     arg = build_ptrmemfunc_type (build_pointer_type (arg));
12219   else if (addr_p)
12220     arg = build_pointer_type (arg);
12221
12222   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
12223
12224   /* We don't copy orig_targs for this because if we have already deduced
12225      some template args from previous args, unify would complain when we
12226      try to deduce a template parameter for the same argument, even though
12227      there isn't really a conflict.  */
12228   nargs = TREE_VEC_LENGTH (targs);
12229   tempargs = make_tree_vec (nargs);
12230
12231   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
12232     return 0;
12233
12234   /* First make sure we didn't deduce anything that conflicts with
12235      explicitly specified args.  */
12236   for (i = nargs; i--; )
12237     {
12238       tree elt = TREE_VEC_ELT (tempargs, i);
12239       tree oldelt = TREE_VEC_ELT (orig_targs, i);
12240
12241       if (!elt)
12242         /*NOP*/;
12243       else if (uses_template_parms (elt))
12244         /* Since we're unifying against ourselves, we will fill in
12245            template args used in the function parm list with our own
12246            template parms.  Discard them.  */
12247         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
12248       else if (oldelt && !template_args_equal (oldelt, elt))
12249         return 0;
12250     }
12251
12252   for (i = nargs; i--; )
12253     {
12254       tree elt = TREE_VEC_ELT (tempargs, i);
12255
12256       if (elt)
12257         TREE_VEC_ELT (targs, i) = elt;
12258     }
12259
12260   return 1;
12261 }
12262
12263 /* PARM is a template class (perhaps with unbound template
12264    parameters).  ARG is a fully instantiated type.  If ARG can be
12265    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
12266    TARGS are as for unify.  */
12267
12268 static tree
12269 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
12270 {
12271   tree copy_of_targs;
12272
12273   if (!CLASSTYPE_TEMPLATE_INFO (arg)
12274       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
12275           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
12276     return NULL_TREE;
12277
12278   /* We need to make a new template argument vector for the call to
12279      unify.  If we used TARGS, we'd clutter it up with the result of
12280      the attempted unification, even if this class didn't work out.
12281      We also don't want to commit ourselves to all the unifications
12282      we've already done, since unification is supposed to be done on
12283      an argument-by-argument basis.  In other words, consider the
12284      following pathological case:
12285
12286        template <int I, int J, int K>
12287        struct S {};
12288
12289        template <int I, int J>
12290        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
12291
12292        template <int I, int J, int K>
12293        void f(S<I, J, K>, S<I, I, I>);
12294
12295        void g() {
12296          S<0, 0, 0> s0;
12297          S<0, 1, 2> s2;
12298
12299          f(s0, s2);
12300        }
12301
12302      Now, by the time we consider the unification involving `s2', we
12303      already know that we must have `f<0, 0, 0>'.  But, even though
12304      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
12305      because there are two ways to unify base classes of S<0, 1, 2>
12306      with S<I, I, I>.  If we kept the already deduced knowledge, we
12307      would reject the possibility I=1.  */
12308   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
12309
12310   /* If unification failed, we're done.  */
12311   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
12312              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
12313     return NULL_TREE;
12314
12315   return arg;
12316 }
12317
12318 /* Given a template type PARM and a class type ARG, find the unique
12319    base type in ARG that is an instance of PARM.  We do not examine
12320    ARG itself; only its base-classes.  If there is not exactly one
12321    appropriate base class, return NULL_TREE.  PARM may be the type of
12322    a partial specialization, as well as a plain template type.  Used
12323    by unify.  */
12324
12325 static tree
12326 get_template_base (tree tparms, tree targs, tree parm, tree arg)
12327 {
12328   tree rval = NULL_TREE;
12329   tree binfo;
12330
12331   gcc_assert (IS_AGGR_TYPE_CODE (TREE_CODE (arg)));
12332
12333   binfo = TYPE_BINFO (complete_type (arg));
12334   if (!binfo)
12335     /* The type could not be completed.  */
12336     return NULL_TREE;
12337
12338   /* Walk in inheritance graph order.  The search order is not
12339      important, and this avoids multiple walks of virtual bases.  */
12340   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
12341     {
12342       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
12343
12344       if (r)
12345         {
12346           /* If there is more than one satisfactory baseclass, then:
12347
12348                [temp.deduct.call]
12349
12350               If they yield more than one possible deduced A, the type
12351               deduction fails.
12352
12353              applies.  */
12354           if (rval && !same_type_p (r, rval))
12355             return NULL_TREE;
12356
12357           rval = r;
12358         }
12359     }
12360
12361   return rval;
12362 }
12363
12364 /* Returns the level of DECL, which declares a template parameter.  */
12365
12366 static int
12367 template_decl_level (tree decl)
12368 {
12369   switch (TREE_CODE (decl))
12370     {
12371     case TYPE_DECL:
12372     case TEMPLATE_DECL:
12373       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
12374
12375     case PARM_DECL:
12376       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
12377
12378     default:
12379       gcc_unreachable ();
12380     }
12381   return 0;
12382 }
12383
12384 /* Decide whether ARG can be unified with PARM, considering only the
12385    cv-qualifiers of each type, given STRICT as documented for unify.
12386    Returns nonzero iff the unification is OK on that basis.  */
12387
12388 static int
12389 check_cv_quals_for_unify (int strict, tree arg, tree parm)
12390 {
12391   int arg_quals = cp_type_quals (arg);
12392   int parm_quals = cp_type_quals (parm);
12393
12394   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12395       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12396     {
12397       /*  Although a CVR qualifier is ignored when being applied to a
12398           substituted template parameter ([8.3.2]/1 for example), that
12399           does not apply during deduction [14.8.2.4]/1, (even though
12400           that is not explicitly mentioned, [14.8.2.4]/9 indicates
12401           this).  Except when we're allowing additional CV qualifiers
12402           at the outer level [14.8.2.1]/3,1st bullet.  */
12403       if ((TREE_CODE (arg) == REFERENCE_TYPE
12404            || TREE_CODE (arg) == FUNCTION_TYPE
12405            || TREE_CODE (arg) == METHOD_TYPE)
12406           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
12407         return 0;
12408
12409       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
12410           && (parm_quals & TYPE_QUAL_RESTRICT))
12411         return 0;
12412     }
12413
12414   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12415       && (arg_quals & parm_quals) != parm_quals)
12416     return 0;
12417
12418   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
12419       && (parm_quals & arg_quals) != arg_quals)
12420     return 0;
12421
12422   return 1;
12423 }
12424
12425 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
12426 void 
12427 template_parm_level_and_index (tree parm, int* level, int* index)
12428 {
12429   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12430       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12431       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12432     {
12433       *index = TEMPLATE_TYPE_IDX (parm);
12434       *level = TEMPLATE_TYPE_LEVEL (parm);
12435     }
12436   else
12437     {
12438       *index = TEMPLATE_PARM_IDX (parm);
12439       *level = TEMPLATE_PARM_LEVEL (parm);
12440     }
12441 }
12442
12443 /* Unifies the remaining arguments in PACKED_ARGS with the pack
12444    expansion at the end of PACKED_PARMS. Returns 0 if the type
12445    deduction succeeds, 1 otherwise. STRICT is the same as in
12446    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
12447    call argument list. We'll need to adjust the arguments to make them
12448    types. SUBR tells us if this is from a recursive call to
12449    type_unification_real.  */
12450 int
12451 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
12452                       tree packed_args, int strict, bool call_args_p,
12453                       bool subr)
12454 {
12455   tree parm 
12456     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
12457   tree pattern = PACK_EXPANSION_PATTERN (parm);
12458   tree pack, packs = NULL_TREE;
12459   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
12460   int len = TREE_VEC_LENGTH (packed_args);
12461
12462   /* Determine the parameter packs we will be deducing from the
12463      pattern, and record their current deductions.  */
12464   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
12465        pack; pack = TREE_CHAIN (pack))
12466     {
12467       tree parm_pack = TREE_VALUE (pack);
12468       int idx, level;
12469
12470       /* Determine the index and level of this parameter pack.  */
12471       template_parm_level_and_index (parm_pack, &level, &idx);
12472
12473       /* Keep track of the parameter packs and their corresponding
12474          argument packs.  */
12475       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
12476       TREE_TYPE (packs) = make_tree_vec (len - start);
12477     }
12478   
12479   /* Loop through all of the arguments that have not yet been
12480      unified and unify each with the pattern.  */
12481   for (i = start; i < len; i++)
12482     {
12483       tree parm = pattern;
12484
12485       /* For each parameter pack, clear out the deduced value so that
12486          we can deduce it again.  */
12487       for (pack = packs; pack; pack = TREE_CHAIN (pack))
12488         {
12489           int idx, level;
12490           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12491
12492           TMPL_ARG (targs, level, idx) = NULL_TREE;
12493         }
12494
12495       /* Unify the pattern with the current argument.  */
12496       {
12497         tree arg = TREE_VEC_ELT (packed_args, i);
12498         tree arg_expr = NULL_TREE;
12499         int arg_strict = strict;
12500         bool skip_arg_p = false;
12501
12502         if (call_args_p)
12503           {
12504             int sub_strict;
12505
12506             /* This mirrors what we do in type_unification_real.  */
12507             switch (strict)
12508               {
12509               case DEDUCE_CALL:
12510                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
12511                               | UNIFY_ALLOW_MORE_CV_QUAL
12512                               | UNIFY_ALLOW_DERIVED);
12513                 break;
12514                 
12515               case DEDUCE_CONV:
12516                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12517                 break;
12518                 
12519               case DEDUCE_EXACT:
12520                 sub_strict = UNIFY_ALLOW_NONE;
12521                 break;
12522                 
12523               default:
12524                 gcc_unreachable ();
12525               }
12526
12527             if (!TYPE_P (arg))
12528               {
12529                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12530                 if (type_unknown_p (arg))
12531                   {
12532                     /* [temp.deduct.type] A template-argument can be
12533                        deduced from a pointer to function or pointer
12534                        to member function argument if the set of
12535                        overloaded functions does not contain function
12536                        templates and at most one of a set of
12537                        overloaded functions provides a unique
12538                        match.  */
12539
12540                     if (resolve_overloaded_unification
12541                         (tparms, targs, parm, arg, strict, sub_strict)
12542                         != 0)
12543                       return 1;
12544                     skip_arg_p = true;
12545                   }
12546
12547                 if (!skip_arg_p)
12548                   {
12549                     arg_expr = arg;
12550                     arg = unlowered_expr_type (arg);
12551                     if (arg == error_mark_node)
12552                       return 1;
12553                   }
12554               }
12555       
12556             arg_strict = sub_strict;
12557
12558             if (!subr)
12559               arg_strict |= 
12560                 maybe_adjust_types_for_deduction (strict, &parm, &arg, 
12561                                                   arg_expr);
12562           }
12563
12564         if (!skip_arg_p)
12565           {
12566             if (unify (tparms, targs, parm, arg, arg_strict))
12567               return 1;
12568           }
12569       }
12570
12571       /* For each parameter pack, collect the deduced value.  */
12572       for (pack = packs; pack; pack = TREE_CHAIN (pack))
12573         {
12574           int idx, level;
12575           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12576
12577           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
12578             TMPL_ARG (targs, level, idx);
12579         }
12580     }
12581
12582   /* Verify that the results of unification with the parameter packs
12583      produce results consistent with what we've seen before, and make
12584      the deduced argument packs available.  */
12585   for (pack = packs; pack; pack = TREE_CHAIN (pack))
12586     {
12587       tree old_pack = TREE_VALUE (pack);
12588       tree new_args = TREE_TYPE (pack);
12589       int i, len = TREE_VEC_LENGTH (new_args);
12590       bool nondeduced_p = false;
12591
12592       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
12593          actually deduce anything.  */
12594       for (i = 0; i < len && !nondeduced_p; ++i)
12595         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
12596           nondeduced_p = true;
12597       if (nondeduced_p)
12598         continue;
12599
12600       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
12601         {
12602           /* Prepend the explicit arguments onto NEW_ARGS.  */
12603           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
12604           tree old_args = new_args;
12605           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
12606           int len = explicit_len + TREE_VEC_LENGTH (old_args);
12607
12608           /* Copy the explicit arguments.  */
12609           new_args = make_tree_vec (len);
12610           for (i = 0; i < explicit_len; i++)
12611             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
12612
12613           /* Copy the deduced arguments.  */
12614           for (; i < len; i++)
12615             TREE_VEC_ELT (new_args, i) =
12616               TREE_VEC_ELT (old_args, i - explicit_len);
12617         }
12618
12619       if (!old_pack)
12620         {
12621           tree result;
12622           int idx, level;
12623           
12624           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12625
12626           /* Build the deduced *_ARGUMENT_PACK.  */
12627           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
12628             {
12629               result = make_node (NONTYPE_ARGUMENT_PACK);
12630               TREE_TYPE (result) = 
12631                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
12632               TREE_CONSTANT (result) = 1;
12633             }
12634           else
12635             result = make_node (TYPE_ARGUMENT_PACK);
12636
12637           SET_ARGUMENT_PACK_ARGS (result, new_args);
12638
12639           /* Note the deduced argument packs for this parameter
12640              pack.  */
12641           TMPL_ARG (targs, level, idx) = result;
12642         }
12643       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
12644                && (ARGUMENT_PACK_ARGS (old_pack) 
12645                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
12646         {
12647           /* We only had the explicitly-provided arguments before, but
12648              now we have a complete set of arguments.  */
12649           int idx, level;
12650           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
12651           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12652
12653           /* Keep the original deduced argument pack.  */
12654           TMPL_ARG (targs, level, idx) = old_pack;
12655
12656           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
12657           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
12658           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
12659         }
12660       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
12661                                     new_args))
12662         /* Inconsistent unification of this parameter pack.  */
12663         return 1;
12664       else
12665         {
12666           int idx, level;
12667           
12668           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12669
12670           /* Keep the original deduced argument pack.  */
12671           TMPL_ARG (targs, level, idx) = old_pack;
12672         }
12673     }
12674
12675   return 0;
12676 }
12677
12678 /* Deduce the value of template parameters.  TPARMS is the (innermost)
12679    set of template parameters to a template.  TARGS is the bindings
12680    for those template parameters, as determined thus far; TARGS may
12681    include template arguments for outer levels of template parameters
12682    as well.  PARM is a parameter to a template function, or a
12683    subcomponent of that parameter; ARG is the corresponding argument.
12684    This function attempts to match PARM with ARG in a manner
12685    consistent with the existing assignments in TARGS.  If more values
12686    are deduced, then TARGS is updated.
12687
12688    Returns 0 if the type deduction succeeds, 1 otherwise.  The
12689    parameter STRICT is a bitwise or of the following flags:
12690
12691      UNIFY_ALLOW_NONE:
12692        Require an exact match between PARM and ARG.
12693      UNIFY_ALLOW_MORE_CV_QUAL:
12694        Allow the deduced ARG to be more cv-qualified (by qualification
12695        conversion) than ARG.
12696      UNIFY_ALLOW_LESS_CV_QUAL:
12697        Allow the deduced ARG to be less cv-qualified than ARG.
12698      UNIFY_ALLOW_DERIVED:
12699        Allow the deduced ARG to be a template base class of ARG,
12700        or a pointer to a template base class of the type pointed to by
12701        ARG.
12702      UNIFY_ALLOW_INTEGER:
12703        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
12704        case for more information.
12705      UNIFY_ALLOW_OUTER_LEVEL:
12706        This is the outermost level of a deduction. Used to determine validity
12707        of qualification conversions. A valid qualification conversion must
12708        have const qualified pointers leading up to the inner type which
12709        requires additional CV quals, except at the outer level, where const
12710        is not required [conv.qual]. It would be normal to set this flag in
12711        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
12712      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
12713        This is the outermost level of a deduction, and PARM can be more CV
12714        qualified at this point.
12715      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
12716        This is the outermost level of a deduction, and PARM can be less CV
12717        qualified at this point.  */
12718
12719 static int
12720 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
12721 {
12722   int idx;
12723   tree targ;
12724   tree tparm;
12725   int strict_in = strict;
12726
12727   /* I don't think this will do the right thing with respect to types.
12728      But the only case I've seen it in so far has been array bounds, where
12729      signedness is the only information lost, and I think that will be
12730      okay.  */
12731   while (TREE_CODE (parm) == NOP_EXPR)
12732     parm = TREE_OPERAND (parm, 0);
12733
12734   if (arg == error_mark_node)
12735     return 1;
12736   if (arg == unknown_type_node)
12737     /* We can't deduce anything from this, but we might get all the
12738        template args from other function args.  */
12739     return 0;
12740
12741   /* If PARM uses template parameters, then we can't bail out here,
12742      even if ARG == PARM, since we won't record unifications for the
12743      template parameters.  We might need them if we're trying to
12744      figure out which of two things is more specialized.  */
12745   if (arg == parm && !uses_template_parms (parm))
12746     return 0;
12747
12748   /* Immediately reject some pairs that won't unify because of
12749      cv-qualification mismatches.  */
12750   if (TREE_CODE (arg) == TREE_CODE (parm)
12751       && TYPE_P (arg)
12752       /* It is the elements of the array which hold the cv quals of an array
12753          type, and the elements might be template type parms. We'll check
12754          when we recurse.  */
12755       && TREE_CODE (arg) != ARRAY_TYPE
12756       /* We check the cv-qualifiers when unifying with template type
12757          parameters below.  We want to allow ARG `const T' to unify with
12758          PARM `T' for example, when computing which of two templates
12759          is more specialized, for example.  */
12760       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
12761       && !check_cv_quals_for_unify (strict_in, arg, parm))
12762     return 1;
12763
12764   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
12765       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
12766     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
12767   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
12768   strict &= ~UNIFY_ALLOW_DERIVED;
12769   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12770   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
12771
12772   switch (TREE_CODE (parm))
12773     {
12774     case TYPENAME_TYPE:
12775     case SCOPE_REF:
12776     case UNBOUND_CLASS_TEMPLATE:
12777       /* In a type which contains a nested-name-specifier, template
12778          argument values cannot be deduced for template parameters used
12779          within the nested-name-specifier.  */
12780       return 0;
12781
12782     case TEMPLATE_TYPE_PARM:
12783     case TEMPLATE_TEMPLATE_PARM:
12784     case BOUND_TEMPLATE_TEMPLATE_PARM:
12785       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
12786       if (tparm == error_mark_node)
12787         return 1;
12788
12789       if (TEMPLATE_TYPE_LEVEL (parm)
12790           != template_decl_level (tparm))
12791         /* The PARM is not one we're trying to unify.  Just check
12792            to see if it matches ARG.  */
12793         return (TREE_CODE (arg) == TREE_CODE (parm)
12794                 && same_type_p (parm, arg)) ? 0 : 1;
12795       idx = TEMPLATE_TYPE_IDX (parm);
12796       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
12797       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
12798
12799       /* Check for mixed types and values.  */
12800       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12801            && TREE_CODE (tparm) != TYPE_DECL)
12802           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12803               && TREE_CODE (tparm) != TEMPLATE_DECL))
12804         return 1;
12805
12806       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12807         {
12808           /* ARG must be constructed from a template class or a template
12809              template parameter.  */
12810           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
12811               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
12812             return 1;
12813
12814           {
12815             tree parmvec = TYPE_TI_ARGS (parm);
12816             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
12817             tree argtmplvec
12818               = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_TI_TEMPLATE (arg));
12819             int i, len;
12820             int parm_variadic_p = 0;
12821
12822             /* The resolution to DR150 makes clear that default
12823                arguments for an N-argument may not be used to bind T
12824                to a template template parameter with fewer than N
12825                parameters.  It is not safe to permit the binding of
12826                default arguments as an extension, as that may change
12827                the meaning of a conforming program.  Consider:
12828
12829                   struct Dense { static const unsigned int dim = 1; };
12830
12831                   template <template <typename> class View,
12832                             typename Block>
12833                   void operator+(float, View<Block> const&);
12834
12835                   template <typename Block,
12836                             unsigned int Dim = Block::dim>
12837                   struct Lvalue_proxy { operator float() const; };
12838
12839                   void
12840                   test_1d (void) {
12841                     Lvalue_proxy<Dense> p;
12842                     float b;
12843                     b + p;
12844                   }
12845
12846               Here, if Lvalue_proxy is permitted to bind to View, then
12847               the global operator+ will be used; if they are not, the
12848               Lvalue_proxy will be converted to float.  */
12849             if (coerce_template_parms (argtmplvec, parmvec,
12850                                        TYPE_TI_TEMPLATE (parm),
12851                                        tf_none,
12852                                        /*require_all_args=*/true,
12853                                        /*use_default_args=*/false)
12854                 == error_mark_node)
12855               return 1;
12856
12857             /* Deduce arguments T, i from TT<T> or TT<i>.
12858                We check each element of PARMVEC and ARGVEC individually
12859                rather than the whole TREE_VEC since they can have
12860                different number of elements.  */
12861
12862             parmvec = expand_template_argument_pack (parmvec);
12863             argvec = expand_template_argument_pack (argvec);
12864
12865             len = TREE_VEC_LENGTH (parmvec);
12866
12867             /* Check if the parameters end in a pack, making them
12868                variadic.  */
12869             if (len > 0
12870                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
12871               parm_variadic_p = 1;
12872             
12873             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
12874               return 1;
12875
12876              for (i = 0; i < len - parm_variadic_p; ++i)
12877               {
12878                 if (unify (tparms, targs,
12879                            TREE_VEC_ELT (parmvec, i),
12880                            TREE_VEC_ELT (argvec, i),
12881                            UNIFY_ALLOW_NONE))
12882                   return 1;
12883               }
12884
12885             if (parm_variadic_p
12886                 && unify_pack_expansion (tparms, targs,
12887                                          parmvec, argvec,
12888                                          UNIFY_ALLOW_NONE,
12889                                          /*call_args_p=*/false,
12890                                          /*subr=*/false))
12891               return 1;
12892           }
12893           arg = TYPE_TI_TEMPLATE (arg);
12894
12895           /* Fall through to deduce template name.  */
12896         }
12897
12898       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12899           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12900         {
12901           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
12902
12903           /* Simple cases: Value already set, does match or doesn't.  */
12904           if (targ != NULL_TREE && template_args_equal (targ, arg))
12905             return 0;
12906           else if (targ)
12907             return 1;
12908         }
12909       else
12910         {
12911           /* If PARM is `const T' and ARG is only `int', we don't have
12912              a match unless we are allowing additional qualification.
12913              If ARG is `const int' and PARM is just `T' that's OK;
12914              that binds `const int' to `T'.  */
12915           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
12916                                          arg, parm))
12917             return 1;
12918
12919           /* Consider the case where ARG is `const volatile int' and
12920              PARM is `const T'.  Then, T should be `volatile int'.  */
12921           arg = cp_build_qualified_type_real
12922             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
12923           if (arg == error_mark_node)
12924             return 1;
12925
12926           /* Simple cases: Value already set, does match or doesn't.  */
12927           if (targ != NULL_TREE && same_type_p (targ, arg))
12928             return 0;
12929           else if (targ)
12930             return 1;
12931
12932           /* Make sure that ARG is not a variable-sized array.  (Note
12933              that were talking about variable-sized arrays (like
12934              `int[n]'), rather than arrays of unknown size (like
12935              `int[]').)  We'll get very confused by such a type since
12936              the bound of the array will not be computable in an
12937              instantiation.  Besides, such types are not allowed in
12938              ISO C++, so we can do as we please here.  */
12939           if (variably_modified_type_p (arg, NULL_TREE))
12940             return 1;
12941         }
12942
12943       /* If ARG is a parameter pack or an expansion, we cannot unify
12944          against it unless PARM is also a parameter pack.  */
12945       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
12946           && !template_parameter_pack_p (parm))
12947         return 1;
12948
12949       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
12950       return 0;
12951
12952     case TEMPLATE_PARM_INDEX:
12953       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
12954       if (tparm == error_mark_node)
12955         return 1;
12956
12957       if (TEMPLATE_PARM_LEVEL (parm)
12958           != template_decl_level (tparm))
12959         /* The PARM is not one we're trying to unify.  Just check
12960            to see if it matches ARG.  */
12961         return !(TREE_CODE (arg) == TREE_CODE (parm)
12962                  && cp_tree_equal (parm, arg));
12963
12964       idx = TEMPLATE_PARM_IDX (parm);
12965       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
12966
12967       if (targ)
12968         return !cp_tree_equal (targ, arg);
12969
12970       /* [temp.deduct.type] If, in the declaration of a function template
12971          with a non-type template-parameter, the non-type
12972          template-parameter is used in an expression in the function
12973          parameter-list and, if the corresponding template-argument is
12974          deduced, the template-argument type shall match the type of the
12975          template-parameter exactly, except that a template-argument
12976          deduced from an array bound may be of any integral type.
12977          The non-type parameter might use already deduced type parameters.  */
12978       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
12979       if (!TREE_TYPE (arg))
12980         /* Template-parameter dependent expression.  Just accept it for now.
12981            It will later be processed in convert_template_argument.  */
12982         ;
12983       else if (same_type_p (TREE_TYPE (arg), tparm))
12984         /* OK */;
12985       else if ((strict & UNIFY_ALLOW_INTEGER)
12986                && (TREE_CODE (tparm) == INTEGER_TYPE
12987                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
12988         /* Convert the ARG to the type of PARM; the deduced non-type
12989            template argument must exactly match the types of the
12990            corresponding parameter.  */
12991         arg = fold (build_nop (TREE_TYPE (parm), arg));
12992       else if (uses_template_parms (tparm))
12993         /* We haven't deduced the type of this parameter yet.  Try again
12994            later.  */
12995         return 0;
12996       else
12997         return 1;
12998
12999       /* If ARG is a parameter pack or an expansion, we cannot unify
13000          against it unless PARM is also a parameter pack.  */
13001       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13002           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
13003         return 1;
13004
13005       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13006       return 0;
13007
13008     case PTRMEM_CST:
13009      {
13010         /* A pointer-to-member constant can be unified only with
13011          another constant.  */
13012       if (TREE_CODE (arg) != PTRMEM_CST)
13013         return 1;
13014
13015       /* Just unify the class member. It would be useless (and possibly
13016          wrong, depending on the strict flags) to unify also
13017          PTRMEM_CST_CLASS, because we want to be sure that both parm and
13018          arg refer to the same variable, even if through different
13019          classes. For instance:
13020
13021          struct A { int x; };
13022          struct B : A { };
13023
13024          Unification of &A::x and &B::x must succeed.  */
13025       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
13026                     PTRMEM_CST_MEMBER (arg), strict);
13027      }
13028
13029     case POINTER_TYPE:
13030       {
13031         if (TREE_CODE (arg) != POINTER_TYPE)
13032           return 1;
13033
13034         /* [temp.deduct.call]
13035
13036            A can be another pointer or pointer to member type that can
13037            be converted to the deduced A via a qualification
13038            conversion (_conv.qual_).
13039
13040            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
13041            This will allow for additional cv-qualification of the
13042            pointed-to types if appropriate.  */
13043
13044         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
13045           /* The derived-to-base conversion only persists through one
13046              level of pointers.  */
13047           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
13048
13049         return unify (tparms, targs, TREE_TYPE (parm),
13050                       TREE_TYPE (arg), strict);
13051       }
13052
13053     case REFERENCE_TYPE:
13054       if (TREE_CODE (arg) != REFERENCE_TYPE)
13055         return 1;
13056       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13057                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13058
13059     case ARRAY_TYPE:
13060       if (TREE_CODE (arg) != ARRAY_TYPE)
13061         return 1;
13062       if ((TYPE_DOMAIN (parm) == NULL_TREE)
13063           != (TYPE_DOMAIN (arg) == NULL_TREE))
13064         return 1;
13065       if (TYPE_DOMAIN (parm) != NULL_TREE)
13066         {
13067           tree parm_max;
13068           tree arg_max;
13069           bool parm_cst;
13070           bool arg_cst;
13071
13072           /* Our representation of array types uses "N - 1" as the
13073              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
13074              not an integer constant.  We cannot unify arbitrarily
13075              complex expressions, so we eliminate the MINUS_EXPRs
13076              here.  */
13077           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
13078           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
13079           if (!parm_cst)
13080             {
13081               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
13082               parm_max = TREE_OPERAND (parm_max, 0);
13083             }
13084           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
13085           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
13086           if (!arg_cst)
13087             {
13088               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
13089                  trying to unify the type of a variable with the type
13090                  of a template parameter.  For example:
13091
13092                    template <unsigned int N>
13093                    void f (char (&) [N]);
13094                    int g(); 
13095                    void h(int i) {
13096                      char a[g(i)];
13097                      f(a); 
13098                    }
13099
13100                 Here, the type of the ARG will be "int [g(i)]", and
13101                 may be a SAVE_EXPR, etc.  */
13102               if (TREE_CODE (arg_max) != MINUS_EXPR)
13103                 return 1;
13104               arg_max = TREE_OPERAND (arg_max, 0);
13105             }
13106
13107           /* If only one of the bounds used a MINUS_EXPR, compensate
13108              by adding one to the other bound.  */
13109           if (parm_cst && !arg_cst)
13110             parm_max = fold_build2 (PLUS_EXPR,
13111                                     integer_type_node,
13112                                     parm_max,
13113                                     integer_one_node);
13114           else if (arg_cst && !parm_cst)
13115             arg_max = fold_build2 (PLUS_EXPR,
13116                                    integer_type_node,
13117                                    arg_max,
13118                                    integer_one_node);
13119
13120           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
13121             return 1;
13122         }
13123       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13124                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13125
13126     case REAL_TYPE:
13127     case COMPLEX_TYPE:
13128     case VECTOR_TYPE:
13129     case INTEGER_TYPE:
13130     case BOOLEAN_TYPE:
13131     case ENUMERAL_TYPE:
13132     case VOID_TYPE:
13133       if (TREE_CODE (arg) != TREE_CODE (parm))
13134         return 1;
13135
13136       /* We have already checked cv-qualification at the top of the
13137          function.  */
13138       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
13139         return 1;
13140
13141       /* As far as unification is concerned, this wins.  Later checks
13142          will invalidate it if necessary.  */
13143       return 0;
13144
13145       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
13146       /* Type INTEGER_CST can come from ordinary constant template args.  */
13147     case INTEGER_CST:
13148       while (TREE_CODE (arg) == NOP_EXPR)
13149         arg = TREE_OPERAND (arg, 0);
13150
13151       if (TREE_CODE (arg) != INTEGER_CST)
13152         return 1;
13153       return !tree_int_cst_equal (parm, arg);
13154
13155     case TREE_VEC:
13156       {
13157         int i;
13158         if (TREE_CODE (arg) != TREE_VEC)
13159           return 1;
13160         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
13161           return 1;
13162         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
13163           if (unify (tparms, targs,
13164                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
13165                      UNIFY_ALLOW_NONE))
13166             return 1;
13167         return 0;
13168       }
13169
13170     case RECORD_TYPE:
13171     case UNION_TYPE:
13172       if (TREE_CODE (arg) != TREE_CODE (parm))
13173         return 1;
13174
13175       if (TYPE_PTRMEMFUNC_P (parm))
13176         {
13177           if (!TYPE_PTRMEMFUNC_P (arg))
13178             return 1;
13179
13180           return unify (tparms, targs,
13181                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
13182                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
13183                         strict);
13184         }
13185
13186       if (CLASSTYPE_TEMPLATE_INFO (parm))
13187         {
13188           tree t = NULL_TREE;
13189
13190           if (strict_in & UNIFY_ALLOW_DERIVED)
13191             {
13192               /* First, we try to unify the PARM and ARG directly.  */
13193               t = try_class_unification (tparms, targs,
13194                                          parm, arg);
13195
13196               if (!t)
13197                 {
13198                   /* Fallback to the special case allowed in
13199                      [temp.deduct.call]:
13200
13201                        If P is a class, and P has the form
13202                        template-id, then A can be a derived class of
13203                        the deduced A.  Likewise, if P is a pointer to
13204                        a class of the form template-id, A can be a
13205                        pointer to a derived class pointed to by the
13206                        deduced A.  */
13207                   t = get_template_base (tparms, targs, parm, arg);
13208
13209                   if (!t)
13210                     return 1;
13211                 }
13212             }
13213           else if (CLASSTYPE_TEMPLATE_INFO (arg)
13214                    && (CLASSTYPE_TI_TEMPLATE (parm)
13215                        == CLASSTYPE_TI_TEMPLATE (arg)))
13216             /* Perhaps PARM is something like S<U> and ARG is S<int>.
13217                Then, we should unify `int' and `U'.  */
13218             t = arg;
13219           else
13220             /* There's no chance of unification succeeding.  */
13221             return 1;
13222
13223           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
13224                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
13225         }
13226       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
13227         return 1;
13228       return 0;
13229
13230     case METHOD_TYPE:
13231     case FUNCTION_TYPE:
13232       if (TREE_CODE (arg) != TREE_CODE (parm))
13233         return 1;
13234
13235       /* CV qualifications for methods can never be deduced, they must
13236          match exactly.  We need to check them explicitly here,
13237          because type_unification_real treats them as any other
13238          cvqualified parameter.  */
13239       if (TREE_CODE (parm) == METHOD_TYPE
13240           && (!check_cv_quals_for_unify
13241               (UNIFY_ALLOW_NONE,
13242                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
13243                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
13244         return 1;
13245
13246       if (unify (tparms, targs, TREE_TYPE (parm),
13247                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
13248         return 1;
13249       return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
13250                                     TYPE_ARG_TYPES (arg), 1, DEDUCE_EXACT,
13251                                     LOOKUP_NORMAL);
13252
13253     case OFFSET_TYPE:
13254       /* Unify a pointer to member with a pointer to member function, which
13255          deduces the type of the member as a function type. */
13256       if (TYPE_PTRMEMFUNC_P (arg))
13257         {
13258           tree method_type;
13259           tree fntype;
13260           cp_cv_quals cv_quals;
13261
13262           /* Check top-level cv qualifiers */
13263           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
13264             return 1;
13265
13266           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13267                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
13268             return 1;
13269
13270           /* Determine the type of the function we are unifying against. */
13271           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
13272           fntype =
13273             build_function_type (TREE_TYPE (method_type),
13274                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
13275
13276           /* Extract the cv-qualifiers of the member function from the
13277              implicit object parameter and place them on the function
13278              type to be restored later. */
13279           cv_quals =
13280             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
13281           fntype = build_qualified_type (fntype, cv_quals);
13282           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
13283         }
13284
13285       if (TREE_CODE (arg) != OFFSET_TYPE)
13286         return 1;
13287       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13288                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
13289         return 1;
13290       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13291                     strict);
13292
13293     case CONST_DECL:
13294       if (DECL_TEMPLATE_PARM_P (parm))
13295         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
13296       if (arg != integral_constant_value (parm))
13297         return 1;
13298       return 0;
13299
13300     case FIELD_DECL:
13301     case TEMPLATE_DECL:
13302       /* Matched cases are handled by the ARG == PARM test above.  */
13303       return 1;
13304
13305     case TYPE_ARGUMENT_PACK:
13306     case NONTYPE_ARGUMENT_PACK:
13307       {
13308         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
13309         tree packed_args = ARGUMENT_PACK_ARGS (arg);
13310         int i, len = TREE_VEC_LENGTH (packed_parms);
13311         int argslen = TREE_VEC_LENGTH (packed_args);
13312         int parm_variadic_p = 0;
13313
13314         for (i = 0; i < len; ++i)
13315           {
13316             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
13317               {
13318                 if (i == len - 1)
13319                   /* We can unify against something with a trailing
13320                      parameter pack.  */
13321                   parm_variadic_p = 1;
13322                 else
13323                   /* Since there is something following the pack
13324                      expansion, we cannot unify this template argument
13325                      list.  */
13326                   return 0;
13327               }
13328           }
13329           
13330
13331         /* If we don't have enough arguments to satisfy the parameters
13332            (not counting the pack expression at the end), or we have
13333            too many arguments for a parameter list that doesn't end in
13334            a pack expression, we can't unify.  */
13335         if (argslen < (len - parm_variadic_p)
13336             || (argslen > len && !parm_variadic_p))
13337           return 1;
13338
13339         /* Unify all of the parameters that precede the (optional)
13340            pack expression.  */
13341         for (i = 0; i < len - parm_variadic_p; ++i)
13342           {
13343             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
13344                        TREE_VEC_ELT (packed_args, i), strict))
13345               return 1;
13346           }
13347
13348         if (parm_variadic_p)
13349           return unify_pack_expansion (tparms, targs, 
13350                                        packed_parms, packed_args,
13351                                        strict, /*call_args_p=*/false,
13352                                        /*subr=*/false);
13353         return 0;
13354       }
13355
13356       break;
13357
13358     case TYPEOF_TYPE:
13359     case DECLTYPE_TYPE:
13360       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
13361          nodes.  */
13362       return 0;
13363
13364     case ERROR_MARK:
13365       /* Unification fails if we hit an error node.  */
13366       return 1;
13367
13368     default:
13369       gcc_assert (EXPR_P (parm));
13370
13371       /* We must be looking at an expression.  This can happen with
13372          something like:
13373
13374            template <int I>
13375            void foo(S<I>, S<I + 2>);
13376
13377          This is a "nondeduced context":
13378
13379            [deduct.type]
13380
13381            The nondeduced contexts are:
13382
13383            --A type that is a template-id in which one or more of
13384              the template-arguments is an expression that references
13385              a template-parameter.
13386
13387          In these cases, we assume deduction succeeded, but don't
13388          actually infer any unifications.  */
13389
13390       if (!uses_template_parms (parm)
13391           && !template_args_equal (parm, arg))
13392         return 1;
13393       else
13394         return 0;
13395     }
13396 }
13397 \f
13398 /* Note that DECL can be defined in this translation unit, if
13399    required.  */
13400
13401 static void
13402 mark_definable (tree decl)
13403 {
13404   tree clone;
13405   DECL_NOT_REALLY_EXTERN (decl) = 1;
13406   FOR_EACH_CLONE (clone, decl)
13407     DECL_NOT_REALLY_EXTERN (clone) = 1;
13408 }
13409
13410 /* Called if RESULT is explicitly instantiated, or is a member of an
13411    explicitly instantiated class.  */
13412
13413 void
13414 mark_decl_instantiated (tree result, int extern_p)
13415 {
13416   SET_DECL_EXPLICIT_INSTANTIATION (result);
13417
13418   /* If this entity has already been written out, it's too late to
13419      make any modifications.  */
13420   if (TREE_ASM_WRITTEN (result))
13421     return;
13422
13423   if (TREE_CODE (result) != FUNCTION_DECL)
13424     /* The TREE_PUBLIC flag for function declarations will have been
13425        set correctly by tsubst.  */
13426     TREE_PUBLIC (result) = 1;
13427
13428   /* This might have been set by an earlier implicit instantiation.  */
13429   DECL_COMDAT (result) = 0;
13430
13431   if (extern_p)
13432     DECL_NOT_REALLY_EXTERN (result) = 0;
13433   else
13434     {
13435       mark_definable (result);
13436       /* Always make artificials weak.  */
13437       if (DECL_ARTIFICIAL (result) && flag_weak)
13438         comdat_linkage (result);
13439       /* For WIN32 we also want to put explicit instantiations in
13440          linkonce sections.  */
13441       else if (TREE_PUBLIC (result))
13442         maybe_make_one_only (result);
13443     }
13444
13445   /* If EXTERN_P, then this function will not be emitted -- unless
13446      followed by an explicit instantiation, at which point its linkage
13447      will be adjusted.  If !EXTERN_P, then this function will be
13448      emitted here.  In neither circumstance do we want
13449      import_export_decl to adjust the linkage.  */
13450   DECL_INTERFACE_KNOWN (result) = 1;
13451 }
13452
13453 /* Given two function templates PAT1 and PAT2, return:
13454
13455    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
13456    -1 if PAT2 is more specialized than PAT1.
13457    0 if neither is more specialized.
13458
13459    LEN indicates the number of parameters we should consider
13460    (defaulted parameters should not be considered).
13461
13462    The 1998 std underspecified function template partial ordering, and
13463    DR214 addresses the issue.  We take pairs of arguments, one from
13464    each of the templates, and deduce them against each other.  One of
13465    the templates will be more specialized if all the *other*
13466    template's arguments deduce against its arguments and at least one
13467    of its arguments *does* *not* deduce against the other template's
13468    corresponding argument.  Deduction is done as for class templates.
13469    The arguments used in deduction have reference and top level cv
13470    qualifiers removed.  Iff both arguments were originally reference
13471    types *and* deduction succeeds in both directions, the template
13472    with the more cv-qualified argument wins for that pairing (if
13473    neither is more cv-qualified, they both are equal).  Unlike regular
13474    deduction, after all the arguments have been deduced in this way,
13475    we do *not* verify the deduced template argument values can be
13476    substituted into non-deduced contexts, nor do we have to verify
13477    that all template arguments have been deduced.  */
13478
13479 int
13480 more_specialized_fn (tree pat1, tree pat2, int len)
13481 {
13482   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
13483   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
13484   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
13485   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
13486   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
13487   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
13488   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
13489   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
13490   int better1 = 0;
13491   int better2 = 0;
13492
13493   /* Remove the this parameter from non-static member functions.  If
13494      one is a non-static member function and the other is not a static
13495      member function, remove the first parameter from that function
13496      also.  This situation occurs for operator functions where we
13497      locate both a member function (with this pointer) and non-member
13498      operator (with explicit first operand).  */
13499   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
13500     {
13501       len--; /* LEN is the number of significant arguments for DECL1 */
13502       args1 = TREE_CHAIN (args1);
13503       if (!DECL_STATIC_FUNCTION_P (decl2))
13504         args2 = TREE_CHAIN (args2);
13505     }
13506   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
13507     {
13508       args2 = TREE_CHAIN (args2);
13509       if (!DECL_STATIC_FUNCTION_P (decl1))
13510         {
13511           len--;
13512           args1 = TREE_CHAIN (args1);
13513         }
13514     }
13515
13516   /* If only one is a conversion operator, they are unordered.  */
13517   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
13518     return 0;
13519
13520   /* Consider the return type for a conversion function */
13521   if (DECL_CONV_FN_P (decl1))
13522     {
13523       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
13524       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
13525       len++;
13526     }
13527
13528   processing_template_decl++;
13529
13530   while (len--)
13531     {
13532       tree arg1 = TREE_VALUE (args1);
13533       tree arg2 = TREE_VALUE (args2);
13534       int deduce1, deduce2;
13535       int quals1 = -1;
13536       int quals2 = -1;
13537
13538       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
13539           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13540         {
13541           /* When both arguments are pack expansions, we need only
13542              unify the patterns themselves.  */
13543           arg1 = PACK_EXPANSION_PATTERN (arg1);
13544           arg2 = PACK_EXPANSION_PATTERN (arg2);
13545
13546           /* This is the last comparison we need to do.  */
13547           len = 0;
13548         }
13549
13550       if (TREE_CODE (arg1) == REFERENCE_TYPE)
13551         {
13552           arg1 = TREE_TYPE (arg1);
13553           quals1 = cp_type_quals (arg1);
13554         }
13555
13556       if (TREE_CODE (arg2) == REFERENCE_TYPE)
13557         {
13558           arg2 = TREE_TYPE (arg2);
13559           quals2 = cp_type_quals (arg2);
13560         }
13561
13562       if ((quals1 < 0) != (quals2 < 0))
13563         {
13564           /* Only of the args is a reference, see if we should apply
13565              array/function pointer decay to it.  This is not part of
13566              DR214, but is, IMHO, consistent with the deduction rules
13567              for the function call itself, and with our earlier
13568              implementation of the underspecified partial ordering
13569              rules.  (nathan).  */
13570           if (quals1 >= 0)
13571             {
13572               switch (TREE_CODE (arg1))
13573                 {
13574                 case ARRAY_TYPE:
13575                   arg1 = TREE_TYPE (arg1);
13576                   /* FALLTHROUGH. */
13577                 case FUNCTION_TYPE:
13578                   arg1 = build_pointer_type (arg1);
13579                   break;
13580
13581                 default:
13582                   break;
13583                 }
13584             }
13585           else
13586             {
13587               switch (TREE_CODE (arg2))
13588                 {
13589                 case ARRAY_TYPE:
13590                   arg2 = TREE_TYPE (arg2);
13591                   /* FALLTHROUGH. */
13592                 case FUNCTION_TYPE:
13593                   arg2 = build_pointer_type (arg2);
13594                   break;
13595
13596                 default:
13597                   break;
13598                 }
13599             }
13600         }
13601
13602       arg1 = TYPE_MAIN_VARIANT (arg1);
13603       arg2 = TYPE_MAIN_VARIANT (arg2);
13604
13605       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
13606         {
13607           int i, len2 = list_length (args2);
13608           tree parmvec = make_tree_vec (1);
13609           tree argvec = make_tree_vec (len2);
13610           tree ta = args2;
13611
13612           /* Setup the parameter vector, which contains only ARG1.  */
13613           TREE_VEC_ELT (parmvec, 0) = arg1;
13614
13615           /* Setup the argument vector, which contains the remaining
13616              arguments.  */
13617           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
13618             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
13619
13620           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
13621                                            argvec, UNIFY_ALLOW_NONE, 
13622                                            /*call_args_p=*/false, 
13623                                            /*subr=*/0);
13624
13625           /* We cannot deduce in the other direction, because ARG1 is
13626              a pack expansion but ARG2 is not.  */
13627           deduce2 = 0;
13628         }
13629       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13630         {
13631           int i, len1 = list_length (args1);
13632           tree parmvec = make_tree_vec (1);
13633           tree argvec = make_tree_vec (len1);
13634           tree ta = args1;
13635
13636           /* Setup the parameter vector, which contains only ARG1.  */
13637           TREE_VEC_ELT (parmvec, 0) = arg2;
13638
13639           /* Setup the argument vector, which contains the remaining
13640              arguments.  */
13641           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
13642             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
13643
13644           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
13645                                            argvec, UNIFY_ALLOW_NONE, 
13646                                            /*call_args_p=*/false, 
13647                                            /*subr=*/0);
13648
13649           /* We cannot deduce in the other direction, because ARG2 is
13650              a pack expansion but ARG1 is not.*/
13651           deduce1 = 0;
13652         }
13653
13654       else
13655         {
13656           /* The normal case, where neither argument is a pack
13657              expansion.  */
13658           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
13659           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
13660         }
13661
13662       if (!deduce1)
13663         better2 = -1;
13664       if (!deduce2)
13665         better1 = -1;
13666       if (better1 < 0 && better2 < 0)
13667         /* We've failed to deduce something in either direction.
13668            These must be unordered.  */
13669         break;
13670
13671       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
13672         {
13673           /* Deduces in both directions, see if quals can
13674              disambiguate.  Pretend the worse one failed to deduce. */
13675           if ((quals1 & quals2) == quals2)
13676             deduce1 = 0;
13677           if ((quals1 & quals2) == quals1)
13678             deduce2 = 0;
13679         }
13680       if (deduce1 && !deduce2 && !better2)
13681         better2 = 1;
13682       if (deduce2 && !deduce1 && !better1)
13683         better1 = 1;
13684
13685       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
13686           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13687         /* We have already processed all of the arguments in our
13688            handing of the pack expansion type.  */
13689         len = 0;
13690
13691       args1 = TREE_CHAIN (args1);
13692       args2 = TREE_CHAIN (args2);
13693
13694       /* Stop when an ellipsis is seen.  */
13695       if (args1 == NULL_TREE || args2 == NULL_TREE)
13696         break;
13697     }
13698
13699   processing_template_decl--;
13700
13701   /* All things being equal, if the next argument is a pack expansion
13702      for one function but not for the other, prefer the
13703      non-variadic function.  */
13704   if ((better1 > 0) - (better2 > 0) == 0
13705       && args1 && TREE_VALUE (args1)
13706       && args2 && TREE_VALUE (args2))
13707     {
13708       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
13709         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
13710       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
13711         return 1;
13712     }
13713
13714   return (better1 > 0) - (better2 > 0);
13715 }
13716
13717 /* Determine which of two partial specializations is more specialized.
13718
13719    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
13720    to the first partial specialization.  The TREE_VALUE is the
13721    innermost set of template parameters for the partial
13722    specialization.  PAT2 is similar, but for the second template.
13723
13724    Return 1 if the first partial specialization is more specialized;
13725    -1 if the second is more specialized; 0 if neither is more
13726    specialized.
13727
13728    See [temp.class.order] for information about determining which of
13729    two templates is more specialized.  */
13730
13731 static int
13732 more_specialized_class (tree pat1, tree pat2)
13733 {
13734   tree targs;
13735   tree tmpl1, tmpl2;
13736   int winner = 0;
13737   bool any_deductions = false;
13738
13739   tmpl1 = TREE_TYPE (pat1);
13740   tmpl2 = TREE_TYPE (pat2);
13741
13742   /* Just like what happens for functions, if we are ordering between
13743      different class template specializations, we may encounter dependent
13744      types in the arguments, and we need our dependency check functions
13745      to behave correctly.  */
13746   ++processing_template_decl;
13747   targs = get_class_bindings (TREE_VALUE (pat1),
13748                               CLASSTYPE_TI_ARGS (tmpl1),
13749                               CLASSTYPE_TI_ARGS (tmpl2));
13750   if (targs)
13751     {
13752       --winner;
13753       any_deductions = true;
13754     }
13755
13756   targs = get_class_bindings (TREE_VALUE (pat2),
13757                               CLASSTYPE_TI_ARGS (tmpl2),
13758                               CLASSTYPE_TI_ARGS (tmpl1));
13759   if (targs)
13760     {
13761       ++winner;
13762       any_deductions = true;
13763     }
13764   --processing_template_decl;
13765
13766   /* In the case of a tie where at least one of the class templates
13767      has a parameter pack at the end, the template with the most
13768      non-packed parameters wins.  */
13769   if (winner == 0
13770       && any_deductions
13771       && (template_args_variadic_p (TREE_PURPOSE (pat1))
13772           || template_args_variadic_p (TREE_PURPOSE (pat2))))
13773     {
13774       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
13775       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
13776       int len1 = TREE_VEC_LENGTH (args1);
13777       int len2 = TREE_VEC_LENGTH (args2);
13778
13779       /* We don't count the pack expansion at the end.  */
13780       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
13781         --len1;
13782       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
13783         --len2;
13784
13785       if (len1 > len2)
13786         return 1;
13787       else if (len1 < len2)
13788         return -1;
13789     }
13790
13791   return winner;
13792 }
13793
13794 /* Return the template arguments that will produce the function signature
13795    DECL from the function template FN, with the explicit template
13796    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
13797    also match.  Return NULL_TREE if no satisfactory arguments could be
13798    found.  */
13799
13800 static tree
13801 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
13802 {
13803   int ntparms = DECL_NTPARMS (fn);
13804   tree targs = make_tree_vec (ntparms);
13805   tree decl_type;
13806   tree decl_arg_types;
13807
13808   /* Substitute the explicit template arguments into the type of DECL.
13809      The call to fn_type_unification will handle substitution into the
13810      FN.  */
13811   decl_type = TREE_TYPE (decl);
13812   if (explicit_args && uses_template_parms (decl_type))
13813     {
13814       tree tmpl;
13815       tree converted_args;
13816
13817       if (DECL_TEMPLATE_INFO (decl))
13818         tmpl = DECL_TI_TEMPLATE (decl);
13819       else
13820         /* We can get here for some invalid specializations.  */
13821         return NULL_TREE;
13822
13823       converted_args
13824         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
13825                                  explicit_args, NULL_TREE,
13826                                  tf_none,
13827                                  /*require_all_args=*/false,
13828                                  /*use_default_args=*/false);
13829       if (converted_args == error_mark_node)
13830         return NULL_TREE;
13831
13832       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
13833       if (decl_type == error_mark_node)
13834         return NULL_TREE;
13835     }
13836
13837   /* Never do unification on the 'this' parameter.  */
13838   decl_arg_types = skip_artificial_parms_for (decl, 
13839                                               TYPE_ARG_TYPES (decl_type));
13840
13841   if (fn_type_unification (fn, explicit_args, targs,
13842                            decl_arg_types,
13843                            (check_rettype || DECL_CONV_FN_P (fn)
13844                             ? TREE_TYPE (decl_type) : NULL_TREE),
13845                            DEDUCE_EXACT, LOOKUP_NORMAL))
13846     return NULL_TREE;
13847
13848   return targs;
13849 }
13850
13851 /* Return the innermost template arguments that, when applied to a
13852    template specialization whose innermost template parameters are
13853    TPARMS, and whose specialization arguments are PARMS, yield the
13854    ARGS.
13855
13856    For example, suppose we have:
13857
13858      template <class T, class U> struct S {};
13859      template <class T> struct S<T*, int> {};
13860
13861    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
13862    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
13863    int}.  The resulting vector will be {double}, indicating that `T'
13864    is bound to `double'.  */
13865
13866 static tree
13867 get_class_bindings (tree tparms, tree spec_args, tree args)
13868 {
13869   int i, ntparms = TREE_VEC_LENGTH (tparms);
13870   tree deduced_args;
13871   tree innermost_deduced_args;
13872
13873   innermost_deduced_args = make_tree_vec (ntparms);
13874   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13875     {
13876       deduced_args = copy_node (args);
13877       SET_TMPL_ARGS_LEVEL (deduced_args,
13878                            TMPL_ARGS_DEPTH (deduced_args),
13879                            innermost_deduced_args);
13880     }
13881   else
13882     deduced_args = innermost_deduced_args;
13883
13884   if (unify (tparms, deduced_args,
13885              INNERMOST_TEMPLATE_ARGS (spec_args),
13886              INNERMOST_TEMPLATE_ARGS (args),
13887              UNIFY_ALLOW_NONE))
13888     return NULL_TREE;
13889
13890   for (i =  0; i < ntparms; ++i)
13891     if (! TREE_VEC_ELT (innermost_deduced_args, i))
13892       return NULL_TREE;
13893
13894   /* Verify that nondeduced template arguments agree with the type
13895      obtained from argument deduction.
13896
13897      For example:
13898
13899        struct A { typedef int X; };
13900        template <class T, class U> struct C {};
13901        template <class T> struct C<T, typename T::X> {};
13902
13903      Then with the instantiation `C<A, int>', we can deduce that
13904      `T' is `A' but unify () does not check whether `typename T::X'
13905      is `int'.  */
13906   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
13907   if (spec_args == error_mark_node
13908       /* We only need to check the innermost arguments; the other
13909          arguments will always agree.  */
13910       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
13911                               INNERMOST_TEMPLATE_ARGS (args)))
13912     return NULL_TREE;
13913
13914   /* Now that we have bindings for all of the template arguments,
13915      ensure that the arguments deduced for the template template
13916      parameters have compatible template parameter lists.  See the use
13917      of template_template_parm_bindings_ok_p in fn_type_unification
13918      for more information.  */
13919   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
13920     return NULL_TREE;
13921
13922   return deduced_args;
13923 }
13924
13925 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
13926    Return the TREE_LIST node with the most specialized template, if
13927    any.  If there is no most specialized template, the error_mark_node
13928    is returned.
13929
13930    Note that this function does not look at, or modify, the
13931    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
13932    returned is one of the elements of INSTANTIATIONS, callers may
13933    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
13934    and retrieve it from the value returned.  */
13935
13936 tree
13937 most_specialized_instantiation (tree templates)
13938 {
13939   tree fn, champ;
13940
13941   ++processing_template_decl;
13942
13943   champ = templates;
13944   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
13945     {
13946       int fate = 0;
13947
13948       if (get_bindings (TREE_VALUE (champ),
13949                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
13950                         NULL_TREE, /*check_ret=*/false))
13951         fate--;
13952
13953       if (get_bindings (TREE_VALUE (fn),
13954                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
13955                         NULL_TREE, /*check_ret=*/false))
13956         fate++;
13957
13958       if (fate == -1)
13959         champ = fn;
13960       else if (!fate)
13961         {
13962           /* Equally specialized, move to next function.  If there
13963              is no next function, nothing's most specialized.  */
13964           fn = TREE_CHAIN (fn);
13965           champ = fn;
13966           if (!fn)
13967             break;
13968         }
13969     }
13970
13971   if (champ)
13972     /* Now verify that champ is better than everything earlier in the
13973        instantiation list.  */
13974     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
13975       if (get_bindings (TREE_VALUE (champ),
13976                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
13977                         NULL_TREE, /*check_ret=*/false)
13978           || !get_bindings (TREE_VALUE (fn),
13979                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
13980                             NULL_TREE, /*check_ret=*/false))
13981         {
13982           champ = NULL_TREE;
13983           break;
13984         }
13985
13986   processing_template_decl--;
13987
13988   if (!champ)
13989     return error_mark_node;
13990
13991   return champ;
13992 }
13993
13994 /* If DECL is a specialization of some template, return the most
13995    general such template.  Otherwise, returns NULL_TREE.
13996
13997    For example, given:
13998
13999      template <class T> struct S { template <class U> void f(U); };
14000
14001    if TMPL is `template <class U> void S<int>::f(U)' this will return
14002    the full template.  This function will not trace past partial
14003    specializations, however.  For example, given in addition:
14004
14005      template <class T> struct S<T*> { template <class U> void f(U); };
14006
14007    if TMPL is `template <class U> void S<int*>::f(U)' this will return
14008    `template <class T> template <class U> S<T*>::f(U)'.  */
14009
14010 tree
14011 most_general_template (tree decl)
14012 {
14013   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
14014      an immediate specialization.  */
14015   if (TREE_CODE (decl) == FUNCTION_DECL)
14016     {
14017       if (DECL_TEMPLATE_INFO (decl)) {
14018         decl = DECL_TI_TEMPLATE (decl);
14019
14020         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
14021            template friend.  */
14022         if (TREE_CODE (decl) != TEMPLATE_DECL)
14023           return NULL_TREE;
14024       } else
14025         return NULL_TREE;
14026     }
14027
14028   /* Look for more and more general templates.  */
14029   while (DECL_TEMPLATE_INFO (decl))
14030     {
14031       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
14032          (See cp-tree.h for details.)  */
14033       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
14034         break;
14035
14036       if (CLASS_TYPE_P (TREE_TYPE (decl))
14037           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
14038         break;
14039
14040       /* Stop if we run into an explicitly specialized class template.  */
14041       if (!DECL_NAMESPACE_SCOPE_P (decl)
14042           && DECL_CONTEXT (decl)
14043           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
14044         break;
14045
14046       decl = DECL_TI_TEMPLATE (decl);
14047     }
14048
14049   return decl;
14050 }
14051
14052 /* Return the most specialized of the class template partial
14053    specializations of TMPL which can produce TYPE, a specialization of
14054    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
14055    a _TYPE node corresponding to the partial specialization, while the
14056    TREE_PURPOSE is the set of template arguments that must be
14057    substituted into the TREE_TYPE in order to generate TYPE.
14058
14059    If the choice of partial specialization is ambiguous, a diagnostic
14060    is issued, and the error_mark_node is returned.  If there are no
14061    partial specializations of TMPL matching TYPE, then NULL_TREE is
14062    returned.  */
14063
14064 static tree
14065 most_specialized_class (tree type, tree tmpl)
14066 {
14067   tree list = NULL_TREE;
14068   tree t;
14069   tree champ;
14070   int fate;
14071   bool ambiguous_p;
14072   tree args;
14073   tree outer_args = NULL_TREE;
14074
14075   tmpl = most_general_template (tmpl);
14076   args = CLASSTYPE_TI_ARGS (type);
14077
14078   /* For determining which partial specialization to use, only the
14079      innermost args are interesting.  */
14080   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14081     {
14082       outer_args = strip_innermost_template_args (args, 1);
14083       args = INNERMOST_TEMPLATE_ARGS (args);
14084     }
14085
14086   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
14087     {
14088       tree partial_spec_args;
14089       tree spec_args;
14090       tree parms = TREE_VALUE (t);
14091
14092       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
14093       if (outer_args)
14094         {
14095           int i;
14096
14097           ++processing_template_decl;
14098
14099           /* Discard the outer levels of args, and then substitute in the
14100              template args from the enclosing class.  */
14101           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
14102           partial_spec_args = tsubst_template_args
14103             (partial_spec_args, outer_args, tf_none, NULL_TREE);
14104
14105           /* PARMS already refers to just the innermost parms, but the
14106              template parms in partial_spec_args had their levels lowered
14107              by tsubst, so we need to do the same for the parm list.  We
14108              can't just tsubst the TREE_VEC itself, as tsubst wants to
14109              treat a TREE_VEC as an argument vector.  */
14110           parms = copy_node (parms);
14111           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
14112             TREE_VEC_ELT (parms, i) =
14113               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
14114
14115           --processing_template_decl;
14116         }
14117       spec_args = get_class_bindings (parms,
14118                                       partial_spec_args,
14119                                       args);
14120       if (spec_args)
14121         {
14122           if (outer_args)
14123             spec_args = add_to_template_args (outer_args, spec_args);
14124           list = tree_cons (spec_args, TREE_VALUE (t), list);
14125           TREE_TYPE (list) = TREE_TYPE (t);
14126         }
14127     }
14128
14129   if (! list)
14130     return NULL_TREE;
14131
14132   ambiguous_p = false;
14133   t = list;
14134   champ = t;
14135   t = TREE_CHAIN (t);
14136   for (; t; t = TREE_CHAIN (t))
14137     {
14138       fate = more_specialized_class (champ, t);
14139       if (fate == 1)
14140         ;
14141       else
14142         {
14143           if (fate == 0)
14144             {
14145               t = TREE_CHAIN (t);
14146               if (! t)
14147                 {
14148                   ambiguous_p = true;
14149                   break;
14150                 }
14151             }
14152           champ = t;
14153         }
14154     }
14155
14156   if (!ambiguous_p)
14157     for (t = list; t && t != champ; t = TREE_CHAIN (t))
14158       {
14159         fate = more_specialized_class (champ, t);
14160         if (fate != 1)
14161           {
14162             ambiguous_p = true;
14163             break;
14164           }
14165       }
14166
14167   if (ambiguous_p)
14168     {
14169       const char *str = "candidates are:";
14170       error ("ambiguous class template instantiation for %q#T", type);
14171       for (t = list; t; t = TREE_CHAIN (t))
14172         {
14173           error ("%s %+#T", str, TREE_TYPE (t));
14174           str = "               ";
14175         }
14176       return error_mark_node;
14177     }
14178
14179   return champ;
14180 }
14181
14182 /* Explicitly instantiate DECL.  */
14183
14184 void
14185 do_decl_instantiation (tree decl, tree storage)
14186 {
14187   tree result = NULL_TREE;
14188   int extern_p = 0;
14189
14190   if (!decl || decl == error_mark_node)
14191     /* An error occurred, for which grokdeclarator has already issued
14192        an appropriate message.  */
14193     return;
14194   else if (! DECL_LANG_SPECIFIC (decl))
14195     {
14196       error ("explicit instantiation of non-template %q#D", decl);
14197       return;
14198     }
14199   else if (TREE_CODE (decl) == VAR_DECL)
14200     {
14201       /* There is an asymmetry here in the way VAR_DECLs and
14202          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
14203          the latter, the DECL we get back will be marked as a
14204          template instantiation, and the appropriate
14205          DECL_TEMPLATE_INFO will be set up.  This does not happen for
14206          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
14207          should handle VAR_DECLs as it currently handles
14208          FUNCTION_DECLs.  */
14209       if (!DECL_CLASS_SCOPE_P (decl))
14210         {
14211           error ("%qD is not a static data member of a class template", decl);
14212           return;
14213         }
14214       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
14215       if (!result || TREE_CODE (result) != VAR_DECL)
14216         {
14217           error ("no matching template for %qD found", decl);
14218           return;
14219         }
14220       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
14221         {
14222           error ("type %qT for explicit instantiation %qD does not match "
14223                  "declared type %qT", TREE_TYPE (result), decl,
14224                  TREE_TYPE (decl));
14225           return;
14226         }
14227     }
14228   else if (TREE_CODE (decl) != FUNCTION_DECL)
14229     {
14230       error ("explicit instantiation of %q#D", decl);
14231       return;
14232     }
14233   else
14234     result = decl;
14235
14236   /* Check for various error cases.  Note that if the explicit
14237      instantiation is valid the RESULT will currently be marked as an
14238      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
14239      until we get here.  */
14240
14241   if (DECL_TEMPLATE_SPECIALIZATION (result))
14242     {
14243       /* DR 259 [temp.spec].
14244
14245          Both an explicit instantiation and a declaration of an explicit
14246          specialization shall not appear in a program unless the explicit
14247          instantiation follows a declaration of the explicit specialization.
14248
14249          For a given set of template parameters, if an explicit
14250          instantiation of a template appears after a declaration of an
14251          explicit specialization for that template, the explicit
14252          instantiation has no effect.  */
14253       return;
14254     }
14255   else if (DECL_EXPLICIT_INSTANTIATION (result))
14256     {
14257       /* [temp.spec]
14258
14259          No program shall explicitly instantiate any template more
14260          than once.
14261
14262          We check DECL_NOT_REALLY_EXTERN so as not to complain when
14263          the first instantiation was `extern' and the second is not,
14264          and EXTERN_P for the opposite case.  */
14265       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
14266         pedwarn ("duplicate explicit instantiation of %q#D", result);
14267       /* If an "extern" explicit instantiation follows an ordinary
14268          explicit instantiation, the template is instantiated.  */
14269       if (extern_p)
14270         return;
14271     }
14272   else if (!DECL_IMPLICIT_INSTANTIATION (result))
14273     {
14274       error ("no matching template for %qD found", result);
14275       return;
14276     }
14277   else if (!DECL_TEMPLATE_INFO (result))
14278     {
14279       pedwarn ("explicit instantiation of non-template %q#D", result);
14280       return;
14281     }
14282
14283   if (storage == NULL_TREE)
14284     ;
14285   else if (storage == ridpointers[(int) RID_EXTERN])
14286     {
14287       if (pedantic && !in_system_header)
14288         pedwarn ("ISO C++ forbids the use of %<extern%> on explicit "
14289                  "instantiations");
14290       extern_p = 1;
14291     }
14292   else
14293     error ("storage class %qD applied to template instantiation", storage);
14294
14295   check_explicit_instantiation_namespace (result);
14296   mark_decl_instantiated (result, extern_p);
14297   if (! extern_p)
14298     instantiate_decl (result, /*defer_ok=*/1,
14299                       /*expl_inst_class_mem_p=*/false);
14300 }
14301
14302 static void
14303 mark_class_instantiated (tree t, int extern_p)
14304 {
14305   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
14306   SET_CLASSTYPE_INTERFACE_KNOWN (t);
14307   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
14308   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
14309   if (! extern_p)
14310     {
14311       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
14312       rest_of_type_compilation (t, 1);
14313     }
14314 }
14315
14316 /* Called from do_type_instantiation through binding_table_foreach to
14317    do recursive instantiation for the type bound in ENTRY.  */
14318 static void
14319 bt_instantiate_type_proc (binding_entry entry, void *data)
14320 {
14321   tree storage = *(tree *) data;
14322
14323   if (IS_AGGR_TYPE (entry->type)
14324       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
14325     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
14326 }
14327
14328 /* Called from do_type_instantiation to instantiate a member
14329    (a member function or a static member variable) of an
14330    explicitly instantiated class template.  */
14331 static void
14332 instantiate_class_member (tree decl, int extern_p)
14333 {
14334   mark_decl_instantiated (decl, extern_p);
14335   if (! extern_p)
14336     instantiate_decl (decl, /*defer_ok=*/1,
14337                       /*expl_inst_class_mem_p=*/true);
14338 }
14339
14340 /* Perform an explicit instantiation of template class T.  STORAGE, if
14341    non-null, is the RID for extern, inline or static.  COMPLAIN is
14342    nonzero if this is called from the parser, zero if called recursively,
14343    since the standard is unclear (as detailed below).  */
14344
14345 void
14346 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
14347 {
14348   int extern_p = 0;
14349   int nomem_p = 0;
14350   int static_p = 0;
14351   int previous_instantiation_extern_p = 0;
14352
14353   if (TREE_CODE (t) == TYPE_DECL)
14354     t = TREE_TYPE (t);
14355
14356   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
14357     {
14358       error ("explicit instantiation of non-template type %qT", t);
14359       return;
14360     }
14361
14362   complete_type (t);
14363
14364   if (!COMPLETE_TYPE_P (t))
14365     {
14366       if (complain & tf_error)
14367         error ("explicit instantiation of %q#T before definition of template",
14368                t);
14369       return;
14370     }
14371
14372   if (storage != NULL_TREE)
14373     {
14374       if (pedantic && !in_system_header)
14375         pedwarn("ISO C++ forbids the use of %qE on explicit instantiations",
14376                 storage);
14377
14378       if (storage == ridpointers[(int) RID_INLINE])
14379         nomem_p = 1;
14380       else if (storage == ridpointers[(int) RID_EXTERN])
14381         extern_p = 1;
14382       else if (storage == ridpointers[(int) RID_STATIC])
14383         static_p = 1;
14384       else
14385         {
14386           error ("storage class %qD applied to template instantiation",
14387                  storage);
14388           extern_p = 0;
14389         }
14390     }
14391
14392   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
14393     {
14394       /* DR 259 [temp.spec].
14395
14396          Both an explicit instantiation and a declaration of an explicit
14397          specialization shall not appear in a program unless the explicit
14398          instantiation follows a declaration of the explicit specialization.
14399
14400          For a given set of template parameters, if an explicit
14401          instantiation of a template appears after a declaration of an
14402          explicit specialization for that template, the explicit
14403          instantiation has no effect.  */
14404       return;
14405     }
14406   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
14407     {
14408       /* [temp.spec]
14409
14410          No program shall explicitly instantiate any template more
14411          than once.
14412
14413          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
14414          instantiation was `extern'.  If EXTERN_P then the second is.
14415          These cases are OK.  */
14416       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
14417
14418       if (!previous_instantiation_extern_p && !extern_p
14419           && (complain & tf_error))
14420         pedwarn ("duplicate explicit instantiation of %q#T", t);
14421
14422       /* If we've already instantiated the template, just return now.  */
14423       if (!CLASSTYPE_INTERFACE_ONLY (t))
14424         return;
14425     }
14426
14427   check_explicit_instantiation_namespace (TYPE_NAME (t));
14428   mark_class_instantiated (t, extern_p);
14429
14430   if (nomem_p)
14431     return;
14432
14433   {
14434     tree tmp;
14435
14436     /* In contrast to implicit instantiation, where only the
14437        declarations, and not the definitions, of members are
14438        instantiated, we have here:
14439
14440          [temp.explicit]
14441
14442          The explicit instantiation of a class template specialization
14443          implies the instantiation of all of its members not
14444          previously explicitly specialized in the translation unit
14445          containing the explicit instantiation.
14446
14447        Of course, we can't instantiate member template classes, since
14448        we don't have any arguments for them.  Note that the standard
14449        is unclear on whether the instantiation of the members are
14450        *explicit* instantiations or not.  However, the most natural
14451        interpretation is that it should be an explicit instantiation.  */
14452
14453     if (! static_p)
14454       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
14455         if (TREE_CODE (tmp) == FUNCTION_DECL
14456             && DECL_TEMPLATE_INSTANTIATION (tmp))
14457           instantiate_class_member (tmp, extern_p);
14458
14459     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
14460       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
14461         instantiate_class_member (tmp, extern_p);
14462
14463     if (CLASSTYPE_NESTED_UTDS (t))
14464       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
14465                              bt_instantiate_type_proc, &storage);
14466   }
14467 }
14468
14469 /* Given a function DECL, which is a specialization of TMPL, modify
14470    DECL to be a re-instantiation of TMPL with the same template
14471    arguments.  TMPL should be the template into which tsubst'ing
14472    should occur for DECL, not the most general template.
14473
14474    One reason for doing this is a scenario like this:
14475
14476      template <class T>
14477      void f(const T&, int i);
14478
14479      void g() { f(3, 7); }
14480
14481      template <class T>
14482      void f(const T& t, const int i) { }
14483
14484    Note that when the template is first instantiated, with
14485    instantiate_template, the resulting DECL will have no name for the
14486    first parameter, and the wrong type for the second.  So, when we go
14487    to instantiate the DECL, we regenerate it.  */
14488
14489 static void
14490 regenerate_decl_from_template (tree decl, tree tmpl)
14491 {
14492   /* The arguments used to instantiate DECL, from the most general
14493      template.  */
14494   tree args;
14495   tree code_pattern;
14496
14497   args = DECL_TI_ARGS (decl);
14498   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
14499
14500   /* Make sure that we can see identifiers, and compute access
14501      correctly.  */
14502   push_access_scope (decl);
14503
14504   if (TREE_CODE (decl) == FUNCTION_DECL)
14505     {
14506       tree decl_parm;
14507       tree pattern_parm;
14508       tree specs;
14509       int args_depth;
14510       int parms_depth;
14511
14512       args_depth = TMPL_ARGS_DEPTH (args);
14513       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
14514       if (args_depth > parms_depth)
14515         args = get_innermost_template_args (args, parms_depth);
14516
14517       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
14518                                               args, tf_error, NULL_TREE);
14519       if (specs)
14520         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
14521                                                     specs);
14522
14523       /* Merge parameter declarations.  */
14524       decl_parm = skip_artificial_parms_for (decl,
14525                                              DECL_ARGUMENTS (decl));
14526       pattern_parm
14527         = skip_artificial_parms_for (code_pattern,
14528                                      DECL_ARGUMENTS (code_pattern));
14529       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
14530         {
14531           tree parm_type;
14532           tree attributes;
14533           
14534           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
14535             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
14536           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
14537                               NULL_TREE);
14538           parm_type = type_decays_to (parm_type);
14539           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
14540             TREE_TYPE (decl_parm) = parm_type;
14541           attributes = DECL_ATTRIBUTES (pattern_parm);
14542           if (DECL_ATTRIBUTES (decl_parm) != attributes)
14543             {
14544               DECL_ATTRIBUTES (decl_parm) = attributes;
14545               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
14546             }
14547           decl_parm = TREE_CHAIN (decl_parm);
14548           pattern_parm = TREE_CHAIN (pattern_parm);
14549         }
14550       /* Merge any parameters that match with the function parameter
14551          pack.  */
14552       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
14553         {
14554           int i, len;
14555           tree expanded_types;
14556           /* Expand the TYPE_PACK_EXPANSION that provides the types for
14557              the parameters in this function parameter pack.  */
14558           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
14559                                                  args, tf_error, NULL_TREE);
14560           len = TREE_VEC_LENGTH (expanded_types);
14561           for (i = 0; i < len; i++)
14562             {
14563               tree parm_type;
14564               tree attributes;
14565           
14566               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
14567                 /* Rename the parameter to include the index.  */
14568                 DECL_NAME (decl_parm) = 
14569                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
14570               parm_type = TREE_VEC_ELT (expanded_types, i);
14571               parm_type = type_decays_to (parm_type);
14572               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
14573                 TREE_TYPE (decl_parm) = parm_type;
14574               attributes = DECL_ATTRIBUTES (pattern_parm);
14575               if (DECL_ATTRIBUTES (decl_parm) != attributes)
14576                 {
14577                   DECL_ATTRIBUTES (decl_parm) = attributes;
14578                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
14579                 }
14580               decl_parm = TREE_CHAIN (decl_parm);
14581             }
14582         }
14583       /* Merge additional specifiers from the CODE_PATTERN.  */
14584       if (DECL_DECLARED_INLINE_P (code_pattern)
14585           && !DECL_DECLARED_INLINE_P (decl))
14586         DECL_DECLARED_INLINE_P (decl) = 1;
14587       if (DECL_INLINE (code_pattern) && !DECL_INLINE (decl))
14588         DECL_INLINE (decl) = 1;
14589     }
14590   else if (TREE_CODE (decl) == VAR_DECL)
14591     DECL_INITIAL (decl) =
14592       tsubst_expr (DECL_INITIAL (code_pattern), args,
14593                    tf_error, DECL_TI_TEMPLATE (decl),
14594                    /*integral_constant_expression_p=*/false);
14595   else
14596     gcc_unreachable ();
14597
14598   pop_access_scope (decl);
14599 }
14600
14601 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
14602    substituted to get DECL.  */
14603
14604 tree
14605 template_for_substitution (tree decl)
14606 {
14607   tree tmpl = DECL_TI_TEMPLATE (decl);
14608
14609   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
14610      for the instantiation.  This is not always the most general
14611      template.  Consider, for example:
14612
14613         template <class T>
14614         struct S { template <class U> void f();
14615                    template <> void f<int>(); };
14616
14617      and an instantiation of S<double>::f<int>.  We want TD to be the
14618      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
14619   while (/* An instantiation cannot have a definition, so we need a
14620             more general template.  */
14621          DECL_TEMPLATE_INSTANTIATION (tmpl)
14622            /* We must also deal with friend templates.  Given:
14623
14624                 template <class T> struct S {
14625                   template <class U> friend void f() {};
14626                 };
14627
14628               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
14629               so far as the language is concerned, but that's still
14630               where we get the pattern for the instantiation from.  On
14631               other hand, if the definition comes outside the class, say:
14632
14633                 template <class T> struct S {
14634                   template <class U> friend void f();
14635                 };
14636                 template <class U> friend void f() {}
14637
14638               we don't need to look any further.  That's what the check for
14639               DECL_INITIAL is for.  */
14640           || (TREE_CODE (decl) == FUNCTION_DECL
14641               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
14642               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
14643     {
14644       /* The present template, TD, should not be a definition.  If it
14645          were a definition, we should be using it!  Note that we
14646          cannot restructure the loop to just keep going until we find
14647          a template with a definition, since that might go too far if
14648          a specialization was declared, but not defined.  */
14649       gcc_assert (TREE_CODE (decl) != VAR_DECL
14650                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
14651
14652       /* Fetch the more general template.  */
14653       tmpl = DECL_TI_TEMPLATE (tmpl);
14654     }
14655
14656   return tmpl;
14657 }
14658
14659 /* Produce the definition of D, a _DECL generated from a template.  If
14660    DEFER_OK is nonzero, then we don't have to actually do the
14661    instantiation now; we just have to do it sometime.  Normally it is
14662    an error if this is an explicit instantiation but D is undefined.
14663    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
14664    explicitly instantiated class template.  */
14665
14666 tree
14667 instantiate_decl (tree d, int defer_ok,
14668                   bool expl_inst_class_mem_p)
14669 {
14670   tree tmpl = DECL_TI_TEMPLATE (d);
14671   tree gen_args;
14672   tree args;
14673   tree td;
14674   tree code_pattern;
14675   tree spec;
14676   tree gen_tmpl;
14677   bool pattern_defined;
14678   int need_push;
14679   location_t saved_loc = input_location;
14680   int saved_in_system_header = in_system_header;
14681   bool external_p;
14682
14683   /* This function should only be used to instantiate templates for
14684      functions and static member variables.  */
14685   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
14686               || TREE_CODE (d) == VAR_DECL);
14687
14688   /* Variables are never deferred; if instantiation is required, they
14689      are instantiated right away.  That allows for better code in the
14690      case that an expression refers to the value of the variable --
14691      if the variable has a constant value the referring expression can
14692      take advantage of that fact.  */
14693   if (TREE_CODE (d) == VAR_DECL)
14694     defer_ok = 0;
14695
14696   /* Don't instantiate cloned functions.  Instead, instantiate the
14697      functions they cloned.  */
14698   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
14699     d = DECL_CLONED_FUNCTION (d);
14700
14701   if (DECL_TEMPLATE_INSTANTIATED (d))
14702     /* D has already been instantiated.  It might seem reasonable to
14703        check whether or not D is an explicit instantiation, and, if so,
14704        stop here.  But when an explicit instantiation is deferred
14705        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
14706        is set, even though we still need to do the instantiation.  */
14707     return d;
14708
14709   /* If we already have a specialization of this declaration, then
14710      there's no reason to instantiate it.  Note that
14711      retrieve_specialization gives us both instantiations and
14712      specializations, so we must explicitly check
14713      DECL_TEMPLATE_SPECIALIZATION.  */
14714   gen_tmpl = most_general_template (tmpl);
14715   gen_args = DECL_TI_ARGS (d);
14716   spec = retrieve_specialization (gen_tmpl, gen_args,
14717                                   /*class_specializations_p=*/false);
14718   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
14719     return spec;
14720
14721   /* This needs to happen before any tsubsting.  */
14722   if (! push_tinst_level (d))
14723     return d;
14724
14725   timevar_push (TV_PARSE);
14726
14727   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
14728      for the instantiation.  */
14729   td = template_for_substitution (d);
14730   code_pattern = DECL_TEMPLATE_RESULT (td);
14731
14732   /* We should never be trying to instantiate a member of a class
14733      template or partial specialization.  */
14734   gcc_assert (d != code_pattern);
14735
14736   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
14737       || DECL_TEMPLATE_SPECIALIZATION (td))
14738     /* In the case of a friend template whose definition is provided
14739        outside the class, we may have too many arguments.  Drop the
14740        ones we don't need.  The same is true for specializations.  */
14741     args = get_innermost_template_args
14742       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
14743   else
14744     args = gen_args;
14745
14746   if (TREE_CODE (d) == FUNCTION_DECL)
14747     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
14748   else
14749     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
14750
14751   /* We may be in the middle of deferred access check.  Disable it now.  */
14752   push_deferring_access_checks (dk_no_deferred);
14753
14754   /* Unless an explicit instantiation directive has already determined
14755      the linkage of D, remember that a definition is available for
14756      this entity.  */
14757   if (pattern_defined
14758       && !DECL_INTERFACE_KNOWN (d)
14759       && !DECL_NOT_REALLY_EXTERN (d))
14760     mark_definable (d);
14761
14762   input_location = DECL_SOURCE_LOCATION (d);
14763   in_system_header = DECL_IN_SYSTEM_HEADER (d);
14764
14765   /* If D is a member of an explicitly instantiated class template,
14766      and no definition is available, treat it like an implicit
14767      instantiation.  */
14768   if (!pattern_defined && expl_inst_class_mem_p
14769       && DECL_EXPLICIT_INSTANTIATION (d))
14770     {
14771       DECL_NOT_REALLY_EXTERN (d) = 0;
14772       DECL_INTERFACE_KNOWN (d) = 0;
14773       SET_DECL_IMPLICIT_INSTANTIATION (d);
14774     }
14775
14776   if (!defer_ok)
14777     {
14778       /* Recheck the substitutions to obtain any warning messages
14779          about ignoring cv qualifiers.  */
14780       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
14781       tree type = TREE_TYPE (gen);
14782
14783       /* Make sure that we can see identifiers, and compute access
14784          correctly.  D is already the target FUNCTION_DECL with the
14785          right context.  */
14786       push_access_scope (d);
14787
14788       if (TREE_CODE (gen) == FUNCTION_DECL)
14789         {
14790           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
14791           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
14792                                           d);
14793           /* Don't simply tsubst the function type, as that will give
14794              duplicate warnings about poor parameter qualifications.
14795              The function arguments are the same as the decl_arguments
14796              without the top level cv qualifiers.  */
14797           type = TREE_TYPE (type);
14798         }
14799       tsubst (type, gen_args, tf_warning_or_error, d);
14800
14801       pop_access_scope (d);
14802     }
14803
14804   /* Check to see whether we know that this template will be
14805      instantiated in some other file, as with "extern template"
14806      extension.  */
14807   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
14808   /* In general, we do not instantiate such templates...  */
14809   if (external_p
14810       /* ... but we instantiate inline functions so that we can inline
14811          them and ... */
14812       && ! (TREE_CODE (d) == FUNCTION_DECL && DECL_INLINE (d))
14813       /* ... we instantiate static data members whose values are
14814          needed in integral constant expressions.  */
14815       && ! (TREE_CODE (d) == VAR_DECL
14816             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
14817     goto out;
14818   /* Defer all other templates, unless we have been explicitly
14819      forbidden from doing so.  */
14820   if (/* If there is no definition, we cannot instantiate the
14821          template.  */
14822       ! pattern_defined
14823       /* If it's OK to postpone instantiation, do so.  */
14824       || defer_ok
14825       /* If this is a static data member that will be defined
14826          elsewhere, we don't want to instantiate the entire data
14827          member, but we do want to instantiate the initializer so that
14828          we can substitute that elsewhere.  */
14829       || (external_p && TREE_CODE (d) == VAR_DECL))
14830     {
14831       /* The definition of the static data member is now required so
14832          we must substitute the initializer.  */
14833       if (TREE_CODE (d) == VAR_DECL
14834           && !DECL_INITIAL (d)
14835           && DECL_INITIAL (code_pattern))
14836         {
14837           tree ns;
14838           tree init;
14839
14840           ns = decl_namespace_context (d);
14841           push_nested_namespace (ns);
14842           push_nested_class (DECL_CONTEXT (d));
14843           init = tsubst_expr (DECL_INITIAL (code_pattern),
14844                               args,
14845                               tf_warning_or_error, NULL_TREE,
14846                               /*integral_constant_expression_p=*/false);
14847           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
14848                           /*asmspec_tree=*/NULL_TREE,
14849                           LOOKUP_ONLYCONVERTING);
14850           pop_nested_class ();
14851           pop_nested_namespace (ns);
14852         }
14853
14854       /* We restore the source position here because it's used by
14855          add_pending_template.  */
14856       input_location = saved_loc;
14857
14858       if (at_eof && !pattern_defined
14859           && DECL_EXPLICIT_INSTANTIATION (d))
14860         /* [temp.explicit]
14861
14862            The definition of a non-exported function template, a
14863            non-exported member function template, or a non-exported
14864            member function or static data member of a class template
14865            shall be present in every translation unit in which it is
14866            explicitly instantiated.  */
14867         pedwarn
14868           ("explicit instantiation of %qD but no definition available", d);
14869
14870       /* ??? Historically, we have instantiated inline functions, even
14871          when marked as "extern template".  */
14872       if (!(external_p && TREE_CODE (d) == VAR_DECL))
14873         add_pending_template (d);
14874       goto out;
14875     }
14876   /* Tell the repository that D is available in this translation unit
14877      -- and see if it is supposed to be instantiated here.  */
14878   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
14879     {
14880       /* In a PCH file, despite the fact that the repository hasn't
14881          requested instantiation in the PCH it is still possible that
14882          an instantiation will be required in a file that includes the
14883          PCH.  */
14884       if (pch_file)
14885         add_pending_template (d);
14886       /* Instantiate inline functions so that the inliner can do its
14887          job, even though we'll not be emitting a copy of this
14888          function.  */
14889       if (!(TREE_CODE (d) == FUNCTION_DECL
14890             && flag_inline_trees
14891             && DECL_DECLARED_INLINE_P (d)))
14892         goto out;
14893     }
14894
14895   need_push = !cfun || !global_bindings_p ();
14896   if (need_push)
14897     push_to_top_level ();
14898
14899   /* Mark D as instantiated so that recursive calls to
14900      instantiate_decl do not try to instantiate it again.  */
14901   DECL_TEMPLATE_INSTANTIATED (d) = 1;
14902
14903   /* Regenerate the declaration in case the template has been modified
14904      by a subsequent redeclaration.  */
14905   regenerate_decl_from_template (d, td);
14906
14907   /* We already set the file and line above.  Reset them now in case
14908      they changed as a result of calling regenerate_decl_from_template.  */
14909   input_location = DECL_SOURCE_LOCATION (d);
14910
14911   if (TREE_CODE (d) == VAR_DECL)
14912     {
14913       tree init;
14914
14915       /* Clear out DECL_RTL; whatever was there before may not be right
14916          since we've reset the type of the declaration.  */
14917       SET_DECL_RTL (d, NULL_RTX);
14918       DECL_IN_AGGR_P (d) = 0;
14919
14920       /* The initializer is placed in DECL_INITIAL by
14921          regenerate_decl_from_template.  Pull it out so that
14922          finish_decl can process it.  */
14923       init = DECL_INITIAL (d);
14924       DECL_INITIAL (d) = NULL_TREE;
14925       DECL_INITIALIZED_P (d) = 0;
14926
14927       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
14928          initializer.  That function will defer actual emission until
14929          we have a chance to determine linkage.  */
14930       DECL_EXTERNAL (d) = 0;
14931
14932       /* Enter the scope of D so that access-checking works correctly.  */
14933       push_nested_class (DECL_CONTEXT (d));
14934       finish_decl (d, init, NULL_TREE);
14935       pop_nested_class ();
14936     }
14937   else if (TREE_CODE (d) == FUNCTION_DECL)
14938     {
14939       htab_t saved_local_specializations;
14940       tree subst_decl;
14941       tree tmpl_parm;
14942       tree spec_parm;
14943
14944       /* Save away the current list, in case we are instantiating one
14945          template from within the body of another.  */
14946       saved_local_specializations = local_specializations;
14947
14948       /* Set up the list of local specializations.  */
14949       local_specializations = htab_create (37,
14950                                            hash_local_specialization,
14951                                            eq_local_specializations,
14952                                            NULL);
14953
14954       /* Set up context.  */
14955       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
14956
14957       /* Create substitution entries for the parameters.  */
14958       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
14959       tmpl_parm = DECL_ARGUMENTS (subst_decl);
14960       spec_parm = DECL_ARGUMENTS (d);
14961       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
14962         {
14963           register_local_specialization (spec_parm, tmpl_parm);
14964           spec_parm = skip_artificial_parms_for (d, spec_parm);
14965           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
14966         }
14967       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
14968         {
14969           register_local_specialization (spec_parm, tmpl_parm);
14970           tmpl_parm = TREE_CHAIN (tmpl_parm);
14971           spec_parm = TREE_CHAIN (spec_parm);
14972         }
14973       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
14974         {
14975           /* Collect all of the extra "packed" parameters into an
14976              argument pack.  */
14977           tree parmvec;
14978           tree parmtypevec;
14979           tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
14980           tree argtypepack = make_node (TYPE_ARGUMENT_PACK);
14981           int i, len = 0;
14982           tree t;
14983           
14984           /* Count how many parameters remain.  */
14985           for (t = spec_parm; t; t = TREE_CHAIN (t))
14986             len++;
14987
14988           /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
14989           parmvec = make_tree_vec (len);
14990           parmtypevec = make_tree_vec (len);
14991           for(i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
14992             {
14993               TREE_VEC_ELT (parmvec, i) = spec_parm;
14994               TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
14995             }
14996
14997           /* Build the argument packs.  */
14998           SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
14999           SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
15000           TREE_TYPE (argpack) = argtypepack;
15001           
15002           /* Register the (value) argument pack as a specialization of
15003              TMPL_PARM, then move on.  */
15004           register_local_specialization (argpack, tmpl_parm);
15005           tmpl_parm = TREE_CHAIN (tmpl_parm);
15006         }
15007       gcc_assert (!spec_parm);
15008
15009       /* Substitute into the body of the function.  */
15010       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
15011                    tf_warning_or_error, tmpl,
15012                    /*integral_constant_expression_p=*/false);
15013
15014       /* Set the current input_location to the end of the function
15015          so that finish_function knows where we are.  */
15016       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
15017
15018       /* We don't need the local specializations any more.  */
15019       htab_delete (local_specializations);
15020       local_specializations = saved_local_specializations;
15021
15022       /* Finish the function.  */
15023       d = finish_function (0);
15024       expand_or_defer_fn (d);
15025     }
15026
15027   /* We're not deferring instantiation any more.  */
15028   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
15029
15030   if (need_push)
15031     pop_from_top_level ();
15032
15033 out:
15034   input_location = saved_loc;
15035   in_system_header = saved_in_system_header;
15036   pop_deferring_access_checks ();
15037   pop_tinst_level ();
15038
15039   timevar_pop (TV_PARSE);
15040
15041   return d;
15042 }
15043
15044 /* Run through the list of templates that we wish we could
15045    instantiate, and instantiate any we can.  RETRIES is the
15046    number of times we retry pending template instantiation.  */
15047
15048 void
15049 instantiate_pending_templates (int retries)
15050 {
15051   int reconsider;
15052   location_t saved_loc = input_location;
15053   int saved_in_system_header = in_system_header;
15054
15055   /* Instantiating templates may trigger vtable generation.  This in turn
15056      may require further template instantiations.  We place a limit here
15057      to avoid infinite loop.  */
15058   if (pending_templates && retries >= max_tinst_depth)
15059     {
15060       tree decl = pending_templates->tinst->decl;
15061
15062       error ("template instantiation depth exceeds maximum of %d"
15063              " instantiating %q+D, possibly from virtual table generation"
15064              " (use -ftemplate-depth-NN to increase the maximum)",
15065              max_tinst_depth, decl);
15066       if (TREE_CODE (decl) == FUNCTION_DECL)
15067         /* Pretend that we defined it.  */
15068         DECL_INITIAL (decl) = error_mark_node;
15069       return;
15070     }
15071
15072   do
15073     {
15074       struct pending_template **t = &pending_templates;
15075       struct pending_template *last = NULL;
15076       reconsider = 0;
15077       while (*t)
15078         {
15079           tree instantiation = reopen_tinst_level ((*t)->tinst);
15080           bool complete = false;
15081
15082           if (TYPE_P (instantiation))
15083             {
15084               tree fn;
15085
15086               if (!COMPLETE_TYPE_P (instantiation))
15087                 {
15088                   instantiate_class_template (instantiation);
15089                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
15090                     for (fn = TYPE_METHODS (instantiation);
15091                          fn;
15092                          fn = TREE_CHAIN (fn))
15093                       if (! DECL_ARTIFICIAL (fn))
15094                         instantiate_decl (fn,
15095                                           /*defer_ok=*/0,
15096                                           /*expl_inst_class_mem_p=*/false);
15097                   if (COMPLETE_TYPE_P (instantiation))
15098                     reconsider = 1;
15099                 }
15100
15101               complete = COMPLETE_TYPE_P (instantiation);
15102             }
15103           else
15104             {
15105               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
15106                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
15107                 {
15108                   instantiation
15109                     = instantiate_decl (instantiation,
15110                                         /*defer_ok=*/0,
15111                                         /*expl_inst_class_mem_p=*/false);
15112                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
15113                     reconsider = 1;
15114                 }
15115
15116               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
15117                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
15118             }
15119
15120           if (complete)
15121             /* If INSTANTIATION has been instantiated, then we don't
15122                need to consider it again in the future.  */
15123             *t = (*t)->next;
15124           else
15125             {
15126               last = *t;
15127               t = &(*t)->next;
15128             }
15129           tinst_depth = 0;
15130           current_tinst_level = NULL;
15131         }
15132       last_pending_template = last;
15133     }
15134   while (reconsider);
15135
15136   input_location = saved_loc;
15137   in_system_header = saved_in_system_header;
15138 }
15139
15140 /* Substitute ARGVEC into T, which is a list of initializers for
15141    either base class or a non-static data member.  The TREE_PURPOSEs
15142    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
15143    instantiate_decl.  */
15144
15145 static tree
15146 tsubst_initializer_list (tree t, tree argvec)
15147 {
15148   tree inits = NULL_TREE;
15149
15150   for (; t; t = TREE_CHAIN (t))
15151     {
15152       tree decl;
15153       tree init;
15154       tree expanded_bases = NULL_TREE;
15155       tree expanded_arguments = NULL_TREE;
15156       int i, len = 1;
15157
15158       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
15159         {
15160           tree expr;
15161           tree arg;
15162
15163           /* Expand the base class expansion type into separate base
15164              classes.  */
15165           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
15166                                                  tf_warning_or_error,
15167                                                  NULL_TREE);
15168           if (expanded_bases == error_mark_node)
15169             continue;
15170           
15171           /* We'll be building separate TREE_LISTs of arguments for
15172              each base.  */
15173           len = TREE_VEC_LENGTH (expanded_bases);
15174           expanded_arguments = make_tree_vec (len);
15175           for (i = 0; i < len; i++)
15176             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
15177
15178           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
15179              expand each argument in the TREE_VALUE of t.  */
15180           expr = make_node (EXPR_PACK_EXPANSION);
15181           PACK_EXPANSION_PARAMETER_PACKS (expr) =
15182             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
15183
15184           if (TREE_VALUE (t) == void_type_node)
15185             /* VOID_TYPE_NODE is used to indicate
15186                value-initialization.  */
15187             {
15188               for (i = 0; i < len; i++)
15189                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
15190             }
15191           else
15192             {
15193               /* Substitute parameter packs into each argument in the
15194                  TREE_LIST.  */
15195               in_base_initializer = 1;
15196               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
15197                 {
15198                   tree expanded_exprs;
15199
15200                   /* Expand the argument.  */
15201                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
15202                   expanded_exprs 
15203                     = tsubst_pack_expansion (expr, argvec,
15204                                              tf_warning_or_error,
15205                                              NULL_TREE);
15206
15207                   /* Prepend each of the expanded expressions to the
15208                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
15209                   for (i = 0; i < len; i++)
15210                     {
15211                       TREE_VEC_ELT (expanded_arguments, i) = 
15212                         tree_cons (NULL_TREE, 
15213                                    TREE_VEC_ELT (expanded_exprs, i),
15214                                    TREE_VEC_ELT (expanded_arguments, i));
15215                     }
15216                 }
15217               in_base_initializer = 0;
15218
15219               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
15220                  since we built them backwards.  */
15221               for (i = 0; i < len; i++)
15222                 {
15223                   TREE_VEC_ELT (expanded_arguments, i) = 
15224                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
15225                 }
15226             }
15227         }
15228
15229       for (i = 0; i < len; ++i)
15230         {
15231           if (expanded_bases)
15232             {
15233               decl = TREE_VEC_ELT (expanded_bases, i);
15234               decl = expand_member_init (decl);
15235               init = TREE_VEC_ELT (expanded_arguments, i);
15236             }
15237           else
15238             {
15239               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
15240                                   tf_warning_or_error, NULL_TREE);
15241
15242               decl = expand_member_init (decl);
15243               if (decl && !DECL_P (decl))
15244                 in_base_initializer = 1;
15245
15246               init = tsubst_expr (TREE_VALUE (t), argvec, 
15247                                   tf_warning_or_error, NULL_TREE,
15248                                   /*integral_constant_expression_p=*/false);
15249               in_base_initializer = 0;
15250             }
15251
15252           if (decl)
15253             {
15254               init = build_tree_list (decl, init);
15255               TREE_CHAIN (init) = inits;
15256               inits = init;
15257             }
15258         }
15259     }
15260   return inits;
15261 }
15262
15263 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
15264
15265 static void
15266 set_current_access_from_decl (tree decl)
15267 {
15268   if (TREE_PRIVATE (decl))
15269     current_access_specifier = access_private_node;
15270   else if (TREE_PROTECTED (decl))
15271     current_access_specifier = access_protected_node;
15272   else
15273     current_access_specifier = access_public_node;
15274 }
15275
15276 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
15277    is the instantiation (which should have been created with
15278    start_enum) and ARGS are the template arguments to use.  */
15279
15280 static void
15281 tsubst_enum (tree tag, tree newtag, tree args)
15282 {
15283   tree e;
15284
15285   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
15286     {
15287       tree value;
15288       tree decl;
15289
15290       decl = TREE_VALUE (e);
15291       /* Note that in a template enum, the TREE_VALUE is the
15292          CONST_DECL, not the corresponding INTEGER_CST.  */
15293       value = tsubst_expr (DECL_INITIAL (decl),
15294                            args, tf_warning_or_error, NULL_TREE,
15295                            /*integral_constant_expression_p=*/true);
15296
15297       /* Give this enumeration constant the correct access.  */
15298       set_current_access_from_decl (decl);
15299
15300       /* Actually build the enumerator itself.  */
15301       build_enumerator (DECL_NAME (decl), value, newtag);
15302     }
15303
15304   finish_enum (newtag);
15305   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
15306     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
15307 }
15308
15309 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
15310    its type -- but without substituting the innermost set of template
15311    arguments.  So, innermost set of template parameters will appear in
15312    the type.  */
15313
15314 tree
15315 get_mostly_instantiated_function_type (tree decl)
15316 {
15317   tree fn_type;
15318   tree tmpl;
15319   tree targs;
15320   tree tparms;
15321   int parm_depth;
15322
15323   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15324   targs = DECL_TI_ARGS (decl);
15325   tparms = DECL_TEMPLATE_PARMS (tmpl);
15326   parm_depth = TMPL_PARMS_DEPTH (tparms);
15327
15328   /* There should be as many levels of arguments as there are levels
15329      of parameters.  */
15330   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
15331
15332   fn_type = TREE_TYPE (tmpl);
15333
15334   if (parm_depth == 1)
15335     /* No substitution is necessary.  */
15336     ;
15337   else
15338     {
15339       int i, save_access_control;
15340       tree partial_args;
15341
15342       /* Replace the innermost level of the TARGS with NULL_TREEs to
15343          let tsubst know not to substitute for those parameters.  */
15344       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
15345       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
15346         SET_TMPL_ARGS_LEVEL (partial_args, i,
15347                              TMPL_ARGS_LEVEL (targs, i));
15348       SET_TMPL_ARGS_LEVEL (partial_args,
15349                            TMPL_ARGS_DEPTH (targs),
15350                            make_tree_vec (DECL_NTPARMS (tmpl)));
15351
15352       /* Disable access control as this function is used only during
15353          name-mangling.  */
15354       save_access_control = flag_access_control;
15355       flag_access_control = 0;
15356
15357       ++processing_template_decl;
15358       /* Now, do the (partial) substitution to figure out the
15359          appropriate function type.  */
15360       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
15361       --processing_template_decl;
15362
15363       /* Substitute into the template parameters to obtain the real
15364          innermost set of parameters.  This step is important if the
15365          innermost set of template parameters contains value
15366          parameters whose types depend on outer template parameters.  */
15367       TREE_VEC_LENGTH (partial_args)--;
15368       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
15369
15370       flag_access_control = save_access_control;
15371     }
15372
15373   return fn_type;
15374 }
15375
15376 /* Return truthvalue if we're processing a template different from
15377    the last one involved in diagnostics.  */
15378 int
15379 problematic_instantiation_changed (void)
15380 {
15381   return last_template_error_tick != tinst_level_tick;
15382 }
15383
15384 /* Remember current template involved in diagnostics.  */
15385 void
15386 record_last_problematic_instantiation (void)
15387 {
15388   last_template_error_tick = tinst_level_tick;
15389 }
15390
15391 struct tinst_level *
15392 current_instantiation (void)
15393 {
15394   return current_tinst_level;
15395 }
15396
15397 /* [temp.param] Check that template non-type parm TYPE is of an allowable
15398    type. Return zero for ok, nonzero for disallowed. Issue error and
15399    warning messages under control of COMPLAIN.  */
15400
15401 static int
15402 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
15403 {
15404   if (INTEGRAL_TYPE_P (type))
15405     return 0;
15406   else if (POINTER_TYPE_P (type))
15407     return 0;
15408   else if (TYPE_PTR_TO_MEMBER_P (type))
15409     return 0;
15410   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
15411     return 0;
15412   else if (TREE_CODE (type) == TYPENAME_TYPE)
15413     return 0;
15414
15415   if (complain & tf_error)
15416     error ("%q#T is not a valid type for a template constant parameter", type);
15417   return 1;
15418 }
15419
15420 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
15421    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
15422
15423 static bool
15424 dependent_type_p_r (tree type)
15425 {
15426   tree scope;
15427
15428   /* [temp.dep.type]
15429
15430      A type is dependent if it is:
15431
15432      -- a template parameter. Template template parameters are types
15433         for us (since TYPE_P holds true for them) so we handle
15434         them here.  */
15435   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
15436       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
15437     return true;
15438   /* -- a qualified-id with a nested-name-specifier which contains a
15439         class-name that names a dependent type or whose unqualified-id
15440         names a dependent type.  */
15441   if (TREE_CODE (type) == TYPENAME_TYPE)
15442     return true;
15443   /* -- a cv-qualified type where the cv-unqualified type is
15444         dependent.  */
15445   type = TYPE_MAIN_VARIANT (type);
15446   /* -- a compound type constructed from any dependent type.  */
15447   if (TYPE_PTR_TO_MEMBER_P (type))
15448     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
15449             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
15450                                            (type)));
15451   else if (TREE_CODE (type) == POINTER_TYPE
15452            || TREE_CODE (type) == REFERENCE_TYPE)
15453     return dependent_type_p (TREE_TYPE (type));
15454   else if (TREE_CODE (type) == FUNCTION_TYPE
15455            || TREE_CODE (type) == METHOD_TYPE)
15456     {
15457       tree arg_type;
15458
15459       if (dependent_type_p (TREE_TYPE (type)))
15460         return true;
15461       for (arg_type = TYPE_ARG_TYPES (type);
15462            arg_type;
15463            arg_type = TREE_CHAIN (arg_type))
15464         if (dependent_type_p (TREE_VALUE (arg_type)))
15465           return true;
15466       return false;
15467     }
15468   /* -- an array type constructed from any dependent type or whose
15469         size is specified by a constant expression that is
15470         value-dependent.  */
15471   if (TREE_CODE (type) == ARRAY_TYPE)
15472     {
15473       if (TYPE_DOMAIN (type)
15474           && dependent_type_p (TYPE_DOMAIN (type)))
15475         return true;
15476       return dependent_type_p (TREE_TYPE (type));
15477     }
15478   else if (TREE_CODE (type) == INTEGER_TYPE
15479            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
15480     {
15481       /* If this is the TYPE_DOMAIN of an array type, consider it
15482          dependent.  */
15483       return (value_dependent_expression_p (TYPE_MAX_VALUE (type))
15484               || type_dependent_expression_p (TYPE_MAX_VALUE (type)));
15485     }
15486
15487   /* -- a template-id in which either the template name is a template
15488      parameter ...  */
15489   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
15490     return true;
15491   /* ... or any of the template arguments is a dependent type or
15492         an expression that is type-dependent or value-dependent.  */
15493   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
15494            && (any_dependent_template_arguments_p
15495                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
15496     return true;
15497
15498   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
15499      argument of the `typeof' expression is not type-dependent, then
15500      it should already been have resolved.  */
15501   if (TREE_CODE (type) == TYPEOF_TYPE
15502       || TREE_CODE (type) == DECLTYPE_TYPE)
15503     return true;
15504
15505   /* A template argument pack is dependent if any of its packed
15506      arguments are.  */
15507   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
15508     {
15509       tree args = ARGUMENT_PACK_ARGS (type);
15510       int i, len = TREE_VEC_LENGTH (args);
15511       for (i = 0; i < len; ++i)
15512         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
15513           return true;
15514     }
15515
15516   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
15517      be template parameters.  */
15518   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
15519     return true;
15520
15521   /* The standard does not specifically mention types that are local
15522      to template functions or local classes, but they should be
15523      considered dependent too.  For example:
15524
15525        template <int I> void f() {
15526          enum E { a = I };
15527          S<sizeof (E)> s;
15528        }
15529
15530      The size of `E' cannot be known until the value of `I' has been
15531      determined.  Therefore, `E' must be considered dependent.  */
15532   scope = TYPE_CONTEXT (type);
15533   if (scope && TYPE_P (scope))
15534     return dependent_type_p (scope);
15535   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
15536     return type_dependent_expression_p (scope);
15537
15538   /* Other types are non-dependent.  */
15539   return false;
15540 }
15541
15542 /* Returns TRUE if TYPE is dependent, in the sense of
15543    [temp.dep.type].  */
15544
15545 bool
15546 dependent_type_p (tree type)
15547 {
15548   /* If there are no template parameters in scope, then there can't be
15549      any dependent types.  */
15550   if (!processing_template_decl)
15551     {
15552       /* If we are not processing a template, then nobody should be
15553          providing us with a dependent type.  */
15554       gcc_assert (type);
15555       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM);
15556       return false;
15557     }
15558
15559   /* If the type is NULL, we have not computed a type for the entity
15560      in question; in that case, the type is dependent.  */
15561   if (!type)
15562     return true;
15563
15564   /* Erroneous types can be considered non-dependent.  */
15565   if (type == error_mark_node)
15566     return false;
15567
15568   /* If we have not already computed the appropriate value for TYPE,
15569      do so now.  */
15570   if (!TYPE_DEPENDENT_P_VALID (type))
15571     {
15572       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
15573       TYPE_DEPENDENT_P_VALID (type) = 1;
15574     }
15575
15576   return TYPE_DEPENDENT_P (type);
15577 }
15578
15579 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
15580
15581 static bool
15582 dependent_scope_ref_p (tree expression, bool criterion (tree))
15583 {
15584   tree scope;
15585   tree name;
15586
15587   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
15588
15589   if (!TYPE_P (TREE_OPERAND (expression, 0)))
15590     return true;
15591
15592   scope = TREE_OPERAND (expression, 0);
15593   name = TREE_OPERAND (expression, 1);
15594
15595   /* [temp.dep.expr]
15596
15597      An id-expression is type-dependent if it contains a
15598      nested-name-specifier that contains a class-name that names a
15599      dependent type.  */
15600   /* The suggested resolution to Core Issue 2 implies that if the
15601      qualifying type is the current class, then we must peek
15602      inside it.  */
15603   if (DECL_P (name)
15604       && currently_open_class (scope)
15605       && !criterion (name))
15606     return false;
15607   if (dependent_type_p (scope))
15608     return true;
15609
15610   return false;
15611 }
15612
15613 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
15614    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
15615    expression.  */
15616
15617 bool
15618 value_dependent_expression_p (tree expression)
15619 {
15620   if (!processing_template_decl)
15621     return false;
15622
15623   /* A name declared with a dependent type.  */
15624   if (DECL_P (expression) && type_dependent_expression_p (expression))
15625     return true;
15626
15627   switch (TREE_CODE (expression))
15628     {
15629     case IDENTIFIER_NODE:
15630       /* A name that has not been looked up -- must be dependent.  */
15631       return true;
15632
15633     case TEMPLATE_PARM_INDEX:
15634       /* A non-type template parm.  */
15635       return true;
15636
15637     case CONST_DECL:
15638       /* A non-type template parm.  */
15639       if (DECL_TEMPLATE_PARM_P (expression))
15640         return true;
15641       return value_dependent_expression_p (DECL_INITIAL (expression));
15642
15643     case VAR_DECL:
15644        /* A constant with integral or enumeration type and is initialized
15645           with an expression that is value-dependent.  */
15646       if (DECL_INITIAL (expression)
15647           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
15648           && value_dependent_expression_p (DECL_INITIAL (expression)))
15649         return true;
15650       return false;
15651
15652     case DYNAMIC_CAST_EXPR:
15653     case STATIC_CAST_EXPR:
15654     case CONST_CAST_EXPR:
15655     case REINTERPRET_CAST_EXPR:
15656     case CAST_EXPR:
15657       /* These expressions are value-dependent if the type to which
15658          the cast occurs is dependent or the expression being casted
15659          is value-dependent.  */
15660       {
15661         tree type = TREE_TYPE (expression);
15662
15663         if (dependent_type_p (type))
15664           return true;
15665
15666         /* A functional cast has a list of operands.  */
15667         expression = TREE_OPERAND (expression, 0);
15668         if (!expression)
15669           {
15670             /* If there are no operands, it must be an expression such
15671                as "int()". This should not happen for aggregate types
15672                because it would form non-constant expressions.  */
15673             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
15674
15675             return false;
15676           }
15677
15678         if (TREE_CODE (expression) == TREE_LIST)
15679           return any_value_dependent_elements_p (expression);
15680
15681         return value_dependent_expression_p (expression);
15682       }
15683
15684     case SIZEOF_EXPR:
15685     case ALIGNOF_EXPR:
15686       /* A `sizeof' expression is value-dependent if the operand is
15687          type-dependent or is a pack expansion.  */
15688       expression = TREE_OPERAND (expression, 0);
15689       if (PACK_EXPANSION_P (expression))
15690         return true;
15691       else if (TYPE_P (expression))
15692         return dependent_type_p (expression);
15693       return type_dependent_expression_p (expression);
15694
15695     case SCOPE_REF:
15696       return dependent_scope_ref_p (expression, value_dependent_expression_p);
15697
15698     case COMPONENT_REF:
15699       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
15700               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
15701
15702     case CALL_EXPR:
15703       /* A CALL_EXPR may appear in a constant expression if it is a
15704          call to a builtin function, e.g., __builtin_constant_p.  All
15705          such calls are value-dependent.  */
15706       return true;
15707
15708     case NONTYPE_ARGUMENT_PACK:
15709       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
15710          is value-dependent.  */
15711       {
15712         tree values = ARGUMENT_PACK_ARGS (expression);
15713         int i, len = TREE_VEC_LENGTH (values);
15714         
15715         for (i = 0; i < len; ++i)
15716           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
15717             return true;
15718         
15719         return false;
15720       }
15721
15722     case TRAIT_EXPR:
15723       {
15724         tree type2 = TRAIT_EXPR_TYPE2 (expression);
15725         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
15726                 || (type2 ? dependent_type_p (type2) : false));
15727       }
15728
15729     case MODOP_EXPR:
15730       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
15731               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
15732
15733     default:
15734       /* A constant expression is value-dependent if any subexpression is
15735          value-dependent.  */
15736       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
15737         {
15738         case tcc_reference:
15739         case tcc_unary:
15740           return (value_dependent_expression_p
15741                   (TREE_OPERAND (expression, 0)));
15742
15743         case tcc_comparison:
15744         case tcc_binary:
15745           return ((value_dependent_expression_p
15746                    (TREE_OPERAND (expression, 0)))
15747                   || (value_dependent_expression_p
15748                       (TREE_OPERAND (expression, 1))));
15749
15750         case tcc_expression:
15751         case tcc_vl_exp:
15752           {
15753             int i;
15754             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
15755               /* In some cases, some of the operands may be missing.
15756                  (For example, in the case of PREDECREMENT_EXPR, the
15757                  amount to increment by may be missing.)  That doesn't
15758                  make the expression dependent.  */
15759               if (TREE_OPERAND (expression, i)
15760                   && (value_dependent_expression_p
15761                       (TREE_OPERAND (expression, i))))
15762                 return true;
15763             return false;
15764           }
15765
15766         default:
15767           break;
15768         }
15769     }
15770
15771   /* The expression is not value-dependent.  */
15772   return false;
15773 }
15774
15775 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
15776    [temp.dep.expr].  */
15777
15778 bool
15779 type_dependent_expression_p (tree expression)
15780 {
15781   if (!processing_template_decl)
15782     return false;
15783
15784   if (expression == error_mark_node)
15785     return false;
15786
15787   /* An unresolved name is always dependent.  */
15788   if (TREE_CODE (expression) == IDENTIFIER_NODE
15789       || TREE_CODE (expression) == USING_DECL)
15790     return true;
15791
15792   /* Some expression forms are never type-dependent.  */
15793   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
15794       || TREE_CODE (expression) == SIZEOF_EXPR
15795       || TREE_CODE (expression) == ALIGNOF_EXPR
15796       || TREE_CODE (expression) == TRAIT_EXPR
15797       || TREE_CODE (expression) == TYPEID_EXPR
15798       || TREE_CODE (expression) == DELETE_EXPR
15799       || TREE_CODE (expression) == VEC_DELETE_EXPR
15800       || TREE_CODE (expression) == THROW_EXPR)
15801     return false;
15802
15803   /* The types of these expressions depends only on the type to which
15804      the cast occurs.  */
15805   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
15806       || TREE_CODE (expression) == STATIC_CAST_EXPR
15807       || TREE_CODE (expression) == CONST_CAST_EXPR
15808       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
15809       || TREE_CODE (expression) == CAST_EXPR)
15810     return dependent_type_p (TREE_TYPE (expression));
15811
15812   /* The types of these expressions depends only on the type created
15813      by the expression.  */
15814   if (TREE_CODE (expression) == NEW_EXPR
15815       || TREE_CODE (expression) == VEC_NEW_EXPR)
15816     {
15817       /* For NEW_EXPR tree nodes created inside a template, either
15818          the object type itself or a TREE_LIST may appear as the
15819          operand 1.  */
15820       tree type = TREE_OPERAND (expression, 1);
15821       if (TREE_CODE (type) == TREE_LIST)
15822         /* This is an array type.  We need to check array dimensions
15823            as well.  */
15824         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
15825                || value_dependent_expression_p
15826                     (TREE_OPERAND (TREE_VALUE (type), 1));
15827       else
15828         return dependent_type_p (type);
15829     }
15830
15831   if (TREE_CODE (expression) == SCOPE_REF
15832       && dependent_scope_ref_p (expression,
15833                                 type_dependent_expression_p))
15834     return true;
15835
15836   if (TREE_CODE (expression) == FUNCTION_DECL
15837       && DECL_LANG_SPECIFIC (expression)
15838       && DECL_TEMPLATE_INFO (expression)
15839       && (any_dependent_template_arguments_p
15840           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
15841     return true;
15842
15843   if (TREE_CODE (expression) == TEMPLATE_DECL
15844       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
15845     return false;
15846
15847   if (TREE_CODE (expression) == STMT_EXPR)
15848     expression = stmt_expr_value_expr (expression);
15849
15850   if (TREE_TYPE (expression) == unknown_type_node)
15851     {
15852       if (TREE_CODE (expression) == ADDR_EXPR)
15853         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
15854       if (TREE_CODE (expression) == COMPONENT_REF
15855           || TREE_CODE (expression) == OFFSET_REF)
15856         {
15857           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
15858             return true;
15859           expression = TREE_OPERAND (expression, 1);
15860           if (TREE_CODE (expression) == IDENTIFIER_NODE)
15861             return false;
15862         }
15863       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
15864       if (TREE_CODE (expression) == SCOPE_REF)
15865         return false;
15866
15867       if (TREE_CODE (expression) == BASELINK)
15868         expression = BASELINK_FUNCTIONS (expression);
15869
15870       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
15871         {
15872           if (any_dependent_template_arguments_p
15873               (TREE_OPERAND (expression, 1)))
15874             return true;
15875           expression = TREE_OPERAND (expression, 0);
15876         }
15877       gcc_assert (TREE_CODE (expression) == OVERLOAD
15878                   || TREE_CODE (expression) == FUNCTION_DECL);
15879
15880       while (expression)
15881         {
15882           if (type_dependent_expression_p (OVL_CURRENT (expression)))
15883             return true;
15884           expression = OVL_NEXT (expression);
15885         }
15886       return false;
15887     }
15888
15889   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
15890
15891   return (dependent_type_p (TREE_TYPE (expression)));
15892 }
15893
15894 /* Returns TRUE if ARGS (a TREE_LIST of arguments to a function call)
15895    contains a type-dependent expression.  */
15896
15897 bool
15898 any_type_dependent_arguments_p (const_tree args)
15899 {
15900   while (args)
15901     {
15902       tree arg = TREE_VALUE (args);
15903
15904       if (type_dependent_expression_p (arg))
15905         return true;
15906       args = TREE_CHAIN (args);
15907     }
15908   return false;
15909 }
15910
15911 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
15912    expressions) contains any value-dependent expressions.  */
15913
15914 bool
15915 any_value_dependent_elements_p (const_tree list)
15916 {
15917   for (; list; list = TREE_CHAIN (list))
15918     if (value_dependent_expression_p (TREE_VALUE (list)))
15919       return true;
15920
15921   return false;
15922 }
15923
15924 /* Returns TRUE if the ARG (a template argument) is dependent.  */
15925
15926 bool
15927 dependent_template_arg_p (tree arg)
15928 {
15929   if (!processing_template_decl)
15930     return false;
15931
15932   if (TREE_CODE (arg) == TEMPLATE_DECL
15933       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
15934     return dependent_template_p (arg);
15935   else if (ARGUMENT_PACK_P (arg))
15936     {
15937       tree args = ARGUMENT_PACK_ARGS (arg);
15938       int i, len = TREE_VEC_LENGTH (args);
15939       for (i = 0; i < len; ++i)
15940         {
15941           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
15942             return true;
15943         }
15944
15945       return false;
15946     }
15947   else if (TYPE_P (arg))
15948     return dependent_type_p (arg);
15949   else
15950     return (type_dependent_expression_p (arg)
15951             || value_dependent_expression_p (arg));
15952 }
15953
15954 /* Returns true if ARGS (a collection of template arguments) contains
15955    any types that require structural equality testing.  */
15956
15957 bool
15958 any_template_arguments_need_structural_equality_p (tree args)
15959 {
15960   int i;
15961   int j;
15962
15963   if (!args)
15964     return false;
15965   if (args == error_mark_node)
15966     return true;
15967
15968   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
15969     {
15970       tree level = TMPL_ARGS_LEVEL (args, i + 1);
15971       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
15972         {
15973           tree arg = TREE_VEC_ELT (level, j);
15974           tree packed_args = NULL_TREE;
15975           int k, len = 1;
15976
15977           if (ARGUMENT_PACK_P (arg))
15978             {
15979               /* Look inside the argument pack.  */
15980               packed_args = ARGUMENT_PACK_ARGS (arg);
15981               len = TREE_VEC_LENGTH (packed_args);
15982             }
15983
15984           for (k = 0; k < len; ++k)
15985             {
15986               if (packed_args)
15987                 arg = TREE_VEC_ELT (packed_args, k);
15988
15989               if (error_operand_p (arg))
15990                 return true;
15991               else if (TREE_CODE (arg) == TEMPLATE_DECL
15992                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
15993                 continue;
15994               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
15995                 return true;
15996               else if (!TYPE_P (arg) && TREE_TYPE (arg)
15997                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
15998                 return true;
15999             }
16000         }
16001     }
16002
16003   return false;
16004 }
16005
16006 /* Returns true if ARGS (a collection of template arguments) contains
16007    any dependent arguments.  */
16008
16009 bool
16010 any_dependent_template_arguments_p (const_tree args)
16011 {
16012   int i;
16013   int j;
16014
16015   if (!args)
16016     return false;
16017   if (args == error_mark_node)
16018     return true;
16019
16020   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16021     {
16022       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
16023       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16024         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
16025           return true;
16026     }
16027
16028   return false;
16029 }
16030
16031 /* Returns TRUE if the template TMPL is dependent.  */
16032
16033 bool
16034 dependent_template_p (tree tmpl)
16035 {
16036   if (TREE_CODE (tmpl) == OVERLOAD)
16037     {
16038       while (tmpl)
16039         {
16040           if (dependent_template_p (OVL_FUNCTION (tmpl)))
16041             return true;
16042           tmpl = OVL_CHAIN (tmpl);
16043         }
16044       return false;
16045     }
16046
16047   /* Template template parameters are dependent.  */
16048   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
16049       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16050     return true;
16051   /* So are names that have not been looked up.  */
16052   if (TREE_CODE (tmpl) == SCOPE_REF
16053       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
16054     return true;
16055   /* So are member templates of dependent classes.  */
16056   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
16057     return dependent_type_p (DECL_CONTEXT (tmpl));
16058   return false;
16059 }
16060
16061 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
16062
16063 bool
16064 dependent_template_id_p (tree tmpl, tree args)
16065 {
16066   return (dependent_template_p (tmpl)
16067           || any_dependent_template_arguments_p (args));
16068 }
16069
16070 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
16071    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
16072    no such TYPE can be found.  Note that this function peers inside
16073    uninstantiated templates and therefore should be used only in
16074    extremely limited situations.  ONLY_CURRENT_P restricts this
16075    peering to the currently open classes hierarchy (which is required
16076    when comparing types).  */
16077
16078 tree
16079 resolve_typename_type (tree type, bool only_current_p)
16080 {
16081   tree scope;
16082   tree name;
16083   tree decl;
16084   int quals;
16085   tree pushed_scope;
16086   tree result;
16087
16088   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
16089
16090   scope = TYPE_CONTEXT (type);
16091   name = TYPE_IDENTIFIER (type);
16092
16093   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
16094      it first before we can figure out what NAME refers to.  */
16095   if (TREE_CODE (scope) == TYPENAME_TYPE)
16096     scope = resolve_typename_type (scope, only_current_p);
16097   /* If we don't know what SCOPE refers to, then we cannot resolve the
16098      TYPENAME_TYPE.  */
16099   if (TREE_CODE (scope) == TYPENAME_TYPE)
16100     return type;
16101   /* If the SCOPE is a template type parameter, we have no way of
16102      resolving the name.  */
16103   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
16104     return type;
16105   /* If the SCOPE is not the current instantiation, there's no reason
16106      to look inside it.  */
16107   if (only_current_p && !currently_open_class (scope))
16108     return type;
16109   /* If SCOPE isn't the template itself, it will not have a valid
16110      TYPE_FIELDS list.  */
16111   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
16112     /* scope is either the template itself or a compatible instantiation
16113        like X<T>, so look up the name in the original template.  */
16114     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
16115   else
16116     /* scope is a partial instantiation, so we can't do the lookup or we
16117        will lose the template arguments.  */
16118     return type;
16119   /* Enter the SCOPE so that name lookup will be resolved as if we
16120      were in the class definition.  In particular, SCOPE will no
16121      longer be considered a dependent type.  */
16122   pushed_scope = push_scope (scope);
16123   /* Look up the declaration.  */
16124   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
16125
16126   result = NULL_TREE;
16127   
16128   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
16129      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
16130   if (!decl)
16131     /*nop*/;
16132   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
16133            && TREE_CODE (decl) == TYPE_DECL)
16134     {
16135       result = TREE_TYPE (decl);
16136       if (result == error_mark_node)
16137         result = NULL_TREE;
16138     }
16139   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
16140            && DECL_CLASS_TEMPLATE_P (decl))
16141     {
16142       tree tmpl;
16143       tree args;
16144       /* Obtain the template and the arguments.  */
16145       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
16146       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
16147       /* Instantiate the template.  */
16148       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
16149                                       /*entering_scope=*/0,
16150                                       tf_error | tf_user);
16151       if (result == error_mark_node)
16152         result = NULL_TREE;
16153     }
16154   
16155   /* Leave the SCOPE.  */
16156   if (pushed_scope)
16157     pop_scope (pushed_scope);
16158
16159   /* If we failed to resolve it, return the original typename.  */
16160   if (!result)
16161     return type;
16162   
16163   /* If lookup found a typename type, resolve that too.  */
16164   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
16165     {
16166       /* Ill-formed programs can cause infinite recursion here, so we
16167          must catch that.  */
16168       TYPENAME_IS_RESOLVING_P (type) = 1;
16169       result = resolve_typename_type (result, only_current_p);
16170       TYPENAME_IS_RESOLVING_P (type) = 0;
16171     }
16172   
16173   /* Qualify the resulting type.  */
16174   quals = cp_type_quals (type);
16175   if (quals)
16176     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
16177
16178   return result;
16179 }
16180
16181 /* EXPR is an expression which is not type-dependent.  Return a proxy
16182    for EXPR that can be used to compute the types of larger
16183    expressions containing EXPR.  */
16184
16185 tree
16186 build_non_dependent_expr (tree expr)
16187 {
16188   tree inner_expr;
16189
16190   /* Preserve null pointer constants so that the type of things like
16191      "p == 0" where "p" is a pointer can be determined.  */
16192   if (null_ptr_cst_p (expr))
16193     return expr;
16194   /* Preserve OVERLOADs; the functions must be available to resolve
16195      types.  */
16196   inner_expr = expr;
16197   if (TREE_CODE (inner_expr) == STMT_EXPR)
16198     inner_expr = stmt_expr_value_expr (inner_expr);
16199   if (TREE_CODE (inner_expr) == ADDR_EXPR)
16200     inner_expr = TREE_OPERAND (inner_expr, 0);
16201   if (TREE_CODE (inner_expr) == COMPONENT_REF)
16202     inner_expr = TREE_OPERAND (inner_expr, 1);
16203   if (is_overloaded_fn (inner_expr)
16204       || TREE_CODE (inner_expr) == OFFSET_REF)
16205     return expr;
16206   /* There is no need to return a proxy for a variable.  */
16207   if (TREE_CODE (expr) == VAR_DECL)
16208     return expr;
16209   /* Preserve string constants; conversions from string constants to
16210      "char *" are allowed, even though normally a "const char *"
16211      cannot be used to initialize a "char *".  */
16212   if (TREE_CODE (expr) == STRING_CST)
16213     return expr;
16214   /* Preserve arithmetic constants, as an optimization -- there is no
16215      reason to create a new node.  */
16216   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
16217     return expr;
16218   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
16219      There is at least one place where we want to know that a
16220      particular expression is a throw-expression: when checking a ?:
16221      expression, there are special rules if the second or third
16222      argument is a throw-expression.  */
16223   if (TREE_CODE (expr) == THROW_EXPR)
16224     return expr;
16225
16226   if (TREE_CODE (expr) == COND_EXPR)
16227     return build3 (COND_EXPR,
16228                    TREE_TYPE (expr),
16229                    TREE_OPERAND (expr, 0),
16230                    (TREE_OPERAND (expr, 1)
16231                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
16232                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
16233                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
16234   if (TREE_CODE (expr) == COMPOUND_EXPR
16235       && !COMPOUND_EXPR_OVERLOADED (expr))
16236     return build2 (COMPOUND_EXPR,
16237                    TREE_TYPE (expr),
16238                    TREE_OPERAND (expr, 0),
16239                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
16240
16241   /* If the type is unknown, it can't really be non-dependent */
16242   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
16243
16244   /* Otherwise, build a NON_DEPENDENT_EXPR.
16245
16246      REFERENCE_TYPEs are not stripped for expressions in templates
16247      because doing so would play havoc with mangling.  Consider, for
16248      example:
16249
16250        template <typename T> void f<T& g>() { g(); }
16251
16252      In the body of "f", the expression for "g" will have
16253      REFERENCE_TYPE, even though the standard says that it should
16254      not.  The reason is that we must preserve the syntactic form of
16255      the expression so that mangling (say) "f<g>" inside the body of
16256      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
16257      stripped here.  */
16258   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
16259 }
16260
16261 /* ARGS is a TREE_LIST of expressions as arguments to a function call.
16262    Return a new TREE_LIST with the various arguments replaced with
16263    equivalent non-dependent expressions.  */
16264
16265 tree
16266 build_non_dependent_args (tree args)
16267 {
16268   tree a;
16269   tree new_args;
16270
16271   new_args = NULL_TREE;
16272   for (a = args; a; a = TREE_CHAIN (a))
16273     new_args = tree_cons (NULL_TREE,
16274                           build_non_dependent_expr (TREE_VALUE (a)),
16275                           new_args);
16276   return nreverse (new_args);
16277 }
16278
16279 #include "gt-cp-pt.h"