re PR c++/35405 (Internal compiler error)
[platform/upstream/gcc.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 (MAYBE_CLASS_TYPE_P (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_READONLY (decl) = 1;
388             DECL_INITIAL (decl) = DECL_INITIAL (parm);
389             SET_DECL_TEMPLATE_PARM_P (decl);
390             pushdecl (decl);
391           }
392           break;
393
394         default:
395           gcc_unreachable ();
396         }
397     }
398 }
399
400 /* Restore the template parameter context for a member template or
401    a friend template defined in a class definition.  */
402
403 void
404 maybe_begin_member_template_processing (tree decl)
405 {
406   tree parms;
407   int levels = 0;
408
409   if (inline_needs_template_parms (decl))
410     {
411       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
412       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
413
414       if (DECL_TEMPLATE_SPECIALIZATION (decl))
415         {
416           --levels;
417           parms = TREE_CHAIN (parms);
418         }
419
420       push_inline_template_parms_recursive (parms, levels);
421     }
422
423   /* Remember how many levels of template parameters we pushed so that
424      we can pop them later.  */
425   VEC_safe_push (int, heap, inline_parm_levels, levels);
426 }
427
428 /* Undo the effects of maybe_begin_member_template_processing.  */
429
430 void
431 maybe_end_member_template_processing (void)
432 {
433   int i;
434   int last;
435
436   if (VEC_length (int, inline_parm_levels) == 0)
437     return;
438
439   last = VEC_pop (int, inline_parm_levels);
440   for (i = 0; i < last; ++i)
441     {
442       --processing_template_decl;
443       current_template_parms = TREE_CHAIN (current_template_parms);
444       poplevel (0, 0, 0);
445     }
446 }
447
448 /* Return a new template argument vector which contains all of ARGS,
449    but has as its innermost set of arguments the EXTRA_ARGS.  */
450
451 static tree
452 add_to_template_args (tree args, tree extra_args)
453 {
454   tree new_args;
455   int extra_depth;
456   int i;
457   int j;
458
459   extra_depth = TMPL_ARGS_DEPTH (extra_args);
460   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
461
462   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
463     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
464
465   for (j = 1; j <= extra_depth; ++j, ++i)
466     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
467
468   return new_args;
469 }
470
471 /* Like add_to_template_args, but only the outermost ARGS are added to
472    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
473    (EXTRA_ARGS) levels are added.  This function is used to combine
474    the template arguments from a partial instantiation with the
475    template arguments used to attain the full instantiation from the
476    partial instantiation.  */
477
478 static tree
479 add_outermost_template_args (tree args, tree extra_args)
480 {
481   tree new_args;
482
483   /* If there are more levels of EXTRA_ARGS than there are ARGS,
484      something very fishy is going on.  */
485   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
486
487   /* If *all* the new arguments will be the EXTRA_ARGS, just return
488      them.  */
489   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
490     return extra_args;
491
492   /* For the moment, we make ARGS look like it contains fewer levels.  */
493   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
494
495   new_args = add_to_template_args (args, extra_args);
496
497   /* Now, we restore ARGS to its full dimensions.  */
498   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
499
500   return new_args;
501 }
502
503 /* Return the N levels of innermost template arguments from the ARGS.  */
504
505 tree
506 get_innermost_template_args (tree args, int n)
507 {
508   tree new_args;
509   int extra_levels;
510   int i;
511
512   gcc_assert (n >= 0);
513
514   /* If N is 1, just return the innermost set of template arguments.  */
515   if (n == 1)
516     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
517
518   /* If we're not removing anything, just return the arguments we were
519      given.  */
520   extra_levels = TMPL_ARGS_DEPTH (args) - n;
521   gcc_assert (extra_levels >= 0);
522   if (extra_levels == 0)
523     return args;
524
525   /* Make a new set of arguments, not containing the outer arguments.  */
526   new_args = make_tree_vec (n);
527   for (i = 1; i <= n; ++i)
528     SET_TMPL_ARGS_LEVEL (new_args, i,
529                          TMPL_ARGS_LEVEL (args, i + extra_levels));
530
531   return new_args;
532 }
533
534 /* The inverse of get_innermost_template_args: Return all but the innermost
535    EXTRA_LEVELS levels of template arguments from the ARGS.  */
536
537 static tree
538 strip_innermost_template_args (tree args, int extra_levels)
539 {
540   tree new_args;
541   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
542   int i;
543
544   gcc_assert (n >= 0);
545
546   /* If N is 1, just return the outermost set of template arguments.  */
547   if (n == 1)
548     return TMPL_ARGS_LEVEL (args, 1);
549
550   /* If we're not removing anything, just return the arguments we were
551      given.  */
552   gcc_assert (extra_levels >= 0);
553   if (extra_levels == 0)
554     return args;
555
556   /* Make a new set of arguments, not containing the inner arguments.  */
557   new_args = make_tree_vec (n);
558   for (i = 1; i <= n; ++i)
559     SET_TMPL_ARGS_LEVEL (new_args, i,
560                          TMPL_ARGS_LEVEL (args, i));
561
562   return new_args;
563 }
564
565 /* We've got a template header coming up; push to a new level for storing
566    the parms.  */
567
568 void
569 begin_template_parm_list (void)
570 {
571   /* We use a non-tag-transparent scope here, which causes pushtag to
572      put tags in this scope, rather than in the enclosing class or
573      namespace scope.  This is the right thing, since we want
574      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
575      global template class, push_template_decl handles putting the
576      TEMPLATE_DECL into top-level scope.  For a nested template class,
577      e.g.:
578
579        template <class T> struct S1 {
580          template <class T> struct S2 {};
581        };
582
583      pushtag contains special code to call pushdecl_with_scope on the
584      TEMPLATE_DECL for S2.  */
585   begin_scope (sk_template_parms, NULL);
586   ++processing_template_decl;
587   ++processing_template_parmlist;
588   note_template_header (0);
589 }
590
591 /* This routine is called when a specialization is declared.  If it is
592    invalid to declare a specialization here, an error is reported and
593    false is returned, otherwise this routine will return true.  */
594
595 static bool
596 check_specialization_scope (void)
597 {
598   tree scope = current_scope ();
599
600   /* [temp.expl.spec]
601
602      An explicit specialization shall be declared in the namespace of
603      which the template is a member, or, for member templates, in the
604      namespace of which the enclosing class or enclosing class
605      template is a member.  An explicit specialization of a member
606      function, member class or static data member of a class template
607      shall be declared in the namespace of which the class template
608      is a member.  */
609   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
610     {
611       error ("explicit specialization in non-namespace scope %qD", scope);
612       return false;
613     }
614
615   /* [temp.expl.spec]
616
617      In an explicit specialization declaration for a member of a class
618      template or a member template that appears in namespace scope,
619      the member template and some of its enclosing class templates may
620      remain unspecialized, except that the declaration shall not
621      explicitly specialize a class member template if its enclosing
622      class templates are not explicitly specialized as well.  */
623   if (current_template_parms)
624     {
625       error ("enclosing class templates are not explicitly specialized");
626       return false;
627     }
628
629   return true;
630 }
631
632 /* We've just seen template <>.  */
633
634 bool
635 begin_specialization (void)
636 {
637   begin_scope (sk_template_spec, NULL);
638   note_template_header (1);
639   return check_specialization_scope ();
640 }
641
642 /* Called at then end of processing a declaration preceded by
643    template<>.  */
644
645 void
646 end_specialization (void)
647 {
648   finish_scope ();
649   reset_specialization ();
650 }
651
652 /* Any template <>'s that we have seen thus far are not referring to a
653    function specialization.  */
654
655 void
656 reset_specialization (void)
657 {
658   processing_specialization = 0;
659   template_header_count = 0;
660 }
661
662 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
663    it was of the form template <>.  */
664
665 static void
666 note_template_header (int specialization)
667 {
668   processing_specialization = specialization;
669   template_header_count++;
670 }
671
672 /* We're beginning an explicit instantiation.  */
673
674 void
675 begin_explicit_instantiation (void)
676 {
677   gcc_assert (!processing_explicit_instantiation);
678   processing_explicit_instantiation = true;
679 }
680
681
682 void
683 end_explicit_instantiation (void)
684 {
685   gcc_assert (processing_explicit_instantiation);
686   processing_explicit_instantiation = false;
687 }
688
689 /* An explicit specialization or partial specialization TMPL is being
690    declared.  Check that the namespace in which the specialization is
691    occurring is permissible.  Returns false iff it is invalid to
692    specialize TMPL in the current namespace.  */
693
694 static bool
695 check_specialization_namespace (tree tmpl)
696 {
697   tree tpl_ns = decl_namespace_context (tmpl);
698
699   /* [tmpl.expl.spec]
700
701      An explicit specialization shall be declared in the namespace of
702      which the template is a member, or, for member templates, in the
703      namespace of which the enclosing class or enclosing class
704      template is a member.  An explicit specialization of a member
705      function, member class or static data member of a class template
706      shall be declared in the namespace of which the class template is
707      a member.  */
708   if (is_associated_namespace (current_namespace, tpl_ns))
709     /* Same or super-using namespace.  */
710     return true;
711   else
712     {
713       permerror (input_location, "specialization of %qD in different namespace", tmpl);
714       permerror (input_location, "  from definition of %q+#D", tmpl);
715       return false;
716     }
717 }
718
719 /* SPEC is an explicit instantiation.  Check that it is valid to
720    perform this explicit instantiation in the current namespace.  */
721
722 static void
723 check_explicit_instantiation_namespace (tree spec)
724 {
725   tree ns;
726
727   /* DR 275: An explicit instantiation shall appear in an enclosing
728      namespace of its template.  */
729   ns = decl_namespace_context (spec);
730   if (!is_ancestor (current_namespace, ns))
731     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
732                "(which does not enclose namespace %qD)",
733                spec, current_namespace, ns);
734 }
735
736 /* The TYPE is being declared.  If it is a template type, that means it
737    is a partial specialization.  Do appropriate error-checking.  */
738
739 tree
740 maybe_process_partial_specialization (tree type)
741 {
742   tree context;
743
744   if (type == error_mark_node)
745     return error_mark_node;
746
747   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
748     {
749       error ("name of class shadows template template parameter %qD",
750              TYPE_NAME (type));
751       return error_mark_node;
752     }
753
754   context = TYPE_CONTEXT (type);
755
756   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
757     {
758       /* This is for ordinary explicit specialization and partial
759          specialization of a template class such as:
760
761            template <> class C<int>;
762
763          or:
764
765            template <class T> class C<T*>;
766
767          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
768
769       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
770           && !COMPLETE_TYPE_P (type))
771         {
772           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
773           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
774           if (processing_template_decl)
775             {
776               if (push_template_decl (TYPE_MAIN_DECL (type))
777                   == error_mark_node)
778                 return error_mark_node;
779             }
780         }
781       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
782         error ("specialization of %qT after instantiation", type);
783     }
784   else if (CLASS_TYPE_P (type)
785            && !CLASSTYPE_USE_TEMPLATE (type)
786            && CLASSTYPE_TEMPLATE_INFO (type)
787            && context && CLASS_TYPE_P (context)
788            && CLASSTYPE_TEMPLATE_INFO (context))
789     {
790       /* This is for an explicit specialization of member class
791          template according to [temp.expl.spec/18]:
792
793            template <> template <class U> class C<int>::D;
794
795          The context `C<int>' must be an implicit instantiation.
796          Otherwise this is just a member class template declared
797          earlier like:
798
799            template <> class C<int> { template <class U> class D; };
800            template <> template <class U> class C<int>::D;
801
802          In the first case, `C<int>::D' is a specialization of `C<T>::D'
803          while in the second case, `C<int>::D' is a primary template
804          and `C<T>::D' may not exist.  */
805
806       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
807           && !COMPLETE_TYPE_P (type))
808         {
809           tree t;
810
811           if (current_namespace
812               != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
813             {
814               permerror (input_location, "specializing %q#T in different namespace", type);
815               permerror (input_location, "  from definition of %q+#D",
816                          CLASSTYPE_TI_TEMPLATE (type));
817             }
818
819           /* Check for invalid specialization after instantiation:
820
821                template <> template <> class C<int>::D<int>;
822                template <> template <class U> class C<int>::D;  */
823
824           for (t = DECL_TEMPLATE_INSTANTIATIONS
825                  (most_general_template (CLASSTYPE_TI_TEMPLATE (type)));
826                t; t = TREE_CHAIN (t))
827             if (TREE_VALUE (t) != type
828                 && TYPE_CONTEXT (TREE_VALUE (t)) == context)
829               error ("specialization %qT after instantiation %qT",
830                      type, TREE_VALUE (t));
831
832           /* Mark TYPE as a specialization.  And as a result, we only
833              have one level of template argument for the innermost
834              class template.  */
835           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
836           CLASSTYPE_TI_ARGS (type)
837             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
838         }
839     }
840   else if (processing_specialization)
841     {
842       error ("explicit specialization of non-template %qT", type);
843       return error_mark_node;
844     }
845
846   return type;
847 }
848
849 /* Returns nonzero if we can optimize the retrieval of specializations
850    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
851    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
852
853 static inline bool
854 optimize_specialization_lookup_p (tree tmpl)
855 {
856   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
857           && DECL_CLASS_SCOPE_P (tmpl)
858           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
859              parameter.  */
860           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
861           /* The optimized lookup depends on the fact that the
862              template arguments for the member function template apply
863              purely to the containing class, which is not true if the
864              containing class is an explicit or partial
865              specialization.  */
866           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
867           && !DECL_MEMBER_TEMPLATE_P (tmpl)
868           && !DECL_CONV_FN_P (tmpl)
869           /* It is possible to have a template that is not a member
870              template and is not a member of a template class:
871
872              template <typename T>
873              struct S { friend A::f(); };
874
875              Here, the friend function is a template, but the context does
876              not have template information.  The optimized lookup relies
877              on having ARGS be the template arguments for both the class
878              and the function template.  */
879           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
880 }
881
882 /* Retrieve the specialization (in the sense of [temp.spec] - a
883    specialization is either an instantiation or an explicit
884    specialization) of TMPL for the given template ARGS.  If there is
885    no such specialization, return NULL_TREE.  The ARGS are a vector of
886    arguments, or a vector of vectors of arguments, in the case of
887    templates with more than one level of parameters.
888
889    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
890    then we search for a partial specialization matching ARGS.  This
891    parameter is ignored if TMPL is not a class template.  */
892
893 static tree
894 retrieve_specialization (tree tmpl, tree args,
895                          bool class_specializations_p)
896 {
897   if (args == error_mark_node)
898     return NULL_TREE;
899
900   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
901
902   /* There should be as many levels of arguments as there are
903      levels of parameters.  */
904   gcc_assert (TMPL_ARGS_DEPTH (args)
905               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
906
907   if (optimize_specialization_lookup_p (tmpl))
908     {
909       tree class_template;
910       tree class_specialization;
911       VEC(tree,gc) *methods;
912       tree fns;
913       int idx;
914
915       /* The template arguments actually apply to the containing
916          class.  Find the class specialization with those
917          arguments.  */
918       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
919       class_specialization
920         = retrieve_specialization (class_template, args,
921                                    /*class_specializations_p=*/false);
922       if (!class_specialization)
923         return NULL_TREE;
924       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
925          for the specialization.  */
926       idx = class_method_index_for_fn (class_specialization, tmpl);
927       if (idx == -1)
928         return NULL_TREE;
929       /* Iterate through the methods with the indicated name, looking
930          for the one that has an instance of TMPL.  */
931       methods = CLASSTYPE_METHOD_VEC (class_specialization);
932       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
933         {
934           tree fn = OVL_CURRENT (fns);
935           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl)
936             return fn;
937         }
938       return NULL_TREE;
939     }
940   else
941     {
942       tree *sp;
943       tree *head;
944
945       /* Class templates store their instantiations on the
946          DECL_TEMPLATE_INSTANTIATIONS list; other templates use the
947          DECL_TEMPLATE_SPECIALIZATIONS list.  */
948       if (!class_specializations_p
949           && TREE_CODE (DECL_TEMPLATE_RESULT (tmpl)) == TYPE_DECL
950           && TAGGED_TYPE_P (TREE_TYPE (tmpl)))
951         sp = &DECL_TEMPLATE_INSTANTIATIONS (tmpl);
952       else
953         sp = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
954       head = sp;
955       /* Iterate through the list until we find a matching template.  */
956       while (*sp != NULL_TREE)
957         {
958           tree spec = *sp;
959
960           if (comp_template_args (TREE_PURPOSE (spec), args))
961             {
962               /* Use the move-to-front heuristic to speed up future
963                  searches.  */
964               if (spec != *head)
965                 {
966                   *sp = TREE_CHAIN (*sp);
967                   TREE_CHAIN (spec) = *head;
968                   *head = spec;
969                 }
970               return TREE_VALUE (spec);
971             }
972           sp = &TREE_CHAIN (spec);
973         }
974     }
975
976   return NULL_TREE;
977 }
978
979 /* Like retrieve_specialization, but for local declarations.  */
980
981 static tree
982 retrieve_local_specialization (tree tmpl)
983 {
984   tree spec;
985
986   if (local_specializations == NULL)
987     return NULL_TREE;
988
989   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
990                                      htab_hash_pointer (tmpl));
991   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
992 }
993
994 /* Returns nonzero iff DECL is a specialization of TMPL.  */
995
996 int
997 is_specialization_of (tree decl, tree tmpl)
998 {
999   tree t;
1000
1001   if (TREE_CODE (decl) == FUNCTION_DECL)
1002     {
1003       for (t = decl;
1004            t != NULL_TREE;
1005            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1006         if (t == tmpl)
1007           return 1;
1008     }
1009   else
1010     {
1011       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1012
1013       for (t = TREE_TYPE (decl);
1014            t != NULL_TREE;
1015            t = CLASSTYPE_USE_TEMPLATE (t)
1016              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1017         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1018           return 1;
1019     }
1020
1021   return 0;
1022 }
1023
1024 /* Returns nonzero iff DECL is a specialization of friend declaration
1025    FRIEND_DECL according to [temp.friend].  */
1026
1027 bool
1028 is_specialization_of_friend (tree decl, tree friend_decl)
1029 {
1030   bool need_template = true;
1031   int template_depth;
1032
1033   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1034               || TREE_CODE (decl) == TYPE_DECL);
1035
1036   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1037      of a template class, we want to check if DECL is a specialization
1038      if this.  */
1039   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1040       && DECL_TEMPLATE_INFO (friend_decl)
1041       && !DECL_USE_TEMPLATE (friend_decl))
1042     {
1043       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1044       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1045       need_template = false;
1046     }
1047   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1048            && !PRIMARY_TEMPLATE_P (friend_decl))
1049     need_template = false;
1050
1051   /* There is nothing to do if this is not a template friend.  */
1052   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1053     return false;
1054
1055   if (is_specialization_of (decl, friend_decl))
1056     return true;
1057
1058   /* [temp.friend/6]
1059      A member of a class template may be declared to be a friend of a
1060      non-template class.  In this case, the corresponding member of
1061      every specialization of the class template is a friend of the
1062      class granting friendship.
1063
1064      For example, given a template friend declaration
1065
1066        template <class T> friend void A<T>::f();
1067
1068      the member function below is considered a friend
1069
1070        template <> struct A<int> {
1071          void f();
1072        };
1073
1074      For this type of template friend, TEMPLATE_DEPTH below will be
1075      nonzero.  To determine if DECL is a friend of FRIEND, we first
1076      check if the enclosing class is a specialization of another.  */
1077
1078   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1079   if (template_depth
1080       && DECL_CLASS_SCOPE_P (decl)
1081       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1082                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1083     {
1084       /* Next, we check the members themselves.  In order to handle
1085          a few tricky cases, such as when FRIEND_DECL's are
1086
1087            template <class T> friend void A<T>::g(T t);
1088            template <class T> template <T t> friend void A<T>::h();
1089
1090          and DECL's are
1091
1092            void A<int>::g(int);
1093            template <int> void A<int>::h();
1094
1095          we need to figure out ARGS, the template arguments from
1096          the context of DECL.  This is required for template substitution
1097          of `T' in the function parameter of `g' and template parameter
1098          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1099
1100       tree context = DECL_CONTEXT (decl);
1101       tree args = NULL_TREE;
1102       int current_depth = 0;
1103
1104       while (current_depth < template_depth)
1105         {
1106           if (CLASSTYPE_TEMPLATE_INFO (context))
1107             {
1108               if (current_depth == 0)
1109                 args = TYPE_TI_ARGS (context);
1110               else
1111                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1112               current_depth++;
1113             }
1114           context = TYPE_CONTEXT (context);
1115         }
1116
1117       if (TREE_CODE (decl) == FUNCTION_DECL)
1118         {
1119           bool is_template;
1120           tree friend_type;
1121           tree decl_type;
1122           tree friend_args_type;
1123           tree decl_args_type;
1124
1125           /* Make sure that both DECL and FRIEND_DECL are templates or
1126              non-templates.  */
1127           is_template = DECL_TEMPLATE_INFO (decl)
1128                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1129           if (need_template ^ is_template)
1130             return false;
1131           else if (is_template)
1132             {
1133               /* If both are templates, check template parameter list.  */
1134               tree friend_parms
1135                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1136                                          args, tf_none);
1137               if (!comp_template_parms
1138                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1139                       friend_parms))
1140                 return false;
1141
1142               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1143             }
1144           else
1145             decl_type = TREE_TYPE (decl);
1146
1147           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1148                                               tf_none, NULL_TREE);
1149           if (friend_type == error_mark_node)
1150             return false;
1151
1152           /* Check if return types match.  */
1153           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1154             return false;
1155
1156           /* Check if function parameter types match, ignoring the
1157              `this' parameter.  */
1158           friend_args_type = TYPE_ARG_TYPES (friend_type);
1159           decl_args_type = TYPE_ARG_TYPES (decl_type);
1160           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1161             friend_args_type = TREE_CHAIN (friend_args_type);
1162           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1163             decl_args_type = TREE_CHAIN (decl_args_type);
1164
1165           return compparms (decl_args_type, friend_args_type);
1166         }
1167       else
1168         {
1169           /* DECL is a TYPE_DECL */
1170           bool is_template;
1171           tree decl_type = TREE_TYPE (decl);
1172
1173           /* Make sure that both DECL and FRIEND_DECL are templates or
1174              non-templates.  */
1175           is_template
1176             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1177               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1178
1179           if (need_template ^ is_template)
1180             return false;
1181           else if (is_template)
1182             {
1183               tree friend_parms;
1184               /* If both are templates, check the name of the two
1185                  TEMPLATE_DECL's first because is_friend didn't.  */
1186               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1187                   != DECL_NAME (friend_decl))
1188                 return false;
1189
1190               /* Now check template parameter list.  */
1191               friend_parms
1192                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1193                                          args, tf_none);
1194               return comp_template_parms
1195                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1196                  friend_parms);
1197             }
1198           else
1199             return (DECL_NAME (decl)
1200                     == DECL_NAME (friend_decl));
1201         }
1202     }
1203   return false;
1204 }
1205
1206 /* Register the specialization SPEC as a specialization of TMPL with
1207    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1208    is actually just a friend declaration.  Returns SPEC, or an
1209    equivalent prior declaration, if available.  */
1210
1211 static tree
1212 register_specialization (tree spec, tree tmpl, tree args, bool is_friend)
1213 {
1214   tree fn;
1215
1216   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1217
1218   if (TREE_CODE (spec) == FUNCTION_DECL
1219       && uses_template_parms (DECL_TI_ARGS (spec)))
1220     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1221        register it; we want the corresponding TEMPLATE_DECL instead.
1222        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1223        the more obvious `uses_template_parms (spec)' to avoid problems
1224        with default function arguments.  In particular, given
1225        something like this:
1226
1227           template <class T> void f(T t1, T t = T())
1228
1229        the default argument expression is not substituted for in an
1230        instantiation unless and until it is actually needed.  */
1231     return spec;
1232
1233   fn = retrieve_specialization (tmpl, args,
1234                                 /*class_specializations_p=*/false);
1235   /* We can sometimes try to re-register a specialization that we've
1236      already got.  In particular, regenerate_decl_from_template calls
1237      duplicate_decls which will update the specialization list.  But,
1238      we'll still get called again here anyhow.  It's more convenient
1239      to simply allow this than to try to prevent it.  */
1240   if (fn == spec)
1241     return spec;
1242   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1243     {
1244       if (DECL_TEMPLATE_INSTANTIATION (fn))
1245         {
1246           if (TREE_USED (fn)
1247               || DECL_EXPLICIT_INSTANTIATION (fn))
1248             {
1249               error ("specialization of %qD after instantiation",
1250                      fn);
1251               return error_mark_node;
1252             }
1253           else
1254             {
1255               tree clone;
1256               /* This situation should occur only if the first
1257                  specialization is an implicit instantiation, the
1258                  second is an explicit specialization, and the
1259                  implicit instantiation has not yet been used.  That
1260                  situation can occur if we have implicitly
1261                  instantiated a member function and then specialized
1262                  it later.
1263
1264                  We can also wind up here if a friend declaration that
1265                  looked like an instantiation turns out to be a
1266                  specialization:
1267
1268                    template <class T> void foo(T);
1269                    class S { friend void foo<>(int) };
1270                    template <> void foo(int);
1271
1272                  We transform the existing DECL in place so that any
1273                  pointers to it become pointers to the updated
1274                  declaration.
1275
1276                  If there was a definition for the template, but not
1277                  for the specialization, we want this to look as if
1278                  there were no definition, and vice versa.  */
1279               DECL_INITIAL (fn) = NULL_TREE;
1280               duplicate_decls (spec, fn, is_friend);
1281               /* The call to duplicate_decls will have applied
1282                  [temp.expl.spec]:
1283
1284                    An explicit specialization of a function template
1285                    is inline only if it is explicitly declared to be,
1286                    and independently of whether its function template
1287                    is.
1288
1289                 to the primary function; now copy the inline bits to
1290                 the various clones.  */
1291               FOR_EACH_CLONE (clone, fn)
1292                 DECL_DECLARED_INLINE_P (clone)
1293                   = DECL_DECLARED_INLINE_P (fn);
1294               check_specialization_namespace (fn);
1295
1296               return fn;
1297             }
1298         }
1299       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1300         {
1301           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1302             /* Dup decl failed, but this is a new definition. Set the
1303                line number so any errors match this new
1304                definition.  */
1305             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1306
1307           return fn;
1308         }
1309     }
1310
1311   /* A specialization must be declared in the same namespace as the
1312      template it is specializing.  */
1313   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1314       && !check_specialization_namespace (tmpl))
1315     DECL_CONTEXT (spec) = FROB_CONTEXT (decl_namespace_context (tmpl));
1316
1317   if (!optimize_specialization_lookup_p (tmpl))
1318     DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
1319       = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
1320
1321   return spec;
1322 }
1323
1324 /* Unregister the specialization SPEC as a specialization of TMPL.
1325    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1326    if the SPEC was listed as a specialization of TMPL.  */
1327
1328 bool
1329 reregister_specialization (tree spec, tree tmpl, tree new_spec)
1330 {
1331   tree* s;
1332
1333   for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
1334        *s != NULL_TREE;
1335        s = &TREE_CHAIN (*s))
1336     if (TREE_VALUE (*s) == spec)
1337       {
1338         if (!new_spec)
1339           *s = TREE_CHAIN (*s);
1340         else
1341           TREE_VALUE (*s) = new_spec;
1342         return 1;
1343       }
1344
1345   return 0;
1346 }
1347
1348 /* Compare an entry in the local specializations hash table P1 (which
1349    is really a pointer to a TREE_LIST) with P2 (which is really a
1350    DECL).  */
1351
1352 static int
1353 eq_local_specializations (const void *p1, const void *p2)
1354 {
1355   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1356 }
1357
1358 /* Hash P1, an entry in the local specializations table.  */
1359
1360 static hashval_t
1361 hash_local_specialization (const void* p1)
1362 {
1363   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1364 }
1365
1366 /* Like register_specialization, but for local declarations.  We are
1367    registering SPEC, an instantiation of TMPL.  */
1368
1369 static void
1370 register_local_specialization (tree spec, tree tmpl)
1371 {
1372   void **slot;
1373
1374   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1375                                    htab_hash_pointer (tmpl), INSERT);
1376   *slot = build_tree_list (spec, tmpl);
1377 }
1378
1379 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1380    specialized class.  */
1381
1382 bool
1383 explicit_class_specialization_p (tree type)
1384 {
1385   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1386     return false;
1387   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1388 }
1389
1390 /* Print the list of candidate FNS in an error message.  */
1391
1392 void
1393 print_candidates (tree fns)
1394 {
1395   tree fn;
1396
1397   const char *str = "candidates are:";
1398
1399   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1400     {
1401       tree f;
1402
1403       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1404         error ("%s %+#D", str, OVL_CURRENT (f));
1405       str = "               ";
1406     }
1407 }
1408
1409 /* Returns the template (one of the functions given by TEMPLATE_ID)
1410    which can be specialized to match the indicated DECL with the
1411    explicit template args given in TEMPLATE_ID.  The DECL may be
1412    NULL_TREE if none is available.  In that case, the functions in
1413    TEMPLATE_ID are non-members.
1414
1415    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1416    specialization of a member template.
1417
1418    The TEMPLATE_COUNT is the number of references to qualifying
1419    template classes that appeared in the name of the function. See
1420    check_explicit_specialization for a more accurate description.
1421
1422    TSK indicates what kind of template declaration (if any) is being
1423    declared.  TSK_TEMPLATE indicates that the declaration given by
1424    DECL, though a FUNCTION_DECL, has template parameters, and is
1425    therefore a template function.
1426
1427    The template args (those explicitly specified and those deduced)
1428    are output in a newly created vector *TARGS_OUT.
1429
1430    If it is impossible to determine the result, an error message is
1431    issued.  The error_mark_node is returned to indicate failure.  */
1432
1433 static tree
1434 determine_specialization (tree template_id,
1435                           tree decl,
1436                           tree* targs_out,
1437                           int need_member_template,
1438                           int template_count,
1439                           tmpl_spec_kind tsk)
1440 {
1441   tree fns;
1442   tree targs;
1443   tree explicit_targs;
1444   tree candidates = NULL_TREE;
1445   /* A TREE_LIST of templates of which DECL may be a specialization.
1446      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1447      corresponding TREE_PURPOSE is the set of template arguments that,
1448      when used to instantiate the template, would produce a function
1449      with the signature of DECL.  */
1450   tree templates = NULL_TREE;
1451   int header_count;
1452   struct cp_binding_level *b;
1453
1454   *targs_out = NULL_TREE;
1455
1456   if (template_id == error_mark_node || decl == error_mark_node)
1457     return error_mark_node;
1458
1459   fns = TREE_OPERAND (template_id, 0);
1460   explicit_targs = TREE_OPERAND (template_id, 1);
1461
1462   if (fns == error_mark_node)
1463     return error_mark_node;
1464
1465   /* Check for baselinks.  */
1466   if (BASELINK_P (fns))
1467     fns = BASELINK_FUNCTIONS (fns);
1468
1469   if (!is_overloaded_fn (fns))
1470     {
1471       error ("%qD is not a function template", fns);
1472       return error_mark_node;
1473     }
1474
1475   /* Count the number of template headers specified for this
1476      specialization.  */
1477   header_count = 0;
1478   for (b = current_binding_level;
1479        b->kind == sk_template_parms;
1480        b = b->level_chain)
1481     ++header_count;
1482
1483   for (; fns; fns = OVL_NEXT (fns))
1484     {
1485       tree fn = OVL_CURRENT (fns);
1486
1487       if (TREE_CODE (fn) == TEMPLATE_DECL)
1488         {
1489           tree decl_arg_types;
1490           tree fn_arg_types;
1491
1492           /* In case of explicit specialization, we need to check if
1493              the number of template headers appearing in the specialization
1494              is correct. This is usually done in check_explicit_specialization,
1495              but the check done there cannot be exhaustive when specializing
1496              member functions. Consider the following code:
1497
1498              template <> void A<int>::f(int);
1499              template <> template <> void A<int>::f(int);
1500
1501              Assuming that A<int> is not itself an explicit specialization
1502              already, the first line specializes "f" which is a non-template
1503              member function, whilst the second line specializes "f" which
1504              is a template member function. So both lines are syntactically
1505              correct, and check_explicit_specialization does not reject
1506              them.
1507
1508              Here, we can do better, as we are matching the specialization
1509              against the declarations. We count the number of template
1510              headers, and we check if they match TEMPLATE_COUNT + 1
1511              (TEMPLATE_COUNT is the number of qualifying template classes,
1512              plus there must be another header for the member template
1513              itself).
1514
1515              Notice that if header_count is zero, this is not a
1516              specialization but rather a template instantiation, so there
1517              is no check we can perform here.  */
1518           if (header_count && header_count != template_count + 1)
1519             continue;
1520
1521           /* Check that the number of template arguments at the
1522              innermost level for DECL is the same as for FN.  */
1523           if (current_binding_level->kind == sk_template_parms
1524               && !current_binding_level->explicit_spec_p
1525               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1526                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1527                                       (current_template_parms))))
1528             continue;
1529
1530           /* DECL might be a specialization of FN.  */
1531           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1532           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1533
1534           /* For a non-static member function, we need to make sure
1535              that the const qualification is the same.  Since
1536              get_bindings does not try to merge the "this" parameter,
1537              we must do the comparison explicitly.  */
1538           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1539               && !same_type_p (TREE_VALUE (fn_arg_types),
1540                                TREE_VALUE (decl_arg_types)))
1541             continue;
1542
1543           /* Skip the "this" parameter and, for constructors of
1544              classes with virtual bases, the VTT parameter.  A
1545              full specialization of a constructor will have a VTT
1546              parameter, but a template never will.  */ 
1547           decl_arg_types 
1548             = skip_artificial_parms_for (decl, decl_arg_types);
1549           fn_arg_types 
1550             = skip_artificial_parms_for (fn, fn_arg_types);
1551
1552           /* Check that the number of function parameters matches.
1553              For example,
1554                template <class T> void f(int i = 0);
1555                template <> void f<int>();
1556              The specialization f<int> is invalid but is not caught
1557              by get_bindings below.  */
1558           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1559             continue;
1560
1561           /* Function templates cannot be specializations; there are
1562              no partial specializations of functions.  Therefore, if
1563              the type of DECL does not match FN, there is no
1564              match.  */
1565           if (tsk == tsk_template)
1566             {
1567               if (compparms (fn_arg_types, decl_arg_types))
1568                 candidates = tree_cons (NULL_TREE, fn, candidates);
1569               continue;
1570             }
1571
1572           /* See whether this function might be a specialization of this
1573              template.  */
1574           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1575
1576           if (!targs)
1577             /* We cannot deduce template arguments that when used to
1578                specialize TMPL will produce DECL.  */
1579             continue;
1580
1581           /* Save this template, and the arguments deduced.  */
1582           templates = tree_cons (targs, fn, templates);
1583         }
1584       else if (need_member_template)
1585         /* FN is an ordinary member function, and we need a
1586            specialization of a member template.  */
1587         ;
1588       else if (TREE_CODE (fn) != FUNCTION_DECL)
1589         /* We can get IDENTIFIER_NODEs here in certain erroneous
1590            cases.  */
1591         ;
1592       else if (!DECL_FUNCTION_MEMBER_P (fn))
1593         /* This is just an ordinary non-member function.  Nothing can
1594            be a specialization of that.  */
1595         ;
1596       else if (DECL_ARTIFICIAL (fn))
1597         /* Cannot specialize functions that are created implicitly.  */
1598         ;
1599       else
1600         {
1601           tree decl_arg_types;
1602
1603           /* This is an ordinary member function.  However, since
1604              we're here, we can assume it's enclosing class is a
1605              template class.  For example,
1606
1607                template <typename T> struct S { void f(); };
1608                template <> void S<int>::f() {}
1609
1610              Here, S<int>::f is a non-template, but S<int> is a
1611              template class.  If FN has the same type as DECL, we
1612              might be in business.  */
1613
1614           if (!DECL_TEMPLATE_INFO (fn))
1615             /* Its enclosing class is an explicit specialization
1616                of a template class.  This is not a candidate.  */
1617             continue;
1618
1619           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1620                             TREE_TYPE (TREE_TYPE (fn))))
1621             /* The return types differ.  */
1622             continue;
1623
1624           /* Adjust the type of DECL in case FN is a static member.  */
1625           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1626           if (DECL_STATIC_FUNCTION_P (fn)
1627               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1628             decl_arg_types = TREE_CHAIN (decl_arg_types);
1629
1630           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1631                          decl_arg_types))
1632             /* They match!  */
1633             candidates = tree_cons (NULL_TREE, fn, candidates);
1634         }
1635     }
1636
1637   if (templates && TREE_CHAIN (templates))
1638     {
1639       /* We have:
1640
1641            [temp.expl.spec]
1642
1643            It is possible for a specialization with a given function
1644            signature to be instantiated from more than one function
1645            template.  In such cases, explicit specification of the
1646            template arguments must be used to uniquely identify the
1647            function template specialization being specialized.
1648
1649          Note that here, there's no suggestion that we're supposed to
1650          determine which of the candidate templates is most
1651          specialized.  However, we, also have:
1652
1653            [temp.func.order]
1654
1655            Partial ordering of overloaded function template
1656            declarations is used in the following contexts to select
1657            the function template to which a function template
1658            specialization refers:
1659
1660            -- when an explicit specialization refers to a function
1661               template.
1662
1663          So, we do use the partial ordering rules, at least for now.
1664          This extension can only serve to make invalid programs valid,
1665          so it's safe.  And, there is strong anecdotal evidence that
1666          the committee intended the partial ordering rules to apply;
1667          the EDG front end has that behavior, and John Spicer claims
1668          that the committee simply forgot to delete the wording in
1669          [temp.expl.spec].  */
1670       tree tmpl = most_specialized_instantiation (templates);
1671       if (tmpl != error_mark_node)
1672         {
1673           templates = tmpl;
1674           TREE_CHAIN (templates) = NULL_TREE;
1675         }
1676     }
1677
1678   if (templates == NULL_TREE && candidates == NULL_TREE)
1679     {
1680       error ("template-id %qD for %q+D does not match any template "
1681              "declaration", template_id, decl);
1682       return error_mark_node;
1683     }
1684   else if ((templates && TREE_CHAIN (templates))
1685            || (candidates && TREE_CHAIN (candidates))
1686            || (templates && candidates))
1687     {
1688       error ("ambiguous template specialization %qD for %q+D",
1689              template_id, decl);
1690       chainon (candidates, templates);
1691       print_candidates (candidates);
1692       return error_mark_node;
1693     }
1694
1695   /* We have one, and exactly one, match.  */
1696   if (candidates)
1697     {
1698       tree fn = TREE_VALUE (candidates);
1699       /* DECL is a re-declaration of a template function.  */
1700       if (TREE_CODE (fn) == TEMPLATE_DECL)
1701         return fn;
1702       /* It was a specialization of an ordinary member function in a
1703          template class.  */
1704       *targs_out = copy_node (DECL_TI_ARGS (fn));
1705       return DECL_TI_TEMPLATE (fn);
1706     }
1707
1708   /* It was a specialization of a template.  */
1709   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1710   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1711     {
1712       *targs_out = copy_node (targs);
1713       SET_TMPL_ARGS_LEVEL (*targs_out,
1714                            TMPL_ARGS_DEPTH (*targs_out),
1715                            TREE_PURPOSE (templates));
1716     }
1717   else
1718     *targs_out = TREE_PURPOSE (templates);
1719   return TREE_VALUE (templates);
1720 }
1721
1722 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1723    but with the default argument values filled in from those in the
1724    TMPL_TYPES.  */
1725
1726 static tree
1727 copy_default_args_to_explicit_spec_1 (tree spec_types,
1728                                       tree tmpl_types)
1729 {
1730   tree new_spec_types;
1731
1732   if (!spec_types)
1733     return NULL_TREE;
1734
1735   if (spec_types == void_list_node)
1736     return void_list_node;
1737
1738   /* Substitute into the rest of the list.  */
1739   new_spec_types =
1740     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1741                                           TREE_CHAIN (tmpl_types));
1742
1743   /* Add the default argument for this parameter.  */
1744   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1745                          TREE_VALUE (spec_types),
1746                          new_spec_types);
1747 }
1748
1749 /* DECL is an explicit specialization.  Replicate default arguments
1750    from the template it specializes.  (That way, code like:
1751
1752      template <class T> void f(T = 3);
1753      template <> void f(double);
1754      void g () { f (); }
1755
1756    works, as required.)  An alternative approach would be to look up
1757    the correct default arguments at the call-site, but this approach
1758    is consistent with how implicit instantiations are handled.  */
1759
1760 static void
1761 copy_default_args_to_explicit_spec (tree decl)
1762 {
1763   tree tmpl;
1764   tree spec_types;
1765   tree tmpl_types;
1766   tree new_spec_types;
1767   tree old_type;
1768   tree new_type;
1769   tree t;
1770   tree object_type = NULL_TREE;
1771   tree in_charge = NULL_TREE;
1772   tree vtt = NULL_TREE;
1773
1774   /* See if there's anything we need to do.  */
1775   tmpl = DECL_TI_TEMPLATE (decl);
1776   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
1777   for (t = tmpl_types; t; t = TREE_CHAIN (t))
1778     if (TREE_PURPOSE (t))
1779       break;
1780   if (!t)
1781     return;
1782
1783   old_type = TREE_TYPE (decl);
1784   spec_types = TYPE_ARG_TYPES (old_type);
1785
1786   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1787     {
1788       /* Remove the this pointer, but remember the object's type for
1789          CV quals.  */
1790       object_type = TREE_TYPE (TREE_VALUE (spec_types));
1791       spec_types = TREE_CHAIN (spec_types);
1792       tmpl_types = TREE_CHAIN (tmpl_types);
1793
1794       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
1795         {
1796           /* DECL may contain more parameters than TMPL due to the extra
1797              in-charge parameter in constructors and destructors.  */
1798           in_charge = spec_types;
1799           spec_types = TREE_CHAIN (spec_types);
1800         }
1801       if (DECL_HAS_VTT_PARM_P (decl))
1802         {
1803           vtt = spec_types;
1804           spec_types = TREE_CHAIN (spec_types);
1805         }
1806     }
1807
1808   /* Compute the merged default arguments.  */
1809   new_spec_types =
1810     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
1811
1812   /* Compute the new FUNCTION_TYPE.  */
1813   if (object_type)
1814     {
1815       if (vtt)
1816         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
1817                                          TREE_VALUE (vtt),
1818                                          new_spec_types);
1819
1820       if (in_charge)
1821         /* Put the in-charge parameter back.  */
1822         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
1823                                          TREE_VALUE (in_charge),
1824                                          new_spec_types);
1825
1826       new_type = build_method_type_directly (object_type,
1827                                              TREE_TYPE (old_type),
1828                                              new_spec_types);
1829     }
1830   else
1831     new_type = build_function_type (TREE_TYPE (old_type),
1832                                     new_spec_types);
1833   new_type = cp_build_type_attribute_variant (new_type,
1834                                               TYPE_ATTRIBUTES (old_type));
1835   new_type = build_exception_variant (new_type,
1836                                       TYPE_RAISES_EXCEPTIONS (old_type));
1837   TREE_TYPE (decl) = new_type;
1838 }
1839
1840 /* Check to see if the function just declared, as indicated in
1841    DECLARATOR, and in DECL, is a specialization of a function
1842    template.  We may also discover that the declaration is an explicit
1843    instantiation at this point.
1844
1845    Returns DECL, or an equivalent declaration that should be used
1846    instead if all goes well.  Issues an error message if something is
1847    amiss.  Returns error_mark_node if the error is not easily
1848    recoverable.
1849
1850    FLAGS is a bitmask consisting of the following flags:
1851
1852    2: The function has a definition.
1853    4: The function is a friend.
1854
1855    The TEMPLATE_COUNT is the number of references to qualifying
1856    template classes that appeared in the name of the function.  For
1857    example, in
1858
1859      template <class T> struct S { void f(); };
1860      void S<int>::f();
1861
1862    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
1863    classes are not counted in the TEMPLATE_COUNT, so that in
1864
1865      template <class T> struct S {};
1866      template <> struct S<int> { void f(); }
1867      template <> void S<int>::f();
1868
1869    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
1870    invalid; there should be no template <>.)
1871
1872    If the function is a specialization, it is marked as such via
1873    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
1874    is set up correctly, and it is added to the list of specializations
1875    for that template.  */
1876
1877 tree
1878 check_explicit_specialization (tree declarator,
1879                                tree decl,
1880                                int template_count,
1881                                int flags)
1882 {
1883   int have_def = flags & 2;
1884   int is_friend = flags & 4;
1885   int specialization = 0;
1886   int explicit_instantiation = 0;
1887   int member_specialization = 0;
1888   tree ctype = DECL_CLASS_CONTEXT (decl);
1889   tree dname = DECL_NAME (decl);
1890   tmpl_spec_kind tsk;
1891
1892   if (is_friend)
1893     {
1894       if (!processing_specialization)
1895         tsk = tsk_none;
1896       else
1897         tsk = tsk_excessive_parms;
1898     }
1899   else
1900     tsk = current_tmpl_spec_kind (template_count);
1901
1902   switch (tsk)
1903     {
1904     case tsk_none:
1905       if (processing_specialization)
1906         {
1907           specialization = 1;
1908           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1909         }
1910       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1911         {
1912           if (is_friend)
1913             /* This could be something like:
1914
1915                template <class T> void f(T);
1916                class S { friend void f<>(int); }  */
1917             specialization = 1;
1918           else
1919             {
1920               /* This case handles bogus declarations like template <>
1921                  template <class T> void f<int>(); */
1922
1923               error ("template-id %qD in declaration of primary template",
1924                      declarator);
1925               return decl;
1926             }
1927         }
1928       break;
1929
1930     case tsk_invalid_member_spec:
1931       /* The error has already been reported in
1932          check_specialization_scope.  */
1933       return error_mark_node;
1934
1935     case tsk_invalid_expl_inst:
1936       error ("template parameter list used in explicit instantiation");
1937
1938       /* Fall through.  */
1939
1940     case tsk_expl_inst:
1941       if (have_def)
1942         error ("definition provided for explicit instantiation");
1943
1944       explicit_instantiation = 1;
1945       break;
1946
1947     case tsk_excessive_parms:
1948     case tsk_insufficient_parms:
1949       if (tsk == tsk_excessive_parms)
1950         error ("too many template parameter lists in declaration of %qD",
1951                decl);
1952       else if (template_header_count)
1953         error("too few template parameter lists in declaration of %qD", decl);
1954       else
1955         error("explicit specialization of %qD must be introduced by "
1956               "%<template <>%>", decl);
1957
1958       /* Fall through.  */
1959     case tsk_expl_spec:
1960       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1961       if (ctype)
1962         member_specialization = 1;
1963       else
1964         specialization = 1;
1965       break;
1966
1967     case tsk_template:
1968       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1969         {
1970           /* This case handles bogus declarations like template <>
1971              template <class T> void f<int>(); */
1972
1973           if (uses_template_parms (declarator))
1974             error ("function template partial specialization %qD "
1975                    "is not allowed", declarator);
1976           else
1977             error ("template-id %qD in declaration of primary template",
1978                    declarator);
1979           return decl;
1980         }
1981
1982       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
1983         /* This is a specialization of a member template, without
1984            specialization the containing class.  Something like:
1985
1986              template <class T> struct S {
1987                template <class U> void f (U);
1988              };
1989              template <> template <class U> void S<int>::f(U) {}
1990
1991            That's a specialization -- but of the entire template.  */
1992         specialization = 1;
1993       break;
1994
1995     default:
1996       gcc_unreachable ();
1997     }
1998
1999   if (specialization || member_specialization)
2000     {
2001       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2002       for (; t; t = TREE_CHAIN (t))
2003         if (TREE_PURPOSE (t))
2004           {
2005             permerror (input_location, 
2006                        "default argument specified in explicit specialization");
2007             break;
2008           }
2009     }
2010
2011   if (specialization || member_specialization || explicit_instantiation)
2012     {
2013       tree tmpl = NULL_TREE;
2014       tree targs = NULL_TREE;
2015
2016       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2017       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2018         {
2019           tree fns;
2020
2021           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2022           if (ctype)
2023             fns = dname;
2024           else
2025             {
2026               /* If there is no class context, the explicit instantiation
2027                  must be at namespace scope.  */
2028               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2029
2030               /* Find the namespace binding, using the declaration
2031                  context.  */
2032               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2033                                            false, true);
2034               if (fns == error_mark_node || !is_overloaded_fn (fns))
2035                 {
2036                   error ("%qD is not a template function", dname);
2037                   fns = error_mark_node;
2038                 }
2039               else
2040                 {
2041                   tree fn = OVL_CURRENT (fns);
2042                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2043                                                 CP_DECL_CONTEXT (fn)))
2044                     error ("%qD is not declared in %qD",
2045                            decl, current_namespace);
2046                 }
2047             }
2048
2049           declarator = lookup_template_function (fns, NULL_TREE);
2050         }
2051
2052       if (declarator == error_mark_node)
2053         return error_mark_node;
2054
2055       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2056         {
2057           if (!explicit_instantiation)
2058             /* A specialization in class scope.  This is invalid,
2059                but the error will already have been flagged by
2060                check_specialization_scope.  */
2061             return error_mark_node;
2062           else
2063             {
2064               /* It's not valid to write an explicit instantiation in
2065                  class scope, e.g.:
2066
2067                    class C { template void f(); }
2068
2069                    This case is caught by the parser.  However, on
2070                    something like:
2071
2072                    template class C { void f(); };
2073
2074                    (which is invalid) we can get here.  The error will be
2075                    issued later.  */
2076               ;
2077             }
2078
2079           return decl;
2080         }
2081       else if (ctype != NULL_TREE
2082                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2083                    IDENTIFIER_NODE))
2084         {
2085           /* Find the list of functions in ctype that have the same
2086              name as the declared function.  */
2087           tree name = TREE_OPERAND (declarator, 0);
2088           tree fns = NULL_TREE;
2089           int idx;
2090
2091           if (constructor_name_p (name, ctype))
2092             {
2093               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2094
2095               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2096                   : !CLASSTYPE_DESTRUCTORS (ctype))
2097                 {
2098                   /* From [temp.expl.spec]:
2099
2100                      If such an explicit specialization for the member
2101                      of a class template names an implicitly-declared
2102                      special member function (clause _special_), the
2103                      program is ill-formed.
2104
2105                      Similar language is found in [temp.explicit].  */
2106                   error ("specialization of implicitly-declared special member function");
2107                   return error_mark_node;
2108                 }
2109
2110               name = is_constructor ? ctor_identifier : dtor_identifier;
2111             }
2112
2113           if (!DECL_CONV_FN_P (decl))
2114             {
2115               idx = lookup_fnfields_1 (ctype, name);
2116               if (idx >= 0)
2117                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2118             }
2119           else
2120             {
2121               VEC(tree,gc) *methods;
2122               tree ovl;
2123
2124               /* For a type-conversion operator, we cannot do a
2125                  name-based lookup.  We might be looking for `operator
2126                  int' which will be a specialization of `operator T'.
2127                  So, we find *all* the conversion operators, and then
2128                  select from them.  */
2129               fns = NULL_TREE;
2130
2131               methods = CLASSTYPE_METHOD_VEC (ctype);
2132               if (methods)
2133                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2134                      VEC_iterate (tree, methods, idx, ovl);
2135                      ++idx)
2136                   {
2137                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2138                       /* There are no more conversion functions.  */
2139                       break;
2140
2141                     /* Glue all these conversion functions together
2142                        with those we already have.  */
2143                     for (; ovl; ovl = OVL_NEXT (ovl))
2144                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2145                   }
2146             }
2147
2148           if (fns == NULL_TREE)
2149             {
2150               error ("no member function %qD declared in %qT", name, ctype);
2151               return error_mark_node;
2152             }
2153           else
2154             TREE_OPERAND (declarator, 0) = fns;
2155         }
2156
2157       /* Figure out what exactly is being specialized at this point.
2158          Note that for an explicit instantiation, even one for a
2159          member function, we cannot tell apriori whether the
2160          instantiation is for a member template, or just a member
2161          function of a template class.  Even if a member template is
2162          being instantiated, the member template arguments may be
2163          elided if they can be deduced from the rest of the
2164          declaration.  */
2165       tmpl = determine_specialization (declarator, decl,
2166                                        &targs,
2167                                        member_specialization,
2168                                        template_count,
2169                                        tsk);
2170
2171       if (!tmpl || tmpl == error_mark_node)
2172         /* We couldn't figure out what this declaration was
2173            specializing.  */
2174         return error_mark_node;
2175       else
2176         {
2177           tree gen_tmpl = most_general_template (tmpl);
2178
2179           if (explicit_instantiation)
2180             {
2181               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2182                  is done by do_decl_instantiation later.  */
2183
2184               int arg_depth = TMPL_ARGS_DEPTH (targs);
2185               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2186
2187               if (arg_depth > parm_depth)
2188                 {
2189                   /* If TMPL is not the most general template (for
2190                      example, if TMPL is a friend template that is
2191                      injected into namespace scope), then there will
2192                      be too many levels of TARGS.  Remove some of them
2193                      here.  */
2194                   int i;
2195                   tree new_targs;
2196
2197                   new_targs = make_tree_vec (parm_depth);
2198                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2199                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2200                       = TREE_VEC_ELT (targs, i);
2201                   targs = new_targs;
2202                 }
2203
2204               return instantiate_template (tmpl, targs, tf_error);
2205             }
2206
2207           /* If we thought that the DECL was a member function, but it
2208              turns out to be specializing a static member function,
2209              make DECL a static member function as well.  */
2210           if (DECL_STATIC_FUNCTION_P (tmpl)
2211               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2212             revert_static_member_fn (decl);
2213
2214           /* If this is a specialization of a member template of a
2215              template class, we want to return the TEMPLATE_DECL, not
2216              the specialization of it.  */
2217           if (tsk == tsk_template)
2218             {
2219               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2220               DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl)) = NULL_TREE;
2221               if (have_def)
2222                 {
2223                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2224                   DECL_SOURCE_LOCATION (DECL_TEMPLATE_RESULT (tmpl))
2225                     = DECL_SOURCE_LOCATION (decl);
2226                   /* We want to use the argument list specified in the
2227                      definition, not in the original declaration.  */
2228                   DECL_ARGUMENTS (DECL_TEMPLATE_RESULT (tmpl))
2229                     = DECL_ARGUMENTS (decl);
2230                 }
2231               return tmpl;
2232             }
2233
2234           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2235           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2236
2237           /* Inherit default function arguments from the template
2238              DECL is specializing.  */
2239           copy_default_args_to_explicit_spec (decl);
2240
2241           /* This specialization has the same protection as the
2242              template it specializes.  */
2243           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2244           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2245
2246           /* 7.1.1-1 [dcl.stc]
2247
2248              A storage-class-specifier shall not be specified in an
2249              explicit specialization...
2250
2251              The parser rejects these, so unless action is taken here,
2252              explicit function specializations will always appear with
2253              global linkage.
2254
2255              The action recommended by the C++ CWG in response to C++
2256              defect report 605 is to make the storage class and linkage
2257              of the explicit specialization match the templated function:
2258
2259              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2260            */
2261           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2262             {
2263               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2264               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2265
2266               /* This specialization has the same linkage and visibility as
2267                  the function template it specializes.  */
2268               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2269               if (! TREE_PUBLIC (decl))
2270                 {
2271                   DECL_INTERFACE_KNOWN (decl) = 1;
2272                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2273                 }
2274               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2275               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2276                 {
2277                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2278                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2279                 }
2280             }
2281
2282           /* If DECL is a friend declaration, declared using an
2283              unqualified name, the namespace associated with DECL may
2284              have been set incorrectly.  For example, in:
2285
2286                template <typename T> void f(T);
2287                namespace N {
2288                  struct S { friend void f<int>(int); }
2289                }
2290
2291              we will have set the DECL_CONTEXT for the friend
2292              declaration to N, rather than to the global namespace.  */
2293           if (DECL_NAMESPACE_SCOPE_P (decl))
2294             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2295
2296           if (is_friend && !have_def)
2297             /* This is not really a declaration of a specialization.
2298                It's just the name of an instantiation.  But, it's not
2299                a request for an instantiation, either.  */
2300             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2301           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2302             /* This is indeed a specialization.  In case of constructors
2303                and destructors, we need in-charge and not-in-charge
2304                versions in V3 ABI.  */
2305             clone_function_decl (decl, /*update_method_vec_p=*/0);
2306
2307           /* Register this specialization so that we can find it
2308              again.  */
2309           decl = register_specialization (decl, gen_tmpl, targs, is_friend);
2310         }
2311     }
2312
2313   return decl;
2314 }
2315
2316 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2317    parameters.  These are represented in the same format used for
2318    DECL_TEMPLATE_PARMS.  */
2319
2320 int
2321 comp_template_parms (const_tree parms1, const_tree parms2)
2322 {
2323   const_tree p1;
2324   const_tree p2;
2325
2326   if (parms1 == parms2)
2327     return 1;
2328
2329   for (p1 = parms1, p2 = parms2;
2330        p1 != NULL_TREE && p2 != NULL_TREE;
2331        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2332     {
2333       tree t1 = TREE_VALUE (p1);
2334       tree t2 = TREE_VALUE (p2);
2335       int i;
2336
2337       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2338       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2339
2340       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2341         return 0;
2342
2343       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2344         {
2345           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2346           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2347
2348           /* If either of the template parameters are invalid, assume
2349              they match for the sake of error recovery. */
2350           if (parm1 == error_mark_node || parm2 == error_mark_node)
2351             return 1;
2352
2353           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2354             return 0;
2355
2356           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2357               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2358                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2359             continue;
2360           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2361             return 0;
2362         }
2363     }
2364
2365   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2366     /* One set of parameters has more parameters lists than the
2367        other.  */
2368     return 0;
2369
2370   return 1;
2371 }
2372
2373 /* Determine whether PARM is a parameter pack.  */
2374 bool 
2375 template_parameter_pack_p (const_tree parm)
2376 {
2377   /* Determine if we have a non-type template parameter pack.  */
2378   if (TREE_CODE (parm) == PARM_DECL)
2379     return (DECL_TEMPLATE_PARM_P (parm) 
2380             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2381
2382   /* If this is a list of template parameters, we could get a
2383      TYPE_DECL or a TEMPLATE_DECL.  */ 
2384   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2385     parm = TREE_TYPE (parm);
2386
2387   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2388            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2389           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2390 }
2391
2392 /* Determine whether ARGS describes a variadic template args list,
2393    i.e., one that is terminated by a template argument pack.  */
2394 static bool 
2395 template_args_variadic_p (tree args)
2396 {
2397   int nargs;
2398   tree last_parm;
2399
2400   if (args == NULL_TREE)
2401     return false;
2402
2403   args = INNERMOST_TEMPLATE_ARGS (args);
2404   nargs = TREE_VEC_LENGTH (args);
2405
2406   if (nargs == 0)
2407     return false;
2408
2409   last_parm = TREE_VEC_ELT (args, nargs - 1);
2410
2411   return ARGUMENT_PACK_P (last_parm);
2412 }
2413
2414 /* Generate a new name for the parameter pack name NAME (an
2415    IDENTIFIER_NODE) that incorporates its */
2416 static tree
2417 make_ith_pack_parameter_name (tree name, int i)
2418 {
2419   /* Munge the name to include the parameter index.  */
2420   char numbuf[128];
2421   char* newname;
2422   
2423   sprintf(numbuf, "%i", i);
2424   newname = (char*)alloca (IDENTIFIER_LENGTH (name) + strlen(numbuf) + 2);
2425   sprintf(newname, "%s#%i", IDENTIFIER_POINTER (name), i);
2426   return get_identifier (newname);
2427 }
2428
2429 /* Structure used to track the progress of find_parameter_packs_r.  */
2430 struct find_parameter_pack_data 
2431 {
2432   /* TREE_LIST that will contain all of the parameter packs found by
2433      the traversal.  */
2434   tree* parameter_packs;
2435
2436   /* Set of AST nodes that have been visited by the traversal.  */
2437   struct pointer_set_t *visited;
2438 };
2439
2440 /* Identifies all of the argument packs that occur in a template
2441    argument and appends them to the TREE_LIST inside DATA, which is a
2442    find_parameter_pack_data structure. This is a subroutine of
2443    make_pack_expansion and uses_parameter_packs.  */
2444 static tree
2445 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2446 {
2447   tree t = *tp;
2448   struct find_parameter_pack_data* ppd = 
2449     (struct find_parameter_pack_data*)data;
2450   bool parameter_pack_p = false;
2451
2452   /* Identify whether this is a parameter pack or not.  */
2453   switch (TREE_CODE (t))
2454     {
2455     case TEMPLATE_PARM_INDEX:
2456       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2457         parameter_pack_p = true;
2458       break;
2459
2460     case TEMPLATE_TYPE_PARM:
2461     case TEMPLATE_TEMPLATE_PARM:
2462       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2463         parameter_pack_p = true;
2464       break;
2465
2466     case PARM_DECL:
2467       if (FUNCTION_PARAMETER_PACK_P (t))
2468         {
2469           /* We don't want to walk into the type of a PARM_DECL,
2470              because we don't want to see the type parameter pack.  */
2471           *walk_subtrees = 0;
2472           parameter_pack_p = true;
2473         }
2474       break;
2475
2476     default:
2477       /* Not a parameter pack.  */
2478       break;
2479     }
2480
2481   if (parameter_pack_p)
2482     {
2483       /* Add this parameter pack to the list.  */
2484       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2485     }
2486
2487   if (TYPE_P (t))
2488     cp_walk_tree (&TYPE_CONTEXT (t), 
2489                   &find_parameter_packs_r, ppd, ppd->visited);
2490
2491   /* This switch statement will return immediately if we don't find a
2492      parameter pack.  */
2493   switch (TREE_CODE (t)) 
2494     {
2495     case TEMPLATE_PARM_INDEX:
2496       return NULL_TREE;
2497
2498     case BOUND_TEMPLATE_TEMPLATE_PARM:
2499       /* Check the template itself.  */
2500       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2501                     &find_parameter_packs_r, ppd, ppd->visited);
2502       /* Check the template arguments.  */
2503       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2504                     ppd->visited);
2505       *walk_subtrees = 0;
2506       return NULL_TREE;
2507
2508     case TEMPLATE_TYPE_PARM:
2509     case TEMPLATE_TEMPLATE_PARM:
2510       return NULL_TREE;
2511
2512     case PARM_DECL:
2513       return NULL_TREE;
2514
2515     case RECORD_TYPE:
2516       if (TYPE_PTRMEMFUNC_P (t))
2517         return NULL_TREE;
2518       /* Fall through.  */
2519
2520     case UNION_TYPE:
2521     case ENUMERAL_TYPE:
2522       if (TYPE_TEMPLATE_INFO (t))
2523         cp_walk_tree (&TREE_VALUE (TYPE_TEMPLATE_INFO (t)), 
2524                       &find_parameter_packs_r, ppd, ppd->visited);
2525
2526       *walk_subtrees = 0;
2527       return NULL_TREE;
2528
2529     case TEMPLATE_DECL:
2530       cp_walk_tree (&TREE_TYPE (t),
2531                     &find_parameter_packs_r, ppd, ppd->visited);
2532       return NULL_TREE;
2533  
2534     case TYPENAME_TYPE:
2535       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2536                    ppd, ppd->visited);
2537       *walk_subtrees = 0;
2538       return NULL_TREE;
2539       
2540     case TYPE_PACK_EXPANSION:
2541     case EXPR_PACK_EXPANSION:
2542       *walk_subtrees = 0;
2543       return NULL_TREE;
2544
2545     case INTEGER_TYPE:
2546       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2547                     ppd, ppd->visited);
2548       *walk_subtrees = 0;
2549       return NULL_TREE;
2550
2551     case IDENTIFIER_NODE:
2552       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2553                     ppd->visited);
2554       *walk_subtrees = 0;
2555       return NULL_TREE;
2556
2557     default:
2558       return NULL_TREE;
2559     }
2560
2561   return NULL_TREE;
2562 }
2563
2564 /* Determines if the expression or type T uses any parameter packs.  */
2565 bool
2566 uses_parameter_packs (tree t)
2567 {
2568   tree parameter_packs = NULL_TREE;
2569   struct find_parameter_pack_data ppd;
2570   ppd.parameter_packs = &parameter_packs;
2571   ppd.visited = pointer_set_create ();
2572   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2573   pointer_set_destroy (ppd.visited);
2574   return parameter_packs != NULL_TREE;
2575 }
2576
2577 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2578    representation a base-class initializer into a parameter pack
2579    expansion. If all goes well, the resulting node will be an
2580    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2581    respectively.  */
2582 tree 
2583 make_pack_expansion (tree arg)
2584 {
2585   tree result;
2586   tree parameter_packs = NULL_TREE;
2587   bool for_types = false;
2588   struct find_parameter_pack_data ppd;
2589
2590   if (!arg || arg == error_mark_node)
2591     return arg;
2592
2593   if (TREE_CODE (arg) == TREE_LIST)
2594     {
2595       /* The only time we will see a TREE_LIST here is for a base
2596          class initializer.  In this case, the TREE_PURPOSE will be a
2597          _TYPE node (representing the base class expansion we're
2598          initializing) and the TREE_VALUE will be a TREE_LIST
2599          containing the initialization arguments. 
2600
2601          The resulting expansion looks somewhat different from most
2602          expansions. Rather than returning just one _EXPANSION, we
2603          return a TREE_LIST whose TREE_PURPOSE is a
2604          TYPE_PACK_EXPANSION containing the bases that will be
2605          initialized.  The TREE_VALUE will be identical to the
2606          original TREE_VALUE, which is a list of arguments that will
2607          be passed to each base.  We do not introduce any new pack
2608          expansion nodes into the TREE_VALUE (although it is possible
2609          that some already exist), because the TREE_PURPOSE and
2610          TREE_VALUE all need to be expanded together with the same
2611          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2612          resulting TREE_PURPOSE will mention the parameter packs in
2613          both the bases and the arguments to the bases.  */
2614       tree purpose;
2615       tree value;
2616       tree parameter_packs = NULL_TREE;
2617
2618       /* Determine which parameter packs will be used by the base
2619          class expansion.  */
2620       ppd.visited = pointer_set_create ();
2621       ppd.parameter_packs = &parameter_packs;
2622       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
2623                     &ppd, ppd.visited);
2624
2625       if (parameter_packs == NULL_TREE)
2626         {
2627           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
2628           pointer_set_destroy (ppd.visited);
2629           return error_mark_node;
2630         }
2631
2632       if (TREE_VALUE (arg) != void_type_node)
2633         {
2634           /* Collect the sets of parameter packs used in each of the
2635              initialization arguments.  */
2636           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
2637             {
2638               /* Determine which parameter packs will be expanded in this
2639                  argument.  */
2640               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
2641                             &ppd, ppd.visited);
2642             }
2643         }
2644
2645       pointer_set_destroy (ppd.visited);
2646
2647       /* Create the pack expansion type for the base type.  */
2648       purpose = make_node (TYPE_PACK_EXPANSION);
2649       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
2650       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
2651
2652       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2653          they will rarely be compared to anything.  */
2654       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
2655
2656       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
2657     }
2658
2659   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
2660     for_types = true;
2661
2662   /* Build the PACK_EXPANSION_* node.  */
2663   result = make_node (for_types ? TYPE_PACK_EXPANSION : EXPR_PACK_EXPANSION);
2664   SET_PACK_EXPANSION_PATTERN (result, arg);
2665   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
2666     {
2667       /* Propagate type and const-expression information.  */
2668       TREE_TYPE (result) = TREE_TYPE (arg);
2669       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
2670     }
2671   else
2672     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2673        they will rarely be compared to anything.  */
2674     SET_TYPE_STRUCTURAL_EQUALITY (result);
2675
2676   /* Determine which parameter packs will be expanded.  */
2677   ppd.parameter_packs = &parameter_packs;
2678   ppd.visited = pointer_set_create ();
2679   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
2680   pointer_set_destroy (ppd.visited);
2681
2682   /* Make sure we found some parameter packs.  */
2683   if (parameter_packs == NULL_TREE)
2684     {
2685       if (TYPE_P (arg))
2686         error ("expansion pattern %<%T%> contains no argument packs", arg);
2687       else
2688         error ("expansion pattern %<%E%> contains no argument packs", arg);
2689       return error_mark_node;
2690     }
2691   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
2692
2693   return result;
2694 }
2695
2696 /* Checks T for any "bare" parameter packs, which have not yet been
2697    expanded, and issues an error if any are found. This operation can
2698    only be done on full expressions or types (e.g., an expression
2699    statement, "if" condition, etc.), because we could have expressions like:
2700
2701      foo(f(g(h(args)))...)
2702
2703    where "args" is a parameter pack. check_for_bare_parameter_packs
2704    should not be called for the subexpressions args, h(args),
2705    g(h(args)), or f(g(h(args))), because we would produce erroneous
2706    error messages. 
2707
2708    Returns TRUE and emits an error if there were bare parameter packs,
2709    returns FALSE otherwise.  */
2710 bool 
2711 check_for_bare_parameter_packs (tree t)
2712 {
2713   tree parameter_packs = NULL_TREE;
2714   struct find_parameter_pack_data ppd;
2715
2716   if (!processing_template_decl || !t || t == error_mark_node)
2717     return false;
2718
2719   if (TREE_CODE (t) == TYPE_DECL)
2720     t = TREE_TYPE (t);
2721
2722   ppd.parameter_packs = &parameter_packs;
2723   ppd.visited = pointer_set_create ();
2724   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2725   pointer_set_destroy (ppd.visited);
2726
2727   if (parameter_packs) 
2728     {
2729       error ("parameter packs not expanded with %<...%>:");
2730       while (parameter_packs)
2731         {
2732           tree pack = TREE_VALUE (parameter_packs);
2733           tree name = NULL_TREE;
2734
2735           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
2736               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
2737             name = TYPE_NAME (pack);
2738           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
2739             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
2740           else
2741             name = DECL_NAME (pack);
2742
2743           if (name)
2744             inform (input_location, "        %qD", name);
2745           else
2746             inform (input_location, "        <anonymous>");
2747
2748           parameter_packs = TREE_CHAIN (parameter_packs);
2749         }
2750
2751       return true;
2752     }
2753
2754   return false;
2755 }
2756
2757 /* Expand any parameter packs that occur in the template arguments in
2758    ARGS.  */
2759 tree
2760 expand_template_argument_pack (tree args)
2761 {
2762   tree result_args = NULL_TREE;
2763   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
2764   int num_result_args = -1;
2765
2766   /* First, determine if we need to expand anything, and the number of
2767      slots we'll need.  */
2768   for (in_arg = 0; in_arg < nargs; ++in_arg)
2769     {
2770       tree arg = TREE_VEC_ELT (args, in_arg);
2771       if (ARGUMENT_PACK_P (arg))
2772         {
2773           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
2774           if (num_result_args < 0)
2775             num_result_args = in_arg + num_packed;
2776           else
2777             num_result_args += num_packed;
2778         }
2779       else
2780         {
2781           if (num_result_args >= 0)
2782             num_result_args++;
2783         }
2784     }
2785
2786   /* If no expansion is necessary, we're done.  */
2787   if (num_result_args < 0)
2788     return args;
2789
2790   /* Expand arguments.  */
2791   result_args = make_tree_vec (num_result_args);
2792   for (in_arg = 0; in_arg < nargs; ++in_arg)
2793     {
2794       tree arg = TREE_VEC_ELT (args, in_arg);
2795       if (ARGUMENT_PACK_P (arg))
2796         {
2797           tree packed = ARGUMENT_PACK_ARGS (arg);
2798           int i, num_packed = TREE_VEC_LENGTH (packed);
2799           for (i = 0; i < num_packed; ++i, ++out_arg)
2800             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
2801         }
2802       else
2803         {
2804           TREE_VEC_ELT (result_args, out_arg) = arg;
2805           ++out_arg;
2806         }
2807     }
2808
2809   return result_args;
2810 }
2811
2812 /* Checks if DECL shadows a template parameter.
2813
2814    [temp.local]: A template-parameter shall not be redeclared within its
2815    scope (including nested scopes).
2816
2817    Emits an error and returns TRUE if the DECL shadows a parameter,
2818    returns FALSE otherwise.  */
2819
2820 bool
2821 check_template_shadow (tree decl)
2822 {
2823   tree olddecl;
2824
2825   /* If we're not in a template, we can't possibly shadow a template
2826      parameter.  */
2827   if (!current_template_parms)
2828     return true;
2829
2830   /* Figure out what we're shadowing.  */
2831   if (TREE_CODE (decl) == OVERLOAD)
2832     decl = OVL_CURRENT (decl);
2833   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
2834
2835   /* If there's no previous binding for this name, we're not shadowing
2836      anything, let alone a template parameter.  */
2837   if (!olddecl)
2838     return true;
2839
2840   /* If we're not shadowing a template parameter, we're done.  Note
2841      that OLDDECL might be an OVERLOAD (or perhaps even an
2842      ERROR_MARK), so we can't just blithely assume it to be a _DECL
2843      node.  */
2844   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
2845     return true;
2846
2847   /* We check for decl != olddecl to avoid bogus errors for using a
2848      name inside a class.  We check TPFI to avoid duplicate errors for
2849      inline member templates.  */
2850   if (decl == olddecl
2851       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
2852     return true;
2853
2854   error ("declaration of %q+#D", decl);
2855   error (" shadows template parm %q+#D", olddecl);
2856   return false;
2857 }
2858
2859 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
2860    ORIG_LEVEL, DECL, and TYPE.  */
2861
2862 static tree
2863 build_template_parm_index (int index,
2864                            int level,
2865                            int orig_level,
2866                            tree decl,
2867                            tree type)
2868 {
2869   tree t = make_node (TEMPLATE_PARM_INDEX);
2870   TEMPLATE_PARM_IDX (t) = index;
2871   TEMPLATE_PARM_LEVEL (t) = level;
2872   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
2873   TEMPLATE_PARM_DECL (t) = decl;
2874   TREE_TYPE (t) = type;
2875   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
2876   TREE_READONLY (t) = TREE_READONLY (decl);
2877
2878   return t;
2879 }
2880
2881 /* Find the canonical type parameter for the given template type
2882    parameter.  Returns the canonical type parameter, which may be TYPE
2883    if no such parameter existed.  */
2884 static tree
2885 canonical_type_parameter (tree type)
2886 {
2887   tree list;
2888   int idx = TEMPLATE_TYPE_IDX (type);
2889   if (!canonical_template_parms)
2890     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
2891
2892   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
2893     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
2894
2895   list = VEC_index (tree, canonical_template_parms, idx);
2896   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
2897     list = TREE_CHAIN (list);
2898
2899   if (list)
2900     return TREE_VALUE (list);
2901   else
2902     {
2903       VEC_replace(tree, canonical_template_parms, idx,
2904                   tree_cons (NULL_TREE, type, 
2905                              VEC_index (tree, canonical_template_parms, idx)));
2906       return type;
2907     }
2908 }
2909
2910 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
2911    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
2912    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
2913    new one is created.  */
2914
2915 static tree
2916 reduce_template_parm_level (tree index, tree type, int levels, tree args,
2917                             tsubst_flags_t complain)
2918 {
2919   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
2920       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
2921           != TEMPLATE_PARM_LEVEL (index) - levels))
2922     {
2923       tree orig_decl = TEMPLATE_PARM_DECL (index);
2924       tree decl, t;
2925
2926       decl = build_decl (TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
2927       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
2928       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
2929       DECL_ARTIFICIAL (decl) = 1;
2930       SET_DECL_TEMPLATE_PARM_P (decl);
2931
2932       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
2933                                      TEMPLATE_PARM_LEVEL (index) - levels,
2934                                      TEMPLATE_PARM_ORIG_LEVEL (index),
2935                                      decl, type);
2936       TEMPLATE_PARM_DESCENDANTS (index) = t;
2937       TEMPLATE_PARM_PARAMETER_PACK (t) 
2938         = TEMPLATE_PARM_PARAMETER_PACK (index);
2939
2940         /* Template template parameters need this.  */
2941       if (TREE_CODE (decl) == TEMPLATE_DECL)
2942         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
2943           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
2944            args, complain);
2945     }
2946
2947   return TEMPLATE_PARM_DESCENDANTS (index);
2948 }
2949
2950 /* Process information from new template parameter PARM and append it to the
2951    LIST being built.  This new parameter is a non-type parameter iff
2952    IS_NON_TYPE is true. This new parameter is a parameter
2953    pack iff IS_PARAMETER_PACK is true.  */
2954
2955 tree
2956 process_template_parm (tree list, tree parm, bool is_non_type, 
2957                        bool is_parameter_pack)
2958 {
2959   tree decl = 0;
2960   tree defval;
2961   tree err_parm_list;
2962   int idx = 0;
2963
2964   gcc_assert (TREE_CODE (parm) == TREE_LIST);
2965   defval = TREE_PURPOSE (parm);
2966
2967   if (list)
2968     {
2969       tree p = tree_last (list);
2970
2971       if (p && TREE_VALUE (p) != error_mark_node)
2972         {
2973           p = TREE_VALUE (p);
2974           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
2975             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
2976           else
2977             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
2978         }
2979
2980       ++idx;
2981     }
2982   else
2983     idx = 0;
2984
2985   if (is_non_type)
2986     {
2987       parm = TREE_VALUE (parm);
2988
2989       SET_DECL_TEMPLATE_PARM_P (parm);
2990
2991       if (TREE_TYPE (parm) == error_mark_node)
2992         {
2993           err_parm_list = build_tree_list (defval, parm);
2994           TREE_VALUE (err_parm_list) = error_mark_node;
2995            return chainon (list, err_parm_list);
2996         }
2997       else
2998       {
2999         /* [temp.param]
3000
3001            The top-level cv-qualifiers on the template-parameter are
3002            ignored when determining its type.  */
3003         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3004         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3005           {
3006             err_parm_list = build_tree_list (defval, parm);
3007             TREE_VALUE (err_parm_list) = error_mark_node;
3008              return chainon (list, err_parm_list);
3009           }
3010
3011         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3012           {
3013             /* This template parameter is not a parameter pack, but it
3014                should be. Complain about "bare" parameter packs.  */
3015             check_for_bare_parameter_packs (TREE_TYPE (parm));
3016             
3017             /* Recover by calling this a parameter pack.  */
3018             is_parameter_pack = true;
3019           }
3020       }
3021
3022       /* A template parameter is not modifiable.  */
3023       TREE_CONSTANT (parm) = 1;
3024       TREE_READONLY (parm) = 1;
3025       decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3026       TREE_CONSTANT (decl) = 1;
3027       TREE_READONLY (decl) = 1;
3028       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3029         = build_template_parm_index (idx, processing_template_decl,
3030                                      processing_template_decl,
3031                                      decl, TREE_TYPE (parm));
3032
3033       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3034         = is_parameter_pack;
3035     }
3036   else
3037     {
3038       tree t;
3039       parm = TREE_VALUE (TREE_VALUE (parm));
3040
3041       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3042         {
3043           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3044           /* This is for distinguishing between real templates and template
3045              template parameters */
3046           TREE_TYPE (parm) = t;
3047           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3048           decl = parm;
3049         }
3050       else
3051         {
3052           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3053           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3054           decl = build_decl (TYPE_DECL, parm, t);
3055         }
3056
3057       TYPE_NAME (t) = decl;
3058       TYPE_STUB_DECL (t) = decl;
3059       parm = decl;
3060       TEMPLATE_TYPE_PARM_INDEX (t)
3061         = build_template_parm_index (idx, processing_template_decl,
3062                                      processing_template_decl,
3063                                      decl, TREE_TYPE (parm));
3064       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3065       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3066     }
3067   DECL_ARTIFICIAL (decl) = 1;
3068   SET_DECL_TEMPLATE_PARM_P (decl);
3069   pushdecl (decl);
3070   parm = build_tree_list (defval, parm);
3071   return chainon (list, parm);
3072 }
3073
3074 /* The end of a template parameter list has been reached.  Process the
3075    tree list into a parameter vector, converting each parameter into a more
3076    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3077    as PARM_DECLs.  */
3078
3079 tree
3080 end_template_parm_list (tree parms)
3081 {
3082   int nparms;
3083   tree parm, next;
3084   tree saved_parmlist = make_tree_vec (list_length (parms));
3085
3086   current_template_parms
3087     = tree_cons (size_int (processing_template_decl),
3088                  saved_parmlist, current_template_parms);
3089
3090   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3091     {
3092       next = TREE_CHAIN (parm);
3093       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3094       TREE_CHAIN (parm) = NULL_TREE;
3095     }
3096
3097   --processing_template_parmlist;
3098
3099   return saved_parmlist;
3100 }
3101
3102 /* end_template_decl is called after a template declaration is seen.  */
3103
3104 void
3105 end_template_decl (void)
3106 {
3107   reset_specialization ();
3108
3109   if (! processing_template_decl)
3110     return;
3111
3112   /* This matches the pushlevel in begin_template_parm_list.  */
3113   finish_scope ();
3114
3115   --processing_template_decl;
3116   current_template_parms = TREE_CHAIN (current_template_parms);
3117 }
3118
3119 /* Within the declaration of a template, return all levels of template
3120    parameters that apply.  The template parameters are represented as
3121    a TREE_VEC, in the form documented in cp-tree.h for template
3122    arguments.  */
3123
3124 static tree
3125 current_template_args (void)
3126 {
3127   tree header;
3128   tree args = NULL_TREE;
3129   int length = TMPL_PARMS_DEPTH (current_template_parms);
3130   int l = length;
3131
3132   /* If there is only one level of template parameters, we do not
3133      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3134      TREE_VEC containing the arguments.  */
3135   if (length > 1)
3136     args = make_tree_vec (length);
3137
3138   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3139     {
3140       tree a = copy_node (TREE_VALUE (header));
3141       int i;
3142
3143       TREE_TYPE (a) = NULL_TREE;
3144       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3145         {
3146           tree t = TREE_VEC_ELT (a, i);
3147
3148           /* T will be a list if we are called from within a
3149              begin/end_template_parm_list pair, but a vector directly
3150              if within a begin/end_member_template_processing pair.  */
3151           if (TREE_CODE (t) == TREE_LIST)
3152             {
3153               t = TREE_VALUE (t);
3154
3155               if (!error_operand_p (t))
3156                 {
3157                   if (TREE_CODE (t) == TYPE_DECL
3158                       || TREE_CODE (t) == TEMPLATE_DECL)
3159                     {
3160                       t = TREE_TYPE (t);
3161                       
3162                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3163                         {
3164                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3165                              with a single element, which expands T.  */
3166                           tree vec = make_tree_vec (1);
3167                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3168                           
3169                           t = make_node (TYPE_ARGUMENT_PACK);
3170                           SET_ARGUMENT_PACK_ARGS (t, vec);
3171                         }
3172                     }
3173                   else
3174                     {
3175                       t = DECL_INITIAL (t);
3176                       
3177                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3178                         {
3179                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3180                              with a single element, which expands T.  */
3181                           tree vec = make_tree_vec (1);
3182                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3183                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3184                           
3185                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3186                           SET_ARGUMENT_PACK_ARGS (t, vec);
3187                           TREE_TYPE (t) = type;
3188                         }
3189                     }
3190                   TREE_VEC_ELT (a, i) = t;
3191                 }
3192             }
3193         }
3194
3195       if (length > 1)
3196         TREE_VEC_ELT (args, --l) = a;
3197       else
3198         args = a;
3199     }
3200
3201   return args;
3202 }
3203
3204 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3205    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3206    a member template.  Used by push_template_decl below.  */
3207
3208 static tree
3209 build_template_decl (tree decl, tree parms, bool member_template_p)
3210 {
3211   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3212   DECL_TEMPLATE_PARMS (tmpl) = parms;
3213   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3214   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3215   if (DECL_LANG_SPECIFIC (decl))
3216     {
3217       DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
3218       DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
3219       DECL_DESTRUCTOR_P (tmpl) = DECL_DESTRUCTOR_P (decl);
3220       DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
3221       DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
3222       if (DECL_OVERLOADED_OPERATOR_P (decl))
3223         SET_OVERLOADED_OPERATOR_CODE (tmpl,
3224                                       DECL_OVERLOADED_OPERATOR_P (decl));
3225     }
3226
3227   return tmpl;
3228 }
3229
3230 struct template_parm_data
3231 {
3232   /* The level of the template parameters we are currently
3233      processing.  */
3234   int level;
3235
3236   /* The index of the specialization argument we are currently
3237      processing.  */
3238   int current_arg;
3239
3240   /* An array whose size is the number of template parameters.  The
3241      elements are nonzero if the parameter has been used in any one
3242      of the arguments processed so far.  */
3243   int* parms;
3244
3245   /* An array whose size is the number of template arguments.  The
3246      elements are nonzero if the argument makes use of template
3247      parameters of this level.  */
3248   int* arg_uses_template_parms;
3249 };
3250
3251 /* Subroutine of push_template_decl used to see if each template
3252    parameter in a partial specialization is used in the explicit
3253    argument list.  If T is of the LEVEL given in DATA (which is
3254    treated as a template_parm_data*), then DATA->PARMS is marked
3255    appropriately.  */
3256
3257 static int
3258 mark_template_parm (tree t, void* data)
3259 {
3260   int level;
3261   int idx;
3262   struct template_parm_data* tpd = (struct template_parm_data*) data;
3263
3264   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3265     {
3266       level = TEMPLATE_PARM_LEVEL (t);
3267       idx = TEMPLATE_PARM_IDX (t);
3268     }
3269   else
3270     {
3271       level = TEMPLATE_TYPE_LEVEL (t);
3272       idx = TEMPLATE_TYPE_IDX (t);
3273     }
3274
3275   if (level == tpd->level)
3276     {
3277       tpd->parms[idx] = 1;
3278       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3279     }
3280
3281   /* Return zero so that for_each_template_parm will continue the
3282      traversal of the tree; we want to mark *every* template parm.  */
3283   return 0;
3284 }
3285
3286 /* Process the partial specialization DECL.  */
3287
3288 static tree
3289 process_partial_specialization (tree decl)
3290 {
3291   tree type = TREE_TYPE (decl);
3292   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3293   tree specargs = CLASSTYPE_TI_ARGS (type);
3294   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3295   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3296   tree inner_parms;
3297   int nargs = TREE_VEC_LENGTH (inner_args);
3298   int ntparms;
3299   int  i;
3300   int did_error_intro = 0;
3301   struct template_parm_data tpd;
3302   struct template_parm_data tpd2;
3303
3304   gcc_assert (current_template_parms);
3305
3306   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3307   ntparms = TREE_VEC_LENGTH (inner_parms);
3308
3309   /* We check that each of the template parameters given in the
3310      partial specialization is used in the argument list to the
3311      specialization.  For example:
3312
3313        template <class T> struct S;
3314        template <class T> struct S<T*>;
3315
3316      The second declaration is OK because `T*' uses the template
3317      parameter T, whereas
3318
3319        template <class T> struct S<int>;
3320
3321      is no good.  Even trickier is:
3322
3323        template <class T>
3324        struct S1
3325        {
3326           template <class U>
3327           struct S2;
3328           template <class U>
3329           struct S2<T>;
3330        };
3331
3332      The S2<T> declaration is actually invalid; it is a
3333      full-specialization.  Of course,
3334
3335           template <class U>
3336           struct S2<T (*)(U)>;
3337
3338      or some such would have been OK.  */
3339   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3340   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3341   memset (tpd.parms, 0, sizeof (int) * ntparms);
3342
3343   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3344   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3345   for (i = 0; i < nargs; ++i)
3346     {
3347       tpd.current_arg = i;
3348       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3349                               &mark_template_parm,
3350                               &tpd,
3351                               NULL,
3352                               /*include_nondeduced_p=*/false);
3353     }
3354   for (i = 0; i < ntparms; ++i)
3355     if (tpd.parms[i] == 0)
3356       {
3357         /* One of the template parms was not used in the
3358            specialization.  */
3359         if (!did_error_intro)
3360           {
3361             error ("template parameters not used in partial specialization:");
3362             did_error_intro = 1;
3363           }
3364
3365         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3366       }
3367
3368   /* [temp.class.spec]
3369
3370      The argument list of the specialization shall not be identical to
3371      the implicit argument list of the primary template.  */
3372   if (comp_template_args
3373       (inner_args,
3374        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3375                                                    (maintmpl)))))
3376     error ("partial specialization %qT does not specialize any template arguments", type);
3377
3378   /* [temp.class.spec]
3379
3380      A partially specialized non-type argument expression shall not
3381      involve template parameters of the partial specialization except
3382      when the argument expression is a simple identifier.
3383
3384      The type of a template parameter corresponding to a specialized
3385      non-type argument shall not be dependent on a parameter of the
3386      specialization. 
3387
3388      Also, we verify that pack expansions only occur at the
3389      end of the argument list.  */
3390   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3391   tpd2.parms = 0;
3392   for (i = 0; i < nargs; ++i)
3393     {
3394       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3395       tree arg = TREE_VEC_ELT (inner_args, i);
3396       tree packed_args = NULL_TREE;
3397       int j, len = 1;
3398
3399       if (ARGUMENT_PACK_P (arg))
3400         {
3401           /* Extract the arguments from the argument pack. We'll be
3402              iterating over these in the following loop.  */
3403           packed_args = ARGUMENT_PACK_ARGS (arg);
3404           len = TREE_VEC_LENGTH (packed_args);
3405         }
3406
3407       for (j = 0; j < len; j++)
3408         {
3409           if (packed_args)
3410             /* Get the Jth argument in the parameter pack.  */
3411             arg = TREE_VEC_ELT (packed_args, j);
3412
3413           if (PACK_EXPANSION_P (arg))
3414             {
3415               /* Pack expansions must come at the end of the
3416                  argument list.  */
3417               if ((packed_args && j < len - 1)
3418                   || (!packed_args && i < nargs - 1))
3419                 {
3420                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3421                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3422                   else
3423                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3424
3425                   if (packed_args)
3426                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3427                 }
3428             }
3429
3430           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3431             /* We only care about the pattern.  */
3432             arg = PACK_EXPANSION_PATTERN (arg);
3433
3434           if (/* These first two lines are the `non-type' bit.  */
3435               !TYPE_P (arg)
3436               && TREE_CODE (arg) != TEMPLATE_DECL
3437               /* This next line is the `argument expression is not just a
3438                  simple identifier' condition and also the `specialized
3439                  non-type argument' bit.  */
3440               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3441             {
3442               if ((!packed_args && tpd.arg_uses_template_parms[i])
3443                   || (packed_args && uses_template_parms (arg)))
3444                 error ("template argument %qE involves template parameter(s)",
3445                        arg);
3446               else 
3447                 {
3448                   /* Look at the corresponding template parameter,
3449                      marking which template parameters its type depends
3450                      upon.  */
3451                   tree type = TREE_TYPE (parm);
3452
3453                   if (!tpd2.parms)
3454                     {
3455                       /* We haven't yet initialized TPD2.  Do so now.  */
3456                       tpd2.arg_uses_template_parms 
3457                         = (int *) alloca (sizeof (int) * nargs);
3458                       /* The number of parameters here is the number in the
3459                          main template, which, as checked in the assertion
3460                          above, is NARGS.  */
3461                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3462                       tpd2.level = 
3463                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3464                     }
3465
3466                   /* Mark the template parameters.  But this time, we're
3467                      looking for the template parameters of the main
3468                      template, not in the specialization.  */
3469                   tpd2.current_arg = i;
3470                   tpd2.arg_uses_template_parms[i] = 0;
3471                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3472                   for_each_template_parm (type,
3473                                           &mark_template_parm,
3474                                           &tpd2,
3475                                           NULL,
3476                                           /*include_nondeduced_p=*/false);
3477
3478                   if (tpd2.arg_uses_template_parms [i])
3479                     {
3480                       /* The type depended on some template parameters.
3481                          If they are fully specialized in the
3482                          specialization, that's OK.  */
3483                       int j;
3484                       for (j = 0; j < nargs; ++j)
3485                         if (tpd2.parms[j] != 0
3486                             && tpd.arg_uses_template_parms [j])
3487                           {
3488                             error ("type %qT of template argument %qE depends "
3489                                    "on template parameter(s)", 
3490                                    type,
3491                                    arg);
3492                             break;
3493                           }
3494                     }
3495                 }
3496             }
3497         }
3498     }
3499
3500   if (retrieve_specialization (maintmpl, specargs,
3501                                /*class_specializations_p=*/true))
3502     /* We've already got this specialization.  */
3503     return decl;
3504
3505   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3506     = tree_cons (specargs, inner_parms,
3507                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3508   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3509   return decl;
3510 }
3511
3512 /* Check that a template declaration's use of default arguments and
3513    parameter packs is not invalid.  Here, PARMS are the template
3514    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3515    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3516    specialization.
3517    
3518
3519    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3520    declaration (but not a definition); 1 indicates a declaration, 2
3521    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3522    emitted for extraneous default arguments.
3523
3524    Returns TRUE if there were no errors found, FALSE otherwise. */
3525
3526 bool
3527 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3528                          int is_partial, int is_friend_decl)
3529 {
3530   const char *msg;
3531   int last_level_to_check;
3532   tree parm_level;
3533   bool no_errors = true;
3534
3535   /* [temp.param]
3536
3537      A default template-argument shall not be specified in a
3538      function template declaration or a function template definition, nor
3539      in the template-parameter-list of the definition of a member of a
3540      class template.  */
3541
3542   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3543     /* You can't have a function template declaration in a local
3544        scope, nor you can you define a member of a class template in a
3545        local scope.  */
3546     return true;
3547
3548   if (current_class_type
3549       && !TYPE_BEING_DEFINED (current_class_type)
3550       && DECL_LANG_SPECIFIC (decl)
3551       /* If this is either a friend defined in the scope of the class
3552          or a member function.  */
3553       && (DECL_FUNCTION_MEMBER_P (decl)
3554           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3555           : DECL_FRIEND_CONTEXT (decl)
3556           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3557           : false)
3558       /* And, if it was a member function, it really was defined in
3559          the scope of the class.  */
3560       && (!DECL_FUNCTION_MEMBER_P (decl)
3561           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3562     /* We already checked these parameters when the template was
3563        declared, so there's no need to do it again now.  This function
3564        was defined in class scope, but we're processing it's body now
3565        that the class is complete.  */
3566     return true;
3567
3568   /* Core issue 226 (C++0x only): the following only applies to class
3569      templates.  */
3570   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3571     {
3572       /* [temp.param]
3573
3574          If a template-parameter has a default template-argument, all
3575          subsequent template-parameters shall have a default
3576          template-argument supplied.  */
3577       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3578         {
3579           tree inner_parms = TREE_VALUE (parm_level);
3580           int ntparms = TREE_VEC_LENGTH (inner_parms);
3581           int seen_def_arg_p = 0;
3582           int i;
3583
3584           for (i = 0; i < ntparms; ++i)
3585             {
3586               tree parm = TREE_VEC_ELT (inner_parms, i);
3587
3588               if (parm == error_mark_node)
3589                 continue;
3590
3591               if (TREE_PURPOSE (parm))
3592                 seen_def_arg_p = 1;
3593               else if (seen_def_arg_p)
3594                 {
3595                   error ("no default argument for %qD", TREE_VALUE (parm));
3596                   /* For better subsequent error-recovery, we indicate that
3597                      there should have been a default argument.  */
3598                   TREE_PURPOSE (parm) = error_mark_node;
3599                   no_errors = false;
3600                 }
3601               else if (is_primary
3602                        && !is_partial
3603                        && !is_friend_decl
3604                        && TREE_CODE (decl) == TYPE_DECL
3605                        && i < ntparms - 1
3606                        && template_parameter_pack_p (TREE_VALUE (parm)))
3607                 {
3608                   /* A primary class template can only have one
3609                      parameter pack, at the end of the template
3610                      parameter list.  */
3611
3612                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
3613                     error ("parameter pack %qE must be at the end of the"
3614                            " template parameter list", TREE_VALUE (parm));
3615                   else
3616                     error ("parameter pack %qT must be at the end of the"
3617                            " template parameter list", 
3618                            TREE_TYPE (TREE_VALUE (parm)));
3619
3620                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
3621                     = error_mark_node;
3622                   no_errors = false;
3623                 }
3624             }
3625         }
3626     }
3627
3628   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
3629       || is_partial 
3630       || !is_primary
3631       || is_friend_decl)
3632     /* For an ordinary class template, default template arguments are
3633        allowed at the innermost level, e.g.:
3634          template <class T = int>
3635          struct S {};
3636        but, in a partial specialization, they're not allowed even
3637        there, as we have in [temp.class.spec]:
3638
3639          The template parameter list of a specialization shall not
3640          contain default template argument values.
3641
3642        So, for a partial specialization, or for a function template
3643        (in C++98/C++03), we look at all of them.  */
3644     ;
3645   else
3646     /* But, for a primary class template that is not a partial
3647        specialization we look at all template parameters except the
3648        innermost ones.  */
3649     parms = TREE_CHAIN (parms);
3650
3651   /* Figure out what error message to issue.  */
3652   if (is_friend_decl == 2)
3653     msg = "default template arguments may not be used in function template friend re-declaration";
3654   else if (is_friend_decl)
3655     msg = "default template arguments may not be used in function template friend declarations";
3656   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
3657     msg = "default template arguments may not be used in function templates";
3658   else if (is_partial)
3659     msg = "default template arguments may not be used in partial specializations";
3660   else
3661     msg = "default argument for template parameter for class enclosing %qD";
3662
3663   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
3664     /* If we're inside a class definition, there's no need to
3665        examine the parameters to the class itself.  On the one
3666        hand, they will be checked when the class is defined, and,
3667        on the other, default arguments are valid in things like:
3668          template <class T = double>
3669          struct S { template <class U> void f(U); };
3670        Here the default argument for `S' has no bearing on the
3671        declaration of `f'.  */
3672     last_level_to_check = template_class_depth (current_class_type) + 1;
3673   else
3674     /* Check everything.  */
3675     last_level_to_check = 0;
3676
3677   for (parm_level = parms;
3678        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
3679        parm_level = TREE_CHAIN (parm_level))
3680     {
3681       tree inner_parms = TREE_VALUE (parm_level);
3682       int i;
3683       int ntparms;
3684
3685       ntparms = TREE_VEC_LENGTH (inner_parms);
3686       for (i = 0; i < ntparms; ++i)
3687         {
3688           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
3689             continue;
3690
3691           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
3692             {
3693               if (msg)
3694                 {
3695                   no_errors = false;
3696                   if (is_friend_decl == 2)
3697                     return no_errors;
3698
3699                   error (msg, decl);
3700                   msg = 0;
3701                 }
3702
3703               /* Clear out the default argument so that we are not
3704                  confused later.  */
3705               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
3706             }
3707         }
3708
3709       /* At this point, if we're still interested in issuing messages,
3710          they must apply to classes surrounding the object declared.  */
3711       if (msg)
3712         msg = "default argument for template parameter for class enclosing %qD";
3713     }
3714
3715   return no_errors;
3716 }
3717
3718 /* Worker for push_template_decl_real, called via
3719    for_each_template_parm.  DATA is really an int, indicating the
3720    level of the parameters we are interested in.  If T is a template
3721    parameter of that level, return nonzero.  */
3722
3723 static int
3724 template_parm_this_level_p (tree t, void* data)
3725 {
3726   int this_level = *(int *)data;
3727   int level;
3728
3729   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3730     level = TEMPLATE_PARM_LEVEL (t);
3731   else
3732     level = TEMPLATE_TYPE_LEVEL (t);
3733   return level == this_level;
3734 }
3735
3736 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
3737    parameters given by current_template_args, or reuses a
3738    previously existing one, if appropriate.  Returns the DECL, or an
3739    equivalent one, if it is replaced via a call to duplicate_decls.
3740
3741    If IS_FRIEND is true, DECL is a friend declaration.  */
3742
3743 tree
3744 push_template_decl_real (tree decl, bool is_friend)
3745 {
3746   tree tmpl;
3747   tree args;
3748   tree info;
3749   tree ctx;
3750   int primary;
3751   int is_partial;
3752   int new_template_p = 0;
3753   /* True if the template is a member template, in the sense of
3754      [temp.mem].  */
3755   bool member_template_p = false;
3756
3757   if (decl == error_mark_node || !current_template_parms)
3758     return error_mark_node;
3759
3760   /* See if this is a partial specialization.  */
3761   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
3762                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3763                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
3764
3765   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
3766     is_friend = true;
3767
3768   if (is_friend)
3769     /* For a friend, we want the context of the friend function, not
3770        the type of which it is a friend.  */
3771     ctx = DECL_CONTEXT (decl);
3772   else if (CP_DECL_CONTEXT (decl)
3773            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
3774     /* In the case of a virtual function, we want the class in which
3775        it is defined.  */
3776     ctx = CP_DECL_CONTEXT (decl);
3777   else
3778     /* Otherwise, if we're currently defining some class, the DECL
3779        is assumed to be a member of the class.  */
3780     ctx = current_scope ();
3781
3782   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
3783     ctx = NULL_TREE;
3784
3785   if (!DECL_CONTEXT (decl))
3786     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
3787
3788   /* See if this is a primary template.  */
3789   if (is_friend && ctx)
3790     /* A friend template that specifies a class context, i.e.
3791          template <typename T> friend void A<T>::f();
3792        is not primary.  */
3793     primary = 0;
3794   else
3795     primary = template_parm_scope_p ();
3796
3797   if (primary)
3798     {
3799       if (DECL_CLASS_SCOPE_P (decl))
3800         member_template_p = true;
3801       if (TREE_CODE (decl) == TYPE_DECL
3802           && ANON_AGGRNAME_P (DECL_NAME (decl)))
3803         {
3804           error ("template class without a name");
3805           return error_mark_node;
3806         }
3807       else if (TREE_CODE (decl) == FUNCTION_DECL)
3808         {
3809           if (DECL_DESTRUCTOR_P (decl))
3810             {
3811               /* [temp.mem]
3812
3813                  A destructor shall not be a member template.  */
3814               error ("destructor %qD declared as member template", decl);
3815               return error_mark_node;
3816             }
3817           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
3818               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
3819                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
3820                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
3821                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
3822                       == void_list_node)))
3823             {
3824               /* [basic.stc.dynamic.allocation]
3825
3826                  An allocation function can be a function
3827                  template. ... Template allocation functions shall
3828                  have two or more parameters.  */
3829               error ("invalid template declaration of %qD", decl);
3830               return error_mark_node;
3831             }
3832         }
3833       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3834                && CLASS_TYPE_P (TREE_TYPE (decl)))
3835         /* OK */;
3836       else
3837         {
3838           error ("template declaration of %q#D", decl);
3839           return error_mark_node;
3840         }
3841     }
3842
3843   /* Check to see that the rules regarding the use of default
3844      arguments are not being violated.  */
3845   check_default_tmpl_args (decl, current_template_parms,
3846                            primary, is_partial, /*is_friend_decl=*/0);
3847
3848   /* Ensure that there are no parameter packs in the type of this
3849      declaration that have not been expanded.  */
3850   if (TREE_CODE (decl) == FUNCTION_DECL)
3851     {
3852       /* Check each of the arguments individually to see if there are
3853          any bare parameter packs.  */
3854       tree type = TREE_TYPE (decl);
3855       tree arg = DECL_ARGUMENTS (decl);
3856       tree argtype = TYPE_ARG_TYPES (type);
3857
3858       while (arg && argtype)
3859         {
3860           if (!FUNCTION_PARAMETER_PACK_P (arg)
3861               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
3862             {
3863             /* This is a PARM_DECL that contains unexpanded parameter
3864                packs. We have already complained about this in the
3865                check_for_bare_parameter_packs call, so just replace
3866                these types with ERROR_MARK_NODE.  */
3867               TREE_TYPE (arg) = error_mark_node;
3868               TREE_VALUE (argtype) = error_mark_node;
3869             }
3870
3871           arg = TREE_CHAIN (arg);
3872           argtype = TREE_CHAIN (argtype);
3873         }
3874
3875       /* Check for bare parameter packs in the return type and the
3876          exception specifiers.  */
3877       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
3878         /* Errors were already issued, set return type to int
3879            as the frontend doesn't expect error_mark_node as
3880            the return type.  */
3881         TREE_TYPE (type) = integer_type_node;
3882       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
3883         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
3884     }
3885   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
3886     {
3887       TREE_TYPE (decl) = error_mark_node;
3888       return error_mark_node;
3889     }
3890
3891   if (is_partial)
3892     return process_partial_specialization (decl);
3893
3894   args = current_template_args ();
3895
3896   if (!ctx
3897       || TREE_CODE (ctx) == FUNCTION_DECL
3898       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
3899       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
3900     {
3901       if (DECL_LANG_SPECIFIC (decl)
3902           && DECL_TEMPLATE_INFO (decl)
3903           && DECL_TI_TEMPLATE (decl))
3904         tmpl = DECL_TI_TEMPLATE (decl);
3905       /* If DECL is a TYPE_DECL for a class-template, then there won't
3906          be DECL_LANG_SPECIFIC.  The information equivalent to
3907          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
3908       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3909                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3910                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3911         {
3912           /* Since a template declaration already existed for this
3913              class-type, we must be redeclaring it here.  Make sure
3914              that the redeclaration is valid.  */
3915           redeclare_class_template (TREE_TYPE (decl),
3916                                     current_template_parms);
3917           /* We don't need to create a new TEMPLATE_DECL; just use the
3918              one we already had.  */
3919           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3920         }
3921       else
3922         {
3923           tmpl = build_template_decl (decl, current_template_parms,
3924                                       member_template_p);
3925           new_template_p = 1;
3926
3927           if (DECL_LANG_SPECIFIC (decl)
3928               && DECL_TEMPLATE_SPECIALIZATION (decl))
3929             {
3930               /* A specialization of a member template of a template
3931                  class.  */
3932               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3933               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
3934               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
3935             }
3936         }
3937     }
3938   else
3939     {
3940       tree a, t, current, parms;
3941       int i;
3942       tree tinfo = get_template_info (decl);
3943
3944       if (!tinfo)
3945         {
3946           error ("template definition of non-template %q#D", decl);
3947           return error_mark_node;
3948         }
3949
3950       tmpl = TI_TEMPLATE (tinfo);
3951
3952       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3953           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
3954           && DECL_TEMPLATE_SPECIALIZATION (decl)
3955           && DECL_MEMBER_TEMPLATE_P (tmpl))
3956         {
3957           tree new_tmpl;
3958
3959           /* The declaration is a specialization of a member
3960              template, declared outside the class.  Therefore, the
3961              innermost template arguments will be NULL, so we
3962              replace them with the arguments determined by the
3963              earlier call to check_explicit_specialization.  */
3964           args = DECL_TI_ARGS (decl);
3965
3966           new_tmpl
3967             = build_template_decl (decl, current_template_parms,
3968                                    member_template_p);
3969           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
3970           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
3971           DECL_TI_TEMPLATE (decl) = new_tmpl;
3972           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
3973           DECL_TEMPLATE_INFO (new_tmpl)
3974             = tree_cons (tmpl, args, NULL_TREE);
3975
3976           register_specialization (new_tmpl,
3977                                    most_general_template (tmpl),
3978                                    args,
3979                                    is_friend);
3980           return decl;
3981         }
3982
3983       /* Make sure the template headers we got make sense.  */
3984
3985       parms = DECL_TEMPLATE_PARMS (tmpl);
3986       i = TMPL_PARMS_DEPTH (parms);
3987       if (TMPL_ARGS_DEPTH (args) != i)
3988         {
3989           error ("expected %d levels of template parms for %q#D, got %d",
3990                  i, decl, TMPL_ARGS_DEPTH (args));
3991         }
3992       else
3993         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
3994           {
3995             a = TMPL_ARGS_LEVEL (args, i);
3996             t = INNERMOST_TEMPLATE_PARMS (parms);
3997
3998             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
3999               {
4000                 if (current == decl)
4001                   error ("got %d template parameters for %q#D",
4002                          TREE_VEC_LENGTH (a), decl);
4003                 else
4004                   error ("got %d template parameters for %q#T",
4005                          TREE_VEC_LENGTH (a), current);
4006                 error ("  but %d required", TREE_VEC_LENGTH (t));
4007                 return error_mark_node;
4008               }
4009
4010             if (current == decl)
4011               current = ctx;
4012             else
4013               current = (TYPE_P (current)
4014                          ? TYPE_CONTEXT (current)
4015                          : DECL_CONTEXT (current));
4016           }
4017
4018       /* Check that the parms are used in the appropriate qualifying scopes
4019          in the declarator.  */
4020       if (!comp_template_args
4021           (TI_ARGS (tinfo),
4022            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4023         {
4024           error ("\
4025 template arguments to %qD do not match original template %qD",
4026                  decl, DECL_TEMPLATE_RESULT (tmpl));
4027           if (!uses_template_parms (TI_ARGS (tinfo)))
4028             inform (input_location, "use template<> for an explicit specialization");
4029           /* Avoid crash in import_export_decl.  */
4030           DECL_INTERFACE_KNOWN (decl) = 1;
4031           return error_mark_node;
4032         }
4033     }
4034
4035   DECL_TEMPLATE_RESULT (tmpl) = decl;
4036   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4037
4038   /* Push template declarations for global functions and types.  Note
4039      that we do not try to push a global template friend declared in a
4040      template class; such a thing may well depend on the template
4041      parameters of the class.  */
4042   if (new_template_p && !ctx
4043       && !(is_friend && template_class_depth (current_class_type) > 0))
4044     {
4045       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4046       if (tmpl == error_mark_node)
4047         return error_mark_node;
4048
4049       /* Hide template friend classes that haven't been declared yet.  */
4050       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4051         {
4052           DECL_ANTICIPATED (tmpl) = 1;
4053           DECL_FRIEND_P (tmpl) = 1;
4054         }
4055     }
4056
4057   if (primary)
4058     {
4059       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4060       int i;
4061
4062       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4063       if (DECL_CONV_FN_P (tmpl))
4064         {
4065           int depth = TMPL_PARMS_DEPTH (parms);
4066
4067           /* It is a conversion operator. See if the type converted to
4068              depends on innermost template operands.  */
4069
4070           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4071                                          depth))
4072             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4073         }
4074
4075       /* Give template template parms a DECL_CONTEXT of the template
4076          for which they are a parameter.  */
4077       parms = INNERMOST_TEMPLATE_PARMS (parms);
4078       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4079         {
4080           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4081           if (TREE_CODE (parm) == TEMPLATE_DECL)
4082             DECL_CONTEXT (parm) = tmpl;
4083         }
4084     }
4085
4086   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4087      back to its most general template.  If TMPL is a specialization,
4088      ARGS may only have the innermost set of arguments.  Add the missing
4089      argument levels if necessary.  */
4090   if (DECL_TEMPLATE_INFO (tmpl))
4091     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4092
4093   info = tree_cons (tmpl, args, NULL_TREE);
4094
4095   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4096     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4097   else if (DECL_LANG_SPECIFIC (decl))
4098     DECL_TEMPLATE_INFO (decl) = info;
4099
4100   return DECL_TEMPLATE_RESULT (tmpl);
4101 }
4102
4103 tree
4104 push_template_decl (tree decl)
4105 {
4106   return push_template_decl_real (decl, false);
4107 }
4108
4109 /* Called when a class template TYPE is redeclared with the indicated
4110    template PARMS, e.g.:
4111
4112      template <class T> struct S;
4113      template <class T> struct S {};  */
4114
4115 bool
4116 redeclare_class_template (tree type, tree parms)
4117 {
4118   tree tmpl;
4119   tree tmpl_parms;
4120   int i;
4121
4122   if (!TYPE_TEMPLATE_INFO (type))
4123     {
4124       error ("%qT is not a template type", type);
4125       return false;
4126     }
4127
4128   tmpl = TYPE_TI_TEMPLATE (type);
4129   if (!PRIMARY_TEMPLATE_P (tmpl))
4130     /* The type is nested in some template class.  Nothing to worry
4131        about here; there are no new template parameters for the nested
4132        type.  */
4133     return true;
4134
4135   if (!parms)
4136     {
4137       error ("template specifiers not specified in declaration of %qD",
4138              tmpl);
4139       return false;
4140     }
4141
4142   parms = INNERMOST_TEMPLATE_PARMS (parms);
4143   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4144
4145   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4146     {
4147       error ("redeclared with %d template parameter(s)", 
4148              TREE_VEC_LENGTH (parms));
4149       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4150              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4151       return false;
4152     }
4153
4154   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4155     {
4156       tree tmpl_parm;
4157       tree parm;
4158       tree tmpl_default;
4159       tree parm_default;
4160
4161       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4162           || TREE_VEC_ELT (parms, i) == error_mark_node)
4163         continue;
4164
4165       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4166       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4167       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4168       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4169
4170       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4171          TEMPLATE_DECL.  */
4172       if (tmpl_parm != error_mark_node
4173           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4174               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4175                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4176               || (TREE_CODE (tmpl_parm) != PARM_DECL
4177                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4178                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4179               || (TREE_CODE (tmpl_parm) == PARM_DECL
4180                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4181                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4182         {
4183           error ("template parameter %q+#D", tmpl_parm);
4184           error ("redeclared here as %q#D", parm);
4185           return false;
4186         }
4187
4188       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4189         {
4190           /* We have in [temp.param]:
4191
4192              A template-parameter may not be given default arguments
4193              by two different declarations in the same scope.  */
4194           error ("redefinition of default argument for %q#D", parm);
4195           inform (input_location, "%Joriginal definition appeared here", tmpl_parm);
4196           return false;
4197         }
4198
4199       if (parm_default != NULL_TREE)
4200         /* Update the previous template parameters (which are the ones
4201            that will really count) with the new default value.  */
4202         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4203       else if (tmpl_default != NULL_TREE)
4204         /* Update the new parameters, too; they'll be used as the
4205            parameters for any members.  */
4206         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4207     }
4208
4209     return true;
4210 }
4211
4212 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4213    (possibly simplified) expression.  */
4214
4215 tree
4216 fold_non_dependent_expr (tree expr)
4217 {
4218   if (expr == NULL_TREE)
4219     return NULL_TREE;
4220
4221   /* If we're in a template, but EXPR isn't value dependent, simplify
4222      it.  We're supposed to treat:
4223
4224        template <typename T> void f(T[1 + 1]);
4225        template <typename T> void f(T[2]);
4226
4227      as two declarations of the same function, for example.  */
4228   if (processing_template_decl
4229       && !type_dependent_expression_p (expr)
4230       && !value_dependent_expression_p (expr))
4231     {
4232       HOST_WIDE_INT saved_processing_template_decl;
4233
4234       saved_processing_template_decl = processing_template_decl;
4235       processing_template_decl = 0;
4236       expr = tsubst_copy_and_build (expr,
4237                                     /*args=*/NULL_TREE,
4238                                     tf_error,
4239                                     /*in_decl=*/NULL_TREE,
4240                                     /*function_p=*/false,
4241                                     /*integral_constant_expression_p=*/true);
4242       processing_template_decl = saved_processing_template_decl;
4243     }
4244   return expr;
4245 }
4246
4247 /* EXPR is an expression which is used in a constant-expression context.
4248    For instance, it could be a VAR_DECL with a constant initializer.
4249    Extract the innermost constant expression.
4250
4251    This is basically a more powerful version of
4252    integral_constant_value, which can be used also in templates where
4253    initializers can maintain a syntactic rather than semantic form
4254    (even if they are non-dependent, for access-checking purposes).  */
4255
4256 static tree
4257 fold_decl_constant_value (tree expr)
4258 {
4259   tree const_expr = expr;
4260   do
4261     {
4262       expr = fold_non_dependent_expr (const_expr);
4263       const_expr = integral_constant_value (expr);
4264     }
4265   while (expr != const_expr);
4266
4267   return expr;
4268 }
4269
4270 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4271    must be a function or a pointer-to-function type, as specified
4272    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4273    and check that the resulting function has external linkage.  */
4274
4275 static tree
4276 convert_nontype_argument_function (tree type, tree expr)
4277 {
4278   tree fns = expr;
4279   tree fn, fn_no_ptr;
4280
4281   fn = instantiate_type (type, fns, tf_none);
4282   if (fn == error_mark_node)
4283     return error_mark_node;
4284
4285   fn_no_ptr = fn;
4286   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4287     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4288   if (TREE_CODE (fn_no_ptr) == BASELINK)
4289     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4290  
4291   /* [temp.arg.nontype]/1
4292
4293      A template-argument for a non-type, non-template template-parameter
4294      shall be one of:
4295      [...]
4296      -- the address of an object or function with external linkage.  */
4297   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4298     {
4299       error ("%qE is not a valid template argument for type %qT "
4300              "because function %qD has not external linkage",
4301              expr, type, fn_no_ptr);
4302       return NULL_TREE;
4303     }
4304
4305   return fn;
4306 }
4307
4308 /* Attempt to convert the non-type template parameter EXPR to the
4309    indicated TYPE.  If the conversion is successful, return the
4310    converted value.  If the conversion is unsuccessful, return
4311    NULL_TREE if we issued an error message, or error_mark_node if we
4312    did not.  We issue error messages for out-and-out bad template
4313    parameters, but not simply because the conversion failed, since we
4314    might be just trying to do argument deduction.  Both TYPE and EXPR
4315    must be non-dependent.
4316
4317    The conversion follows the special rules described in
4318    [temp.arg.nontype], and it is much more strict than an implicit
4319    conversion.
4320
4321    This function is called twice for each template argument (see
4322    lookup_template_class for a more accurate description of this
4323    problem). This means that we need to handle expressions which
4324    are not valid in a C++ source, but can be created from the
4325    first call (for instance, casts to perform conversions). These
4326    hacks can go away after we fix the double coercion problem.  */
4327
4328 static tree
4329 convert_nontype_argument (tree type, tree expr)
4330 {
4331   tree expr_type;
4332
4333   /* Detect immediately string literals as invalid non-type argument.
4334      This special-case is not needed for correctness (we would easily
4335      catch this later), but only to provide better diagnostic for this
4336      common user mistake. As suggested by DR 100, we do not mention
4337      linkage issues in the diagnostic as this is not the point.  */
4338   if (TREE_CODE (expr) == STRING_CST)
4339     {
4340       error ("%qE is not a valid template argument for type %qT "
4341              "because string literals can never be used in this context",
4342              expr, type);
4343       return NULL_TREE;
4344     }
4345
4346   /* If we are in a template, EXPR may be non-dependent, but still
4347      have a syntactic, rather than semantic, form.  For example, EXPR
4348      might be a SCOPE_REF, rather than the VAR_DECL to which the
4349      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4350      so that access checking can be performed when the template is
4351      instantiated -- but here we need the resolved form so that we can
4352      convert the argument.  */
4353   expr = fold_non_dependent_expr (expr);
4354   if (error_operand_p (expr))
4355     return error_mark_node;
4356   expr_type = TREE_TYPE (expr);
4357
4358   /* HACK: Due to double coercion, we can get a
4359      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4360      which is the tree that we built on the first call (see
4361      below when coercing to reference to object or to reference to
4362      function). We just strip everything and get to the arg.
4363      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4364      for examples.  */
4365   if (TREE_CODE (expr) == NOP_EXPR)
4366     {
4367       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4368         {
4369           /* ??? Maybe we could use convert_from_reference here, but we
4370              would need to relax its constraints because the NOP_EXPR
4371              could actually change the type to something more cv-qualified,
4372              and this is not folded by convert_from_reference.  */
4373           tree addr = TREE_OPERAND (expr, 0);
4374           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4375           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4376           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4377           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4378                       (TREE_TYPE (expr_type),
4379                        TREE_TYPE (TREE_TYPE (addr))));
4380
4381           expr = TREE_OPERAND (addr, 0);
4382           expr_type = TREE_TYPE (expr);
4383         }
4384
4385       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4386          parameter is a pointer to object, through decay and
4387          qualification conversion. Let's strip everything.  */
4388       else if (TYPE_PTROBV_P (type))
4389         {
4390           STRIP_NOPS (expr);
4391           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4392           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4393           /* Skip the ADDR_EXPR only if it is part of the decay for
4394              an array. Otherwise, it is part of the original argument
4395              in the source code.  */
4396           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4397             expr = TREE_OPERAND (expr, 0);
4398           expr_type = TREE_TYPE (expr);
4399         }
4400     }
4401
4402   /* [temp.arg.nontype]/5, bullet 1
4403
4404      For a non-type template-parameter of integral or enumeration type,
4405      integral promotions (_conv.prom_) and integral conversions
4406      (_conv.integral_) are applied.  */
4407   if (INTEGRAL_TYPE_P (type))
4408     {
4409       if (!INTEGRAL_TYPE_P (expr_type))
4410         return error_mark_node;
4411
4412       expr = fold_decl_constant_value (expr);
4413       /* Notice that there are constant expressions like '4 % 0' which
4414          do not fold into integer constants.  */
4415       if (TREE_CODE (expr) != INTEGER_CST)
4416         {
4417           error ("%qE is not a valid template argument for type %qT "
4418                  "because it is a non-constant expression", expr, type);
4419           return NULL_TREE;
4420         }
4421
4422       /* At this point, an implicit conversion does what we want,
4423          because we already know that the expression is of integral
4424          type.  */
4425       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4426       if (expr == error_mark_node)
4427         return error_mark_node;
4428
4429       /* Conversion was allowed: fold it to a bare integer constant.  */
4430       expr = fold (expr);
4431     }
4432   /* [temp.arg.nontype]/5, bullet 2
4433
4434      For a non-type template-parameter of type pointer to object,
4435      qualification conversions (_conv.qual_) and the array-to-pointer
4436      conversion (_conv.array_) are applied.  */
4437   else if (TYPE_PTROBV_P (type))
4438     {
4439       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4440
4441          A template-argument for a non-type, non-template template-parameter
4442          shall be one of: [...]
4443
4444          -- the name of a non-type template-parameter;
4445          -- the address of an object or function with external linkage, [...]
4446             expressed as "& id-expression" where the & is optional if the name
4447             refers to a function or array, or if the corresponding
4448             template-parameter is a reference.
4449
4450         Here, we do not care about functions, as they are invalid anyway
4451         for a parameter of type pointer-to-object.  */
4452
4453       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4454         /* Non-type template parameters are OK.  */
4455         ;
4456       else if (TREE_CODE (expr) != ADDR_EXPR
4457                && TREE_CODE (expr_type) != ARRAY_TYPE)
4458         {
4459           if (TREE_CODE (expr) == VAR_DECL)
4460             {
4461               error ("%qD is not a valid template argument "
4462                      "because %qD is a variable, not the address of "
4463                      "a variable",
4464                      expr, expr);
4465               return NULL_TREE;
4466             }
4467           /* Other values, like integer constants, might be valid
4468              non-type arguments of some other type.  */
4469           return error_mark_node;
4470         }
4471       else
4472         {
4473           tree decl;
4474
4475           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4476                   ? TREE_OPERAND (expr, 0) : expr);
4477           if (TREE_CODE (decl) != VAR_DECL)
4478             {
4479               error ("%qE is not a valid template argument of type %qT "
4480                      "because %qE is not a variable",
4481                      expr, type, decl);
4482               return NULL_TREE;
4483             }
4484           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4485             {
4486               error ("%qE is not a valid template argument of type %qT "
4487                      "because %qD does not have external linkage",
4488                      expr, type, decl);
4489               return NULL_TREE;
4490             }
4491         }
4492
4493       expr = decay_conversion (expr);
4494       if (expr == error_mark_node)
4495         return error_mark_node;
4496
4497       expr = perform_qualification_conversions (type, expr);
4498       if (expr == error_mark_node)
4499         return error_mark_node;
4500     }
4501   /* [temp.arg.nontype]/5, bullet 3
4502
4503      For a non-type template-parameter of type reference to object, no
4504      conversions apply. The type referred to by the reference may be more
4505      cv-qualified than the (otherwise identical) type of the
4506      template-argument. The template-parameter is bound directly to the
4507      template-argument, which must be an lvalue.  */
4508   else if (TYPE_REF_OBJ_P (type))
4509     {
4510       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4511                                                       expr_type))
4512         return error_mark_node;
4513
4514       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4515         {
4516           error ("%qE is not a valid template argument for type %qT "
4517                  "because of conflicts in cv-qualification", expr, type);
4518           return NULL_TREE;
4519         }
4520
4521       if (!real_lvalue_p (expr))
4522         {
4523           error ("%qE is not a valid template argument for type %qT "
4524                  "because it is not an lvalue", expr, type);
4525           return NULL_TREE;
4526         }
4527
4528       /* [temp.arg.nontype]/1
4529
4530          A template-argument for a non-type, non-template template-parameter
4531          shall be one of: [...]
4532
4533          -- the address of an object or function with external linkage.  */
4534       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4535         {
4536           error ("%qE is not a valid template argument for type %qT "
4537                  "because object %qD has not external linkage",
4538                  expr, type, expr);
4539           return NULL_TREE;
4540         }
4541
4542       expr = build_nop (type, build_address (expr));
4543     }
4544   /* [temp.arg.nontype]/5, bullet 4
4545
4546      For a non-type template-parameter of type pointer to function, only
4547      the function-to-pointer conversion (_conv.func_) is applied. If the
4548      template-argument represents a set of overloaded functions (or a
4549      pointer to such), the matching function is selected from the set
4550      (_over.over_).  */
4551   else if (TYPE_PTRFN_P (type))
4552     {
4553       /* If the argument is a template-id, we might not have enough
4554          context information to decay the pointer.  */
4555       if (!type_unknown_p (expr_type))
4556         {
4557           expr = decay_conversion (expr);
4558           if (expr == error_mark_node)
4559             return error_mark_node;
4560         }
4561
4562       expr = convert_nontype_argument_function (type, expr);
4563       if (!expr || expr == error_mark_node)
4564         return expr;
4565     }
4566   /* [temp.arg.nontype]/5, bullet 5
4567
4568      For a non-type template-parameter of type reference to function, no
4569      conversions apply. If the template-argument represents a set of
4570      overloaded functions, the matching function is selected from the set
4571      (_over.over_).  */
4572   else if (TYPE_REFFN_P (type))
4573     {
4574       if (TREE_CODE (expr) == ADDR_EXPR)
4575         {
4576           error ("%qE is not a valid template argument for type %qT "
4577                  "because it is a pointer", expr, type);
4578           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
4579           return NULL_TREE;
4580         }
4581
4582       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4583       if (!expr || expr == error_mark_node)
4584         return expr;
4585
4586       expr = build_nop (type, build_address (expr));
4587     }
4588   /* [temp.arg.nontype]/5, bullet 6
4589
4590      For a non-type template-parameter of type pointer to member function,
4591      no conversions apply. If the template-argument represents a set of
4592      overloaded member functions, the matching member function is selected
4593      from the set (_over.over_).  */
4594   else if (TYPE_PTRMEMFUNC_P (type))
4595     {
4596       expr = instantiate_type (type, expr, tf_none);
4597       if (expr == error_mark_node)
4598         return error_mark_node;
4599
4600       /* There is no way to disable standard conversions in
4601          resolve_address_of_overloaded_function (called by
4602          instantiate_type). It is possible that the call succeeded by
4603          converting &B::I to &D::I (where B is a base of D), so we need
4604          to reject this conversion here.
4605
4606          Actually, even if there was a way to disable standard conversions,
4607          it would still be better to reject them here so that we can
4608          provide a superior diagnostic.  */
4609       if (!same_type_p (TREE_TYPE (expr), type))
4610         {
4611           /* Make sure we are just one standard conversion off.  */
4612           gcc_assert (can_convert (type, TREE_TYPE (expr)));
4613           error ("%qE is not a valid template argument for type %qT "
4614                  "because it is of type %qT", expr, type,
4615                  TREE_TYPE (expr));
4616           inform (input_location, "standard conversions are not allowed in this context");
4617           return NULL_TREE;
4618         }
4619     }
4620   /* [temp.arg.nontype]/5, bullet 7
4621
4622      For a non-type template-parameter of type pointer to data member,
4623      qualification conversions (_conv.qual_) are applied.  */
4624   else if (TYPE_PTRMEM_P (type))
4625     {
4626       expr = perform_qualification_conversions (type, expr);
4627       if (expr == error_mark_node)
4628         return expr;
4629     }
4630   /* A template non-type parameter must be one of the above.  */
4631   else
4632     gcc_unreachable ();
4633
4634   /* Sanity check: did we actually convert the argument to the
4635      right type?  */
4636   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
4637   return expr;
4638 }
4639
4640 /* Subroutine of coerce_template_template_parms, which returns 1 if
4641    PARM_PARM and ARG_PARM match using the rule for the template
4642    parameters of template template parameters. Both PARM and ARG are
4643    template parameters; the rest of the arguments are the same as for
4644    coerce_template_template_parms.
4645  */
4646 static int
4647 coerce_template_template_parm (tree parm,
4648                               tree arg,
4649                               tsubst_flags_t complain,
4650                               tree in_decl,
4651                               tree outer_args)
4652 {
4653   if (arg == NULL_TREE || arg == error_mark_node
4654       || parm == NULL_TREE || parm == error_mark_node)
4655     return 0;
4656   
4657   if (TREE_CODE (arg) != TREE_CODE (parm))
4658     return 0;
4659   
4660   switch (TREE_CODE (parm))
4661     {
4662     case TEMPLATE_DECL:
4663       /* We encounter instantiations of templates like
4664          template <template <template <class> class> class TT>
4665          class C;  */
4666       {
4667         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4668         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4669         
4670         if (!coerce_template_template_parms
4671             (parmparm, argparm, complain, in_decl, outer_args))
4672           return 0;
4673       }
4674       /* Fall through.  */
4675       
4676     case TYPE_DECL:
4677       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
4678           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4679         /* Argument is a parameter pack but parameter is not.  */
4680         return 0;
4681       break;
4682       
4683     case PARM_DECL:
4684       /* The tsubst call is used to handle cases such as
4685          
4686            template <int> class C {};
4687            template <class T, template <T> class TT> class D {};
4688            D<int, C> d;
4689
4690          i.e. the parameter list of TT depends on earlier parameters.  */
4691       if (!dependent_type_p (TREE_TYPE (arg))
4692           && !same_type_p
4693                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
4694                  TREE_TYPE (arg)))
4695         return 0;
4696       
4697       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
4698           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4699         /* Argument is a parameter pack but parameter is not.  */
4700         return 0;
4701       
4702       break;
4703
4704     default:
4705       gcc_unreachable ();
4706     }
4707
4708   return 1;
4709 }
4710
4711
4712 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
4713    template template parameters.  Both PARM_PARMS and ARG_PARMS are
4714    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
4715    or PARM_DECL.
4716
4717    Consider the example:
4718      template <class T> class A;
4719      template<template <class U> class TT> class B;
4720
4721    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
4722    the parameters to A, and OUTER_ARGS contains A.  */
4723
4724 static int
4725 coerce_template_template_parms (tree parm_parms,
4726                                 tree arg_parms,
4727                                 tsubst_flags_t complain,
4728                                 tree in_decl,
4729                                 tree outer_args)
4730 {
4731   int nparms, nargs, i;
4732   tree parm, arg;
4733   int variadic_p = 0;
4734
4735   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
4736   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
4737
4738   nparms = TREE_VEC_LENGTH (parm_parms);
4739   nargs = TREE_VEC_LENGTH (arg_parms);
4740
4741   /* Determine whether we have a parameter pack at the end of the
4742      template template parameter's template parameter list.  */
4743   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
4744     {
4745       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
4746       
4747       switch (TREE_CODE (parm))
4748         {
4749         case TEMPLATE_DECL:
4750         case TYPE_DECL:
4751           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4752             variadic_p = 1;
4753           break;
4754           
4755         case PARM_DECL:
4756           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4757             variadic_p = 1;
4758           break;
4759           
4760         default:
4761           gcc_unreachable ();
4762         }
4763     }
4764  
4765   if (nargs != nparms
4766       && !(variadic_p && nargs >= nparms - 1))
4767     return 0;
4768
4769   /* Check all of the template parameters except the parameter pack at
4770      the end (if any).  */
4771   for (i = 0; i < nparms - variadic_p; ++i)
4772     {
4773       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
4774           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4775         continue;
4776
4777       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4778       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4779
4780       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4781                                           outer_args))
4782         return 0;
4783
4784     }
4785
4786   if (variadic_p)
4787     {
4788       /* Check each of the template parameters in the template
4789          argument against the template parameter pack at the end of
4790          the template template parameter.  */
4791       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
4792         return 0;
4793
4794       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4795
4796       for (; i < nargs; ++i)
4797         {
4798           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4799             continue;
4800  
4801           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4802  
4803           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4804                                               outer_args))
4805             return 0;
4806         }
4807     }
4808
4809   return 1;
4810 }
4811
4812 /* Verifies that the deduced template arguments (in TARGS) for the
4813    template template parameters (in TPARMS) represent valid bindings,
4814    by comparing the template parameter list of each template argument
4815    to the template parameter list of its corresponding template
4816    template parameter, in accordance with DR150. This
4817    routine can only be called after all template arguments have been
4818    deduced. It will return TRUE if all of the template template
4819    parameter bindings are okay, FALSE otherwise.  */
4820 bool 
4821 template_template_parm_bindings_ok_p (tree tparms, tree targs)
4822 {
4823   int i, ntparms = TREE_VEC_LENGTH (tparms);
4824   bool ret = true;
4825
4826   /* We're dealing with template parms in this process.  */
4827   ++processing_template_decl;
4828
4829   targs = INNERMOST_TEMPLATE_ARGS (targs);
4830
4831   for (i = 0; i < ntparms; ++i)
4832     {
4833       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
4834       tree targ = TREE_VEC_ELT (targs, i);
4835
4836       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
4837         {
4838           tree packed_args = NULL_TREE;
4839           int idx, len = 1;
4840
4841           if (ARGUMENT_PACK_P (targ))
4842             {
4843               /* Look inside the argument pack.  */
4844               packed_args = ARGUMENT_PACK_ARGS (targ);
4845               len = TREE_VEC_LENGTH (packed_args);
4846             }
4847
4848           for (idx = 0; idx < len; ++idx)
4849             {
4850               tree targ_parms = NULL_TREE;
4851
4852               if (packed_args)
4853                 /* Extract the next argument from the argument
4854                    pack.  */
4855                 targ = TREE_VEC_ELT (packed_args, idx);
4856
4857               if (PACK_EXPANSION_P (targ))
4858                 /* Look at the pattern of the pack expansion.  */
4859                 targ = PACK_EXPANSION_PATTERN (targ);
4860
4861               /* Extract the template parameters from the template
4862                  argument.  */
4863               if (TREE_CODE (targ) == TEMPLATE_DECL)
4864                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
4865               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
4866                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
4867
4868               /* Verify that we can coerce the template template
4869                  parameters from the template argument to the template
4870                  parameter.  This requires an exact match.  */
4871               if (targ_parms
4872                   && !coerce_template_template_parms
4873                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
4874                         targ_parms,
4875                         tf_none,
4876                         tparm,
4877                         targs))
4878                 {
4879                   ret = false;
4880                   goto out;
4881                 }
4882             }
4883         }
4884     }
4885
4886  out:
4887
4888   --processing_template_decl;
4889   return ret;
4890 }
4891
4892 /* Convert the indicated template ARG as necessary to match the
4893    indicated template PARM.  Returns the converted ARG, or
4894    error_mark_node if the conversion was unsuccessful.  Error and
4895    warning messages are issued under control of COMPLAIN.  This
4896    conversion is for the Ith parameter in the parameter list.  ARGS is
4897    the full set of template arguments deduced so far.  */
4898
4899 static tree
4900 convert_template_argument (tree parm,
4901                            tree arg,
4902                            tree args,
4903                            tsubst_flags_t complain,
4904                            int i,
4905                            tree in_decl)
4906 {
4907   tree orig_arg;
4908   tree val;
4909   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
4910
4911   if (TREE_CODE (arg) == TREE_LIST
4912       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
4913     {
4914       /* The template argument was the name of some
4915          member function.  That's usually
4916          invalid, but static members are OK.  In any
4917          case, grab the underlying fields/functions
4918          and issue an error later if required.  */
4919       orig_arg = TREE_VALUE (arg);
4920       TREE_TYPE (arg) = unknown_type_node;
4921     }
4922
4923   orig_arg = arg;
4924
4925   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
4926   requires_type = (TREE_CODE (parm) == TYPE_DECL
4927                    || requires_tmpl_type);
4928
4929   /* When determining whether an argument pack expansion is a template,
4930      look at the pattern.  */
4931   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
4932     arg = PACK_EXPANSION_PATTERN (arg);
4933
4934   is_tmpl_type = 
4935     ((TREE_CODE (arg) == TEMPLATE_DECL
4936       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
4937      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4938      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
4939
4940   if (is_tmpl_type
4941       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4942           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
4943     arg = TYPE_STUB_DECL (arg);
4944
4945   is_type = TYPE_P (arg) || is_tmpl_type;
4946
4947   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
4948       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
4949     {
4950       permerror (input_location, "to refer to a type member of a template parameter, "
4951                  "use %<typename %E%>", orig_arg);
4952
4953       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
4954                                      TREE_OPERAND (arg, 1),
4955                                      typename_type,
4956                                      complain & tf_error);
4957       arg = orig_arg;
4958       is_type = 1;
4959     }
4960   if (is_type != requires_type)
4961     {
4962       if (in_decl)
4963         {
4964           if (complain & tf_error)
4965             {
4966               error ("type/value mismatch at argument %d in template "
4967                      "parameter list for %qD",
4968                      i + 1, in_decl);
4969               if (is_type)
4970                 error ("  expected a constant of type %qT, got %qT",
4971                        TREE_TYPE (parm),
4972                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
4973               else if (requires_tmpl_type)
4974                 error ("  expected a class template, got %qE", orig_arg);
4975               else
4976                 error ("  expected a type, got %qE", orig_arg);
4977             }
4978         }
4979       return error_mark_node;
4980     }
4981   if (is_tmpl_type ^ requires_tmpl_type)
4982     {
4983       if (in_decl && (complain & tf_error))
4984         {
4985           error ("type/value mismatch at argument %d in template "
4986                  "parameter list for %qD",
4987                  i + 1, in_decl);
4988           if (is_tmpl_type)
4989             error ("  expected a type, got %qT", DECL_NAME (arg));
4990           else
4991             error ("  expected a class template, got %qT", orig_arg);
4992         }
4993       return error_mark_node;
4994     }
4995
4996   if (is_type)
4997     {
4998       if (requires_tmpl_type)
4999         {
5000           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5001             /* The number of argument required is not known yet.
5002                Just accept it for now.  */
5003             val = TREE_TYPE (arg);
5004           else
5005             {
5006               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5007               tree argparm;
5008
5009               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5010
5011               if (coerce_template_template_parms (parmparm, argparm,
5012                                                   complain, in_decl,
5013                                                   args))
5014                 {
5015                   val = orig_arg;
5016
5017                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5018                      TEMPLATE_DECL.  */
5019                   if (val != error_mark_node)
5020                     {
5021                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5022                         val = TREE_TYPE (val);
5023                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
5024                                && DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
5025                         {
5026                           val = TREE_TYPE (arg);
5027                           val = make_pack_expansion (val);
5028                         }
5029                     }
5030                 }
5031               else
5032                 {
5033                   if (in_decl && (complain & tf_error))
5034                     {
5035                       error ("type/value mismatch at argument %d in "
5036                              "template parameter list for %qD",
5037                              i + 1, in_decl);
5038                       error ("  expected a template of type %qD, got %qD",
5039                              parm, orig_arg);
5040                     }
5041
5042                   val = error_mark_node;
5043                 }
5044             }
5045         }
5046       else
5047         val = orig_arg;
5048       /* We only form one instance of each template specialization.
5049          Therefore, if we use a non-canonical variant (i.e., a
5050          typedef), any future messages referring to the type will use
5051          the typedef, which is confusing if those future uses do not
5052          themselves also use the typedef.  */
5053       if (TYPE_P (val))
5054         val = canonical_type_variant (val);
5055     }
5056   else
5057     {
5058       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5059
5060       if (invalid_nontype_parm_type_p (t, complain))
5061         return error_mark_node;
5062
5063       if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5064         /* We used to call digest_init here.  However, digest_init
5065            will report errors, which we don't want when complain
5066            is zero.  More importantly, digest_init will try too
5067            hard to convert things: for example, `0' should not be
5068            converted to pointer type at this point according to
5069            the standard.  Accepting this is not merely an
5070            extension, since deciding whether or not these
5071            conversions can occur is part of determining which
5072            function template to call, or whether a given explicit
5073            argument specification is valid.  */
5074         val = convert_nontype_argument (t, orig_arg);
5075       else
5076         val = orig_arg;
5077
5078       if (val == NULL_TREE)
5079         val = error_mark_node;
5080       else if (val == error_mark_node && (complain & tf_error))
5081         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5082     }
5083
5084   return val;
5085 }
5086
5087 /* Coerces the remaining template arguments in INNER_ARGS (from
5088    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5089    Returns the coerced argument pack. PARM_IDX is the position of this
5090    parameter in the template parameter list. ARGS is the original
5091    template argument list.  */
5092 static tree
5093 coerce_template_parameter_pack (tree parms,
5094                                 int parm_idx,
5095                                 tree args,
5096                                 tree inner_args,
5097                                 int arg_idx,
5098                                 tree new_args,
5099                                 int* lost,
5100                                 tree in_decl,
5101                                 tsubst_flags_t complain)
5102 {
5103   tree parm = TREE_VEC_ELT (parms, parm_idx);
5104   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5105   tree packed_args;
5106   tree argument_pack;
5107   tree packed_types = NULL_TREE;
5108
5109   if (arg_idx > nargs)
5110     arg_idx = nargs;
5111
5112   packed_args = make_tree_vec (nargs - arg_idx);
5113
5114   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5115       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5116     {
5117       /* When the template parameter is a non-type template
5118          parameter pack whose type uses parameter packs, we need
5119          to look at each of the template arguments
5120          separately. Build a vector of the types for these
5121          non-type template parameters in PACKED_TYPES.  */
5122       tree expansion 
5123         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5124       packed_types = tsubst_pack_expansion (expansion, args,
5125                                             complain, in_decl);
5126
5127       if (packed_types == error_mark_node)
5128         return error_mark_node;
5129
5130       /* Check that we have the right number of arguments.  */
5131       if (arg_idx < nargs
5132           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5133           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5134         {
5135           int needed_parms 
5136             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5137           error ("wrong number of template arguments (%d, should be %d)",
5138                  nargs, needed_parms);
5139           return error_mark_node;
5140         }
5141
5142       /* If we aren't able to check the actual arguments now
5143          (because they haven't been expanded yet), we can at least
5144          verify that all of the types used for the non-type
5145          template parameter pack are, in fact, valid for non-type
5146          template parameters.  */
5147       if (arg_idx < nargs 
5148           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5149         {
5150           int j, len = TREE_VEC_LENGTH (packed_types);
5151           for (j = 0; j < len; ++j)
5152             {
5153               tree t = TREE_VEC_ELT (packed_types, j);
5154               if (invalid_nontype_parm_type_p (t, complain))
5155                 return error_mark_node;
5156             }
5157         }
5158     }
5159
5160   /* Convert the remaining arguments, which will be a part of the
5161      parameter pack "parm".  */
5162   for (; arg_idx < nargs; ++arg_idx)
5163     {
5164       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5165       tree actual_parm = TREE_VALUE (parm);
5166
5167       if (packed_types && !PACK_EXPANSION_P (arg))
5168         {
5169           /* When we have a vector of types (corresponding to the
5170              non-type template parameter pack that uses parameter
5171              packs in its type, as mention above), and the
5172              argument is not an expansion (which expands to a
5173              currently unknown number of arguments), clone the
5174              parm and give it the next type in PACKED_TYPES.  */
5175           actual_parm = copy_node (actual_parm);
5176           TREE_TYPE (actual_parm) = 
5177             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5178         }
5179
5180       if (arg != error_mark_node)
5181         arg = convert_template_argument (actual_parm, 
5182                                          arg, new_args, complain, parm_idx,
5183                                          in_decl);
5184       if (arg == error_mark_node)
5185         (*lost)++;
5186       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5187     }
5188
5189   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5190       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5191     argument_pack = make_node (TYPE_ARGUMENT_PACK);
5192   else
5193     {
5194       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5195       TREE_TYPE (argument_pack) 
5196         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5197       TREE_CONSTANT (argument_pack) = 1;
5198     }
5199
5200   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5201   return argument_pack;
5202 }
5203
5204 /* Convert all template arguments to their appropriate types, and
5205    return a vector containing the innermost resulting template
5206    arguments.  If any error occurs, return error_mark_node. Error and
5207    warning messages are issued under control of COMPLAIN.
5208
5209    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5210    for arguments not specified in ARGS.  Otherwise, if
5211    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5212    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5213    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5214    ARGS.  */
5215
5216 static tree
5217 coerce_template_parms (tree parms,
5218                        tree args,
5219                        tree in_decl,
5220                        tsubst_flags_t complain,
5221                        bool require_all_args,
5222                        bool use_default_args)
5223 {
5224   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5225   tree inner_args;
5226   tree new_args;
5227   tree new_inner_args;
5228   bool saved_skip_evaluation;
5229
5230   /* When used as a boolean value, indicates whether this is a
5231      variadic template parameter list. Since it's an int, we can also
5232      subtract it from nparms to get the number of non-variadic
5233      parameters.  */
5234   int variadic_p = 0;
5235
5236   inner_args 
5237     = expand_template_argument_pack (INNERMOST_TEMPLATE_ARGS (args));
5238
5239   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5240   nparms = TREE_VEC_LENGTH (parms);
5241
5242   /* Determine if there are any parameter packs.  */
5243   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5244     {
5245       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5246       if (template_parameter_pack_p (tparm))
5247         {
5248           variadic_p = 1;
5249           break;
5250         }
5251     }
5252
5253   if ((nargs > nparms - variadic_p && !variadic_p)
5254       || (nargs < nparms - variadic_p
5255           && require_all_args
5256           && (!use_default_args
5257               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5258                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5259     {
5260       if (complain & tf_error)
5261         {
5262           const char *or_more = "";
5263           if (variadic_p)
5264             {
5265               or_more = " or more";
5266               --nparms;
5267             }
5268
5269           error ("wrong number of template arguments (%d, should be %d%s)",
5270                  nargs, nparms, or_more);
5271
5272           if (in_decl)
5273             error ("provided for %q+D", in_decl);
5274         }
5275
5276       return error_mark_node;
5277     }
5278
5279   /* We need to evaluate the template arguments, even though this
5280      template-id may be nested within a "sizeof".  */
5281   saved_skip_evaluation = skip_evaluation;
5282   skip_evaluation = false;
5283   new_inner_args = make_tree_vec (nparms);
5284   new_args = add_outermost_template_args (args, new_inner_args);
5285   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5286     {
5287       tree arg;
5288       tree parm;
5289
5290       /* Get the Ith template parameter.  */
5291       parm = TREE_VEC_ELT (parms, parm_idx);
5292  
5293       if (parm == error_mark_node)
5294       {
5295         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5296         continue;
5297       }
5298
5299       /* Calculate the next argument.  */
5300       if (template_parameter_pack_p (TREE_VALUE (parm)))
5301         {
5302           /* All remaining arguments will be placed in the
5303              template parameter pack PARM.  */
5304           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5305                                                 inner_args, arg_idx,
5306                                                 new_args, &lost,
5307                                                 in_decl, complain);
5308           
5309           /* Store this argument.  */
5310           if (arg == error_mark_node)
5311             lost++;
5312           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5313
5314           /* We are done with all of the arguments.  */
5315           arg_idx = nargs;
5316
5317           continue;
5318         }
5319       else if (arg_idx < nargs)
5320         {
5321           arg = TREE_VEC_ELT (inner_args, arg_idx);
5322
5323           if (arg && PACK_EXPANSION_P (arg))
5324             {
5325               if (complain & tf_error)
5326                 {
5327                   /* If ARG is a pack expansion, but PARM is not a
5328                      template parameter pack (if it were, we would have
5329                      handled it above), we're trying to expand into a
5330                      fixed-length argument list.  */
5331                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5332                     error ("cannot expand %<%E%> into a fixed-length "
5333                            "argument list", arg);
5334                   else
5335                     error ("cannot expand %<%T%> into a fixed-length "
5336                            "argument list", arg);
5337                 }
5338               return error_mark_node;
5339             }
5340         }
5341       else if (require_all_args)
5342         /* There must be a default arg in this case.  */
5343         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5344                                    complain, in_decl);
5345       else
5346         break;
5347
5348       if (arg == error_mark_node)
5349         {
5350           if (complain & tf_error)
5351             error ("template argument %d is invalid", arg_idx + 1);
5352         }
5353       else if (!arg)
5354         /* This only occurs if there was an error in the template
5355            parameter list itself (which we would already have
5356            reported) that we are trying to recover from, e.g., a class
5357            template with a parameter list such as
5358            template<typename..., typename>.  */
5359         return error_mark_node;
5360       else
5361         arg = convert_template_argument (TREE_VALUE (parm),
5362                                          arg, new_args, complain, 
5363                                          parm_idx, in_decl);
5364
5365       if (arg == error_mark_node)
5366         lost++;
5367       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5368     }
5369   skip_evaluation = saved_skip_evaluation;
5370
5371   if (lost)
5372     return error_mark_node;
5373
5374   return new_inner_args;
5375 }
5376
5377 /* Returns 1 if template args OT and NT are equivalent.  */
5378
5379 static int
5380 template_args_equal (tree ot, tree nt)
5381 {
5382   if (nt == ot)
5383     return 1;
5384
5385   if (TREE_CODE (nt) == TREE_VEC)
5386     /* For member templates */
5387     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5388   else if (PACK_EXPANSION_P (ot))
5389     return PACK_EXPANSION_P (nt) 
5390       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5391                               PACK_EXPANSION_PATTERN (nt));
5392   else if (TYPE_P (nt))
5393     return TYPE_P (ot) && same_type_p (ot, nt);
5394   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5395     return 0;
5396   else
5397     return cp_tree_equal (ot, nt);
5398 }
5399
5400 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5401    of template arguments.  Returns 0 otherwise.  */
5402
5403 int
5404 comp_template_args (tree oldargs, tree newargs)
5405 {
5406   int i;
5407
5408   oldargs = expand_template_argument_pack (oldargs);
5409   newargs = expand_template_argument_pack (newargs);
5410
5411   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5412     return 0;
5413
5414   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5415     {
5416       tree nt = TREE_VEC_ELT (newargs, i);
5417       tree ot = TREE_VEC_ELT (oldargs, i);
5418
5419       if (! template_args_equal (ot, nt))
5420         return 0;
5421     }
5422   return 1;
5423 }
5424
5425 static void
5426 add_pending_template (tree d)
5427 {
5428   tree ti = (TYPE_P (d)
5429              ? CLASSTYPE_TEMPLATE_INFO (d)
5430              : DECL_TEMPLATE_INFO (d));
5431   struct pending_template *pt;
5432   int level;
5433
5434   if (TI_PENDING_TEMPLATE_FLAG (ti))
5435     return;
5436
5437   /* We are called both from instantiate_decl, where we've already had a
5438      tinst_level pushed, and instantiate_template, where we haven't.
5439      Compensate.  */
5440   level = !current_tinst_level || current_tinst_level->decl != d;
5441
5442   if (level)
5443     push_tinst_level (d);
5444
5445   pt = GGC_NEW (struct pending_template);
5446   pt->next = NULL;
5447   pt->tinst = current_tinst_level;
5448   if (last_pending_template)
5449     last_pending_template->next = pt;
5450   else
5451     pending_templates = pt;
5452
5453   last_pending_template = pt;
5454
5455   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5456
5457   if (level)
5458     pop_tinst_level ();
5459 }
5460
5461
5462 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5463    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5464    documentation for TEMPLATE_ID_EXPR.  */
5465
5466 tree
5467 lookup_template_function (tree fns, tree arglist)
5468 {
5469   tree type;
5470
5471   if (fns == error_mark_node || arglist == error_mark_node)
5472     return error_mark_node;
5473
5474   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5475   gcc_assert (fns && (is_overloaded_fn (fns)
5476                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5477
5478   if (BASELINK_P (fns))
5479     {
5480       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5481                                          unknown_type_node,
5482                                          BASELINK_FUNCTIONS (fns),
5483                                          arglist);
5484       return fns;
5485     }
5486
5487   type = TREE_TYPE (fns);
5488   if (TREE_CODE (fns) == OVERLOAD || !type)
5489     type = unknown_type_node;
5490
5491   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5492 }
5493
5494 /* Within the scope of a template class S<T>, the name S gets bound
5495    (in build_self_reference) to a TYPE_DECL for the class, not a
5496    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5497    or one of its enclosing classes, and that type is a template,
5498    return the associated TEMPLATE_DECL.  Otherwise, the original
5499    DECL is returned.  */
5500
5501 tree
5502 maybe_get_template_decl_from_type_decl (tree decl)
5503 {
5504   return (decl != NULL_TREE
5505           && TREE_CODE (decl) == TYPE_DECL
5506           && DECL_ARTIFICIAL (decl)
5507           && CLASS_TYPE_P (TREE_TYPE (decl))
5508           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5509     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5510 }
5511
5512 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5513    parameters, find the desired type.
5514
5515    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5516
5517    IN_DECL, if non-NULL, is the template declaration we are trying to
5518    instantiate.
5519
5520    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5521    the class we are looking up.
5522
5523    Issue error and warning messages under control of COMPLAIN.
5524
5525    If the template class is really a local class in a template
5526    function, then the FUNCTION_CONTEXT is the function in which it is
5527    being instantiated.
5528
5529    ??? Note that this function is currently called *twice* for each
5530    template-id: the first time from the parser, while creating the
5531    incomplete type (finish_template_type), and the second type during the
5532    real instantiation (instantiate_template_class). This is surely something
5533    that we want to avoid. It also causes some problems with argument
5534    coercion (see convert_nontype_argument for more information on this).  */
5535
5536 tree
5537 lookup_template_class (tree d1,
5538                        tree arglist,
5539                        tree in_decl,
5540                        tree context,
5541                        int entering_scope,
5542                        tsubst_flags_t complain)
5543 {
5544   tree templ = NULL_TREE, parmlist;
5545   tree t;
5546
5547   timevar_push (TV_NAME_LOOKUP);
5548
5549   if (TREE_CODE (d1) == IDENTIFIER_NODE)
5550     {
5551       tree value = innermost_non_namespace_value (d1);
5552       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
5553         templ = value;
5554       else
5555         {
5556           if (context)
5557             push_decl_namespace (context);
5558           templ = lookup_name (d1);
5559           templ = maybe_get_template_decl_from_type_decl (templ);
5560           if (context)
5561             pop_decl_namespace ();
5562         }
5563       if (templ)
5564         context = DECL_CONTEXT (templ);
5565     }
5566   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
5567     {
5568       tree type = TREE_TYPE (d1);
5569
5570       /* If we are declaring a constructor, say A<T>::A<T>, we will get
5571          an implicit typename for the second A.  Deal with it.  */
5572       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
5573         type = TREE_TYPE (type);
5574
5575       if (CLASSTYPE_TEMPLATE_INFO (type))
5576         {
5577           templ = CLASSTYPE_TI_TEMPLATE (type);
5578           d1 = DECL_NAME (templ);
5579         }
5580     }
5581   else if (TREE_CODE (d1) == ENUMERAL_TYPE
5582            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
5583     {
5584       templ = TYPE_TI_TEMPLATE (d1);
5585       d1 = DECL_NAME (templ);
5586     }
5587   else if (TREE_CODE (d1) == TEMPLATE_DECL
5588            && DECL_TEMPLATE_RESULT (d1)
5589            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
5590     {
5591       templ = d1;
5592       d1 = DECL_NAME (templ);
5593       context = DECL_CONTEXT (templ);
5594     }
5595
5596   /* Issue an error message if we didn't find a template.  */
5597   if (! templ)
5598     {
5599       if (complain & tf_error)
5600         error ("%qT is not a template", d1);
5601       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5602     }
5603
5604   if (TREE_CODE (templ) != TEMPLATE_DECL
5605          /* Make sure it's a user visible template, if it was named by
5606             the user.  */
5607       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
5608           && !PRIMARY_TEMPLATE_P (templ)))
5609     {
5610       if (complain & tf_error)
5611         {
5612           error ("non-template type %qT used as a template", d1);
5613           if (in_decl)
5614             error ("for template declaration %q+D", in_decl);
5615         }
5616       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5617     }
5618
5619   complain &= ~tf_user;
5620
5621   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
5622     {
5623       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
5624          template arguments */
5625
5626       tree parm;
5627       tree arglist2;
5628       tree outer;
5629
5630       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
5631
5632       /* Consider an example where a template template parameter declared as
5633
5634            template <class T, class U = std::allocator<T> > class TT
5635
5636          The template parameter level of T and U are one level larger than
5637          of TT.  To proper process the default argument of U, say when an
5638          instantiation `TT<int>' is seen, we need to build the full
5639          arguments containing {int} as the innermost level.  Outer levels,
5640          available when not appearing as default template argument, can be
5641          obtained from the arguments of the enclosing template.
5642
5643          Suppose that TT is later substituted with std::vector.  The above
5644          instantiation is `TT<int, std::allocator<T> >' with TT at
5645          level 1, and T at level 2, while the template arguments at level 1
5646          becomes {std::vector} and the inner level 2 is {int}.  */
5647
5648       outer = DECL_CONTEXT (templ);
5649       if (outer)
5650         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
5651       else if (current_template_parms)
5652         /* This is an argument of the current template, so we haven't set
5653            DECL_CONTEXT yet.  */
5654         outer = current_template_args ();
5655
5656       if (outer)
5657         arglist = add_to_template_args (outer, arglist);
5658
5659       arglist2 = coerce_template_parms (parmlist, arglist, templ,
5660                                         complain,
5661                                         /*require_all_args=*/true,
5662                                         /*use_default_args=*/true);
5663       if (arglist2 == error_mark_node
5664           || (!uses_template_parms (arglist2)
5665               && check_instantiated_args (templ, arglist2, complain)))
5666         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5667
5668       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
5669       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
5670     }
5671   else
5672     {
5673       tree template_type = TREE_TYPE (templ);
5674       tree gen_tmpl;
5675       tree type_decl;
5676       tree found = NULL_TREE;
5677       int arg_depth;
5678       int parm_depth;
5679       int is_partial_instantiation;
5680
5681       gen_tmpl = most_general_template (templ);
5682       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
5683       parm_depth = TMPL_PARMS_DEPTH (parmlist);
5684       arg_depth = TMPL_ARGS_DEPTH (arglist);
5685
5686       if (arg_depth == 1 && parm_depth > 1)
5687         {
5688           /* We've been given an incomplete set of template arguments.
5689              For example, given:
5690
5691                template <class T> struct S1 {
5692                  template <class U> struct S2 {};
5693                  template <class U> struct S2<U*> {};
5694                 };
5695
5696              we will be called with an ARGLIST of `U*', but the
5697              TEMPLATE will be `template <class T> template
5698              <class U> struct S1<T>::S2'.  We must fill in the missing
5699              arguments.  */
5700           arglist
5701             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
5702                                            arglist);
5703           arg_depth = TMPL_ARGS_DEPTH (arglist);
5704         }
5705
5706       /* Now we should have enough arguments.  */
5707       gcc_assert (parm_depth == arg_depth);
5708
5709       /* From here on, we're only interested in the most general
5710          template.  */
5711       templ = gen_tmpl;
5712
5713       /* Calculate the BOUND_ARGS.  These will be the args that are
5714          actually tsubst'd into the definition to create the
5715          instantiation.  */
5716       if (parm_depth > 1)
5717         {
5718           /* We have multiple levels of arguments to coerce, at once.  */
5719           int i;
5720           int saved_depth = TMPL_ARGS_DEPTH (arglist);
5721
5722           tree bound_args = make_tree_vec (parm_depth);
5723
5724           for (i = saved_depth,
5725                  t = DECL_TEMPLATE_PARMS (templ);
5726                i > 0 && t != NULL_TREE;
5727                --i, t = TREE_CHAIN (t))
5728             {
5729               tree a = coerce_template_parms (TREE_VALUE (t),
5730                                               arglist, templ,
5731                                               complain,
5732                                               /*require_all_args=*/true,
5733                                               /*use_default_args=*/true);
5734
5735               /* Don't process further if one of the levels fails.  */
5736               if (a == error_mark_node)
5737                 {
5738                   /* Restore the ARGLIST to its full size.  */
5739                   TREE_VEC_LENGTH (arglist) = saved_depth;
5740                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5741                 }
5742
5743               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
5744
5745               /* We temporarily reduce the length of the ARGLIST so
5746                  that coerce_template_parms will see only the arguments
5747                  corresponding to the template parameters it is
5748                  examining.  */
5749               TREE_VEC_LENGTH (arglist)--;
5750             }
5751
5752           /* Restore the ARGLIST to its full size.  */
5753           TREE_VEC_LENGTH (arglist) = saved_depth;
5754
5755           arglist = bound_args;
5756         }
5757       else
5758         arglist
5759           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
5760                                    INNERMOST_TEMPLATE_ARGS (arglist),
5761                                    templ,
5762                                    complain,
5763                                    /*require_all_args=*/true,
5764                                    /*use_default_args=*/true);
5765
5766       if (arglist == error_mark_node)
5767         /* We were unable to bind the arguments.  */
5768         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5769
5770       /* In the scope of a template class, explicit references to the
5771          template class refer to the type of the template, not any
5772          instantiation of it.  For example, in:
5773
5774            template <class T> class C { void f(C<T>); }
5775
5776          the `C<T>' is just the same as `C'.  Outside of the
5777          class, however, such a reference is an instantiation.  */
5778       if (comp_template_args (TYPE_TI_ARGS (template_type),
5779                               arglist))
5780         {
5781           found = template_type;
5782
5783           if (!entering_scope && PRIMARY_TEMPLATE_P (templ))
5784             {
5785               tree ctx;
5786
5787               for (ctx = current_class_type;
5788                    ctx && TREE_CODE (ctx) != NAMESPACE_DECL;
5789                    ctx = (TYPE_P (ctx)
5790                           ? TYPE_CONTEXT (ctx)
5791                           : DECL_CONTEXT (ctx)))
5792                 if (TYPE_P (ctx) && same_type_p (ctx, template_type))
5793                   goto found_ctx;
5794
5795               /* We're not in the scope of the class, so the
5796                  TEMPLATE_TYPE is not the type we want after all.  */
5797               found = NULL_TREE;
5798             found_ctx:;
5799             }
5800         }
5801       if (found)
5802         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5803
5804       /* If we already have this specialization, return it.  */
5805       found = retrieve_specialization (templ, arglist,
5806                                        /*class_specializations_p=*/false);
5807       if (found)
5808         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5809
5810       /* This type is a "partial instantiation" if any of the template
5811          arguments still involve template parameters.  Note that we set
5812          IS_PARTIAL_INSTANTIATION for partial specializations as
5813          well.  */
5814       is_partial_instantiation = uses_template_parms (arglist);
5815
5816       /* If the deduced arguments are invalid, then the binding
5817          failed.  */
5818       if (!is_partial_instantiation
5819           && check_instantiated_args (templ,
5820                                       INNERMOST_TEMPLATE_ARGS (arglist),
5821                                       complain))
5822         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5823
5824       if (!is_partial_instantiation
5825           && !PRIMARY_TEMPLATE_P (templ)
5826           && TREE_CODE (CP_DECL_CONTEXT (templ)) == NAMESPACE_DECL)
5827         {
5828           found = xref_tag_from_type (TREE_TYPE (templ),
5829                                       DECL_NAME (templ),
5830                                       /*tag_scope=*/ts_global);
5831           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5832         }
5833
5834       context = tsubst (DECL_CONTEXT (templ), arglist,
5835                         complain, in_decl);
5836       if (!context)
5837         context = global_namespace;
5838
5839       /* Create the type.  */
5840       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
5841         {
5842           if (!is_partial_instantiation)
5843             {
5844               set_current_access_from_decl (TYPE_NAME (template_type));
5845               t = start_enum (TYPE_IDENTIFIER (template_type),
5846                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
5847                                       arglist, complain, in_decl),
5848                               SCOPED_ENUM_P (template_type));
5849             }
5850           else
5851             {
5852               /* We don't want to call start_enum for this type, since
5853                  the values for the enumeration constants may involve
5854                  template parameters.  And, no one should be interested
5855                  in the enumeration constants for such a type.  */
5856               t = make_node (ENUMERAL_TYPE);
5857               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
5858             }
5859         }
5860       else
5861         {
5862           t = make_class_type (TREE_CODE (template_type));
5863           CLASSTYPE_DECLARED_CLASS (t)
5864             = CLASSTYPE_DECLARED_CLASS (template_type);
5865           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
5866           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
5867
5868           /* A local class.  Make sure the decl gets registered properly.  */
5869           if (context == current_function_decl)
5870             pushtag (DECL_NAME (templ), t, /*tag_scope=*/ts_current);
5871
5872           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
5873             /* This instantiation is another name for the primary
5874                template type. Set the TYPE_CANONICAL field
5875                appropriately. */
5876             TYPE_CANONICAL (t) = template_type;
5877           else if (any_template_arguments_need_structural_equality_p (arglist))
5878             /* Some of the template arguments require structural
5879                equality testing, so this template class requires
5880                structural equality testing. */
5881             SET_TYPE_STRUCTURAL_EQUALITY (t);
5882         }
5883
5884       /* If we called start_enum or pushtag above, this information
5885          will already be set up.  */
5886       if (!TYPE_NAME (t))
5887         {
5888           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
5889
5890           type_decl = create_implicit_typedef (DECL_NAME (templ), t);
5891           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
5892           TYPE_STUB_DECL (t) = type_decl;
5893           DECL_SOURCE_LOCATION (type_decl)
5894             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
5895         }
5896       else
5897         type_decl = TYPE_NAME (t);
5898
5899       TREE_PRIVATE (type_decl)
5900         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
5901       TREE_PROTECTED (type_decl)
5902         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
5903       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
5904         {
5905           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
5906           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
5907         }
5908
5909       /* Set up the template information.  We have to figure out which
5910          template is the immediate parent if this is a full
5911          instantiation.  */
5912       if (parm_depth == 1 || is_partial_instantiation
5913           || !PRIMARY_TEMPLATE_P (templ))
5914         /* This case is easy; there are no member templates involved.  */
5915         found = templ;
5916       else
5917         {
5918           /* This is a full instantiation of a member template.  Look
5919              for a partial instantiation of which this is an instance.  */
5920
5921           for (found = DECL_TEMPLATE_INSTANTIATIONS (templ);
5922                found; found = TREE_CHAIN (found))
5923             {
5924               int success;
5925               tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
5926
5927               /* We only want partial instantiations, here, not
5928                  specializations or full instantiations.  */
5929               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
5930                   || !uses_template_parms (TREE_VALUE (found)))
5931                 continue;
5932
5933               /* Temporarily reduce by one the number of levels in the
5934                  ARGLIST and in FOUND so as to avoid comparing the
5935                  last set of arguments.  */
5936               TREE_VEC_LENGTH (arglist)--;
5937               TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
5938
5939               /* See if the arguments match.  If they do, then TMPL is
5940                  the partial instantiation we want.  */
5941               success = comp_template_args (TREE_PURPOSE (found), arglist);
5942
5943               /* Restore the argument vectors to their full size.  */
5944               TREE_VEC_LENGTH (arglist)++;
5945               TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
5946
5947               if (success)
5948                 {
5949                   found = tmpl;
5950                   break;
5951                 }
5952             }
5953
5954           if (!found)
5955             {
5956               /* There was no partial instantiation. This happens
5957                  where C<T> is a member template of A<T> and it's used
5958                  in something like
5959
5960                   template <typename T> struct B { A<T>::C<int> m; };
5961                   B<float>;
5962
5963                  Create the partial instantiation.
5964                */
5965               TREE_VEC_LENGTH (arglist)--;
5966               found = tsubst (templ, arglist, complain, NULL_TREE);
5967               TREE_VEC_LENGTH (arglist)++;
5968             }
5969         }
5970
5971       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
5972       DECL_TEMPLATE_INSTANTIATIONS (templ)
5973         = tree_cons (arglist, t,
5974                      DECL_TEMPLATE_INSTANTIATIONS (templ));
5975
5976       if (TREE_CODE (t) == ENUMERAL_TYPE
5977           && !is_partial_instantiation)
5978         /* Now that the type has been registered on the instantiations
5979            list, we set up the enumerators.  Because the enumeration
5980            constants may involve the enumeration type itself, we make
5981            sure to register the type first, and then create the
5982            constants.  That way, doing tsubst_expr for the enumeration
5983            constants won't result in recursive calls here; we'll find
5984            the instantiation and exit above.  */
5985         tsubst_enum (template_type, t, arglist);
5986
5987       if (is_partial_instantiation)
5988         /* If the type makes use of template parameters, the
5989            code that generates debugging information will crash.  */
5990         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
5991
5992       /* Possibly limit visibility based on template args.  */
5993       TREE_PUBLIC (type_decl) = 1;
5994       determine_visibility (type_decl);
5995
5996       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
5997     }
5998   timevar_pop (TV_NAME_LOOKUP);
5999 }
6000 \f
6001 struct pair_fn_data
6002 {
6003   tree_fn_t fn;
6004   void *data;
6005   /* True when we should also visit template parameters that occur in
6006      non-deduced contexts.  */
6007   bool include_nondeduced_p;
6008   struct pointer_set_t *visited;
6009 };
6010
6011 /* Called from for_each_template_parm via walk_tree.  */
6012
6013 static tree
6014 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6015 {
6016   tree t = *tp;
6017   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6018   tree_fn_t fn = pfd->fn;
6019   void *data = pfd->data;
6020
6021   if (TYPE_P (t)
6022       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6023       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6024                                  pfd->include_nondeduced_p))
6025     return error_mark_node;
6026
6027   switch (TREE_CODE (t))
6028     {
6029     case RECORD_TYPE:
6030       if (TYPE_PTRMEMFUNC_P (t))
6031         break;
6032       /* Fall through.  */
6033
6034     case UNION_TYPE:
6035     case ENUMERAL_TYPE:
6036       if (!TYPE_TEMPLATE_INFO (t))
6037         *walk_subtrees = 0;
6038       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
6039                                        fn, data, pfd->visited, 
6040                                        pfd->include_nondeduced_p))
6041         return error_mark_node;
6042       break;
6043
6044     case INTEGER_TYPE:
6045       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6046                                   fn, data, pfd->visited, 
6047                                   pfd->include_nondeduced_p)
6048           || for_each_template_parm (TYPE_MAX_VALUE (t),
6049                                      fn, data, pfd->visited,
6050                                      pfd->include_nondeduced_p))
6051         return error_mark_node;
6052       break;
6053
6054     case METHOD_TYPE:
6055       /* Since we're not going to walk subtrees, we have to do this
6056          explicitly here.  */
6057       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6058                                   pfd->visited, pfd->include_nondeduced_p))
6059         return error_mark_node;
6060       /* Fall through.  */
6061
6062     case FUNCTION_TYPE:
6063       /* Check the return type.  */
6064       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6065                                   pfd->include_nondeduced_p))
6066         return error_mark_node;
6067
6068       /* Check the parameter types.  Since default arguments are not
6069          instantiated until they are needed, the TYPE_ARG_TYPES may
6070          contain expressions that involve template parameters.  But,
6071          no-one should be looking at them yet.  And, once they're
6072          instantiated, they don't contain template parameters, so
6073          there's no point in looking at them then, either.  */
6074       {
6075         tree parm;
6076
6077         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6078           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6079                                       pfd->visited, pfd->include_nondeduced_p))
6080             return error_mark_node;
6081
6082         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6083            want walk_tree walking into them itself.  */
6084         *walk_subtrees = 0;
6085       }
6086       break;
6087
6088     case TYPEOF_TYPE:
6089       if (pfd->include_nondeduced_p
6090           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6091                                      pfd->visited, 
6092                                      pfd->include_nondeduced_p))
6093         return error_mark_node;
6094       break;
6095
6096     case FUNCTION_DECL:
6097     case VAR_DECL:
6098       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6099           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6100                                      pfd->visited, pfd->include_nondeduced_p))
6101         return error_mark_node;
6102       /* Fall through.  */
6103
6104     case PARM_DECL:
6105     case CONST_DECL:
6106       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6107           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6108                                      pfd->visited, pfd->include_nondeduced_p))
6109         return error_mark_node;
6110       if (DECL_CONTEXT (t)
6111           && pfd->include_nondeduced_p
6112           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6113                                      pfd->visited, pfd->include_nondeduced_p))
6114         return error_mark_node;
6115       break;
6116
6117     case BOUND_TEMPLATE_TEMPLATE_PARM:
6118       /* Record template parameters such as `T' inside `TT<T>'.  */
6119       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6120                                   pfd->include_nondeduced_p))
6121         return error_mark_node;
6122       /* Fall through.  */
6123
6124     case TEMPLATE_TEMPLATE_PARM:
6125     case TEMPLATE_TYPE_PARM:
6126     case TEMPLATE_PARM_INDEX:
6127       if (fn && (*fn)(t, data))
6128         return error_mark_node;
6129       else if (!fn)
6130         return error_mark_node;
6131       break;
6132
6133     case TEMPLATE_DECL:
6134       /* A template template parameter is encountered.  */
6135       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6136           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6137                                      pfd->include_nondeduced_p))
6138         return error_mark_node;
6139
6140       /* Already substituted template template parameter */
6141       *walk_subtrees = 0;
6142       break;
6143
6144     case TYPENAME_TYPE:
6145       if (!fn
6146           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6147                                      data, pfd->visited, 
6148                                      pfd->include_nondeduced_p))
6149         return error_mark_node;
6150       break;
6151
6152     case CONSTRUCTOR:
6153       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6154           && pfd->include_nondeduced_p
6155           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6156                                      (TREE_TYPE (t)), fn, data,
6157                                      pfd->visited, pfd->include_nondeduced_p))
6158         return error_mark_node;
6159       break;
6160
6161     case INDIRECT_REF:
6162     case COMPONENT_REF:
6163       /* If there's no type, then this thing must be some expression
6164          involving template parameters.  */
6165       if (!fn && !TREE_TYPE (t))
6166         return error_mark_node;
6167       break;
6168
6169     case MODOP_EXPR:
6170     case CAST_EXPR:
6171     case REINTERPRET_CAST_EXPR:
6172     case CONST_CAST_EXPR:
6173     case STATIC_CAST_EXPR:
6174     case DYNAMIC_CAST_EXPR:
6175     case ARROW_EXPR:
6176     case DOTSTAR_EXPR:
6177     case TYPEID_EXPR:
6178     case PSEUDO_DTOR_EXPR:
6179       if (!fn)
6180         return error_mark_node;
6181       break;
6182
6183     default:
6184       break;
6185     }
6186
6187   /* We didn't find any template parameters we liked.  */
6188   return NULL_TREE;
6189 }
6190
6191 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6192    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6193    call FN with the parameter and the DATA.
6194    If FN returns nonzero, the iteration is terminated, and
6195    for_each_template_parm returns 1.  Otherwise, the iteration
6196    continues.  If FN never returns a nonzero value, the value
6197    returned by for_each_template_parm is 0.  If FN is NULL, it is
6198    considered to be the function which always returns 1.
6199
6200    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6201    parameters that occur in non-deduced contexts.  When false, only
6202    visits those template parameters that can be deduced.  */
6203
6204 static int
6205 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6206                         struct pointer_set_t *visited,
6207                         bool include_nondeduced_p)
6208 {
6209   struct pair_fn_data pfd;
6210   int result;
6211
6212   /* Set up.  */
6213   pfd.fn = fn;
6214   pfd.data = data;
6215   pfd.include_nondeduced_p = include_nondeduced_p;
6216
6217   /* Walk the tree.  (Conceptually, we would like to walk without
6218      duplicates, but for_each_template_parm_r recursively calls
6219      for_each_template_parm, so we would need to reorganize a fair
6220      bit to use walk_tree_without_duplicates, so we keep our own
6221      visited list.)  */
6222   if (visited)
6223     pfd.visited = visited;
6224   else
6225     pfd.visited = pointer_set_create ();
6226   result = cp_walk_tree (&t,
6227                          for_each_template_parm_r,
6228                          &pfd,
6229                          pfd.visited) != NULL_TREE;
6230
6231   /* Clean up.  */
6232   if (!visited)
6233     {
6234       pointer_set_destroy (pfd.visited);
6235       pfd.visited = 0;
6236     }
6237
6238   return result;
6239 }
6240
6241 /* Returns true if T depends on any template parameter.  */
6242
6243 int
6244 uses_template_parms (tree t)
6245 {
6246   bool dependent_p;
6247   int saved_processing_template_decl;
6248
6249   saved_processing_template_decl = processing_template_decl;
6250   if (!saved_processing_template_decl)
6251     processing_template_decl = 1;
6252   if (TYPE_P (t))
6253     dependent_p = dependent_type_p (t);
6254   else if (TREE_CODE (t) == TREE_VEC)
6255     dependent_p = any_dependent_template_arguments_p (t);
6256   else if (TREE_CODE (t) == TREE_LIST)
6257     dependent_p = (uses_template_parms (TREE_VALUE (t))
6258                    || uses_template_parms (TREE_CHAIN (t)));
6259   else if (TREE_CODE (t) == TYPE_DECL)
6260     dependent_p = dependent_type_p (TREE_TYPE (t));
6261   else if (DECL_P (t)
6262            || EXPR_P (t)
6263            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6264            || TREE_CODE (t) == OVERLOAD
6265            || TREE_CODE (t) == BASELINK
6266            || TREE_CODE (t) == IDENTIFIER_NODE
6267            || TREE_CODE (t) == TRAIT_EXPR
6268            || CONSTANT_CLASS_P (t))
6269     dependent_p = (type_dependent_expression_p (t)
6270                    || value_dependent_expression_p (t));
6271   else
6272     {
6273       gcc_assert (t == error_mark_node);
6274       dependent_p = false;
6275     }
6276
6277   processing_template_decl = saved_processing_template_decl;
6278
6279   return dependent_p;
6280 }
6281
6282 /* Returns true if T depends on any template parameter with level LEVEL.  */
6283
6284 int
6285 uses_template_parms_level (tree t, int level)
6286 {
6287   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6288                                  /*include_nondeduced_p=*/true);
6289 }
6290
6291 static int tinst_depth;
6292 extern int max_tinst_depth;
6293 #ifdef GATHER_STATISTICS
6294 int depth_reached;
6295 #endif
6296 static int tinst_level_tick;
6297 static int last_template_error_tick;
6298
6299 /* We're starting to instantiate D; record the template instantiation context
6300    for diagnostics and to restore it later.  */
6301
6302 static int
6303 push_tinst_level (tree d)
6304 {
6305   struct tinst_level *new_level;
6306
6307   if (tinst_depth >= max_tinst_depth)
6308     {
6309       /* If the instantiation in question still has unbound template parms,
6310          we don't really care if we can't instantiate it, so just return.
6311          This happens with base instantiation for implicit `typename'.  */
6312       if (uses_template_parms (d))
6313         return 0;
6314
6315       last_template_error_tick = tinst_level_tick;
6316       error ("template instantiation depth exceeds maximum of %d (use "
6317              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6318              max_tinst_depth, d);
6319
6320       print_instantiation_context ();
6321
6322       return 0;
6323     }
6324
6325   new_level = GGC_NEW (struct tinst_level);
6326   new_level->decl = d;
6327   new_level->locus = input_location;
6328   new_level->in_system_header_p = in_system_header;
6329   new_level->next = current_tinst_level;
6330   current_tinst_level = new_level;
6331
6332   ++tinst_depth;
6333 #ifdef GATHER_STATISTICS
6334   if (tinst_depth > depth_reached)
6335     depth_reached = tinst_depth;
6336 #endif
6337
6338   ++tinst_level_tick;
6339   return 1;
6340 }
6341
6342 /* We're done instantiating this template; return to the instantiation
6343    context.  */
6344
6345 static void
6346 pop_tinst_level (void)
6347 {
6348   /* Restore the filename and line number stashed away when we started
6349      this instantiation.  */
6350   input_location = current_tinst_level->locus;
6351   current_tinst_level = current_tinst_level->next;
6352   --tinst_depth;
6353   ++tinst_level_tick;
6354 }
6355
6356 /* We're instantiating a deferred template; restore the template
6357    instantiation context in which the instantiation was requested, which
6358    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6359
6360 static tree
6361 reopen_tinst_level (struct tinst_level *level)
6362 {
6363   struct tinst_level *t;
6364
6365   tinst_depth = 0;
6366   for (t = level; t; t = t->next)
6367     ++tinst_depth;
6368
6369   current_tinst_level = level;
6370   pop_tinst_level ();
6371   return level->decl;
6372 }
6373
6374 /* Returns the TINST_LEVEL which gives the original instantiation
6375    context.  */
6376
6377 struct tinst_level *
6378 outermost_tinst_level (void)
6379 {
6380   struct tinst_level *level = current_tinst_level;
6381   if (level)
6382     while (level->next)
6383       level = level->next;
6384   return level;
6385 }
6386
6387 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6388    vector of template arguments, as for tsubst.
6389
6390    Returns an appropriate tsubst'd friend declaration.  */
6391
6392 static tree
6393 tsubst_friend_function (tree decl, tree args)
6394 {
6395   tree new_friend;
6396
6397   if (TREE_CODE (decl) == FUNCTION_DECL
6398       && DECL_TEMPLATE_INSTANTIATION (decl)
6399       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6400     /* This was a friend declared with an explicit template
6401        argument list, e.g.:
6402
6403        friend void f<>(T);
6404
6405        to indicate that f was a template instantiation, not a new
6406        function declaration.  Now, we have to figure out what
6407        instantiation of what template.  */
6408     {
6409       tree template_id, arglist, fns;
6410       tree new_args;
6411       tree tmpl;
6412       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6413
6414       /* Friend functions are looked up in the containing namespace scope.
6415          We must enter that scope, to avoid finding member functions of the
6416          current class with same name.  */
6417       push_nested_namespace (ns);
6418       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6419                          tf_warning_or_error, NULL_TREE,
6420                          /*integral_constant_expression_p=*/false);
6421       pop_nested_namespace (ns);
6422       arglist = tsubst (DECL_TI_ARGS (decl), args,
6423                         tf_warning_or_error, NULL_TREE);
6424       template_id = lookup_template_function (fns, arglist);
6425
6426       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6427       tmpl = determine_specialization (template_id, new_friend,
6428                                        &new_args,
6429                                        /*need_member_template=*/0,
6430                                        TREE_VEC_LENGTH (args),
6431                                        tsk_none);
6432       return instantiate_template (tmpl, new_args, tf_error);
6433     }
6434
6435   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6436
6437   /* The NEW_FRIEND will look like an instantiation, to the
6438      compiler, but is not an instantiation from the point of view of
6439      the language.  For example, we might have had:
6440
6441      template <class T> struct S {
6442        template <class U> friend void f(T, U);
6443      };
6444
6445      Then, in S<int>, template <class U> void f(int, U) is not an
6446      instantiation of anything.  */
6447   if (new_friend == error_mark_node)
6448     return error_mark_node;
6449
6450   DECL_USE_TEMPLATE (new_friend) = 0;
6451   if (TREE_CODE (decl) == TEMPLATE_DECL)
6452     {
6453       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6454       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6455         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6456     }
6457
6458   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6459      is not a template instantiation and should not be mangled like
6460      one.  Therefore, we forget the mangling here; we'll recompute it
6461      later if we need it.  */
6462   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6463     {
6464       SET_DECL_RTL (new_friend, NULL_RTX);
6465       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6466     }
6467
6468   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6469     {
6470       tree old_decl;
6471       tree new_friend_template_info;
6472       tree new_friend_result_template_info;
6473       tree ns;
6474       int  new_friend_is_defn;
6475
6476       /* We must save some information from NEW_FRIEND before calling
6477          duplicate decls since that function will free NEW_FRIEND if
6478          possible.  */
6479       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6480       new_friend_is_defn =
6481             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6482                            (template_for_substitution (new_friend)))
6483              != NULL_TREE);
6484       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6485         {
6486           /* This declaration is a `primary' template.  */
6487           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6488
6489           new_friend_result_template_info
6490             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6491         }
6492       else
6493         new_friend_result_template_info = NULL_TREE;
6494
6495       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6496       if (new_friend_is_defn)
6497         DECL_INITIAL (new_friend) = error_mark_node;
6498
6499       /* Inside pushdecl_namespace_level, we will push into the
6500          current namespace. However, the friend function should go
6501          into the namespace of the template.  */
6502       ns = decl_namespace_context (new_friend);
6503       push_nested_namespace (ns);
6504       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6505       pop_nested_namespace (ns);
6506
6507       if (old_decl == error_mark_node)
6508         return error_mark_node;
6509
6510       if (old_decl != new_friend)
6511         {
6512           /* This new friend declaration matched an existing
6513              declaration.  For example, given:
6514
6515                template <class T> void f(T);
6516                template <class U> class C {
6517                  template <class T> friend void f(T) {}
6518                };
6519
6520              the friend declaration actually provides the definition
6521              of `f', once C has been instantiated for some type.  So,
6522              old_decl will be the out-of-class template declaration,
6523              while new_friend is the in-class definition.
6524
6525              But, if `f' was called before this point, the
6526              instantiation of `f' will have DECL_TI_ARGS corresponding
6527              to `T' but not to `U', references to which might appear
6528              in the definition of `f'.  Previously, the most general
6529              template for an instantiation of `f' was the out-of-class
6530              version; now it is the in-class version.  Therefore, we
6531              run through all specialization of `f', adding to their
6532              DECL_TI_ARGS appropriately.  In particular, they need a
6533              new set of outer arguments, corresponding to the
6534              arguments for this class instantiation.
6535
6536              The same situation can arise with something like this:
6537
6538                friend void f(int);
6539                template <class T> class C {
6540                  friend void f(T) {}
6541                };
6542
6543              when `C<int>' is instantiated.  Now, `f(int)' is defined
6544              in the class.  */
6545
6546           if (!new_friend_is_defn)
6547             /* On the other hand, if the in-class declaration does
6548                *not* provide a definition, then we don't want to alter
6549                existing definitions.  We can just leave everything
6550                alone.  */
6551             ;
6552           else
6553             {
6554               /* Overwrite whatever template info was there before, if
6555                  any, with the new template information pertaining to
6556                  the declaration.  */
6557               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
6558
6559               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
6560                 reregister_specialization (new_friend,
6561                                            most_general_template (old_decl),
6562                                            old_decl);
6563               else
6564                 {
6565                   tree t;
6566                   tree new_friend_args;
6567
6568                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
6569                     = new_friend_result_template_info;
6570
6571                   new_friend_args = TI_ARGS (new_friend_template_info);
6572                   for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl);
6573                        t != NULL_TREE;
6574                        t = TREE_CHAIN (t))
6575                     {
6576                       tree spec = TREE_VALUE (t);
6577
6578                       DECL_TI_ARGS (spec)
6579                         = add_outermost_template_args (new_friend_args,
6580                                                        DECL_TI_ARGS (spec));
6581                     }
6582
6583                   /* Now, since specializations are always supposed to
6584                      hang off of the most general template, we must move
6585                      them.  */
6586                   t = most_general_template (old_decl);
6587                   if (t != old_decl)
6588                     {
6589                       DECL_TEMPLATE_SPECIALIZATIONS (t)
6590                         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
6591                                    DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
6592                       DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
6593                     }
6594                 }
6595             }
6596
6597           /* The information from NEW_FRIEND has been merged into OLD_DECL
6598              by duplicate_decls.  */
6599           new_friend = old_decl;
6600         }
6601     }
6602   else
6603     {
6604       tree context = DECL_CONTEXT (new_friend);
6605       bool dependent_p;
6606
6607       /* In the code
6608            template <class T> class C {
6609              template <class U> friend void C1<U>::f (); // case 1
6610              friend void C2<T>::f ();                    // case 2
6611            };
6612          we only need to make sure CONTEXT is a complete type for
6613          case 2.  To distinguish between the two cases, we note that
6614          CONTEXT of case 1 remains dependent type after tsubst while
6615          this isn't true for case 2.  */
6616       ++processing_template_decl;
6617       dependent_p = dependent_type_p (context);
6618       --processing_template_decl;
6619
6620       if (!dependent_p
6621           && !complete_type_or_else (context, NULL_TREE))
6622         return error_mark_node;
6623
6624       if (COMPLETE_TYPE_P (context))
6625         {
6626           /* Check to see that the declaration is really present, and,
6627              possibly obtain an improved declaration.  */
6628           tree fn = check_classfn (context,
6629                                    new_friend, NULL_TREE);
6630
6631           if (fn)
6632             new_friend = fn;
6633         }
6634     }
6635
6636   return new_friend;
6637 }
6638
6639 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
6640    template arguments, as for tsubst.
6641
6642    Returns an appropriate tsubst'd friend type or error_mark_node on
6643    failure.  */
6644
6645 static tree
6646 tsubst_friend_class (tree friend_tmpl, tree args)
6647 {
6648   tree friend_type;
6649   tree tmpl;
6650   tree context;
6651
6652   context = DECL_CONTEXT (friend_tmpl);
6653
6654   if (context)
6655     {
6656       if (TREE_CODE (context) == NAMESPACE_DECL)
6657         push_nested_namespace (context);
6658       else
6659         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
6660     }
6661
6662   /* Look for a class template declaration.  We look for hidden names
6663      because two friend declarations of the same template are the
6664      same.  For example, in:
6665
6666        struct A { 
6667          template <typename> friend class F;
6668        };
6669        template <typename> struct B { 
6670          template <typename> friend class F;
6671        };
6672
6673      both F templates are the same.  */
6674   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
6675                            /*block_p=*/true, 0, 
6676                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
6677
6678   /* But, if we don't find one, it might be because we're in a
6679      situation like this:
6680
6681        template <class T>
6682        struct S {
6683          template <class U>
6684          friend struct S;
6685        };
6686
6687      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
6688      for `S<int>', not the TEMPLATE_DECL.  */
6689   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
6690     {
6691       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
6692       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
6693     }
6694
6695   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
6696     {
6697       /* The friend template has already been declared.  Just
6698          check to see that the declarations match, and install any new
6699          default parameters.  We must tsubst the default parameters,
6700          of course.  We only need the innermost template parameters
6701          because that is all that redeclare_class_template will look
6702          at.  */
6703       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
6704           > TMPL_ARGS_DEPTH (args))
6705         {
6706           tree parms;
6707           location_t saved_input_location;
6708           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
6709                                          args, tf_warning_or_error);
6710
6711           saved_input_location = input_location;
6712           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
6713           redeclare_class_template (TREE_TYPE (tmpl), parms);
6714           input_location = saved_input_location;
6715           
6716         }
6717
6718       friend_type = TREE_TYPE (tmpl);
6719     }
6720   else
6721     {
6722       /* The friend template has not already been declared.  In this
6723          case, the instantiation of the template class will cause the
6724          injection of this template into the global scope.  */
6725       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
6726       if (tmpl == error_mark_node)
6727         return error_mark_node;
6728
6729       /* The new TMPL is not an instantiation of anything, so we
6730          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
6731          the new type because that is supposed to be the corresponding
6732          template decl, i.e., TMPL.  */
6733       DECL_USE_TEMPLATE (tmpl) = 0;
6734       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
6735       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
6736       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
6737         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
6738
6739       /* Inject this template into the global scope.  */
6740       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
6741     }
6742
6743   if (context)
6744     {
6745       if (TREE_CODE (context) == NAMESPACE_DECL)
6746         pop_nested_namespace (context);
6747       else
6748         pop_nested_class ();
6749     }
6750
6751   return friend_type;
6752 }
6753
6754 /* Returns zero if TYPE cannot be completed later due to circularity.
6755    Otherwise returns one.  */
6756
6757 static int
6758 can_complete_type_without_circularity (tree type)
6759 {
6760   if (type == NULL_TREE || type == error_mark_node)
6761     return 0;
6762   else if (COMPLETE_TYPE_P (type))
6763     return 1;
6764   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
6765     return can_complete_type_without_circularity (TREE_TYPE (type));
6766   else if (CLASS_TYPE_P (type)
6767            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
6768     return 0;
6769   else
6770     return 1;
6771 }
6772
6773 /* Apply any attributes which had to be deferred until instantiation
6774    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
6775    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
6776
6777 static void
6778 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
6779                                 tree args, tsubst_flags_t complain, tree in_decl)
6780 {
6781   tree last_dep = NULL_TREE;
6782   tree t;
6783   tree *p;
6784
6785   for (t = attributes; t; t = TREE_CHAIN (t))
6786     if (ATTR_IS_DEPENDENT (t))
6787       {
6788         last_dep = t;
6789         attributes = copy_list (attributes);
6790         break;
6791       }
6792
6793   if (DECL_P (*decl_p))
6794     {
6795       if (TREE_TYPE (*decl_p) == error_mark_node)
6796         return;
6797       p = &DECL_ATTRIBUTES (*decl_p);
6798     }
6799   else
6800     p = &TYPE_ATTRIBUTES (*decl_p);
6801
6802   if (last_dep)
6803     {
6804       tree late_attrs = NULL_TREE;
6805       tree *q = &late_attrs;
6806
6807       for (*p = attributes; *p; )
6808         {
6809           t = *p;
6810           if (ATTR_IS_DEPENDENT (t))
6811             {
6812               *p = TREE_CHAIN (t);
6813               TREE_CHAIN (t) = NULL_TREE;
6814               /* If the first attribute argument is an identifier, don't
6815                  pass it through tsubst.  Attributes like mode, format,
6816                  cleanup and several target specific attributes expect it
6817                  unmodified.  */
6818               if (TREE_VALUE (t)
6819                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
6820                   && TREE_VALUE (TREE_VALUE (t))
6821                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
6822                       == IDENTIFIER_NODE))
6823                 {
6824                   tree chain
6825                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
6826                                    in_decl,
6827                                    /*integral_constant_expression_p=*/false);
6828                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
6829                     TREE_VALUE (t)
6830                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
6831                                    chain);
6832                 }
6833               else
6834                 TREE_VALUE (t)
6835                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
6836                                  /*integral_constant_expression_p=*/false);
6837               *q = t;
6838               q = &TREE_CHAIN (t);
6839             }
6840           else
6841             p = &TREE_CHAIN (t);
6842         }
6843
6844       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
6845     }
6846 }
6847
6848 tree
6849 instantiate_class_template (tree type)
6850 {
6851   tree templ, args, pattern, t, member;
6852   tree typedecl;
6853   tree pbinfo;
6854   tree base_list;
6855
6856   if (type == error_mark_node)
6857     return error_mark_node;
6858
6859   if (TYPE_BEING_DEFINED (type)
6860       || COMPLETE_TYPE_P (type)
6861       || dependent_type_p (type))
6862     return type;
6863
6864   /* Figure out which template is being instantiated.  */
6865   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
6866   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6867
6868   /* Determine what specialization of the original template to
6869      instantiate.  */
6870   t = most_specialized_class (type, templ);
6871   if (t == error_mark_node)
6872     {
6873       TYPE_BEING_DEFINED (type) = 1;
6874       return error_mark_node;
6875     }
6876   else if (t)
6877     {
6878       /* This TYPE is actually an instantiation of a partial
6879          specialization.  We replace the innermost set of ARGS with
6880          the arguments appropriate for substitution.  For example,
6881          given:
6882
6883            template <class T> struct S {};
6884            template <class T> struct S<T*> {};
6885
6886          and supposing that we are instantiating S<int*>, ARGS will
6887          presently be {int*} -- but we need {int}.  */
6888       pattern = TREE_TYPE (t);
6889       args = TREE_PURPOSE (t);
6890     }
6891   else
6892     {
6893       pattern = TREE_TYPE (templ);
6894       args = CLASSTYPE_TI_ARGS (type);
6895     }
6896
6897   /* If the template we're instantiating is incomplete, then clearly
6898      there's nothing we can do.  */
6899   if (!COMPLETE_TYPE_P (pattern))
6900     return type;
6901
6902   /* If we've recursively instantiated too many templates, stop.  */
6903   if (! push_tinst_level (type))
6904     return type;
6905
6906   /* Now we're really doing the instantiation.  Mark the type as in
6907      the process of being defined.  */
6908   TYPE_BEING_DEFINED (type) = 1;
6909
6910   /* We may be in the middle of deferred access check.  Disable
6911      it now.  */
6912   push_deferring_access_checks (dk_no_deferred);
6913
6914   push_to_top_level ();
6915
6916   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
6917
6918   /* Set the input location to the template definition. This is needed
6919      if tsubsting causes an error.  */
6920   typedecl = TYPE_MAIN_DECL (type);
6921   input_location = DECL_SOURCE_LOCATION (typedecl);
6922
6923   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
6924   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
6925   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
6926   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
6927   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
6928   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
6929   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
6930   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
6931   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
6932   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
6933   TYPE_PACKED (type) = TYPE_PACKED (pattern);
6934   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
6935   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
6936   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
6937   if (ANON_AGGR_TYPE_P (pattern))
6938     SET_ANON_AGGR_TYPE_P (type);
6939   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
6940     {
6941       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
6942       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
6943     }
6944
6945   pbinfo = TYPE_BINFO (pattern);
6946
6947   /* We should never instantiate a nested class before its enclosing
6948      class; we need to look up the nested class by name before we can
6949      instantiate it, and that lookup should instantiate the enclosing
6950      class.  */
6951   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
6952               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
6953               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
6954
6955   base_list = NULL_TREE;
6956   if (BINFO_N_BASE_BINFOS (pbinfo))
6957     {
6958       tree pbase_binfo;
6959       tree context = TYPE_CONTEXT (type);
6960       tree pushed_scope;
6961       int i;
6962
6963       /* We must enter the scope containing the type, as that is where
6964          the accessibility of types named in dependent bases are
6965          looked up from.  */
6966       pushed_scope = push_scope (context ? context : global_namespace);
6967
6968       /* Substitute into each of the bases to determine the actual
6969          basetypes.  */
6970       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
6971         {
6972           tree base;
6973           tree access = BINFO_BASE_ACCESS (pbinfo, i);
6974           tree expanded_bases = NULL_TREE;
6975           int idx, len = 1;
6976
6977           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
6978             {
6979               expanded_bases = 
6980                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
6981                                        args, tf_error, NULL_TREE);
6982               if (expanded_bases == error_mark_node)
6983                 continue;
6984
6985               len = TREE_VEC_LENGTH (expanded_bases);
6986             }
6987
6988           for (idx = 0; idx < len; idx++)
6989             {
6990               if (expanded_bases)
6991                 /* Extract the already-expanded base class.  */
6992                 base = TREE_VEC_ELT (expanded_bases, idx);
6993               else
6994                 /* Substitute to figure out the base class.  */
6995                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
6996                                NULL_TREE);
6997
6998               if (base == error_mark_node)
6999                 continue;
7000
7001               base_list = tree_cons (access, base, base_list);
7002               if (BINFO_VIRTUAL_P (pbase_binfo))
7003                 TREE_TYPE (base_list) = integer_type_node;
7004             }
7005         }
7006
7007       /* The list is now in reverse order; correct that.  */
7008       base_list = nreverse (base_list);
7009
7010       if (pushed_scope)
7011         pop_scope (pushed_scope);
7012     }
7013   /* Now call xref_basetypes to set up all the base-class
7014      information.  */
7015   xref_basetypes (type, base_list);
7016
7017   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7018                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7019                                   args, tf_error, NULL_TREE);
7020
7021   /* Now that our base classes are set up, enter the scope of the
7022      class, so that name lookups into base classes, etc. will work
7023      correctly.  This is precisely analogous to what we do in
7024      begin_class_definition when defining an ordinary non-template
7025      class, except we also need to push the enclosing classes.  */
7026   push_nested_class (type);
7027
7028   /* Now members are processed in the order of declaration.  */
7029   for (member = CLASSTYPE_DECL_LIST (pattern);
7030        member; member = TREE_CHAIN (member))
7031     {
7032       tree t = TREE_VALUE (member);
7033
7034       if (TREE_PURPOSE (member))
7035         {
7036           if (TYPE_P (t))
7037             {
7038               /* Build new CLASSTYPE_NESTED_UTDS.  */
7039
7040               tree newtag;
7041               bool class_template_p;
7042
7043               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7044                                   && TYPE_LANG_SPECIFIC (t)
7045                                   && CLASSTYPE_IS_TEMPLATE (t));
7046               /* If the member is a class template, then -- even after
7047                  substitution -- there may be dependent types in the
7048                  template argument list for the class.  We increment
7049                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7050                  that function will assume that no types are dependent
7051                  when outside of a template.  */
7052               if (class_template_p)
7053                 ++processing_template_decl;
7054               newtag = tsubst (t, args, tf_error, NULL_TREE);
7055               if (class_template_p)
7056                 --processing_template_decl;
7057               if (newtag == error_mark_node)
7058                 continue;
7059
7060               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7061                 {
7062                   tree name = TYPE_IDENTIFIER (t);
7063
7064                   if (class_template_p)
7065                     /* Unfortunately, lookup_template_class sets
7066                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7067                        instantiation (i.e., for the type of a member
7068                        template class nested within a template class.)
7069                        This behavior is required for
7070                        maybe_process_partial_specialization to work
7071                        correctly, but is not accurate in this case;
7072                        the TAG is not an instantiation of anything.
7073                        (The corresponding TEMPLATE_DECL is an
7074                        instantiation, but the TYPE is not.) */
7075                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7076
7077                   /* Now, we call pushtag to put this NEWTAG into the scope of
7078                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7079                      pushtag calling push_template_decl.  We don't have to do
7080                      this for enums because it will already have been done in
7081                      tsubst_enum.  */
7082                   if (name)
7083                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7084                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7085                 }
7086             }
7087           else if (TREE_CODE (t) == FUNCTION_DECL
7088                    || DECL_FUNCTION_TEMPLATE_P (t))
7089             {
7090               /* Build new TYPE_METHODS.  */
7091               tree r;
7092
7093               if (TREE_CODE (t) == TEMPLATE_DECL)
7094                 ++processing_template_decl;
7095               r = tsubst (t, args, tf_error, NULL_TREE);
7096               if (TREE_CODE (t) == TEMPLATE_DECL)
7097                 --processing_template_decl;
7098               set_current_access_from_decl (r);
7099               finish_member_declaration (r);
7100             }
7101           else
7102             {
7103               /* Build new TYPE_FIELDS.  */
7104               if (TREE_CODE (t) == STATIC_ASSERT)
7105                 {
7106                   tree condition = 
7107                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7108                                  tf_warning_or_error, NULL_TREE,
7109                                  /*integral_constant_expression_p=*/true);
7110                   finish_static_assert (condition,
7111                                         STATIC_ASSERT_MESSAGE (t), 
7112                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7113                                         /*member_p=*/true);
7114                 }
7115               else if (TREE_CODE (t) != CONST_DECL)
7116                 {
7117                   tree r;
7118
7119                   /* The file and line for this declaration, to
7120                      assist in error message reporting.  Since we
7121                      called push_tinst_level above, we don't need to
7122                      restore these.  */
7123                   input_location = DECL_SOURCE_LOCATION (t);
7124
7125                   if (TREE_CODE (t) == TEMPLATE_DECL)
7126                     ++processing_template_decl;
7127                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7128                   if (TREE_CODE (t) == TEMPLATE_DECL)
7129                     --processing_template_decl;
7130                   if (TREE_CODE (r) == VAR_DECL)
7131                     {
7132                       /* In [temp.inst]:
7133
7134                            [t]he initialization (and any associated
7135                            side-effects) of a static data member does
7136                            not occur unless the static data member is
7137                            itself used in a way that requires the
7138                            definition of the static data member to
7139                            exist.
7140
7141                          Therefore, we do not substitute into the
7142                          initialized for the static data member here.  */
7143                       finish_static_data_member_decl
7144                         (r,
7145                          /*init=*/NULL_TREE,
7146                          /*init_const_expr_p=*/false,
7147                          /*asmspec_tree=*/NULL_TREE,
7148                          /*flags=*/0);
7149                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7150                         check_static_variable_definition (r, TREE_TYPE (r));
7151                     }
7152                   else if (TREE_CODE (r) == FIELD_DECL)
7153                     {
7154                       /* Determine whether R has a valid type and can be
7155                          completed later.  If R is invalid, then it is
7156                          replaced by error_mark_node so that it will not be
7157                          added to TYPE_FIELDS.  */
7158                       tree rtype = TREE_TYPE (r);
7159                       if (can_complete_type_without_circularity (rtype))
7160                         complete_type (rtype);
7161
7162                       if (!COMPLETE_TYPE_P (rtype))
7163                         {
7164                           cxx_incomplete_type_error (r, rtype);
7165                           r = error_mark_node;
7166                         }
7167                     }
7168
7169                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7170                      such a thing will already have been added to the field
7171                      list by tsubst_enum in finish_member_declaration in the
7172                      CLASSTYPE_NESTED_UTDS case above.  */
7173                   if (!(TREE_CODE (r) == TYPE_DECL
7174                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7175                         && DECL_ARTIFICIAL (r)))
7176                     {
7177                       set_current_access_from_decl (r);
7178                       finish_member_declaration (r);
7179                     }
7180                 }
7181             }
7182         }
7183       else
7184         {
7185           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7186             {
7187               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7188
7189               tree friend_type = t;
7190               bool adjust_processing_template_decl = false;
7191
7192               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7193                 {
7194                   /* template <class T> friend class C;  */
7195                   friend_type = tsubst_friend_class (friend_type, args);
7196                   adjust_processing_template_decl = true;
7197                 }
7198               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7199                 {
7200                   /* template <class T> friend class C::D;  */
7201                   friend_type = tsubst (friend_type, args,
7202                                         tf_warning_or_error, NULL_TREE);
7203                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7204                     friend_type = TREE_TYPE (friend_type);
7205                   adjust_processing_template_decl = true;
7206                 }
7207               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7208                 {
7209                   /* This could be either
7210
7211                        friend class T::C;
7212
7213                      when dependent_type_p is false or
7214
7215                        template <class U> friend class T::C;
7216
7217                      otherwise.  */
7218                   friend_type = tsubst (friend_type, args,
7219                                         tf_warning_or_error, NULL_TREE);
7220                   /* Bump processing_template_decl for correct
7221                      dependent_type_p calculation.  */
7222                   ++processing_template_decl;
7223                   if (dependent_type_p (friend_type))
7224                     adjust_processing_template_decl = true;
7225                   --processing_template_decl;
7226                 }
7227               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7228                        && hidden_name_p (TYPE_NAME (friend_type)))
7229                 {
7230                   /* friend class C;
7231
7232                      where C hasn't been declared yet.  Let's lookup name
7233                      from namespace scope directly, bypassing any name that
7234                      come from dependent base class.  */
7235                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7236
7237                   /* The call to xref_tag_from_type does injection for friend
7238                      classes.  */
7239                   push_nested_namespace (ns);
7240                   friend_type =
7241                     xref_tag_from_type (friend_type, NULL_TREE,
7242                                         /*tag_scope=*/ts_current);
7243                   pop_nested_namespace (ns);
7244                 }
7245               else if (uses_template_parms (friend_type))
7246                 /* friend class C<T>;  */
7247                 friend_type = tsubst (friend_type, args,
7248                                       tf_warning_or_error, NULL_TREE);
7249               /* Otherwise it's
7250
7251                    friend class C;
7252
7253                  where C is already declared or
7254
7255                    friend class C<int>;
7256
7257                  We don't have to do anything in these cases.  */
7258
7259               if (adjust_processing_template_decl)
7260                 /* Trick make_friend_class into realizing that the friend
7261                    we're adding is a template, not an ordinary class.  It's
7262                    important that we use make_friend_class since it will
7263                    perform some error-checking and output cross-reference
7264                    information.  */
7265                 ++processing_template_decl;
7266
7267               if (friend_type != error_mark_node)
7268                 make_friend_class (type, friend_type, /*complain=*/false);
7269
7270               if (adjust_processing_template_decl)
7271                 --processing_template_decl;
7272             }
7273           else
7274             {
7275               /* Build new DECL_FRIENDLIST.  */
7276               tree r;
7277
7278               /* The file and line for this declaration, to
7279                  assist in error message reporting.  Since we
7280                  called push_tinst_level above, we don't need to
7281                  restore these.  */
7282               input_location = DECL_SOURCE_LOCATION (t);
7283
7284               if (TREE_CODE (t) == TEMPLATE_DECL)
7285                 {
7286                   ++processing_template_decl;
7287                   push_deferring_access_checks (dk_no_check);
7288                 }
7289
7290               r = tsubst_friend_function (t, args);
7291               add_friend (type, r, /*complain=*/false);
7292               if (TREE_CODE (t) == TEMPLATE_DECL)
7293                 {
7294                   pop_deferring_access_checks ();
7295                   --processing_template_decl;
7296                 }
7297             }
7298         }
7299     }
7300
7301   /* Set the file and line number information to whatever is given for
7302      the class itself.  This puts error messages involving generated
7303      implicit functions at a predictable point, and the same point
7304      that would be used for non-template classes.  */
7305   input_location = DECL_SOURCE_LOCATION (typedecl);
7306
7307   unreverse_member_declarations (type);
7308   finish_struct_1 (type);
7309   TYPE_BEING_DEFINED (type) = 0;
7310
7311   /* Now that the class is complete, instantiate default arguments for
7312      any member functions.  We don't do this earlier because the
7313      default arguments may reference members of the class.  */
7314   if (!PRIMARY_TEMPLATE_P (templ))
7315     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7316       if (TREE_CODE (t) == FUNCTION_DECL
7317           /* Implicitly generated member functions will not have template
7318              information; they are not instantiations, but instead are
7319              created "fresh" for each instantiation.  */
7320           && DECL_TEMPLATE_INFO (t))
7321         tsubst_default_arguments (t);
7322
7323   pop_nested_class ();
7324   pop_from_top_level ();
7325   pop_deferring_access_checks ();
7326   pop_tinst_level ();
7327
7328   /* The vtable for a template class can be emitted in any translation
7329      unit in which the class is instantiated.  When there is no key
7330      method, however, finish_struct_1 will already have added TYPE to
7331      the keyed_classes list.  */
7332   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7333     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7334
7335   return type;
7336 }
7337
7338 static tree
7339 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7340 {
7341   tree r;
7342
7343   if (!t)
7344     r = t;
7345   else if (TYPE_P (t))
7346     r = tsubst (t, args, complain, in_decl);
7347   else
7348     {
7349       r = tsubst_expr (t, args, complain, in_decl,
7350                        /*integral_constant_expression_p=*/true);
7351       r = fold_non_dependent_expr (r);
7352     }
7353   return r;
7354 }
7355
7356 /* Substitute ARGS into T, which is an pack expansion
7357    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7358    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7359    (if only a partial substitution could be performed) or
7360    ERROR_MARK_NODE if there was an error.  */
7361 tree
7362 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7363                        tree in_decl)
7364 {
7365   tree pattern;
7366   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7367   tree first_arg_pack; int i, len = -1;
7368   tree result;
7369   int incomplete = 0;
7370
7371   gcc_assert (PACK_EXPANSION_P (t));
7372   pattern = PACK_EXPANSION_PATTERN (t);
7373
7374   /* Determine the argument packs that will instantiate the parameter
7375      packs used in the expansion expression. While we're at it,
7376      compute the number of arguments to be expanded and make sure it
7377      is consistent.  */
7378   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7379        pack = TREE_CHAIN (pack))
7380     {
7381       tree parm_pack = TREE_VALUE (pack);
7382       tree arg_pack = NULL_TREE;
7383       tree orig_arg = NULL_TREE;
7384
7385       if (TREE_CODE (parm_pack) == PARM_DECL)
7386         arg_pack = retrieve_local_specialization (parm_pack);
7387       else
7388         {
7389           int level, idx, levels;
7390           template_parm_level_and_index (parm_pack, &level, &idx);
7391
7392           levels = TMPL_ARGS_DEPTH (args);
7393           if (level <= levels)
7394             arg_pack = TMPL_ARG (args, level, idx);
7395         }
7396
7397       orig_arg = arg_pack;
7398       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7399         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7400       
7401       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7402         /* This can only happen if we forget to expand an argument
7403            pack somewhere else. Just return an error, silently.  */
7404         {
7405           result = make_tree_vec (1);
7406           TREE_VEC_ELT (result, 0) = error_mark_node;
7407           return result;
7408         }
7409
7410       if (arg_pack
7411           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
7412           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
7413         {
7414           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
7415           tree pattern = PACK_EXPANSION_PATTERN (expansion);
7416           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
7417               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
7418             /* The argument pack that the parameter maps to is just an
7419                expansion of the parameter itself, such as one would
7420                find in the implicit typedef of a class inside the
7421                class itself.  Consider this parameter "unsubstituted",
7422                so that we will maintain the outer pack expansion.  */
7423             arg_pack = NULL_TREE;
7424         }
7425           
7426       if (arg_pack)
7427         {
7428           int my_len = 
7429             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7430
7431           /* It's all-or-nothing with incomplete argument packs.  */
7432           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7433             return error_mark_node;
7434           
7435           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7436             incomplete = 1;
7437
7438           if (len < 0)
7439             {
7440               len = my_len;
7441               first_arg_pack = arg_pack;
7442             }
7443           else if (len != my_len)
7444             {
7445               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
7446                 error ("mismatched argument pack lengths while expanding "
7447                        "%<%T%>",
7448                        pattern);
7449               else
7450                 error ("mismatched argument pack lengths while expanding "
7451                        "%<%E%>",
7452                        pattern);
7453               return error_mark_node;
7454             }
7455
7456           /* Keep track of the parameter packs and their corresponding
7457              argument packs.  */
7458           packs = tree_cons (parm_pack, arg_pack, packs);
7459           TREE_TYPE (packs) = orig_arg;
7460         }
7461       else
7462         /* We can't substitute for this parameter pack.  */
7463         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
7464                                          TREE_VALUE (pack),
7465                                          unsubstituted_packs);
7466     }
7467
7468   /* We cannot expand this expansion expression, because we don't have
7469      all of the argument packs we need. Substitute into the pattern
7470      and return a PACK_EXPANSION_*. The caller will need to deal with
7471      that.  */
7472   if (unsubstituted_packs)
7473     return make_pack_expansion (tsubst (pattern, args, complain, 
7474                                         in_decl));
7475
7476   /* We could not find any argument packs that work.  */
7477   if (len < 0)
7478     return error_mark_node;
7479
7480   /* For each argument in each argument pack, substitute into the
7481      pattern.  */
7482   result = make_tree_vec (len + incomplete);
7483   for (i = 0; i < len + incomplete; ++i)
7484     {
7485       /* For parameter pack, change the substitution of the parameter
7486          pack to the ith argument in its argument pack, then expand
7487          the pattern.  */
7488       for (pack = packs; pack; pack = TREE_CHAIN (pack))
7489         {
7490           tree parm = TREE_PURPOSE (pack);
7491
7492           if (TREE_CODE (parm) == PARM_DECL)
7493             {
7494               /* Select the Ith argument from the pack.  */
7495               tree arg = make_node (ARGUMENT_PACK_SELECT);
7496               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
7497               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
7498               mark_used (parm);
7499               register_local_specialization (arg, parm);
7500             }
7501           else
7502             {
7503               tree value = parm;
7504               int idx, level;
7505               template_parm_level_and_index (parm, &level, &idx);
7506               
7507               if (i < len) 
7508                 {
7509                   /* Select the Ith argument from the pack. */
7510                   value = make_node (ARGUMENT_PACK_SELECT);
7511                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
7512                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
7513                 }
7514
7515               /* Update the corresponding argument.  */
7516               TMPL_ARG (args, level, idx) = value;
7517             }
7518         }
7519
7520       /* Substitute into the PATTERN with the altered arguments.  */
7521       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7522         TREE_VEC_ELT (result, i) = 
7523           tsubst_expr (pattern, args, complain, in_decl,
7524                        /*integral_constant_expression_p=*/false);
7525       else
7526         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
7527
7528       if (i == len)
7529         /* When we have incomplete argument packs, the last "expanded"
7530            result is itself a pack expansion, which allows us
7531            to deduce more arguments.  */
7532         TREE_VEC_ELT (result, i) = 
7533           make_pack_expansion (TREE_VEC_ELT (result, i));
7534
7535       if (TREE_VEC_ELT (result, i) == error_mark_node)
7536         {
7537           result = error_mark_node;
7538           break;
7539         }
7540     }
7541   
7542   /* Update ARGS to restore the substitution from parameter packs to
7543      their argument packs.  */
7544   for (pack = packs; pack; pack = TREE_CHAIN (pack))
7545     {
7546       tree parm = TREE_PURPOSE (pack);
7547
7548       if (TREE_CODE (parm) == PARM_DECL)
7549         register_local_specialization (TREE_TYPE (pack), parm);
7550       else
7551         {
7552           int idx, level;
7553           template_parm_level_and_index (parm, &level, &idx);
7554           
7555           /* Update the corresponding argument.  */
7556           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
7557             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
7558               TREE_TYPE (pack);
7559           else
7560             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
7561         }
7562     }
7563
7564   return result;
7565 }
7566
7567 /* Substitute ARGS into the vector or list of template arguments T.  */
7568
7569 static tree
7570 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7571 {
7572   tree orig_t = t;
7573   int len = TREE_VEC_LENGTH (t);
7574   int need_new = 0, i, expanded_len_adjust = 0, out;
7575   tree *elts = (tree *) alloca (len * sizeof (tree));
7576
7577   for (i = 0; i < len; i++)
7578     {
7579       tree orig_arg = TREE_VEC_ELT (t, i);
7580       tree new_arg;
7581
7582       if (TREE_CODE (orig_arg) == TREE_VEC)
7583         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
7584       else if (PACK_EXPANSION_P (orig_arg))
7585         {
7586           /* Substitute into an expansion expression.  */
7587           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
7588
7589           if (TREE_CODE (new_arg) == TREE_VEC)
7590             /* Add to the expanded length adjustment the number of
7591                expanded arguments. We subtract one from this
7592                measurement, because the argument pack expression
7593                itself is already counted as 1 in
7594                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
7595                the argument pack is empty.  */
7596             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
7597         }
7598       else if (ARGUMENT_PACK_P (orig_arg))
7599         {
7600           /* Substitute into each of the arguments.  */
7601           new_arg = make_node (TREE_CODE (orig_arg));
7602           
7603           SET_ARGUMENT_PACK_ARGS (
7604             new_arg,
7605             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
7606                                   args, complain, in_decl));
7607
7608           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
7609             new_arg = error_mark_node;
7610
7611           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
7612             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
7613                                           complain, in_decl);
7614             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
7615
7616             if (TREE_TYPE (new_arg) == error_mark_node)
7617               new_arg = error_mark_node;
7618           }
7619         }
7620       else
7621         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
7622
7623       if (new_arg == error_mark_node)
7624         return error_mark_node;
7625
7626       elts[i] = new_arg;
7627       if (new_arg != orig_arg)
7628         need_new = 1;
7629     }
7630
7631   if (!need_new)
7632     return t;
7633
7634   /* Make space for the expanded arguments coming from template
7635      argument packs.  */
7636   t = make_tree_vec (len + expanded_len_adjust);
7637   for (i = 0, out = 0; i < len; i++)
7638     {
7639       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
7640            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
7641           && TREE_CODE (elts[i]) == TREE_VEC)
7642         {
7643           int idx;
7644
7645           /* Now expand the template argument pack "in place".  */
7646           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
7647             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
7648         }
7649       else
7650         {
7651           TREE_VEC_ELT (t, out) = elts[i];
7652           out++;
7653         }
7654     }
7655
7656   return t;
7657 }
7658
7659 /* Return the result of substituting ARGS into the template parameters
7660    given by PARMS.  If there are m levels of ARGS and m + n levels of
7661    PARMS, then the result will contain n levels of PARMS.  For
7662    example, if PARMS is `template <class T> template <class U>
7663    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
7664    result will be `template <int*, double, class V>'.  */
7665
7666 static tree
7667 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
7668 {
7669   tree r = NULL_TREE;
7670   tree* new_parms;
7671
7672   /* When substituting into a template, we must set
7673      PROCESSING_TEMPLATE_DECL as the template parameters may be
7674      dependent if they are based on one-another, and the dependency
7675      predicates are short-circuit outside of templates.  */
7676   ++processing_template_decl;
7677
7678   for (new_parms = &r;
7679        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
7680        new_parms = &(TREE_CHAIN (*new_parms)),
7681          parms = TREE_CHAIN (parms))
7682     {
7683       tree new_vec =
7684         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
7685       int i;
7686
7687       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
7688         {
7689           tree tuple;
7690           tree default_value;
7691           tree parm_decl;
7692
7693           if (parms == error_mark_node)
7694             continue;
7695
7696           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
7697
7698           if (tuple == error_mark_node)
7699             continue;
7700
7701           default_value = TREE_PURPOSE (tuple);
7702           parm_decl = TREE_VALUE (tuple);
7703
7704           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
7705           if (TREE_CODE (parm_decl) == PARM_DECL
7706               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
7707             parm_decl = error_mark_node;
7708           default_value = tsubst_template_arg (default_value, args,
7709                                                complain, NULL_TREE);
7710
7711           tuple = build_tree_list (default_value, parm_decl);
7712           TREE_VEC_ELT (new_vec, i) = tuple;
7713         }
7714
7715       *new_parms =
7716         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
7717                              - TMPL_ARGS_DEPTH (args)),
7718                    new_vec, NULL_TREE);
7719     }
7720
7721   --processing_template_decl;
7722
7723   return r;
7724 }
7725
7726 /* Substitute the ARGS into the indicated aggregate (or enumeration)
7727    type T.  If T is not an aggregate or enumeration type, it is
7728    handled as if by tsubst.  IN_DECL is as for tsubst.  If
7729    ENTERING_SCOPE is nonzero, T is the context for a template which
7730    we are presently tsubst'ing.  Return the substituted value.  */
7731
7732 static tree
7733 tsubst_aggr_type (tree t,
7734                   tree args,
7735                   tsubst_flags_t complain,
7736                   tree in_decl,
7737                   int entering_scope)
7738 {
7739   if (t == NULL_TREE)
7740     return NULL_TREE;
7741
7742   switch (TREE_CODE (t))
7743     {
7744     case RECORD_TYPE:
7745       if (TYPE_PTRMEMFUNC_P (t))
7746         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
7747
7748       /* Else fall through.  */
7749     case ENUMERAL_TYPE:
7750     case UNION_TYPE:
7751       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
7752         {
7753           tree argvec;
7754           tree context;
7755           tree r;
7756           bool saved_skip_evaluation;
7757
7758           /* In "sizeof(X<I>)" we need to evaluate "I".  */
7759           saved_skip_evaluation = skip_evaluation;
7760           skip_evaluation = false;
7761
7762           /* First, determine the context for the type we are looking
7763              up.  */
7764           context = TYPE_CONTEXT (t);
7765           if (context)
7766             {
7767               context = tsubst_aggr_type (context, args, complain,
7768                                           in_decl, /*entering_scope=*/1);
7769               /* If context is a nested class inside a class template,
7770                  it may still need to be instantiated (c++/33959).  */
7771               if (TYPE_P (context))
7772                 context = complete_type (context);
7773             }
7774
7775           /* Then, figure out what arguments are appropriate for the
7776              type we are trying to find.  For example, given:
7777
7778                template <class T> struct S;
7779                template <class T, class U> void f(T, U) { S<U> su; }
7780
7781              and supposing that we are instantiating f<int, double>,
7782              then our ARGS will be {int, double}, but, when looking up
7783              S we only want {double}.  */
7784           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
7785                                          complain, in_decl);
7786           if (argvec == error_mark_node)
7787             r = error_mark_node;
7788           else
7789             {
7790               r = lookup_template_class (t, argvec, in_decl, context,
7791                                          entering_scope, complain);
7792               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
7793             }
7794
7795           skip_evaluation = saved_skip_evaluation;
7796
7797           return r;
7798         }
7799       else
7800         /* This is not a template type, so there's nothing to do.  */
7801         return t;
7802
7803     default:
7804       return tsubst (t, args, complain, in_decl);
7805     }
7806 }
7807
7808 /* Substitute into the default argument ARG (a default argument for
7809    FN), which has the indicated TYPE.  */
7810
7811 tree
7812 tsubst_default_argument (tree fn, tree type, tree arg)
7813 {
7814   tree saved_class_ptr = NULL_TREE;
7815   tree saved_class_ref = NULL_TREE;
7816
7817   /* This default argument came from a template.  Instantiate the
7818      default argument here, not in tsubst.  In the case of
7819      something like:
7820
7821        template <class T>
7822        struct S {
7823          static T t();
7824          void f(T = t());
7825        };
7826
7827      we must be careful to do name lookup in the scope of S<T>,
7828      rather than in the current class.  */
7829   push_access_scope (fn);
7830   /* The "this" pointer is not valid in a default argument.  */
7831   if (cfun)
7832     {
7833       saved_class_ptr = current_class_ptr;
7834       cp_function_chain->x_current_class_ptr = NULL_TREE;
7835       saved_class_ref = current_class_ref;
7836       cp_function_chain->x_current_class_ref = NULL_TREE;
7837     }
7838
7839   push_deferring_access_checks(dk_no_deferred);
7840   /* The default argument expression may cause implicitly defined
7841      member functions to be synthesized, which will result in garbage
7842      collection.  We must treat this situation as if we were within
7843      the body of function so as to avoid collecting live data on the
7844      stack.  */
7845   ++function_depth;
7846   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
7847                      tf_warning_or_error, NULL_TREE,
7848                      /*integral_constant_expression_p=*/false);
7849   --function_depth;
7850   pop_deferring_access_checks();
7851
7852   /* Restore the "this" pointer.  */
7853   if (cfun)
7854     {
7855       cp_function_chain->x_current_class_ptr = saved_class_ptr;
7856       cp_function_chain->x_current_class_ref = saved_class_ref;
7857     }
7858
7859   pop_access_scope (fn);
7860
7861   /* Make sure the default argument is reasonable.  */
7862   arg = check_default_argument (type, arg);
7863
7864   return arg;
7865 }
7866
7867 /* Substitute into all the default arguments for FN.  */
7868
7869 static void
7870 tsubst_default_arguments (tree fn)
7871 {
7872   tree arg;
7873   tree tmpl_args;
7874
7875   tmpl_args = DECL_TI_ARGS (fn);
7876
7877   /* If this function is not yet instantiated, we certainly don't need
7878      its default arguments.  */
7879   if (uses_template_parms (tmpl_args))
7880     return;
7881
7882   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
7883        arg;
7884        arg = TREE_CHAIN (arg))
7885     if (TREE_PURPOSE (arg))
7886       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
7887                                                     TREE_VALUE (arg),
7888                                                     TREE_PURPOSE (arg));
7889 }
7890
7891 /* Substitute the ARGS into the T, which is a _DECL.  Return the
7892    result of the substitution.  Issue error and warning messages under
7893    control of COMPLAIN.  */
7894
7895 static tree
7896 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
7897 {
7898   location_t saved_loc;
7899   tree r = NULL_TREE;
7900   tree in_decl = t;
7901
7902   /* Set the filename and linenumber to improve error-reporting.  */
7903   saved_loc = input_location;
7904   input_location = DECL_SOURCE_LOCATION (t);
7905
7906   switch (TREE_CODE (t))
7907     {
7908     case TEMPLATE_DECL:
7909       {
7910         /* We can get here when processing a member function template,
7911            member class template, and template template parameter of
7912            a template class.  */
7913         tree decl = DECL_TEMPLATE_RESULT (t);
7914         tree spec;
7915         tree tmpl_args;
7916         tree full_args;
7917
7918         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
7919           {
7920             /* Template template parameter is treated here.  */
7921             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7922             if (new_type == error_mark_node)
7923               return error_mark_node;
7924
7925             r = copy_decl (t);
7926             TREE_CHAIN (r) = NULL_TREE;
7927             TREE_TYPE (r) = new_type;
7928             DECL_TEMPLATE_RESULT (r)
7929               = build_decl (TYPE_DECL, DECL_NAME (decl), new_type);
7930             DECL_TEMPLATE_PARMS (r)
7931               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
7932                                        complain);
7933             TYPE_NAME (new_type) = r;
7934             break;
7935           }
7936
7937         /* We might already have an instance of this template.
7938            The ARGS are for the surrounding class type, so the
7939            full args contain the tsubst'd args for the context,
7940            plus the innermost args from the template decl.  */
7941         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
7942           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
7943           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
7944         /* Because this is a template, the arguments will still be
7945            dependent, even after substitution.  If
7946            PROCESSING_TEMPLATE_DECL is not set, the dependency
7947            predicates will short-circuit.  */
7948         ++processing_template_decl;
7949         full_args = tsubst_template_args (tmpl_args, args,
7950                                           complain, in_decl);
7951         --processing_template_decl;
7952         if (full_args == error_mark_node)
7953           return error_mark_node;
7954
7955         /* tsubst_template_args doesn't copy the vector if
7956            nothing changed.  But, *something* should have
7957            changed.  */
7958         gcc_assert (full_args != tmpl_args);
7959
7960         spec = retrieve_specialization (t, full_args,
7961                                         /*class_specializations_p=*/true);
7962         if (spec != NULL_TREE)
7963           {
7964             r = spec;
7965             break;
7966           }
7967
7968         /* Make a new template decl.  It will be similar to the
7969            original, but will record the current template arguments.
7970            We also create a new function declaration, which is just
7971            like the old one, but points to this new template, rather
7972            than the old one.  */
7973         r = copy_decl (t);
7974         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
7975         TREE_CHAIN (r) = NULL_TREE;
7976
7977         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
7978
7979         if (TREE_CODE (decl) == TYPE_DECL)
7980           {
7981             tree new_type;
7982             ++processing_template_decl;
7983             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7984             --processing_template_decl;
7985             if (new_type == error_mark_node)
7986               return error_mark_node;
7987
7988             TREE_TYPE (r) = new_type;
7989             CLASSTYPE_TI_TEMPLATE (new_type) = r;
7990             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
7991             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
7992             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
7993           }
7994         else
7995           {
7996             tree new_decl;
7997             ++processing_template_decl;
7998             new_decl = tsubst (decl, args, complain, in_decl);
7999             --processing_template_decl;
8000             if (new_decl == error_mark_node)
8001               return error_mark_node;
8002
8003             DECL_TEMPLATE_RESULT (r) = new_decl;
8004             DECL_TI_TEMPLATE (new_decl) = r;
8005             TREE_TYPE (r) = TREE_TYPE (new_decl);
8006             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8007             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8008           }
8009
8010         SET_DECL_IMPLICIT_INSTANTIATION (r);
8011         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8012         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8013
8014         /* The template parameters for this new template are all the
8015            template parameters for the old template, except the
8016            outermost level of parameters.  */
8017         DECL_TEMPLATE_PARMS (r)
8018           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8019                                    complain);
8020
8021         if (PRIMARY_TEMPLATE_P (t))
8022           DECL_PRIMARY_TEMPLATE (r) = r;
8023
8024         if (TREE_CODE (decl) != TYPE_DECL)
8025           /* Record this non-type partial instantiation.  */
8026           register_specialization (r, t,
8027                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8028                                    false);
8029       }
8030       break;
8031
8032     case FUNCTION_DECL:
8033       {
8034         tree ctx;
8035         tree argvec = NULL_TREE;
8036         tree *friends;
8037         tree gen_tmpl;
8038         tree type;
8039         int member;
8040         int args_depth;
8041         int parms_depth;
8042
8043         /* Nobody should be tsubst'ing into non-template functions.  */
8044         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8045
8046         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8047           {
8048             tree spec;
8049             bool dependent_p;
8050
8051             /* If T is not dependent, just return it.  We have to
8052                increment PROCESSING_TEMPLATE_DECL because
8053                value_dependent_expression_p assumes that nothing is
8054                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8055             ++processing_template_decl;
8056             dependent_p = value_dependent_expression_p (t);
8057             --processing_template_decl;
8058             if (!dependent_p)
8059               return t;
8060
8061             /* Calculate the most general template of which R is a
8062                specialization, and the complete set of arguments used to
8063                specialize R.  */
8064             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8065             argvec = tsubst_template_args (DECL_TI_ARGS
8066                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8067                                            args, complain, in_decl);
8068
8069             /* Check to see if we already have this specialization.  */
8070             spec = retrieve_specialization (gen_tmpl, argvec,
8071                                             /*class_specializations_p=*/false);
8072
8073             if (spec)
8074               {
8075                 r = spec;
8076                 break;
8077               }
8078
8079             /* We can see more levels of arguments than parameters if
8080                there was a specialization of a member template, like
8081                this:
8082
8083                  template <class T> struct S { template <class U> void f(); }
8084                  template <> template <class U> void S<int>::f(U);
8085
8086                Here, we'll be substituting into the specialization,
8087                because that's where we can find the code we actually
8088                want to generate, but we'll have enough arguments for
8089                the most general template.
8090
8091                We also deal with the peculiar case:
8092
8093                  template <class T> struct S {
8094                    template <class U> friend void f();
8095                  };
8096                  template <class U> void f() {}
8097                  template S<int>;
8098                  template void f<double>();
8099
8100                Here, the ARGS for the instantiation of will be {int,
8101                double}.  But, we only need as many ARGS as there are
8102                levels of template parameters in CODE_PATTERN.  We are
8103                careful not to get fooled into reducing the ARGS in
8104                situations like:
8105
8106                  template <class T> struct S { template <class U> void f(U); }
8107                  template <class T> template <> void S<T>::f(int) {}
8108
8109                which we can spot because the pattern will be a
8110                specialization in this case.  */
8111             args_depth = TMPL_ARGS_DEPTH (args);
8112             parms_depth =
8113               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8114             if (args_depth > parms_depth
8115                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8116               args = get_innermost_template_args (args, parms_depth);
8117           }
8118         else
8119           {
8120             /* This special case arises when we have something like this:
8121
8122                  template <class T> struct S {
8123                    friend void f<int>(int, double);
8124                  };
8125
8126                Here, the DECL_TI_TEMPLATE for the friend declaration
8127                will be an IDENTIFIER_NODE.  We are being called from
8128                tsubst_friend_function, and we want only to create a
8129                new decl (R) with appropriate types so that we can call
8130                determine_specialization.  */
8131             gen_tmpl = NULL_TREE;
8132           }
8133
8134         if (DECL_CLASS_SCOPE_P (t))
8135           {
8136             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8137               member = 2;
8138             else
8139               member = 1;
8140             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8141                                     complain, t, /*entering_scope=*/1);
8142           }
8143         else
8144           {
8145             member = 0;
8146             ctx = DECL_CONTEXT (t);
8147           }
8148         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8149         if (type == error_mark_node)
8150           return error_mark_node;
8151
8152         /* We do NOT check for matching decls pushed separately at this
8153            point, as they may not represent instantiations of this
8154            template, and in any case are considered separate under the
8155            discrete model.  */
8156         r = copy_decl (t);
8157         DECL_USE_TEMPLATE (r) = 0;
8158         TREE_TYPE (r) = type;
8159         /* Clear out the mangled name and RTL for the instantiation.  */
8160         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8161         SET_DECL_RTL (r, NULL_RTX);
8162         /* Leave DECL_INITIAL set on deleted instantiations.  */
8163         if (!DECL_DELETED_FN (r))
8164           DECL_INITIAL (r) = NULL_TREE;
8165         DECL_CONTEXT (r) = ctx;
8166
8167         if (member && DECL_CONV_FN_P (r))
8168           /* Type-conversion operator.  Reconstruct the name, in
8169              case it's the name of one of the template's parameters.  */
8170           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8171
8172         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8173                                      complain, t);
8174         DECL_RESULT (r) = NULL_TREE;
8175
8176         TREE_STATIC (r) = 0;
8177         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8178         DECL_EXTERNAL (r) = 1;
8179         /* If this is an instantiation of a function with internal
8180            linkage, we already know what object file linkage will be
8181            assigned to the instantiation.  */
8182         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8183         DECL_DEFER_OUTPUT (r) = 0;
8184         TREE_CHAIN (r) = NULL_TREE;
8185         DECL_PENDING_INLINE_INFO (r) = 0;
8186         DECL_PENDING_INLINE_P (r) = 0;
8187         DECL_SAVED_TREE (r) = NULL_TREE;
8188         DECL_STRUCT_FUNCTION (r) = NULL;
8189         TREE_USED (r) = 0;
8190         if (DECL_CLONED_FUNCTION (r))
8191           {
8192             DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
8193                                                args, complain, t);
8194             TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
8195             TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
8196           }
8197
8198         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8199            this in the special friend case mentioned above where
8200            GEN_TMPL is NULL.  */
8201         if (gen_tmpl)
8202           {
8203             DECL_TEMPLATE_INFO (r)
8204               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8205             SET_DECL_IMPLICIT_INSTANTIATION (r);
8206             register_specialization (r, gen_tmpl, argvec, false);
8207
8208             /* We're not supposed to instantiate default arguments
8209                until they are called, for a template.  But, for a
8210                declaration like:
8211
8212                  template <class T> void f ()
8213                  { extern void g(int i = T()); }
8214
8215                we should do the substitution when the template is
8216                instantiated.  We handle the member function case in
8217                instantiate_class_template since the default arguments
8218                might refer to other members of the class.  */
8219             if (!member
8220                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8221                 && !uses_template_parms (argvec))
8222               tsubst_default_arguments (r);
8223           }
8224         else
8225           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8226
8227         /* Copy the list of befriending classes.  */
8228         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8229              *friends;
8230              friends = &TREE_CHAIN (*friends))
8231           {
8232             *friends = copy_node (*friends);
8233             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8234                                             args, complain,
8235                                             in_decl);
8236           }
8237
8238         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8239           {
8240             maybe_retrofit_in_chrg (r);
8241             if (DECL_CONSTRUCTOR_P (r))
8242               grok_ctor_properties (ctx, r);
8243             /* If this is an instantiation of a member template, clone it.
8244                If it isn't, that'll be handled by
8245                clone_constructors_and_destructors.  */
8246             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8247               clone_function_decl (r, /*update_method_vec_p=*/0);
8248           }
8249         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r))
8250                  && !grok_op_properties (r, (complain & tf_error) != 0))
8251           return error_mark_node;
8252
8253         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8254           SET_DECL_FRIEND_CONTEXT (r,
8255                                    tsubst (DECL_FRIEND_CONTEXT (t),
8256                                             args, complain, in_decl));
8257
8258         /* Possibly limit visibility based on template args.  */
8259         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8260         if (DECL_VISIBILITY_SPECIFIED (t))
8261           {
8262             DECL_VISIBILITY_SPECIFIED (r) = 0;
8263             DECL_ATTRIBUTES (r)
8264               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8265           }
8266         determine_visibility (r);
8267
8268         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8269                                         args, complain, in_decl);
8270       }
8271       break;
8272
8273     case PARM_DECL:
8274       {
8275         tree type = NULL_TREE;
8276         int i, len = 1;
8277         tree expanded_types = NULL_TREE;
8278         tree prev_r = NULL_TREE;
8279         tree first_r = NULL_TREE;
8280
8281         if (FUNCTION_PARAMETER_PACK_P (t))
8282           {
8283             /* If there is a local specialization that isn't a
8284                parameter pack, it means that we're doing a "simple"
8285                substitution from inside tsubst_pack_expansion. Just
8286                return the local specialization (which will be a single
8287                parm).  */
8288             tree spec = retrieve_local_specialization (t);
8289             if (spec 
8290                 && TREE_CODE (spec) == PARM_DECL
8291                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8292               return spec;
8293
8294             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8295                the parameters in this function parameter pack.  */
8296             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8297                                                     complain, in_decl);
8298             if (TREE_CODE (expanded_types) == TREE_VEC)
8299               {
8300                 len = TREE_VEC_LENGTH (expanded_types);
8301
8302                 /* Zero-length parameter packs are boring. Just substitute
8303                    into the chain.  */
8304                 if (len == 0)
8305                   return tsubst (TREE_CHAIN (t), args, complain, 
8306                                  TREE_CHAIN (t));
8307               }
8308             else
8309               {
8310                 /* All we did was update the type. Make a note of that.  */
8311                 type = expanded_types;
8312                 expanded_types = NULL_TREE;
8313               }
8314           }
8315
8316         /* Loop through all of the parameter's we'll build. When T is
8317            a function parameter pack, LEN is the number of expanded
8318            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8319         r = NULL_TREE;
8320         for (i = 0; i < len; ++i)
8321           {
8322             prev_r = r;
8323             r = copy_node (t);
8324             if (DECL_TEMPLATE_PARM_P (t))
8325               SET_DECL_TEMPLATE_PARM_P (r);
8326
8327             if (expanded_types)
8328               /* We're on the Ith parameter of the function parameter
8329                  pack.  */
8330               {
8331                 /* Get the Ith type.  */
8332                 type = TREE_VEC_ELT (expanded_types, i);
8333
8334                 if (DECL_NAME (r))
8335                   /* Rename the parameter to include the index.  */
8336                   DECL_NAME (r) =
8337                     make_ith_pack_parameter_name (DECL_NAME (r), i);
8338               }
8339             else if (!type)
8340               /* We're dealing with a normal parameter.  */
8341               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8342
8343             type = type_decays_to (type);
8344             TREE_TYPE (r) = type;
8345             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8346
8347             if (DECL_INITIAL (r))
8348               {
8349                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
8350                   DECL_INITIAL (r) = TREE_TYPE (r);
8351                 else
8352                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
8353                                              complain, in_decl);
8354               }
8355
8356             DECL_CONTEXT (r) = NULL_TREE;
8357
8358             if (!DECL_TEMPLATE_PARM_P (r))
8359               DECL_ARG_TYPE (r) = type_passed_as (type);
8360
8361             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8362                                             args, complain, in_decl);
8363
8364             /* Keep track of the first new parameter we
8365                generate. That's what will be returned to the
8366                caller.  */
8367             if (!first_r)
8368               first_r = r;
8369
8370             /* Build a proper chain of parameters when substituting
8371                into a function parameter pack.  */
8372             if (prev_r)
8373               TREE_CHAIN (prev_r) = r;
8374           }
8375
8376         if (TREE_CHAIN (t))
8377           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
8378                                    complain, TREE_CHAIN (t));
8379
8380         /* FIRST_R contains the start of the chain we've built.  */
8381         r = first_r;
8382       }
8383       break;
8384
8385     case FIELD_DECL:
8386       {
8387         tree type;
8388
8389         r = copy_decl (t);
8390         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8391         if (type == error_mark_node)
8392           return error_mark_node;
8393         TREE_TYPE (r) = type;
8394         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8395
8396         /* DECL_INITIAL gives the number of bits in a bit-field.  */
8397         DECL_INITIAL (r)
8398           = tsubst_expr (DECL_INITIAL (t), args,
8399                          complain, in_decl,
8400                          /*integral_constant_expression_p=*/true);
8401         /* We don't have to set DECL_CONTEXT here; it is set by
8402            finish_member_declaration.  */
8403         TREE_CHAIN (r) = NULL_TREE;
8404         if (VOID_TYPE_P (type))
8405           error ("instantiation of %q+D as type %qT", r, type);
8406
8407         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8408                                         args, complain, in_decl);
8409       }
8410       break;
8411
8412     case USING_DECL:
8413       /* We reach here only for member using decls.  */
8414       if (DECL_DEPENDENT_P (t))
8415         {
8416           r = do_class_using_decl
8417             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
8418              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
8419           if (!r)
8420             r = error_mark_node;
8421         }
8422       else
8423         {
8424           r = copy_node (t);
8425           TREE_CHAIN (r) = NULL_TREE;
8426         }
8427       break;
8428
8429     case TYPE_DECL:
8430     case VAR_DECL:
8431       {
8432         tree argvec = NULL_TREE;
8433         tree gen_tmpl = NULL_TREE;
8434         tree spec;
8435         tree tmpl = NULL_TREE;
8436         tree ctx;
8437         tree type = NULL_TREE;
8438         bool local_p;
8439
8440         if (TREE_CODE (t) == TYPE_DECL
8441             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
8442           {
8443             /* If this is the canonical decl, we don't have to
8444                mess with instantiations, and often we can't (for
8445                typename, template type parms and such).  Note that
8446                TYPE_NAME is not correct for the above test if
8447                we've copied the type for a typedef.  */
8448             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8449             if (type == error_mark_node)
8450               return error_mark_node;
8451             r = TYPE_NAME (type);
8452             break;
8453           }
8454
8455         /* Check to see if we already have the specialization we
8456            need.  */
8457         spec = NULL_TREE;
8458         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
8459           {
8460             /* T is a static data member or namespace-scope entity.
8461                We have to substitute into namespace-scope variables
8462                (even though such entities are never templates) because
8463                of cases like:
8464                
8465                  template <class T> void f() { extern T t; }
8466
8467                where the entity referenced is not known until
8468                instantiation time.  */
8469             local_p = false;
8470             ctx = DECL_CONTEXT (t);
8471             if (DECL_CLASS_SCOPE_P (t))
8472               {
8473                 ctx = tsubst_aggr_type (ctx, args,
8474                                         complain,
8475                                         in_decl, /*entering_scope=*/1);
8476                 /* If CTX is unchanged, then T is in fact the
8477                    specialization we want.  That situation occurs when
8478                    referencing a static data member within in its own
8479                    class.  We can use pointer equality, rather than
8480                    same_type_p, because DECL_CONTEXT is always
8481                    canonical.  */
8482                 if (ctx == DECL_CONTEXT (t))
8483                   spec = t;
8484               }
8485
8486             if (!spec)
8487               {
8488                 tmpl = DECL_TI_TEMPLATE (t);
8489                 gen_tmpl = most_general_template (tmpl);
8490                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
8491                 spec = (retrieve_specialization 
8492                         (gen_tmpl, argvec,
8493                          /*class_specializations_p=*/false));
8494               }
8495           }
8496         else
8497           {
8498             /* A local variable.  */
8499             local_p = true;
8500             /* Subsequent calls to pushdecl will fill this in.  */
8501             ctx = NULL_TREE;
8502             spec = retrieve_local_specialization (t);
8503           }
8504         /* If we already have the specialization we need, there is
8505            nothing more to do.  */ 
8506         if (spec)
8507           {
8508             r = spec;
8509             break;
8510           }
8511
8512         /* Create a new node for the specialization we need.  */
8513         r = copy_decl (t);
8514         if (type == NULL_TREE)
8515           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8516         if (TREE_CODE (r) == VAR_DECL)
8517           {
8518             /* Even if the original location is out of scope, the
8519                newly substituted one is not.  */
8520             DECL_DEAD_FOR_LOCAL (r) = 0;
8521             DECL_INITIALIZED_P (r) = 0;
8522             DECL_TEMPLATE_INSTANTIATED (r) = 0;
8523             if (type == error_mark_node)
8524               return error_mark_node;
8525             if (TREE_CODE (type) == FUNCTION_TYPE)
8526               {
8527                 /* It may seem that this case cannot occur, since:
8528
8529                      typedef void f();
8530                      void g() { f x; }
8531
8532                    declares a function, not a variable.  However:
8533       
8534                      typedef void f();
8535                      template <typename T> void g() { T t; }
8536                      template void g<f>();
8537
8538                    is an attempt to declare a variable with function
8539                    type.  */
8540                 error ("variable %qD has function type",
8541                        /* R is not yet sufficiently initialized, so we
8542                           just use its name.  */
8543                        DECL_NAME (r));
8544                 return error_mark_node;
8545               }
8546             type = complete_type (type);
8547             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
8548               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
8549             type = check_var_type (DECL_NAME (r), type);
8550
8551             if (DECL_HAS_VALUE_EXPR_P (t))
8552               {
8553                 tree ve = DECL_VALUE_EXPR (t);
8554                 ve = tsubst_expr (ve, args, complain, in_decl,
8555                                   /*constant_expression_p=*/false);
8556                 SET_DECL_VALUE_EXPR (r, ve);
8557               }
8558           }
8559         else if (DECL_SELF_REFERENCE_P (t))
8560           SET_DECL_SELF_REFERENCE_P (r);
8561         TREE_TYPE (r) = type;
8562         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8563         DECL_CONTEXT (r) = ctx;
8564         /* Clear out the mangled name and RTL for the instantiation.  */
8565         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8566         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8567           SET_DECL_RTL (r, NULL_RTX);
8568         /* The initializer must not be expanded until it is required;
8569            see [temp.inst].  */
8570         DECL_INITIAL (r) = NULL_TREE;
8571         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8572           SET_DECL_RTL (r, NULL_RTX);
8573         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
8574         if (TREE_CODE (r) == VAR_DECL)
8575           {
8576             /* Possibly limit visibility based on template args.  */
8577             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8578             if (DECL_VISIBILITY_SPECIFIED (t))
8579               {
8580                 DECL_VISIBILITY_SPECIFIED (r) = 0;
8581                 DECL_ATTRIBUTES (r)
8582                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8583               }
8584             determine_visibility (r);
8585           }
8586         /* Preserve a typedef that names a type.  */
8587         else if (TREE_CODE (r) == TYPE_DECL
8588                  && DECL_ORIGINAL_TYPE (t)
8589                  && type != error_mark_node)
8590           {
8591             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
8592                                              args, complain, in_decl);
8593             TREE_TYPE (r) = type = build_variant_type_copy (type);
8594             TYPE_NAME (type) = r;
8595           }
8596
8597         if (!local_p)
8598           {
8599             /* A static data member declaration is always marked
8600                external when it is declared in-class, even if an
8601                initializer is present.  We mimic the non-template
8602                processing here.  */
8603             DECL_EXTERNAL (r) = 1;
8604
8605             register_specialization (r, gen_tmpl, argvec, false);
8606             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
8607             SET_DECL_IMPLICIT_INSTANTIATION (r);
8608           }
8609         else
8610           register_local_specialization (r, t);
8611
8612         TREE_CHAIN (r) = NULL_TREE;
8613
8614         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
8615                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
8616                                         args, complain, in_decl);
8617         layout_decl (r, 0);
8618       }
8619       break;
8620
8621     default:
8622       gcc_unreachable ();
8623     }
8624
8625   /* Restore the file and line information.  */
8626   input_location = saved_loc;
8627
8628   return r;
8629 }
8630
8631 /* Substitute into the ARG_TYPES of a function type.  */
8632
8633 static tree
8634 tsubst_arg_types (tree arg_types,
8635                   tree args,
8636                   tsubst_flags_t complain,
8637                   tree in_decl)
8638 {
8639   tree remaining_arg_types;
8640   tree type = NULL_TREE;
8641   int i = 1;
8642   tree expanded_args = NULL_TREE;
8643   tree default_arg;
8644
8645   if (!arg_types || arg_types == void_list_node)
8646     return arg_types;
8647
8648   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
8649                                           args, complain, in_decl);
8650   if (remaining_arg_types == error_mark_node)
8651     return error_mark_node;
8652
8653   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
8654     {
8655       /* For a pack expansion, perform substitution on the
8656          entire expression. Later on, we'll handle the arguments
8657          one-by-one.  */
8658       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
8659                                             args, complain, in_decl);
8660
8661       if (TREE_CODE (expanded_args) == TREE_VEC)
8662         /* So that we'll spin through the parameters, one by one.  */
8663         i = TREE_VEC_LENGTH (expanded_args);
8664       else
8665         {
8666           /* We only partially substituted into the parameter
8667              pack. Our type is TYPE_PACK_EXPANSION.  */
8668           type = expanded_args;
8669           expanded_args = NULL_TREE;
8670         }
8671     }
8672
8673   while (i > 0) {
8674     --i;
8675     
8676     if (expanded_args)
8677       type = TREE_VEC_ELT (expanded_args, i);
8678     else if (!type)
8679       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
8680
8681     if (type == error_mark_node)
8682       return error_mark_node;
8683     if (VOID_TYPE_P (type))
8684       {
8685         if (complain & tf_error)
8686           {
8687             error ("invalid parameter type %qT", type);
8688             if (in_decl)
8689               error ("in declaration %q+D", in_decl);
8690           }
8691         return error_mark_node;
8692     }
8693     
8694     /* Do array-to-pointer, function-to-pointer conversion, and ignore
8695        top-level qualifiers as required.  */
8696     type = TYPE_MAIN_VARIANT (type_decays_to (type));
8697
8698     /* We do not substitute into default arguments here.  The standard
8699        mandates that they be instantiated only when needed, which is
8700        done in build_over_call.  */
8701     default_arg = TREE_PURPOSE (arg_types);
8702
8703     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
8704       {
8705         /* We've instantiated a template before its default arguments
8706            have been parsed.  This can happen for a nested template
8707            class, and is not an error unless we require the default
8708            argument in a call of this function.  */
8709         remaining_arg_types = 
8710           tree_cons (default_arg, type, remaining_arg_types);
8711         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
8712                        remaining_arg_types);
8713       }
8714     else
8715       remaining_arg_types = 
8716         hash_tree_cons (default_arg, type, remaining_arg_types);
8717   }
8718         
8719   return remaining_arg_types;
8720 }
8721
8722 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
8723    *not* handle the exception-specification for FNTYPE, because the
8724    initial substitution of explicitly provided template parameters
8725    during argument deduction forbids substitution into the
8726    exception-specification:
8727
8728      [temp.deduct]
8729
8730      All references in the function type of the function template to  the
8731      corresponding template parameters are replaced by the specified tem-
8732      plate argument values.  If a substitution in a template parameter or
8733      in  the function type of the function template results in an invalid
8734      type, type deduction fails.  [Note: The equivalent  substitution  in
8735      exception specifications is done only when the function is instanti-
8736      ated, at which point a program is  ill-formed  if  the  substitution
8737      results in an invalid type.]  */
8738
8739 static tree
8740 tsubst_function_type (tree t,
8741                       tree args,
8742                       tsubst_flags_t complain,
8743                       tree in_decl)
8744 {
8745   tree return_type;
8746   tree arg_types;
8747   tree fntype;
8748
8749   /* The TYPE_CONTEXT is not used for function/method types.  */
8750   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
8751
8752   /* Substitute the return type.  */
8753   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8754   if (return_type == error_mark_node)
8755     return error_mark_node;
8756   /* The standard does not presently indicate that creation of a
8757      function type with an invalid return type is a deduction failure.
8758      However, that is clearly analogous to creating an array of "void"
8759      or a reference to a reference.  This is core issue #486.  */
8760   if (TREE_CODE (return_type) == ARRAY_TYPE
8761       || TREE_CODE (return_type) == FUNCTION_TYPE)
8762     {
8763       if (complain & tf_error)
8764         {
8765           if (TREE_CODE (return_type) == ARRAY_TYPE)
8766             error ("function returning an array");
8767           else
8768             error ("function returning a function");
8769         }
8770       return error_mark_node;
8771     }
8772
8773   /* Substitute the argument types.  */
8774   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
8775                                 complain, in_decl);
8776   if (arg_types == error_mark_node)
8777     return error_mark_node;
8778
8779   /* Construct a new type node and return it.  */
8780   if (TREE_CODE (t) == FUNCTION_TYPE)
8781     fntype = build_function_type (return_type, arg_types);
8782   else
8783     {
8784       tree r = TREE_TYPE (TREE_VALUE (arg_types));
8785       if (! MAYBE_CLASS_TYPE_P (r))
8786         {
8787           /* [temp.deduct]
8788
8789              Type deduction may fail for any of the following
8790              reasons:
8791
8792              -- Attempting to create "pointer to member of T" when T
8793              is not a class type.  */
8794           if (complain & tf_error)
8795             error ("creating pointer to member function of non-class type %qT",
8796                       r);
8797           return error_mark_node;
8798         }
8799
8800       fntype = build_method_type_directly (r, return_type,
8801                                            TREE_CHAIN (arg_types));
8802     }
8803   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
8804   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
8805
8806   return fntype;
8807 }
8808
8809 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
8810    ARGS into that specification, and return the substituted
8811    specification.  If there is no specification, return NULL_TREE.  */
8812
8813 static tree
8814 tsubst_exception_specification (tree fntype,
8815                                 tree args,
8816                                 tsubst_flags_t complain,
8817                                 tree in_decl)
8818 {
8819   tree specs;
8820   tree new_specs;
8821
8822   specs = TYPE_RAISES_EXCEPTIONS (fntype);
8823   new_specs = NULL_TREE;
8824   if (specs)
8825     {
8826       if (! TREE_VALUE (specs))
8827         new_specs = specs;
8828       else
8829         while (specs)
8830           {
8831             tree spec;
8832             int i, len = 1;
8833             tree expanded_specs = NULL_TREE;
8834
8835             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
8836               {
8837                 /* Expand the pack expansion type.  */
8838                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
8839                                                        args, complain,
8840                                                        in_decl);
8841
8842                 if (expanded_specs == error_mark_node)
8843                   return error_mark_node;
8844                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
8845                   len = TREE_VEC_LENGTH (expanded_specs);
8846                 else
8847                   {
8848                     /* We're substituting into a member template, so
8849                        we got a TYPE_PACK_EXPANSION back.  Add that
8850                        expansion and move on.  */
8851                     gcc_assert (TREE_CODE (expanded_specs) 
8852                                 == TYPE_PACK_EXPANSION);
8853                     new_specs = add_exception_specifier (new_specs,
8854                                                          expanded_specs,
8855                                                          complain);
8856                     specs = TREE_CHAIN (specs);
8857                     continue;
8858                   }
8859               }
8860
8861             for (i = 0; i < len; ++i)
8862               {
8863                 if (expanded_specs)
8864                   spec = TREE_VEC_ELT (expanded_specs, i);
8865                 else
8866                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
8867                 if (spec == error_mark_node)
8868                   return spec;
8869                 new_specs = add_exception_specifier (new_specs, spec, 
8870                                                      complain);
8871               }
8872
8873             specs = TREE_CHAIN (specs);
8874           }
8875     }
8876   return new_specs;
8877 }
8878
8879 /* Take the tree structure T and replace template parameters used
8880    therein with the argument vector ARGS.  IN_DECL is an associated
8881    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
8882    Issue error and warning messages under control of COMPLAIN.  Note
8883    that we must be relatively non-tolerant of extensions here, in
8884    order to preserve conformance; if we allow substitutions that
8885    should not be allowed, we may allow argument deductions that should
8886    not succeed, and therefore report ambiguous overload situations
8887    where there are none.  In theory, we could allow the substitution,
8888    but indicate that it should have failed, and allow our caller to
8889    make sure that the right thing happens, but we don't try to do this
8890    yet.
8891
8892    This function is used for dealing with types, decls and the like;
8893    for expressions, use tsubst_expr or tsubst_copy.  */
8894
8895 static tree
8896 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8897 {
8898   tree type, r;
8899
8900   if (t == NULL_TREE || t == error_mark_node
8901       || t == integer_type_node
8902       || t == void_type_node
8903       || t == char_type_node
8904       || t == unknown_type_node
8905       || TREE_CODE (t) == NAMESPACE_DECL)
8906     return t;
8907
8908   if (DECL_P (t))
8909     return tsubst_decl (t, args, complain);
8910
8911   if (TREE_CODE (t) == IDENTIFIER_NODE)
8912     type = IDENTIFIER_TYPE_VALUE (t);
8913   else
8914     type = TREE_TYPE (t);
8915
8916   gcc_assert (type != unknown_type_node);
8917
8918   /* Reuse typedefs.  We need to do this to handle dependent attributes,
8919      such as attribute aligned.  */
8920   if (TYPE_P (t)
8921       && TYPE_NAME (t)
8922       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
8923     {
8924       tree decl = TYPE_NAME (t);
8925       
8926       if (DECL_CLASS_SCOPE_P (decl)
8927           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
8928           && uses_template_parms (DECL_CONTEXT (decl)))
8929         {
8930           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
8931           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
8932           r = retrieve_specialization (tmpl, gen_args, false);
8933         }
8934       else if (DECL_FUNCTION_SCOPE_P (decl)
8935                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
8936                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
8937         r = retrieve_local_specialization (decl);
8938       else
8939         /* The typedef is from a non-template context.  */
8940         return t;
8941
8942       if (r)
8943         {
8944           r = TREE_TYPE (r);
8945           r = cp_build_qualified_type_real
8946             (r, cp_type_quals (t) | cp_type_quals (r),
8947              complain | tf_ignore_bad_quals);
8948           return r;
8949         }
8950       /* Else we must be instantiating the typedef, so fall through.  */
8951     }
8952
8953   if (type
8954       && TREE_CODE (t) != TYPENAME_TYPE
8955       && TREE_CODE (t) != IDENTIFIER_NODE
8956       && TREE_CODE (t) != FUNCTION_TYPE
8957       && TREE_CODE (t) != METHOD_TYPE)
8958     type = tsubst (type, args, complain, in_decl);
8959   if (type == error_mark_node)
8960     return error_mark_node;
8961
8962   switch (TREE_CODE (t))
8963     {
8964     case RECORD_TYPE:
8965     case UNION_TYPE:
8966     case ENUMERAL_TYPE:
8967       return tsubst_aggr_type (t, args, complain, in_decl,
8968                                /*entering_scope=*/0);
8969
8970     case ERROR_MARK:
8971     case IDENTIFIER_NODE:
8972     case VOID_TYPE:
8973     case REAL_TYPE:
8974     case COMPLEX_TYPE:
8975     case VECTOR_TYPE:
8976     case BOOLEAN_TYPE:
8977     case INTEGER_CST:
8978     case REAL_CST:
8979     case STRING_CST:
8980       return t;
8981
8982     case INTEGER_TYPE:
8983       if (t == integer_type_node)
8984         return t;
8985
8986       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
8987           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
8988         return t;
8989
8990       {
8991         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
8992
8993         max = tsubst_expr (omax, args, complain, in_decl,
8994                            /*integral_constant_expression_p=*/false);
8995         max = fold_decl_constant_value (max);
8996
8997         if (TREE_CODE (max) != INTEGER_CST
8998             && !at_function_scope_p ()
8999             && !value_dependent_expression_p (max))
9000           {
9001             if (complain & tf_error)
9002               error ("array bound is not an integer constant");
9003             return error_mark_node;
9004           }
9005
9006         /* [temp.deduct]
9007
9008            Type deduction may fail for any of the following
9009            reasons:
9010
9011              Attempting to create an array with a size that is
9012              zero or negative.  */
9013         if (integer_zerop (max) && !(complain & tf_error))
9014           /* We must fail if performing argument deduction (as
9015              indicated by the state of complain), so that
9016              another substitution can be found.  */
9017           return error_mark_node;
9018         else if (TREE_CODE (max) == INTEGER_CST
9019                  && INT_CST_LT (max, integer_zero_node))
9020           {
9021             if (complain & tf_error)
9022               error ("creating array with negative size (%qE)", max);
9023
9024             return error_mark_node;
9025           }
9026
9027         return compute_array_index_type (NULL_TREE, max);
9028       }
9029
9030     case TEMPLATE_TYPE_PARM:
9031     case TEMPLATE_TEMPLATE_PARM:
9032     case BOUND_TEMPLATE_TEMPLATE_PARM:
9033     case TEMPLATE_PARM_INDEX:
9034       {
9035         int idx;
9036         int level;
9037         int levels;
9038         tree arg = NULL_TREE;
9039
9040         r = NULL_TREE;
9041
9042         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9043         template_parm_level_and_index (t, &level, &idx); 
9044
9045         levels = TMPL_ARGS_DEPTH (args);
9046         if (level <= levels)
9047           {
9048             arg = TMPL_ARG (args, level, idx);
9049
9050             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9051               /* See through ARGUMENT_PACK_SELECT arguments. */
9052               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9053           }
9054
9055         if (arg == error_mark_node)
9056           return error_mark_node;
9057         else if (arg != NULL_TREE)
9058           {
9059             if (ARGUMENT_PACK_P (arg))
9060               /* If ARG is an argument pack, we don't actually want to
9061                  perform a substitution here, because substitutions
9062                  for argument packs are only done
9063                  element-by-element. We can get to this point when
9064                  substituting the type of a non-type template
9065                  parameter pack, when that type actually contains
9066                  template parameter packs from an outer template, e.g.,
9067
9068                  template<typename... Types> struct A {
9069                    template<Types... Values> struct B { };
9070                  };  */
9071               return t;
9072
9073             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9074               {
9075                 int quals;
9076                 gcc_assert (TYPE_P (arg));
9077
9078                 /* cv-quals from the template are discarded when
9079                    substituting in a function or reference type.  */
9080                 if (TREE_CODE (arg) == FUNCTION_TYPE
9081                     || TREE_CODE (arg) == METHOD_TYPE
9082                     || TREE_CODE (arg) == REFERENCE_TYPE)
9083                   quals = cp_type_quals (arg);
9084                 else
9085                   quals = cp_type_quals (arg) | cp_type_quals (t);
9086                   
9087                 return cp_build_qualified_type_real
9088                   (arg, quals, complain | tf_ignore_bad_quals);
9089               }
9090             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9091               {
9092                 /* We are processing a type constructed from a
9093                    template template parameter.  */
9094                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9095                                       args, complain, in_decl);
9096                 if (argvec == error_mark_node)
9097                   return error_mark_node;
9098
9099                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9100                    are resolving nested-types in the signature of a
9101                    member function templates.  Otherwise ARG is a
9102                    TEMPLATE_DECL and is the real template to be
9103                    instantiated.  */
9104                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9105                   arg = TYPE_NAME (arg);
9106
9107                 r = lookup_template_class (arg,
9108                                            argvec, in_decl,
9109                                            DECL_CONTEXT (arg),
9110                                             /*entering_scope=*/0,
9111                                            complain);
9112                 return cp_build_qualified_type_real
9113                   (r, TYPE_QUALS (t), complain);
9114               }
9115             else
9116               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9117               return arg;
9118           }
9119
9120         if (level == 1)
9121           /* This can happen during the attempted tsubst'ing in
9122              unify.  This means that we don't yet have any information
9123              about the template parameter in question.  */
9124           return t;
9125
9126         /* If we get here, we must have been looking at a parm for a
9127            more deeply nested template.  Make a new version of this
9128            template parameter, but with a lower level.  */
9129         switch (TREE_CODE (t))
9130           {
9131           case TEMPLATE_TYPE_PARM:
9132           case TEMPLATE_TEMPLATE_PARM:
9133           case BOUND_TEMPLATE_TEMPLATE_PARM:
9134             if (cp_type_quals (t))
9135               {
9136                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9137                 r = cp_build_qualified_type_real
9138                   (r, cp_type_quals (t),
9139                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9140                                ? tf_ignore_bad_quals : 0));
9141               }
9142             else
9143               {
9144                 r = copy_type (t);
9145                 TEMPLATE_TYPE_PARM_INDEX (r)
9146                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9147                                                 r, levels, args, complain);
9148                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9149                 TYPE_MAIN_VARIANT (r) = r;
9150                 TYPE_POINTER_TO (r) = NULL_TREE;
9151                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9152
9153                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9154                   /* We have reduced the level of the template
9155                      template parameter, but not the levels of its
9156                      template parameters, so canonical_type_parameter
9157                      will not be able to find the canonical template
9158                      template parameter for this level. Thus, we
9159                      require structural equality checking to compare
9160                      TEMPLATE_TEMPLATE_PARMs. */
9161                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9162                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9163                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9164                 else
9165                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9166
9167                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9168                   {
9169                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9170                                           complain, in_decl);
9171                     if (argvec == error_mark_node)
9172                       return error_mark_node;
9173
9174                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9175                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9176                   }
9177               }
9178             break;
9179
9180           case TEMPLATE_PARM_INDEX:
9181             r = reduce_template_parm_level (t, type, levels, args, complain);
9182             break;
9183
9184           default:
9185             gcc_unreachable ();
9186           }
9187
9188         return r;
9189       }
9190
9191     case TREE_LIST:
9192       {
9193         tree purpose, value, chain;
9194
9195         if (t == void_list_node)
9196           return t;
9197
9198         purpose = TREE_PURPOSE (t);
9199         if (purpose)
9200           {
9201             purpose = tsubst (purpose, args, complain, in_decl);
9202             if (purpose == error_mark_node)
9203               return error_mark_node;
9204           }
9205         value = TREE_VALUE (t);
9206         if (value)
9207           {
9208             value = tsubst (value, args, complain, in_decl);
9209             if (value == error_mark_node)
9210               return error_mark_node;
9211           }
9212         chain = TREE_CHAIN (t);
9213         if (chain && chain != void_type_node)
9214           {
9215             chain = tsubst (chain, args, complain, in_decl);
9216             if (chain == error_mark_node)
9217               return error_mark_node;
9218           }
9219         if (purpose == TREE_PURPOSE (t)
9220             && value == TREE_VALUE (t)
9221             && chain == TREE_CHAIN (t))
9222           return t;
9223         return hash_tree_cons (purpose, value, chain);
9224       }
9225
9226     case TREE_BINFO:
9227       /* We should never be tsubsting a binfo.  */
9228       gcc_unreachable ();
9229
9230     case TREE_VEC:
9231       /* A vector of template arguments.  */
9232       gcc_assert (!type);
9233       return tsubst_template_args (t, args, complain, in_decl);
9234
9235     case POINTER_TYPE:
9236     case REFERENCE_TYPE:
9237       {
9238         enum tree_code code;
9239
9240         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9241           return t;
9242
9243         code = TREE_CODE (t);
9244
9245
9246         /* [temp.deduct]
9247
9248            Type deduction may fail for any of the following
9249            reasons:
9250
9251            -- Attempting to create a pointer to reference type.
9252            -- Attempting to create a reference to a reference type or
9253               a reference to void.
9254
9255           Core issue 106 says that creating a reference to a reference
9256           during instantiation is no longer a cause for failure. We
9257           only enforce this check in strict C++98 mode.  */
9258         if ((TREE_CODE (type) == REFERENCE_TYPE
9259              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9260             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9261           {
9262             static location_t last_loc;
9263
9264             /* We keep track of the last time we issued this error
9265                message to avoid spewing a ton of messages during a
9266                single bad template instantiation.  */
9267             if (complain & tf_error
9268                 && last_loc != input_location)
9269               {
9270                 if (TREE_CODE (type) == VOID_TYPE)
9271                   error ("forming reference to void");
9272                 else
9273                   error ("forming %s to reference type %qT",
9274                          (code == POINTER_TYPE) ? "pointer" : "reference",
9275                          type);
9276                 last_loc = input_location;
9277               }
9278
9279             return error_mark_node;
9280           }
9281         else if (code == POINTER_TYPE)
9282           {
9283             r = build_pointer_type (type);
9284             if (TREE_CODE (type) == METHOD_TYPE)
9285               r = build_ptrmemfunc_type (r);
9286           }
9287         else if (TREE_CODE (type) == REFERENCE_TYPE)
9288           /* In C++0x, during template argument substitution, when there is an
9289              attempt to create a reference to a reference type, reference
9290              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9291
9292              "If a template-argument for a template-parameter T names a type
9293              that is a reference to a type A, an attempt to create the type
9294              'lvalue reference to cv T' creates the type 'lvalue reference to
9295              A,' while an attempt to create the type type rvalue reference to
9296              cv T' creates the type T"
9297           */
9298           r = cp_build_reference_type
9299               (TREE_TYPE (type),
9300                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9301         else
9302           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9303         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9304
9305         if (r != error_mark_node)
9306           /* Will this ever be needed for TYPE_..._TO values?  */
9307           layout_type (r);
9308
9309         return r;
9310       }
9311     case OFFSET_TYPE:
9312       {
9313         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9314         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
9315           {
9316             /* [temp.deduct]
9317
9318                Type deduction may fail for any of the following
9319                reasons:
9320
9321                -- Attempting to create "pointer to member of T" when T
9322                   is not a class type.  */
9323             if (complain & tf_error)
9324               error ("creating pointer to member of non-class type %qT", r);
9325             return error_mark_node;
9326           }
9327         if (TREE_CODE (type) == REFERENCE_TYPE)
9328           {
9329             if (complain & tf_error)
9330               error ("creating pointer to member reference type %qT", type);
9331             return error_mark_node;
9332           }
9333         if (TREE_CODE (type) == VOID_TYPE)
9334           {
9335             if (complain & tf_error)
9336               error ("creating pointer to member of type void");
9337             return error_mark_node;
9338           }
9339         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
9340         if (TREE_CODE (type) == FUNCTION_TYPE)
9341           {
9342             /* The type of the implicit object parameter gets its
9343                cv-qualifiers from the FUNCTION_TYPE. */
9344             tree method_type;
9345             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
9346                                                       cp_type_quals (type));
9347             tree memptr;
9348             method_type = build_method_type_directly (this_type,
9349                                                       TREE_TYPE (type),
9350                                                       TYPE_ARG_TYPES (type));
9351             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
9352             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
9353                                                  complain);
9354           }
9355         else
9356           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
9357                                                TYPE_QUALS (t),
9358                                                complain);
9359       }
9360     case FUNCTION_TYPE:
9361     case METHOD_TYPE:
9362       {
9363         tree fntype;
9364         tree specs;
9365         fntype = tsubst_function_type (t, args, complain, in_decl);
9366         if (fntype == error_mark_node)
9367           return error_mark_node;
9368
9369         /* Substitute the exception specification.  */
9370         specs = tsubst_exception_specification (t, args, complain,
9371                                                 in_decl);
9372         if (specs == error_mark_node)
9373           return error_mark_node;
9374         if (specs)
9375           fntype = build_exception_variant (fntype, specs);
9376         return fntype;
9377       }
9378     case ARRAY_TYPE:
9379       {
9380         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
9381         if (domain == error_mark_node)
9382           return error_mark_node;
9383
9384         /* As an optimization, we avoid regenerating the array type if
9385            it will obviously be the same as T.  */
9386         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
9387           return t;
9388
9389         /* These checks should match the ones in grokdeclarator.
9390
9391            [temp.deduct]
9392
9393            The deduction may fail for any of the following reasons:
9394
9395            -- Attempting to create an array with an element type that
9396               is void, a function type, or a reference type, or [DR337]
9397               an abstract class type.  */
9398         if (TREE_CODE (type) == VOID_TYPE
9399             || TREE_CODE (type) == FUNCTION_TYPE
9400             || TREE_CODE (type) == REFERENCE_TYPE)
9401           {
9402             if (complain & tf_error)
9403               error ("creating array of %qT", type);
9404             return error_mark_node;
9405           }
9406         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
9407           {
9408             if (complain & tf_error)
9409               error ("creating array of %qT, which is an abstract class type",
9410                      type);
9411             return error_mark_node;
9412           }
9413
9414         r = build_cplus_array_type (type, domain);
9415
9416         if (TYPE_USER_ALIGN (t))
9417           {
9418             TYPE_ALIGN (r) = TYPE_ALIGN (t);
9419             TYPE_USER_ALIGN (r) = 1;
9420           }
9421
9422         return r;
9423       }
9424
9425     case PLUS_EXPR:
9426     case MINUS_EXPR:
9427       {
9428         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9429         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9430
9431         if (e1 == error_mark_node || e2 == error_mark_node)
9432           return error_mark_node;
9433
9434         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
9435       }
9436
9437     case NEGATE_EXPR:
9438     case NOP_EXPR:
9439       {
9440         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9441         if (e == error_mark_node)
9442           return error_mark_node;
9443
9444         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
9445       }
9446
9447     case TYPENAME_TYPE:
9448       {
9449         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9450                                      in_decl, /*entering_scope=*/1);
9451         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
9452                               complain, in_decl);
9453
9454         if (ctx == error_mark_node || f == error_mark_node)
9455           return error_mark_node;
9456
9457         if (!MAYBE_CLASS_TYPE_P (ctx))
9458           {
9459             if (complain & tf_error)
9460               error ("%qT is not a class, struct, or union type", ctx);
9461             return error_mark_node;
9462           }
9463         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
9464           {
9465             /* Normally, make_typename_type does not require that the CTX
9466                have complete type in order to allow things like:
9467
9468                  template <class T> struct S { typename S<T>::X Y; };
9469
9470                But, such constructs have already been resolved by this
9471                point, so here CTX really should have complete type, unless
9472                it's a partial instantiation.  */
9473             ctx = complete_type (ctx);
9474             if (!COMPLETE_TYPE_P (ctx))
9475               {
9476                 if (complain & tf_error)
9477                   cxx_incomplete_type_error (NULL_TREE, ctx);
9478                 return error_mark_node;
9479               }
9480           }
9481
9482         f = make_typename_type (ctx, f, typename_type,
9483                                 (complain & tf_error) | tf_keep_type_decl);
9484         if (f == error_mark_node)
9485           return f;
9486         if (TREE_CODE (f) == TYPE_DECL)
9487           {
9488             complain |= tf_ignore_bad_quals;
9489             f = TREE_TYPE (f);
9490           }
9491
9492         if (TREE_CODE (f) != TYPENAME_TYPE)
9493           {
9494             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
9495               error ("%qT resolves to %qT, which is not an enumeration type",
9496                      t, f);
9497             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
9498               error ("%qT resolves to %qT, which is is not a class type",
9499                      t, f);
9500           }
9501
9502         return cp_build_qualified_type_real
9503           (f, cp_type_quals (f) | cp_type_quals (t), complain);
9504       }
9505
9506     case UNBOUND_CLASS_TEMPLATE:
9507       {
9508         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9509                                      in_decl, /*entering_scope=*/1);
9510         tree name = TYPE_IDENTIFIER (t);
9511         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
9512
9513         if (ctx == error_mark_node || name == error_mark_node)
9514           return error_mark_node;
9515
9516         if (parm_list)
9517           parm_list = tsubst_template_parms (parm_list, args, complain);
9518         return make_unbound_class_template (ctx, name, parm_list, complain);
9519       }
9520
9521     case INDIRECT_REF:
9522     case ADDR_EXPR:
9523     case CALL_EXPR:
9524       gcc_unreachable ();
9525
9526     case ARRAY_REF:
9527       {
9528         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9529         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
9530                                /*integral_constant_expression_p=*/false);
9531         if (e1 == error_mark_node || e2 == error_mark_node)
9532           return error_mark_node;
9533
9534         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
9535       }
9536
9537     case SCOPE_REF:
9538       {
9539         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9540         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9541         if (e1 == error_mark_node || e2 == error_mark_node)
9542           return error_mark_node;
9543
9544         return build_qualified_name (/*type=*/NULL_TREE,
9545                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
9546       }
9547
9548     case TYPEOF_TYPE:
9549       {
9550         tree type;
9551
9552         type = finish_typeof (tsubst_expr 
9553                               (TYPEOF_TYPE_EXPR (t), args,
9554                                complain, in_decl,
9555                                /*integral_constant_expression_p=*/false));
9556         return cp_build_qualified_type_real (type,
9557                                              cp_type_quals (t)
9558                                              | cp_type_quals (type),
9559                                              complain);
9560       }
9561
9562     case DECLTYPE_TYPE:
9563       {
9564         tree type;
9565
9566         ++skip_evaluation;
9567
9568         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
9569                             complain, in_decl,
9570                             /*integral_constant_expression_p=*/false);
9571
9572         --skip_evaluation;
9573
9574         type =
9575           finish_decltype_type (type,
9576                                 DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
9577         return cp_build_qualified_type_real (type,
9578                                              cp_type_quals (t)
9579                                              | cp_type_quals (type),
9580                                              complain);
9581       }
9582
9583     case TYPE_ARGUMENT_PACK:
9584     case NONTYPE_ARGUMENT_PACK:
9585       {
9586         tree r = make_node (TREE_CODE (t));
9587         tree packed_out = 
9588           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
9589                                 args,
9590                                 complain,
9591                                 in_decl);
9592         SET_ARGUMENT_PACK_ARGS (r, packed_out);
9593
9594         /* For template nontype argument packs, also substitute into
9595            the type.  */
9596         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
9597           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
9598
9599         return r;
9600       }
9601       break;
9602
9603     default:
9604       sorry ("use of %qs in template",
9605              tree_code_name [(int) TREE_CODE (t)]);
9606       return error_mark_node;
9607     }
9608 }
9609
9610 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
9611    type of the expression on the left-hand side of the "." or "->"
9612    operator.  */
9613
9614 static tree
9615 tsubst_baselink (tree baselink, tree object_type,
9616                  tree args, tsubst_flags_t complain, tree in_decl)
9617 {
9618     tree name;
9619     tree qualifying_scope;
9620     tree fns;
9621     tree optype;
9622     tree template_args = 0;
9623     bool template_id_p = false;
9624
9625     /* A baselink indicates a function from a base class.  Both the
9626        BASELINK_ACCESS_BINFO and the base class referenced may
9627        indicate bases of the template class, rather than the
9628        instantiated class.  In addition, lookups that were not
9629        ambiguous before may be ambiguous now.  Therefore, we perform
9630        the lookup again.  */
9631     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
9632     qualifying_scope = tsubst (qualifying_scope, args,
9633                                complain, in_decl);
9634     fns = BASELINK_FUNCTIONS (baselink);
9635     optype = BASELINK_OPTYPE (baselink);
9636     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
9637       {
9638         template_id_p = true;
9639         template_args = TREE_OPERAND (fns, 1);
9640         fns = TREE_OPERAND (fns, 0);
9641         if (template_args)
9642           template_args = tsubst_template_args (template_args, args,
9643                                                 complain, in_decl);
9644       }
9645     name = DECL_NAME (get_first_fn (fns));
9646     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
9647
9648     /* If lookup found a single function, mark it as used at this
9649        point.  (If it lookup found multiple functions the one selected
9650        later by overload resolution will be marked as used at that
9651        point.)  */
9652     if (BASELINK_P (baselink))
9653       fns = BASELINK_FUNCTIONS (baselink);
9654     if (!template_id_p && !really_overloaded_fn (fns))
9655       mark_used (OVL_CURRENT (fns));
9656
9657     /* Add back the template arguments, if present.  */
9658     if (BASELINK_P (baselink) && template_id_p)
9659       BASELINK_FUNCTIONS (baselink)
9660         = build_nt (TEMPLATE_ID_EXPR,
9661                     BASELINK_FUNCTIONS (baselink),
9662                     template_args);
9663     /* Update the conversion operator type.  */
9664     BASELINK_OPTYPE (baselink) 
9665       = tsubst (optype, args, complain, in_decl);
9666
9667     if (!object_type)
9668       object_type = current_class_type;
9669     return adjust_result_of_qualified_name_lookup (baselink,
9670                                                    qualifying_scope,
9671                                                    object_type);
9672 }
9673
9674 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
9675    true if the qualified-id will be a postfix-expression in-and-of
9676    itself; false if more of the postfix-expression follows the
9677    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
9678    of "&".  */
9679
9680 static tree
9681 tsubst_qualified_id (tree qualified_id, tree args,
9682                      tsubst_flags_t complain, tree in_decl,
9683                      bool done, bool address_p)
9684 {
9685   tree expr;
9686   tree scope;
9687   tree name;
9688   bool is_template;
9689   tree template_args;
9690
9691   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
9692
9693   /* Figure out what name to look up.  */
9694   name = TREE_OPERAND (qualified_id, 1);
9695   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
9696     {
9697       is_template = true;
9698       template_args = TREE_OPERAND (name, 1);
9699       if (template_args)
9700         template_args = tsubst_template_args (template_args, args,
9701                                               complain, in_decl);
9702       name = TREE_OPERAND (name, 0);
9703     }
9704   else
9705     {
9706       is_template = false;
9707       template_args = NULL_TREE;
9708     }
9709
9710   /* Substitute into the qualifying scope.  When there are no ARGS, we
9711      are just trying to simplify a non-dependent expression.  In that
9712      case the qualifying scope may be dependent, and, in any case,
9713      substituting will not help.  */
9714   scope = TREE_OPERAND (qualified_id, 0);
9715   if (args)
9716     {
9717       scope = tsubst (scope, args, complain, in_decl);
9718       expr = tsubst_copy (name, args, complain, in_decl);
9719     }
9720   else
9721     expr = name;
9722
9723   if (dependent_type_p (scope))
9724     return build_qualified_name (/*type=*/NULL_TREE,
9725                                  scope, expr,
9726                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
9727
9728   if (!BASELINK_P (name) && !DECL_P (expr))
9729     {
9730       if (TREE_CODE (expr) == BIT_NOT_EXPR)
9731         /* If this were actually a destructor call, it would have been
9732            parsed as such by the parser.  */
9733         expr = error_mark_node;
9734       else
9735         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
9736       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
9737                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
9738         {
9739           if (complain & tf_error)
9740             {
9741               error ("dependent-name %qE is parsed as a non-type, but "
9742                      "instantiation yields a type", qualified_id);
9743               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
9744             }
9745           return error_mark_node;
9746         }
9747     }
9748
9749   if (DECL_P (expr))
9750     {
9751       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
9752                                            scope);
9753       /* Remember that there was a reference to this entity.  */
9754       mark_used (expr);
9755     }
9756
9757   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
9758     {
9759       if (complain & tf_error)
9760         qualified_name_lookup_error (scope,
9761                                      TREE_OPERAND (qualified_id, 1),
9762                                      expr, input_location);
9763       return error_mark_node;
9764     }
9765
9766   if (is_template)
9767     expr = lookup_template_function (expr, template_args);
9768
9769   if (expr == error_mark_node && complain & tf_error)
9770     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
9771                                  expr, input_location);
9772   else if (TYPE_P (scope))
9773     {
9774       expr = (adjust_result_of_qualified_name_lookup
9775               (expr, scope, current_class_type));
9776       expr = (finish_qualified_id_expr
9777               (scope, expr, done, address_p,
9778                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
9779                /*template_arg_p=*/false));
9780     }
9781
9782   /* Expressions do not generally have reference type.  */
9783   if (TREE_CODE (expr) != SCOPE_REF
9784       /* However, if we're about to form a pointer-to-member, we just
9785          want the referenced member referenced.  */
9786       && TREE_CODE (expr) != OFFSET_REF)
9787     expr = convert_from_reference (expr);
9788
9789   return expr;
9790 }
9791
9792 /* Like tsubst, but deals with expressions.  This function just replaces
9793    template parms; to finish processing the resultant expression, use
9794    tsubst_expr.  */
9795
9796 static tree
9797 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9798 {
9799   enum tree_code code;
9800   tree r;
9801
9802   if (t == NULL_TREE || t == error_mark_node)
9803     return t;
9804
9805   code = TREE_CODE (t);
9806
9807   switch (code)
9808     {
9809     case PARM_DECL:
9810       r = retrieve_local_specialization (t);
9811
9812       if (r == NULL)
9813         {
9814           /* This can happen for a parameter name used later in a function
9815              declaration (such as in a late-specified return type).
9816              Replace it with an arbitrary expression with the same type
9817              (*(T*)0).  This should only occur in an unevaluated context
9818              (i.e. decltype).  */
9819           gcc_assert (skip_evaluation);
9820           r = non_reference (TREE_TYPE (t));
9821           r = tsubst (r, args, complain, in_decl);
9822           r = build_pointer_type (r);
9823           r = build_c_cast (r, null_node);
9824           return cp_build_indirect_ref (r, NULL, tf_warning_or_error);
9825         }
9826       
9827       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
9828         r = ARGUMENT_PACK_SELECT_ARG (r);
9829       mark_used (r);
9830       return r;
9831
9832     case CONST_DECL:
9833       {
9834         tree enum_type;
9835         tree v;
9836
9837         if (DECL_TEMPLATE_PARM_P (t))
9838           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
9839         /* There is no need to substitute into namespace-scope
9840            enumerators.  */
9841         if (DECL_NAMESPACE_SCOPE_P (t))
9842           return t;
9843         /* If ARGS is NULL, then T is known to be non-dependent.  */
9844         if (args == NULL_TREE)
9845           return integral_constant_value (t);
9846
9847         /* Unfortunately, we cannot just call lookup_name here.
9848            Consider:
9849
9850              template <int I> int f() {
9851              enum E { a = I };
9852              struct S { void g() { E e = a; } };
9853              };
9854
9855            When we instantiate f<7>::S::g(), say, lookup_name is not
9856            clever enough to find f<7>::a.  */
9857         enum_type
9858           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
9859                               /*entering_scope=*/0);
9860
9861         for (v = TYPE_VALUES (enum_type);
9862              v != NULL_TREE;
9863              v = TREE_CHAIN (v))
9864           if (TREE_PURPOSE (v) == DECL_NAME (t))
9865             return TREE_VALUE (v);
9866
9867           /* We didn't find the name.  That should never happen; if
9868              name-lookup found it during preliminary parsing, we
9869              should find it again here during instantiation.  */
9870         gcc_unreachable ();
9871       }
9872       return t;
9873
9874     case FIELD_DECL:
9875       if (DECL_CONTEXT (t))
9876         {
9877           tree ctx;
9878
9879           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
9880                                   /*entering_scope=*/1);
9881           if (ctx != DECL_CONTEXT (t))
9882             {
9883               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
9884               if (!r)
9885                 {
9886                   if (complain & tf_error)
9887                     error ("using invalid field %qD", t);
9888                   return error_mark_node;
9889                 }
9890               return r;
9891             }
9892         }
9893
9894       return t;
9895
9896     case VAR_DECL:
9897     case FUNCTION_DECL:
9898       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
9899           || local_variable_p (t))
9900         t = tsubst (t, args, complain, in_decl);
9901       mark_used (t);
9902       return t;
9903
9904     case BASELINK:
9905       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
9906
9907     case TEMPLATE_DECL:
9908       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9909         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
9910                        args, complain, in_decl);
9911       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
9912         return tsubst (t, args, complain, in_decl);
9913       else if (DECL_CLASS_SCOPE_P (t)
9914                && uses_template_parms (DECL_CONTEXT (t)))
9915         {
9916           /* Template template argument like the following example need
9917              special treatment:
9918
9919                template <template <class> class TT> struct C {};
9920                template <class T> struct D {
9921                  template <class U> struct E {};
9922                  C<E> c;                                // #1
9923                };
9924                D<int> d;                                // #2
9925
9926              We are processing the template argument `E' in #1 for
9927              the template instantiation #2.  Originally, `E' is a
9928              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
9929              have to substitute this with one having context `D<int>'.  */
9930
9931           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
9932           return lookup_field (context, DECL_NAME(t), 0, false);
9933         }
9934       else
9935         /* Ordinary template template argument.  */
9936         return t;
9937
9938     case CAST_EXPR:
9939     case REINTERPRET_CAST_EXPR:
9940     case CONST_CAST_EXPR:
9941     case STATIC_CAST_EXPR:
9942     case DYNAMIC_CAST_EXPR:
9943     case NOP_EXPR:
9944       return build1
9945         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
9946          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
9947
9948     case SIZEOF_EXPR:
9949       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
9950         {
9951           /* We only want to compute the number of arguments.  */
9952           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
9953                                                 complain, in_decl);
9954           int len = 0;
9955
9956           if (TREE_CODE (expanded) == TREE_VEC)
9957             len = TREE_VEC_LENGTH (expanded);
9958
9959           if (expanded == error_mark_node)
9960             return error_mark_node;
9961           else if (PACK_EXPANSION_P (expanded)
9962                    || (TREE_CODE (expanded) == TREE_VEC
9963                        && len > 0
9964                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
9965             {
9966               if (TREE_CODE (expanded) == TREE_VEC)
9967                 expanded = TREE_VEC_ELT (expanded, len - 1);
9968
9969               if (TYPE_P (expanded))
9970                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
9971                                                    complain & tf_error);
9972               else
9973                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
9974                                                    complain & tf_error);
9975             }
9976           else
9977             return build_int_cst (size_type_node, len);
9978         }
9979       /* Fall through */
9980
9981     case INDIRECT_REF:
9982     case NEGATE_EXPR:
9983     case TRUTH_NOT_EXPR:
9984     case BIT_NOT_EXPR:
9985     case ADDR_EXPR:
9986     case UNARY_PLUS_EXPR:      /* Unary + */
9987     case ALIGNOF_EXPR:
9988     case ARROW_EXPR:
9989     case THROW_EXPR:
9990     case TYPEID_EXPR:
9991     case REALPART_EXPR:
9992     case IMAGPART_EXPR:
9993       return build1
9994         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
9995          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
9996
9997     case COMPONENT_REF:
9998       {
9999         tree object;
10000         tree name;
10001
10002         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10003         name = TREE_OPERAND (t, 1);
10004         if (TREE_CODE (name) == BIT_NOT_EXPR)
10005           {
10006             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10007                                 complain, in_decl);
10008             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10009           }
10010         else if (TREE_CODE (name) == SCOPE_REF
10011                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10012           {
10013             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10014                                      complain, in_decl);
10015             name = TREE_OPERAND (name, 1);
10016             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10017                                 complain, in_decl);
10018             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10019             name = build_qualified_name (/*type=*/NULL_TREE,
10020                                          base, name,
10021                                          /*template_p=*/false);
10022           }
10023         else if (TREE_CODE (name) == BASELINK)
10024           name = tsubst_baselink (name,
10025                                   non_reference (TREE_TYPE (object)),
10026                                   args, complain,
10027                                   in_decl);
10028         else
10029           name = tsubst_copy (name, args, complain, in_decl);
10030         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10031       }
10032
10033     case PLUS_EXPR:
10034     case MINUS_EXPR:
10035     case MULT_EXPR:
10036     case TRUNC_DIV_EXPR:
10037     case CEIL_DIV_EXPR:
10038     case FLOOR_DIV_EXPR:
10039     case ROUND_DIV_EXPR:
10040     case EXACT_DIV_EXPR:
10041     case BIT_AND_EXPR:
10042     case BIT_IOR_EXPR:
10043     case BIT_XOR_EXPR:
10044     case TRUNC_MOD_EXPR:
10045     case FLOOR_MOD_EXPR:
10046     case TRUTH_ANDIF_EXPR:
10047     case TRUTH_ORIF_EXPR:
10048     case TRUTH_AND_EXPR:
10049     case TRUTH_OR_EXPR:
10050     case RSHIFT_EXPR:
10051     case LSHIFT_EXPR:
10052     case RROTATE_EXPR:
10053     case LROTATE_EXPR:
10054     case EQ_EXPR:
10055     case NE_EXPR:
10056     case MAX_EXPR:
10057     case MIN_EXPR:
10058     case LE_EXPR:
10059     case GE_EXPR:
10060     case LT_EXPR:
10061     case GT_EXPR:
10062     case COMPOUND_EXPR:
10063     case DOTSTAR_EXPR:
10064     case MEMBER_REF:
10065     case PREDECREMENT_EXPR:
10066     case PREINCREMENT_EXPR:
10067     case POSTDECREMENT_EXPR:
10068     case POSTINCREMENT_EXPR:
10069       return build_nt
10070         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10071          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10072
10073     case SCOPE_REF:
10074       return build_qualified_name (/*type=*/NULL_TREE,
10075                                    tsubst_copy (TREE_OPERAND (t, 0),
10076                                                 args, complain, in_decl),
10077                                    tsubst_copy (TREE_OPERAND (t, 1),
10078                                                 args, complain, in_decl),
10079                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10080
10081     case ARRAY_REF:
10082       return build_nt
10083         (ARRAY_REF,
10084          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10085          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10086          NULL_TREE, NULL_TREE);
10087
10088     case CALL_EXPR:
10089       {
10090         int n = VL_EXP_OPERAND_LENGTH (t);
10091         tree result = build_vl_exp (CALL_EXPR, n);
10092         int i;
10093         for (i = 0; i < n; i++)
10094           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10095                                              complain, in_decl);
10096         return result;
10097       }
10098
10099     case COND_EXPR:
10100     case MODOP_EXPR:
10101     case PSEUDO_DTOR_EXPR:
10102       {
10103         r = build_nt
10104           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10105            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10106            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10107         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10108         return r;
10109       }
10110
10111     case NEW_EXPR:
10112       {
10113         r = build_nt
10114         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10115          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10116          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10117         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10118         return r;
10119       }
10120
10121     case DELETE_EXPR:
10122       {
10123         r = build_nt
10124         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10125          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10126         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10127         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10128         return r;
10129       }
10130
10131     case TEMPLATE_ID_EXPR:
10132       {
10133         /* Substituted template arguments */
10134         tree fn = TREE_OPERAND (t, 0);
10135         tree targs = TREE_OPERAND (t, 1);
10136
10137         fn = tsubst_copy (fn, args, complain, in_decl);
10138         if (targs)
10139           targs = tsubst_template_args (targs, args, complain, in_decl);
10140
10141         return lookup_template_function (fn, targs);
10142       }
10143
10144     case TREE_LIST:
10145       {
10146         tree purpose, value, chain;
10147
10148         if (t == void_list_node)
10149           return t;
10150
10151         purpose = TREE_PURPOSE (t);
10152         if (purpose)
10153           purpose = tsubst_copy (purpose, args, complain, in_decl);
10154         value = TREE_VALUE (t);
10155         if (value)
10156           value = tsubst_copy (value, args, complain, in_decl);
10157         chain = TREE_CHAIN (t);
10158         if (chain && chain != void_type_node)
10159           chain = tsubst_copy (chain, args, complain, in_decl);
10160         if (purpose == TREE_PURPOSE (t)
10161             && value == TREE_VALUE (t)
10162             && chain == TREE_CHAIN (t))
10163           return t;
10164         return tree_cons (purpose, value, chain);
10165       }
10166
10167     case RECORD_TYPE:
10168     case UNION_TYPE:
10169     case ENUMERAL_TYPE:
10170     case INTEGER_TYPE:
10171     case TEMPLATE_TYPE_PARM:
10172     case TEMPLATE_TEMPLATE_PARM:
10173     case BOUND_TEMPLATE_TEMPLATE_PARM:
10174     case TEMPLATE_PARM_INDEX:
10175     case POINTER_TYPE:
10176     case REFERENCE_TYPE:
10177     case OFFSET_TYPE:
10178     case FUNCTION_TYPE:
10179     case METHOD_TYPE:
10180     case ARRAY_TYPE:
10181     case TYPENAME_TYPE:
10182     case UNBOUND_CLASS_TEMPLATE:
10183     case TYPEOF_TYPE:
10184     case DECLTYPE_TYPE:
10185     case TYPE_DECL:
10186       return tsubst (t, args, complain, in_decl);
10187
10188     case IDENTIFIER_NODE:
10189       if (IDENTIFIER_TYPENAME_P (t))
10190         {
10191           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10192           return mangle_conv_op_name_for_type (new_type);
10193         }
10194       else
10195         return t;
10196
10197     case CONSTRUCTOR:
10198       /* This is handled by tsubst_copy_and_build.  */
10199       gcc_unreachable ();
10200
10201     case VA_ARG_EXPR:
10202       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10203                                           in_decl),
10204                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10205
10206     case CLEANUP_POINT_EXPR:
10207       /* We shouldn't have built any of these during initial template
10208          generation.  Instead, they should be built during instantiation
10209          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10210       gcc_unreachable ();
10211
10212     case OFFSET_REF:
10213       mark_used (TREE_OPERAND (t, 1));
10214       return t;
10215
10216     case EXPR_PACK_EXPANSION:
10217       error ("invalid use of pack expansion expression");
10218       return error_mark_node;
10219
10220     case NONTYPE_ARGUMENT_PACK:
10221       error ("use %<...%> to expand argument pack");
10222       return error_mark_node;
10223
10224     default:
10225       return t;
10226     }
10227 }
10228
10229 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10230
10231 static tree
10232 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10233                     tree in_decl)
10234 {
10235   tree new_clauses = NULL, nc, oc;
10236
10237   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10238     {
10239       nc = copy_node (oc);
10240       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10241       new_clauses = nc;
10242
10243       switch (OMP_CLAUSE_CODE (nc))
10244         {
10245         case OMP_CLAUSE_LASTPRIVATE:
10246           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
10247             {
10248               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
10249               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
10250                            in_decl, /*integral_constant_expression_p=*/false);
10251               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
10252                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
10253             }
10254           /* FALLTHRU */
10255         case OMP_CLAUSE_PRIVATE:
10256         case OMP_CLAUSE_SHARED:
10257         case OMP_CLAUSE_FIRSTPRIVATE:
10258         case OMP_CLAUSE_REDUCTION:
10259         case OMP_CLAUSE_COPYIN:
10260         case OMP_CLAUSE_COPYPRIVATE:
10261         case OMP_CLAUSE_IF:
10262         case OMP_CLAUSE_NUM_THREADS:
10263         case OMP_CLAUSE_SCHEDULE:
10264         case OMP_CLAUSE_COLLAPSE:
10265           OMP_CLAUSE_OPERAND (nc, 0)
10266             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10267                            in_decl, /*integral_constant_expression_p=*/false);
10268           break;
10269         case OMP_CLAUSE_NOWAIT:
10270         case OMP_CLAUSE_ORDERED:
10271         case OMP_CLAUSE_DEFAULT:
10272         case OMP_CLAUSE_UNTIED:
10273           break;
10274         default:
10275           gcc_unreachable ();
10276         }
10277     }
10278
10279   return finish_omp_clauses (nreverse (new_clauses));
10280 }
10281
10282 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10283
10284 static tree
10285 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10286                           tree in_decl)
10287 {
10288 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10289
10290   tree purpose, value, chain;
10291
10292   if (t == NULL)
10293     return t;
10294
10295   if (TREE_CODE (t) != TREE_LIST)
10296     return tsubst_copy_and_build (t, args, complain, in_decl,
10297                                   /*function_p=*/false,
10298                                   /*integral_constant_expression_p=*/false);
10299
10300   if (t == void_list_node)
10301     return t;
10302
10303   purpose = TREE_PURPOSE (t);
10304   if (purpose)
10305     purpose = RECUR (purpose);
10306   value = TREE_VALUE (t);
10307   if (value)
10308     value = RECUR (value);
10309   chain = TREE_CHAIN (t);
10310   if (chain && chain != void_type_node)
10311     chain = RECUR (chain);
10312   return tree_cons (purpose, value, chain);
10313 #undef RECUR
10314 }
10315
10316 /* Substitute one OMP_FOR iterator.  */
10317
10318 static void
10319 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
10320                          tree condv, tree incrv, tree *clauses,
10321                          tree args, tsubst_flags_t complain, tree in_decl,
10322                          bool integral_constant_expression_p)
10323 {
10324 #define RECUR(NODE)                             \
10325   tsubst_expr ((NODE), args, complain, in_decl, \
10326                integral_constant_expression_p)
10327   tree decl, init, cond, incr;
10328
10329   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
10330   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10331   decl = RECUR (TREE_OPERAND (init, 0));
10332   init = TREE_OPERAND (init, 1);
10333   gcc_assert (!type_dependent_expression_p (decl));
10334
10335   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
10336     {
10337       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
10338       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10339       if (TREE_CODE (incr) == MODIFY_EXPR)
10340         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
10341                                     RECUR (TREE_OPERAND (incr, 1)),
10342                                     complain);
10343       else
10344         incr = RECUR (incr);
10345       TREE_VEC_ELT (declv, i) = decl;
10346       TREE_VEC_ELT (initv, i) = init;
10347       TREE_VEC_ELT (condv, i) = cond;
10348       TREE_VEC_ELT (incrv, i) = incr;
10349       return;
10350     }
10351
10352   if (init && TREE_CODE (init) != DECL_EXPR)
10353     {
10354       tree c;
10355       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
10356         {
10357           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
10358                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
10359               && OMP_CLAUSE_DECL (c) == decl)
10360             break;
10361           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
10362                    && OMP_CLAUSE_DECL (c) == decl)
10363             error ("iteration variable %qD should not be firstprivate", decl);
10364           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
10365                    && OMP_CLAUSE_DECL (c) == decl)
10366             error ("iteration variable %qD should not be reduction", decl);
10367         }
10368       if (c == NULL)
10369         {
10370           c = build_omp_clause (OMP_CLAUSE_PRIVATE);
10371           OMP_CLAUSE_DECL (c) = decl;
10372           c = finish_omp_clauses (c);
10373           if (c)
10374             {
10375               OMP_CLAUSE_CHAIN (c) = *clauses;
10376               *clauses = c;
10377             }
10378         }
10379     }
10380   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
10381   if (COMPARISON_CLASS_P (cond))
10382     cond = build2 (TREE_CODE (cond), boolean_type_node,
10383                    RECUR (TREE_OPERAND (cond, 0)),
10384                    RECUR (TREE_OPERAND (cond, 1)));
10385   else
10386     cond = RECUR (cond);
10387   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10388   switch (TREE_CODE (incr))
10389     {
10390     case PREINCREMENT_EXPR:
10391     case PREDECREMENT_EXPR:
10392     case POSTINCREMENT_EXPR:
10393     case POSTDECREMENT_EXPR:
10394       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
10395                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
10396       break;
10397     case MODIFY_EXPR:
10398       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10399           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10400         {
10401           tree rhs = TREE_OPERAND (incr, 1);
10402           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10403                          RECUR (TREE_OPERAND (incr, 0)),
10404                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10405                                  RECUR (TREE_OPERAND (rhs, 0)),
10406                                  RECUR (TREE_OPERAND (rhs, 1))));
10407         }
10408       else
10409         incr = RECUR (incr);
10410       break;
10411     case MODOP_EXPR:
10412       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10413           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10414         {
10415           tree lhs = RECUR (TREE_OPERAND (incr, 0));
10416           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
10417                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
10418                                  TREE_TYPE (decl), lhs,
10419                                  RECUR (TREE_OPERAND (incr, 2))));
10420         }
10421       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
10422                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
10423                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
10424         {
10425           tree rhs = TREE_OPERAND (incr, 2);
10426           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10427                          RECUR (TREE_OPERAND (incr, 0)),
10428                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10429                                  RECUR (TREE_OPERAND (rhs, 0)),
10430                                  RECUR (TREE_OPERAND (rhs, 1))));
10431         }
10432       else
10433         incr = RECUR (incr);
10434       break;
10435     default:
10436       incr = RECUR (incr);
10437       break;
10438     }
10439
10440   TREE_VEC_ELT (declv, i) = decl;
10441   TREE_VEC_ELT (initv, i) = init;
10442   TREE_VEC_ELT (condv, i) = cond;
10443   TREE_VEC_ELT (incrv, i) = incr;
10444 #undef RECUR
10445 }
10446
10447 /* Like tsubst_copy for expressions, etc. but also does semantic
10448    processing.  */
10449
10450 static tree
10451 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
10452              bool integral_constant_expression_p)
10453 {
10454 #define RECUR(NODE)                             \
10455   tsubst_expr ((NODE), args, complain, in_decl, \
10456                integral_constant_expression_p)
10457
10458   tree stmt, tmp;
10459
10460   if (t == NULL_TREE || t == error_mark_node)
10461     return t;
10462
10463   if (EXPR_HAS_LOCATION (t))
10464     input_location = EXPR_LOCATION (t);
10465   if (STATEMENT_CODE_P (TREE_CODE (t)))
10466     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
10467
10468   switch (TREE_CODE (t))
10469     {
10470     case STATEMENT_LIST:
10471       {
10472         tree_stmt_iterator i;
10473         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
10474           RECUR (tsi_stmt (i));
10475         break;
10476       }
10477
10478     case CTOR_INITIALIZER:
10479       finish_mem_initializers (tsubst_initializer_list
10480                                (TREE_OPERAND (t, 0), args));
10481       break;
10482
10483     case RETURN_EXPR:
10484       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
10485       break;
10486
10487     case EXPR_STMT:
10488       tmp = RECUR (EXPR_STMT_EXPR (t));
10489       if (EXPR_STMT_STMT_EXPR_RESULT (t))
10490         finish_stmt_expr_expr (tmp, cur_stmt_expr);
10491       else
10492         finish_expr_stmt (tmp);
10493       break;
10494
10495     case USING_STMT:
10496       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
10497       break;
10498
10499     case DECL_EXPR:
10500       {
10501         tree decl;
10502         tree init;
10503
10504         decl = DECL_EXPR_DECL (t);
10505         if (TREE_CODE (decl) == LABEL_DECL)
10506           finish_label_decl (DECL_NAME (decl));
10507         else if (TREE_CODE (decl) == USING_DECL)
10508           {
10509             tree scope = USING_DECL_SCOPE (decl);
10510             tree name = DECL_NAME (decl);
10511             tree decl;
10512
10513             scope = RECUR (scope);
10514             decl = lookup_qualified_name (scope, name,
10515                                           /*is_type_p=*/false,
10516                                           /*complain=*/false);
10517             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
10518               qualified_name_lookup_error (scope, name, decl, input_location);
10519             else
10520               do_local_using_decl (decl, scope, name);
10521           }
10522         else
10523           {
10524             init = DECL_INITIAL (decl);
10525             decl = tsubst (decl, args, complain, in_decl);
10526             if (decl != error_mark_node)
10527               {
10528                 /* By marking the declaration as instantiated, we avoid
10529                    trying to instantiate it.  Since instantiate_decl can't
10530                    handle local variables, and since we've already done
10531                    all that needs to be done, that's the right thing to
10532                    do.  */
10533                 if (TREE_CODE (decl) == VAR_DECL)
10534                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10535                 if (TREE_CODE (decl) == VAR_DECL
10536                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
10537                   /* Anonymous aggregates are a special case.  */
10538                   finish_anon_union (decl);
10539                 else
10540                   {
10541                     maybe_push_decl (decl);
10542                     if (TREE_CODE (decl) == VAR_DECL
10543                         && DECL_PRETTY_FUNCTION_P (decl))
10544                       {
10545                         /* For __PRETTY_FUNCTION__ we have to adjust the
10546                            initializer.  */
10547                         const char *const name
10548                           = cxx_printable_name (current_function_decl, 2);
10549                         init = cp_fname_init (name, &TREE_TYPE (decl));
10550                       }
10551                     else
10552                       {
10553                         tree t = RECUR (init);
10554
10555                         if (init && !t)
10556                           /* If we had an initializer but it
10557                              instantiated to nothing,
10558                              value-initialize the object.  This will
10559                              only occur when the initializer was a
10560                              pack expansion where the parameter packs
10561                              used in that expansion were of length
10562                              zero.  */
10563                           init = build_default_init (TREE_TYPE (decl),
10564                                                      NULL_TREE);
10565                         else
10566                           init = t;
10567                       }
10568
10569                     finish_decl (decl, init, NULL_TREE);
10570                   }
10571               }
10572           }
10573
10574         /* A DECL_EXPR can also be used as an expression, in the condition
10575            clause of an if/for/while construct.  */
10576         return decl;
10577       }
10578
10579     case FOR_STMT:
10580       stmt = begin_for_stmt ();
10581                           RECUR (FOR_INIT_STMT (t));
10582       finish_for_init_stmt (stmt);
10583       tmp = RECUR (FOR_COND (t));
10584       finish_for_cond (tmp, stmt);
10585       tmp = RECUR (FOR_EXPR (t));
10586       finish_for_expr (tmp, stmt);
10587       RECUR (FOR_BODY (t));
10588       finish_for_stmt (stmt);
10589       break;
10590
10591     case WHILE_STMT:
10592       stmt = begin_while_stmt ();
10593       tmp = RECUR (WHILE_COND (t));
10594       finish_while_stmt_cond (tmp, stmt);
10595       RECUR (WHILE_BODY (t));
10596       finish_while_stmt (stmt);
10597       break;
10598
10599     case DO_STMT:
10600       stmt = begin_do_stmt ();
10601       RECUR (DO_BODY (t));
10602       finish_do_body (stmt);
10603       tmp = RECUR (DO_COND (t));
10604       finish_do_stmt (tmp, stmt);
10605       break;
10606
10607     case IF_STMT:
10608       stmt = begin_if_stmt ();
10609       tmp = RECUR (IF_COND (t));
10610       finish_if_stmt_cond (tmp, stmt);
10611       RECUR (THEN_CLAUSE (t));
10612       finish_then_clause (stmt);
10613
10614       if (ELSE_CLAUSE (t))
10615         {
10616           begin_else_clause (stmt);
10617           RECUR (ELSE_CLAUSE (t));
10618           finish_else_clause (stmt);
10619         }
10620
10621       finish_if_stmt (stmt);
10622       break;
10623
10624     case BIND_EXPR:
10625       if (BIND_EXPR_BODY_BLOCK (t))
10626         stmt = begin_function_body ();
10627       else
10628         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
10629                                     ? BCS_TRY_BLOCK : 0);
10630
10631       RECUR (BIND_EXPR_BODY (t));
10632
10633       if (BIND_EXPR_BODY_BLOCK (t))
10634         finish_function_body (stmt);
10635       else
10636         finish_compound_stmt (stmt);
10637       break;
10638
10639     case BREAK_STMT:
10640       finish_break_stmt ();
10641       break;
10642
10643     case CONTINUE_STMT:
10644       finish_continue_stmt ();
10645       break;
10646
10647     case SWITCH_STMT:
10648       stmt = begin_switch_stmt ();
10649       tmp = RECUR (SWITCH_STMT_COND (t));
10650       finish_switch_cond (tmp, stmt);
10651       RECUR (SWITCH_STMT_BODY (t));
10652       finish_switch_stmt (stmt);
10653       break;
10654
10655     case CASE_LABEL_EXPR:
10656       finish_case_label (RECUR (CASE_LOW (t)),
10657                          RECUR (CASE_HIGH (t)));
10658       break;
10659
10660     case LABEL_EXPR:
10661       finish_label_stmt (DECL_NAME (LABEL_EXPR_LABEL (t)));
10662       break;
10663
10664     case GOTO_EXPR:
10665       tmp = GOTO_DESTINATION (t);
10666       if (TREE_CODE (tmp) != LABEL_DECL)
10667         /* Computed goto's must be tsubst'd into.  On the other hand,
10668            non-computed gotos must not be; the identifier in question
10669            will have no binding.  */
10670         tmp = RECUR (tmp);
10671       else
10672         tmp = DECL_NAME (tmp);
10673       finish_goto_stmt (tmp);
10674       break;
10675
10676     case ASM_EXPR:
10677       tmp = finish_asm_stmt
10678         (ASM_VOLATILE_P (t),
10679          RECUR (ASM_STRING (t)),
10680          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
10681          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
10682          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
10683       {
10684         tree asm_expr = tmp;
10685         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
10686           asm_expr = TREE_OPERAND (asm_expr, 0);
10687         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
10688       }
10689       break;
10690
10691     case TRY_BLOCK:
10692       if (CLEANUP_P (t))
10693         {
10694           stmt = begin_try_block ();
10695           RECUR (TRY_STMTS (t));
10696           finish_cleanup_try_block (stmt);
10697           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
10698         }
10699       else
10700         {
10701           tree compound_stmt = NULL_TREE;
10702
10703           if (FN_TRY_BLOCK_P (t))
10704             stmt = begin_function_try_block (&compound_stmt);
10705           else
10706             stmt = begin_try_block ();
10707
10708           RECUR (TRY_STMTS (t));
10709
10710           if (FN_TRY_BLOCK_P (t))
10711             finish_function_try_block (stmt);
10712           else
10713             finish_try_block (stmt);
10714
10715           RECUR (TRY_HANDLERS (t));
10716           if (FN_TRY_BLOCK_P (t))
10717             finish_function_handler_sequence (stmt, compound_stmt);
10718           else
10719             finish_handler_sequence (stmt);
10720         }
10721       break;
10722
10723     case HANDLER:
10724       {
10725         tree decl = HANDLER_PARMS (t);
10726
10727         if (decl)
10728           {
10729             decl = tsubst (decl, args, complain, in_decl);
10730             /* Prevent instantiate_decl from trying to instantiate
10731                this variable.  We've already done all that needs to be
10732                done.  */
10733             if (decl != error_mark_node)
10734               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10735           }
10736         stmt = begin_handler ();
10737         finish_handler_parms (decl, stmt);
10738         RECUR (HANDLER_BODY (t));
10739         finish_handler (stmt);
10740       }
10741       break;
10742
10743     case TAG_DEFN:
10744       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
10745       break;
10746
10747     case STATIC_ASSERT:
10748       {
10749         tree condition = 
10750           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
10751                        args,
10752                        complain, in_decl,
10753                        /*integral_constant_expression_p=*/true);
10754         finish_static_assert (condition,
10755                               STATIC_ASSERT_MESSAGE (t),
10756                               STATIC_ASSERT_SOURCE_LOCATION (t),
10757                               /*member_p=*/false);
10758       }
10759       break;
10760
10761     case OMP_PARALLEL:
10762       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
10763                                 args, complain, in_decl);
10764       stmt = begin_omp_parallel ();
10765       RECUR (OMP_PARALLEL_BODY (t));
10766       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
10767         = OMP_PARALLEL_COMBINED (t);
10768       break;
10769
10770     case OMP_TASK:
10771       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
10772                                 args, complain, in_decl);
10773       stmt = begin_omp_task ();
10774       RECUR (OMP_TASK_BODY (t));
10775       finish_omp_task (tmp, stmt);
10776       break;
10777
10778     case OMP_FOR:
10779       {
10780         tree clauses, body, pre_body;
10781         tree declv, initv, condv, incrv;
10782         int i;
10783
10784         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
10785                                       args, complain, in_decl);
10786         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10787         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10788         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10789         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10790
10791         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
10792           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
10793                                    &clauses, args, complain, in_decl,
10794                                    integral_constant_expression_p);
10795
10796         stmt = begin_omp_structured_block ();
10797
10798         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
10799           if (TREE_VEC_ELT (initv, i) == NULL
10800               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
10801             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
10802           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
10803             {
10804               tree init = RECUR (TREE_VEC_ELT (initv, i));
10805               gcc_assert (init == TREE_VEC_ELT (declv, i));
10806               TREE_VEC_ELT (initv, i) = NULL_TREE;
10807             }
10808           else
10809             {
10810               tree decl_expr = TREE_VEC_ELT (initv, i);
10811               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
10812               gcc_assert (init != NULL);
10813               TREE_VEC_ELT (initv, i) = RECUR (init);
10814               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
10815               RECUR (decl_expr);
10816               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
10817             }
10818
10819         pre_body = push_stmt_list ();
10820         RECUR (OMP_FOR_PRE_BODY (t));
10821         pre_body = pop_stmt_list (pre_body);
10822
10823         body = push_stmt_list ();
10824         RECUR (OMP_FOR_BODY (t));
10825         body = pop_stmt_list (body);
10826
10827         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
10828                             body, pre_body, clauses);
10829
10830         add_stmt (finish_omp_structured_block (stmt));
10831       }
10832       break;
10833
10834     case OMP_SECTIONS:
10835     case OMP_SINGLE:
10836       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
10837       stmt = push_stmt_list ();
10838       RECUR (OMP_BODY (t));
10839       stmt = pop_stmt_list (stmt);
10840
10841       t = copy_node (t);
10842       OMP_BODY (t) = stmt;
10843       OMP_CLAUSES (t) = tmp;
10844       add_stmt (t);
10845       break;
10846
10847     case OMP_SECTION:
10848     case OMP_CRITICAL:
10849     case OMP_MASTER:
10850     case OMP_ORDERED:
10851       stmt = push_stmt_list ();
10852       RECUR (OMP_BODY (t));
10853       stmt = pop_stmt_list (stmt);
10854
10855       t = copy_node (t);
10856       OMP_BODY (t) = stmt;
10857       add_stmt (t);
10858       break;
10859
10860     case OMP_ATOMIC:
10861       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
10862       {
10863         tree op1 = TREE_OPERAND (t, 1);
10864         tree lhs = RECUR (TREE_OPERAND (op1, 0));
10865         tree rhs = RECUR (TREE_OPERAND (op1, 1));
10866         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
10867       }
10868       break;
10869
10870     case EXPR_PACK_EXPANSION:
10871       error ("invalid use of pack expansion expression");
10872       return error_mark_node;
10873
10874     case NONTYPE_ARGUMENT_PACK:
10875       error ("use %<...%> to expand argument pack");
10876       return error_mark_node;
10877
10878     default:
10879       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
10880
10881       return tsubst_copy_and_build (t, args, complain, in_decl,
10882                                     /*function_p=*/false,
10883                                     integral_constant_expression_p);
10884     }
10885
10886   return NULL_TREE;
10887 #undef RECUR
10888 }
10889
10890 /* T is a postfix-expression that is not being used in a function
10891    call.  Return the substituted version of T.  */
10892
10893 static tree
10894 tsubst_non_call_postfix_expression (tree t, tree args,
10895                                     tsubst_flags_t complain,
10896                                     tree in_decl)
10897 {
10898   if (TREE_CODE (t) == SCOPE_REF)
10899     t = tsubst_qualified_id (t, args, complain, in_decl,
10900                              /*done=*/false, /*address_p=*/false);
10901   else
10902     t = tsubst_copy_and_build (t, args, complain, in_decl,
10903                                /*function_p=*/false,
10904                                /*integral_constant_expression_p=*/false);
10905
10906   return t;
10907 }
10908
10909 /* Like tsubst but deals with expressions and performs semantic
10910    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
10911
10912 tree
10913 tsubst_copy_and_build (tree t,
10914                        tree args,
10915                        tsubst_flags_t complain,
10916                        tree in_decl,
10917                        bool function_p,
10918                        bool integral_constant_expression_p)
10919 {
10920 #define RECUR(NODE)                                             \
10921   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
10922                          /*function_p=*/false,                  \
10923                          integral_constant_expression_p)
10924
10925   tree op1;
10926
10927   if (t == NULL_TREE || t == error_mark_node)
10928     return t;
10929
10930   switch (TREE_CODE (t))
10931     {
10932     case USING_DECL:
10933       t = DECL_NAME (t);
10934       /* Fall through.  */
10935     case IDENTIFIER_NODE:
10936       {
10937         tree decl;
10938         cp_id_kind idk;
10939         bool non_integral_constant_expression_p;
10940         const char *error_msg;
10941
10942         if (IDENTIFIER_TYPENAME_P (t))
10943           {
10944             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10945             t = mangle_conv_op_name_for_type (new_type);
10946           }
10947
10948         /* Look up the name.  */
10949         decl = lookup_name (t);
10950
10951         /* By convention, expressions use ERROR_MARK_NODE to indicate
10952            failure, not NULL_TREE.  */
10953         if (decl == NULL_TREE)
10954           decl = error_mark_node;
10955
10956         decl = finish_id_expression (t, decl, NULL_TREE,
10957                                      &idk,
10958                                      integral_constant_expression_p,
10959                                      /*allow_non_integral_constant_expression_p=*/false,
10960                                      &non_integral_constant_expression_p,
10961                                      /*template_p=*/false,
10962                                      /*done=*/true,
10963                                      /*address_p=*/false,
10964                                      /*template_arg_p=*/false,
10965                                      &error_msg,
10966                                      input_location);
10967         if (error_msg)
10968           error (error_msg);
10969         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
10970           decl = unqualified_name_lookup_error (decl);
10971         return decl;
10972       }
10973
10974     case TEMPLATE_ID_EXPR:
10975       {
10976         tree object;
10977         tree templ = RECUR (TREE_OPERAND (t, 0));
10978         tree targs = TREE_OPERAND (t, 1);
10979
10980         if (targs)
10981           targs = tsubst_template_args (targs, args, complain, in_decl);
10982
10983         if (TREE_CODE (templ) == COMPONENT_REF)
10984           {
10985             object = TREE_OPERAND (templ, 0);
10986             templ = TREE_OPERAND (templ, 1);
10987           }
10988         else
10989           object = NULL_TREE;
10990         templ = lookup_template_function (templ, targs);
10991
10992         if (object)
10993           return build3 (COMPONENT_REF, TREE_TYPE (templ),
10994                          object, templ, NULL_TREE);
10995         else
10996           return baselink_for_fns (templ);
10997       }
10998
10999     case INDIRECT_REF:
11000       {
11001         tree r = RECUR (TREE_OPERAND (t, 0));
11002
11003         if (REFERENCE_REF_P (t))
11004           {
11005             /* A type conversion to reference type will be enclosed in
11006                such an indirect ref, but the substitution of the cast
11007                will have also added such an indirect ref.  */
11008             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11009               r = convert_from_reference (r);
11010           }
11011         else
11012           r = build_x_indirect_ref (r, "unary *", complain);
11013         return r;
11014       }
11015
11016     case NOP_EXPR:
11017       return build_nop
11018         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11019          RECUR (TREE_OPERAND (t, 0)));
11020
11021     case CAST_EXPR:
11022     case REINTERPRET_CAST_EXPR:
11023     case CONST_CAST_EXPR:
11024     case DYNAMIC_CAST_EXPR:
11025     case STATIC_CAST_EXPR:
11026       {
11027         tree type;
11028         tree op;
11029
11030         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11031         if (integral_constant_expression_p
11032             && !cast_valid_in_integral_constant_expression_p (type))
11033           {
11034             if (complain & tf_error)
11035               error ("a cast to a type other than an integral or "
11036                      "enumeration type cannot appear in a constant-expression");
11037             return error_mark_node; 
11038           }
11039
11040         op = RECUR (TREE_OPERAND (t, 0));
11041
11042         switch (TREE_CODE (t))
11043           {
11044           case CAST_EXPR:
11045             return build_functional_cast (type, op, complain);
11046           case REINTERPRET_CAST_EXPR:
11047             return build_reinterpret_cast (type, op, complain);
11048           case CONST_CAST_EXPR:
11049             return build_const_cast (type, op, complain);
11050           case DYNAMIC_CAST_EXPR:
11051             return build_dynamic_cast (type, op, complain);
11052           case STATIC_CAST_EXPR:
11053             return build_static_cast (type, op, complain);
11054           default:
11055             gcc_unreachable ();
11056           }
11057       }
11058
11059     case POSTDECREMENT_EXPR:
11060     case POSTINCREMENT_EXPR:
11061       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11062                                                 args, complain, in_decl);
11063       return build_x_unary_op (TREE_CODE (t), op1, complain);
11064
11065     case PREDECREMENT_EXPR:
11066     case PREINCREMENT_EXPR:
11067     case NEGATE_EXPR:
11068     case BIT_NOT_EXPR:
11069     case ABS_EXPR:
11070     case TRUTH_NOT_EXPR:
11071     case UNARY_PLUS_EXPR:  /* Unary + */
11072     case REALPART_EXPR:
11073     case IMAGPART_EXPR:
11074       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11075                                complain);
11076
11077     case ADDR_EXPR:
11078       op1 = TREE_OPERAND (t, 0);
11079       if (TREE_CODE (op1) == SCOPE_REF)
11080         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11081                                    /*done=*/true, /*address_p=*/true);
11082       else
11083         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11084                                                   in_decl);
11085       if (TREE_CODE (op1) == LABEL_DECL)
11086         return finish_label_address_expr (DECL_NAME (op1),
11087                                           EXPR_LOCATION (op1));
11088       return build_x_unary_op (ADDR_EXPR, op1, complain);
11089
11090     case PLUS_EXPR:
11091     case MINUS_EXPR:
11092     case MULT_EXPR:
11093     case TRUNC_DIV_EXPR:
11094     case CEIL_DIV_EXPR:
11095     case FLOOR_DIV_EXPR:
11096     case ROUND_DIV_EXPR:
11097     case EXACT_DIV_EXPR:
11098     case BIT_AND_EXPR:
11099     case BIT_IOR_EXPR:
11100     case BIT_XOR_EXPR:
11101     case TRUNC_MOD_EXPR:
11102     case FLOOR_MOD_EXPR:
11103     case TRUTH_ANDIF_EXPR:
11104     case TRUTH_ORIF_EXPR:
11105     case TRUTH_AND_EXPR:
11106     case TRUTH_OR_EXPR:
11107     case RSHIFT_EXPR:
11108     case LSHIFT_EXPR:
11109     case RROTATE_EXPR:
11110     case LROTATE_EXPR:
11111     case EQ_EXPR:
11112     case NE_EXPR:
11113     case MAX_EXPR:
11114     case MIN_EXPR:
11115     case LE_EXPR:
11116     case GE_EXPR:
11117     case LT_EXPR:
11118     case GT_EXPR:
11119     case MEMBER_REF:
11120     case DOTSTAR_EXPR:
11121       return build_x_binary_op
11122         (TREE_CODE (t),
11123          RECUR (TREE_OPERAND (t, 0)),
11124          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11125           ? ERROR_MARK
11126           : TREE_CODE (TREE_OPERAND (t, 0))),
11127          RECUR (TREE_OPERAND (t, 1)),
11128          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11129           ? ERROR_MARK
11130           : TREE_CODE (TREE_OPERAND (t, 1))),
11131          /*overloaded_p=*/NULL,
11132          complain);
11133
11134     case SCOPE_REF:
11135       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11136                                   /*address_p=*/false);
11137     case ARRAY_REF:
11138       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11139                                                 args, complain, in_decl);
11140       return build_x_binary_op (ARRAY_REF, op1,
11141                                 (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11142                                  ? ERROR_MARK
11143                                  : TREE_CODE (TREE_OPERAND (t, 0))),
11144                                 RECUR (TREE_OPERAND (t, 1)),
11145                                 (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11146                                  ? ERROR_MARK
11147                                  : TREE_CODE (TREE_OPERAND (t, 1))),
11148                                 /*overloaded_p=*/NULL,
11149                                 complain);
11150
11151     case SIZEOF_EXPR:
11152       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11153         return tsubst_copy (t, args, complain, in_decl);
11154       /* Fall through */
11155       
11156     case ALIGNOF_EXPR:
11157       op1 = TREE_OPERAND (t, 0);
11158       if (!args)
11159         {
11160           /* When there are no ARGS, we are trying to evaluate a
11161              non-dependent expression from the parser.  Trying to do
11162              the substitutions may not work.  */
11163           if (!TYPE_P (op1))
11164             op1 = TREE_TYPE (op1);
11165         }
11166       else
11167         {
11168           ++skip_evaluation;
11169           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11170                                        /*function_p=*/false,
11171                                        /*integral_constant_expression_p=*/false);
11172           --skip_evaluation;
11173         }
11174       if (TYPE_P (op1))
11175         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11176                                            complain & tf_error);
11177       else
11178         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11179                                            complain & tf_error);
11180
11181     case MODOP_EXPR:
11182       {
11183         tree r = build_x_modify_expr
11184           (RECUR (TREE_OPERAND (t, 0)),
11185            TREE_CODE (TREE_OPERAND (t, 1)),
11186            RECUR (TREE_OPERAND (t, 2)),
11187            complain);
11188         /* TREE_NO_WARNING must be set if either the expression was
11189            parenthesized or it uses an operator such as >>= rather
11190            than plain assignment.  In the former case, it was already
11191            set and must be copied.  In the latter case,
11192            build_x_modify_expr sets it and it must not be reset
11193            here.  */
11194         if (TREE_NO_WARNING (t))
11195           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11196         return r;
11197       }
11198
11199     case ARROW_EXPR:
11200       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11201                                                 args, complain, in_decl);
11202       /* Remember that there was a reference to this entity.  */
11203       if (DECL_P (op1))
11204         mark_used (op1);
11205       return build_x_arrow (op1);
11206
11207     case NEW_EXPR:
11208       {
11209         tree init = RECUR (TREE_OPERAND (t, 3));
11210
11211         if (TREE_OPERAND (t, 3) && !init)
11212           /* If there was an initializer in the original tree, but
11213              it instantiated to an empty list, then we should pass on
11214              VOID_ZERO_NODE to tell build_new that it was an empty
11215              initializer () rather than no initializer.  This can only
11216              happen when the initializer is a pack expansion whose
11217              parameter packs are of length zero.  */
11218           init = void_zero_node;
11219
11220         return build_new
11221           (RECUR (TREE_OPERAND (t, 0)),
11222            RECUR (TREE_OPERAND (t, 1)),
11223            RECUR (TREE_OPERAND (t, 2)),
11224            init,
11225            NEW_EXPR_USE_GLOBAL (t),
11226            complain);
11227       }
11228
11229     case DELETE_EXPR:
11230      return delete_sanity
11231        (RECUR (TREE_OPERAND (t, 0)),
11232         RECUR (TREE_OPERAND (t, 1)),
11233         DELETE_EXPR_USE_VEC (t),
11234         DELETE_EXPR_USE_GLOBAL (t));
11235
11236     case COMPOUND_EXPR:
11237       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
11238                                     RECUR (TREE_OPERAND (t, 1)),
11239                                     complain);
11240
11241     case CALL_EXPR:
11242       {
11243         tree function;
11244         tree call_args;
11245         bool qualified_p;
11246         bool koenig_p;
11247
11248         function = CALL_EXPR_FN (t);
11249         /* When we parsed the expression,  we determined whether or
11250            not Koenig lookup should be performed.  */
11251         koenig_p = KOENIG_LOOKUP_P (t);
11252         if (TREE_CODE (function) == SCOPE_REF)
11253           {
11254             qualified_p = true;
11255             function = tsubst_qualified_id (function, args, complain, in_decl,
11256                                             /*done=*/false,
11257                                             /*address_p=*/false);
11258           }
11259         else
11260           {
11261             if (TREE_CODE (function) == COMPONENT_REF)
11262               {
11263                 tree op = TREE_OPERAND (function, 1);
11264
11265                 qualified_p = (TREE_CODE (op) == SCOPE_REF
11266                                || (BASELINK_P (op)
11267                                    && BASELINK_QUALIFIED_P (op)));
11268               }
11269             else
11270               qualified_p = false;
11271
11272             function = tsubst_copy_and_build (function, args, complain,
11273                                               in_decl,
11274                                               !qualified_p,
11275                                               integral_constant_expression_p);
11276
11277             if (BASELINK_P (function))
11278               qualified_p = true;
11279           }
11280
11281         /* FIXME:  Rewrite this so as not to construct an arglist.  */
11282         call_args = RECUR (CALL_EXPR_ARGS (t));
11283
11284         /* We do not perform argument-dependent lookup if normal
11285            lookup finds a non-function, in accordance with the
11286            expected resolution of DR 218.  */
11287         if (koenig_p
11288             && ((is_overloaded_fn (function)
11289                  /* If lookup found a member function, the Koenig lookup is
11290                     not appropriate, even if an unqualified-name was used
11291                     to denote the function.  */
11292                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
11293                 || TREE_CODE (function) == IDENTIFIER_NODE))
11294           function = perform_koenig_lookup (function, call_args);
11295
11296         if (TREE_CODE (function) == IDENTIFIER_NODE)
11297           {
11298             unqualified_name_lookup_error (function);
11299             return error_mark_node;
11300           }
11301
11302         /* Remember that there was a reference to this entity.  */
11303         if (DECL_P (function))
11304           mark_used (function);
11305
11306         if (TREE_CODE (function) == OFFSET_REF)
11307           return build_offset_ref_call_from_tree (function, call_args);
11308         if (TREE_CODE (function) == COMPONENT_REF)
11309           {
11310             if (!BASELINK_P (TREE_OPERAND (function, 1)))
11311               return finish_call_expr (function, call_args,
11312                                        /*disallow_virtual=*/false,
11313                                        /*koenig_p=*/false,
11314                                        complain);
11315             else
11316               return (build_new_method_call
11317                       (TREE_OPERAND (function, 0),
11318                        TREE_OPERAND (function, 1),
11319                        call_args, NULL_TREE,
11320                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
11321                        /*fn_p=*/NULL,
11322                        complain));
11323           }
11324         return finish_call_expr (function, call_args,
11325                                  /*disallow_virtual=*/qualified_p,
11326                                  koenig_p,
11327                                  complain);
11328       }
11329
11330     case COND_EXPR:
11331       return build_x_conditional_expr
11332         (RECUR (TREE_OPERAND (t, 0)),
11333          RECUR (TREE_OPERAND (t, 1)),
11334          RECUR (TREE_OPERAND (t, 2)),
11335          complain);
11336
11337     case PSEUDO_DTOR_EXPR:
11338       return finish_pseudo_destructor_expr
11339         (RECUR (TREE_OPERAND (t, 0)),
11340          RECUR (TREE_OPERAND (t, 1)),
11341          RECUR (TREE_OPERAND (t, 2)));
11342
11343     case TREE_LIST:
11344       {
11345         tree purpose, value, chain;
11346
11347         if (t == void_list_node)
11348           return t;
11349
11350         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
11351             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
11352           {
11353             /* We have pack expansions, so expand those and
11354                create a new list out of it.  */
11355             tree purposevec = NULL_TREE;
11356             tree valuevec = NULL_TREE;
11357             tree chain;
11358             int i, len = -1;
11359
11360             /* Expand the argument expressions.  */
11361             if (TREE_PURPOSE (t))
11362               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
11363                                                  complain, in_decl);
11364             if (TREE_VALUE (t))
11365               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
11366                                                complain, in_decl);
11367
11368             /* Build the rest of the list.  */
11369             chain = TREE_CHAIN (t);
11370             if (chain && chain != void_type_node)
11371               chain = RECUR (chain);
11372
11373             /* Determine the number of arguments.  */
11374             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
11375               {
11376                 len = TREE_VEC_LENGTH (purposevec);
11377                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
11378               }
11379             else if (TREE_CODE (valuevec) == TREE_VEC)
11380               len = TREE_VEC_LENGTH (valuevec);
11381             else
11382               {
11383                 /* Since we only performed a partial substitution into
11384                    the argument pack, we only return a single list
11385                    node.  */
11386                 if (purposevec == TREE_PURPOSE (t)
11387                     && valuevec == TREE_VALUE (t)
11388                     && chain == TREE_CHAIN (t))
11389                   return t;
11390
11391                 return tree_cons (purposevec, valuevec, chain);
11392               }
11393             
11394             /* Convert the argument vectors into a TREE_LIST */
11395             i = len;
11396             while (i > 0)
11397               {
11398                 /* Grab the Ith values.  */
11399                 i--;
11400                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
11401                                      : NULL_TREE;
11402                 value 
11403                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
11404                              : NULL_TREE;
11405
11406                 /* Build the list (backwards).  */
11407                 chain = tree_cons (purpose, value, chain);
11408               }
11409
11410             return chain;
11411           }
11412
11413         purpose = TREE_PURPOSE (t);
11414         if (purpose)
11415           purpose = RECUR (purpose);
11416         value = TREE_VALUE (t);
11417         if (value)
11418           value = RECUR (value);
11419         chain = TREE_CHAIN (t);
11420         if (chain && chain != void_type_node)
11421           chain = RECUR (chain);
11422         if (purpose == TREE_PURPOSE (t)
11423             && value == TREE_VALUE (t)
11424             && chain == TREE_CHAIN (t))
11425           return t;
11426         return tree_cons (purpose, value, chain);
11427       }
11428
11429     case COMPONENT_REF:
11430       {
11431         tree object;
11432         tree object_type;
11433         tree member;
11434
11435         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11436                                                      args, complain, in_decl);
11437         /* Remember that there was a reference to this entity.  */
11438         if (DECL_P (object))
11439           mark_used (object);
11440         object_type = TREE_TYPE (object);
11441
11442         member = TREE_OPERAND (t, 1);
11443         if (BASELINK_P (member))
11444           member = tsubst_baselink (member,
11445                                     non_reference (TREE_TYPE (object)),
11446                                     args, complain, in_decl);
11447         else
11448           member = tsubst_copy (member, args, complain, in_decl);
11449         if (member == error_mark_node)
11450           return error_mark_node;
11451
11452         if (object_type && !CLASS_TYPE_P (object_type))
11453           {
11454             if (SCALAR_TYPE_P (object_type))
11455               {
11456                 tree s = NULL_TREE;
11457                 tree dtor = member;
11458
11459                 if (TREE_CODE (dtor) == SCOPE_REF)
11460                   {
11461                     s = TREE_OPERAND (dtor, 0);
11462                     dtor = TREE_OPERAND (dtor, 1);
11463                   }
11464                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
11465                   {
11466                     dtor = TREE_OPERAND (dtor, 0);
11467                     if (TYPE_P (dtor))
11468                       return finish_pseudo_destructor_expr (object, s, dtor);
11469                   }
11470               }
11471           }
11472         else if (TREE_CODE (member) == SCOPE_REF
11473                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
11474           {
11475             tree tmpl;
11476             tree args;
11477
11478             /* Lookup the template functions now that we know what the
11479                scope is.  */
11480             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
11481             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
11482             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
11483                                             /*is_type_p=*/false,
11484                                             /*complain=*/false);
11485             if (BASELINK_P (member))
11486               {
11487                 BASELINK_FUNCTIONS (member)
11488                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
11489                               args);
11490                 member = (adjust_result_of_qualified_name_lookup
11491                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
11492                            object_type));
11493               }
11494             else
11495               {
11496                 qualified_name_lookup_error (object_type, tmpl, member,
11497                                              input_location);
11498                 return error_mark_node;
11499               }
11500           }
11501         else if (TREE_CODE (member) == SCOPE_REF
11502                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
11503                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
11504           {
11505             if (complain & tf_error)
11506               {
11507                 if (TYPE_P (TREE_OPERAND (member, 0)))
11508                   error ("%qT is not a class or namespace",
11509                          TREE_OPERAND (member, 0));
11510                 else
11511                   error ("%qD is not a class or namespace",
11512                          TREE_OPERAND (member, 0));
11513               }
11514             return error_mark_node;
11515           }
11516         else if (TREE_CODE (member) == FIELD_DECL)
11517           return finish_non_static_data_member (member, object, NULL_TREE);
11518
11519         return finish_class_member_access_expr (object, member,
11520                                                 /*template_p=*/false,
11521                                                 complain);
11522       }
11523
11524     case THROW_EXPR:
11525       return build_throw
11526         (RECUR (TREE_OPERAND (t, 0)));
11527
11528     case CONSTRUCTOR:
11529       {
11530         VEC(constructor_elt,gc) *n;
11531         constructor_elt *ce;
11532         unsigned HOST_WIDE_INT idx;
11533         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11534         bool process_index_p;
11535         int newlen;
11536         bool need_copy_p = false;
11537         tree r;
11538
11539         if (type == error_mark_node)
11540           return error_mark_node;
11541
11542         /* digest_init will do the wrong thing if we let it.  */
11543         if (type && TYPE_PTRMEMFUNC_P (type))
11544           return t;
11545
11546         /* We do not want to process the index of aggregate
11547            initializers as they are identifier nodes which will be
11548            looked up by digest_init.  */
11549         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
11550
11551         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
11552         newlen = VEC_length (constructor_elt, n);
11553         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
11554           {
11555             if (ce->index && process_index_p)
11556               ce->index = RECUR (ce->index);
11557
11558             if (PACK_EXPANSION_P (ce->value))
11559               {
11560                 /* Substitute into the pack expansion.  */
11561                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
11562                                                   in_decl);
11563
11564                 if (ce->value == error_mark_node)
11565                   ;
11566                 else if (TREE_VEC_LENGTH (ce->value) == 1)
11567                   /* Just move the argument into place.  */
11568                   ce->value = TREE_VEC_ELT (ce->value, 0);
11569                 else
11570                   {
11571                     /* Update the length of the final CONSTRUCTOR
11572                        arguments vector, and note that we will need to
11573                        copy.*/
11574                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
11575                     need_copy_p = true;
11576                   }
11577               }
11578             else
11579               ce->value = RECUR (ce->value);
11580           }
11581
11582         if (need_copy_p)
11583           {
11584             VEC(constructor_elt,gc) *old_n = n;
11585
11586             n = VEC_alloc (constructor_elt, gc, newlen);
11587             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
11588                  idx++)
11589               {
11590                 if (TREE_CODE (ce->value) == TREE_VEC)
11591                   {
11592                     int i, len = TREE_VEC_LENGTH (ce->value);
11593                     for (i = 0; i < len; ++i)
11594                       CONSTRUCTOR_APPEND_ELT (n, 0,
11595                                               TREE_VEC_ELT (ce->value, i));
11596                   }
11597                 else
11598                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
11599               }
11600           }
11601
11602         r = build_constructor (init_list_type_node, n);
11603
11604         if (TREE_HAS_CONSTRUCTOR (t))
11605           return finish_compound_literal (type, r);
11606
11607         return r;
11608       }
11609
11610     case TYPEID_EXPR:
11611       {
11612         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
11613         if (TYPE_P (operand_0))
11614           return get_typeid (operand_0);
11615         return build_typeid (operand_0);
11616       }
11617
11618     case VAR_DECL:
11619       if (!args)
11620         return t;
11621       /* Fall through */
11622
11623     case PARM_DECL:
11624       {
11625         tree r = tsubst_copy (t, args, complain, in_decl);
11626
11627         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
11628           /* If the original type was a reference, we'll be wrapped in
11629              the appropriate INDIRECT_REF.  */
11630           r = convert_from_reference (r);
11631         return r;
11632       }
11633
11634     case VA_ARG_EXPR:
11635       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
11636                              tsubst_copy (TREE_TYPE (t), args, complain,
11637                                           in_decl));
11638
11639     case OFFSETOF_EXPR:
11640       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
11641
11642     case TRAIT_EXPR:
11643       {
11644         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
11645                                   complain, in_decl);
11646
11647         tree type2 = TRAIT_EXPR_TYPE2 (t);
11648         if (type2)
11649           type2 = tsubst_copy (type2, args, complain, in_decl);
11650         
11651         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
11652       }
11653
11654     case STMT_EXPR:
11655       {
11656         tree old_stmt_expr = cur_stmt_expr;
11657         tree stmt_expr = begin_stmt_expr ();
11658
11659         cur_stmt_expr = stmt_expr;
11660         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
11661                      integral_constant_expression_p);
11662         stmt_expr = finish_stmt_expr (stmt_expr, false);
11663         cur_stmt_expr = old_stmt_expr;
11664
11665         return stmt_expr;
11666       }
11667
11668     case CONST_DECL:
11669       t = tsubst_copy (t, args, complain, in_decl);
11670       /* As in finish_id_expression, we resolve enumeration constants
11671          to their underlying values.  */
11672       if (TREE_CODE (t) == CONST_DECL)
11673         {
11674           used_types_insert (TREE_TYPE (t));
11675           return DECL_INITIAL (t);
11676         }
11677       return t;
11678
11679     default:
11680       /* Handle Objective-C++ constructs, if appropriate.  */
11681       {
11682         tree subst
11683           = objcp_tsubst_copy_and_build (t, args, complain,
11684                                          in_decl, /*function_p=*/false);
11685         if (subst)
11686           return subst;
11687       }
11688       return tsubst_copy (t, args, complain, in_decl);
11689     }
11690
11691 #undef RECUR
11692 }
11693
11694 /* Verify that the instantiated ARGS are valid. For type arguments,
11695    make sure that the type's linkage is ok. For non-type arguments,
11696    make sure they are constants if they are integral or enumerations.
11697    Emit an error under control of COMPLAIN, and return TRUE on error.  */
11698
11699 static bool
11700 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
11701 {
11702   int ix, len = DECL_NTPARMS (tmpl);
11703   bool result = false;
11704
11705   for (ix = 0; ix != len; ix++)
11706     {
11707       tree t = TREE_VEC_ELT (args, ix);
11708
11709       if (TYPE_P (t))
11710         {
11711           /* [basic.link]: A name with no linkage (notably, the name
11712              of a class or enumeration declared in a local scope)
11713              shall not be used to declare an entity with linkage.
11714              This implies that names with no linkage cannot be used as
11715              template arguments.  */
11716           tree nt = no_linkage_check (t, /*relaxed_p=*/false);
11717
11718           if (nt)
11719             {
11720               /* DR 488 makes use of a type with no linkage cause
11721                  type deduction to fail.  */
11722               if (complain & tf_error)
11723                 {
11724                   if (TYPE_ANONYMOUS_P (nt))
11725                     error ("%qT is/uses anonymous type", t);
11726                   else
11727                     error ("template argument for %qD uses local type %qT",
11728                            tmpl, t);
11729                 }
11730               result = true;
11731             }
11732           /* In order to avoid all sorts of complications, we do not
11733              allow variably-modified types as template arguments.  */
11734           else if (variably_modified_type_p (t, NULL_TREE))
11735             {
11736               if (complain & tf_error)
11737                 error ("%qT is a variably modified type", t);
11738               result = true;
11739             }
11740         }
11741       /* A non-type argument of integral or enumerated type must be a
11742          constant.  */
11743       else if (TREE_TYPE (t)
11744                && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
11745                && !TREE_CONSTANT (t))
11746         {
11747           if (complain & tf_error)
11748             error ("integral expression %qE is not constant", t);
11749           result = true;
11750         }
11751     }
11752   if (result && (complain & tf_error))
11753     error ("  trying to instantiate %qD", tmpl);
11754   return result;
11755 }
11756
11757 /* Instantiate the indicated variable or function template TMPL with
11758    the template arguments in TARG_PTR.  */
11759
11760 tree
11761 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
11762 {
11763   tree fndecl;
11764   tree gen_tmpl;
11765   tree spec;
11766   HOST_WIDE_INT saved_processing_template_decl;
11767
11768   if (tmpl == error_mark_node)
11769     return error_mark_node;
11770
11771   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
11772
11773   /* If this function is a clone, handle it specially.  */
11774   if (DECL_CLONED_FUNCTION_P (tmpl))
11775     {
11776       tree spec;
11777       tree clone;
11778
11779       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
11780                                    complain);
11781       if (spec == error_mark_node)
11782         return error_mark_node;
11783
11784       /* Look for the clone.  */
11785       FOR_EACH_CLONE (clone, spec)
11786         if (DECL_NAME (clone) == DECL_NAME (tmpl))
11787           return clone;
11788       /* We should always have found the clone by now.  */
11789       gcc_unreachable ();
11790       return NULL_TREE;
11791     }
11792
11793   /* Check to see if we already have this specialization.  */
11794   spec = retrieve_specialization (tmpl, targ_ptr,
11795                                   /*class_specializations_p=*/false);
11796   if (spec != NULL_TREE)
11797     return spec;
11798
11799   gen_tmpl = most_general_template (tmpl);
11800   if (tmpl != gen_tmpl)
11801     {
11802       /* The TMPL is a partial instantiation.  To get a full set of
11803          arguments we must add the arguments used to perform the
11804          partial instantiation.  */
11805       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
11806                                               targ_ptr);
11807
11808       /* Check to see if we already have this specialization.  */
11809       spec = retrieve_specialization (gen_tmpl, targ_ptr,
11810                                       /*class_specializations_p=*/false);
11811       if (spec != NULL_TREE)
11812         return spec;
11813     }
11814
11815   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
11816                                complain))
11817     return error_mark_node;
11818
11819   /* We are building a FUNCTION_DECL, during which the access of its
11820      parameters and return types have to be checked.  However this
11821      FUNCTION_DECL which is the desired context for access checking
11822      is not built yet.  We solve this chicken-and-egg problem by
11823      deferring all checks until we have the FUNCTION_DECL.  */
11824   push_deferring_access_checks (dk_deferred);
11825
11826   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
11827      (because, for example, we have encountered a non-dependent
11828      function call in the body of a template function and must now
11829      determine which of several overloaded functions will be called),
11830      within the instantiation itself we are not processing a
11831      template.  */  
11832   saved_processing_template_decl = processing_template_decl;
11833   processing_template_decl = 0;
11834   /* Substitute template parameters to obtain the specialization.  */
11835   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
11836                    targ_ptr, complain, gen_tmpl);
11837   processing_template_decl = saved_processing_template_decl;
11838   if (fndecl == error_mark_node)
11839     return error_mark_node;
11840
11841   /* Now we know the specialization, compute access previously
11842      deferred.  */
11843   push_access_scope (fndecl);
11844   perform_deferred_access_checks ();
11845   pop_access_scope (fndecl);
11846   pop_deferring_access_checks ();
11847
11848   /* The DECL_TI_TEMPLATE should always be the immediate parent
11849      template, not the most general template.  */
11850   DECL_TI_TEMPLATE (fndecl) = tmpl;
11851
11852   /* If we've just instantiated the main entry point for a function,
11853      instantiate all the alternate entry points as well.  We do this
11854      by cloning the instantiation of the main entry point, not by
11855      instantiating the template clones.  */
11856   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
11857     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
11858
11859   return fndecl;
11860 }
11861
11862 /* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
11863    arguments that are being used when calling it.  TARGS is a vector
11864    into which the deduced template arguments are placed.
11865
11866    Return zero for success, 2 for an incomplete match that doesn't resolve
11867    all the types, and 1 for complete failure.  An error message will be
11868    printed only for an incomplete match.
11869
11870    If FN is a conversion operator, or we are trying to produce a specific
11871    specialization, RETURN_TYPE is the return type desired.
11872
11873    The EXPLICIT_TARGS are explicit template arguments provided via a
11874    template-id.
11875
11876    The parameter STRICT is one of:
11877
11878    DEDUCE_CALL:
11879      We are deducing arguments for a function call, as in
11880      [temp.deduct.call].
11881
11882    DEDUCE_CONV:
11883      We are deducing arguments for a conversion function, as in
11884      [temp.deduct.conv].
11885
11886    DEDUCE_EXACT:
11887      We are deducing arguments when doing an explicit instantiation
11888      as in [temp.explicit], when determining an explicit specialization
11889      as in [temp.expl.spec], or when taking the address of a function
11890      template, as in [temp.deduct.funcaddr].  */
11891
11892 int
11893 fn_type_unification (tree fn,
11894                      tree explicit_targs,
11895                      tree targs,
11896                      tree args,
11897                      tree return_type,
11898                      unification_kind_t strict,
11899                      int flags)
11900 {
11901   tree parms;
11902   tree fntype;
11903   int result;
11904   bool incomplete_argument_packs_p = false;
11905
11906   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
11907
11908   fntype = TREE_TYPE (fn);
11909   if (explicit_targs)
11910     {
11911       /* [temp.deduct]
11912
11913          The specified template arguments must match the template
11914          parameters in kind (i.e., type, nontype, template), and there
11915          must not be more arguments than there are parameters;
11916          otherwise type deduction fails.
11917
11918          Nontype arguments must match the types of the corresponding
11919          nontype template parameters, or must be convertible to the
11920          types of the corresponding nontype parameters as specified in
11921          _temp.arg.nontype_, otherwise type deduction fails.
11922
11923          All references in the function type of the function template
11924          to the corresponding template parameters are replaced by the
11925          specified template argument values.  If a substitution in a
11926          template parameter or in the function type of the function
11927          template results in an invalid type, type deduction fails.  */
11928       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
11929       int i, len = TREE_VEC_LENGTH (tparms);
11930       tree converted_args;
11931       bool incomplete = false;
11932
11933       if (explicit_targs == error_mark_node)
11934         return 1;
11935
11936       converted_args
11937         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
11938                                   /*require_all_args=*/false,
11939                                   /*use_default_args=*/false));
11940       if (converted_args == error_mark_node)
11941         return 1;
11942
11943       /* Substitute the explicit args into the function type.  This is
11944          necessary so that, for instance, explicitly declared function
11945          arguments can match null pointed constants.  If we were given
11946          an incomplete set of explicit args, we must not do semantic
11947          processing during substitution as we could create partial
11948          instantiations.  */
11949       for (i = 0; i < len; i++)
11950         {
11951           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
11952           bool parameter_pack = false;
11953
11954           /* Dig out the actual parm.  */
11955           if (TREE_CODE (parm) == TYPE_DECL
11956               || TREE_CODE (parm) == TEMPLATE_DECL)
11957             {
11958               parm = TREE_TYPE (parm);
11959               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
11960             }
11961           else if (TREE_CODE (parm) == PARM_DECL)
11962             {
11963               parm = DECL_INITIAL (parm);
11964               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
11965             }
11966
11967           if (parameter_pack)
11968             {
11969               int level, idx;
11970               tree targ;
11971               template_parm_level_and_index (parm, &level, &idx);
11972
11973               /* Mark the argument pack as "incomplete". We could
11974                  still deduce more arguments during unification.  */
11975               targ = TMPL_ARG (converted_args, level, idx);
11976               if (targ)
11977                 {
11978                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
11979                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
11980                     = ARGUMENT_PACK_ARGS (targ);
11981                 }
11982
11983               /* We have some incomplete argument packs.  */
11984               incomplete_argument_packs_p = true;
11985             }
11986         }
11987
11988       if (incomplete_argument_packs_p)
11989         /* Any substitution is guaranteed to be incomplete if there
11990            are incomplete argument packs, because we can still deduce
11991            more arguments.  */
11992         incomplete = 1;
11993       else
11994         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
11995
11996       processing_template_decl += incomplete;
11997       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
11998       processing_template_decl -= incomplete;
11999
12000       if (fntype == error_mark_node)
12001         return 1;
12002
12003       /* Place the explicitly specified arguments in TARGS.  */
12004       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12005         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12006     }
12007
12008   /* Never do unification on the 'this' parameter.  */
12009   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12010
12011   if (return_type)
12012     {
12013       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12014       args = tree_cons (NULL_TREE, return_type, args);
12015     }
12016
12017   /* We allow incomplete unification without an error message here
12018      because the standard doesn't seem to explicitly prohibit it.  Our
12019      callers must be ready to deal with unification failures in any
12020      event.  */
12021   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12022                                   targs, parms, args, /*subr=*/0,
12023                                   strict, flags);
12024
12025   if (result == 0 && incomplete_argument_packs_p)
12026     {
12027       int i, len = NUM_TMPL_ARGS (targs);
12028
12029       /* Clear the "incomplete" flags on all argument packs.  */
12030       for (i = 0; i < len; i++)
12031         {
12032           tree arg = TREE_VEC_ELT (targs, i);
12033           if (ARGUMENT_PACK_P (arg))
12034             {
12035               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12036               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12037             }
12038         }
12039     }
12040
12041   /* Now that we have bindings for all of the template arguments,
12042      ensure that the arguments deduced for the template template
12043      parameters have compatible template parameter lists.  We cannot
12044      check this property before we have deduced all template
12045      arguments, because the template parameter types of a template
12046      template parameter might depend on prior template parameters
12047      deduced after the template template parameter.  The following
12048      ill-formed example illustrates this issue:
12049
12050        template<typename T, template<T> class C> void f(C<5>, T);
12051
12052        template<int N> struct X {};
12053
12054        void g() {
12055          f(X<5>(), 5l); // error: template argument deduction fails
12056        }
12057
12058      The template parameter list of 'C' depends on the template type
12059      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
12060      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
12061      time that we deduce 'C'.  */
12062   if (result == 0
12063       && !template_template_parm_bindings_ok_p 
12064            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
12065     return 1;
12066
12067   if (result == 0)
12068     /* All is well so far.  Now, check:
12069
12070        [temp.deduct]
12071
12072        When all template arguments have been deduced, all uses of
12073        template parameters in nondeduced contexts are replaced with
12074        the corresponding deduced argument values.  If the
12075        substitution results in an invalid type, as described above,
12076        type deduction fails.  */
12077     if (tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE)
12078         == error_mark_node)
12079       return 1;
12080
12081   return result;
12082 }
12083
12084 /* Adjust types before performing type deduction, as described in
12085    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
12086    sections are symmetric.  PARM is the type of a function parameter
12087    or the return type of the conversion function.  ARG is the type of
12088    the argument passed to the call, or the type of the value
12089    initialized with the result of the conversion function.
12090    ARG_EXPR is the original argument expression, which may be null.  */
12091
12092 static int
12093 maybe_adjust_types_for_deduction (unification_kind_t strict,
12094                                   tree* parm,
12095                                   tree* arg,
12096                                   tree arg_expr)
12097 {
12098   int result = 0;
12099
12100   switch (strict)
12101     {
12102     case DEDUCE_CALL:
12103       break;
12104
12105     case DEDUCE_CONV:
12106       {
12107         /* Swap PARM and ARG throughout the remainder of this
12108            function; the handling is precisely symmetric since PARM
12109            will initialize ARG rather than vice versa.  */
12110         tree* temp = parm;
12111         parm = arg;
12112         arg = temp;
12113         break;
12114       }
12115
12116     case DEDUCE_EXACT:
12117       /* There is nothing to do in this case.  */
12118       return 0;
12119
12120     default:
12121       gcc_unreachable ();
12122     }
12123
12124   if (TREE_CODE (*parm) != REFERENCE_TYPE)
12125     {
12126       /* [temp.deduct.call]
12127
12128          If P is not a reference type:
12129
12130          --If A is an array type, the pointer type produced by the
12131          array-to-pointer standard conversion (_conv.array_) is
12132          used in place of A for type deduction; otherwise,
12133
12134          --If A is a function type, the pointer type produced by
12135          the function-to-pointer standard conversion
12136          (_conv.func_) is used in place of A for type deduction;
12137          otherwise,
12138
12139          --If A is a cv-qualified type, the top level
12140          cv-qualifiers of A's type are ignored for type
12141          deduction.  */
12142       if (TREE_CODE (*arg) == ARRAY_TYPE)
12143         *arg = build_pointer_type (TREE_TYPE (*arg));
12144       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
12145         *arg = build_pointer_type (*arg);
12146       else
12147         *arg = TYPE_MAIN_VARIANT (*arg);
12148     }
12149
12150   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
12151      of the form T&&, where T is a template parameter, and the argument
12152      is an lvalue, T is deduced as A& */
12153   if (TREE_CODE (*parm) == REFERENCE_TYPE
12154       && TYPE_REF_IS_RVALUE (*parm)
12155       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
12156       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
12157       && arg_expr && real_lvalue_p (arg_expr))
12158     *arg = build_reference_type (*arg);
12159
12160   /* [temp.deduct.call]
12161
12162      If P is a cv-qualified type, the top level cv-qualifiers
12163      of P's type are ignored for type deduction.  If P is a
12164      reference type, the type referred to by P is used for
12165      type deduction.  */
12166   *parm = TYPE_MAIN_VARIANT (*parm);
12167   if (TREE_CODE (*parm) == REFERENCE_TYPE)
12168     {
12169       *parm = TREE_TYPE (*parm);
12170       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12171     }
12172
12173   /* DR 322. For conversion deduction, remove a reference type on parm
12174      too (which has been swapped into ARG).  */
12175   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
12176     *arg = TREE_TYPE (*arg);
12177
12178   return result;
12179 }
12180
12181 /* Most parms like fn_type_unification.
12182
12183    If SUBR is 1, we're being called recursively (to unify the
12184    arguments of a function or method parameter of a function
12185    template). */
12186
12187 static int
12188 type_unification_real (tree tparms,
12189                        tree targs,
12190                        tree xparms,
12191                        tree xargs,
12192                        int subr,
12193                        unification_kind_t strict,
12194                        int flags)
12195 {
12196   tree parm, arg, arg_expr;
12197   int i;
12198   int ntparms = TREE_VEC_LENGTH (tparms);
12199   int sub_strict;
12200   int saw_undeduced = 0;
12201   tree parms, args;
12202
12203   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
12204   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
12205   gcc_assert (!xargs || TREE_CODE (xargs) == TREE_LIST);
12206   gcc_assert (ntparms > 0);
12207
12208   switch (strict)
12209     {
12210     case DEDUCE_CALL:
12211       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
12212                     | UNIFY_ALLOW_DERIVED);
12213       break;
12214
12215     case DEDUCE_CONV:
12216       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12217       break;
12218
12219     case DEDUCE_EXACT:
12220       sub_strict = UNIFY_ALLOW_NONE;
12221       break;
12222
12223     default:
12224       gcc_unreachable ();
12225     }
12226
12227  again:
12228   parms = xparms;
12229   args = xargs;
12230
12231   while (parms && parms != void_list_node
12232          && args && args != void_list_node)
12233     {
12234       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12235         break;
12236
12237       parm = TREE_VALUE (parms);
12238       parms = TREE_CHAIN (parms);
12239       arg = TREE_VALUE (args);
12240       args = TREE_CHAIN (args);
12241       arg_expr = NULL;
12242
12243       if (arg == error_mark_node)
12244         return 1;
12245       if (arg == unknown_type_node)
12246         /* We can't deduce anything from this, but we might get all the
12247            template args from other function args.  */
12248         continue;
12249
12250       /* Conversions will be performed on a function argument that
12251          corresponds with a function parameter that contains only
12252          non-deducible template parameters and explicitly specified
12253          template parameters.  */
12254       if (!uses_template_parms (parm))
12255         {
12256           tree type;
12257
12258           if (!TYPE_P (arg))
12259             type = TREE_TYPE (arg);
12260           else
12261             type = arg;
12262
12263           if (same_type_p (parm, type))
12264             continue;
12265           if (strict != DEDUCE_EXACT
12266               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
12267                                   flags))
12268             continue;
12269
12270           return 1;
12271         }
12272
12273       if (!TYPE_P (arg))
12274         {
12275           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12276           if (type_unknown_p (arg))
12277             {
12278               /* [temp.deduct.type] 
12279
12280                  A template-argument can be deduced from a pointer to
12281                  function or pointer to member function argument if
12282                  the set of overloaded functions does not contain
12283                  function templates and at most one of a set of
12284                  overloaded functions provides a unique match.  */
12285               if (resolve_overloaded_unification
12286                   (tparms, targs, parm, arg, strict, sub_strict))
12287                 continue;
12288
12289               return 1;
12290             }
12291           arg_expr = arg;
12292           arg = unlowered_expr_type (arg);
12293           if (arg == error_mark_node)
12294             return 1;
12295         }
12296
12297       {
12298         int arg_strict = sub_strict;
12299
12300         if (!subr)
12301           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
12302                                                           arg_expr);
12303
12304         if (arg == init_list_type_node && arg_expr)
12305           arg = arg_expr;
12306         if (unify (tparms, targs, parm, arg, arg_strict))
12307           return 1;
12308       }
12309     }
12310
12311
12312   if (parms 
12313       && parms != void_list_node
12314       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12315     {
12316       /* Unify the remaining arguments with the pack expansion type.  */
12317       tree argvec;
12318       tree parmvec = make_tree_vec (1);
12319       int len = 0;
12320       tree t;
12321
12322       /* Count the number of arguments that remain.  */
12323       for (t = args; t && t != void_list_node; t = TREE_CHAIN (t))
12324         len++;
12325         
12326       /* Allocate a TREE_VEC and copy in all of the arguments */ 
12327       argvec = make_tree_vec (len);
12328       for (i = 0; args && args != void_list_node; args = TREE_CHAIN (args))
12329         {
12330           TREE_VEC_ELT (argvec, i) = TREE_VALUE (args);
12331           ++i;
12332         }
12333
12334       /* Copy the parameter into parmvec.  */
12335       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
12336       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
12337                                 /*call_args_p=*/true, /*subr=*/subr))
12338         return 1;
12339
12340       /* Advance to the end of the list of parameters.  */
12341       parms = TREE_CHAIN (parms);
12342     }
12343
12344   /* Fail if we've reached the end of the parm list, and more args
12345      are present, and the parm list isn't variadic.  */
12346   if (args && args != void_list_node && parms == void_list_node)
12347     return 1;
12348   /* Fail if parms are left and they don't have default values.  */
12349   if (parms && parms != void_list_node
12350       && TREE_PURPOSE (parms) == NULL_TREE)
12351     return 1;
12352
12353   if (!subr)
12354     for (i = 0; i < ntparms; i++)
12355       if (!TREE_VEC_ELT (targs, i))
12356         {
12357           tree tparm;
12358
12359           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
12360             continue;
12361
12362           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12363
12364           /* If this is an undeduced nontype parameter that depends on
12365              a type parameter, try another pass; its type may have been
12366              deduced from a later argument than the one from which
12367              this parameter can be deduced.  */
12368           if (TREE_CODE (tparm) == PARM_DECL
12369               && uses_template_parms (TREE_TYPE (tparm))
12370               && !saw_undeduced++)
12371             goto again;
12372
12373           /* Core issue #226 (C++0x) [temp.deduct]:
12374
12375                If a template argument has not been deduced, its
12376                default template argument, if any, is used. 
12377
12378              When we are in C++98 mode, TREE_PURPOSE will either
12379              be NULL_TREE or ERROR_MARK_NODE, so we do not need
12380              to explicitly check cxx_dialect here.  */
12381           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
12382             {
12383               tree arg = tsubst (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)), 
12384                                  targs, tf_none, NULL_TREE);
12385               if (arg == error_mark_node)
12386                 return 1;
12387               else
12388                 {
12389                   TREE_VEC_ELT (targs, i) = arg;
12390                   continue;
12391                 }
12392             }
12393
12394           /* If the type parameter is a parameter pack, then it will
12395              be deduced to an empty parameter pack.  */
12396           if (template_parameter_pack_p (tparm))
12397             {
12398               tree arg;
12399
12400               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
12401                 {
12402                   arg = make_node (NONTYPE_ARGUMENT_PACK);
12403                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
12404                   TREE_CONSTANT (arg) = 1;
12405                 }
12406               else
12407                 arg = make_node (TYPE_ARGUMENT_PACK);
12408
12409               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
12410
12411               TREE_VEC_ELT (targs, i) = arg;
12412               continue;
12413             }
12414
12415           return 2;
12416         }
12417
12418   return 0;
12419 }
12420
12421 /* Subroutine of type_unification_real.  Args are like the variables
12422    at the call site.  ARG is an overloaded function (or template-id);
12423    we try deducing template args from each of the overloads, and if
12424    only one succeeds, we go with that.  Modifies TARGS and returns
12425    true on success.  */
12426
12427 static bool
12428 resolve_overloaded_unification (tree tparms,
12429                                 tree targs,
12430                                 tree parm,
12431                                 tree arg,
12432                                 unification_kind_t strict,
12433                                 int sub_strict)
12434 {
12435   tree tempargs = copy_node (targs);
12436   int good = 0;
12437   bool addr_p;
12438
12439   if (TREE_CODE (arg) == ADDR_EXPR)
12440     {
12441       arg = TREE_OPERAND (arg, 0);
12442       addr_p = true;
12443     }
12444   else
12445     addr_p = false;
12446
12447   if (TREE_CODE (arg) == COMPONENT_REF)
12448     /* Handle `&x' where `x' is some static or non-static member
12449        function name.  */
12450     arg = TREE_OPERAND (arg, 1);
12451
12452   if (TREE_CODE (arg) == OFFSET_REF)
12453     arg = TREE_OPERAND (arg, 1);
12454
12455   /* Strip baselink information.  */
12456   if (BASELINK_P (arg))
12457     arg = BASELINK_FUNCTIONS (arg);
12458
12459   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
12460     {
12461       /* If we got some explicit template args, we need to plug them into
12462          the affected templates before we try to unify, in case the
12463          explicit args will completely resolve the templates in question.  */
12464
12465       tree expl_subargs = TREE_OPERAND (arg, 1);
12466       arg = TREE_OPERAND (arg, 0);
12467
12468       for (; arg; arg = OVL_NEXT (arg))
12469         {
12470           tree fn = OVL_CURRENT (arg);
12471           tree subargs, elem;
12472
12473           if (TREE_CODE (fn) != TEMPLATE_DECL)
12474             continue;
12475
12476           ++processing_template_decl;
12477           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
12478                                   expl_subargs, /*check_ret=*/false);
12479           if (subargs)
12480             {
12481               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
12482               good += try_one_overload (tparms, targs, tempargs, parm,
12483                                         elem, strict, sub_strict, addr_p);
12484             }
12485           --processing_template_decl;
12486         }
12487     }
12488   else if (TREE_CODE (arg) != OVERLOAD
12489            && TREE_CODE (arg) != FUNCTION_DECL)
12490     /* If ARG is, for example, "(0, &f)" then its type will be unknown
12491        -- but the deduction does not succeed because the expression is
12492        not just the function on its own.  */
12493     return false;
12494   else
12495     for (; arg; arg = OVL_NEXT (arg))
12496       good += try_one_overload (tparms, targs, tempargs, parm,
12497                                 TREE_TYPE (OVL_CURRENT (arg)),
12498                                 strict, sub_strict, addr_p);
12499
12500   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12501      to function or pointer to member function argument if the set of
12502      overloaded functions does not contain function templates and at most
12503      one of a set of overloaded functions provides a unique match.
12504
12505      So if we found multiple possibilities, we return success but don't
12506      deduce anything.  */
12507
12508   if (good == 1)
12509     {
12510       int i = TREE_VEC_LENGTH (targs);
12511       for (; i--; )
12512         if (TREE_VEC_ELT (tempargs, i))
12513           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
12514     }
12515   if (good)
12516     return true;
12517
12518   return false;
12519 }
12520
12521 /* Subroutine of resolve_overloaded_unification; does deduction for a single
12522    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
12523    different overloads deduce different arguments for a given parm.
12524    ADDR_P is true if the expression for which deduction is being
12525    performed was of the form "& fn" rather than simply "fn".
12526
12527    Returns 1 on success.  */
12528
12529 static int
12530 try_one_overload (tree tparms,
12531                   tree orig_targs,
12532                   tree targs,
12533                   tree parm,
12534                   tree arg,
12535                   unification_kind_t strict,
12536                   int sub_strict,
12537                   bool addr_p)
12538 {
12539   int nargs;
12540   tree tempargs;
12541   int i;
12542
12543   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12544      to function or pointer to member function argument if the set of
12545      overloaded functions does not contain function templates and at most
12546      one of a set of overloaded functions provides a unique match.
12547
12548      So if this is a template, just return success.  */
12549
12550   if (uses_template_parms (arg))
12551     return 1;
12552
12553   if (TREE_CODE (arg) == METHOD_TYPE)
12554     arg = build_ptrmemfunc_type (build_pointer_type (arg));
12555   else if (addr_p)
12556     arg = build_pointer_type (arg);
12557
12558   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
12559
12560   /* We don't copy orig_targs for this because if we have already deduced
12561      some template args from previous args, unify would complain when we
12562      try to deduce a template parameter for the same argument, even though
12563      there isn't really a conflict.  */
12564   nargs = TREE_VEC_LENGTH (targs);
12565   tempargs = make_tree_vec (nargs);
12566
12567   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
12568     return 0;
12569
12570   /* First make sure we didn't deduce anything that conflicts with
12571      explicitly specified args.  */
12572   for (i = nargs; i--; )
12573     {
12574       tree elt = TREE_VEC_ELT (tempargs, i);
12575       tree oldelt = TREE_VEC_ELT (orig_targs, i);
12576
12577       if (!elt)
12578         /*NOP*/;
12579       else if (uses_template_parms (elt))
12580         /* Since we're unifying against ourselves, we will fill in
12581            template args used in the function parm list with our own
12582            template parms.  Discard them.  */
12583         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
12584       else if (oldelt && !template_args_equal (oldelt, elt))
12585         return 0;
12586     }
12587
12588   for (i = nargs; i--; )
12589     {
12590       tree elt = TREE_VEC_ELT (tempargs, i);
12591
12592       if (elt)
12593         TREE_VEC_ELT (targs, i) = elt;
12594     }
12595
12596   return 1;
12597 }
12598
12599 /* PARM is a template class (perhaps with unbound template
12600    parameters).  ARG is a fully instantiated type.  If ARG can be
12601    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
12602    TARGS are as for unify.  */
12603
12604 static tree
12605 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
12606 {
12607   tree copy_of_targs;
12608
12609   if (!CLASSTYPE_TEMPLATE_INFO (arg)
12610       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
12611           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
12612     return NULL_TREE;
12613
12614   /* We need to make a new template argument vector for the call to
12615      unify.  If we used TARGS, we'd clutter it up with the result of
12616      the attempted unification, even if this class didn't work out.
12617      We also don't want to commit ourselves to all the unifications
12618      we've already done, since unification is supposed to be done on
12619      an argument-by-argument basis.  In other words, consider the
12620      following pathological case:
12621
12622        template <int I, int J, int K>
12623        struct S {};
12624
12625        template <int I, int J>
12626        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
12627
12628        template <int I, int J, int K>
12629        void f(S<I, J, K>, S<I, I, I>);
12630
12631        void g() {
12632          S<0, 0, 0> s0;
12633          S<0, 1, 2> s2;
12634
12635          f(s0, s2);
12636        }
12637
12638      Now, by the time we consider the unification involving `s2', we
12639      already know that we must have `f<0, 0, 0>'.  But, even though
12640      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
12641      because there are two ways to unify base classes of S<0, 1, 2>
12642      with S<I, I, I>.  If we kept the already deduced knowledge, we
12643      would reject the possibility I=1.  */
12644   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
12645
12646   /* If unification failed, we're done.  */
12647   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
12648              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
12649     return NULL_TREE;
12650
12651   return arg;
12652 }
12653
12654 /* Given a template type PARM and a class type ARG, find the unique
12655    base type in ARG that is an instance of PARM.  We do not examine
12656    ARG itself; only its base-classes.  If there is not exactly one
12657    appropriate base class, return NULL_TREE.  PARM may be the type of
12658    a partial specialization, as well as a plain template type.  Used
12659    by unify.  */
12660
12661 static tree
12662 get_template_base (tree tparms, tree targs, tree parm, tree arg)
12663 {
12664   tree rval = NULL_TREE;
12665   tree binfo;
12666
12667   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
12668
12669   binfo = TYPE_BINFO (complete_type (arg));
12670   if (!binfo)
12671     /* The type could not be completed.  */
12672     return NULL_TREE;
12673
12674   /* Walk in inheritance graph order.  The search order is not
12675      important, and this avoids multiple walks of virtual bases.  */
12676   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
12677     {
12678       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
12679
12680       if (r)
12681         {
12682           /* If there is more than one satisfactory baseclass, then:
12683
12684                [temp.deduct.call]
12685
12686               If they yield more than one possible deduced A, the type
12687               deduction fails.
12688
12689              applies.  */
12690           if (rval && !same_type_p (r, rval))
12691             return NULL_TREE;
12692
12693           rval = r;
12694         }
12695     }
12696
12697   return rval;
12698 }
12699
12700 /* Returns the level of DECL, which declares a template parameter.  */
12701
12702 static int
12703 template_decl_level (tree decl)
12704 {
12705   switch (TREE_CODE (decl))
12706     {
12707     case TYPE_DECL:
12708     case TEMPLATE_DECL:
12709       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
12710
12711     case PARM_DECL:
12712       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
12713
12714     default:
12715       gcc_unreachable ();
12716     }
12717   return 0;
12718 }
12719
12720 /* Decide whether ARG can be unified with PARM, considering only the
12721    cv-qualifiers of each type, given STRICT as documented for unify.
12722    Returns nonzero iff the unification is OK on that basis.  */
12723
12724 static int
12725 check_cv_quals_for_unify (int strict, tree arg, tree parm)
12726 {
12727   int arg_quals = cp_type_quals (arg);
12728   int parm_quals = cp_type_quals (parm);
12729
12730   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12731       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12732     {
12733       /*  Although a CVR qualifier is ignored when being applied to a
12734           substituted template parameter ([8.3.2]/1 for example), that
12735           does not apply during deduction [14.8.2.4]/1, (even though
12736           that is not explicitly mentioned, [14.8.2.4]/9 indicates
12737           this).  Except when we're allowing additional CV qualifiers
12738           at the outer level [14.8.2.1]/3,1st bullet.  */
12739       if ((TREE_CODE (arg) == REFERENCE_TYPE
12740            || TREE_CODE (arg) == FUNCTION_TYPE
12741            || TREE_CODE (arg) == METHOD_TYPE)
12742           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
12743         return 0;
12744
12745       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
12746           && (parm_quals & TYPE_QUAL_RESTRICT))
12747         return 0;
12748     }
12749
12750   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12751       && (arg_quals & parm_quals) != parm_quals)
12752     return 0;
12753
12754   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
12755       && (parm_quals & arg_quals) != arg_quals)
12756     return 0;
12757
12758   return 1;
12759 }
12760
12761 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
12762 void 
12763 template_parm_level_and_index (tree parm, int* level, int* index)
12764 {
12765   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12766       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12767       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12768     {
12769       *index = TEMPLATE_TYPE_IDX (parm);
12770       *level = TEMPLATE_TYPE_LEVEL (parm);
12771     }
12772   else
12773     {
12774       *index = TEMPLATE_PARM_IDX (parm);
12775       *level = TEMPLATE_PARM_LEVEL (parm);
12776     }
12777 }
12778
12779 /* Unifies the remaining arguments in PACKED_ARGS with the pack
12780    expansion at the end of PACKED_PARMS. Returns 0 if the type
12781    deduction succeeds, 1 otherwise. STRICT is the same as in
12782    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
12783    call argument list. We'll need to adjust the arguments to make them
12784    types. SUBR tells us if this is from a recursive call to
12785    type_unification_real.  */
12786 int
12787 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
12788                       tree packed_args, int strict, bool call_args_p,
12789                       bool subr)
12790 {
12791   tree parm 
12792     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
12793   tree pattern = PACK_EXPANSION_PATTERN (parm);
12794   tree pack, packs = NULL_TREE;
12795   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
12796   int len = TREE_VEC_LENGTH (packed_args);
12797
12798   /* Determine the parameter packs we will be deducing from the
12799      pattern, and record their current deductions.  */
12800   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
12801        pack; pack = TREE_CHAIN (pack))
12802     {
12803       tree parm_pack = TREE_VALUE (pack);
12804       int idx, level;
12805
12806       /* Determine the index and level of this parameter pack.  */
12807       template_parm_level_and_index (parm_pack, &level, &idx);
12808
12809       /* Keep track of the parameter packs and their corresponding
12810          argument packs.  */
12811       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
12812       TREE_TYPE (packs) = make_tree_vec (len - start);
12813     }
12814   
12815   /* Loop through all of the arguments that have not yet been
12816      unified and unify each with the pattern.  */
12817   for (i = start; i < len; i++)
12818     {
12819       tree parm = pattern;
12820
12821       /* For each parameter pack, clear out the deduced value so that
12822          we can deduce it again.  */
12823       for (pack = packs; pack; pack = TREE_CHAIN (pack))
12824         {
12825           int idx, level;
12826           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12827
12828           TMPL_ARG (targs, level, idx) = NULL_TREE;
12829         }
12830
12831       /* Unify the pattern with the current argument.  */
12832       {
12833         tree arg = TREE_VEC_ELT (packed_args, i);
12834         tree arg_expr = NULL_TREE;
12835         int arg_strict = strict;
12836         bool skip_arg_p = false;
12837
12838         if (call_args_p)
12839           {
12840             int sub_strict;
12841
12842             /* This mirrors what we do in type_unification_real.  */
12843             switch (strict)
12844               {
12845               case DEDUCE_CALL:
12846                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
12847                               | UNIFY_ALLOW_MORE_CV_QUAL
12848                               | UNIFY_ALLOW_DERIVED);
12849                 break;
12850                 
12851               case DEDUCE_CONV:
12852                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12853                 break;
12854                 
12855               case DEDUCE_EXACT:
12856                 sub_strict = UNIFY_ALLOW_NONE;
12857                 break;
12858                 
12859               default:
12860                 gcc_unreachable ();
12861               }
12862
12863             if (!TYPE_P (arg))
12864               {
12865                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12866                 if (type_unknown_p (arg))
12867                   {
12868                     /* [temp.deduct.type] A template-argument can be
12869                        deduced from a pointer to function or pointer
12870                        to member function argument if the set of
12871                        overloaded functions does not contain function
12872                        templates and at most one of a set of
12873                        overloaded functions provides a unique
12874                        match.  */
12875
12876                     if (resolve_overloaded_unification
12877                         (tparms, targs, parm, arg, strict, sub_strict)
12878                         != 0)
12879                       return 1;
12880                     skip_arg_p = true;
12881                   }
12882
12883                 if (!skip_arg_p)
12884                   {
12885                     arg_expr = arg;
12886                     arg = unlowered_expr_type (arg);
12887                     if (arg == error_mark_node)
12888                       return 1;
12889                   }
12890               }
12891       
12892             arg_strict = sub_strict;
12893
12894             if (!subr)
12895               arg_strict |= 
12896                 maybe_adjust_types_for_deduction (strict, &parm, &arg, 
12897                                                   arg_expr);
12898           }
12899
12900         if (!skip_arg_p)
12901           {
12902             if (unify (tparms, targs, parm, arg, arg_strict))
12903               return 1;
12904           }
12905       }
12906
12907       /* For each parameter pack, collect the deduced value.  */
12908       for (pack = packs; pack; pack = TREE_CHAIN (pack))
12909         {
12910           int idx, level;
12911           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12912
12913           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
12914             TMPL_ARG (targs, level, idx);
12915         }
12916     }
12917
12918   /* Verify that the results of unification with the parameter packs
12919      produce results consistent with what we've seen before, and make
12920      the deduced argument packs available.  */
12921   for (pack = packs; pack; pack = TREE_CHAIN (pack))
12922     {
12923       tree old_pack = TREE_VALUE (pack);
12924       tree new_args = TREE_TYPE (pack);
12925       int i, len = TREE_VEC_LENGTH (new_args);
12926       bool nondeduced_p = false;
12927
12928       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
12929          actually deduce anything.  */
12930       for (i = 0; i < len && !nondeduced_p; ++i)
12931         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
12932           nondeduced_p = true;
12933       if (nondeduced_p)
12934         continue;
12935
12936       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
12937         {
12938           /* Prepend the explicit arguments onto NEW_ARGS.  */
12939           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
12940           tree old_args = new_args;
12941           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
12942           int len = explicit_len + TREE_VEC_LENGTH (old_args);
12943
12944           /* Copy the explicit arguments.  */
12945           new_args = make_tree_vec (len);
12946           for (i = 0; i < explicit_len; i++)
12947             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
12948
12949           /* Copy the deduced arguments.  */
12950           for (; i < len; i++)
12951             TREE_VEC_ELT (new_args, i) =
12952               TREE_VEC_ELT (old_args, i - explicit_len);
12953         }
12954
12955       if (!old_pack)
12956         {
12957           tree result;
12958           int idx, level;
12959           
12960           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12961
12962           /* Build the deduced *_ARGUMENT_PACK.  */
12963           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
12964             {
12965               result = make_node (NONTYPE_ARGUMENT_PACK);
12966               TREE_TYPE (result) = 
12967                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
12968               TREE_CONSTANT (result) = 1;
12969             }
12970           else
12971             result = make_node (TYPE_ARGUMENT_PACK);
12972
12973           SET_ARGUMENT_PACK_ARGS (result, new_args);
12974
12975           /* Note the deduced argument packs for this parameter
12976              pack.  */
12977           TMPL_ARG (targs, level, idx) = result;
12978         }
12979       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
12980                && (ARGUMENT_PACK_ARGS (old_pack) 
12981                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
12982         {
12983           /* We only had the explicitly-provided arguments before, but
12984              now we have a complete set of arguments.  */
12985           int idx, level;
12986           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
12987           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12988
12989           /* Keep the original deduced argument pack.  */
12990           TMPL_ARG (targs, level, idx) = old_pack;
12991
12992           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
12993           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
12994           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
12995         }
12996       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
12997                                     new_args))
12998         /* Inconsistent unification of this parameter pack.  */
12999         return 1;
13000       else
13001         {
13002           int idx, level;
13003           
13004           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13005
13006           /* Keep the original deduced argument pack.  */
13007           TMPL_ARG (targs, level, idx) = old_pack;
13008         }
13009     }
13010
13011   return 0;
13012 }
13013
13014 /* Deduce the value of template parameters.  TPARMS is the (innermost)
13015    set of template parameters to a template.  TARGS is the bindings
13016    for those template parameters, as determined thus far; TARGS may
13017    include template arguments for outer levels of template parameters
13018    as well.  PARM is a parameter to a template function, or a
13019    subcomponent of that parameter; ARG is the corresponding argument.
13020    This function attempts to match PARM with ARG in a manner
13021    consistent with the existing assignments in TARGS.  If more values
13022    are deduced, then TARGS is updated.
13023
13024    Returns 0 if the type deduction succeeds, 1 otherwise.  The
13025    parameter STRICT is a bitwise or of the following flags:
13026
13027      UNIFY_ALLOW_NONE:
13028        Require an exact match between PARM and ARG.
13029      UNIFY_ALLOW_MORE_CV_QUAL:
13030        Allow the deduced ARG to be more cv-qualified (by qualification
13031        conversion) than ARG.
13032      UNIFY_ALLOW_LESS_CV_QUAL:
13033        Allow the deduced ARG to be less cv-qualified than ARG.
13034      UNIFY_ALLOW_DERIVED:
13035        Allow the deduced ARG to be a template base class of ARG,
13036        or a pointer to a template base class of the type pointed to by
13037        ARG.
13038      UNIFY_ALLOW_INTEGER:
13039        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
13040        case for more information.
13041      UNIFY_ALLOW_OUTER_LEVEL:
13042        This is the outermost level of a deduction. Used to determine validity
13043        of qualification conversions. A valid qualification conversion must
13044        have const qualified pointers leading up to the inner type which
13045        requires additional CV quals, except at the outer level, where const
13046        is not required [conv.qual]. It would be normal to set this flag in
13047        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
13048      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
13049        This is the outermost level of a deduction, and PARM can be more CV
13050        qualified at this point.
13051      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
13052        This is the outermost level of a deduction, and PARM can be less CV
13053        qualified at this point.  */
13054
13055 static int
13056 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
13057 {
13058   int idx;
13059   tree targ;
13060   tree tparm;
13061   int strict_in = strict;
13062
13063   /* I don't think this will do the right thing with respect to types.
13064      But the only case I've seen it in so far has been array bounds, where
13065      signedness is the only information lost, and I think that will be
13066      okay.  */
13067   while (TREE_CODE (parm) == NOP_EXPR)
13068     parm = TREE_OPERAND (parm, 0);
13069
13070   if (arg == error_mark_node)
13071     return 1;
13072   if (arg == unknown_type_node
13073       || arg == init_list_type_node)
13074     /* We can't deduce anything from this, but we might get all the
13075        template args from other function args.  */
13076     return 0;
13077
13078   /* If PARM uses template parameters, then we can't bail out here,
13079      even if ARG == PARM, since we won't record unifications for the
13080      template parameters.  We might need them if we're trying to
13081      figure out which of two things is more specialized.  */
13082   if (arg == parm && !uses_template_parms (parm))
13083     return 0;
13084
13085   /* Handle init lists early, so the rest of the function can assume
13086      we're dealing with a type. */
13087   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
13088     {
13089       tree elt, elttype;
13090       unsigned i;
13091
13092       if (!is_std_init_list (parm))
13093         /* We can only deduce from an initializer list argument if the
13094            parameter is std::initializer_list; otherwise this is a
13095            non-deduced context. */
13096         return 0;
13097
13098       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
13099
13100       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
13101         {
13102           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
13103             elt = TREE_TYPE (elt);
13104           if (unify (tparms, targs, elttype, elt, UNIFY_ALLOW_NONE))
13105             return 1;
13106         }
13107       return 0;
13108     }
13109
13110   /* Immediately reject some pairs that won't unify because of
13111      cv-qualification mismatches.  */
13112   if (TREE_CODE (arg) == TREE_CODE (parm)
13113       && TYPE_P (arg)
13114       /* It is the elements of the array which hold the cv quals of an array
13115          type, and the elements might be template type parms. We'll check
13116          when we recurse.  */
13117       && TREE_CODE (arg) != ARRAY_TYPE
13118       /* We check the cv-qualifiers when unifying with template type
13119          parameters below.  We want to allow ARG `const T' to unify with
13120          PARM `T' for example, when computing which of two templates
13121          is more specialized, for example.  */
13122       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
13123       && !check_cv_quals_for_unify (strict_in, arg, parm))
13124     return 1;
13125
13126   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
13127       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
13128     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
13129   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
13130   strict &= ~UNIFY_ALLOW_DERIVED;
13131   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13132   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
13133
13134   switch (TREE_CODE (parm))
13135     {
13136     case TYPENAME_TYPE:
13137     case SCOPE_REF:
13138     case UNBOUND_CLASS_TEMPLATE:
13139       /* In a type which contains a nested-name-specifier, template
13140          argument values cannot be deduced for template parameters used
13141          within the nested-name-specifier.  */
13142       return 0;
13143
13144     case TEMPLATE_TYPE_PARM:
13145     case TEMPLATE_TEMPLATE_PARM:
13146     case BOUND_TEMPLATE_TEMPLATE_PARM:
13147       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13148       if (tparm == error_mark_node)
13149         return 1;
13150
13151       if (TEMPLATE_TYPE_LEVEL (parm)
13152           != template_decl_level (tparm))
13153         /* The PARM is not one we're trying to unify.  Just check
13154            to see if it matches ARG.  */
13155         return (TREE_CODE (arg) == TREE_CODE (parm)
13156                 && same_type_p (parm, arg)) ? 0 : 1;
13157       idx = TEMPLATE_TYPE_IDX (parm);
13158       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13159       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
13160
13161       /* Check for mixed types and values.  */
13162       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13163            && TREE_CODE (tparm) != TYPE_DECL)
13164           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13165               && TREE_CODE (tparm) != TEMPLATE_DECL))
13166         return 1;
13167
13168       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13169         {
13170           /* ARG must be constructed from a template class or a template
13171              template parameter.  */
13172           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
13173               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
13174             return 1;
13175
13176           {
13177             tree parmvec = TYPE_TI_ARGS (parm);
13178             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
13179             tree parm_parms 
13180               = DECL_INNERMOST_TEMPLATE_PARMS
13181                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
13182             int i, len;
13183             int parm_variadic_p = 0;
13184
13185             /* The resolution to DR150 makes clear that default
13186                arguments for an N-argument may not be used to bind T
13187                to a template template parameter with fewer than N
13188                parameters.  It is not safe to permit the binding of
13189                default arguments as an extension, as that may change
13190                the meaning of a conforming program.  Consider:
13191
13192                   struct Dense { static const unsigned int dim = 1; };
13193
13194                   template <template <typename> class View,
13195                             typename Block>
13196                   void operator+(float, View<Block> const&);
13197
13198                   template <typename Block,
13199                             unsigned int Dim = Block::dim>
13200                   struct Lvalue_proxy { operator float() const; };
13201
13202                   void
13203                   test_1d (void) {
13204                     Lvalue_proxy<Dense> p;
13205                     float b;
13206                     b + p;
13207                   }
13208
13209               Here, if Lvalue_proxy is permitted to bind to View, then
13210               the global operator+ will be used; if they are not, the
13211               Lvalue_proxy will be converted to float.  */
13212             if (coerce_template_parms (parm_parms,
13213                                        argvec,
13214                                        TYPE_TI_TEMPLATE (parm),
13215                                        tf_none,
13216                                        /*require_all_args=*/true,
13217                                        /*use_default_args=*/false)
13218                 == error_mark_node)
13219               return 1;
13220
13221             /* Deduce arguments T, i from TT<T> or TT<i>.
13222                We check each element of PARMVEC and ARGVEC individually
13223                rather than the whole TREE_VEC since they can have
13224                different number of elements.  */
13225
13226             parmvec = expand_template_argument_pack (parmvec);
13227             argvec = expand_template_argument_pack (argvec);
13228
13229             len = TREE_VEC_LENGTH (parmvec);
13230
13231             /* Check if the parameters end in a pack, making them
13232                variadic.  */
13233             if (len > 0
13234                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
13235               parm_variadic_p = 1;
13236             
13237             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
13238               return 1;
13239
13240              for (i = 0; i < len - parm_variadic_p; ++i)
13241               {
13242                 if (unify (tparms, targs,
13243                            TREE_VEC_ELT (parmvec, i),
13244                            TREE_VEC_ELT (argvec, i),
13245                            UNIFY_ALLOW_NONE))
13246                   return 1;
13247               }
13248
13249             if (parm_variadic_p
13250                 && unify_pack_expansion (tparms, targs,
13251                                          parmvec, argvec,
13252                                          UNIFY_ALLOW_NONE,
13253                                          /*call_args_p=*/false,
13254                                          /*subr=*/false))
13255               return 1;
13256           }
13257           arg = TYPE_TI_TEMPLATE (arg);
13258
13259           /* Fall through to deduce template name.  */
13260         }
13261
13262       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13263           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13264         {
13265           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
13266
13267           /* Simple cases: Value already set, does match or doesn't.  */
13268           if (targ != NULL_TREE && template_args_equal (targ, arg))
13269             return 0;
13270           else if (targ)
13271             return 1;
13272         }
13273       else
13274         {
13275           /* If PARM is `const T' and ARG is only `int', we don't have
13276              a match unless we are allowing additional qualification.
13277              If ARG is `const int' and PARM is just `T' that's OK;
13278              that binds `const int' to `T'.  */
13279           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
13280                                          arg, parm))
13281             return 1;
13282
13283           /* Consider the case where ARG is `const volatile int' and
13284              PARM is `const T'.  Then, T should be `volatile int'.  */
13285           arg = cp_build_qualified_type_real
13286             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
13287           if (arg == error_mark_node)
13288             return 1;
13289
13290           /* Simple cases: Value already set, does match or doesn't.  */
13291           if (targ != NULL_TREE && same_type_p (targ, arg))
13292             return 0;
13293           else if (targ)
13294             return 1;
13295
13296           /* Make sure that ARG is not a variable-sized array.  (Note
13297              that were talking about variable-sized arrays (like
13298              `int[n]'), rather than arrays of unknown size (like
13299              `int[]').)  We'll get very confused by such a type since
13300              the bound of the array will not be computable in an
13301              instantiation.  Besides, such types are not allowed in
13302              ISO C++, so we can do as we please here.  */
13303           if (variably_modified_type_p (arg, NULL_TREE))
13304             return 1;
13305         }
13306
13307       /* If ARG is a parameter pack or an expansion, we cannot unify
13308          against it unless PARM is also a parameter pack.  */
13309       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13310           && !template_parameter_pack_p (parm))
13311         return 1;
13312
13313       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13314       return 0;
13315
13316     case TEMPLATE_PARM_INDEX:
13317       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13318       if (tparm == error_mark_node)
13319         return 1;
13320
13321       if (TEMPLATE_PARM_LEVEL (parm)
13322           != template_decl_level (tparm))
13323         /* The PARM is not one we're trying to unify.  Just check
13324            to see if it matches ARG.  */
13325         return !(TREE_CODE (arg) == TREE_CODE (parm)
13326                  && cp_tree_equal (parm, arg));
13327
13328       idx = TEMPLATE_PARM_IDX (parm);
13329       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13330
13331       if (targ)
13332         return !cp_tree_equal (targ, arg);
13333
13334       /* [temp.deduct.type] If, in the declaration of a function template
13335          with a non-type template-parameter, the non-type
13336          template-parameter is used in an expression in the function
13337          parameter-list and, if the corresponding template-argument is
13338          deduced, the template-argument type shall match the type of the
13339          template-parameter exactly, except that a template-argument
13340          deduced from an array bound may be of any integral type.
13341          The non-type parameter might use already deduced type parameters.  */
13342       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
13343       if (!TREE_TYPE (arg))
13344         /* Template-parameter dependent expression.  Just accept it for now.
13345            It will later be processed in convert_template_argument.  */
13346         ;
13347       else if (same_type_p (TREE_TYPE (arg), tparm))
13348         /* OK */;
13349       else if ((strict & UNIFY_ALLOW_INTEGER)
13350                && (TREE_CODE (tparm) == INTEGER_TYPE
13351                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
13352         /* Convert the ARG to the type of PARM; the deduced non-type
13353            template argument must exactly match the types of the
13354            corresponding parameter.  */
13355         arg = fold (build_nop (TREE_TYPE (parm), arg));
13356       else if (uses_template_parms (tparm))
13357         /* We haven't deduced the type of this parameter yet.  Try again
13358            later.  */
13359         return 0;
13360       else
13361         return 1;
13362
13363       /* If ARG is a parameter pack or an expansion, we cannot unify
13364          against it unless PARM is also a parameter pack.  */
13365       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13366           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
13367         return 1;
13368
13369       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13370       return 0;
13371
13372     case PTRMEM_CST:
13373      {
13374         /* A pointer-to-member constant can be unified only with
13375          another constant.  */
13376       if (TREE_CODE (arg) != PTRMEM_CST)
13377         return 1;
13378
13379       /* Just unify the class member. It would be useless (and possibly
13380          wrong, depending on the strict flags) to unify also
13381          PTRMEM_CST_CLASS, because we want to be sure that both parm and
13382          arg refer to the same variable, even if through different
13383          classes. For instance:
13384
13385          struct A { int x; };
13386          struct B : A { };
13387
13388          Unification of &A::x and &B::x must succeed.  */
13389       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
13390                     PTRMEM_CST_MEMBER (arg), strict);
13391      }
13392
13393     case POINTER_TYPE:
13394       {
13395         if (TREE_CODE (arg) != POINTER_TYPE)
13396           return 1;
13397
13398         /* [temp.deduct.call]
13399
13400            A can be another pointer or pointer to member type that can
13401            be converted to the deduced A via a qualification
13402            conversion (_conv.qual_).
13403
13404            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
13405            This will allow for additional cv-qualification of the
13406            pointed-to types if appropriate.  */
13407
13408         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
13409           /* The derived-to-base conversion only persists through one
13410              level of pointers.  */
13411           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
13412
13413         return unify (tparms, targs, TREE_TYPE (parm),
13414                       TREE_TYPE (arg), strict);
13415       }
13416
13417     case REFERENCE_TYPE:
13418       if (TREE_CODE (arg) != REFERENCE_TYPE)
13419         return 1;
13420       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13421                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13422
13423     case ARRAY_TYPE:
13424       if (TREE_CODE (arg) != ARRAY_TYPE)
13425         return 1;
13426       if ((TYPE_DOMAIN (parm) == NULL_TREE)
13427           != (TYPE_DOMAIN (arg) == NULL_TREE))
13428         return 1;
13429       if (TYPE_DOMAIN (parm) != NULL_TREE)
13430         {
13431           tree parm_max;
13432           tree arg_max;
13433           bool parm_cst;
13434           bool arg_cst;
13435
13436           /* Our representation of array types uses "N - 1" as the
13437              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
13438              not an integer constant.  We cannot unify arbitrarily
13439              complex expressions, so we eliminate the MINUS_EXPRs
13440              here.  */
13441           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
13442           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
13443           if (!parm_cst)
13444             {
13445               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
13446               parm_max = TREE_OPERAND (parm_max, 0);
13447             }
13448           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
13449           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
13450           if (!arg_cst)
13451             {
13452               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
13453                  trying to unify the type of a variable with the type
13454                  of a template parameter.  For example:
13455
13456                    template <unsigned int N>
13457                    void f (char (&) [N]);
13458                    int g(); 
13459                    void h(int i) {
13460                      char a[g(i)];
13461                      f(a); 
13462                    }
13463
13464                 Here, the type of the ARG will be "int [g(i)]", and
13465                 may be a SAVE_EXPR, etc.  */
13466               if (TREE_CODE (arg_max) != MINUS_EXPR)
13467                 return 1;
13468               arg_max = TREE_OPERAND (arg_max, 0);
13469             }
13470
13471           /* If only one of the bounds used a MINUS_EXPR, compensate
13472              by adding one to the other bound.  */
13473           if (parm_cst && !arg_cst)
13474             parm_max = fold_build2 (PLUS_EXPR,
13475                                     integer_type_node,
13476                                     parm_max,
13477                                     integer_one_node);
13478           else if (arg_cst && !parm_cst)
13479             arg_max = fold_build2 (PLUS_EXPR,
13480                                    integer_type_node,
13481                                    arg_max,
13482                                    integer_one_node);
13483
13484           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
13485             return 1;
13486         }
13487       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13488                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13489
13490     case REAL_TYPE:
13491     case COMPLEX_TYPE:
13492     case VECTOR_TYPE:
13493     case INTEGER_TYPE:
13494     case BOOLEAN_TYPE:
13495     case ENUMERAL_TYPE:
13496     case VOID_TYPE:
13497       if (TREE_CODE (arg) != TREE_CODE (parm))
13498         return 1;
13499
13500       /* We have already checked cv-qualification at the top of the
13501          function.  */
13502       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
13503         return 1;
13504
13505       /* As far as unification is concerned, this wins.  Later checks
13506          will invalidate it if necessary.  */
13507       return 0;
13508
13509       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
13510       /* Type INTEGER_CST can come from ordinary constant template args.  */
13511     case INTEGER_CST:
13512       while (TREE_CODE (arg) == NOP_EXPR)
13513         arg = TREE_OPERAND (arg, 0);
13514
13515       if (TREE_CODE (arg) != INTEGER_CST)
13516         return 1;
13517       return !tree_int_cst_equal (parm, arg);
13518
13519     case TREE_VEC:
13520       {
13521         int i;
13522         if (TREE_CODE (arg) != TREE_VEC)
13523           return 1;
13524         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
13525           return 1;
13526         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
13527           if (unify (tparms, targs,
13528                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
13529                      UNIFY_ALLOW_NONE))
13530             return 1;
13531         return 0;
13532       }
13533
13534     case RECORD_TYPE:
13535     case UNION_TYPE:
13536       if (TREE_CODE (arg) != TREE_CODE (parm))
13537         return 1;
13538
13539       if (TYPE_PTRMEMFUNC_P (parm))
13540         {
13541           if (!TYPE_PTRMEMFUNC_P (arg))
13542             return 1;
13543
13544           return unify (tparms, targs,
13545                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
13546                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
13547                         strict);
13548         }
13549
13550       if (CLASSTYPE_TEMPLATE_INFO (parm))
13551         {
13552           tree t = NULL_TREE;
13553
13554           if (strict_in & UNIFY_ALLOW_DERIVED)
13555             {
13556               /* First, we try to unify the PARM and ARG directly.  */
13557               t = try_class_unification (tparms, targs,
13558                                          parm, arg);
13559
13560               if (!t)
13561                 {
13562                   /* Fallback to the special case allowed in
13563                      [temp.deduct.call]:
13564
13565                        If P is a class, and P has the form
13566                        template-id, then A can be a derived class of
13567                        the deduced A.  Likewise, if P is a pointer to
13568                        a class of the form template-id, A can be a
13569                        pointer to a derived class pointed to by the
13570                        deduced A.  */
13571                   t = get_template_base (tparms, targs, parm, arg);
13572
13573                   if (!t)
13574                     return 1;
13575                 }
13576             }
13577           else if (CLASSTYPE_TEMPLATE_INFO (arg)
13578                    && (CLASSTYPE_TI_TEMPLATE (parm)
13579                        == CLASSTYPE_TI_TEMPLATE (arg)))
13580             /* Perhaps PARM is something like S<U> and ARG is S<int>.
13581                Then, we should unify `int' and `U'.  */
13582             t = arg;
13583           else
13584             /* There's no chance of unification succeeding.  */
13585             return 1;
13586
13587           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
13588                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
13589         }
13590       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
13591         return 1;
13592       return 0;
13593
13594     case METHOD_TYPE:
13595     case FUNCTION_TYPE:
13596       if (TREE_CODE (arg) != TREE_CODE (parm))
13597         return 1;
13598
13599       /* CV qualifications for methods can never be deduced, they must
13600          match exactly.  We need to check them explicitly here,
13601          because type_unification_real treats them as any other
13602          cv-qualified parameter.  */
13603       if (TREE_CODE (parm) == METHOD_TYPE
13604           && (!check_cv_quals_for_unify
13605               (UNIFY_ALLOW_NONE,
13606                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
13607                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
13608         return 1;
13609
13610       if (unify (tparms, targs, TREE_TYPE (parm),
13611                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
13612         return 1;
13613       return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
13614                                     TYPE_ARG_TYPES (arg), 1, DEDUCE_EXACT,
13615                                     LOOKUP_NORMAL);
13616
13617     case OFFSET_TYPE:
13618       /* Unify a pointer to member with a pointer to member function, which
13619          deduces the type of the member as a function type. */
13620       if (TYPE_PTRMEMFUNC_P (arg))
13621         {
13622           tree method_type;
13623           tree fntype;
13624           cp_cv_quals cv_quals;
13625
13626           /* Check top-level cv qualifiers */
13627           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
13628             return 1;
13629
13630           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13631                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
13632             return 1;
13633
13634           /* Determine the type of the function we are unifying against. */
13635           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
13636           fntype =
13637             build_function_type (TREE_TYPE (method_type),
13638                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
13639
13640           /* Extract the cv-qualifiers of the member function from the
13641              implicit object parameter and place them on the function
13642              type to be restored later. */
13643           cv_quals =
13644             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
13645           fntype = build_qualified_type (fntype, cv_quals);
13646           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
13647         }
13648
13649       if (TREE_CODE (arg) != OFFSET_TYPE)
13650         return 1;
13651       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13652                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
13653         return 1;
13654       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13655                     strict);
13656
13657     case CONST_DECL:
13658       if (DECL_TEMPLATE_PARM_P (parm))
13659         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
13660       if (arg != integral_constant_value (parm))
13661         return 1;
13662       return 0;
13663
13664     case FIELD_DECL:
13665     case TEMPLATE_DECL:
13666       /* Matched cases are handled by the ARG == PARM test above.  */
13667       return 1;
13668
13669     case TYPE_ARGUMENT_PACK:
13670     case NONTYPE_ARGUMENT_PACK:
13671       {
13672         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
13673         tree packed_args = ARGUMENT_PACK_ARGS (arg);
13674         int i, len = TREE_VEC_LENGTH (packed_parms);
13675         int argslen = TREE_VEC_LENGTH (packed_args);
13676         int parm_variadic_p = 0;
13677
13678         for (i = 0; i < len; ++i)
13679           {
13680             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
13681               {
13682                 if (i == len - 1)
13683                   /* We can unify against something with a trailing
13684                      parameter pack.  */
13685                   parm_variadic_p = 1;
13686                 else
13687                   /* Since there is something following the pack
13688                      expansion, we cannot unify this template argument
13689                      list.  */
13690                   return 0;
13691               }
13692           }
13693           
13694
13695         /* If we don't have enough arguments to satisfy the parameters
13696            (not counting the pack expression at the end), or we have
13697            too many arguments for a parameter list that doesn't end in
13698            a pack expression, we can't unify.  */
13699         if (argslen < (len - parm_variadic_p)
13700             || (argslen > len && !parm_variadic_p))
13701           return 1;
13702
13703         /* Unify all of the parameters that precede the (optional)
13704            pack expression.  */
13705         for (i = 0; i < len - parm_variadic_p; ++i)
13706           {
13707             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
13708                        TREE_VEC_ELT (packed_args, i), strict))
13709               return 1;
13710           }
13711
13712         if (parm_variadic_p)
13713           return unify_pack_expansion (tparms, targs, 
13714                                        packed_parms, packed_args,
13715                                        strict, /*call_args_p=*/false,
13716                                        /*subr=*/false);
13717         return 0;
13718       }
13719
13720       break;
13721
13722     case TYPEOF_TYPE:
13723     case DECLTYPE_TYPE:
13724       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
13725          nodes.  */
13726       return 0;
13727
13728     case ERROR_MARK:
13729       /* Unification fails if we hit an error node.  */
13730       return 1;
13731
13732     default:
13733       gcc_assert (EXPR_P (parm));
13734
13735       /* We must be looking at an expression.  This can happen with
13736          something like:
13737
13738            template <int I>
13739            void foo(S<I>, S<I + 2>);
13740
13741          This is a "nondeduced context":
13742
13743            [deduct.type]
13744
13745            The nondeduced contexts are:
13746
13747            --A type that is a template-id in which one or more of
13748              the template-arguments is an expression that references
13749              a template-parameter.
13750
13751          In these cases, we assume deduction succeeded, but don't
13752          actually infer any unifications.  */
13753
13754       if (!uses_template_parms (parm)
13755           && !template_args_equal (parm, arg))
13756         return 1;
13757       else
13758         return 0;
13759     }
13760 }
13761 \f
13762 /* Note that DECL can be defined in this translation unit, if
13763    required.  */
13764
13765 static void
13766 mark_definable (tree decl)
13767 {
13768   tree clone;
13769   DECL_NOT_REALLY_EXTERN (decl) = 1;
13770   FOR_EACH_CLONE (clone, decl)
13771     DECL_NOT_REALLY_EXTERN (clone) = 1;
13772 }
13773
13774 /* Called if RESULT is explicitly instantiated, or is a member of an
13775    explicitly instantiated class.  */
13776
13777 void
13778 mark_decl_instantiated (tree result, int extern_p)
13779 {
13780   SET_DECL_EXPLICIT_INSTANTIATION (result);
13781
13782   /* If this entity has already been written out, it's too late to
13783      make any modifications.  */
13784   if (TREE_ASM_WRITTEN (result))
13785     return;
13786
13787   if (TREE_CODE (result) != FUNCTION_DECL)
13788     /* The TREE_PUBLIC flag for function declarations will have been
13789        set correctly by tsubst.  */
13790     TREE_PUBLIC (result) = 1;
13791
13792   /* This might have been set by an earlier implicit instantiation.  */
13793   DECL_COMDAT (result) = 0;
13794
13795   if (extern_p)
13796     DECL_NOT_REALLY_EXTERN (result) = 0;
13797   else
13798     {
13799       mark_definable (result);
13800       /* Always make artificials weak.  */
13801       if (DECL_ARTIFICIAL (result) && flag_weak)
13802         comdat_linkage (result);
13803       /* For WIN32 we also want to put explicit instantiations in
13804          linkonce sections.  */
13805       else if (TREE_PUBLIC (result))
13806         maybe_make_one_only (result);
13807     }
13808
13809   /* If EXTERN_P, then this function will not be emitted -- unless
13810      followed by an explicit instantiation, at which point its linkage
13811      will be adjusted.  If !EXTERN_P, then this function will be
13812      emitted here.  In neither circumstance do we want
13813      import_export_decl to adjust the linkage.  */
13814   DECL_INTERFACE_KNOWN (result) = 1;
13815 }
13816
13817 /* Given two function templates PAT1 and PAT2, return:
13818
13819    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
13820    -1 if PAT2 is more specialized than PAT1.
13821    0 if neither is more specialized.
13822
13823    LEN indicates the number of parameters we should consider
13824    (defaulted parameters should not be considered).
13825
13826    The 1998 std underspecified function template partial ordering, and
13827    DR214 addresses the issue.  We take pairs of arguments, one from
13828    each of the templates, and deduce them against each other.  One of
13829    the templates will be more specialized if all the *other*
13830    template's arguments deduce against its arguments and at least one
13831    of its arguments *does* *not* deduce against the other template's
13832    corresponding argument.  Deduction is done as for class templates.
13833    The arguments used in deduction have reference and top level cv
13834    qualifiers removed.  Iff both arguments were originally reference
13835    types *and* deduction succeeds in both directions, the template
13836    with the more cv-qualified argument wins for that pairing (if
13837    neither is more cv-qualified, they both are equal).  Unlike regular
13838    deduction, after all the arguments have been deduced in this way,
13839    we do *not* verify the deduced template argument values can be
13840    substituted into non-deduced contexts, nor do we have to verify
13841    that all template arguments have been deduced.  */
13842
13843 int
13844 more_specialized_fn (tree pat1, tree pat2, int len)
13845 {
13846   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
13847   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
13848   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
13849   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
13850   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
13851   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
13852   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
13853   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
13854   int better1 = 0;
13855   int better2 = 0;
13856
13857   /* Remove the this parameter from non-static member functions.  If
13858      one is a non-static member function and the other is not a static
13859      member function, remove the first parameter from that function
13860      also.  This situation occurs for operator functions where we
13861      locate both a member function (with this pointer) and non-member
13862      operator (with explicit first operand).  */
13863   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
13864     {
13865       len--; /* LEN is the number of significant arguments for DECL1 */
13866       args1 = TREE_CHAIN (args1);
13867       if (!DECL_STATIC_FUNCTION_P (decl2))
13868         args2 = TREE_CHAIN (args2);
13869     }
13870   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
13871     {
13872       args2 = TREE_CHAIN (args2);
13873       if (!DECL_STATIC_FUNCTION_P (decl1))
13874         {
13875           len--;
13876           args1 = TREE_CHAIN (args1);
13877         }
13878     }
13879
13880   /* If only one is a conversion operator, they are unordered.  */
13881   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
13882     return 0;
13883
13884   /* Consider the return type for a conversion function */
13885   if (DECL_CONV_FN_P (decl1))
13886     {
13887       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
13888       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
13889       len++;
13890     }
13891
13892   processing_template_decl++;
13893
13894   while (len--
13895          /* Stop when an ellipsis is seen.  */
13896          && args1 != NULL_TREE && args2 != NULL_TREE)
13897     {
13898       tree arg1 = TREE_VALUE (args1);
13899       tree arg2 = TREE_VALUE (args2);
13900       int deduce1, deduce2;
13901       int quals1 = -1;
13902       int quals2 = -1;
13903
13904       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
13905           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13906         {
13907           /* When both arguments are pack expansions, we need only
13908              unify the patterns themselves.  */
13909           arg1 = PACK_EXPANSION_PATTERN (arg1);
13910           arg2 = PACK_EXPANSION_PATTERN (arg2);
13911
13912           /* This is the last comparison we need to do.  */
13913           len = 0;
13914         }
13915
13916       if (TREE_CODE (arg1) == REFERENCE_TYPE)
13917         {
13918           arg1 = TREE_TYPE (arg1);
13919           quals1 = cp_type_quals (arg1);
13920         }
13921
13922       if (TREE_CODE (arg2) == REFERENCE_TYPE)
13923         {
13924           arg2 = TREE_TYPE (arg2);
13925           quals2 = cp_type_quals (arg2);
13926         }
13927
13928       if ((quals1 < 0) != (quals2 < 0))
13929         {
13930           /* Only of the args is a reference, see if we should apply
13931              array/function pointer decay to it.  This is not part of
13932              DR214, but is, IMHO, consistent with the deduction rules
13933              for the function call itself, and with our earlier
13934              implementation of the underspecified partial ordering
13935              rules.  (nathan).  */
13936           if (quals1 >= 0)
13937             {
13938               switch (TREE_CODE (arg1))
13939                 {
13940                 case ARRAY_TYPE:
13941                   arg1 = TREE_TYPE (arg1);
13942                   /* FALLTHROUGH. */
13943                 case FUNCTION_TYPE:
13944                   arg1 = build_pointer_type (arg1);
13945                   break;
13946
13947                 default:
13948                   break;
13949                 }
13950             }
13951           else
13952             {
13953               switch (TREE_CODE (arg2))
13954                 {
13955                 case ARRAY_TYPE:
13956                   arg2 = TREE_TYPE (arg2);
13957                   /* FALLTHROUGH. */
13958                 case FUNCTION_TYPE:
13959                   arg2 = build_pointer_type (arg2);
13960                   break;
13961
13962                 default:
13963                   break;
13964                 }
13965             }
13966         }
13967
13968       arg1 = TYPE_MAIN_VARIANT (arg1);
13969       arg2 = TYPE_MAIN_VARIANT (arg2);
13970
13971       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
13972         {
13973           int i, len2 = list_length (args2);
13974           tree parmvec = make_tree_vec (1);
13975           tree argvec = make_tree_vec (len2);
13976           tree ta = args2;
13977
13978           /* Setup the parameter vector, which contains only ARG1.  */
13979           TREE_VEC_ELT (parmvec, 0) = arg1;
13980
13981           /* Setup the argument vector, which contains the remaining
13982              arguments.  */
13983           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
13984             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
13985
13986           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
13987                                            argvec, UNIFY_ALLOW_NONE, 
13988                                            /*call_args_p=*/false, 
13989                                            /*subr=*/0);
13990
13991           /* We cannot deduce in the other direction, because ARG1 is
13992              a pack expansion but ARG2 is not.  */
13993           deduce2 = 0;
13994         }
13995       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13996         {
13997           int i, len1 = list_length (args1);
13998           tree parmvec = make_tree_vec (1);
13999           tree argvec = make_tree_vec (len1);
14000           tree ta = args1;
14001
14002           /* Setup the parameter vector, which contains only ARG1.  */
14003           TREE_VEC_ELT (parmvec, 0) = arg2;
14004
14005           /* Setup the argument vector, which contains the remaining
14006              arguments.  */
14007           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
14008             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14009
14010           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
14011                                            argvec, UNIFY_ALLOW_NONE, 
14012                                            /*call_args_p=*/false, 
14013                                            /*subr=*/0);
14014
14015           /* We cannot deduce in the other direction, because ARG2 is
14016              a pack expansion but ARG1 is not.*/
14017           deduce1 = 0;
14018         }
14019
14020       else
14021         {
14022           /* The normal case, where neither argument is a pack
14023              expansion.  */
14024           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
14025           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
14026         }
14027
14028       if (!deduce1)
14029         better2 = -1;
14030       if (!deduce2)
14031         better1 = -1;
14032       if (better1 < 0 && better2 < 0)
14033         /* We've failed to deduce something in either direction.
14034            These must be unordered.  */
14035         break;
14036
14037       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
14038         {
14039           /* Deduces in both directions, see if quals can
14040              disambiguate.  Pretend the worse one failed to deduce. */
14041           if ((quals1 & quals2) == quals2)
14042             deduce1 = 0;
14043           if ((quals1 & quals2) == quals1)
14044             deduce2 = 0;
14045         }
14046       if (deduce1 && !deduce2 && !better2)
14047         better2 = 1;
14048       if (deduce2 && !deduce1 && !better1)
14049         better1 = 1;
14050
14051       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14052           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14053         /* We have already processed all of the arguments in our
14054            handing of the pack expansion type.  */
14055         len = 0;
14056
14057       args1 = TREE_CHAIN (args1);
14058       args2 = TREE_CHAIN (args2);
14059     }
14060
14061   processing_template_decl--;
14062
14063   /* All things being equal, if the next argument is a pack expansion
14064      for one function but not for the other, prefer the
14065      non-variadic function.  */
14066   if ((better1 > 0) - (better2 > 0) == 0
14067       && args1 && TREE_VALUE (args1)
14068       && args2 && TREE_VALUE (args2))
14069     {
14070       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
14071         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
14072       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
14073         return 1;
14074     }
14075
14076   return (better1 > 0) - (better2 > 0);
14077 }
14078
14079 /* Determine which of two partial specializations is more specialized.
14080
14081    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
14082    to the first partial specialization.  The TREE_VALUE is the
14083    innermost set of template parameters for the partial
14084    specialization.  PAT2 is similar, but for the second template.
14085
14086    Return 1 if the first partial specialization is more specialized;
14087    -1 if the second is more specialized; 0 if neither is more
14088    specialized.
14089
14090    See [temp.class.order] for information about determining which of
14091    two templates is more specialized.  */
14092
14093 static int
14094 more_specialized_class (tree pat1, tree pat2)
14095 {
14096   tree targs;
14097   tree tmpl1, tmpl2;
14098   int winner = 0;
14099   bool any_deductions = false;
14100
14101   tmpl1 = TREE_TYPE (pat1);
14102   tmpl2 = TREE_TYPE (pat2);
14103
14104   /* Just like what happens for functions, if we are ordering between
14105      different class template specializations, we may encounter dependent
14106      types in the arguments, and we need our dependency check functions
14107      to behave correctly.  */
14108   ++processing_template_decl;
14109   targs = get_class_bindings (TREE_VALUE (pat1),
14110                               CLASSTYPE_TI_ARGS (tmpl1),
14111                               CLASSTYPE_TI_ARGS (tmpl2));
14112   if (targs)
14113     {
14114       --winner;
14115       any_deductions = true;
14116     }
14117
14118   targs = get_class_bindings (TREE_VALUE (pat2),
14119                               CLASSTYPE_TI_ARGS (tmpl2),
14120                               CLASSTYPE_TI_ARGS (tmpl1));
14121   if (targs)
14122     {
14123       ++winner;
14124       any_deductions = true;
14125     }
14126   --processing_template_decl;
14127
14128   /* In the case of a tie where at least one of the class templates
14129      has a parameter pack at the end, the template with the most
14130      non-packed parameters wins.  */
14131   if (winner == 0
14132       && any_deductions
14133       && (template_args_variadic_p (TREE_PURPOSE (pat1))
14134           || template_args_variadic_p (TREE_PURPOSE (pat2))))
14135     {
14136       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
14137       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
14138       int len1 = TREE_VEC_LENGTH (args1);
14139       int len2 = TREE_VEC_LENGTH (args2);
14140
14141       /* We don't count the pack expansion at the end.  */
14142       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
14143         --len1;
14144       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
14145         --len2;
14146
14147       if (len1 > len2)
14148         return 1;
14149       else if (len1 < len2)
14150         return -1;
14151     }
14152
14153   return winner;
14154 }
14155
14156 /* Return the template arguments that will produce the function signature
14157    DECL from the function template FN, with the explicit template
14158    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
14159    also match.  Return NULL_TREE if no satisfactory arguments could be
14160    found.  */
14161
14162 static tree
14163 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
14164 {
14165   int ntparms = DECL_NTPARMS (fn);
14166   tree targs = make_tree_vec (ntparms);
14167   tree decl_type;
14168   tree decl_arg_types;
14169
14170   /* Substitute the explicit template arguments into the type of DECL.
14171      The call to fn_type_unification will handle substitution into the
14172      FN.  */
14173   decl_type = TREE_TYPE (decl);
14174   if (explicit_args && uses_template_parms (decl_type))
14175     {
14176       tree tmpl;
14177       tree converted_args;
14178
14179       if (DECL_TEMPLATE_INFO (decl))
14180         tmpl = DECL_TI_TEMPLATE (decl);
14181       else
14182         /* We can get here for some invalid specializations.  */
14183         return NULL_TREE;
14184
14185       converted_args
14186         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
14187                                  explicit_args, NULL_TREE,
14188                                  tf_none,
14189                                  /*require_all_args=*/false,
14190                                  /*use_default_args=*/false);
14191       if (converted_args == error_mark_node)
14192         return NULL_TREE;
14193
14194       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
14195       if (decl_type == error_mark_node)
14196         return NULL_TREE;
14197     }
14198
14199   /* Never do unification on the 'this' parameter.  */
14200   decl_arg_types = skip_artificial_parms_for (decl, 
14201                                               TYPE_ARG_TYPES (decl_type));
14202
14203   if (fn_type_unification (fn, explicit_args, targs,
14204                            decl_arg_types,
14205                            (check_rettype || DECL_CONV_FN_P (fn)
14206                             ? TREE_TYPE (decl_type) : NULL_TREE),
14207                            DEDUCE_EXACT, LOOKUP_NORMAL))
14208     return NULL_TREE;
14209
14210   return targs;
14211 }
14212
14213 /* Return the innermost template arguments that, when applied to a
14214    template specialization whose innermost template parameters are
14215    TPARMS, and whose specialization arguments are PARMS, yield the
14216    ARGS.
14217
14218    For example, suppose we have:
14219
14220      template <class T, class U> struct S {};
14221      template <class T> struct S<T*, int> {};
14222
14223    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
14224    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
14225    int}.  The resulting vector will be {double}, indicating that `T'
14226    is bound to `double'.  */
14227
14228 static tree
14229 get_class_bindings (tree tparms, tree spec_args, tree args)
14230 {
14231   int i, ntparms = TREE_VEC_LENGTH (tparms);
14232   tree deduced_args;
14233   tree innermost_deduced_args;
14234
14235   innermost_deduced_args = make_tree_vec (ntparms);
14236   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14237     {
14238       deduced_args = copy_node (args);
14239       SET_TMPL_ARGS_LEVEL (deduced_args,
14240                            TMPL_ARGS_DEPTH (deduced_args),
14241                            innermost_deduced_args);
14242     }
14243   else
14244     deduced_args = innermost_deduced_args;
14245
14246   if (unify (tparms, deduced_args,
14247              INNERMOST_TEMPLATE_ARGS (spec_args),
14248              INNERMOST_TEMPLATE_ARGS (args),
14249              UNIFY_ALLOW_NONE))
14250     return NULL_TREE;
14251
14252   for (i =  0; i < ntparms; ++i)
14253     if (! TREE_VEC_ELT (innermost_deduced_args, i))
14254       return NULL_TREE;
14255
14256   /* Verify that nondeduced template arguments agree with the type
14257      obtained from argument deduction.
14258
14259      For example:
14260
14261        struct A { typedef int X; };
14262        template <class T, class U> struct C {};
14263        template <class T> struct C<T, typename T::X> {};
14264
14265      Then with the instantiation `C<A, int>', we can deduce that
14266      `T' is `A' but unify () does not check whether `typename T::X'
14267      is `int'.  */
14268   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
14269   if (spec_args == error_mark_node
14270       /* We only need to check the innermost arguments; the other
14271          arguments will always agree.  */
14272       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
14273                               INNERMOST_TEMPLATE_ARGS (args)))
14274     return NULL_TREE;
14275
14276   /* Now that we have bindings for all of the template arguments,
14277      ensure that the arguments deduced for the template template
14278      parameters have compatible template parameter lists.  See the use
14279      of template_template_parm_bindings_ok_p in fn_type_unification
14280      for more information.  */
14281   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
14282     return NULL_TREE;
14283
14284   return deduced_args;
14285 }
14286
14287 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
14288    Return the TREE_LIST node with the most specialized template, if
14289    any.  If there is no most specialized template, the error_mark_node
14290    is returned.
14291
14292    Note that this function does not look at, or modify, the
14293    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
14294    returned is one of the elements of INSTANTIATIONS, callers may
14295    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
14296    and retrieve it from the value returned.  */
14297
14298 tree
14299 most_specialized_instantiation (tree templates)
14300 {
14301   tree fn, champ;
14302
14303   ++processing_template_decl;
14304
14305   champ = templates;
14306   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
14307     {
14308       int fate = 0;
14309
14310       if (get_bindings (TREE_VALUE (champ),
14311                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14312                         NULL_TREE, /*check_ret=*/false))
14313         fate--;
14314
14315       if (get_bindings (TREE_VALUE (fn),
14316                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14317                         NULL_TREE, /*check_ret=*/false))
14318         fate++;
14319
14320       if (fate == -1)
14321         champ = fn;
14322       else if (!fate)
14323         {
14324           /* Equally specialized, move to next function.  If there
14325              is no next function, nothing's most specialized.  */
14326           fn = TREE_CHAIN (fn);
14327           champ = fn;
14328           if (!fn)
14329             break;
14330         }
14331     }
14332
14333   if (champ)
14334     /* Now verify that champ is better than everything earlier in the
14335        instantiation list.  */
14336     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
14337       if (get_bindings (TREE_VALUE (champ),
14338                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14339                         NULL_TREE, /*check_ret=*/false)
14340           || !get_bindings (TREE_VALUE (fn),
14341                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14342                             NULL_TREE, /*check_ret=*/false))
14343         {
14344           champ = NULL_TREE;
14345           break;
14346         }
14347
14348   processing_template_decl--;
14349
14350   if (!champ)
14351     return error_mark_node;
14352
14353   return champ;
14354 }
14355
14356 /* If DECL is a specialization of some template, return the most
14357    general such template.  Otherwise, returns NULL_TREE.
14358
14359    For example, given:
14360
14361      template <class T> struct S { template <class U> void f(U); };
14362
14363    if TMPL is `template <class U> void S<int>::f(U)' this will return
14364    the full template.  This function will not trace past partial
14365    specializations, however.  For example, given in addition:
14366
14367      template <class T> struct S<T*> { template <class U> void f(U); };
14368
14369    if TMPL is `template <class U> void S<int*>::f(U)' this will return
14370    `template <class T> template <class U> S<T*>::f(U)'.  */
14371
14372 tree
14373 most_general_template (tree decl)
14374 {
14375   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
14376      an immediate specialization.  */
14377   if (TREE_CODE (decl) == FUNCTION_DECL)
14378     {
14379       if (DECL_TEMPLATE_INFO (decl)) {
14380         decl = DECL_TI_TEMPLATE (decl);
14381
14382         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
14383            template friend.  */
14384         if (TREE_CODE (decl) != TEMPLATE_DECL)
14385           return NULL_TREE;
14386       } else
14387         return NULL_TREE;
14388     }
14389
14390   /* Look for more and more general templates.  */
14391   while (DECL_TEMPLATE_INFO (decl))
14392     {
14393       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
14394          (See cp-tree.h for details.)  */
14395       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
14396         break;
14397
14398       if (CLASS_TYPE_P (TREE_TYPE (decl))
14399           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
14400         break;
14401
14402       /* Stop if we run into an explicitly specialized class template.  */
14403       if (!DECL_NAMESPACE_SCOPE_P (decl)
14404           && DECL_CONTEXT (decl)
14405           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
14406         break;
14407
14408       decl = DECL_TI_TEMPLATE (decl);
14409     }
14410
14411   return decl;
14412 }
14413
14414 /* Return the most specialized of the class template partial
14415    specializations of TMPL which can produce TYPE, a specialization of
14416    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
14417    a _TYPE node corresponding to the partial specialization, while the
14418    TREE_PURPOSE is the set of template arguments that must be
14419    substituted into the TREE_TYPE in order to generate TYPE.
14420
14421    If the choice of partial specialization is ambiguous, a diagnostic
14422    is issued, and the error_mark_node is returned.  If there are no
14423    partial specializations of TMPL matching TYPE, then NULL_TREE is
14424    returned.  */
14425
14426 static tree
14427 most_specialized_class (tree type, tree tmpl)
14428 {
14429   tree list = NULL_TREE;
14430   tree t;
14431   tree champ;
14432   int fate;
14433   bool ambiguous_p;
14434   tree args;
14435   tree outer_args = NULL_TREE;
14436
14437   tmpl = most_general_template (tmpl);
14438   args = CLASSTYPE_TI_ARGS (type);
14439
14440   /* For determining which partial specialization to use, only the
14441      innermost args are interesting.  */
14442   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14443     {
14444       outer_args = strip_innermost_template_args (args, 1);
14445       args = INNERMOST_TEMPLATE_ARGS (args);
14446     }
14447
14448   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
14449     {
14450       tree partial_spec_args;
14451       tree spec_args;
14452       tree parms = TREE_VALUE (t);
14453
14454       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
14455       if (outer_args)
14456         {
14457           int i;
14458
14459           ++processing_template_decl;
14460
14461           /* Discard the outer levels of args, and then substitute in the
14462              template args from the enclosing class.  */
14463           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
14464           partial_spec_args = tsubst_template_args
14465             (partial_spec_args, outer_args, tf_none, NULL_TREE);
14466
14467           /* PARMS already refers to just the innermost parms, but the
14468              template parms in partial_spec_args had their levels lowered
14469              by tsubst, so we need to do the same for the parm list.  We
14470              can't just tsubst the TREE_VEC itself, as tsubst wants to
14471              treat a TREE_VEC as an argument vector.  */
14472           parms = copy_node (parms);
14473           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
14474             TREE_VEC_ELT (parms, i) =
14475               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
14476
14477           --processing_template_decl;
14478         }
14479       spec_args = get_class_bindings (parms,
14480                                       partial_spec_args,
14481                                       args);
14482       if (spec_args)
14483         {
14484           if (outer_args)
14485             spec_args = add_to_template_args (outer_args, spec_args);
14486           list = tree_cons (spec_args, TREE_VALUE (t), list);
14487           TREE_TYPE (list) = TREE_TYPE (t);
14488         }
14489     }
14490
14491   if (! list)
14492     return NULL_TREE;
14493
14494   ambiguous_p = false;
14495   t = list;
14496   champ = t;
14497   t = TREE_CHAIN (t);
14498   for (; t; t = TREE_CHAIN (t))
14499     {
14500       fate = more_specialized_class (champ, t);
14501       if (fate == 1)
14502         ;
14503       else
14504         {
14505           if (fate == 0)
14506             {
14507               t = TREE_CHAIN (t);
14508               if (! t)
14509                 {
14510                   ambiguous_p = true;
14511                   break;
14512                 }
14513             }
14514           champ = t;
14515         }
14516     }
14517
14518   if (!ambiguous_p)
14519     for (t = list; t && t != champ; t = TREE_CHAIN (t))
14520       {
14521         fate = more_specialized_class (champ, t);
14522         if (fate != 1)
14523           {
14524             ambiguous_p = true;
14525             break;
14526           }
14527       }
14528
14529   if (ambiguous_p)
14530     {
14531       const char *str = "candidates are:";
14532       error ("ambiguous class template instantiation for %q#T", type);
14533       for (t = list; t; t = TREE_CHAIN (t))
14534         {
14535           error ("%s %+#T", str, TREE_TYPE (t));
14536           str = "               ";
14537         }
14538       return error_mark_node;
14539     }
14540
14541   return champ;
14542 }
14543
14544 /* Explicitly instantiate DECL.  */
14545
14546 void
14547 do_decl_instantiation (tree decl, tree storage)
14548 {
14549   tree result = NULL_TREE;
14550   int extern_p = 0;
14551
14552   if (!decl || decl == error_mark_node)
14553     /* An error occurred, for which grokdeclarator has already issued
14554        an appropriate message.  */
14555     return;
14556   else if (! DECL_LANG_SPECIFIC (decl))
14557     {
14558       error ("explicit instantiation of non-template %q#D", decl);
14559       return;
14560     }
14561   else if (TREE_CODE (decl) == VAR_DECL)
14562     {
14563       /* There is an asymmetry here in the way VAR_DECLs and
14564          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
14565          the latter, the DECL we get back will be marked as a
14566          template instantiation, and the appropriate
14567          DECL_TEMPLATE_INFO will be set up.  This does not happen for
14568          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
14569          should handle VAR_DECLs as it currently handles
14570          FUNCTION_DECLs.  */
14571       if (!DECL_CLASS_SCOPE_P (decl))
14572         {
14573           error ("%qD is not a static data member of a class template", decl);
14574           return;
14575         }
14576       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
14577       if (!result || TREE_CODE (result) != VAR_DECL)
14578         {
14579           error ("no matching template for %qD found", decl);
14580           return;
14581         }
14582       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
14583         {
14584           error ("type %qT for explicit instantiation %qD does not match "
14585                  "declared type %qT", TREE_TYPE (result), decl,
14586                  TREE_TYPE (decl));
14587           return;
14588         }
14589     }
14590   else if (TREE_CODE (decl) != FUNCTION_DECL)
14591     {
14592       error ("explicit instantiation of %q#D", decl);
14593       return;
14594     }
14595   else
14596     result = decl;
14597
14598   /* Check for various error cases.  Note that if the explicit
14599      instantiation is valid the RESULT will currently be marked as an
14600      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
14601      until we get here.  */
14602
14603   if (DECL_TEMPLATE_SPECIALIZATION (result))
14604     {
14605       /* DR 259 [temp.spec].
14606
14607          Both an explicit instantiation and a declaration of an explicit
14608          specialization shall not appear in a program unless the explicit
14609          instantiation follows a declaration of the explicit specialization.
14610
14611          For a given set of template parameters, if an explicit
14612          instantiation of a template appears after a declaration of an
14613          explicit specialization for that template, the explicit
14614          instantiation has no effect.  */
14615       return;
14616     }
14617   else if (DECL_EXPLICIT_INSTANTIATION (result))
14618     {
14619       /* [temp.spec]
14620
14621          No program shall explicitly instantiate any template more
14622          than once.
14623
14624          We check DECL_NOT_REALLY_EXTERN so as not to complain when
14625          the first instantiation was `extern' and the second is not,
14626          and EXTERN_P for the opposite case.  */
14627       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
14628         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
14629       /* If an "extern" explicit instantiation follows an ordinary
14630          explicit instantiation, the template is instantiated.  */
14631       if (extern_p)
14632         return;
14633     }
14634   else if (!DECL_IMPLICIT_INSTANTIATION (result))
14635     {
14636       error ("no matching template for %qD found", result);
14637       return;
14638     }
14639   else if (!DECL_TEMPLATE_INFO (result))
14640     {
14641       permerror (input_location, "explicit instantiation of non-template %q#D", result);
14642       return;
14643     }
14644
14645   if (storage == NULL_TREE)
14646     ;
14647   else if (storage == ridpointers[(int) RID_EXTERN])
14648     {
14649       if (!in_system_header && (cxx_dialect == cxx98))
14650         pedwarn (input_location, OPT_pedantic, 
14651                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
14652                  "instantiations");
14653       extern_p = 1;
14654     }
14655   else
14656     error ("storage class %qD applied to template instantiation", storage);
14657
14658   check_explicit_instantiation_namespace (result);
14659   mark_decl_instantiated (result, extern_p);
14660   if (! extern_p)
14661     instantiate_decl (result, /*defer_ok=*/1,
14662                       /*expl_inst_class_mem_p=*/false);
14663 }
14664
14665 static void
14666 mark_class_instantiated (tree t, int extern_p)
14667 {
14668   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
14669   SET_CLASSTYPE_INTERFACE_KNOWN (t);
14670   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
14671   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
14672   if (! extern_p)
14673     {
14674       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
14675       rest_of_type_compilation (t, 1);
14676     }
14677 }
14678
14679 /* Called from do_type_instantiation through binding_table_foreach to
14680    do recursive instantiation for the type bound in ENTRY.  */
14681 static void
14682 bt_instantiate_type_proc (binding_entry entry, void *data)
14683 {
14684   tree storage = *(tree *) data;
14685
14686   if (MAYBE_CLASS_TYPE_P (entry->type)
14687       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
14688     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
14689 }
14690
14691 /* Called from do_type_instantiation to instantiate a member
14692    (a member function or a static member variable) of an
14693    explicitly instantiated class template.  */
14694 static void
14695 instantiate_class_member (tree decl, int extern_p)
14696 {
14697   mark_decl_instantiated (decl, extern_p);
14698   if (! extern_p)
14699     instantiate_decl (decl, /*defer_ok=*/1,
14700                       /*expl_inst_class_mem_p=*/true);
14701 }
14702
14703 /* Perform an explicit instantiation of template class T.  STORAGE, if
14704    non-null, is the RID for extern, inline or static.  COMPLAIN is
14705    nonzero if this is called from the parser, zero if called recursively,
14706    since the standard is unclear (as detailed below).  */
14707
14708 void
14709 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
14710 {
14711   int extern_p = 0;
14712   int nomem_p = 0;
14713   int static_p = 0;
14714   int previous_instantiation_extern_p = 0;
14715
14716   if (TREE_CODE (t) == TYPE_DECL)
14717     t = TREE_TYPE (t);
14718
14719   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
14720     {
14721       error ("explicit instantiation of non-template type %qT", t);
14722       return;
14723     }
14724
14725   complete_type (t);
14726
14727   if (!COMPLETE_TYPE_P (t))
14728     {
14729       if (complain & tf_error)
14730         error ("explicit instantiation of %q#T before definition of template",
14731                t);
14732       return;
14733     }
14734
14735   if (storage != NULL_TREE)
14736     {
14737       if (!in_system_header)
14738         {
14739           if (storage == ridpointers[(int) RID_EXTERN])
14740             {
14741               if (cxx_dialect == cxx98)
14742                 pedwarn (input_location, OPT_pedantic, 
14743                          "ISO C++ 1998 forbids the use of %<extern%> on "
14744                          "explicit instantiations");
14745             }
14746           else
14747             pedwarn (input_location, OPT_pedantic, 
14748                      "ISO C++ forbids the use of %qE"
14749                      " on explicit instantiations", storage);
14750         }
14751
14752       if (storage == ridpointers[(int) RID_INLINE])
14753         nomem_p = 1;
14754       else if (storage == ridpointers[(int) RID_EXTERN])
14755         extern_p = 1;
14756       else if (storage == ridpointers[(int) RID_STATIC])
14757         static_p = 1;
14758       else
14759         {
14760           error ("storage class %qD applied to template instantiation",
14761                  storage);
14762           extern_p = 0;
14763         }
14764     }
14765
14766   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
14767     {
14768       /* DR 259 [temp.spec].
14769
14770          Both an explicit instantiation and a declaration of an explicit
14771          specialization shall not appear in a program unless the explicit
14772          instantiation follows a declaration of the explicit specialization.
14773
14774          For a given set of template parameters, if an explicit
14775          instantiation of a template appears after a declaration of an
14776          explicit specialization for that template, the explicit
14777          instantiation has no effect.  */
14778       return;
14779     }
14780   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
14781     {
14782       /* [temp.spec]
14783
14784          No program shall explicitly instantiate any template more
14785          than once.
14786
14787          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
14788          instantiation was `extern'.  If EXTERN_P then the second is.
14789          These cases are OK.  */
14790       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
14791
14792       if (!previous_instantiation_extern_p && !extern_p
14793           && (complain & tf_error))
14794         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
14795
14796       /* If we've already instantiated the template, just return now.  */
14797       if (!CLASSTYPE_INTERFACE_ONLY (t))
14798         return;
14799     }
14800
14801   check_explicit_instantiation_namespace (TYPE_NAME (t));
14802   mark_class_instantiated (t, extern_p);
14803
14804   if (nomem_p)
14805     return;
14806
14807   {
14808     tree tmp;
14809
14810     /* In contrast to implicit instantiation, where only the
14811        declarations, and not the definitions, of members are
14812        instantiated, we have here:
14813
14814          [temp.explicit]
14815
14816          The explicit instantiation of a class template specialization
14817          implies the instantiation of all of its members not
14818          previously explicitly specialized in the translation unit
14819          containing the explicit instantiation.
14820
14821        Of course, we can't instantiate member template classes, since
14822        we don't have any arguments for them.  Note that the standard
14823        is unclear on whether the instantiation of the members are
14824        *explicit* instantiations or not.  However, the most natural
14825        interpretation is that it should be an explicit instantiation.  */
14826
14827     if (! static_p)
14828       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
14829         if (TREE_CODE (tmp) == FUNCTION_DECL
14830             && DECL_TEMPLATE_INSTANTIATION (tmp))
14831           instantiate_class_member (tmp, extern_p);
14832
14833     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
14834       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
14835         instantiate_class_member (tmp, extern_p);
14836
14837     if (CLASSTYPE_NESTED_UTDS (t))
14838       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
14839                              bt_instantiate_type_proc, &storage);
14840   }
14841 }
14842
14843 /* Given a function DECL, which is a specialization of TMPL, modify
14844    DECL to be a re-instantiation of TMPL with the same template
14845    arguments.  TMPL should be the template into which tsubst'ing
14846    should occur for DECL, not the most general template.
14847
14848    One reason for doing this is a scenario like this:
14849
14850      template <class T>
14851      void f(const T&, int i);
14852
14853      void g() { f(3, 7); }
14854
14855      template <class T>
14856      void f(const T& t, const int i) { }
14857
14858    Note that when the template is first instantiated, with
14859    instantiate_template, the resulting DECL will have no name for the
14860    first parameter, and the wrong type for the second.  So, when we go
14861    to instantiate the DECL, we regenerate it.  */
14862
14863 static void
14864 regenerate_decl_from_template (tree decl, tree tmpl)
14865 {
14866   /* The arguments used to instantiate DECL, from the most general
14867      template.  */
14868   tree args;
14869   tree code_pattern;
14870
14871   args = DECL_TI_ARGS (decl);
14872   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
14873
14874   /* Make sure that we can see identifiers, and compute access
14875      correctly.  */
14876   push_access_scope (decl);
14877
14878   if (TREE_CODE (decl) == FUNCTION_DECL)
14879     {
14880       tree decl_parm;
14881       tree pattern_parm;
14882       tree specs;
14883       int args_depth;
14884       int parms_depth;
14885
14886       args_depth = TMPL_ARGS_DEPTH (args);
14887       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
14888       if (args_depth > parms_depth)
14889         args = get_innermost_template_args (args, parms_depth);
14890
14891       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
14892                                               args, tf_error, NULL_TREE);
14893       if (specs)
14894         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
14895                                                     specs);
14896
14897       /* Merge parameter declarations.  */
14898       decl_parm = skip_artificial_parms_for (decl,
14899                                              DECL_ARGUMENTS (decl));
14900       pattern_parm
14901         = skip_artificial_parms_for (code_pattern,
14902                                      DECL_ARGUMENTS (code_pattern));
14903       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
14904         {
14905           tree parm_type;
14906           tree attributes;
14907           
14908           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
14909             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
14910           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
14911                               NULL_TREE);
14912           parm_type = type_decays_to (parm_type);
14913           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
14914             TREE_TYPE (decl_parm) = parm_type;
14915           attributes = DECL_ATTRIBUTES (pattern_parm);
14916           if (DECL_ATTRIBUTES (decl_parm) != attributes)
14917             {
14918               DECL_ATTRIBUTES (decl_parm) = attributes;
14919               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
14920             }
14921           decl_parm = TREE_CHAIN (decl_parm);
14922           pattern_parm = TREE_CHAIN (pattern_parm);
14923         }
14924       /* Merge any parameters that match with the function parameter
14925          pack.  */
14926       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
14927         {
14928           int i, len;
14929           tree expanded_types;
14930           /* Expand the TYPE_PACK_EXPANSION that provides the types for
14931              the parameters in this function parameter pack.  */
14932           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
14933                                                  args, tf_error, NULL_TREE);
14934           len = TREE_VEC_LENGTH (expanded_types);
14935           for (i = 0; i < len; i++)
14936             {
14937               tree parm_type;
14938               tree attributes;
14939           
14940               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
14941                 /* Rename the parameter to include the index.  */
14942                 DECL_NAME (decl_parm) = 
14943                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
14944               parm_type = TREE_VEC_ELT (expanded_types, i);
14945               parm_type = type_decays_to (parm_type);
14946               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
14947                 TREE_TYPE (decl_parm) = parm_type;
14948               attributes = DECL_ATTRIBUTES (pattern_parm);
14949               if (DECL_ATTRIBUTES (decl_parm) != attributes)
14950                 {
14951                   DECL_ATTRIBUTES (decl_parm) = attributes;
14952                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
14953                 }
14954               decl_parm = TREE_CHAIN (decl_parm);
14955             }
14956         }
14957       /* Merge additional specifiers from the CODE_PATTERN.  */
14958       if (DECL_DECLARED_INLINE_P (code_pattern)
14959           && !DECL_DECLARED_INLINE_P (decl))
14960         DECL_DECLARED_INLINE_P (decl) = 1;
14961     }
14962   else if (TREE_CODE (decl) == VAR_DECL)
14963     DECL_INITIAL (decl) =
14964       tsubst_expr (DECL_INITIAL (code_pattern), args,
14965                    tf_error, DECL_TI_TEMPLATE (decl),
14966                    /*integral_constant_expression_p=*/false);
14967   else
14968     gcc_unreachable ();
14969
14970   pop_access_scope (decl);
14971 }
14972
14973 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
14974    substituted to get DECL.  */
14975
14976 tree
14977 template_for_substitution (tree decl)
14978 {
14979   tree tmpl = DECL_TI_TEMPLATE (decl);
14980
14981   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
14982      for the instantiation.  This is not always the most general
14983      template.  Consider, for example:
14984
14985         template <class T>
14986         struct S { template <class U> void f();
14987                    template <> void f<int>(); };
14988
14989      and an instantiation of S<double>::f<int>.  We want TD to be the
14990      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
14991   while (/* An instantiation cannot have a definition, so we need a
14992             more general template.  */
14993          DECL_TEMPLATE_INSTANTIATION (tmpl)
14994            /* We must also deal with friend templates.  Given:
14995
14996                 template <class T> struct S {
14997                   template <class U> friend void f() {};
14998                 };
14999
15000               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
15001               so far as the language is concerned, but that's still
15002               where we get the pattern for the instantiation from.  On
15003               other hand, if the definition comes outside the class, say:
15004
15005                 template <class T> struct S {
15006                   template <class U> friend void f();
15007                 };
15008                 template <class U> friend void f() {}
15009
15010               we don't need to look any further.  That's what the check for
15011               DECL_INITIAL is for.  */
15012           || (TREE_CODE (decl) == FUNCTION_DECL
15013               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
15014               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
15015     {
15016       /* The present template, TD, should not be a definition.  If it
15017          were a definition, we should be using it!  Note that we
15018          cannot restructure the loop to just keep going until we find
15019          a template with a definition, since that might go too far if
15020          a specialization was declared, but not defined.  */
15021       gcc_assert (TREE_CODE (decl) != VAR_DECL
15022                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
15023
15024       /* Fetch the more general template.  */
15025       tmpl = DECL_TI_TEMPLATE (tmpl);
15026     }
15027
15028   return tmpl;
15029 }
15030
15031 /* Produce the definition of D, a _DECL generated from a template.  If
15032    DEFER_OK is nonzero, then we don't have to actually do the
15033    instantiation now; we just have to do it sometime.  Normally it is
15034    an error if this is an explicit instantiation but D is undefined.
15035    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
15036    explicitly instantiated class template.  */
15037
15038 tree
15039 instantiate_decl (tree d, int defer_ok,
15040                   bool expl_inst_class_mem_p)
15041 {
15042   tree tmpl = DECL_TI_TEMPLATE (d);
15043   tree gen_args;
15044   tree args;
15045   tree td;
15046   tree code_pattern;
15047   tree spec;
15048   tree gen_tmpl;
15049   bool pattern_defined;
15050   int need_push;
15051   location_t saved_loc = input_location;
15052   bool external_p;
15053
15054   /* This function should only be used to instantiate templates for
15055      functions and static member variables.  */
15056   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
15057               || TREE_CODE (d) == VAR_DECL);
15058
15059   /* Variables are never deferred; if instantiation is required, they
15060      are instantiated right away.  That allows for better code in the
15061      case that an expression refers to the value of the variable --
15062      if the variable has a constant value the referring expression can
15063      take advantage of that fact.  */
15064   if (TREE_CODE (d) == VAR_DECL)
15065     defer_ok = 0;
15066
15067   /* Don't instantiate cloned functions.  Instead, instantiate the
15068      functions they cloned.  */
15069   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
15070     d = DECL_CLONED_FUNCTION (d);
15071
15072   if (DECL_TEMPLATE_INSTANTIATED (d))
15073     /* D has already been instantiated.  It might seem reasonable to
15074        check whether or not D is an explicit instantiation, and, if so,
15075        stop here.  But when an explicit instantiation is deferred
15076        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
15077        is set, even though we still need to do the instantiation.  */
15078     return d;
15079
15080   /* If we already have a specialization of this declaration, then
15081      there's no reason to instantiate it.  Note that
15082      retrieve_specialization gives us both instantiations and
15083      specializations, so we must explicitly check
15084      DECL_TEMPLATE_SPECIALIZATION.  */
15085   gen_tmpl = most_general_template (tmpl);
15086   gen_args = DECL_TI_ARGS (d);
15087   spec = retrieve_specialization (gen_tmpl, gen_args,
15088                                   /*class_specializations_p=*/false);
15089   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
15090     return spec;
15091
15092   /* This needs to happen before any tsubsting.  */
15093   if (! push_tinst_level (d))
15094     return d;
15095
15096   timevar_push (TV_PARSE);
15097
15098   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
15099      for the instantiation.  */
15100   td = template_for_substitution (d);
15101   code_pattern = DECL_TEMPLATE_RESULT (td);
15102
15103   /* We should never be trying to instantiate a member of a class
15104      template or partial specialization.  */
15105   gcc_assert (d != code_pattern);
15106
15107   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
15108       || DECL_TEMPLATE_SPECIALIZATION (td))
15109     /* In the case of a friend template whose definition is provided
15110        outside the class, we may have too many arguments.  Drop the
15111        ones we don't need.  The same is true for specializations.  */
15112     args = get_innermost_template_args
15113       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
15114   else
15115     args = gen_args;
15116
15117   if (TREE_CODE (d) == FUNCTION_DECL)
15118     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
15119   else
15120     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
15121
15122   /* We may be in the middle of deferred access check.  Disable it now.  */
15123   push_deferring_access_checks (dk_no_deferred);
15124
15125   /* Unless an explicit instantiation directive has already determined
15126      the linkage of D, remember that a definition is available for
15127      this entity.  */
15128   if (pattern_defined
15129       && !DECL_INTERFACE_KNOWN (d)
15130       && !DECL_NOT_REALLY_EXTERN (d))
15131     mark_definable (d);
15132
15133   input_location = DECL_SOURCE_LOCATION (d);
15134
15135   /* If D is a member of an explicitly instantiated class template,
15136      and no definition is available, treat it like an implicit
15137      instantiation.  */
15138   if (!pattern_defined && expl_inst_class_mem_p
15139       && DECL_EXPLICIT_INSTANTIATION (d))
15140     {
15141       DECL_NOT_REALLY_EXTERN (d) = 0;
15142       DECL_INTERFACE_KNOWN (d) = 0;
15143       SET_DECL_IMPLICIT_INSTANTIATION (d);
15144     }
15145
15146   if (!defer_ok)
15147     {
15148       /* Recheck the substitutions to obtain any warning messages
15149          about ignoring cv qualifiers.  */
15150       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
15151       tree type = TREE_TYPE (gen);
15152
15153       /* Make sure that we can see identifiers, and compute access
15154          correctly.  D is already the target FUNCTION_DECL with the
15155          right context.  */
15156       push_access_scope (d);
15157
15158       if (TREE_CODE (gen) == FUNCTION_DECL)
15159         {
15160           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
15161           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
15162                                           d);
15163           /* Don't simply tsubst the function type, as that will give
15164              duplicate warnings about poor parameter qualifications.
15165              The function arguments are the same as the decl_arguments
15166              without the top level cv qualifiers.  */
15167           type = TREE_TYPE (type);
15168         }
15169       tsubst (type, gen_args, tf_warning_or_error, d);
15170
15171       pop_access_scope (d);
15172     }
15173
15174   /* Check to see whether we know that this template will be
15175      instantiated in some other file, as with "extern template"
15176      extension.  */
15177   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
15178   /* In general, we do not instantiate such templates...  */
15179   if (external_p
15180       /* ... but we instantiate inline functions so that we can inline
15181          them and ... */
15182       && ! (TREE_CODE (d) == FUNCTION_DECL
15183             && possibly_inlined_p (d))
15184       /* ... we instantiate static data members whose values are
15185          needed in integral constant expressions.  */
15186       && ! (TREE_CODE (d) == VAR_DECL
15187             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
15188     goto out;
15189   /* Defer all other templates, unless we have been explicitly
15190      forbidden from doing so.  */
15191   if (/* If there is no definition, we cannot instantiate the
15192          template.  */
15193       ! pattern_defined
15194       /* If it's OK to postpone instantiation, do so.  */
15195       || defer_ok
15196       /* If this is a static data member that will be defined
15197          elsewhere, we don't want to instantiate the entire data
15198          member, but we do want to instantiate the initializer so that
15199          we can substitute that elsewhere.  */
15200       || (external_p && TREE_CODE (d) == VAR_DECL))
15201     {
15202       /* The definition of the static data member is now required so
15203          we must substitute the initializer.  */
15204       if (TREE_CODE (d) == VAR_DECL
15205           && !DECL_INITIAL (d)
15206           && DECL_INITIAL (code_pattern))
15207         {
15208           tree ns;
15209           tree init;
15210
15211           ns = decl_namespace_context (d);
15212           push_nested_namespace (ns);
15213           push_nested_class (DECL_CONTEXT (d));
15214           init = tsubst_expr (DECL_INITIAL (code_pattern),
15215                               args,
15216                               tf_warning_or_error, NULL_TREE,
15217                               /*integral_constant_expression_p=*/false);
15218           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
15219                           /*asmspec_tree=*/NULL_TREE,
15220                           LOOKUP_ONLYCONVERTING);
15221           pop_nested_class ();
15222           pop_nested_namespace (ns);
15223         }
15224
15225       /* We restore the source position here because it's used by
15226          add_pending_template.  */
15227       input_location = saved_loc;
15228
15229       if (at_eof && !pattern_defined
15230           && DECL_EXPLICIT_INSTANTIATION (d)
15231           && DECL_NOT_REALLY_EXTERN (d))
15232         /* [temp.explicit]
15233
15234            The definition of a non-exported function template, a
15235            non-exported member function template, or a non-exported
15236            member function or static data member of a class template
15237            shall be present in every translation unit in which it is
15238            explicitly instantiated.  */
15239         permerror (input_location,  "explicit instantiation of %qD "
15240                    "but no definition available", d);
15241
15242       /* ??? Historically, we have instantiated inline functions, even
15243          when marked as "extern template".  */
15244       if (!(external_p && TREE_CODE (d) == VAR_DECL))
15245         add_pending_template (d);
15246       goto out;
15247     }
15248   /* Tell the repository that D is available in this translation unit
15249      -- and see if it is supposed to be instantiated here.  */
15250   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
15251     {
15252       /* In a PCH file, despite the fact that the repository hasn't
15253          requested instantiation in the PCH it is still possible that
15254          an instantiation will be required in a file that includes the
15255          PCH.  */
15256       if (pch_file)
15257         add_pending_template (d);
15258       /* Instantiate inline functions so that the inliner can do its
15259          job, even though we'll not be emitting a copy of this
15260          function.  */
15261       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
15262         goto out;
15263     }
15264
15265   need_push = !cfun || !global_bindings_p ();
15266   if (need_push)
15267     push_to_top_level ();
15268
15269   /* Mark D as instantiated so that recursive calls to
15270      instantiate_decl do not try to instantiate it again.  */
15271   DECL_TEMPLATE_INSTANTIATED (d) = 1;
15272
15273   /* Regenerate the declaration in case the template has been modified
15274      by a subsequent redeclaration.  */
15275   regenerate_decl_from_template (d, td);
15276
15277   /* We already set the file and line above.  Reset them now in case
15278      they changed as a result of calling regenerate_decl_from_template.  */
15279   input_location = DECL_SOURCE_LOCATION (d);
15280
15281   if (TREE_CODE (d) == VAR_DECL)
15282     {
15283       tree init;
15284
15285       /* Clear out DECL_RTL; whatever was there before may not be right
15286          since we've reset the type of the declaration.  */
15287       SET_DECL_RTL (d, NULL_RTX);
15288       DECL_IN_AGGR_P (d) = 0;
15289
15290       /* The initializer is placed in DECL_INITIAL by
15291          regenerate_decl_from_template.  Pull it out so that
15292          finish_decl can process it.  */
15293       init = DECL_INITIAL (d);
15294       DECL_INITIAL (d) = NULL_TREE;
15295       DECL_INITIALIZED_P (d) = 0;
15296
15297       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
15298          initializer.  That function will defer actual emission until
15299          we have a chance to determine linkage.  */
15300       DECL_EXTERNAL (d) = 0;
15301
15302       /* Enter the scope of D so that access-checking works correctly.  */
15303       push_nested_class (DECL_CONTEXT (d));
15304       finish_decl (d, init, NULL_TREE);
15305       pop_nested_class ();
15306     }
15307   else if (TREE_CODE (d) == FUNCTION_DECL)
15308     {
15309       htab_t saved_local_specializations;
15310       tree subst_decl;
15311       tree tmpl_parm;
15312       tree spec_parm;
15313
15314       /* Save away the current list, in case we are instantiating one
15315          template from within the body of another.  */
15316       saved_local_specializations = local_specializations;
15317
15318       /* Set up the list of local specializations.  */
15319       local_specializations = htab_create (37,
15320                                            hash_local_specialization,
15321                                            eq_local_specializations,
15322                                            NULL);
15323
15324       /* Set up context.  */
15325       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
15326
15327       /* Create substitution entries for the parameters.  */
15328       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
15329       tmpl_parm = DECL_ARGUMENTS (subst_decl);
15330       spec_parm = DECL_ARGUMENTS (d);
15331       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
15332         {
15333           register_local_specialization (spec_parm, tmpl_parm);
15334           spec_parm = skip_artificial_parms_for (d, spec_parm);
15335           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
15336         }
15337       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15338         {
15339           register_local_specialization (spec_parm, tmpl_parm);
15340           tmpl_parm = TREE_CHAIN (tmpl_parm);
15341           spec_parm = TREE_CHAIN (spec_parm);
15342         }
15343       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15344         {
15345           /* Collect all of the extra "packed" parameters into an
15346              argument pack.  */
15347           tree parmvec;
15348           tree parmtypevec;
15349           tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
15350           tree argtypepack = make_node (TYPE_ARGUMENT_PACK);
15351           int i, len = 0;
15352           tree t;
15353           
15354           /* Count how many parameters remain.  */
15355           for (t = spec_parm; t; t = TREE_CHAIN (t))
15356             len++;
15357
15358           /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
15359           parmvec = make_tree_vec (len);
15360           parmtypevec = make_tree_vec (len);
15361           for(i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
15362             {
15363               TREE_VEC_ELT (parmvec, i) = spec_parm;
15364               TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
15365             }
15366
15367           /* Build the argument packs.  */
15368           SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
15369           SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
15370           TREE_TYPE (argpack) = argtypepack;
15371           
15372           /* Register the (value) argument pack as a specialization of
15373              TMPL_PARM, then move on.  */
15374           register_local_specialization (argpack, tmpl_parm);
15375           tmpl_parm = TREE_CHAIN (tmpl_parm);
15376         }
15377       gcc_assert (!spec_parm);
15378
15379       /* Substitute into the body of the function.  */
15380       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
15381                    tf_warning_or_error, tmpl,
15382                    /*integral_constant_expression_p=*/false);
15383
15384       /* Set the current input_location to the end of the function
15385          so that finish_function knows where we are.  */
15386       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
15387
15388       /* We don't need the local specializations any more.  */
15389       htab_delete (local_specializations);
15390       local_specializations = saved_local_specializations;
15391
15392       /* Finish the function.  */
15393       d = finish_function (0);
15394       expand_or_defer_fn (d);
15395     }
15396
15397   /* We're not deferring instantiation any more.  */
15398   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
15399
15400   if (need_push)
15401     pop_from_top_level ();
15402
15403 out:
15404   input_location = saved_loc;
15405   pop_deferring_access_checks ();
15406   pop_tinst_level ();
15407
15408   timevar_pop (TV_PARSE);
15409
15410   return d;
15411 }
15412
15413 /* Run through the list of templates that we wish we could
15414    instantiate, and instantiate any we can.  RETRIES is the
15415    number of times we retry pending template instantiation.  */
15416
15417 void
15418 instantiate_pending_templates (int retries)
15419 {
15420   int reconsider;
15421   location_t saved_loc = input_location;
15422
15423   /* Instantiating templates may trigger vtable generation.  This in turn
15424      may require further template instantiations.  We place a limit here
15425      to avoid infinite loop.  */
15426   if (pending_templates && retries >= max_tinst_depth)
15427     {
15428       tree decl = pending_templates->tinst->decl;
15429
15430       error ("template instantiation depth exceeds maximum of %d"
15431              " instantiating %q+D, possibly from virtual table generation"
15432              " (use -ftemplate-depth-NN to increase the maximum)",
15433              max_tinst_depth, decl);
15434       if (TREE_CODE (decl) == FUNCTION_DECL)
15435         /* Pretend that we defined it.  */
15436         DECL_INITIAL (decl) = error_mark_node;
15437       return;
15438     }
15439
15440   do
15441     {
15442       struct pending_template **t = &pending_templates;
15443       struct pending_template *last = NULL;
15444       reconsider = 0;
15445       while (*t)
15446         {
15447           tree instantiation = reopen_tinst_level ((*t)->tinst);
15448           bool complete = false;
15449
15450           if (TYPE_P (instantiation))
15451             {
15452               tree fn;
15453
15454               if (!COMPLETE_TYPE_P (instantiation))
15455                 {
15456                   instantiate_class_template (instantiation);
15457                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
15458                     for (fn = TYPE_METHODS (instantiation);
15459                          fn;
15460                          fn = TREE_CHAIN (fn))
15461                       if (! DECL_ARTIFICIAL (fn))
15462                         instantiate_decl (fn,
15463                                           /*defer_ok=*/0,
15464                                           /*expl_inst_class_mem_p=*/false);
15465                   if (COMPLETE_TYPE_P (instantiation))
15466                     reconsider = 1;
15467                 }
15468
15469               complete = COMPLETE_TYPE_P (instantiation);
15470             }
15471           else
15472             {
15473               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
15474                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
15475                 {
15476                   instantiation
15477                     = instantiate_decl (instantiation,
15478                                         /*defer_ok=*/0,
15479                                         /*expl_inst_class_mem_p=*/false);
15480                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
15481                     reconsider = 1;
15482                 }
15483
15484               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
15485                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
15486             }
15487
15488           if (complete)
15489             /* If INSTANTIATION has been instantiated, then we don't
15490                need to consider it again in the future.  */
15491             *t = (*t)->next;
15492           else
15493             {
15494               last = *t;
15495               t = &(*t)->next;
15496             }
15497           tinst_depth = 0;
15498           current_tinst_level = NULL;
15499         }
15500       last_pending_template = last;
15501     }
15502   while (reconsider);
15503
15504   input_location = saved_loc;
15505 }
15506
15507 /* Substitute ARGVEC into T, which is a list of initializers for
15508    either base class or a non-static data member.  The TREE_PURPOSEs
15509    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
15510    instantiate_decl.  */
15511
15512 static tree
15513 tsubst_initializer_list (tree t, tree argvec)
15514 {
15515   tree inits = NULL_TREE;
15516
15517   for (; t; t = TREE_CHAIN (t))
15518     {
15519       tree decl;
15520       tree init;
15521       tree expanded_bases = NULL_TREE;
15522       tree expanded_arguments = NULL_TREE;
15523       int i, len = 1;
15524
15525       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
15526         {
15527           tree expr;
15528           tree arg;
15529
15530           /* Expand the base class expansion type into separate base
15531              classes.  */
15532           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
15533                                                  tf_warning_or_error,
15534                                                  NULL_TREE);
15535           if (expanded_bases == error_mark_node)
15536             continue;
15537           
15538           /* We'll be building separate TREE_LISTs of arguments for
15539              each base.  */
15540           len = TREE_VEC_LENGTH (expanded_bases);
15541           expanded_arguments = make_tree_vec (len);
15542           for (i = 0; i < len; i++)
15543             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
15544
15545           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
15546              expand each argument in the TREE_VALUE of t.  */
15547           expr = make_node (EXPR_PACK_EXPANSION);
15548           PACK_EXPANSION_PARAMETER_PACKS (expr) =
15549             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
15550
15551           if (TREE_VALUE (t) == void_type_node)
15552             /* VOID_TYPE_NODE is used to indicate
15553                value-initialization.  */
15554             {
15555               for (i = 0; i < len; i++)
15556                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
15557             }
15558           else
15559             {
15560               /* Substitute parameter packs into each argument in the
15561                  TREE_LIST.  */
15562               in_base_initializer = 1;
15563               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
15564                 {
15565                   tree expanded_exprs;
15566
15567                   /* Expand the argument.  */
15568                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
15569                   expanded_exprs 
15570                     = tsubst_pack_expansion (expr, argvec,
15571                                              tf_warning_or_error,
15572                                              NULL_TREE);
15573                   if (expanded_exprs == error_mark_node)
15574                     continue;
15575
15576                   /* Prepend each of the expanded expressions to the
15577                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
15578                   for (i = 0; i < len; i++)
15579                     {
15580                       TREE_VEC_ELT (expanded_arguments, i) = 
15581                         tree_cons (NULL_TREE, 
15582                                    TREE_VEC_ELT (expanded_exprs, i),
15583                                    TREE_VEC_ELT (expanded_arguments, i));
15584                     }
15585                 }
15586               in_base_initializer = 0;
15587
15588               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
15589                  since we built them backwards.  */
15590               for (i = 0; i < len; i++)
15591                 {
15592                   TREE_VEC_ELT (expanded_arguments, i) = 
15593                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
15594                 }
15595             }
15596         }
15597
15598       for (i = 0; i < len; ++i)
15599         {
15600           if (expanded_bases)
15601             {
15602               decl = TREE_VEC_ELT (expanded_bases, i);
15603               decl = expand_member_init (decl);
15604               init = TREE_VEC_ELT (expanded_arguments, i);
15605             }
15606           else
15607             {
15608               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
15609                                   tf_warning_or_error, NULL_TREE);
15610
15611               decl = expand_member_init (decl);
15612               if (decl && !DECL_P (decl))
15613                 in_base_initializer = 1;
15614
15615               init = tsubst_expr (TREE_VALUE (t), argvec, 
15616                                   tf_warning_or_error, NULL_TREE,
15617                                   /*integral_constant_expression_p=*/false);
15618               in_base_initializer = 0;
15619             }
15620
15621           if (decl)
15622             {
15623               init = build_tree_list (decl, init);
15624               TREE_CHAIN (init) = inits;
15625               inits = init;
15626             }
15627         }
15628     }
15629   return inits;
15630 }
15631
15632 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
15633
15634 static void
15635 set_current_access_from_decl (tree decl)
15636 {
15637   if (TREE_PRIVATE (decl))
15638     current_access_specifier = access_private_node;
15639   else if (TREE_PROTECTED (decl))
15640     current_access_specifier = access_protected_node;
15641   else
15642     current_access_specifier = access_public_node;
15643 }
15644
15645 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
15646    is the instantiation (which should have been created with
15647    start_enum) and ARGS are the template arguments to use.  */
15648
15649 static void
15650 tsubst_enum (tree tag, tree newtag, tree args)
15651 {
15652   tree e;
15653
15654   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
15655     {
15656       tree value;
15657       tree decl;
15658
15659       decl = TREE_VALUE (e);
15660       /* Note that in a template enum, the TREE_VALUE is the
15661          CONST_DECL, not the corresponding INTEGER_CST.  */
15662       value = tsubst_expr (DECL_INITIAL (decl),
15663                            args, tf_warning_or_error, NULL_TREE,
15664                            /*integral_constant_expression_p=*/true);
15665
15666       /* Give this enumeration constant the correct access.  */
15667       set_current_access_from_decl (decl);
15668
15669       /* Actually build the enumerator itself.  */
15670       build_enumerator (DECL_NAME (decl), value, newtag);
15671     }
15672
15673   finish_enum (newtag);
15674   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
15675     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
15676 }
15677
15678 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
15679    its type -- but without substituting the innermost set of template
15680    arguments.  So, innermost set of template parameters will appear in
15681    the type.  */
15682
15683 tree
15684 get_mostly_instantiated_function_type (tree decl)
15685 {
15686   tree fn_type;
15687   tree tmpl;
15688   tree targs;
15689   tree tparms;
15690   int parm_depth;
15691
15692   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15693   targs = DECL_TI_ARGS (decl);
15694   tparms = DECL_TEMPLATE_PARMS (tmpl);
15695   parm_depth = TMPL_PARMS_DEPTH (tparms);
15696
15697   /* There should be as many levels of arguments as there are levels
15698      of parameters.  */
15699   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
15700
15701   fn_type = TREE_TYPE (tmpl);
15702
15703   if (parm_depth == 1)
15704     /* No substitution is necessary.  */
15705     ;
15706   else
15707     {
15708       int i, save_access_control;
15709       tree partial_args;
15710
15711       /* Replace the innermost level of the TARGS with NULL_TREEs to
15712          let tsubst know not to substitute for those parameters.  */
15713       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
15714       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
15715         SET_TMPL_ARGS_LEVEL (partial_args, i,
15716                              TMPL_ARGS_LEVEL (targs, i));
15717       SET_TMPL_ARGS_LEVEL (partial_args,
15718                            TMPL_ARGS_DEPTH (targs),
15719                            make_tree_vec (DECL_NTPARMS (tmpl)));
15720
15721       /* Disable access control as this function is used only during
15722          name-mangling.  */
15723       save_access_control = flag_access_control;
15724       flag_access_control = 0;
15725
15726       ++processing_template_decl;
15727       /* Now, do the (partial) substitution to figure out the
15728          appropriate function type.  */
15729       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
15730       --processing_template_decl;
15731
15732       /* Substitute into the template parameters to obtain the real
15733          innermost set of parameters.  This step is important if the
15734          innermost set of template parameters contains value
15735          parameters whose types depend on outer template parameters.  */
15736       TREE_VEC_LENGTH (partial_args)--;
15737       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
15738
15739       flag_access_control = save_access_control;
15740     }
15741
15742   return fn_type;
15743 }
15744
15745 /* Return truthvalue if we're processing a template different from
15746    the last one involved in diagnostics.  */
15747 int
15748 problematic_instantiation_changed (void)
15749 {
15750   return last_template_error_tick != tinst_level_tick;
15751 }
15752
15753 /* Remember current template involved in diagnostics.  */
15754 void
15755 record_last_problematic_instantiation (void)
15756 {
15757   last_template_error_tick = tinst_level_tick;
15758 }
15759
15760 struct tinst_level *
15761 current_instantiation (void)
15762 {
15763   return current_tinst_level;
15764 }
15765
15766 /* [temp.param] Check that template non-type parm TYPE is of an allowable
15767    type. Return zero for ok, nonzero for disallowed. Issue error and
15768    warning messages under control of COMPLAIN.  */
15769
15770 static int
15771 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
15772 {
15773   if (INTEGRAL_TYPE_P (type))
15774     return 0;
15775   else if (POINTER_TYPE_P (type))
15776     return 0;
15777   else if (TYPE_PTR_TO_MEMBER_P (type))
15778     return 0;
15779   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
15780     return 0;
15781   else if (TREE_CODE (type) == TYPENAME_TYPE)
15782     return 0;
15783
15784   if (complain & tf_error)
15785     error ("%q#T is not a valid type for a template constant parameter", type);
15786   return 1;
15787 }
15788
15789 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
15790    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
15791
15792 static bool
15793 dependent_type_p_r (tree type)
15794 {
15795   tree scope;
15796
15797   /* [temp.dep.type]
15798
15799      A type is dependent if it is:
15800
15801      -- a template parameter. Template template parameters are types
15802         for us (since TYPE_P holds true for them) so we handle
15803         them here.  */
15804   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
15805       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
15806     return true;
15807   /* -- a qualified-id with a nested-name-specifier which contains a
15808         class-name that names a dependent type or whose unqualified-id
15809         names a dependent type.  */
15810   if (TREE_CODE (type) == TYPENAME_TYPE)
15811     return true;
15812   /* -- a cv-qualified type where the cv-unqualified type is
15813         dependent.  */
15814   type = TYPE_MAIN_VARIANT (type);
15815   /* -- a compound type constructed from any dependent type.  */
15816   if (TYPE_PTR_TO_MEMBER_P (type))
15817     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
15818             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
15819                                            (type)));
15820   else if (TREE_CODE (type) == POINTER_TYPE
15821            || TREE_CODE (type) == REFERENCE_TYPE)
15822     return dependent_type_p (TREE_TYPE (type));
15823   else if (TREE_CODE (type) == FUNCTION_TYPE
15824            || TREE_CODE (type) == METHOD_TYPE)
15825     {
15826       tree arg_type;
15827
15828       if (dependent_type_p (TREE_TYPE (type)))
15829         return true;
15830       for (arg_type = TYPE_ARG_TYPES (type);
15831            arg_type;
15832            arg_type = TREE_CHAIN (arg_type))
15833         if (dependent_type_p (TREE_VALUE (arg_type)))
15834           return true;
15835       return false;
15836     }
15837   /* -- an array type constructed from any dependent type or whose
15838         size is specified by a constant expression that is
15839         value-dependent.  */
15840   if (TREE_CODE (type) == ARRAY_TYPE)
15841     {
15842       if (TYPE_DOMAIN (type)
15843           && dependent_type_p (TYPE_DOMAIN (type)))
15844         return true;
15845       return dependent_type_p (TREE_TYPE (type));
15846     }
15847   else if (TREE_CODE (type) == INTEGER_TYPE
15848            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
15849     {
15850       /* If this is the TYPE_DOMAIN of an array type, consider it
15851          dependent.  */
15852       return (value_dependent_expression_p (TYPE_MAX_VALUE (type))
15853               || type_dependent_expression_p (TYPE_MAX_VALUE (type)));
15854     }
15855
15856   /* -- a template-id in which either the template name is a template
15857      parameter ...  */
15858   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
15859     return true;
15860   /* ... or any of the template arguments is a dependent type or
15861         an expression that is type-dependent or value-dependent.  */
15862   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
15863            && (any_dependent_template_arguments_p
15864                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
15865     return true;
15866
15867   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
15868      argument of the `typeof' expression is not type-dependent, then
15869      it should already been have resolved.  */
15870   if (TREE_CODE (type) == TYPEOF_TYPE
15871       || TREE_CODE (type) == DECLTYPE_TYPE)
15872     return true;
15873
15874   /* A template argument pack is dependent if any of its packed
15875      arguments are.  */
15876   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
15877     {
15878       tree args = ARGUMENT_PACK_ARGS (type);
15879       int i, len = TREE_VEC_LENGTH (args);
15880       for (i = 0; i < len; ++i)
15881         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
15882           return true;
15883     }
15884
15885   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
15886      be template parameters.  */
15887   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
15888     return true;
15889
15890   /* The standard does not specifically mention types that are local
15891      to template functions or local classes, but they should be
15892      considered dependent too.  For example:
15893
15894        template <int I> void f() {
15895          enum E { a = I };
15896          S<sizeof (E)> s;
15897        }
15898
15899      The size of `E' cannot be known until the value of `I' has been
15900      determined.  Therefore, `E' must be considered dependent.  */
15901   scope = TYPE_CONTEXT (type);
15902   if (scope && TYPE_P (scope))
15903     return dependent_type_p (scope);
15904   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
15905     return type_dependent_expression_p (scope);
15906
15907   /* Other types are non-dependent.  */
15908   return false;
15909 }
15910
15911 /* Returns TRUE if TYPE is dependent, in the sense of
15912    [temp.dep.type].  */
15913
15914 bool
15915 dependent_type_p (tree type)
15916 {
15917   /* If there are no template parameters in scope, then there can't be
15918      any dependent types.  */
15919   if (!processing_template_decl)
15920     {
15921       /* If we are not processing a template, then nobody should be
15922          providing us with a dependent type.  */
15923       gcc_assert (type);
15924       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
15925       return false;
15926     }
15927
15928   /* If the type is NULL, we have not computed a type for the entity
15929      in question; in that case, the type is dependent.  */
15930   if (!type)
15931     return true;
15932
15933   /* Erroneous types can be considered non-dependent.  */
15934   if (type == error_mark_node)
15935     return false;
15936
15937   /* If we have not already computed the appropriate value for TYPE,
15938      do so now.  */
15939   if (!TYPE_DEPENDENT_P_VALID (type))
15940     {
15941       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
15942       TYPE_DEPENDENT_P_VALID (type) = 1;
15943     }
15944
15945   return TYPE_DEPENDENT_P (type);
15946 }
15947
15948 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
15949
15950 static bool
15951 dependent_scope_ref_p (tree expression, bool criterion (tree))
15952 {
15953   tree scope;
15954   tree name;
15955
15956   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
15957
15958   if (!TYPE_P (TREE_OPERAND (expression, 0)))
15959     return true;
15960
15961   scope = TREE_OPERAND (expression, 0);
15962   name = TREE_OPERAND (expression, 1);
15963
15964   /* [temp.dep.expr]
15965
15966      An id-expression is type-dependent if it contains a
15967      nested-name-specifier that contains a class-name that names a
15968      dependent type.  */
15969   /* The suggested resolution to Core Issue 2 implies that if the
15970      qualifying type is the current class, then we must peek
15971      inside it.  */
15972   if (DECL_P (name)
15973       && currently_open_class (scope)
15974       && !criterion (name))
15975     return false;
15976   if (dependent_type_p (scope))
15977     return true;
15978
15979   return false;
15980 }
15981
15982 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
15983    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
15984    expression.  */
15985
15986 bool
15987 value_dependent_expression_p (tree expression)
15988 {
15989   if (!processing_template_decl)
15990     return false;
15991
15992   /* A name declared with a dependent type.  */
15993   if (DECL_P (expression) && type_dependent_expression_p (expression))
15994     return true;
15995
15996   switch (TREE_CODE (expression))
15997     {
15998     case IDENTIFIER_NODE:
15999       /* A name that has not been looked up -- must be dependent.  */
16000       return true;
16001
16002     case TEMPLATE_PARM_INDEX:
16003       /* A non-type template parm.  */
16004       return true;
16005
16006     case CONST_DECL:
16007       /* A non-type template parm.  */
16008       if (DECL_TEMPLATE_PARM_P (expression))
16009         return true;
16010       return value_dependent_expression_p (DECL_INITIAL (expression));
16011
16012     case VAR_DECL:
16013        /* A constant with integral or enumeration type and is initialized
16014           with an expression that is value-dependent.  */
16015       if (DECL_INITIAL (expression)
16016           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
16017           && value_dependent_expression_p (DECL_INITIAL (expression)))
16018         return true;
16019       return false;
16020
16021     case DYNAMIC_CAST_EXPR:
16022     case STATIC_CAST_EXPR:
16023     case CONST_CAST_EXPR:
16024     case REINTERPRET_CAST_EXPR:
16025     case CAST_EXPR:
16026       /* These expressions are value-dependent if the type to which
16027          the cast occurs is dependent or the expression being casted
16028          is value-dependent.  */
16029       {
16030         tree type = TREE_TYPE (expression);
16031
16032         if (dependent_type_p (type))
16033           return true;
16034
16035         /* A functional cast has a list of operands.  */
16036         expression = TREE_OPERAND (expression, 0);
16037         if (!expression)
16038           {
16039             /* If there are no operands, it must be an expression such
16040                as "int()". This should not happen for aggregate types
16041                because it would form non-constant expressions.  */
16042             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
16043
16044             return false;
16045           }
16046
16047         if (TREE_CODE (expression) == TREE_LIST)
16048           return any_value_dependent_elements_p (expression);
16049
16050         return value_dependent_expression_p (expression);
16051       }
16052
16053     case SIZEOF_EXPR:
16054     case ALIGNOF_EXPR:
16055       /* A `sizeof' expression is value-dependent if the operand is
16056          type-dependent or is a pack expansion.  */
16057       expression = TREE_OPERAND (expression, 0);
16058       if (PACK_EXPANSION_P (expression))
16059         return true;
16060       else if (TYPE_P (expression))
16061         return dependent_type_p (expression);
16062       return type_dependent_expression_p (expression);
16063
16064     case SCOPE_REF:
16065       return dependent_scope_ref_p (expression, value_dependent_expression_p);
16066
16067     case COMPONENT_REF:
16068       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
16069               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
16070
16071     case CALL_EXPR:
16072       /* A CALL_EXPR may appear in a constant expression if it is a
16073          call to a builtin function, e.g., __builtin_constant_p.  All
16074          such calls are value-dependent.  */
16075       return true;
16076
16077     case NONTYPE_ARGUMENT_PACK:
16078       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
16079          is value-dependent.  */
16080       {
16081         tree values = ARGUMENT_PACK_ARGS (expression);
16082         int i, len = TREE_VEC_LENGTH (values);
16083         
16084         for (i = 0; i < len; ++i)
16085           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
16086             return true;
16087         
16088         return false;
16089       }
16090
16091     case TRAIT_EXPR:
16092       {
16093         tree type2 = TRAIT_EXPR_TYPE2 (expression);
16094         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
16095                 || (type2 ? dependent_type_p (type2) : false));
16096       }
16097
16098     case MODOP_EXPR:
16099       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
16100               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
16101
16102     default:
16103       /* A constant expression is value-dependent if any subexpression is
16104          value-dependent.  */
16105       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
16106         {
16107         case tcc_reference:
16108         case tcc_unary:
16109           return (value_dependent_expression_p
16110                   (TREE_OPERAND (expression, 0)));
16111
16112         case tcc_comparison:
16113         case tcc_binary:
16114           return ((value_dependent_expression_p
16115                    (TREE_OPERAND (expression, 0)))
16116                   || (value_dependent_expression_p
16117                       (TREE_OPERAND (expression, 1))));
16118
16119         case tcc_expression:
16120         case tcc_vl_exp:
16121           {
16122             int i;
16123             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
16124               /* In some cases, some of the operands may be missing.
16125                  (For example, in the case of PREDECREMENT_EXPR, the
16126                  amount to increment by may be missing.)  That doesn't
16127                  make the expression dependent.  */
16128               if (TREE_OPERAND (expression, i)
16129                   && (value_dependent_expression_p
16130                       (TREE_OPERAND (expression, i))))
16131                 return true;
16132             return false;
16133           }
16134
16135         default:
16136           break;
16137         }
16138     }
16139
16140   /* The expression is not value-dependent.  */
16141   return false;
16142 }
16143
16144 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
16145    [temp.dep.expr].  */
16146
16147 bool
16148 type_dependent_expression_p (tree expression)
16149 {
16150   if (!processing_template_decl)
16151     return false;
16152
16153   if (expression == error_mark_node)
16154     return false;
16155
16156   /* An unresolved name is always dependent.  */
16157   if (TREE_CODE (expression) == IDENTIFIER_NODE
16158       || TREE_CODE (expression) == USING_DECL)
16159     return true;
16160
16161   /* Some expression forms are never type-dependent.  */
16162   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
16163       || TREE_CODE (expression) == SIZEOF_EXPR
16164       || TREE_CODE (expression) == ALIGNOF_EXPR
16165       || TREE_CODE (expression) == TRAIT_EXPR
16166       || TREE_CODE (expression) == TYPEID_EXPR
16167       || TREE_CODE (expression) == DELETE_EXPR
16168       || TREE_CODE (expression) == VEC_DELETE_EXPR
16169       || TREE_CODE (expression) == THROW_EXPR)
16170     return false;
16171
16172   /* The types of these expressions depends only on the type to which
16173      the cast occurs.  */
16174   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
16175       || TREE_CODE (expression) == STATIC_CAST_EXPR
16176       || TREE_CODE (expression) == CONST_CAST_EXPR
16177       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
16178       || TREE_CODE (expression) == CAST_EXPR)
16179     return dependent_type_p (TREE_TYPE (expression));
16180
16181   /* The types of these expressions depends only on the type created
16182      by the expression.  */
16183   if (TREE_CODE (expression) == NEW_EXPR
16184       || TREE_CODE (expression) == VEC_NEW_EXPR)
16185     {
16186       /* For NEW_EXPR tree nodes created inside a template, either
16187          the object type itself or a TREE_LIST may appear as the
16188          operand 1.  */
16189       tree type = TREE_OPERAND (expression, 1);
16190       if (TREE_CODE (type) == TREE_LIST)
16191         /* This is an array type.  We need to check array dimensions
16192            as well.  */
16193         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
16194                || value_dependent_expression_p
16195                     (TREE_OPERAND (TREE_VALUE (type), 1));
16196       else
16197         return dependent_type_p (type);
16198     }
16199
16200   if (TREE_CODE (expression) == SCOPE_REF
16201       && dependent_scope_ref_p (expression,
16202                                 type_dependent_expression_p))
16203     return true;
16204
16205   if (TREE_CODE (expression) == FUNCTION_DECL
16206       && DECL_LANG_SPECIFIC (expression)
16207       && DECL_TEMPLATE_INFO (expression)
16208       && (any_dependent_template_arguments_p
16209           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
16210     return true;
16211
16212   if (TREE_CODE (expression) == TEMPLATE_DECL
16213       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
16214     return false;
16215
16216   if (TREE_CODE (expression) == STMT_EXPR)
16217     expression = stmt_expr_value_expr (expression);
16218
16219   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
16220     {
16221       tree elt;
16222       unsigned i;
16223
16224       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
16225         {
16226           if (type_dependent_expression_p (elt))
16227             return true;
16228         }
16229       return false;
16230     }
16231
16232   if (TREE_TYPE (expression) == unknown_type_node)
16233     {
16234       if (TREE_CODE (expression) == ADDR_EXPR)
16235         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
16236       if (TREE_CODE (expression) == COMPONENT_REF
16237           || TREE_CODE (expression) == OFFSET_REF)
16238         {
16239           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
16240             return true;
16241           expression = TREE_OPERAND (expression, 1);
16242           if (TREE_CODE (expression) == IDENTIFIER_NODE)
16243             return false;
16244         }
16245       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
16246       if (TREE_CODE (expression) == SCOPE_REF)
16247         return false;
16248
16249       if (TREE_CODE (expression) == BASELINK)
16250         expression = BASELINK_FUNCTIONS (expression);
16251
16252       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
16253         {
16254           if (any_dependent_template_arguments_p
16255               (TREE_OPERAND (expression, 1)))
16256             return true;
16257           expression = TREE_OPERAND (expression, 0);
16258         }
16259       gcc_assert (TREE_CODE (expression) == OVERLOAD
16260                   || TREE_CODE (expression) == FUNCTION_DECL);
16261
16262       while (expression)
16263         {
16264           if (type_dependent_expression_p (OVL_CURRENT (expression)))
16265             return true;
16266           expression = OVL_NEXT (expression);
16267         }
16268       return false;
16269     }
16270
16271   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
16272
16273   return (dependent_type_p (TREE_TYPE (expression)));
16274 }
16275
16276 /* Returns TRUE if ARGS (a TREE_LIST of arguments to a function call)
16277    contains a type-dependent expression.  */
16278
16279 bool
16280 any_type_dependent_arguments_p (const_tree args)
16281 {
16282   while (args)
16283     {
16284       tree arg = TREE_VALUE (args);
16285
16286       if (type_dependent_expression_p (arg))
16287         return true;
16288       args = TREE_CHAIN (args);
16289     }
16290   return false;
16291 }
16292
16293 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
16294    expressions) contains any value-dependent expressions.  */
16295
16296 bool
16297 any_value_dependent_elements_p (const_tree list)
16298 {
16299   for (; list; list = TREE_CHAIN (list))
16300     if (value_dependent_expression_p (TREE_VALUE (list)))
16301       return true;
16302
16303   return false;
16304 }
16305
16306 /* Returns TRUE if the ARG (a template argument) is dependent.  */
16307
16308 bool
16309 dependent_template_arg_p (tree arg)
16310 {
16311   if (!processing_template_decl)
16312     return false;
16313
16314   if (TREE_CODE (arg) == TEMPLATE_DECL
16315       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16316     return dependent_template_p (arg);
16317   else if (ARGUMENT_PACK_P (arg))
16318     {
16319       tree args = ARGUMENT_PACK_ARGS (arg);
16320       int i, len = TREE_VEC_LENGTH (args);
16321       for (i = 0; i < len; ++i)
16322         {
16323           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16324             return true;
16325         }
16326
16327       return false;
16328     }
16329   else if (TYPE_P (arg))
16330     return dependent_type_p (arg);
16331   else
16332     return (type_dependent_expression_p (arg)
16333             || value_dependent_expression_p (arg));
16334 }
16335
16336 /* Returns true if ARGS (a collection of template arguments) contains
16337    any types that require structural equality testing.  */
16338
16339 bool
16340 any_template_arguments_need_structural_equality_p (tree args)
16341 {
16342   int i;
16343   int j;
16344
16345   if (!args)
16346     return false;
16347   if (args == error_mark_node)
16348     return true;
16349
16350   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16351     {
16352       tree level = TMPL_ARGS_LEVEL (args, i + 1);
16353       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16354         {
16355           tree arg = TREE_VEC_ELT (level, j);
16356           tree packed_args = NULL_TREE;
16357           int k, len = 1;
16358
16359           if (ARGUMENT_PACK_P (arg))
16360             {
16361               /* Look inside the argument pack.  */
16362               packed_args = ARGUMENT_PACK_ARGS (arg);
16363               len = TREE_VEC_LENGTH (packed_args);
16364             }
16365
16366           for (k = 0; k < len; ++k)
16367             {
16368               if (packed_args)
16369                 arg = TREE_VEC_ELT (packed_args, k);
16370
16371               if (error_operand_p (arg))
16372                 return true;
16373               else if (TREE_CODE (arg) == TEMPLATE_DECL
16374                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16375                 continue;
16376               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
16377                 return true;
16378               else if (!TYPE_P (arg) && TREE_TYPE (arg)
16379                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
16380                 return true;
16381             }
16382         }
16383     }
16384
16385   return false;
16386 }
16387
16388 /* Returns true if ARGS (a collection of template arguments) contains
16389    any dependent arguments.  */
16390
16391 bool
16392 any_dependent_template_arguments_p (const_tree args)
16393 {
16394   int i;
16395   int j;
16396
16397   if (!args)
16398     return false;
16399   if (args == error_mark_node)
16400     return true;
16401
16402   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16403     {
16404       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
16405       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16406         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
16407           return true;
16408     }
16409
16410   return false;
16411 }
16412
16413 /* Returns TRUE if the template TMPL is dependent.  */
16414
16415 bool
16416 dependent_template_p (tree tmpl)
16417 {
16418   if (TREE_CODE (tmpl) == OVERLOAD)
16419     {
16420       while (tmpl)
16421         {
16422           if (dependent_template_p (OVL_FUNCTION (tmpl)))
16423             return true;
16424           tmpl = OVL_CHAIN (tmpl);
16425         }
16426       return false;
16427     }
16428
16429   /* Template template parameters are dependent.  */
16430   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
16431       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16432     return true;
16433   /* So are names that have not been looked up.  */
16434   if (TREE_CODE (tmpl) == SCOPE_REF
16435       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
16436     return true;
16437   /* So are member templates of dependent classes.  */
16438   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
16439     return dependent_type_p (DECL_CONTEXT (tmpl));
16440   return false;
16441 }
16442
16443 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
16444
16445 bool
16446 dependent_template_id_p (tree tmpl, tree args)
16447 {
16448   return (dependent_template_p (tmpl)
16449           || any_dependent_template_arguments_p (args));
16450 }
16451
16452 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
16453    is dependent.  */
16454
16455 bool
16456 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
16457 {
16458   int i;
16459
16460   if (!processing_template_decl)
16461     return false;
16462
16463   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
16464     {
16465       tree decl = TREE_VEC_ELT (declv, i);
16466       tree init = TREE_VEC_ELT (initv, i);
16467       tree cond = TREE_VEC_ELT (condv, i);
16468       tree incr = TREE_VEC_ELT (incrv, i);
16469
16470       if (type_dependent_expression_p (decl))
16471         return true;
16472
16473       if (init && type_dependent_expression_p (init))
16474         return true;
16475
16476       if (type_dependent_expression_p (cond))
16477         return true;
16478
16479       if (COMPARISON_CLASS_P (cond)
16480           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
16481               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
16482         return true;
16483
16484       if (TREE_CODE (incr) == MODOP_EXPR)
16485         {
16486           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
16487               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
16488             return true;
16489         }
16490       else if (type_dependent_expression_p (incr))
16491         return true;
16492       else if (TREE_CODE (incr) == MODIFY_EXPR)
16493         {
16494           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
16495             return true;
16496           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
16497             {
16498               tree t = TREE_OPERAND (incr, 1);
16499               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
16500                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
16501                 return true;
16502             }
16503         }
16504     }
16505
16506   return false;
16507 }
16508
16509 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
16510    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
16511    no such TYPE can be found.  Note that this function peers inside
16512    uninstantiated templates and therefore should be used only in
16513    extremely limited situations.  ONLY_CURRENT_P restricts this
16514    peering to the currently open classes hierarchy (which is required
16515    when comparing types).  */
16516
16517 tree
16518 resolve_typename_type (tree type, bool only_current_p)
16519 {
16520   tree scope;
16521   tree name;
16522   tree decl;
16523   int quals;
16524   tree pushed_scope;
16525   tree result;
16526
16527   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
16528
16529   scope = TYPE_CONTEXT (type);
16530   name = TYPE_IDENTIFIER (type);
16531
16532   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
16533      it first before we can figure out what NAME refers to.  */
16534   if (TREE_CODE (scope) == TYPENAME_TYPE)
16535     scope = resolve_typename_type (scope, only_current_p);
16536   /* If we don't know what SCOPE refers to, then we cannot resolve the
16537      TYPENAME_TYPE.  */
16538   if (TREE_CODE (scope) == TYPENAME_TYPE)
16539     return type;
16540   /* If the SCOPE is a template type parameter, we have no way of
16541      resolving the name.  */
16542   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
16543     return type;
16544   /* If the SCOPE is not the current instantiation, there's no reason
16545      to look inside it.  */
16546   if (only_current_p && !currently_open_class (scope))
16547     return type;
16548   /* If SCOPE isn't the template itself, it will not have a valid
16549      TYPE_FIELDS list.  */
16550   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
16551     /* scope is either the template itself or a compatible instantiation
16552        like X<T>, so look up the name in the original template.  */
16553     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
16554   else
16555     /* scope is a partial instantiation, so we can't do the lookup or we
16556        will lose the template arguments.  */
16557     return type;
16558   /* Enter the SCOPE so that name lookup will be resolved as if we
16559      were in the class definition.  In particular, SCOPE will no
16560      longer be considered a dependent type.  */
16561   pushed_scope = push_scope (scope);
16562   /* Look up the declaration.  */
16563   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
16564
16565   result = NULL_TREE;
16566   
16567   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
16568      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
16569   if (!decl)
16570     /*nop*/;
16571   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
16572            && TREE_CODE (decl) == TYPE_DECL)
16573     {
16574       result = TREE_TYPE (decl);
16575       if (result == error_mark_node)
16576         result = NULL_TREE;
16577     }
16578   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
16579            && DECL_CLASS_TEMPLATE_P (decl))
16580     {
16581       tree tmpl;
16582       tree args;
16583       /* Obtain the template and the arguments.  */
16584       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
16585       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
16586       /* Instantiate the template.  */
16587       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
16588                                       /*entering_scope=*/0,
16589                                       tf_error | tf_user);
16590       if (result == error_mark_node)
16591         result = NULL_TREE;
16592     }
16593   
16594   /* Leave the SCOPE.  */
16595   if (pushed_scope)
16596     pop_scope (pushed_scope);
16597
16598   /* If we failed to resolve it, return the original typename.  */
16599   if (!result)
16600     return type;
16601   
16602   /* If lookup found a typename type, resolve that too.  */
16603   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
16604     {
16605       /* Ill-formed programs can cause infinite recursion here, so we
16606          must catch that.  */
16607       TYPENAME_IS_RESOLVING_P (type) = 1;
16608       result = resolve_typename_type (result, only_current_p);
16609       TYPENAME_IS_RESOLVING_P (type) = 0;
16610     }
16611   
16612   /* Qualify the resulting type.  */
16613   quals = cp_type_quals (type);
16614   if (quals)
16615     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
16616
16617   return result;
16618 }
16619
16620 /* EXPR is an expression which is not type-dependent.  Return a proxy
16621    for EXPR that can be used to compute the types of larger
16622    expressions containing EXPR.  */
16623
16624 tree
16625 build_non_dependent_expr (tree expr)
16626 {
16627   tree inner_expr;
16628
16629   /* Preserve null pointer constants so that the type of things like
16630      "p == 0" where "p" is a pointer can be determined.  */
16631   if (null_ptr_cst_p (expr))
16632     return expr;
16633   /* Preserve OVERLOADs; the functions must be available to resolve
16634      types.  */
16635   inner_expr = expr;
16636   if (TREE_CODE (inner_expr) == STMT_EXPR)
16637     inner_expr = stmt_expr_value_expr (inner_expr);
16638   if (TREE_CODE (inner_expr) == ADDR_EXPR)
16639     inner_expr = TREE_OPERAND (inner_expr, 0);
16640   if (TREE_CODE (inner_expr) == COMPONENT_REF)
16641     inner_expr = TREE_OPERAND (inner_expr, 1);
16642   if (is_overloaded_fn (inner_expr)
16643       || TREE_CODE (inner_expr) == OFFSET_REF)
16644     return expr;
16645   /* There is no need to return a proxy for a variable.  */
16646   if (TREE_CODE (expr) == VAR_DECL)
16647     return expr;
16648   /* Preserve string constants; conversions from string constants to
16649      "char *" are allowed, even though normally a "const char *"
16650      cannot be used to initialize a "char *".  */
16651   if (TREE_CODE (expr) == STRING_CST)
16652     return expr;
16653   /* Preserve arithmetic constants, as an optimization -- there is no
16654      reason to create a new node.  */
16655   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
16656     return expr;
16657   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
16658      There is at least one place where we want to know that a
16659      particular expression is a throw-expression: when checking a ?:
16660      expression, there are special rules if the second or third
16661      argument is a throw-expression.  */
16662   if (TREE_CODE (expr) == THROW_EXPR)
16663     return expr;
16664
16665   if (TREE_CODE (expr) == COND_EXPR)
16666     return build3 (COND_EXPR,
16667                    TREE_TYPE (expr),
16668                    TREE_OPERAND (expr, 0),
16669                    (TREE_OPERAND (expr, 1)
16670                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
16671                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
16672                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
16673   if (TREE_CODE (expr) == COMPOUND_EXPR
16674       && !COMPOUND_EXPR_OVERLOADED (expr))
16675     return build2 (COMPOUND_EXPR,
16676                    TREE_TYPE (expr),
16677                    TREE_OPERAND (expr, 0),
16678                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
16679
16680   /* If the type is unknown, it can't really be non-dependent */
16681   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
16682
16683   /* Otherwise, build a NON_DEPENDENT_EXPR.
16684
16685      REFERENCE_TYPEs are not stripped for expressions in templates
16686      because doing so would play havoc with mangling.  Consider, for
16687      example:
16688
16689        template <typename T> void f<T& g>() { g(); }
16690
16691      In the body of "f", the expression for "g" will have
16692      REFERENCE_TYPE, even though the standard says that it should
16693      not.  The reason is that we must preserve the syntactic form of
16694      the expression so that mangling (say) "f<g>" inside the body of
16695      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
16696      stripped here.  */
16697   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
16698 }
16699
16700 /* ARGS is a TREE_LIST of expressions as arguments to a function call.
16701    Return a new TREE_LIST with the various arguments replaced with
16702    equivalent non-dependent expressions.  */
16703
16704 tree
16705 build_non_dependent_args (tree args)
16706 {
16707   tree a;
16708   tree new_args;
16709
16710   new_args = NULL_TREE;
16711   for (a = args; a; a = TREE_CHAIN (a))
16712     new_args = tree_cons (NULL_TREE,
16713                           build_non_dependent_expr (TREE_VALUE (a)),
16714                           new_args);
16715   return nreverse (new_args);
16716 }
16717
16718 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
16719    with a level one deeper than the actual template parms.  */
16720
16721 tree
16722 make_auto (void)
16723 {
16724   tree au;
16725
16726   /* ??? Is it worth caching this for multiple autos at the same level?  */
16727   au = cxx_make_type (TEMPLATE_TYPE_PARM);
16728   TYPE_NAME (au) = build_decl (TYPE_DECL, get_identifier ("auto"), au);
16729   TYPE_STUB_DECL (au) = TYPE_NAME (au);
16730   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
16731     (0, processing_template_decl + 1, processing_template_decl + 1,
16732      TYPE_NAME (au), NULL_TREE);
16733   TYPE_CANONICAL (au) = canonical_type_parameter (au);
16734   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
16735   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
16736
16737   return au;
16738 }
16739
16740 /* Replace auto in TYPE with std::initializer_list<auto>.  */
16741
16742 static tree
16743 listify_autos (tree type, tree auto_node)
16744 {
16745   tree std_init_list = namespace_binding
16746     (get_identifier ("initializer_list"), std_node);
16747   tree argvec;
16748   tree init_auto;
16749   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
16750     {    
16751       error ("deducing auto from brace-enclosed initializer list requires "
16752              "#include <initializer_list>");
16753       return error_mark_node;
16754     }
16755   argvec = make_tree_vec (1);
16756   TREE_VEC_ELT (argvec, 0) = auto_node;
16757   init_auto = lookup_template_class (std_init_list, argvec, NULL_TREE,
16758                                      NULL_TREE, 0, tf_warning_or_error);
16759
16760   TREE_VEC_ELT (argvec, 0) = init_auto;
16761   if (processing_template_decl)
16762     argvec = add_to_template_args (current_template_args (), argvec);
16763   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
16764 }
16765
16766 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
16767    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
16768
16769 tree
16770 do_auto_deduction (tree type, tree init, tree auto_node)
16771 {
16772   tree parms, args, tparms, targs;
16773   int val;
16774
16775   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
16776      with either a new invented type template parameter U or, if the
16777      initializer is a braced-init-list (8.5.4), with
16778      std::initializer_list<U>.  */
16779   if (BRACE_ENCLOSED_INITIALIZER_P (init))
16780     type = listify_autos (type, auto_node);
16781
16782   parms = build_tree_list (NULL_TREE, type);
16783   args = build_tree_list (NULL_TREE, init);
16784   tparms = make_tree_vec (1);
16785   targs = make_tree_vec (1);
16786   TREE_VEC_ELT (tparms, 0)
16787     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
16788   val = type_unification_real (tparms, targs, parms, args, 0,
16789                                DEDUCE_CALL, LOOKUP_NORMAL);
16790   if (val > 0)
16791     {
16792       error ("unable to deduce %qT from %qE", type, init);
16793       return error_mark_node;
16794     }
16795
16796   if (processing_template_decl)
16797     targs = add_to_template_args (current_template_args (), targs);
16798   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
16799 }
16800
16801 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
16802    result.  */
16803
16804 tree
16805 splice_late_return_type (tree type, tree late_return_type)
16806 {
16807   tree argvec;
16808
16809   if (late_return_type == NULL_TREE)
16810     return type;
16811   argvec = make_tree_vec (1);
16812   TREE_VEC_ELT (argvec, 0) = late_return_type;
16813   if (processing_template_decl)
16814     argvec = add_to_template_args (current_template_args (), argvec);
16815   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
16816 }
16817
16818 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
16819
16820 bool
16821 is_auto (const_tree type)
16822 {
16823   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16824       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
16825     return true;
16826   else
16827     return false;
16828 }
16829
16830 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
16831    appear as a type-specifier for the declaration in question, we don't
16832    have to look through the whole type.  */
16833
16834 tree
16835 type_uses_auto (tree type)
16836 {
16837   enum tree_code code;
16838   if (is_auto (type))
16839     return type;
16840
16841   code = TREE_CODE (type);
16842
16843   if (code == POINTER_TYPE || code == REFERENCE_TYPE
16844       || code == OFFSET_TYPE || code == FUNCTION_TYPE
16845       || code == METHOD_TYPE || code == ARRAY_TYPE)
16846     return type_uses_auto (TREE_TYPE (type));
16847
16848   if (TYPE_PTRMEMFUNC_P (type))
16849     return type_uses_auto (TREE_TYPE (TREE_TYPE
16850                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
16851
16852   return NULL_TREE;
16853 }
16854
16855 #include "gt-cp-pt.h"