OSDN Git Service

PR c++/38380
[pf3gnuchains/gcc-fork.git] / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU C++.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2007, 2008  Free Software Foundation, Inc.
4    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
5    Rewritten by Jason Merrill (jason@cygnus.com).
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 /* Known bugs or deficiencies include:
24
25      all methods must be provided in header files; can't use a source
26      file that contains only the method templates and "just win".  */
27
28 #include "config.h"
29 #include "system.h"
30 #include "coretypes.h"
31 #include "tm.h"
32 #include "obstack.h"
33 #include "tree.h"
34 #include "pointer-set.h"
35 #include "flags.h"
36 #include "c-common.h"
37 #include "cp-tree.h"
38 #include "cp-objcp-common.h"
39 #include "tree-inline.h"
40 #include "decl.h"
41 #include "output.h"
42 #include "except.h"
43 #include "toplev.h"
44 #include "rtl.h"
45 #include "timevar.h"
46 #include "tree-iterator.h"
47 #include "vecprim.h"
48
49 /* The type of functions taking a tree, and some additional data, and
50    returning an int.  */
51 typedef int (*tree_fn_t) (tree, void*);
52
53 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
54    instantiations have been deferred, either because their definitions
55    were not yet available, or because we were putting off doing the work.  */
56 struct pending_template GTY (()) {
57   struct pending_template *next;
58   struct tinst_level *tinst;
59 };
60
61 static GTY(()) struct pending_template *pending_templates;
62 static GTY(()) struct pending_template *last_pending_template;
63
64 int processing_template_parmlist;
65 static int template_header_count;
66
67 static GTY(()) tree saved_trees;
68 static VEC(int,heap) *inline_parm_levels;
69
70 static GTY(()) struct tinst_level *current_tinst_level;
71
72 static GTY(()) tree saved_access_scope;
73
74 /* Live only within one (recursive) call to tsubst_expr.  We use
75    this to pass the statement expression node from the STMT_EXPR
76    to the EXPR_STMT that is its result.  */
77 static tree cur_stmt_expr;
78
79 /* A map from local variable declarations in the body of the template
80    presently being instantiated to the corresponding instantiated
81    local variables.  */
82 static htab_t local_specializations;
83
84 /* Contains canonical template parameter types. The vector is indexed by
85    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
86    TREE_LIST, whose TREE_VALUEs contain the canonical template
87    parameters of various types and levels.  */
88 static GTY(()) VEC(tree,gc) *canonical_template_parms;
89
90 #define UNIFY_ALLOW_NONE 0
91 #define UNIFY_ALLOW_MORE_CV_QUAL 1
92 #define UNIFY_ALLOW_LESS_CV_QUAL 2
93 #define UNIFY_ALLOW_DERIVED 4
94 #define UNIFY_ALLOW_INTEGER 8
95 #define UNIFY_ALLOW_OUTER_LEVEL 16
96 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
97 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
98
99 static void push_access_scope (tree);
100 static void pop_access_scope (tree);
101 static bool resolve_overloaded_unification (tree, tree, tree, tree,
102                                             unification_kind_t, int);
103 static int try_one_overload (tree, tree, tree, tree, tree,
104                              unification_kind_t, int, bool);
105 static int unify (tree, tree, tree, tree, int);
106 static void add_pending_template (tree);
107 static int push_tinst_level (tree);
108 static void pop_tinst_level (void);
109 static tree reopen_tinst_level (struct tinst_level *);
110 static tree tsubst_initializer_list (tree, tree);
111 static tree get_class_bindings (tree, tree, tree);
112 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
113                                    bool, bool);
114 static void tsubst_enum (tree, tree, tree);
115 static tree add_to_template_args (tree, tree);
116 static tree add_outermost_template_args (tree, tree);
117 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
118 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
119                                              tree);
120 static int  type_unification_real (tree, tree, tree, tree,
121                                    int, unification_kind_t, int);
122 static void note_template_header (int);
123 static tree convert_nontype_argument_function (tree, tree);
124 static tree convert_nontype_argument (tree, tree);
125 static tree convert_template_argument (tree, tree, tree,
126                                        tsubst_flags_t, int, tree);
127 static int for_each_template_parm (tree, tree_fn_t, void*,
128                                    struct pointer_set_t*, bool);
129 static tree expand_template_argument_pack (tree);
130 static tree build_template_parm_index (int, int, int, tree, tree);
131 static bool inline_needs_template_parms (tree);
132 static void push_inline_template_parms_recursive (tree, int);
133 static tree retrieve_local_specialization (tree);
134 static void register_local_specialization (tree, tree);
135 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
136 static int mark_template_parm (tree, void *);
137 static int template_parm_this_level_p (tree, void *);
138 static tree tsubst_friend_function (tree, tree);
139 static tree tsubst_friend_class (tree, tree);
140 static int can_complete_type_without_circularity (tree);
141 static tree get_bindings (tree, tree, tree, bool);
142 static int template_decl_level (tree);
143 static int check_cv_quals_for_unify (int, tree, tree);
144 static void template_parm_level_and_index (tree, int*, int*);
145 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
146 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
147 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
148 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
149 static void regenerate_decl_from_template (tree, tree);
150 static tree most_specialized_class (tree, tree);
151 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
152 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
153 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
154 static bool check_specialization_scope (void);
155 static tree process_partial_specialization (tree);
156 static void set_current_access_from_decl (tree);
157 static tree get_template_base (tree, tree, tree, tree);
158 static tree try_class_unification (tree, tree, tree, tree);
159 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
160                                            tree, tree);
161 static bool template_template_parm_bindings_ok_p (tree, tree);
162 static int template_args_equal (tree, tree);
163 static void tsubst_default_arguments (tree);
164 static tree for_each_template_parm_r (tree *, int *, void *);
165 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
166 static void copy_default_args_to_explicit_spec (tree);
167 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
168 static int eq_local_specializations (const void *, const void *);
169 static bool dependent_template_arg_p (tree);
170 static bool any_template_arguments_need_structural_equality_p (tree);
171 static bool dependent_type_p_r (tree);
172 static tree tsubst (tree, tree, tsubst_flags_t, tree);
173 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
174 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
175 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
176
177 /* Make the current scope suitable for access checking when we are
178    processing T.  T can be FUNCTION_DECL for instantiated function
179    template, or VAR_DECL for static member variable (need by
180    instantiate_decl).  */
181
182 static void
183 push_access_scope (tree t)
184 {
185   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
186               || TREE_CODE (t) == VAR_DECL);
187
188   if (DECL_FRIEND_CONTEXT (t))
189     push_nested_class (DECL_FRIEND_CONTEXT (t));
190   else if (DECL_CLASS_SCOPE_P (t))
191     push_nested_class (DECL_CONTEXT (t));
192   else
193     push_to_top_level ();
194
195   if (TREE_CODE (t) == FUNCTION_DECL)
196     {
197       saved_access_scope = tree_cons
198         (NULL_TREE, current_function_decl, saved_access_scope);
199       current_function_decl = t;
200     }
201 }
202
203 /* Restore the scope set up by push_access_scope.  T is the node we
204    are processing.  */
205
206 static void
207 pop_access_scope (tree t)
208 {
209   if (TREE_CODE (t) == FUNCTION_DECL)
210     {
211       current_function_decl = TREE_VALUE (saved_access_scope);
212       saved_access_scope = TREE_CHAIN (saved_access_scope);
213     }
214
215   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
216     pop_nested_class ();
217   else
218     pop_from_top_level ();
219 }
220
221 /* Do any processing required when DECL (a member template
222    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
223    to DECL, unless it is a specialization, in which case the DECL
224    itself is returned.  */
225
226 tree
227 finish_member_template_decl (tree decl)
228 {
229   if (decl == error_mark_node)
230     return error_mark_node;
231
232   gcc_assert (DECL_P (decl));
233
234   if (TREE_CODE (decl) == TYPE_DECL)
235     {
236       tree type;
237
238       type = TREE_TYPE (decl);
239       if (type == error_mark_node)
240         return error_mark_node;
241       if (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 (!uses_template_parms (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, auto_node;
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   auto_node = type_uses_auto (TREE_TYPE (decl));
10334   if (auto_node && init)
10335     {
10336       tree init_expr = init;
10337       tree orig_type;
10338       if (TREE_CODE (init_expr) == DECL_EXPR)
10339         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
10340       orig_type = TREE_TYPE (init_expr);
10341       TREE_TYPE (init_expr) = RECUR (TREE_TYPE (init_expr));
10342       TREE_TYPE (decl)
10343         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
10344       TREE_TYPE (init_expr) = orig_type;
10345     }
10346   gcc_assert (!type_dependent_expression_p (decl));
10347
10348   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
10349     {
10350       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
10351       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10352       if (TREE_CODE (incr) == MODIFY_EXPR)
10353         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
10354                                     RECUR (TREE_OPERAND (incr, 1)),
10355                                     complain);
10356       else
10357         incr = RECUR (incr);
10358       TREE_VEC_ELT (declv, i) = decl;
10359       TREE_VEC_ELT (initv, i) = init;
10360       TREE_VEC_ELT (condv, i) = cond;
10361       TREE_VEC_ELT (incrv, i) = incr;
10362       return;
10363     }
10364
10365   if (init && TREE_CODE (init) != DECL_EXPR)
10366     {
10367       tree c;
10368       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
10369         {
10370           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
10371                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
10372               && OMP_CLAUSE_DECL (c) == decl)
10373             break;
10374           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
10375                    && OMP_CLAUSE_DECL (c) == decl)
10376             error ("iteration variable %qD should not be firstprivate", decl);
10377           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
10378                    && OMP_CLAUSE_DECL (c) == decl)
10379             error ("iteration variable %qD should not be reduction", decl);
10380         }
10381       if (c == NULL)
10382         {
10383           c = build_omp_clause (OMP_CLAUSE_PRIVATE);
10384           OMP_CLAUSE_DECL (c) = decl;
10385           c = finish_omp_clauses (c);
10386           if (c)
10387             {
10388               OMP_CLAUSE_CHAIN (c) = *clauses;
10389               *clauses = c;
10390             }
10391         }
10392     }
10393   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
10394   if (COMPARISON_CLASS_P (cond))
10395     cond = build2 (TREE_CODE (cond), boolean_type_node,
10396                    RECUR (TREE_OPERAND (cond, 0)),
10397                    RECUR (TREE_OPERAND (cond, 1)));
10398   else
10399     cond = RECUR (cond);
10400   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10401   switch (TREE_CODE (incr))
10402     {
10403     case PREINCREMENT_EXPR:
10404     case PREDECREMENT_EXPR:
10405     case POSTINCREMENT_EXPR:
10406     case POSTDECREMENT_EXPR:
10407       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
10408                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
10409       break;
10410     case MODIFY_EXPR:
10411       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10412           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10413         {
10414           tree rhs = TREE_OPERAND (incr, 1);
10415           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10416                          RECUR (TREE_OPERAND (incr, 0)),
10417                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10418                                  RECUR (TREE_OPERAND (rhs, 0)),
10419                                  RECUR (TREE_OPERAND (rhs, 1))));
10420         }
10421       else
10422         incr = RECUR (incr);
10423       break;
10424     case MODOP_EXPR:
10425       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10426           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10427         {
10428           tree lhs = RECUR (TREE_OPERAND (incr, 0));
10429           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
10430                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
10431                                  TREE_TYPE (decl), lhs,
10432                                  RECUR (TREE_OPERAND (incr, 2))));
10433         }
10434       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
10435                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
10436                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
10437         {
10438           tree rhs = TREE_OPERAND (incr, 2);
10439           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10440                          RECUR (TREE_OPERAND (incr, 0)),
10441                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10442                                  RECUR (TREE_OPERAND (rhs, 0)),
10443                                  RECUR (TREE_OPERAND (rhs, 1))));
10444         }
10445       else
10446         incr = RECUR (incr);
10447       break;
10448     default:
10449       incr = RECUR (incr);
10450       break;
10451     }
10452
10453   TREE_VEC_ELT (declv, i) = decl;
10454   TREE_VEC_ELT (initv, i) = init;
10455   TREE_VEC_ELT (condv, i) = cond;
10456   TREE_VEC_ELT (incrv, i) = incr;
10457 #undef RECUR
10458 }
10459
10460 /* Like tsubst_copy for expressions, etc. but also does semantic
10461    processing.  */
10462
10463 static tree
10464 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
10465              bool integral_constant_expression_p)
10466 {
10467 #define RECUR(NODE)                             \
10468   tsubst_expr ((NODE), args, complain, in_decl, \
10469                integral_constant_expression_p)
10470
10471   tree stmt, tmp;
10472
10473   if (t == NULL_TREE || t == error_mark_node)
10474     return t;
10475
10476   if (EXPR_HAS_LOCATION (t))
10477     input_location = EXPR_LOCATION (t);
10478   if (STATEMENT_CODE_P (TREE_CODE (t)))
10479     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
10480
10481   switch (TREE_CODE (t))
10482     {
10483     case STATEMENT_LIST:
10484       {
10485         tree_stmt_iterator i;
10486         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
10487           RECUR (tsi_stmt (i));
10488         break;
10489       }
10490
10491     case CTOR_INITIALIZER:
10492       finish_mem_initializers (tsubst_initializer_list
10493                                (TREE_OPERAND (t, 0), args));
10494       break;
10495
10496     case RETURN_EXPR:
10497       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
10498       break;
10499
10500     case EXPR_STMT:
10501       tmp = RECUR (EXPR_STMT_EXPR (t));
10502       if (EXPR_STMT_STMT_EXPR_RESULT (t))
10503         finish_stmt_expr_expr (tmp, cur_stmt_expr);
10504       else
10505         finish_expr_stmt (tmp);
10506       break;
10507
10508     case USING_STMT:
10509       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
10510       break;
10511
10512     case DECL_EXPR:
10513       {
10514         tree decl;
10515         tree init;
10516
10517         decl = DECL_EXPR_DECL (t);
10518         if (TREE_CODE (decl) == LABEL_DECL)
10519           finish_label_decl (DECL_NAME (decl));
10520         else if (TREE_CODE (decl) == USING_DECL)
10521           {
10522             tree scope = USING_DECL_SCOPE (decl);
10523             tree name = DECL_NAME (decl);
10524             tree decl;
10525
10526             scope = RECUR (scope);
10527             decl = lookup_qualified_name (scope, name,
10528                                           /*is_type_p=*/false,
10529                                           /*complain=*/false);
10530             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
10531               qualified_name_lookup_error (scope, name, decl, input_location);
10532             else
10533               do_local_using_decl (decl, scope, name);
10534           }
10535         else
10536           {
10537             init = DECL_INITIAL (decl);
10538             decl = tsubst (decl, args, complain, in_decl);
10539             if (decl != error_mark_node)
10540               {
10541                 /* By marking the declaration as instantiated, we avoid
10542                    trying to instantiate it.  Since instantiate_decl can't
10543                    handle local variables, and since we've already done
10544                    all that needs to be done, that's the right thing to
10545                    do.  */
10546                 if (TREE_CODE (decl) == VAR_DECL)
10547                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10548                 if (TREE_CODE (decl) == VAR_DECL
10549                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
10550                   /* Anonymous aggregates are a special case.  */
10551                   finish_anon_union (decl);
10552                 else
10553                   {
10554                     maybe_push_decl (decl);
10555                     if (TREE_CODE (decl) == VAR_DECL
10556                         && DECL_PRETTY_FUNCTION_P (decl))
10557                       {
10558                         /* For __PRETTY_FUNCTION__ we have to adjust the
10559                            initializer.  */
10560                         const char *const name
10561                           = cxx_printable_name (current_function_decl, 2);
10562                         init = cp_fname_init (name, &TREE_TYPE (decl));
10563                       }
10564                     else
10565                       {
10566                         tree t = RECUR (init);
10567
10568                         if (init && !t)
10569                           /* If we had an initializer but it
10570                              instantiated to nothing,
10571                              value-initialize the object.  This will
10572                              only occur when the initializer was a
10573                              pack expansion where the parameter packs
10574                              used in that expansion were of length
10575                              zero.  */
10576                           init = build_value_init (TREE_TYPE (decl));
10577                         else
10578                           init = t;
10579                       }
10580
10581                     finish_decl (decl, init, NULL_TREE);
10582                   }
10583               }
10584           }
10585
10586         /* A DECL_EXPR can also be used as an expression, in the condition
10587            clause of an if/for/while construct.  */
10588         return decl;
10589       }
10590
10591     case FOR_STMT:
10592       stmt = begin_for_stmt ();
10593                           RECUR (FOR_INIT_STMT (t));
10594       finish_for_init_stmt (stmt);
10595       tmp = RECUR (FOR_COND (t));
10596       finish_for_cond (tmp, stmt);
10597       tmp = RECUR (FOR_EXPR (t));
10598       finish_for_expr (tmp, stmt);
10599       RECUR (FOR_BODY (t));
10600       finish_for_stmt (stmt);
10601       break;
10602
10603     case WHILE_STMT:
10604       stmt = begin_while_stmt ();
10605       tmp = RECUR (WHILE_COND (t));
10606       finish_while_stmt_cond (tmp, stmt);
10607       RECUR (WHILE_BODY (t));
10608       finish_while_stmt (stmt);
10609       break;
10610
10611     case DO_STMT:
10612       stmt = begin_do_stmt ();
10613       RECUR (DO_BODY (t));
10614       finish_do_body (stmt);
10615       tmp = RECUR (DO_COND (t));
10616       finish_do_stmt (tmp, stmt);
10617       break;
10618
10619     case IF_STMT:
10620       stmt = begin_if_stmt ();
10621       tmp = RECUR (IF_COND (t));
10622       finish_if_stmt_cond (tmp, stmt);
10623       RECUR (THEN_CLAUSE (t));
10624       finish_then_clause (stmt);
10625
10626       if (ELSE_CLAUSE (t))
10627         {
10628           begin_else_clause (stmt);
10629           RECUR (ELSE_CLAUSE (t));
10630           finish_else_clause (stmt);
10631         }
10632
10633       finish_if_stmt (stmt);
10634       break;
10635
10636     case BIND_EXPR:
10637       if (BIND_EXPR_BODY_BLOCK (t))
10638         stmt = begin_function_body ();
10639       else
10640         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
10641                                     ? BCS_TRY_BLOCK : 0);
10642
10643       RECUR (BIND_EXPR_BODY (t));
10644
10645       if (BIND_EXPR_BODY_BLOCK (t))
10646         finish_function_body (stmt);
10647       else
10648         finish_compound_stmt (stmt);
10649       break;
10650
10651     case BREAK_STMT:
10652       finish_break_stmt ();
10653       break;
10654
10655     case CONTINUE_STMT:
10656       finish_continue_stmt ();
10657       break;
10658
10659     case SWITCH_STMT:
10660       stmt = begin_switch_stmt ();
10661       tmp = RECUR (SWITCH_STMT_COND (t));
10662       finish_switch_cond (tmp, stmt);
10663       RECUR (SWITCH_STMT_BODY (t));
10664       finish_switch_stmt (stmt);
10665       break;
10666
10667     case CASE_LABEL_EXPR:
10668       finish_case_label (RECUR (CASE_LOW (t)),
10669                          RECUR (CASE_HIGH (t)));
10670       break;
10671
10672     case LABEL_EXPR:
10673       finish_label_stmt (DECL_NAME (LABEL_EXPR_LABEL (t)));
10674       break;
10675
10676     case GOTO_EXPR:
10677       tmp = GOTO_DESTINATION (t);
10678       if (TREE_CODE (tmp) != LABEL_DECL)
10679         /* Computed goto's must be tsubst'd into.  On the other hand,
10680            non-computed gotos must not be; the identifier in question
10681            will have no binding.  */
10682         tmp = RECUR (tmp);
10683       else
10684         tmp = DECL_NAME (tmp);
10685       finish_goto_stmt (tmp);
10686       break;
10687
10688     case ASM_EXPR:
10689       tmp = finish_asm_stmt
10690         (ASM_VOLATILE_P (t),
10691          RECUR (ASM_STRING (t)),
10692          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
10693          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
10694          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
10695       {
10696         tree asm_expr = tmp;
10697         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
10698           asm_expr = TREE_OPERAND (asm_expr, 0);
10699         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
10700       }
10701       break;
10702
10703     case TRY_BLOCK:
10704       if (CLEANUP_P (t))
10705         {
10706           stmt = begin_try_block ();
10707           RECUR (TRY_STMTS (t));
10708           finish_cleanup_try_block (stmt);
10709           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
10710         }
10711       else
10712         {
10713           tree compound_stmt = NULL_TREE;
10714
10715           if (FN_TRY_BLOCK_P (t))
10716             stmt = begin_function_try_block (&compound_stmt);
10717           else
10718             stmt = begin_try_block ();
10719
10720           RECUR (TRY_STMTS (t));
10721
10722           if (FN_TRY_BLOCK_P (t))
10723             finish_function_try_block (stmt);
10724           else
10725             finish_try_block (stmt);
10726
10727           RECUR (TRY_HANDLERS (t));
10728           if (FN_TRY_BLOCK_P (t))
10729             finish_function_handler_sequence (stmt, compound_stmt);
10730           else
10731             finish_handler_sequence (stmt);
10732         }
10733       break;
10734
10735     case HANDLER:
10736       {
10737         tree decl = HANDLER_PARMS (t);
10738
10739         if (decl)
10740           {
10741             decl = tsubst (decl, args, complain, in_decl);
10742             /* Prevent instantiate_decl from trying to instantiate
10743                this variable.  We've already done all that needs to be
10744                done.  */
10745             if (decl != error_mark_node)
10746               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10747           }
10748         stmt = begin_handler ();
10749         finish_handler_parms (decl, stmt);
10750         RECUR (HANDLER_BODY (t));
10751         finish_handler (stmt);
10752       }
10753       break;
10754
10755     case TAG_DEFN:
10756       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
10757       break;
10758
10759     case STATIC_ASSERT:
10760       {
10761         tree condition = 
10762           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
10763                        args,
10764                        complain, in_decl,
10765                        /*integral_constant_expression_p=*/true);
10766         finish_static_assert (condition,
10767                               STATIC_ASSERT_MESSAGE (t),
10768                               STATIC_ASSERT_SOURCE_LOCATION (t),
10769                               /*member_p=*/false);
10770       }
10771       break;
10772
10773     case OMP_PARALLEL:
10774       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
10775                                 args, complain, in_decl);
10776       stmt = begin_omp_parallel ();
10777       RECUR (OMP_PARALLEL_BODY (t));
10778       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
10779         = OMP_PARALLEL_COMBINED (t);
10780       break;
10781
10782     case OMP_TASK:
10783       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
10784                                 args, complain, in_decl);
10785       stmt = begin_omp_task ();
10786       RECUR (OMP_TASK_BODY (t));
10787       finish_omp_task (tmp, stmt);
10788       break;
10789
10790     case OMP_FOR:
10791       {
10792         tree clauses, body, pre_body;
10793         tree declv, initv, condv, incrv;
10794         int i;
10795
10796         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
10797                                       args, complain, in_decl);
10798         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10799         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10800         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10801         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10802
10803         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
10804           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
10805                                    &clauses, args, complain, in_decl,
10806                                    integral_constant_expression_p);
10807
10808         stmt = begin_omp_structured_block ();
10809
10810         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
10811           if (TREE_VEC_ELT (initv, i) == NULL
10812               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
10813             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
10814           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
10815             {
10816               tree init = RECUR (TREE_VEC_ELT (initv, i));
10817               gcc_assert (init == TREE_VEC_ELT (declv, i));
10818               TREE_VEC_ELT (initv, i) = NULL_TREE;
10819             }
10820           else
10821             {
10822               tree decl_expr = TREE_VEC_ELT (initv, i);
10823               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
10824               gcc_assert (init != NULL);
10825               TREE_VEC_ELT (initv, i) = RECUR (init);
10826               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
10827               RECUR (decl_expr);
10828               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
10829             }
10830
10831         pre_body = push_stmt_list ();
10832         RECUR (OMP_FOR_PRE_BODY (t));
10833         pre_body = pop_stmt_list (pre_body);
10834
10835         body = push_stmt_list ();
10836         RECUR (OMP_FOR_BODY (t));
10837         body = pop_stmt_list (body);
10838
10839         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
10840                             body, pre_body, clauses);
10841
10842         add_stmt (finish_omp_structured_block (stmt));
10843       }
10844       break;
10845
10846     case OMP_SECTIONS:
10847     case OMP_SINGLE:
10848       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
10849       stmt = push_stmt_list ();
10850       RECUR (OMP_BODY (t));
10851       stmt = pop_stmt_list (stmt);
10852
10853       t = copy_node (t);
10854       OMP_BODY (t) = stmt;
10855       OMP_CLAUSES (t) = tmp;
10856       add_stmt (t);
10857       break;
10858
10859     case OMP_SECTION:
10860     case OMP_CRITICAL:
10861     case OMP_MASTER:
10862     case OMP_ORDERED:
10863       stmt = push_stmt_list ();
10864       RECUR (OMP_BODY (t));
10865       stmt = pop_stmt_list (stmt);
10866
10867       t = copy_node (t);
10868       OMP_BODY (t) = stmt;
10869       add_stmt (t);
10870       break;
10871
10872     case OMP_ATOMIC:
10873       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
10874       {
10875         tree op1 = TREE_OPERAND (t, 1);
10876         tree lhs = RECUR (TREE_OPERAND (op1, 0));
10877         tree rhs = RECUR (TREE_OPERAND (op1, 1));
10878         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
10879       }
10880       break;
10881
10882     case EXPR_PACK_EXPANSION:
10883       error ("invalid use of pack expansion expression");
10884       return error_mark_node;
10885
10886     case NONTYPE_ARGUMENT_PACK:
10887       error ("use %<...%> to expand argument pack");
10888       return error_mark_node;
10889
10890     default:
10891       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
10892
10893       return tsubst_copy_and_build (t, args, complain, in_decl,
10894                                     /*function_p=*/false,
10895                                     integral_constant_expression_p);
10896     }
10897
10898   return NULL_TREE;
10899 #undef RECUR
10900 }
10901
10902 /* T is a postfix-expression that is not being used in a function
10903    call.  Return the substituted version of T.  */
10904
10905 static tree
10906 tsubst_non_call_postfix_expression (tree t, tree args,
10907                                     tsubst_flags_t complain,
10908                                     tree in_decl)
10909 {
10910   if (TREE_CODE (t) == SCOPE_REF)
10911     t = tsubst_qualified_id (t, args, complain, in_decl,
10912                              /*done=*/false, /*address_p=*/false);
10913   else
10914     t = tsubst_copy_and_build (t, args, complain, in_decl,
10915                                /*function_p=*/false,
10916                                /*integral_constant_expression_p=*/false);
10917
10918   return t;
10919 }
10920
10921 /* Like tsubst but deals with expressions and performs semantic
10922    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
10923
10924 tree
10925 tsubst_copy_and_build (tree t,
10926                        tree args,
10927                        tsubst_flags_t complain,
10928                        tree in_decl,
10929                        bool function_p,
10930                        bool integral_constant_expression_p)
10931 {
10932 #define RECUR(NODE)                                             \
10933   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
10934                          /*function_p=*/false,                  \
10935                          integral_constant_expression_p)
10936
10937   tree op1;
10938
10939   if (t == NULL_TREE || t == error_mark_node)
10940     return t;
10941
10942   switch (TREE_CODE (t))
10943     {
10944     case USING_DECL:
10945       t = DECL_NAME (t);
10946       /* Fall through.  */
10947     case IDENTIFIER_NODE:
10948       {
10949         tree decl;
10950         cp_id_kind idk;
10951         bool non_integral_constant_expression_p;
10952         const char *error_msg;
10953
10954         if (IDENTIFIER_TYPENAME_P (t))
10955           {
10956             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10957             t = mangle_conv_op_name_for_type (new_type);
10958           }
10959
10960         /* Look up the name.  */
10961         decl = lookup_name (t);
10962
10963         /* By convention, expressions use ERROR_MARK_NODE to indicate
10964            failure, not NULL_TREE.  */
10965         if (decl == NULL_TREE)
10966           decl = error_mark_node;
10967
10968         decl = finish_id_expression (t, decl, NULL_TREE,
10969                                      &idk,
10970                                      integral_constant_expression_p,
10971                                      /*allow_non_integral_constant_expression_p=*/false,
10972                                      &non_integral_constant_expression_p,
10973                                      /*template_p=*/false,
10974                                      /*done=*/true,
10975                                      /*address_p=*/false,
10976                                      /*template_arg_p=*/false,
10977                                      &error_msg,
10978                                      input_location);
10979         if (error_msg)
10980           error (error_msg);
10981         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
10982           decl = unqualified_name_lookup_error (decl);
10983         return decl;
10984       }
10985
10986     case TEMPLATE_ID_EXPR:
10987       {
10988         tree object;
10989         tree templ = RECUR (TREE_OPERAND (t, 0));
10990         tree targs = TREE_OPERAND (t, 1);
10991
10992         if (targs)
10993           targs = tsubst_template_args (targs, args, complain, in_decl);
10994
10995         if (TREE_CODE (templ) == COMPONENT_REF)
10996           {
10997             object = TREE_OPERAND (templ, 0);
10998             templ = TREE_OPERAND (templ, 1);
10999           }
11000         else
11001           object = NULL_TREE;
11002         templ = lookup_template_function (templ, targs);
11003
11004         if (object)
11005           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11006                          object, templ, NULL_TREE);
11007         else
11008           return baselink_for_fns (templ);
11009       }
11010
11011     case INDIRECT_REF:
11012       {
11013         tree r = RECUR (TREE_OPERAND (t, 0));
11014
11015         if (REFERENCE_REF_P (t))
11016           {
11017             /* A type conversion to reference type will be enclosed in
11018                such an indirect ref, but the substitution of the cast
11019                will have also added such an indirect ref.  */
11020             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11021               r = convert_from_reference (r);
11022           }
11023         else
11024           r = build_x_indirect_ref (r, "unary *", complain);
11025         return r;
11026       }
11027
11028     case NOP_EXPR:
11029       return build_nop
11030         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11031          RECUR (TREE_OPERAND (t, 0)));
11032
11033     case CAST_EXPR:
11034     case REINTERPRET_CAST_EXPR:
11035     case CONST_CAST_EXPR:
11036     case DYNAMIC_CAST_EXPR:
11037     case STATIC_CAST_EXPR:
11038       {
11039         tree type;
11040         tree op;
11041
11042         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11043         if (integral_constant_expression_p
11044             && !cast_valid_in_integral_constant_expression_p (type))
11045           {
11046             if (complain & tf_error)
11047               error ("a cast to a type other than an integral or "
11048                      "enumeration type cannot appear in a constant-expression");
11049             return error_mark_node; 
11050           }
11051
11052         op = RECUR (TREE_OPERAND (t, 0));
11053
11054         switch (TREE_CODE (t))
11055           {
11056           case CAST_EXPR:
11057             return build_functional_cast (type, op, complain);
11058           case REINTERPRET_CAST_EXPR:
11059             return build_reinterpret_cast (type, op, complain);
11060           case CONST_CAST_EXPR:
11061             return build_const_cast (type, op, complain);
11062           case DYNAMIC_CAST_EXPR:
11063             return build_dynamic_cast (type, op, complain);
11064           case STATIC_CAST_EXPR:
11065             return build_static_cast (type, op, complain);
11066           default:
11067             gcc_unreachable ();
11068           }
11069       }
11070
11071     case POSTDECREMENT_EXPR:
11072     case POSTINCREMENT_EXPR:
11073       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11074                                                 args, complain, in_decl);
11075       return build_x_unary_op (TREE_CODE (t), op1, complain);
11076
11077     case PREDECREMENT_EXPR:
11078     case PREINCREMENT_EXPR:
11079     case NEGATE_EXPR:
11080     case BIT_NOT_EXPR:
11081     case ABS_EXPR:
11082     case TRUTH_NOT_EXPR:
11083     case UNARY_PLUS_EXPR:  /* Unary + */
11084     case REALPART_EXPR:
11085     case IMAGPART_EXPR:
11086       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11087                                complain);
11088
11089     case ADDR_EXPR:
11090       op1 = TREE_OPERAND (t, 0);
11091       if (TREE_CODE (op1) == SCOPE_REF)
11092         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11093                                    /*done=*/true, /*address_p=*/true);
11094       else
11095         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11096                                                   in_decl);
11097       if (TREE_CODE (op1) == LABEL_DECL)
11098         return finish_label_address_expr (DECL_NAME (op1),
11099                                           EXPR_LOCATION (op1));
11100       return build_x_unary_op (ADDR_EXPR, op1, complain);
11101
11102     case PLUS_EXPR:
11103     case MINUS_EXPR:
11104     case MULT_EXPR:
11105     case TRUNC_DIV_EXPR:
11106     case CEIL_DIV_EXPR:
11107     case FLOOR_DIV_EXPR:
11108     case ROUND_DIV_EXPR:
11109     case EXACT_DIV_EXPR:
11110     case BIT_AND_EXPR:
11111     case BIT_IOR_EXPR:
11112     case BIT_XOR_EXPR:
11113     case TRUNC_MOD_EXPR:
11114     case FLOOR_MOD_EXPR:
11115     case TRUTH_ANDIF_EXPR:
11116     case TRUTH_ORIF_EXPR:
11117     case TRUTH_AND_EXPR:
11118     case TRUTH_OR_EXPR:
11119     case RSHIFT_EXPR:
11120     case LSHIFT_EXPR:
11121     case RROTATE_EXPR:
11122     case LROTATE_EXPR:
11123     case EQ_EXPR:
11124     case NE_EXPR:
11125     case MAX_EXPR:
11126     case MIN_EXPR:
11127     case LE_EXPR:
11128     case GE_EXPR:
11129     case LT_EXPR:
11130     case GT_EXPR:
11131     case MEMBER_REF:
11132     case DOTSTAR_EXPR:
11133       return build_x_binary_op
11134         (TREE_CODE (t),
11135          RECUR (TREE_OPERAND (t, 0)),
11136          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11137           ? ERROR_MARK
11138           : TREE_CODE (TREE_OPERAND (t, 0))),
11139          RECUR (TREE_OPERAND (t, 1)),
11140          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11141           ? ERROR_MARK
11142           : TREE_CODE (TREE_OPERAND (t, 1))),
11143          /*overloaded_p=*/NULL,
11144          complain);
11145
11146     case SCOPE_REF:
11147       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11148                                   /*address_p=*/false);
11149     case ARRAY_REF:
11150       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11151                                                 args, complain, in_decl);
11152       return build_x_binary_op (ARRAY_REF, op1,
11153                                 (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11154                                  ? ERROR_MARK
11155                                  : TREE_CODE (TREE_OPERAND (t, 0))),
11156                                 RECUR (TREE_OPERAND (t, 1)),
11157                                 (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11158                                  ? ERROR_MARK
11159                                  : TREE_CODE (TREE_OPERAND (t, 1))),
11160                                 /*overloaded_p=*/NULL,
11161                                 complain);
11162
11163     case SIZEOF_EXPR:
11164       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11165         return tsubst_copy (t, args, complain, in_decl);
11166       /* Fall through */
11167       
11168     case ALIGNOF_EXPR:
11169       op1 = TREE_OPERAND (t, 0);
11170       if (!args)
11171         {
11172           /* When there are no ARGS, we are trying to evaluate a
11173              non-dependent expression from the parser.  Trying to do
11174              the substitutions may not work.  */
11175           if (!TYPE_P (op1))
11176             op1 = TREE_TYPE (op1);
11177         }
11178       else
11179         {
11180           ++skip_evaluation;
11181           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11182                                        /*function_p=*/false,
11183                                        /*integral_constant_expression_p=*/false);
11184           --skip_evaluation;
11185         }
11186       if (TYPE_P (op1))
11187         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11188                                            complain & tf_error);
11189       else
11190         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11191                                            complain & tf_error);
11192
11193     case MODOP_EXPR:
11194       {
11195         tree r = build_x_modify_expr
11196           (RECUR (TREE_OPERAND (t, 0)),
11197            TREE_CODE (TREE_OPERAND (t, 1)),
11198            RECUR (TREE_OPERAND (t, 2)),
11199            complain);
11200         /* TREE_NO_WARNING must be set if either the expression was
11201            parenthesized or it uses an operator such as >>= rather
11202            than plain assignment.  In the former case, it was already
11203            set and must be copied.  In the latter case,
11204            build_x_modify_expr sets it and it must not be reset
11205            here.  */
11206         if (TREE_NO_WARNING (t))
11207           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11208         return r;
11209       }
11210
11211     case ARROW_EXPR:
11212       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11213                                                 args, complain, in_decl);
11214       /* Remember that there was a reference to this entity.  */
11215       if (DECL_P (op1))
11216         mark_used (op1);
11217       return build_x_arrow (op1);
11218
11219     case NEW_EXPR:
11220       {
11221         tree init = RECUR (TREE_OPERAND (t, 3));
11222
11223         if (TREE_OPERAND (t, 3) && !init)
11224           /* If there was an initializer in the original tree, but
11225              it instantiated to an empty list, then we should pass on
11226              VOID_ZERO_NODE to tell build_new that it was an empty
11227              initializer () rather than no initializer.  This can only
11228              happen when the initializer is a pack expansion whose
11229              parameter packs are of length zero.  */
11230           init = void_zero_node;
11231
11232         return build_new
11233           (RECUR (TREE_OPERAND (t, 0)),
11234            RECUR (TREE_OPERAND (t, 1)),
11235            RECUR (TREE_OPERAND (t, 2)),
11236            init,
11237            NEW_EXPR_USE_GLOBAL (t),
11238            complain);
11239       }
11240
11241     case DELETE_EXPR:
11242      return delete_sanity
11243        (RECUR (TREE_OPERAND (t, 0)),
11244         RECUR (TREE_OPERAND (t, 1)),
11245         DELETE_EXPR_USE_VEC (t),
11246         DELETE_EXPR_USE_GLOBAL (t));
11247
11248     case COMPOUND_EXPR:
11249       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
11250                                     RECUR (TREE_OPERAND (t, 1)),
11251                                     complain);
11252
11253     case CALL_EXPR:
11254       {
11255         tree function;
11256         tree call_args;
11257         bool qualified_p;
11258         bool koenig_p;
11259
11260         function = CALL_EXPR_FN (t);
11261         /* When we parsed the expression,  we determined whether or
11262            not Koenig lookup should be performed.  */
11263         koenig_p = KOENIG_LOOKUP_P (t);
11264         if (TREE_CODE (function) == SCOPE_REF)
11265           {
11266             qualified_p = true;
11267             function = tsubst_qualified_id (function, args, complain, in_decl,
11268                                             /*done=*/false,
11269                                             /*address_p=*/false);
11270           }
11271         else
11272           {
11273             if (TREE_CODE (function) == COMPONENT_REF)
11274               {
11275                 tree op = TREE_OPERAND (function, 1);
11276
11277                 qualified_p = (TREE_CODE (op) == SCOPE_REF
11278                                || (BASELINK_P (op)
11279                                    && BASELINK_QUALIFIED_P (op)));
11280               }
11281             else
11282               qualified_p = false;
11283
11284             function = tsubst_copy_and_build (function, args, complain,
11285                                               in_decl,
11286                                               !qualified_p,
11287                                               integral_constant_expression_p);
11288
11289             if (BASELINK_P (function))
11290               qualified_p = true;
11291           }
11292
11293         /* FIXME:  Rewrite this so as not to construct an arglist.  */
11294         call_args = RECUR (CALL_EXPR_ARGS (t));
11295
11296         /* We do not perform argument-dependent lookup if normal
11297            lookup finds a non-function, in accordance with the
11298            expected resolution of DR 218.  */
11299         if (koenig_p
11300             && ((is_overloaded_fn (function)
11301                  /* If lookup found a member function, the Koenig lookup is
11302                     not appropriate, even if an unqualified-name was used
11303                     to denote the function.  */
11304                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
11305                 || TREE_CODE (function) == IDENTIFIER_NODE))
11306           function = perform_koenig_lookup (function, call_args);
11307
11308         if (TREE_CODE (function) == IDENTIFIER_NODE)
11309           {
11310             unqualified_name_lookup_error (function);
11311             return error_mark_node;
11312           }
11313
11314         /* Remember that there was a reference to this entity.  */
11315         if (DECL_P (function))
11316           mark_used (function);
11317
11318         if (TREE_CODE (function) == OFFSET_REF)
11319           return build_offset_ref_call_from_tree (function, call_args);
11320         if (TREE_CODE (function) == COMPONENT_REF)
11321           {
11322             if (!BASELINK_P (TREE_OPERAND (function, 1)))
11323               return finish_call_expr (function, call_args,
11324                                        /*disallow_virtual=*/false,
11325                                        /*koenig_p=*/false,
11326                                        complain);
11327             else
11328               return (build_new_method_call
11329                       (TREE_OPERAND (function, 0),
11330                        TREE_OPERAND (function, 1),
11331                        call_args, NULL_TREE,
11332                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
11333                        /*fn_p=*/NULL,
11334                        complain));
11335           }
11336         return finish_call_expr (function, call_args,
11337                                  /*disallow_virtual=*/qualified_p,
11338                                  koenig_p,
11339                                  complain);
11340       }
11341
11342     case COND_EXPR:
11343       return build_x_conditional_expr
11344         (RECUR (TREE_OPERAND (t, 0)),
11345          RECUR (TREE_OPERAND (t, 1)),
11346          RECUR (TREE_OPERAND (t, 2)),
11347          complain);
11348
11349     case PSEUDO_DTOR_EXPR:
11350       return finish_pseudo_destructor_expr
11351         (RECUR (TREE_OPERAND (t, 0)),
11352          RECUR (TREE_OPERAND (t, 1)),
11353          RECUR (TREE_OPERAND (t, 2)));
11354
11355     case TREE_LIST:
11356       {
11357         tree purpose, value, chain;
11358
11359         if (t == void_list_node)
11360           return t;
11361
11362         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
11363             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
11364           {
11365             /* We have pack expansions, so expand those and
11366                create a new list out of it.  */
11367             tree purposevec = NULL_TREE;
11368             tree valuevec = NULL_TREE;
11369             tree chain;
11370             int i, len = -1;
11371
11372             /* Expand the argument expressions.  */
11373             if (TREE_PURPOSE (t))
11374               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
11375                                                  complain, in_decl);
11376             if (TREE_VALUE (t))
11377               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
11378                                                complain, in_decl);
11379
11380             /* Build the rest of the list.  */
11381             chain = TREE_CHAIN (t);
11382             if (chain && chain != void_type_node)
11383               chain = RECUR (chain);
11384
11385             /* Determine the number of arguments.  */
11386             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
11387               {
11388                 len = TREE_VEC_LENGTH (purposevec);
11389                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
11390               }
11391             else if (TREE_CODE (valuevec) == TREE_VEC)
11392               len = TREE_VEC_LENGTH (valuevec);
11393             else
11394               {
11395                 /* Since we only performed a partial substitution into
11396                    the argument pack, we only return a single list
11397                    node.  */
11398                 if (purposevec == TREE_PURPOSE (t)
11399                     && valuevec == TREE_VALUE (t)
11400                     && chain == TREE_CHAIN (t))
11401                   return t;
11402
11403                 return tree_cons (purposevec, valuevec, chain);
11404               }
11405             
11406             /* Convert the argument vectors into a TREE_LIST */
11407             i = len;
11408             while (i > 0)
11409               {
11410                 /* Grab the Ith values.  */
11411                 i--;
11412                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
11413                                      : NULL_TREE;
11414                 value 
11415                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
11416                              : NULL_TREE;
11417
11418                 /* Build the list (backwards).  */
11419                 chain = tree_cons (purpose, value, chain);
11420               }
11421
11422             return chain;
11423           }
11424
11425         purpose = TREE_PURPOSE (t);
11426         if (purpose)
11427           purpose = RECUR (purpose);
11428         value = TREE_VALUE (t);
11429         if (value)
11430           value = RECUR (value);
11431         chain = TREE_CHAIN (t);
11432         if (chain && chain != void_type_node)
11433           chain = RECUR (chain);
11434         if (purpose == TREE_PURPOSE (t)
11435             && value == TREE_VALUE (t)
11436             && chain == TREE_CHAIN (t))
11437           return t;
11438         return tree_cons (purpose, value, chain);
11439       }
11440
11441     case COMPONENT_REF:
11442       {
11443         tree object;
11444         tree object_type;
11445         tree member;
11446
11447         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11448                                                      args, complain, in_decl);
11449         /* Remember that there was a reference to this entity.  */
11450         if (DECL_P (object))
11451           mark_used (object);
11452         object_type = TREE_TYPE (object);
11453
11454         member = TREE_OPERAND (t, 1);
11455         if (BASELINK_P (member))
11456           member = tsubst_baselink (member,
11457                                     non_reference (TREE_TYPE (object)),
11458                                     args, complain, in_decl);
11459         else
11460           member = tsubst_copy (member, args, complain, in_decl);
11461         if (member == error_mark_node)
11462           return error_mark_node;
11463
11464         if (object_type && !CLASS_TYPE_P (object_type))
11465           {
11466             if (SCALAR_TYPE_P (object_type))
11467               {
11468                 tree s = NULL_TREE;
11469                 tree dtor = member;
11470
11471                 if (TREE_CODE (dtor) == SCOPE_REF)
11472                   {
11473                     s = TREE_OPERAND (dtor, 0);
11474                     dtor = TREE_OPERAND (dtor, 1);
11475                   }
11476                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
11477                   {
11478                     dtor = TREE_OPERAND (dtor, 0);
11479                     if (TYPE_P (dtor))
11480                       return finish_pseudo_destructor_expr (object, s, dtor);
11481                   }
11482               }
11483           }
11484         else if (TREE_CODE (member) == SCOPE_REF
11485                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
11486           {
11487             tree tmpl;
11488             tree args;
11489
11490             /* Lookup the template functions now that we know what the
11491                scope is.  */
11492             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
11493             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
11494             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
11495                                             /*is_type_p=*/false,
11496                                             /*complain=*/false);
11497             if (BASELINK_P (member))
11498               {
11499                 BASELINK_FUNCTIONS (member)
11500                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
11501                               args);
11502                 member = (adjust_result_of_qualified_name_lookup
11503                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
11504                            object_type));
11505               }
11506             else
11507               {
11508                 qualified_name_lookup_error (object_type, tmpl, member,
11509                                              input_location);
11510                 return error_mark_node;
11511               }
11512           }
11513         else if (TREE_CODE (member) == SCOPE_REF
11514                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
11515                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
11516           {
11517             if (complain & tf_error)
11518               {
11519                 if (TYPE_P (TREE_OPERAND (member, 0)))
11520                   error ("%qT is not a class or namespace",
11521                          TREE_OPERAND (member, 0));
11522                 else
11523                   error ("%qD is not a class or namespace",
11524                          TREE_OPERAND (member, 0));
11525               }
11526             return error_mark_node;
11527           }
11528         else if (TREE_CODE (member) == FIELD_DECL)
11529           return finish_non_static_data_member (member, object, NULL_TREE);
11530
11531         return finish_class_member_access_expr (object, member,
11532                                                 /*template_p=*/false,
11533                                                 complain);
11534       }
11535
11536     case THROW_EXPR:
11537       return build_throw
11538         (RECUR (TREE_OPERAND (t, 0)));
11539
11540     case CONSTRUCTOR:
11541       {
11542         VEC(constructor_elt,gc) *n;
11543         constructor_elt *ce;
11544         unsigned HOST_WIDE_INT idx;
11545         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11546         bool process_index_p;
11547         int newlen;
11548         bool need_copy_p = false;
11549         tree r;
11550
11551         if (type == error_mark_node)
11552           return error_mark_node;
11553
11554         /* digest_init will do the wrong thing if we let it.  */
11555         if (type && TYPE_PTRMEMFUNC_P (type))
11556           return t;
11557
11558         /* We do not want to process the index of aggregate
11559            initializers as they are identifier nodes which will be
11560            looked up by digest_init.  */
11561         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
11562
11563         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
11564         newlen = VEC_length (constructor_elt, n);
11565         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
11566           {
11567             if (ce->index && process_index_p)
11568               ce->index = RECUR (ce->index);
11569
11570             if (PACK_EXPANSION_P (ce->value))
11571               {
11572                 /* Substitute into the pack expansion.  */
11573                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
11574                                                   in_decl);
11575
11576                 if (ce->value == error_mark_node)
11577                   ;
11578                 else if (TREE_VEC_LENGTH (ce->value) == 1)
11579                   /* Just move the argument into place.  */
11580                   ce->value = TREE_VEC_ELT (ce->value, 0);
11581                 else
11582                   {
11583                     /* Update the length of the final CONSTRUCTOR
11584                        arguments vector, and note that we will need to
11585                        copy.*/
11586                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
11587                     need_copy_p = true;
11588                   }
11589               }
11590             else
11591               ce->value = RECUR (ce->value);
11592           }
11593
11594         if (need_copy_p)
11595           {
11596             VEC(constructor_elt,gc) *old_n = n;
11597
11598             n = VEC_alloc (constructor_elt, gc, newlen);
11599             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
11600                  idx++)
11601               {
11602                 if (TREE_CODE (ce->value) == TREE_VEC)
11603                   {
11604                     int i, len = TREE_VEC_LENGTH (ce->value);
11605                     for (i = 0; i < len; ++i)
11606                       CONSTRUCTOR_APPEND_ELT (n, 0,
11607                                               TREE_VEC_ELT (ce->value, i));
11608                   }
11609                 else
11610                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
11611               }
11612           }
11613
11614         r = build_constructor (init_list_type_node, n);
11615         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
11616
11617         if (TREE_HAS_CONSTRUCTOR (t))
11618           return finish_compound_literal (type, r);
11619
11620         return r;
11621       }
11622
11623     case TYPEID_EXPR:
11624       {
11625         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
11626         if (TYPE_P (operand_0))
11627           return get_typeid (operand_0);
11628         return build_typeid (operand_0);
11629       }
11630
11631     case VAR_DECL:
11632       if (!args)
11633         return t;
11634       /* Fall through */
11635
11636     case PARM_DECL:
11637       {
11638         tree r = tsubst_copy (t, args, complain, in_decl);
11639
11640         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
11641           /* If the original type was a reference, we'll be wrapped in
11642              the appropriate INDIRECT_REF.  */
11643           r = convert_from_reference (r);
11644         return r;
11645       }
11646
11647     case VA_ARG_EXPR:
11648       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
11649                              tsubst_copy (TREE_TYPE (t), args, complain,
11650                                           in_decl));
11651
11652     case OFFSETOF_EXPR:
11653       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
11654
11655     case TRAIT_EXPR:
11656       {
11657         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
11658                                   complain, in_decl);
11659
11660         tree type2 = TRAIT_EXPR_TYPE2 (t);
11661         if (type2)
11662           type2 = tsubst_copy (type2, args, complain, in_decl);
11663         
11664         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
11665       }
11666
11667     case STMT_EXPR:
11668       {
11669         tree old_stmt_expr = cur_stmt_expr;
11670         tree stmt_expr = begin_stmt_expr ();
11671
11672         cur_stmt_expr = stmt_expr;
11673         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
11674                      integral_constant_expression_p);
11675         stmt_expr = finish_stmt_expr (stmt_expr, false);
11676         cur_stmt_expr = old_stmt_expr;
11677
11678         return stmt_expr;
11679       }
11680
11681     case CONST_DECL:
11682       t = tsubst_copy (t, args, complain, in_decl);
11683       /* As in finish_id_expression, we resolve enumeration constants
11684          to their underlying values.  */
11685       if (TREE_CODE (t) == CONST_DECL)
11686         {
11687           used_types_insert (TREE_TYPE (t));
11688           return DECL_INITIAL (t);
11689         }
11690       return t;
11691
11692     default:
11693       /* Handle Objective-C++ constructs, if appropriate.  */
11694       {
11695         tree subst
11696           = objcp_tsubst_copy_and_build (t, args, complain,
11697                                          in_decl, /*function_p=*/false);
11698         if (subst)
11699           return subst;
11700       }
11701       return tsubst_copy (t, args, complain, in_decl);
11702     }
11703
11704 #undef RECUR
11705 }
11706
11707 /* Verify that the instantiated ARGS are valid. For type arguments,
11708    make sure that the type's linkage is ok. For non-type arguments,
11709    make sure they are constants if they are integral or enumerations.
11710    Emit an error under control of COMPLAIN, and return TRUE on error.  */
11711
11712 static bool
11713 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
11714 {
11715   int ix, len = DECL_NTPARMS (tmpl);
11716   bool result = false;
11717
11718   for (ix = 0; ix != len; ix++)
11719     {
11720       tree t = TREE_VEC_ELT (args, ix);
11721
11722       if (TYPE_P (t))
11723         {
11724           /* [basic.link]: A name with no linkage (notably, the name
11725              of a class or enumeration declared in a local scope)
11726              shall not be used to declare an entity with linkage.
11727              This implies that names with no linkage cannot be used as
11728              template arguments.  */
11729           tree nt = no_linkage_check (t, /*relaxed_p=*/false);
11730
11731           if (nt)
11732             {
11733               /* DR 488 makes use of a type with no linkage cause
11734                  type deduction to fail.  */
11735               if (complain & tf_error)
11736                 {
11737                   if (TYPE_ANONYMOUS_P (nt))
11738                     error ("%qT is/uses anonymous type", t);
11739                   else
11740                     error ("template argument for %qD uses local type %qT",
11741                            tmpl, t);
11742                 }
11743               result = true;
11744             }
11745           /* In order to avoid all sorts of complications, we do not
11746              allow variably-modified types as template arguments.  */
11747           else if (variably_modified_type_p (t, NULL_TREE))
11748             {
11749               if (complain & tf_error)
11750                 error ("%qT is a variably modified type", t);
11751               result = true;
11752             }
11753         }
11754       /* A non-type argument of integral or enumerated type must be a
11755          constant.  */
11756       else if (TREE_TYPE (t)
11757                && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
11758                && !TREE_CONSTANT (t))
11759         {
11760           if (complain & tf_error)
11761             error ("integral expression %qE is not constant", t);
11762           result = true;
11763         }
11764     }
11765   if (result && (complain & tf_error))
11766     error ("  trying to instantiate %qD", tmpl);
11767   return result;
11768 }
11769
11770 /* Instantiate the indicated variable or function template TMPL with
11771    the template arguments in TARG_PTR.  */
11772
11773 tree
11774 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
11775 {
11776   tree fndecl;
11777   tree gen_tmpl;
11778   tree spec;
11779   HOST_WIDE_INT saved_processing_template_decl;
11780
11781   if (tmpl == error_mark_node)
11782     return error_mark_node;
11783
11784   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
11785
11786   /* If this function is a clone, handle it specially.  */
11787   if (DECL_CLONED_FUNCTION_P (tmpl))
11788     {
11789       tree spec;
11790       tree clone;
11791
11792       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
11793                                    complain);
11794       if (spec == error_mark_node)
11795         return error_mark_node;
11796
11797       /* Look for the clone.  */
11798       FOR_EACH_CLONE (clone, spec)
11799         if (DECL_NAME (clone) == DECL_NAME (tmpl))
11800           return clone;
11801       /* We should always have found the clone by now.  */
11802       gcc_unreachable ();
11803       return NULL_TREE;
11804     }
11805
11806   /* Check to see if we already have this specialization.  */
11807   spec = retrieve_specialization (tmpl, targ_ptr,
11808                                   /*class_specializations_p=*/false);
11809   if (spec != NULL_TREE)
11810     return spec;
11811
11812   gen_tmpl = most_general_template (tmpl);
11813   if (tmpl != gen_tmpl)
11814     {
11815       /* The TMPL is a partial instantiation.  To get a full set of
11816          arguments we must add the arguments used to perform the
11817          partial instantiation.  */
11818       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
11819                                               targ_ptr);
11820
11821       /* Check to see if we already have this specialization.  */
11822       spec = retrieve_specialization (gen_tmpl, targ_ptr,
11823                                       /*class_specializations_p=*/false);
11824       if (spec != NULL_TREE)
11825         return spec;
11826     }
11827
11828   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
11829                                complain))
11830     return error_mark_node;
11831
11832   /* We are building a FUNCTION_DECL, during which the access of its
11833      parameters and return types have to be checked.  However this
11834      FUNCTION_DECL which is the desired context for access checking
11835      is not built yet.  We solve this chicken-and-egg problem by
11836      deferring all checks until we have the FUNCTION_DECL.  */
11837   push_deferring_access_checks (dk_deferred);
11838
11839   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
11840      (because, for example, we have encountered a non-dependent
11841      function call in the body of a template function and must now
11842      determine which of several overloaded functions will be called),
11843      within the instantiation itself we are not processing a
11844      template.  */  
11845   saved_processing_template_decl = processing_template_decl;
11846   processing_template_decl = 0;
11847   /* Substitute template parameters to obtain the specialization.  */
11848   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
11849                    targ_ptr, complain, gen_tmpl);
11850   processing_template_decl = saved_processing_template_decl;
11851   if (fndecl == error_mark_node)
11852     return error_mark_node;
11853
11854   /* Now we know the specialization, compute access previously
11855      deferred.  */
11856   push_access_scope (fndecl);
11857   perform_deferred_access_checks ();
11858   pop_access_scope (fndecl);
11859   pop_deferring_access_checks ();
11860
11861   /* The DECL_TI_TEMPLATE should always be the immediate parent
11862      template, not the most general template.  */
11863   DECL_TI_TEMPLATE (fndecl) = tmpl;
11864
11865   /* If we've just instantiated the main entry point for a function,
11866      instantiate all the alternate entry points as well.  We do this
11867      by cloning the instantiation of the main entry point, not by
11868      instantiating the template clones.  */
11869   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
11870     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
11871
11872   return fndecl;
11873 }
11874
11875 /* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
11876    arguments that are being used when calling it.  TARGS is a vector
11877    into which the deduced template arguments are placed.
11878
11879    Return zero for success, 2 for an incomplete match that doesn't resolve
11880    all the types, and 1 for complete failure.  An error message will be
11881    printed only for an incomplete match.
11882
11883    If FN is a conversion operator, or we are trying to produce a specific
11884    specialization, RETURN_TYPE is the return type desired.
11885
11886    The EXPLICIT_TARGS are explicit template arguments provided via a
11887    template-id.
11888
11889    The parameter STRICT is one of:
11890
11891    DEDUCE_CALL:
11892      We are deducing arguments for a function call, as in
11893      [temp.deduct.call].
11894
11895    DEDUCE_CONV:
11896      We are deducing arguments for a conversion function, as in
11897      [temp.deduct.conv].
11898
11899    DEDUCE_EXACT:
11900      We are deducing arguments when doing an explicit instantiation
11901      as in [temp.explicit], when determining an explicit specialization
11902      as in [temp.expl.spec], or when taking the address of a function
11903      template, as in [temp.deduct.funcaddr].  */
11904
11905 int
11906 fn_type_unification (tree fn,
11907                      tree explicit_targs,
11908                      tree targs,
11909                      tree args,
11910                      tree return_type,
11911                      unification_kind_t strict,
11912                      int flags)
11913 {
11914   tree parms;
11915   tree fntype;
11916   int result;
11917   bool incomplete_argument_packs_p = false;
11918
11919   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
11920
11921   fntype = TREE_TYPE (fn);
11922   if (explicit_targs)
11923     {
11924       /* [temp.deduct]
11925
11926          The specified template arguments must match the template
11927          parameters in kind (i.e., type, nontype, template), and there
11928          must not be more arguments than there are parameters;
11929          otherwise type deduction fails.
11930
11931          Nontype arguments must match the types of the corresponding
11932          nontype template parameters, or must be convertible to the
11933          types of the corresponding nontype parameters as specified in
11934          _temp.arg.nontype_, otherwise type deduction fails.
11935
11936          All references in the function type of the function template
11937          to the corresponding template parameters are replaced by the
11938          specified template argument values.  If a substitution in a
11939          template parameter or in the function type of the function
11940          template results in an invalid type, type deduction fails.  */
11941       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
11942       int i, len = TREE_VEC_LENGTH (tparms);
11943       tree converted_args;
11944       bool incomplete = false;
11945
11946       if (explicit_targs == error_mark_node)
11947         return 1;
11948
11949       converted_args
11950         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
11951                                   /*require_all_args=*/false,
11952                                   /*use_default_args=*/false));
11953       if (converted_args == error_mark_node)
11954         return 1;
11955
11956       /* Substitute the explicit args into the function type.  This is
11957          necessary so that, for instance, explicitly declared function
11958          arguments can match null pointed constants.  If we were given
11959          an incomplete set of explicit args, we must not do semantic
11960          processing during substitution as we could create partial
11961          instantiations.  */
11962       for (i = 0; i < len; i++)
11963         {
11964           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
11965           bool parameter_pack = false;
11966
11967           /* Dig out the actual parm.  */
11968           if (TREE_CODE (parm) == TYPE_DECL
11969               || TREE_CODE (parm) == TEMPLATE_DECL)
11970             {
11971               parm = TREE_TYPE (parm);
11972               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
11973             }
11974           else if (TREE_CODE (parm) == PARM_DECL)
11975             {
11976               parm = DECL_INITIAL (parm);
11977               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
11978             }
11979
11980           if (parameter_pack)
11981             {
11982               int level, idx;
11983               tree targ;
11984               template_parm_level_and_index (parm, &level, &idx);
11985
11986               /* Mark the argument pack as "incomplete". We could
11987                  still deduce more arguments during unification.  */
11988               targ = TMPL_ARG (converted_args, level, idx);
11989               if (targ)
11990                 {
11991                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
11992                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
11993                     = ARGUMENT_PACK_ARGS (targ);
11994                 }
11995
11996               /* We have some incomplete argument packs.  */
11997               incomplete_argument_packs_p = true;
11998             }
11999         }
12000
12001       if (incomplete_argument_packs_p)
12002         /* Any substitution is guaranteed to be incomplete if there
12003            are incomplete argument packs, because we can still deduce
12004            more arguments.  */
12005         incomplete = 1;
12006       else
12007         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12008
12009       processing_template_decl += incomplete;
12010       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12011       processing_template_decl -= incomplete;
12012
12013       if (fntype == error_mark_node)
12014         return 1;
12015
12016       /* Place the explicitly specified arguments in TARGS.  */
12017       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12018         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12019     }
12020
12021   /* Never do unification on the 'this' parameter.  */
12022   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12023
12024   if (return_type)
12025     {
12026       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12027       args = tree_cons (NULL_TREE, return_type, args);
12028     }
12029
12030   /* We allow incomplete unification without an error message here
12031      because the standard doesn't seem to explicitly prohibit it.  Our
12032      callers must be ready to deal with unification failures in any
12033      event.  */
12034   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12035                                   targs, parms, args, /*subr=*/0,
12036                                   strict, flags);
12037
12038   if (result == 0 && incomplete_argument_packs_p)
12039     {
12040       int i, len = NUM_TMPL_ARGS (targs);
12041
12042       /* Clear the "incomplete" flags on all argument packs.  */
12043       for (i = 0; i < len; i++)
12044         {
12045           tree arg = TREE_VEC_ELT (targs, i);
12046           if (ARGUMENT_PACK_P (arg))
12047             {
12048               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12049               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12050             }
12051         }
12052     }
12053
12054   /* Now that we have bindings for all of the template arguments,
12055      ensure that the arguments deduced for the template template
12056      parameters have compatible template parameter lists.  We cannot
12057      check this property before we have deduced all template
12058      arguments, because the template parameter types of a template
12059      template parameter might depend on prior template parameters
12060      deduced after the template template parameter.  The following
12061      ill-formed example illustrates this issue:
12062
12063        template<typename T, template<T> class C> void f(C<5>, T);
12064
12065        template<int N> struct X {};
12066
12067        void g() {
12068          f(X<5>(), 5l); // error: template argument deduction fails
12069        }
12070
12071      The template parameter list of 'C' depends on the template type
12072      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
12073      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
12074      time that we deduce 'C'.  */
12075   if (result == 0
12076       && !template_template_parm_bindings_ok_p 
12077            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
12078     return 1;
12079
12080   if (result == 0)
12081     /* All is well so far.  Now, check:
12082
12083        [temp.deduct]
12084
12085        When all template arguments have been deduced, all uses of
12086        template parameters in nondeduced contexts are replaced with
12087        the corresponding deduced argument values.  If the
12088        substitution results in an invalid type, as described above,
12089        type deduction fails.  */
12090     if (tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE)
12091         == error_mark_node)
12092       return 1;
12093
12094   return result;
12095 }
12096
12097 /* Adjust types before performing type deduction, as described in
12098    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
12099    sections are symmetric.  PARM is the type of a function parameter
12100    or the return type of the conversion function.  ARG is the type of
12101    the argument passed to the call, or the type of the value
12102    initialized with the result of the conversion function.
12103    ARG_EXPR is the original argument expression, which may be null.  */
12104
12105 static int
12106 maybe_adjust_types_for_deduction (unification_kind_t strict,
12107                                   tree* parm,
12108                                   tree* arg,
12109                                   tree arg_expr)
12110 {
12111   int result = 0;
12112
12113   switch (strict)
12114     {
12115     case DEDUCE_CALL:
12116       break;
12117
12118     case DEDUCE_CONV:
12119       {
12120         /* Swap PARM and ARG throughout the remainder of this
12121            function; the handling is precisely symmetric since PARM
12122            will initialize ARG rather than vice versa.  */
12123         tree* temp = parm;
12124         parm = arg;
12125         arg = temp;
12126         break;
12127       }
12128
12129     case DEDUCE_EXACT:
12130       /* There is nothing to do in this case.  */
12131       return 0;
12132
12133     default:
12134       gcc_unreachable ();
12135     }
12136
12137   if (TREE_CODE (*parm) != REFERENCE_TYPE)
12138     {
12139       /* [temp.deduct.call]
12140
12141          If P is not a reference type:
12142
12143          --If A is an array type, the pointer type produced by the
12144          array-to-pointer standard conversion (_conv.array_) is
12145          used in place of A for type deduction; otherwise,
12146
12147          --If A is a function type, the pointer type produced by
12148          the function-to-pointer standard conversion
12149          (_conv.func_) is used in place of A for type deduction;
12150          otherwise,
12151
12152          --If A is a cv-qualified type, the top level
12153          cv-qualifiers of A's type are ignored for type
12154          deduction.  */
12155       if (TREE_CODE (*arg) == ARRAY_TYPE)
12156         *arg = build_pointer_type (TREE_TYPE (*arg));
12157       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
12158         *arg = build_pointer_type (*arg);
12159       else
12160         *arg = TYPE_MAIN_VARIANT (*arg);
12161     }
12162
12163   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
12164      of the form T&&, where T is a template parameter, and the argument
12165      is an lvalue, T is deduced as A& */
12166   if (TREE_CODE (*parm) == REFERENCE_TYPE
12167       && TYPE_REF_IS_RVALUE (*parm)
12168       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
12169       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
12170       && arg_expr && real_lvalue_p (arg_expr))
12171     *arg = build_reference_type (*arg);
12172
12173   /* [temp.deduct.call]
12174
12175      If P is a cv-qualified type, the top level cv-qualifiers
12176      of P's type are ignored for type deduction.  If P is a
12177      reference type, the type referred to by P is used for
12178      type deduction.  */
12179   *parm = TYPE_MAIN_VARIANT (*parm);
12180   if (TREE_CODE (*parm) == REFERENCE_TYPE)
12181     {
12182       *parm = TREE_TYPE (*parm);
12183       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12184     }
12185
12186   /* DR 322. For conversion deduction, remove a reference type on parm
12187      too (which has been swapped into ARG).  */
12188   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
12189     *arg = TREE_TYPE (*arg);
12190
12191   return result;
12192 }
12193
12194 /* Most parms like fn_type_unification.
12195
12196    If SUBR is 1, we're being called recursively (to unify the
12197    arguments of a function or method parameter of a function
12198    template). */
12199
12200 static int
12201 type_unification_real (tree tparms,
12202                        tree targs,
12203                        tree xparms,
12204                        tree xargs,
12205                        int subr,
12206                        unification_kind_t strict,
12207                        int flags)
12208 {
12209   tree parm, arg, arg_expr;
12210   int i;
12211   int ntparms = TREE_VEC_LENGTH (tparms);
12212   int sub_strict;
12213   int saw_undeduced = 0;
12214   tree parms, args;
12215
12216   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
12217   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
12218   gcc_assert (!xargs || TREE_CODE (xargs) == TREE_LIST);
12219   gcc_assert (ntparms > 0);
12220
12221   switch (strict)
12222     {
12223     case DEDUCE_CALL:
12224       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
12225                     | UNIFY_ALLOW_DERIVED);
12226       break;
12227
12228     case DEDUCE_CONV:
12229       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12230       break;
12231
12232     case DEDUCE_EXACT:
12233       sub_strict = UNIFY_ALLOW_NONE;
12234       break;
12235
12236     default:
12237       gcc_unreachable ();
12238     }
12239
12240  again:
12241   parms = xparms;
12242   args = xargs;
12243
12244   while (parms && parms != void_list_node
12245          && args && args != void_list_node)
12246     {
12247       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12248         break;
12249
12250       parm = TREE_VALUE (parms);
12251       parms = TREE_CHAIN (parms);
12252       arg = TREE_VALUE (args);
12253       args = TREE_CHAIN (args);
12254       arg_expr = NULL;
12255
12256       if (arg == error_mark_node)
12257         return 1;
12258       if (arg == unknown_type_node)
12259         /* We can't deduce anything from this, but we might get all the
12260            template args from other function args.  */
12261         continue;
12262
12263       /* Conversions will be performed on a function argument that
12264          corresponds with a function parameter that contains only
12265          non-deducible template parameters and explicitly specified
12266          template parameters.  */
12267       if (!uses_template_parms (parm))
12268         {
12269           tree type;
12270
12271           if (!TYPE_P (arg))
12272             type = TREE_TYPE (arg);
12273           else
12274             type = arg;
12275
12276           if (same_type_p (parm, type))
12277             continue;
12278           if (strict != DEDUCE_EXACT
12279               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
12280                                   flags))
12281             continue;
12282
12283           return 1;
12284         }
12285
12286       if (!TYPE_P (arg))
12287         {
12288           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12289           if (type_unknown_p (arg))
12290             {
12291               /* [temp.deduct.type] 
12292
12293                  A template-argument can be deduced from a pointer to
12294                  function or pointer to member function argument if
12295                  the set of overloaded functions does not contain
12296                  function templates and at most one of a set of
12297                  overloaded functions provides a unique match.  */
12298               if (resolve_overloaded_unification
12299                   (tparms, targs, parm, arg, strict, sub_strict))
12300                 continue;
12301
12302               return 1;
12303             }
12304           arg_expr = arg;
12305           arg = unlowered_expr_type (arg);
12306           if (arg == error_mark_node)
12307             return 1;
12308         }
12309
12310       {
12311         int arg_strict = sub_strict;
12312
12313         if (!subr)
12314           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
12315                                                           arg_expr);
12316
12317         if (arg == init_list_type_node && arg_expr)
12318           arg = arg_expr;
12319         if (unify (tparms, targs, parm, arg, arg_strict))
12320           return 1;
12321       }
12322     }
12323
12324
12325   if (parms 
12326       && parms != void_list_node
12327       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12328     {
12329       /* Unify the remaining arguments with the pack expansion type.  */
12330       tree argvec;
12331       tree parmvec = make_tree_vec (1);
12332       int len = 0;
12333       tree t;
12334
12335       /* Count the number of arguments that remain.  */
12336       for (t = args; t && t != void_list_node; t = TREE_CHAIN (t))
12337         len++;
12338         
12339       /* Allocate a TREE_VEC and copy in all of the arguments */ 
12340       argvec = make_tree_vec (len);
12341       for (i = 0; args && args != void_list_node; args = TREE_CHAIN (args))
12342         {
12343           TREE_VEC_ELT (argvec, i) = TREE_VALUE (args);
12344           ++i;
12345         }
12346
12347       /* Copy the parameter into parmvec.  */
12348       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
12349       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
12350                                 /*call_args_p=*/true, /*subr=*/subr))
12351         return 1;
12352
12353       /* Advance to the end of the list of parameters.  */
12354       parms = TREE_CHAIN (parms);
12355     }
12356
12357   /* Fail if we've reached the end of the parm list, and more args
12358      are present, and the parm list isn't variadic.  */
12359   if (args && args != void_list_node && parms == void_list_node)
12360     return 1;
12361   /* Fail if parms are left and they don't have default values.  */
12362   if (parms && parms != void_list_node
12363       && TREE_PURPOSE (parms) == NULL_TREE)
12364     return 1;
12365
12366   if (!subr)
12367     for (i = 0; i < ntparms; i++)
12368       if (!TREE_VEC_ELT (targs, i))
12369         {
12370           tree tparm;
12371
12372           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
12373             continue;
12374
12375           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12376
12377           /* If this is an undeduced nontype parameter that depends on
12378              a type parameter, try another pass; its type may have been
12379              deduced from a later argument than the one from which
12380              this parameter can be deduced.  */
12381           if (TREE_CODE (tparm) == PARM_DECL
12382               && uses_template_parms (TREE_TYPE (tparm))
12383               && !saw_undeduced++)
12384             goto again;
12385
12386           /* Core issue #226 (C++0x) [temp.deduct]:
12387
12388                If a template argument has not been deduced, its
12389                default template argument, if any, is used. 
12390
12391              When we are in C++98 mode, TREE_PURPOSE will either
12392              be NULL_TREE or ERROR_MARK_NODE, so we do not need
12393              to explicitly check cxx_dialect here.  */
12394           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
12395             {
12396               tree arg = tsubst (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)), 
12397                                  targs, tf_none, NULL_TREE);
12398               if (arg == error_mark_node)
12399                 return 1;
12400               else
12401                 {
12402                   TREE_VEC_ELT (targs, i) = arg;
12403                   continue;
12404                 }
12405             }
12406
12407           /* If the type parameter is a parameter pack, then it will
12408              be deduced to an empty parameter pack.  */
12409           if (template_parameter_pack_p (tparm))
12410             {
12411               tree arg;
12412
12413               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
12414                 {
12415                   arg = make_node (NONTYPE_ARGUMENT_PACK);
12416                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
12417                   TREE_CONSTANT (arg) = 1;
12418                 }
12419               else
12420                 arg = make_node (TYPE_ARGUMENT_PACK);
12421
12422               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
12423
12424               TREE_VEC_ELT (targs, i) = arg;
12425               continue;
12426             }
12427
12428           return 2;
12429         }
12430
12431   return 0;
12432 }
12433
12434 /* Subroutine of type_unification_real.  Args are like the variables
12435    at the call site.  ARG is an overloaded function (or template-id);
12436    we try deducing template args from each of the overloads, and if
12437    only one succeeds, we go with that.  Modifies TARGS and returns
12438    true on success.  */
12439
12440 static bool
12441 resolve_overloaded_unification (tree tparms,
12442                                 tree targs,
12443                                 tree parm,
12444                                 tree arg,
12445                                 unification_kind_t strict,
12446                                 int sub_strict)
12447 {
12448   tree tempargs = copy_node (targs);
12449   int good = 0;
12450   bool addr_p;
12451
12452   if (TREE_CODE (arg) == ADDR_EXPR)
12453     {
12454       arg = TREE_OPERAND (arg, 0);
12455       addr_p = true;
12456     }
12457   else
12458     addr_p = false;
12459
12460   if (TREE_CODE (arg) == COMPONENT_REF)
12461     /* Handle `&x' where `x' is some static or non-static member
12462        function name.  */
12463     arg = TREE_OPERAND (arg, 1);
12464
12465   if (TREE_CODE (arg) == OFFSET_REF)
12466     arg = TREE_OPERAND (arg, 1);
12467
12468   /* Strip baselink information.  */
12469   if (BASELINK_P (arg))
12470     arg = BASELINK_FUNCTIONS (arg);
12471
12472   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
12473     {
12474       /* If we got some explicit template args, we need to plug them into
12475          the affected templates before we try to unify, in case the
12476          explicit args will completely resolve the templates in question.  */
12477
12478       tree expl_subargs = TREE_OPERAND (arg, 1);
12479       arg = TREE_OPERAND (arg, 0);
12480
12481       for (; arg; arg = OVL_NEXT (arg))
12482         {
12483           tree fn = OVL_CURRENT (arg);
12484           tree subargs, elem;
12485
12486           if (TREE_CODE (fn) != TEMPLATE_DECL)
12487             continue;
12488
12489           ++processing_template_decl;
12490           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
12491                                   expl_subargs, /*check_ret=*/false);
12492           if (subargs)
12493             {
12494               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
12495               good += try_one_overload (tparms, targs, tempargs, parm,
12496                                         elem, strict, sub_strict, addr_p);
12497             }
12498           --processing_template_decl;
12499         }
12500     }
12501   else if (TREE_CODE (arg) != OVERLOAD
12502            && TREE_CODE (arg) != FUNCTION_DECL)
12503     /* If ARG is, for example, "(0, &f)" then its type will be unknown
12504        -- but the deduction does not succeed because the expression is
12505        not just the function on its own.  */
12506     return false;
12507   else
12508     for (; arg; arg = OVL_NEXT (arg))
12509       good += try_one_overload (tparms, targs, tempargs, parm,
12510                                 TREE_TYPE (OVL_CURRENT (arg)),
12511                                 strict, sub_strict, addr_p);
12512
12513   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12514      to function or pointer to member function argument if the set of
12515      overloaded functions does not contain function templates and at most
12516      one of a set of overloaded functions provides a unique match.
12517
12518      So if we found multiple possibilities, we return success but don't
12519      deduce anything.  */
12520
12521   if (good == 1)
12522     {
12523       int i = TREE_VEC_LENGTH (targs);
12524       for (; i--; )
12525         if (TREE_VEC_ELT (tempargs, i))
12526           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
12527     }
12528   if (good)
12529     return true;
12530
12531   return false;
12532 }
12533
12534 /* Subroutine of resolve_overloaded_unification; does deduction for a single
12535    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
12536    different overloads deduce different arguments for a given parm.
12537    ADDR_P is true if the expression for which deduction is being
12538    performed was of the form "& fn" rather than simply "fn".
12539
12540    Returns 1 on success.  */
12541
12542 static int
12543 try_one_overload (tree tparms,
12544                   tree orig_targs,
12545                   tree targs,
12546                   tree parm,
12547                   tree arg,
12548                   unification_kind_t strict,
12549                   int sub_strict,
12550                   bool addr_p)
12551 {
12552   int nargs;
12553   tree tempargs;
12554   int i;
12555
12556   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12557      to function or pointer to member function argument if the set of
12558      overloaded functions does not contain function templates and at most
12559      one of a set of overloaded functions provides a unique match.
12560
12561      So if this is a template, just return success.  */
12562
12563   if (uses_template_parms (arg))
12564     return 1;
12565
12566   if (TREE_CODE (arg) == METHOD_TYPE)
12567     arg = build_ptrmemfunc_type (build_pointer_type (arg));
12568   else if (addr_p)
12569     arg = build_pointer_type (arg);
12570
12571   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
12572
12573   /* We don't copy orig_targs for this because if we have already deduced
12574      some template args from previous args, unify would complain when we
12575      try to deduce a template parameter for the same argument, even though
12576      there isn't really a conflict.  */
12577   nargs = TREE_VEC_LENGTH (targs);
12578   tempargs = make_tree_vec (nargs);
12579
12580   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
12581     return 0;
12582
12583   /* First make sure we didn't deduce anything that conflicts with
12584      explicitly specified args.  */
12585   for (i = nargs; i--; )
12586     {
12587       tree elt = TREE_VEC_ELT (tempargs, i);
12588       tree oldelt = TREE_VEC_ELT (orig_targs, i);
12589
12590       if (!elt)
12591         /*NOP*/;
12592       else if (uses_template_parms (elt))
12593         /* Since we're unifying against ourselves, we will fill in
12594            template args used in the function parm list with our own
12595            template parms.  Discard them.  */
12596         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
12597       else if (oldelt && !template_args_equal (oldelt, elt))
12598         return 0;
12599     }
12600
12601   for (i = nargs; i--; )
12602     {
12603       tree elt = TREE_VEC_ELT (tempargs, i);
12604
12605       if (elt)
12606         TREE_VEC_ELT (targs, i) = elt;
12607     }
12608
12609   return 1;
12610 }
12611
12612 /* PARM is a template class (perhaps with unbound template
12613    parameters).  ARG is a fully instantiated type.  If ARG can be
12614    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
12615    TARGS are as for unify.  */
12616
12617 static tree
12618 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
12619 {
12620   tree copy_of_targs;
12621
12622   if (!CLASSTYPE_TEMPLATE_INFO (arg)
12623       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
12624           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
12625     return NULL_TREE;
12626
12627   /* We need to make a new template argument vector for the call to
12628      unify.  If we used TARGS, we'd clutter it up with the result of
12629      the attempted unification, even if this class didn't work out.
12630      We also don't want to commit ourselves to all the unifications
12631      we've already done, since unification is supposed to be done on
12632      an argument-by-argument basis.  In other words, consider the
12633      following pathological case:
12634
12635        template <int I, int J, int K>
12636        struct S {};
12637
12638        template <int I, int J>
12639        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
12640
12641        template <int I, int J, int K>
12642        void f(S<I, J, K>, S<I, I, I>);
12643
12644        void g() {
12645          S<0, 0, 0> s0;
12646          S<0, 1, 2> s2;
12647
12648          f(s0, s2);
12649        }
12650
12651      Now, by the time we consider the unification involving `s2', we
12652      already know that we must have `f<0, 0, 0>'.  But, even though
12653      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
12654      because there are two ways to unify base classes of S<0, 1, 2>
12655      with S<I, I, I>.  If we kept the already deduced knowledge, we
12656      would reject the possibility I=1.  */
12657   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
12658
12659   /* If unification failed, we're done.  */
12660   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
12661              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
12662     return NULL_TREE;
12663
12664   return arg;
12665 }
12666
12667 /* Given a template type PARM and a class type ARG, find the unique
12668    base type in ARG that is an instance of PARM.  We do not examine
12669    ARG itself; only its base-classes.  If there is not exactly one
12670    appropriate base class, return NULL_TREE.  PARM may be the type of
12671    a partial specialization, as well as a plain template type.  Used
12672    by unify.  */
12673
12674 static tree
12675 get_template_base (tree tparms, tree targs, tree parm, tree arg)
12676 {
12677   tree rval = NULL_TREE;
12678   tree binfo;
12679
12680   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
12681
12682   binfo = TYPE_BINFO (complete_type (arg));
12683   if (!binfo)
12684     /* The type could not be completed.  */
12685     return NULL_TREE;
12686
12687   /* Walk in inheritance graph order.  The search order is not
12688      important, and this avoids multiple walks of virtual bases.  */
12689   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
12690     {
12691       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
12692
12693       if (r)
12694         {
12695           /* If there is more than one satisfactory baseclass, then:
12696
12697                [temp.deduct.call]
12698
12699               If they yield more than one possible deduced A, the type
12700               deduction fails.
12701
12702              applies.  */
12703           if (rval && !same_type_p (r, rval))
12704             return NULL_TREE;
12705
12706           rval = r;
12707         }
12708     }
12709
12710   return rval;
12711 }
12712
12713 /* Returns the level of DECL, which declares a template parameter.  */
12714
12715 static int
12716 template_decl_level (tree decl)
12717 {
12718   switch (TREE_CODE (decl))
12719     {
12720     case TYPE_DECL:
12721     case TEMPLATE_DECL:
12722       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
12723
12724     case PARM_DECL:
12725       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
12726
12727     default:
12728       gcc_unreachable ();
12729     }
12730   return 0;
12731 }
12732
12733 /* Decide whether ARG can be unified with PARM, considering only the
12734    cv-qualifiers of each type, given STRICT as documented for unify.
12735    Returns nonzero iff the unification is OK on that basis.  */
12736
12737 static int
12738 check_cv_quals_for_unify (int strict, tree arg, tree parm)
12739 {
12740   int arg_quals = cp_type_quals (arg);
12741   int parm_quals = cp_type_quals (parm);
12742
12743   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12744       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12745     {
12746       /*  Although a CVR qualifier is ignored when being applied to a
12747           substituted template parameter ([8.3.2]/1 for example), that
12748           does not apply during deduction [14.8.2.4]/1, (even though
12749           that is not explicitly mentioned, [14.8.2.4]/9 indicates
12750           this).  Except when we're allowing additional CV qualifiers
12751           at the outer level [14.8.2.1]/3,1st bullet.  */
12752       if ((TREE_CODE (arg) == REFERENCE_TYPE
12753            || TREE_CODE (arg) == FUNCTION_TYPE
12754            || TREE_CODE (arg) == METHOD_TYPE)
12755           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
12756         return 0;
12757
12758       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
12759           && (parm_quals & TYPE_QUAL_RESTRICT))
12760         return 0;
12761     }
12762
12763   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12764       && (arg_quals & parm_quals) != parm_quals)
12765     return 0;
12766
12767   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
12768       && (parm_quals & arg_quals) != arg_quals)
12769     return 0;
12770
12771   return 1;
12772 }
12773
12774 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
12775 void 
12776 template_parm_level_and_index (tree parm, int* level, int* index)
12777 {
12778   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12779       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12780       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12781     {
12782       *index = TEMPLATE_TYPE_IDX (parm);
12783       *level = TEMPLATE_TYPE_LEVEL (parm);
12784     }
12785   else
12786     {
12787       *index = TEMPLATE_PARM_IDX (parm);
12788       *level = TEMPLATE_PARM_LEVEL (parm);
12789     }
12790 }
12791
12792 /* Unifies the remaining arguments in PACKED_ARGS with the pack
12793    expansion at the end of PACKED_PARMS. Returns 0 if the type
12794    deduction succeeds, 1 otherwise. STRICT is the same as in
12795    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
12796    call argument list. We'll need to adjust the arguments to make them
12797    types. SUBR tells us if this is from a recursive call to
12798    type_unification_real.  */
12799 int
12800 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
12801                       tree packed_args, int strict, bool call_args_p,
12802                       bool subr)
12803 {
12804   tree parm 
12805     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
12806   tree pattern = PACK_EXPANSION_PATTERN (parm);
12807   tree pack, packs = NULL_TREE;
12808   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
12809   int len = TREE_VEC_LENGTH (packed_args);
12810
12811   /* Determine the parameter packs we will be deducing from the
12812      pattern, and record their current deductions.  */
12813   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
12814        pack; pack = TREE_CHAIN (pack))
12815     {
12816       tree parm_pack = TREE_VALUE (pack);
12817       int idx, level;
12818
12819       /* Determine the index and level of this parameter pack.  */
12820       template_parm_level_and_index (parm_pack, &level, &idx);
12821
12822       /* Keep track of the parameter packs and their corresponding
12823          argument packs.  */
12824       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
12825       TREE_TYPE (packs) = make_tree_vec (len - start);
12826     }
12827   
12828   /* Loop through all of the arguments that have not yet been
12829      unified and unify each with the pattern.  */
12830   for (i = start; i < len; i++)
12831     {
12832       tree parm = pattern;
12833
12834       /* For each parameter pack, clear out the deduced value so that
12835          we can deduce it again.  */
12836       for (pack = packs; pack; pack = TREE_CHAIN (pack))
12837         {
12838           int idx, level;
12839           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12840
12841           TMPL_ARG (targs, level, idx) = NULL_TREE;
12842         }
12843
12844       /* Unify the pattern with the current argument.  */
12845       {
12846         tree arg = TREE_VEC_ELT (packed_args, i);
12847         tree arg_expr = NULL_TREE;
12848         int arg_strict = strict;
12849         bool skip_arg_p = false;
12850
12851         if (call_args_p)
12852           {
12853             int sub_strict;
12854
12855             /* This mirrors what we do in type_unification_real.  */
12856             switch (strict)
12857               {
12858               case DEDUCE_CALL:
12859                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
12860                               | UNIFY_ALLOW_MORE_CV_QUAL
12861                               | UNIFY_ALLOW_DERIVED);
12862                 break;
12863                 
12864               case DEDUCE_CONV:
12865                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12866                 break;
12867                 
12868               case DEDUCE_EXACT:
12869                 sub_strict = UNIFY_ALLOW_NONE;
12870                 break;
12871                 
12872               default:
12873                 gcc_unreachable ();
12874               }
12875
12876             if (!TYPE_P (arg))
12877               {
12878                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12879                 if (type_unknown_p (arg))
12880                   {
12881                     /* [temp.deduct.type] A template-argument can be
12882                        deduced from a pointer to function or pointer
12883                        to member function argument if the set of
12884                        overloaded functions does not contain function
12885                        templates and at most one of a set of
12886                        overloaded functions provides a unique
12887                        match.  */
12888
12889                     if (resolve_overloaded_unification
12890                         (tparms, targs, parm, arg, strict, sub_strict)
12891                         != 0)
12892                       return 1;
12893                     skip_arg_p = true;
12894                   }
12895
12896                 if (!skip_arg_p)
12897                   {
12898                     arg_expr = arg;
12899                     arg = unlowered_expr_type (arg);
12900                     if (arg == error_mark_node)
12901                       return 1;
12902                   }
12903               }
12904       
12905             arg_strict = sub_strict;
12906
12907             if (!subr)
12908               arg_strict |= 
12909                 maybe_adjust_types_for_deduction (strict, &parm, &arg, 
12910                                                   arg_expr);
12911           }
12912
12913         if (!skip_arg_p)
12914           {
12915             if (unify (tparms, targs, parm, arg, arg_strict))
12916               return 1;
12917           }
12918       }
12919
12920       /* For each parameter pack, collect the deduced value.  */
12921       for (pack = packs; pack; pack = TREE_CHAIN (pack))
12922         {
12923           int idx, level;
12924           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12925
12926           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
12927             TMPL_ARG (targs, level, idx);
12928         }
12929     }
12930
12931   /* Verify that the results of unification with the parameter packs
12932      produce results consistent with what we've seen before, and make
12933      the deduced argument packs available.  */
12934   for (pack = packs; pack; pack = TREE_CHAIN (pack))
12935     {
12936       tree old_pack = TREE_VALUE (pack);
12937       tree new_args = TREE_TYPE (pack);
12938       int i, len = TREE_VEC_LENGTH (new_args);
12939       bool nondeduced_p = false;
12940
12941       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
12942          actually deduce anything.  */
12943       for (i = 0; i < len && !nondeduced_p; ++i)
12944         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
12945           nondeduced_p = true;
12946       if (nondeduced_p)
12947         continue;
12948
12949       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
12950         {
12951           /* Prepend the explicit arguments onto NEW_ARGS.  */
12952           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
12953           tree old_args = new_args;
12954           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
12955           int len = explicit_len + TREE_VEC_LENGTH (old_args);
12956
12957           /* Copy the explicit arguments.  */
12958           new_args = make_tree_vec (len);
12959           for (i = 0; i < explicit_len; i++)
12960             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
12961
12962           /* Copy the deduced arguments.  */
12963           for (; i < len; i++)
12964             TREE_VEC_ELT (new_args, i) =
12965               TREE_VEC_ELT (old_args, i - explicit_len);
12966         }
12967
12968       if (!old_pack)
12969         {
12970           tree result;
12971           int idx, level;
12972           
12973           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12974
12975           /* Build the deduced *_ARGUMENT_PACK.  */
12976           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
12977             {
12978               result = make_node (NONTYPE_ARGUMENT_PACK);
12979               TREE_TYPE (result) = 
12980                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
12981               TREE_CONSTANT (result) = 1;
12982             }
12983           else
12984             result = make_node (TYPE_ARGUMENT_PACK);
12985
12986           SET_ARGUMENT_PACK_ARGS (result, new_args);
12987
12988           /* Note the deduced argument packs for this parameter
12989              pack.  */
12990           TMPL_ARG (targs, level, idx) = result;
12991         }
12992       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
12993                && (ARGUMENT_PACK_ARGS (old_pack) 
12994                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
12995         {
12996           /* We only had the explicitly-provided arguments before, but
12997              now we have a complete set of arguments.  */
12998           int idx, level;
12999           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13000           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13001
13002           /* Keep the original deduced argument pack.  */
13003           TMPL_ARG (targs, level, idx) = old_pack;
13004
13005           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
13006           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
13007           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
13008         }
13009       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
13010                                     new_args))
13011         /* Inconsistent unification of this parameter pack.  */
13012         return 1;
13013       else
13014         {
13015           int idx, level;
13016           
13017           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13018
13019           /* Keep the original deduced argument pack.  */
13020           TMPL_ARG (targs, level, idx) = old_pack;
13021         }
13022     }
13023
13024   return 0;
13025 }
13026
13027 /* Deduce the value of template parameters.  TPARMS is the (innermost)
13028    set of template parameters to a template.  TARGS is the bindings
13029    for those template parameters, as determined thus far; TARGS may
13030    include template arguments for outer levels of template parameters
13031    as well.  PARM is a parameter to a template function, or a
13032    subcomponent of that parameter; ARG is the corresponding argument.
13033    This function attempts to match PARM with ARG in a manner
13034    consistent with the existing assignments in TARGS.  If more values
13035    are deduced, then TARGS is updated.
13036
13037    Returns 0 if the type deduction succeeds, 1 otherwise.  The
13038    parameter STRICT is a bitwise or of the following flags:
13039
13040      UNIFY_ALLOW_NONE:
13041        Require an exact match between PARM and ARG.
13042      UNIFY_ALLOW_MORE_CV_QUAL:
13043        Allow the deduced ARG to be more cv-qualified (by qualification
13044        conversion) than ARG.
13045      UNIFY_ALLOW_LESS_CV_QUAL:
13046        Allow the deduced ARG to be less cv-qualified than ARG.
13047      UNIFY_ALLOW_DERIVED:
13048        Allow the deduced ARG to be a template base class of ARG,
13049        or a pointer to a template base class of the type pointed to by
13050        ARG.
13051      UNIFY_ALLOW_INTEGER:
13052        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
13053        case for more information.
13054      UNIFY_ALLOW_OUTER_LEVEL:
13055        This is the outermost level of a deduction. Used to determine validity
13056        of qualification conversions. A valid qualification conversion must
13057        have const qualified pointers leading up to the inner type which
13058        requires additional CV quals, except at the outer level, where const
13059        is not required [conv.qual]. It would be normal to set this flag in
13060        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
13061      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
13062        This is the outermost level of a deduction, and PARM can be more CV
13063        qualified at this point.
13064      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
13065        This is the outermost level of a deduction, and PARM can be less CV
13066        qualified at this point.  */
13067
13068 static int
13069 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
13070 {
13071   int idx;
13072   tree targ;
13073   tree tparm;
13074   int strict_in = strict;
13075
13076   /* I don't think this will do the right thing with respect to types.
13077      But the only case I've seen it in so far has been array bounds, where
13078      signedness is the only information lost, and I think that will be
13079      okay.  */
13080   while (TREE_CODE (parm) == NOP_EXPR)
13081     parm = TREE_OPERAND (parm, 0);
13082
13083   if (arg == error_mark_node)
13084     return 1;
13085   if (arg == unknown_type_node
13086       || arg == init_list_type_node)
13087     /* We can't deduce anything from this, but we might get all the
13088        template args from other function args.  */
13089     return 0;
13090
13091   /* If PARM uses template parameters, then we can't bail out here,
13092      even if ARG == PARM, since we won't record unifications for the
13093      template parameters.  We might need them if we're trying to
13094      figure out which of two things is more specialized.  */
13095   if (arg == parm && !uses_template_parms (parm))
13096     return 0;
13097
13098   /* Handle init lists early, so the rest of the function can assume
13099      we're dealing with a type. */
13100   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
13101     {
13102       tree elt, elttype;
13103       unsigned i;
13104
13105       if (!is_std_init_list (parm))
13106         /* We can only deduce from an initializer list argument if the
13107            parameter is std::initializer_list; otherwise this is a
13108            non-deduced context. */
13109         return 0;
13110
13111       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
13112
13113       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
13114         {
13115           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
13116             elt = TREE_TYPE (elt);
13117           if (unify (tparms, targs, elttype, elt, UNIFY_ALLOW_NONE))
13118             return 1;
13119         }
13120       return 0;
13121     }
13122
13123   /* Immediately reject some pairs that won't unify because of
13124      cv-qualification mismatches.  */
13125   if (TREE_CODE (arg) == TREE_CODE (parm)
13126       && TYPE_P (arg)
13127       /* It is the elements of the array which hold the cv quals of an array
13128          type, and the elements might be template type parms. We'll check
13129          when we recurse.  */
13130       && TREE_CODE (arg) != ARRAY_TYPE
13131       /* We check the cv-qualifiers when unifying with template type
13132          parameters below.  We want to allow ARG `const T' to unify with
13133          PARM `T' for example, when computing which of two templates
13134          is more specialized, for example.  */
13135       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
13136       && !check_cv_quals_for_unify (strict_in, arg, parm))
13137     return 1;
13138
13139   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
13140       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
13141     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
13142   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
13143   strict &= ~UNIFY_ALLOW_DERIVED;
13144   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13145   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
13146
13147   switch (TREE_CODE (parm))
13148     {
13149     case TYPENAME_TYPE:
13150     case SCOPE_REF:
13151     case UNBOUND_CLASS_TEMPLATE:
13152       /* In a type which contains a nested-name-specifier, template
13153          argument values cannot be deduced for template parameters used
13154          within the nested-name-specifier.  */
13155       return 0;
13156
13157     case TEMPLATE_TYPE_PARM:
13158     case TEMPLATE_TEMPLATE_PARM:
13159     case BOUND_TEMPLATE_TEMPLATE_PARM:
13160       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13161       if (tparm == error_mark_node)
13162         return 1;
13163
13164       if (TEMPLATE_TYPE_LEVEL (parm)
13165           != template_decl_level (tparm))
13166         /* The PARM is not one we're trying to unify.  Just check
13167            to see if it matches ARG.  */
13168         return (TREE_CODE (arg) == TREE_CODE (parm)
13169                 && same_type_p (parm, arg)) ? 0 : 1;
13170       idx = TEMPLATE_TYPE_IDX (parm);
13171       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13172       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
13173
13174       /* Check for mixed types and values.  */
13175       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13176            && TREE_CODE (tparm) != TYPE_DECL)
13177           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13178               && TREE_CODE (tparm) != TEMPLATE_DECL))
13179         return 1;
13180
13181       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13182         {
13183           /* ARG must be constructed from a template class or a template
13184              template parameter.  */
13185           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
13186               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
13187             return 1;
13188
13189           {
13190             tree parmvec = TYPE_TI_ARGS (parm);
13191             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
13192             tree parm_parms 
13193               = DECL_INNERMOST_TEMPLATE_PARMS
13194                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
13195             int i, len;
13196             int parm_variadic_p = 0;
13197
13198             /* The resolution to DR150 makes clear that default
13199                arguments for an N-argument may not be used to bind T
13200                to a template template parameter with fewer than N
13201                parameters.  It is not safe to permit the binding of
13202                default arguments as an extension, as that may change
13203                the meaning of a conforming program.  Consider:
13204
13205                   struct Dense { static const unsigned int dim = 1; };
13206
13207                   template <template <typename> class View,
13208                             typename Block>
13209                   void operator+(float, View<Block> const&);
13210
13211                   template <typename Block,
13212                             unsigned int Dim = Block::dim>
13213                   struct Lvalue_proxy { operator float() const; };
13214
13215                   void
13216                   test_1d (void) {
13217                     Lvalue_proxy<Dense> p;
13218                     float b;
13219                     b + p;
13220                   }
13221
13222               Here, if Lvalue_proxy is permitted to bind to View, then
13223               the global operator+ will be used; if they are not, the
13224               Lvalue_proxy will be converted to float.  */
13225             if (coerce_template_parms (parm_parms,
13226                                        argvec,
13227                                        TYPE_TI_TEMPLATE (parm),
13228                                        tf_none,
13229                                        /*require_all_args=*/true,
13230                                        /*use_default_args=*/false)
13231                 == error_mark_node)
13232               return 1;
13233
13234             /* Deduce arguments T, i from TT<T> or TT<i>.
13235                We check each element of PARMVEC and ARGVEC individually
13236                rather than the whole TREE_VEC since they can have
13237                different number of elements.  */
13238
13239             parmvec = expand_template_argument_pack (parmvec);
13240             argvec = expand_template_argument_pack (argvec);
13241
13242             len = TREE_VEC_LENGTH (parmvec);
13243
13244             /* Check if the parameters end in a pack, making them
13245                variadic.  */
13246             if (len > 0
13247                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
13248               parm_variadic_p = 1;
13249             
13250             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
13251               return 1;
13252
13253              for (i = 0; i < len - parm_variadic_p; ++i)
13254               {
13255                 if (unify (tparms, targs,
13256                            TREE_VEC_ELT (parmvec, i),
13257                            TREE_VEC_ELT (argvec, i),
13258                            UNIFY_ALLOW_NONE))
13259                   return 1;
13260               }
13261
13262             if (parm_variadic_p
13263                 && unify_pack_expansion (tparms, targs,
13264                                          parmvec, argvec,
13265                                          UNIFY_ALLOW_NONE,
13266                                          /*call_args_p=*/false,
13267                                          /*subr=*/false))
13268               return 1;
13269           }
13270           arg = TYPE_TI_TEMPLATE (arg);
13271
13272           /* Fall through to deduce template name.  */
13273         }
13274
13275       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13276           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13277         {
13278           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
13279
13280           /* Simple cases: Value already set, does match or doesn't.  */
13281           if (targ != NULL_TREE && template_args_equal (targ, arg))
13282             return 0;
13283           else if (targ)
13284             return 1;
13285         }
13286       else
13287         {
13288           /* If PARM is `const T' and ARG is only `int', we don't have
13289              a match unless we are allowing additional qualification.
13290              If ARG is `const int' and PARM is just `T' that's OK;
13291              that binds `const int' to `T'.  */
13292           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
13293                                          arg, parm))
13294             return 1;
13295
13296           /* Consider the case where ARG is `const volatile int' and
13297              PARM is `const T'.  Then, T should be `volatile int'.  */
13298           arg = cp_build_qualified_type_real
13299             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
13300           if (arg == error_mark_node)
13301             return 1;
13302
13303           /* Simple cases: Value already set, does match or doesn't.  */
13304           if (targ != NULL_TREE && same_type_p (targ, arg))
13305             return 0;
13306           else if (targ)
13307             return 1;
13308
13309           /* Make sure that ARG is not a variable-sized array.  (Note
13310              that were talking about variable-sized arrays (like
13311              `int[n]'), rather than arrays of unknown size (like
13312              `int[]').)  We'll get very confused by such a type since
13313              the bound of the array will not be computable in an
13314              instantiation.  Besides, such types are not allowed in
13315              ISO C++, so we can do as we please here.  */
13316           if (variably_modified_type_p (arg, NULL_TREE))
13317             return 1;
13318         }
13319
13320       /* If ARG is a parameter pack or an expansion, we cannot unify
13321          against it unless PARM is also a parameter pack.  */
13322       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13323           && !template_parameter_pack_p (parm))
13324         return 1;
13325
13326       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13327       return 0;
13328
13329     case TEMPLATE_PARM_INDEX:
13330       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13331       if (tparm == error_mark_node)
13332         return 1;
13333
13334       if (TEMPLATE_PARM_LEVEL (parm)
13335           != template_decl_level (tparm))
13336         /* The PARM is not one we're trying to unify.  Just check
13337            to see if it matches ARG.  */
13338         return !(TREE_CODE (arg) == TREE_CODE (parm)
13339                  && cp_tree_equal (parm, arg));
13340
13341       idx = TEMPLATE_PARM_IDX (parm);
13342       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13343
13344       if (targ)
13345         return !cp_tree_equal (targ, arg);
13346
13347       /* [temp.deduct.type] If, in the declaration of a function template
13348          with a non-type template-parameter, the non-type
13349          template-parameter is used in an expression in the function
13350          parameter-list and, if the corresponding template-argument is
13351          deduced, the template-argument type shall match the type of the
13352          template-parameter exactly, except that a template-argument
13353          deduced from an array bound may be of any integral type.
13354          The non-type parameter might use already deduced type parameters.  */
13355       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
13356       if (!TREE_TYPE (arg))
13357         /* Template-parameter dependent expression.  Just accept it for now.
13358            It will later be processed in convert_template_argument.  */
13359         ;
13360       else if (same_type_p (TREE_TYPE (arg), tparm))
13361         /* OK */;
13362       else if ((strict & UNIFY_ALLOW_INTEGER)
13363                && (TREE_CODE (tparm) == INTEGER_TYPE
13364                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
13365         /* Convert the ARG to the type of PARM; the deduced non-type
13366            template argument must exactly match the types of the
13367            corresponding parameter.  */
13368         arg = fold (build_nop (TREE_TYPE (parm), arg));
13369       else if (uses_template_parms (tparm))
13370         /* We haven't deduced the type of this parameter yet.  Try again
13371            later.  */
13372         return 0;
13373       else
13374         return 1;
13375
13376       /* If ARG is a parameter pack or an expansion, we cannot unify
13377          against it unless PARM is also a parameter pack.  */
13378       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13379           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
13380         return 1;
13381
13382       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13383       return 0;
13384
13385     case PTRMEM_CST:
13386      {
13387         /* A pointer-to-member constant can be unified only with
13388          another constant.  */
13389       if (TREE_CODE (arg) != PTRMEM_CST)
13390         return 1;
13391
13392       /* Just unify the class member. It would be useless (and possibly
13393          wrong, depending on the strict flags) to unify also
13394          PTRMEM_CST_CLASS, because we want to be sure that both parm and
13395          arg refer to the same variable, even if through different
13396          classes. For instance:
13397
13398          struct A { int x; };
13399          struct B : A { };
13400
13401          Unification of &A::x and &B::x must succeed.  */
13402       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
13403                     PTRMEM_CST_MEMBER (arg), strict);
13404      }
13405
13406     case POINTER_TYPE:
13407       {
13408         if (TREE_CODE (arg) != POINTER_TYPE)
13409           return 1;
13410
13411         /* [temp.deduct.call]
13412
13413            A can be another pointer or pointer to member type that can
13414            be converted to the deduced A via a qualification
13415            conversion (_conv.qual_).
13416
13417            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
13418            This will allow for additional cv-qualification of the
13419            pointed-to types if appropriate.  */
13420
13421         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
13422           /* The derived-to-base conversion only persists through one
13423              level of pointers.  */
13424           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
13425
13426         return unify (tparms, targs, TREE_TYPE (parm),
13427                       TREE_TYPE (arg), strict);
13428       }
13429
13430     case REFERENCE_TYPE:
13431       if (TREE_CODE (arg) != REFERENCE_TYPE)
13432         return 1;
13433       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13434                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13435
13436     case ARRAY_TYPE:
13437       if (TREE_CODE (arg) != ARRAY_TYPE)
13438         return 1;
13439       if ((TYPE_DOMAIN (parm) == NULL_TREE)
13440           != (TYPE_DOMAIN (arg) == NULL_TREE))
13441         return 1;
13442       if (TYPE_DOMAIN (parm) != NULL_TREE)
13443         {
13444           tree parm_max;
13445           tree arg_max;
13446           bool parm_cst;
13447           bool arg_cst;
13448
13449           /* Our representation of array types uses "N - 1" as the
13450              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
13451              not an integer constant.  We cannot unify arbitrarily
13452              complex expressions, so we eliminate the MINUS_EXPRs
13453              here.  */
13454           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
13455           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
13456           if (!parm_cst)
13457             {
13458               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
13459               parm_max = TREE_OPERAND (parm_max, 0);
13460             }
13461           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
13462           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
13463           if (!arg_cst)
13464             {
13465               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
13466                  trying to unify the type of a variable with the type
13467                  of a template parameter.  For example:
13468
13469                    template <unsigned int N>
13470                    void f (char (&) [N]);
13471                    int g(); 
13472                    void h(int i) {
13473                      char a[g(i)];
13474                      f(a); 
13475                    }
13476
13477                 Here, the type of the ARG will be "int [g(i)]", and
13478                 may be a SAVE_EXPR, etc.  */
13479               if (TREE_CODE (arg_max) != MINUS_EXPR)
13480                 return 1;
13481               arg_max = TREE_OPERAND (arg_max, 0);
13482             }
13483
13484           /* If only one of the bounds used a MINUS_EXPR, compensate
13485              by adding one to the other bound.  */
13486           if (parm_cst && !arg_cst)
13487             parm_max = fold_build2 (PLUS_EXPR,
13488                                     integer_type_node,
13489                                     parm_max,
13490                                     integer_one_node);
13491           else if (arg_cst && !parm_cst)
13492             arg_max = fold_build2 (PLUS_EXPR,
13493                                    integer_type_node,
13494                                    arg_max,
13495                                    integer_one_node);
13496
13497           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
13498             return 1;
13499         }
13500       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13501                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13502
13503     case REAL_TYPE:
13504     case COMPLEX_TYPE:
13505     case VECTOR_TYPE:
13506     case INTEGER_TYPE:
13507     case BOOLEAN_TYPE:
13508     case ENUMERAL_TYPE:
13509     case VOID_TYPE:
13510       if (TREE_CODE (arg) != TREE_CODE (parm))
13511         return 1;
13512
13513       /* We have already checked cv-qualification at the top of the
13514          function.  */
13515       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
13516         return 1;
13517
13518       /* As far as unification is concerned, this wins.  Later checks
13519          will invalidate it if necessary.  */
13520       return 0;
13521
13522       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
13523       /* Type INTEGER_CST can come from ordinary constant template args.  */
13524     case INTEGER_CST:
13525       while (TREE_CODE (arg) == NOP_EXPR)
13526         arg = TREE_OPERAND (arg, 0);
13527
13528       if (TREE_CODE (arg) != INTEGER_CST)
13529         return 1;
13530       return !tree_int_cst_equal (parm, arg);
13531
13532     case TREE_VEC:
13533       {
13534         int i;
13535         if (TREE_CODE (arg) != TREE_VEC)
13536           return 1;
13537         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
13538           return 1;
13539         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
13540           if (unify (tparms, targs,
13541                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
13542                      UNIFY_ALLOW_NONE))
13543             return 1;
13544         return 0;
13545       }
13546
13547     case RECORD_TYPE:
13548     case UNION_TYPE:
13549       if (TREE_CODE (arg) != TREE_CODE (parm))
13550         return 1;
13551
13552       if (TYPE_PTRMEMFUNC_P (parm))
13553         {
13554           if (!TYPE_PTRMEMFUNC_P (arg))
13555             return 1;
13556
13557           return unify (tparms, targs,
13558                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
13559                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
13560                         strict);
13561         }
13562
13563       if (CLASSTYPE_TEMPLATE_INFO (parm))
13564         {
13565           tree t = NULL_TREE;
13566
13567           if (strict_in & UNIFY_ALLOW_DERIVED)
13568             {
13569               /* First, we try to unify the PARM and ARG directly.  */
13570               t = try_class_unification (tparms, targs,
13571                                          parm, arg);
13572
13573               if (!t)
13574                 {
13575                   /* Fallback to the special case allowed in
13576                      [temp.deduct.call]:
13577
13578                        If P is a class, and P has the form
13579                        template-id, then A can be a derived class of
13580                        the deduced A.  Likewise, if P is a pointer to
13581                        a class of the form template-id, A can be a
13582                        pointer to a derived class pointed to by the
13583                        deduced A.  */
13584                   t = get_template_base (tparms, targs, parm, arg);
13585
13586                   if (!t)
13587                     return 1;
13588                 }
13589             }
13590           else if (CLASSTYPE_TEMPLATE_INFO (arg)
13591                    && (CLASSTYPE_TI_TEMPLATE (parm)
13592                        == CLASSTYPE_TI_TEMPLATE (arg)))
13593             /* Perhaps PARM is something like S<U> and ARG is S<int>.
13594                Then, we should unify `int' and `U'.  */
13595             t = arg;
13596           else
13597             /* There's no chance of unification succeeding.  */
13598             return 1;
13599
13600           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
13601                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
13602         }
13603       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
13604         return 1;
13605       return 0;
13606
13607     case METHOD_TYPE:
13608     case FUNCTION_TYPE:
13609       if (TREE_CODE (arg) != TREE_CODE (parm))
13610         return 1;
13611
13612       /* CV qualifications for methods can never be deduced, they must
13613          match exactly.  We need to check them explicitly here,
13614          because type_unification_real treats them as any other
13615          cv-qualified parameter.  */
13616       if (TREE_CODE (parm) == METHOD_TYPE
13617           && (!check_cv_quals_for_unify
13618               (UNIFY_ALLOW_NONE,
13619                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
13620                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
13621         return 1;
13622
13623       if (unify (tparms, targs, TREE_TYPE (parm),
13624                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
13625         return 1;
13626       return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
13627                                     TYPE_ARG_TYPES (arg), 1, DEDUCE_EXACT,
13628                                     LOOKUP_NORMAL);
13629
13630     case OFFSET_TYPE:
13631       /* Unify a pointer to member with a pointer to member function, which
13632          deduces the type of the member as a function type. */
13633       if (TYPE_PTRMEMFUNC_P (arg))
13634         {
13635           tree method_type;
13636           tree fntype;
13637           cp_cv_quals cv_quals;
13638
13639           /* Check top-level cv qualifiers */
13640           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
13641             return 1;
13642
13643           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13644                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
13645             return 1;
13646
13647           /* Determine the type of the function we are unifying against. */
13648           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
13649           fntype =
13650             build_function_type (TREE_TYPE (method_type),
13651                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
13652
13653           /* Extract the cv-qualifiers of the member function from the
13654              implicit object parameter and place them on the function
13655              type to be restored later. */
13656           cv_quals =
13657             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
13658           fntype = build_qualified_type (fntype, cv_quals);
13659           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
13660         }
13661
13662       if (TREE_CODE (arg) != OFFSET_TYPE)
13663         return 1;
13664       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13665                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
13666         return 1;
13667       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13668                     strict);
13669
13670     case CONST_DECL:
13671       if (DECL_TEMPLATE_PARM_P (parm))
13672         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
13673       if (arg != integral_constant_value (parm))
13674         return 1;
13675       return 0;
13676
13677     case FIELD_DECL:
13678     case TEMPLATE_DECL:
13679       /* Matched cases are handled by the ARG == PARM test above.  */
13680       return 1;
13681
13682     case TYPE_ARGUMENT_PACK:
13683     case NONTYPE_ARGUMENT_PACK:
13684       {
13685         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
13686         tree packed_args = ARGUMENT_PACK_ARGS (arg);
13687         int i, len = TREE_VEC_LENGTH (packed_parms);
13688         int argslen = TREE_VEC_LENGTH (packed_args);
13689         int parm_variadic_p = 0;
13690
13691         for (i = 0; i < len; ++i)
13692           {
13693             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
13694               {
13695                 if (i == len - 1)
13696                   /* We can unify against something with a trailing
13697                      parameter pack.  */
13698                   parm_variadic_p = 1;
13699                 else
13700                   /* Since there is something following the pack
13701                      expansion, we cannot unify this template argument
13702                      list.  */
13703                   return 0;
13704               }
13705           }
13706           
13707
13708         /* If we don't have enough arguments to satisfy the parameters
13709            (not counting the pack expression at the end), or we have
13710            too many arguments for a parameter list that doesn't end in
13711            a pack expression, we can't unify.  */
13712         if (argslen < (len - parm_variadic_p)
13713             || (argslen > len && !parm_variadic_p))
13714           return 1;
13715
13716         /* Unify all of the parameters that precede the (optional)
13717            pack expression.  */
13718         for (i = 0; i < len - parm_variadic_p; ++i)
13719           {
13720             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
13721                        TREE_VEC_ELT (packed_args, i), strict))
13722               return 1;
13723           }
13724
13725         if (parm_variadic_p)
13726           return unify_pack_expansion (tparms, targs, 
13727                                        packed_parms, packed_args,
13728                                        strict, /*call_args_p=*/false,
13729                                        /*subr=*/false);
13730         return 0;
13731       }
13732
13733       break;
13734
13735     case TYPEOF_TYPE:
13736     case DECLTYPE_TYPE:
13737       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
13738          nodes.  */
13739       return 0;
13740
13741     case ERROR_MARK:
13742       /* Unification fails if we hit an error node.  */
13743       return 1;
13744
13745     default:
13746       gcc_assert (EXPR_P (parm));
13747
13748       /* We must be looking at an expression.  This can happen with
13749          something like:
13750
13751            template <int I>
13752            void foo(S<I>, S<I + 2>);
13753
13754          This is a "nondeduced context":
13755
13756            [deduct.type]
13757
13758            The nondeduced contexts are:
13759
13760            --A type that is a template-id in which one or more of
13761              the template-arguments is an expression that references
13762              a template-parameter.
13763
13764          In these cases, we assume deduction succeeded, but don't
13765          actually infer any unifications.  */
13766
13767       if (!uses_template_parms (parm)
13768           && !template_args_equal (parm, arg))
13769         return 1;
13770       else
13771         return 0;
13772     }
13773 }
13774 \f
13775 /* Note that DECL can be defined in this translation unit, if
13776    required.  */
13777
13778 static void
13779 mark_definable (tree decl)
13780 {
13781   tree clone;
13782   DECL_NOT_REALLY_EXTERN (decl) = 1;
13783   FOR_EACH_CLONE (clone, decl)
13784     DECL_NOT_REALLY_EXTERN (clone) = 1;
13785 }
13786
13787 /* Called if RESULT is explicitly instantiated, or is a member of an
13788    explicitly instantiated class.  */
13789
13790 void
13791 mark_decl_instantiated (tree result, int extern_p)
13792 {
13793   SET_DECL_EXPLICIT_INSTANTIATION (result);
13794
13795   /* If this entity has already been written out, it's too late to
13796      make any modifications.  */
13797   if (TREE_ASM_WRITTEN (result))
13798     return;
13799
13800   if (TREE_CODE (result) != FUNCTION_DECL)
13801     /* The TREE_PUBLIC flag for function declarations will have been
13802        set correctly by tsubst.  */
13803     TREE_PUBLIC (result) = 1;
13804
13805   /* This might have been set by an earlier implicit instantiation.  */
13806   DECL_COMDAT (result) = 0;
13807
13808   if (extern_p)
13809     DECL_NOT_REALLY_EXTERN (result) = 0;
13810   else
13811     {
13812       mark_definable (result);
13813       /* Always make artificials weak.  */
13814       if (DECL_ARTIFICIAL (result) && flag_weak)
13815         comdat_linkage (result);
13816       /* For WIN32 we also want to put explicit instantiations in
13817          linkonce sections.  */
13818       else if (TREE_PUBLIC (result))
13819         maybe_make_one_only (result);
13820     }
13821
13822   /* If EXTERN_P, then this function will not be emitted -- unless
13823      followed by an explicit instantiation, at which point its linkage
13824      will be adjusted.  If !EXTERN_P, then this function will be
13825      emitted here.  In neither circumstance do we want
13826      import_export_decl to adjust the linkage.  */
13827   DECL_INTERFACE_KNOWN (result) = 1;
13828 }
13829
13830 /* Given two function templates PAT1 and PAT2, return:
13831
13832    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
13833    -1 if PAT2 is more specialized than PAT1.
13834    0 if neither is more specialized.
13835
13836    LEN indicates the number of parameters we should consider
13837    (defaulted parameters should not be considered).
13838
13839    The 1998 std underspecified function template partial ordering, and
13840    DR214 addresses the issue.  We take pairs of arguments, one from
13841    each of the templates, and deduce them against each other.  One of
13842    the templates will be more specialized if all the *other*
13843    template's arguments deduce against its arguments and at least one
13844    of its arguments *does* *not* deduce against the other template's
13845    corresponding argument.  Deduction is done as for class templates.
13846    The arguments used in deduction have reference and top level cv
13847    qualifiers removed.  Iff both arguments were originally reference
13848    types *and* deduction succeeds in both directions, the template
13849    with the more cv-qualified argument wins for that pairing (if
13850    neither is more cv-qualified, they both are equal).  Unlike regular
13851    deduction, after all the arguments have been deduced in this way,
13852    we do *not* verify the deduced template argument values can be
13853    substituted into non-deduced contexts, nor do we have to verify
13854    that all template arguments have been deduced.  */
13855
13856 int
13857 more_specialized_fn (tree pat1, tree pat2, int len)
13858 {
13859   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
13860   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
13861   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
13862   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
13863   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
13864   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
13865   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
13866   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
13867   int better1 = 0;
13868   int better2 = 0;
13869
13870   /* Remove the this parameter from non-static member functions.  If
13871      one is a non-static member function and the other is not a static
13872      member function, remove the first parameter from that function
13873      also.  This situation occurs for operator functions where we
13874      locate both a member function (with this pointer) and non-member
13875      operator (with explicit first operand).  */
13876   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
13877     {
13878       len--; /* LEN is the number of significant arguments for DECL1 */
13879       args1 = TREE_CHAIN (args1);
13880       if (!DECL_STATIC_FUNCTION_P (decl2))
13881         args2 = TREE_CHAIN (args2);
13882     }
13883   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
13884     {
13885       args2 = TREE_CHAIN (args2);
13886       if (!DECL_STATIC_FUNCTION_P (decl1))
13887         {
13888           len--;
13889           args1 = TREE_CHAIN (args1);
13890         }
13891     }
13892
13893   /* If only one is a conversion operator, they are unordered.  */
13894   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
13895     return 0;
13896
13897   /* Consider the return type for a conversion function */
13898   if (DECL_CONV_FN_P (decl1))
13899     {
13900       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
13901       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
13902       len++;
13903     }
13904
13905   processing_template_decl++;
13906
13907   while (len--
13908          /* Stop when an ellipsis is seen.  */
13909          && args1 != NULL_TREE && args2 != NULL_TREE)
13910     {
13911       tree arg1 = TREE_VALUE (args1);
13912       tree arg2 = TREE_VALUE (args2);
13913       int deduce1, deduce2;
13914       int quals1 = -1;
13915       int quals2 = -1;
13916
13917       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
13918           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
13919         {
13920           /* When both arguments are pack expansions, we need only
13921              unify the patterns themselves.  */
13922           arg1 = PACK_EXPANSION_PATTERN (arg1);
13923           arg2 = PACK_EXPANSION_PATTERN (arg2);
13924
13925           /* This is the last comparison we need to do.  */
13926           len = 0;
13927         }
13928
13929       if (TREE_CODE (arg1) == REFERENCE_TYPE)
13930         {
13931           arg1 = TREE_TYPE (arg1);
13932           quals1 = cp_type_quals (arg1);
13933         }
13934
13935       if (TREE_CODE (arg2) == REFERENCE_TYPE)
13936         {
13937           arg2 = TREE_TYPE (arg2);
13938           quals2 = cp_type_quals (arg2);
13939         }
13940
13941       if ((quals1 < 0) != (quals2 < 0))
13942         {
13943           /* Only of the args is a reference, see if we should apply
13944              array/function pointer decay to it.  This is not part of
13945              DR214, but is, IMHO, consistent with the deduction rules
13946              for the function call itself, and with our earlier
13947              implementation of the underspecified partial ordering
13948              rules.  (nathan).  */
13949           if (quals1 >= 0)
13950             {
13951               switch (TREE_CODE (arg1))
13952                 {
13953                 case ARRAY_TYPE:
13954                   arg1 = TREE_TYPE (arg1);
13955                   /* FALLTHROUGH. */
13956                 case FUNCTION_TYPE:
13957                   arg1 = build_pointer_type (arg1);
13958                   break;
13959
13960                 default:
13961                   break;
13962                 }
13963             }
13964           else
13965             {
13966               switch (TREE_CODE (arg2))
13967                 {
13968                 case ARRAY_TYPE:
13969                   arg2 = TREE_TYPE (arg2);
13970                   /* FALLTHROUGH. */
13971                 case FUNCTION_TYPE:
13972                   arg2 = build_pointer_type (arg2);
13973                   break;
13974
13975                 default:
13976                   break;
13977                 }
13978             }
13979         }
13980
13981       arg1 = TYPE_MAIN_VARIANT (arg1);
13982       arg2 = TYPE_MAIN_VARIANT (arg2);
13983
13984       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
13985         {
13986           int i, len2 = list_length (args2);
13987           tree parmvec = make_tree_vec (1);
13988           tree argvec = make_tree_vec (len2);
13989           tree ta = args2;
13990
13991           /* Setup the parameter vector, which contains only ARG1.  */
13992           TREE_VEC_ELT (parmvec, 0) = arg1;
13993
13994           /* Setup the argument vector, which contains the remaining
13995              arguments.  */
13996           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
13997             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
13998
13999           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
14000                                            argvec, UNIFY_ALLOW_NONE, 
14001                                            /*call_args_p=*/false, 
14002                                            /*subr=*/0);
14003
14004           /* We cannot deduce in the other direction, because ARG1 is
14005              a pack expansion but ARG2 is not.  */
14006           deduce2 = 0;
14007         }
14008       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14009         {
14010           int i, len1 = list_length (args1);
14011           tree parmvec = make_tree_vec (1);
14012           tree argvec = make_tree_vec (len1);
14013           tree ta = args1;
14014
14015           /* Setup the parameter vector, which contains only ARG1.  */
14016           TREE_VEC_ELT (parmvec, 0) = arg2;
14017
14018           /* Setup the argument vector, which contains the remaining
14019              arguments.  */
14020           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
14021             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14022
14023           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
14024                                            argvec, UNIFY_ALLOW_NONE, 
14025                                            /*call_args_p=*/false, 
14026                                            /*subr=*/0);
14027
14028           /* We cannot deduce in the other direction, because ARG2 is
14029              a pack expansion but ARG1 is not.*/
14030           deduce1 = 0;
14031         }
14032
14033       else
14034         {
14035           /* The normal case, where neither argument is a pack
14036              expansion.  */
14037           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
14038           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
14039         }
14040
14041       if (!deduce1)
14042         better2 = -1;
14043       if (!deduce2)
14044         better1 = -1;
14045       if (better1 < 0 && better2 < 0)
14046         /* We've failed to deduce something in either direction.
14047            These must be unordered.  */
14048         break;
14049
14050       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
14051         {
14052           /* Deduces in both directions, see if quals can
14053              disambiguate.  Pretend the worse one failed to deduce. */
14054           if ((quals1 & quals2) == quals2)
14055             deduce1 = 0;
14056           if ((quals1 & quals2) == quals1)
14057             deduce2 = 0;
14058         }
14059       if (deduce1 && !deduce2 && !better2)
14060         better2 = 1;
14061       if (deduce2 && !deduce1 && !better1)
14062         better1 = 1;
14063
14064       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14065           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14066         /* We have already processed all of the arguments in our
14067            handing of the pack expansion type.  */
14068         len = 0;
14069
14070       args1 = TREE_CHAIN (args1);
14071       args2 = TREE_CHAIN (args2);
14072     }
14073
14074   processing_template_decl--;
14075
14076   /* All things being equal, if the next argument is a pack expansion
14077      for one function but not for the other, prefer the
14078      non-variadic function.  */
14079   if ((better1 > 0) - (better2 > 0) == 0
14080       && args1 && TREE_VALUE (args1)
14081       && args2 && TREE_VALUE (args2))
14082     {
14083       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
14084         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
14085       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
14086         return 1;
14087     }
14088
14089   return (better1 > 0) - (better2 > 0);
14090 }
14091
14092 /* Determine which of two partial specializations is more specialized.
14093
14094    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
14095    to the first partial specialization.  The TREE_VALUE is the
14096    innermost set of template parameters for the partial
14097    specialization.  PAT2 is similar, but for the second template.
14098
14099    Return 1 if the first partial specialization is more specialized;
14100    -1 if the second is more specialized; 0 if neither is more
14101    specialized.
14102
14103    See [temp.class.order] for information about determining which of
14104    two templates is more specialized.  */
14105
14106 static int
14107 more_specialized_class (tree pat1, tree pat2)
14108 {
14109   tree targs;
14110   tree tmpl1, tmpl2;
14111   int winner = 0;
14112   bool any_deductions = false;
14113
14114   tmpl1 = TREE_TYPE (pat1);
14115   tmpl2 = TREE_TYPE (pat2);
14116
14117   /* Just like what happens for functions, if we are ordering between
14118      different class template specializations, we may encounter dependent
14119      types in the arguments, and we need our dependency check functions
14120      to behave correctly.  */
14121   ++processing_template_decl;
14122   targs = get_class_bindings (TREE_VALUE (pat1),
14123                               CLASSTYPE_TI_ARGS (tmpl1),
14124                               CLASSTYPE_TI_ARGS (tmpl2));
14125   if (targs)
14126     {
14127       --winner;
14128       any_deductions = true;
14129     }
14130
14131   targs = get_class_bindings (TREE_VALUE (pat2),
14132                               CLASSTYPE_TI_ARGS (tmpl2),
14133                               CLASSTYPE_TI_ARGS (tmpl1));
14134   if (targs)
14135     {
14136       ++winner;
14137       any_deductions = true;
14138     }
14139   --processing_template_decl;
14140
14141   /* In the case of a tie where at least one of the class templates
14142      has a parameter pack at the end, the template with the most
14143      non-packed parameters wins.  */
14144   if (winner == 0
14145       && any_deductions
14146       && (template_args_variadic_p (TREE_PURPOSE (pat1))
14147           || template_args_variadic_p (TREE_PURPOSE (pat2))))
14148     {
14149       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
14150       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
14151       int len1 = TREE_VEC_LENGTH (args1);
14152       int len2 = TREE_VEC_LENGTH (args2);
14153
14154       /* We don't count the pack expansion at the end.  */
14155       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
14156         --len1;
14157       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
14158         --len2;
14159
14160       if (len1 > len2)
14161         return 1;
14162       else if (len1 < len2)
14163         return -1;
14164     }
14165
14166   return winner;
14167 }
14168
14169 /* Return the template arguments that will produce the function signature
14170    DECL from the function template FN, with the explicit template
14171    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
14172    also match.  Return NULL_TREE if no satisfactory arguments could be
14173    found.  */
14174
14175 static tree
14176 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
14177 {
14178   int ntparms = DECL_NTPARMS (fn);
14179   tree targs = make_tree_vec (ntparms);
14180   tree decl_type;
14181   tree decl_arg_types;
14182
14183   /* Substitute the explicit template arguments into the type of DECL.
14184      The call to fn_type_unification will handle substitution into the
14185      FN.  */
14186   decl_type = TREE_TYPE (decl);
14187   if (explicit_args && uses_template_parms (decl_type))
14188     {
14189       tree tmpl;
14190       tree converted_args;
14191
14192       if (DECL_TEMPLATE_INFO (decl))
14193         tmpl = DECL_TI_TEMPLATE (decl);
14194       else
14195         /* We can get here for some invalid specializations.  */
14196         return NULL_TREE;
14197
14198       converted_args
14199         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
14200                                  explicit_args, NULL_TREE,
14201                                  tf_none,
14202                                  /*require_all_args=*/false,
14203                                  /*use_default_args=*/false);
14204       if (converted_args == error_mark_node)
14205         return NULL_TREE;
14206
14207       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
14208       if (decl_type == error_mark_node)
14209         return NULL_TREE;
14210     }
14211
14212   /* Never do unification on the 'this' parameter.  */
14213   decl_arg_types = skip_artificial_parms_for (decl, 
14214                                               TYPE_ARG_TYPES (decl_type));
14215
14216   if (fn_type_unification (fn, explicit_args, targs,
14217                            decl_arg_types,
14218                            (check_rettype || DECL_CONV_FN_P (fn)
14219                             ? TREE_TYPE (decl_type) : NULL_TREE),
14220                            DEDUCE_EXACT, LOOKUP_NORMAL))
14221     return NULL_TREE;
14222
14223   return targs;
14224 }
14225
14226 /* Return the innermost template arguments that, when applied to a
14227    template specialization whose innermost template parameters are
14228    TPARMS, and whose specialization arguments are PARMS, yield the
14229    ARGS.
14230
14231    For example, suppose we have:
14232
14233      template <class T, class U> struct S {};
14234      template <class T> struct S<T*, int> {};
14235
14236    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
14237    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
14238    int}.  The resulting vector will be {double}, indicating that `T'
14239    is bound to `double'.  */
14240
14241 static tree
14242 get_class_bindings (tree tparms, tree spec_args, tree args)
14243 {
14244   int i, ntparms = TREE_VEC_LENGTH (tparms);
14245   tree deduced_args;
14246   tree innermost_deduced_args;
14247
14248   innermost_deduced_args = make_tree_vec (ntparms);
14249   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14250     {
14251       deduced_args = copy_node (args);
14252       SET_TMPL_ARGS_LEVEL (deduced_args,
14253                            TMPL_ARGS_DEPTH (deduced_args),
14254                            innermost_deduced_args);
14255     }
14256   else
14257     deduced_args = innermost_deduced_args;
14258
14259   if (unify (tparms, deduced_args,
14260              INNERMOST_TEMPLATE_ARGS (spec_args),
14261              INNERMOST_TEMPLATE_ARGS (args),
14262              UNIFY_ALLOW_NONE))
14263     return NULL_TREE;
14264
14265   for (i =  0; i < ntparms; ++i)
14266     if (! TREE_VEC_ELT (innermost_deduced_args, i))
14267       return NULL_TREE;
14268
14269   /* Verify that nondeduced template arguments agree with the type
14270      obtained from argument deduction.
14271
14272      For example:
14273
14274        struct A { typedef int X; };
14275        template <class T, class U> struct C {};
14276        template <class T> struct C<T, typename T::X> {};
14277
14278      Then with the instantiation `C<A, int>', we can deduce that
14279      `T' is `A' but unify () does not check whether `typename T::X'
14280      is `int'.  */
14281   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
14282   if (spec_args == error_mark_node
14283       /* We only need to check the innermost arguments; the other
14284          arguments will always agree.  */
14285       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
14286                               INNERMOST_TEMPLATE_ARGS (args)))
14287     return NULL_TREE;
14288
14289   /* Now that we have bindings for all of the template arguments,
14290      ensure that the arguments deduced for the template template
14291      parameters have compatible template parameter lists.  See the use
14292      of template_template_parm_bindings_ok_p in fn_type_unification
14293      for more information.  */
14294   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
14295     return NULL_TREE;
14296
14297   return deduced_args;
14298 }
14299
14300 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
14301    Return the TREE_LIST node with the most specialized template, if
14302    any.  If there is no most specialized template, the error_mark_node
14303    is returned.
14304
14305    Note that this function does not look at, or modify, the
14306    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
14307    returned is one of the elements of INSTANTIATIONS, callers may
14308    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
14309    and retrieve it from the value returned.  */
14310
14311 tree
14312 most_specialized_instantiation (tree templates)
14313 {
14314   tree fn, champ;
14315
14316   ++processing_template_decl;
14317
14318   champ = templates;
14319   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
14320     {
14321       int fate = 0;
14322
14323       if (get_bindings (TREE_VALUE (champ),
14324                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14325                         NULL_TREE, /*check_ret=*/false))
14326         fate--;
14327
14328       if (get_bindings (TREE_VALUE (fn),
14329                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14330                         NULL_TREE, /*check_ret=*/false))
14331         fate++;
14332
14333       if (fate == -1)
14334         champ = fn;
14335       else if (!fate)
14336         {
14337           /* Equally specialized, move to next function.  If there
14338              is no next function, nothing's most specialized.  */
14339           fn = TREE_CHAIN (fn);
14340           champ = fn;
14341           if (!fn)
14342             break;
14343         }
14344     }
14345
14346   if (champ)
14347     /* Now verify that champ is better than everything earlier in the
14348        instantiation list.  */
14349     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
14350       if (get_bindings (TREE_VALUE (champ),
14351                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14352                         NULL_TREE, /*check_ret=*/false)
14353           || !get_bindings (TREE_VALUE (fn),
14354                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14355                             NULL_TREE, /*check_ret=*/false))
14356         {
14357           champ = NULL_TREE;
14358           break;
14359         }
14360
14361   processing_template_decl--;
14362
14363   if (!champ)
14364     return error_mark_node;
14365
14366   return champ;
14367 }
14368
14369 /* If DECL is a specialization of some template, return the most
14370    general such template.  Otherwise, returns NULL_TREE.
14371
14372    For example, given:
14373
14374      template <class T> struct S { template <class U> void f(U); };
14375
14376    if TMPL is `template <class U> void S<int>::f(U)' this will return
14377    the full template.  This function will not trace past partial
14378    specializations, however.  For example, given in addition:
14379
14380      template <class T> struct S<T*> { template <class U> void f(U); };
14381
14382    if TMPL is `template <class U> void S<int*>::f(U)' this will return
14383    `template <class T> template <class U> S<T*>::f(U)'.  */
14384
14385 tree
14386 most_general_template (tree decl)
14387 {
14388   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
14389      an immediate specialization.  */
14390   if (TREE_CODE (decl) == FUNCTION_DECL)
14391     {
14392       if (DECL_TEMPLATE_INFO (decl)) {
14393         decl = DECL_TI_TEMPLATE (decl);
14394
14395         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
14396            template friend.  */
14397         if (TREE_CODE (decl) != TEMPLATE_DECL)
14398           return NULL_TREE;
14399       } else
14400         return NULL_TREE;
14401     }
14402
14403   /* Look for more and more general templates.  */
14404   while (DECL_TEMPLATE_INFO (decl))
14405     {
14406       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
14407          (See cp-tree.h for details.)  */
14408       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
14409         break;
14410
14411       if (CLASS_TYPE_P (TREE_TYPE (decl))
14412           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
14413         break;
14414
14415       /* Stop if we run into an explicitly specialized class template.  */
14416       if (!DECL_NAMESPACE_SCOPE_P (decl)
14417           && DECL_CONTEXT (decl)
14418           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
14419         break;
14420
14421       decl = DECL_TI_TEMPLATE (decl);
14422     }
14423
14424   return decl;
14425 }
14426
14427 /* Return the most specialized of the class template partial
14428    specializations of TMPL which can produce TYPE, a specialization of
14429    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
14430    a _TYPE node corresponding to the partial specialization, while the
14431    TREE_PURPOSE is the set of template arguments that must be
14432    substituted into the TREE_TYPE in order to generate TYPE.
14433
14434    If the choice of partial specialization is ambiguous, a diagnostic
14435    is issued, and the error_mark_node is returned.  If there are no
14436    partial specializations of TMPL matching TYPE, then NULL_TREE is
14437    returned.  */
14438
14439 static tree
14440 most_specialized_class (tree type, tree tmpl)
14441 {
14442   tree list = NULL_TREE;
14443   tree t;
14444   tree champ;
14445   int fate;
14446   bool ambiguous_p;
14447   tree args;
14448   tree outer_args = NULL_TREE;
14449
14450   tmpl = most_general_template (tmpl);
14451   args = CLASSTYPE_TI_ARGS (type);
14452
14453   /* For determining which partial specialization to use, only the
14454      innermost args are interesting.  */
14455   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14456     {
14457       outer_args = strip_innermost_template_args (args, 1);
14458       args = INNERMOST_TEMPLATE_ARGS (args);
14459     }
14460
14461   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
14462     {
14463       tree partial_spec_args;
14464       tree spec_args;
14465       tree parms = TREE_VALUE (t);
14466
14467       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
14468       if (outer_args)
14469         {
14470           int i;
14471
14472           ++processing_template_decl;
14473
14474           /* Discard the outer levels of args, and then substitute in the
14475              template args from the enclosing class.  */
14476           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
14477           partial_spec_args = tsubst_template_args
14478             (partial_spec_args, outer_args, tf_none, NULL_TREE);
14479
14480           /* PARMS already refers to just the innermost parms, but the
14481              template parms in partial_spec_args had their levels lowered
14482              by tsubst, so we need to do the same for the parm list.  We
14483              can't just tsubst the TREE_VEC itself, as tsubst wants to
14484              treat a TREE_VEC as an argument vector.  */
14485           parms = copy_node (parms);
14486           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
14487             TREE_VEC_ELT (parms, i) =
14488               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
14489
14490           --processing_template_decl;
14491         }
14492       spec_args = get_class_bindings (parms,
14493                                       partial_spec_args,
14494                                       args);
14495       if (spec_args)
14496         {
14497           if (outer_args)
14498             spec_args = add_to_template_args (outer_args, spec_args);
14499           list = tree_cons (spec_args, TREE_VALUE (t), list);
14500           TREE_TYPE (list) = TREE_TYPE (t);
14501         }
14502     }
14503
14504   if (! list)
14505     return NULL_TREE;
14506
14507   ambiguous_p = false;
14508   t = list;
14509   champ = t;
14510   t = TREE_CHAIN (t);
14511   for (; t; t = TREE_CHAIN (t))
14512     {
14513       fate = more_specialized_class (champ, t);
14514       if (fate == 1)
14515         ;
14516       else
14517         {
14518           if (fate == 0)
14519             {
14520               t = TREE_CHAIN (t);
14521               if (! t)
14522                 {
14523                   ambiguous_p = true;
14524                   break;
14525                 }
14526             }
14527           champ = t;
14528         }
14529     }
14530
14531   if (!ambiguous_p)
14532     for (t = list; t && t != champ; t = TREE_CHAIN (t))
14533       {
14534         fate = more_specialized_class (champ, t);
14535         if (fate != 1)
14536           {
14537             ambiguous_p = true;
14538             break;
14539           }
14540       }
14541
14542   if (ambiguous_p)
14543     {
14544       const char *str = "candidates are:";
14545       error ("ambiguous class template instantiation for %q#T", type);
14546       for (t = list; t; t = TREE_CHAIN (t))
14547         {
14548           error ("%s %+#T", str, TREE_TYPE (t));
14549           str = "               ";
14550         }
14551       return error_mark_node;
14552     }
14553
14554   return champ;
14555 }
14556
14557 /* Explicitly instantiate DECL.  */
14558
14559 void
14560 do_decl_instantiation (tree decl, tree storage)
14561 {
14562   tree result = NULL_TREE;
14563   int extern_p = 0;
14564
14565   if (!decl || decl == error_mark_node)
14566     /* An error occurred, for which grokdeclarator has already issued
14567        an appropriate message.  */
14568     return;
14569   else if (! DECL_LANG_SPECIFIC (decl))
14570     {
14571       error ("explicit instantiation of non-template %q#D", decl);
14572       return;
14573     }
14574   else if (TREE_CODE (decl) == VAR_DECL)
14575     {
14576       /* There is an asymmetry here in the way VAR_DECLs and
14577          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
14578          the latter, the DECL we get back will be marked as a
14579          template instantiation, and the appropriate
14580          DECL_TEMPLATE_INFO will be set up.  This does not happen for
14581          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
14582          should handle VAR_DECLs as it currently handles
14583          FUNCTION_DECLs.  */
14584       if (!DECL_CLASS_SCOPE_P (decl))
14585         {
14586           error ("%qD is not a static data member of a class template", decl);
14587           return;
14588         }
14589       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
14590       if (!result || TREE_CODE (result) != VAR_DECL)
14591         {
14592           error ("no matching template for %qD found", decl);
14593           return;
14594         }
14595       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
14596         {
14597           error ("type %qT for explicit instantiation %qD does not match "
14598                  "declared type %qT", TREE_TYPE (result), decl,
14599                  TREE_TYPE (decl));
14600           return;
14601         }
14602     }
14603   else if (TREE_CODE (decl) != FUNCTION_DECL)
14604     {
14605       error ("explicit instantiation of %q#D", decl);
14606       return;
14607     }
14608   else
14609     result = decl;
14610
14611   /* Check for various error cases.  Note that if the explicit
14612      instantiation is valid the RESULT will currently be marked as an
14613      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
14614      until we get here.  */
14615
14616   if (DECL_TEMPLATE_SPECIALIZATION (result))
14617     {
14618       /* DR 259 [temp.spec].
14619
14620          Both an explicit instantiation and a declaration of an explicit
14621          specialization shall not appear in a program unless the explicit
14622          instantiation follows a declaration of the explicit specialization.
14623
14624          For a given set of template parameters, if an explicit
14625          instantiation of a template appears after a declaration of an
14626          explicit specialization for that template, the explicit
14627          instantiation has no effect.  */
14628       return;
14629     }
14630   else if (DECL_EXPLICIT_INSTANTIATION (result))
14631     {
14632       /* [temp.spec]
14633
14634          No program shall explicitly instantiate any template more
14635          than once.
14636
14637          We check DECL_NOT_REALLY_EXTERN so as not to complain when
14638          the first instantiation was `extern' and the second is not,
14639          and EXTERN_P for the opposite case.  */
14640       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
14641         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
14642       /* If an "extern" explicit instantiation follows an ordinary
14643          explicit instantiation, the template is instantiated.  */
14644       if (extern_p)
14645         return;
14646     }
14647   else if (!DECL_IMPLICIT_INSTANTIATION (result))
14648     {
14649       error ("no matching template for %qD found", result);
14650       return;
14651     }
14652   else if (!DECL_TEMPLATE_INFO (result))
14653     {
14654       permerror (input_location, "explicit instantiation of non-template %q#D", result);
14655       return;
14656     }
14657
14658   if (storage == NULL_TREE)
14659     ;
14660   else if (storage == ridpointers[(int) RID_EXTERN])
14661     {
14662       if (!in_system_header && (cxx_dialect == cxx98))
14663         pedwarn (input_location, OPT_pedantic, 
14664                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
14665                  "instantiations");
14666       extern_p = 1;
14667     }
14668   else
14669     error ("storage class %qD applied to template instantiation", storage);
14670
14671   check_explicit_instantiation_namespace (result);
14672   mark_decl_instantiated (result, extern_p);
14673   if (! extern_p)
14674     instantiate_decl (result, /*defer_ok=*/1,
14675                       /*expl_inst_class_mem_p=*/false);
14676 }
14677
14678 static void
14679 mark_class_instantiated (tree t, int extern_p)
14680 {
14681   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
14682   SET_CLASSTYPE_INTERFACE_KNOWN (t);
14683   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
14684   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
14685   if (! extern_p)
14686     {
14687       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
14688       rest_of_type_compilation (t, 1);
14689     }
14690 }
14691
14692 /* Called from do_type_instantiation through binding_table_foreach to
14693    do recursive instantiation for the type bound in ENTRY.  */
14694 static void
14695 bt_instantiate_type_proc (binding_entry entry, void *data)
14696 {
14697   tree storage = *(tree *) data;
14698
14699   if (MAYBE_CLASS_TYPE_P (entry->type)
14700       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
14701     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
14702 }
14703
14704 /* Called from do_type_instantiation to instantiate a member
14705    (a member function or a static member variable) of an
14706    explicitly instantiated class template.  */
14707 static void
14708 instantiate_class_member (tree decl, int extern_p)
14709 {
14710   mark_decl_instantiated (decl, extern_p);
14711   if (! extern_p)
14712     instantiate_decl (decl, /*defer_ok=*/1,
14713                       /*expl_inst_class_mem_p=*/true);
14714 }
14715
14716 /* Perform an explicit instantiation of template class T.  STORAGE, if
14717    non-null, is the RID for extern, inline or static.  COMPLAIN is
14718    nonzero if this is called from the parser, zero if called recursively,
14719    since the standard is unclear (as detailed below).  */
14720
14721 void
14722 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
14723 {
14724   int extern_p = 0;
14725   int nomem_p = 0;
14726   int static_p = 0;
14727   int previous_instantiation_extern_p = 0;
14728
14729   if (TREE_CODE (t) == TYPE_DECL)
14730     t = TREE_TYPE (t);
14731
14732   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
14733     {
14734       error ("explicit instantiation of non-template type %qT", t);
14735       return;
14736     }
14737
14738   complete_type (t);
14739
14740   if (!COMPLETE_TYPE_P (t))
14741     {
14742       if (complain & tf_error)
14743         error ("explicit instantiation of %q#T before definition of template",
14744                t);
14745       return;
14746     }
14747
14748   if (storage != NULL_TREE)
14749     {
14750       if (!in_system_header)
14751         {
14752           if (storage == ridpointers[(int) RID_EXTERN])
14753             {
14754               if (cxx_dialect == cxx98)
14755                 pedwarn (input_location, OPT_pedantic, 
14756                          "ISO C++ 1998 forbids the use of %<extern%> on "
14757                          "explicit instantiations");
14758             }
14759           else
14760             pedwarn (input_location, OPT_pedantic, 
14761                      "ISO C++ forbids the use of %qE"
14762                      " on explicit instantiations", storage);
14763         }
14764
14765       if (storage == ridpointers[(int) RID_INLINE])
14766         nomem_p = 1;
14767       else if (storage == ridpointers[(int) RID_EXTERN])
14768         extern_p = 1;
14769       else if (storage == ridpointers[(int) RID_STATIC])
14770         static_p = 1;
14771       else
14772         {
14773           error ("storage class %qD applied to template instantiation",
14774                  storage);
14775           extern_p = 0;
14776         }
14777     }
14778
14779   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
14780     {
14781       /* DR 259 [temp.spec].
14782
14783          Both an explicit instantiation and a declaration of an explicit
14784          specialization shall not appear in a program unless the explicit
14785          instantiation follows a declaration of the explicit specialization.
14786
14787          For a given set of template parameters, if an explicit
14788          instantiation of a template appears after a declaration of an
14789          explicit specialization for that template, the explicit
14790          instantiation has no effect.  */
14791       return;
14792     }
14793   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
14794     {
14795       /* [temp.spec]
14796
14797          No program shall explicitly instantiate any template more
14798          than once.
14799
14800          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
14801          instantiation was `extern'.  If EXTERN_P then the second is.
14802          These cases are OK.  */
14803       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
14804
14805       if (!previous_instantiation_extern_p && !extern_p
14806           && (complain & tf_error))
14807         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
14808
14809       /* If we've already instantiated the template, just return now.  */
14810       if (!CLASSTYPE_INTERFACE_ONLY (t))
14811         return;
14812     }
14813
14814   check_explicit_instantiation_namespace (TYPE_NAME (t));
14815   mark_class_instantiated (t, extern_p);
14816
14817   if (nomem_p)
14818     return;
14819
14820   {
14821     tree tmp;
14822
14823     /* In contrast to implicit instantiation, where only the
14824        declarations, and not the definitions, of members are
14825        instantiated, we have here:
14826
14827          [temp.explicit]
14828
14829          The explicit instantiation of a class template specialization
14830          implies the instantiation of all of its members not
14831          previously explicitly specialized in the translation unit
14832          containing the explicit instantiation.
14833
14834        Of course, we can't instantiate member template classes, since
14835        we don't have any arguments for them.  Note that the standard
14836        is unclear on whether the instantiation of the members are
14837        *explicit* instantiations or not.  However, the most natural
14838        interpretation is that it should be an explicit instantiation.  */
14839
14840     if (! static_p)
14841       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
14842         if (TREE_CODE (tmp) == FUNCTION_DECL
14843             && DECL_TEMPLATE_INSTANTIATION (tmp))
14844           instantiate_class_member (tmp, extern_p);
14845
14846     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
14847       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
14848         instantiate_class_member (tmp, extern_p);
14849
14850     if (CLASSTYPE_NESTED_UTDS (t))
14851       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
14852                              bt_instantiate_type_proc, &storage);
14853   }
14854 }
14855
14856 /* Given a function DECL, which is a specialization of TMPL, modify
14857    DECL to be a re-instantiation of TMPL with the same template
14858    arguments.  TMPL should be the template into which tsubst'ing
14859    should occur for DECL, not the most general template.
14860
14861    One reason for doing this is a scenario like this:
14862
14863      template <class T>
14864      void f(const T&, int i);
14865
14866      void g() { f(3, 7); }
14867
14868      template <class T>
14869      void f(const T& t, const int i) { }
14870
14871    Note that when the template is first instantiated, with
14872    instantiate_template, the resulting DECL will have no name for the
14873    first parameter, and the wrong type for the second.  So, when we go
14874    to instantiate the DECL, we regenerate it.  */
14875
14876 static void
14877 regenerate_decl_from_template (tree decl, tree tmpl)
14878 {
14879   /* The arguments used to instantiate DECL, from the most general
14880      template.  */
14881   tree args;
14882   tree code_pattern;
14883
14884   args = DECL_TI_ARGS (decl);
14885   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
14886
14887   /* Make sure that we can see identifiers, and compute access
14888      correctly.  */
14889   push_access_scope (decl);
14890
14891   if (TREE_CODE (decl) == FUNCTION_DECL)
14892     {
14893       tree decl_parm;
14894       tree pattern_parm;
14895       tree specs;
14896       int args_depth;
14897       int parms_depth;
14898
14899       args_depth = TMPL_ARGS_DEPTH (args);
14900       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
14901       if (args_depth > parms_depth)
14902         args = get_innermost_template_args (args, parms_depth);
14903
14904       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
14905                                               args, tf_error, NULL_TREE);
14906       if (specs)
14907         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
14908                                                     specs);
14909
14910       /* Merge parameter declarations.  */
14911       decl_parm = skip_artificial_parms_for (decl,
14912                                              DECL_ARGUMENTS (decl));
14913       pattern_parm
14914         = skip_artificial_parms_for (code_pattern,
14915                                      DECL_ARGUMENTS (code_pattern));
14916       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
14917         {
14918           tree parm_type;
14919           tree attributes;
14920           
14921           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
14922             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
14923           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
14924                               NULL_TREE);
14925           parm_type = type_decays_to (parm_type);
14926           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
14927             TREE_TYPE (decl_parm) = parm_type;
14928           attributes = DECL_ATTRIBUTES (pattern_parm);
14929           if (DECL_ATTRIBUTES (decl_parm) != attributes)
14930             {
14931               DECL_ATTRIBUTES (decl_parm) = attributes;
14932               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
14933             }
14934           decl_parm = TREE_CHAIN (decl_parm);
14935           pattern_parm = TREE_CHAIN (pattern_parm);
14936         }
14937       /* Merge any parameters that match with the function parameter
14938          pack.  */
14939       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
14940         {
14941           int i, len;
14942           tree expanded_types;
14943           /* Expand the TYPE_PACK_EXPANSION that provides the types for
14944              the parameters in this function parameter pack.  */
14945           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
14946                                                  args, tf_error, NULL_TREE);
14947           len = TREE_VEC_LENGTH (expanded_types);
14948           for (i = 0; i < len; i++)
14949             {
14950               tree parm_type;
14951               tree attributes;
14952           
14953               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
14954                 /* Rename the parameter to include the index.  */
14955                 DECL_NAME (decl_parm) = 
14956                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
14957               parm_type = TREE_VEC_ELT (expanded_types, i);
14958               parm_type = type_decays_to (parm_type);
14959               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
14960                 TREE_TYPE (decl_parm) = parm_type;
14961               attributes = DECL_ATTRIBUTES (pattern_parm);
14962               if (DECL_ATTRIBUTES (decl_parm) != attributes)
14963                 {
14964                   DECL_ATTRIBUTES (decl_parm) = attributes;
14965                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
14966                 }
14967               decl_parm = TREE_CHAIN (decl_parm);
14968             }
14969         }
14970       /* Merge additional specifiers from the CODE_PATTERN.  */
14971       if (DECL_DECLARED_INLINE_P (code_pattern)
14972           && !DECL_DECLARED_INLINE_P (decl))
14973         DECL_DECLARED_INLINE_P (decl) = 1;
14974     }
14975   else if (TREE_CODE (decl) == VAR_DECL)
14976     DECL_INITIAL (decl) =
14977       tsubst_expr (DECL_INITIAL (code_pattern), args,
14978                    tf_error, DECL_TI_TEMPLATE (decl),
14979                    /*integral_constant_expression_p=*/false);
14980   else
14981     gcc_unreachable ();
14982
14983   pop_access_scope (decl);
14984 }
14985
14986 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
14987    substituted to get DECL.  */
14988
14989 tree
14990 template_for_substitution (tree decl)
14991 {
14992   tree tmpl = DECL_TI_TEMPLATE (decl);
14993
14994   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
14995      for the instantiation.  This is not always the most general
14996      template.  Consider, for example:
14997
14998         template <class T>
14999         struct S { template <class U> void f();
15000                    template <> void f<int>(); };
15001
15002      and an instantiation of S<double>::f<int>.  We want TD to be the
15003      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
15004   while (/* An instantiation cannot have a definition, so we need a
15005             more general template.  */
15006          DECL_TEMPLATE_INSTANTIATION (tmpl)
15007            /* We must also deal with friend templates.  Given:
15008
15009                 template <class T> struct S {
15010                   template <class U> friend void f() {};
15011                 };
15012
15013               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
15014               so far as the language is concerned, but that's still
15015               where we get the pattern for the instantiation from.  On
15016               other hand, if the definition comes outside the class, say:
15017
15018                 template <class T> struct S {
15019                   template <class U> friend void f();
15020                 };
15021                 template <class U> friend void f() {}
15022
15023               we don't need to look any further.  That's what the check for
15024               DECL_INITIAL is for.  */
15025           || (TREE_CODE (decl) == FUNCTION_DECL
15026               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
15027               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
15028     {
15029       /* The present template, TD, should not be a definition.  If it
15030          were a definition, we should be using it!  Note that we
15031          cannot restructure the loop to just keep going until we find
15032          a template with a definition, since that might go too far if
15033          a specialization was declared, but not defined.  */
15034       gcc_assert (TREE_CODE (decl) != VAR_DECL
15035                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
15036
15037       /* Fetch the more general template.  */
15038       tmpl = DECL_TI_TEMPLATE (tmpl);
15039     }
15040
15041   return tmpl;
15042 }
15043
15044 /* Produce the definition of D, a _DECL generated from a template.  If
15045    DEFER_OK is nonzero, then we don't have to actually do the
15046    instantiation now; we just have to do it sometime.  Normally it is
15047    an error if this is an explicit instantiation but D is undefined.
15048    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
15049    explicitly instantiated class template.  */
15050
15051 tree
15052 instantiate_decl (tree d, int defer_ok,
15053                   bool expl_inst_class_mem_p)
15054 {
15055   tree tmpl = DECL_TI_TEMPLATE (d);
15056   tree gen_args;
15057   tree args;
15058   tree td;
15059   tree code_pattern;
15060   tree spec;
15061   tree gen_tmpl;
15062   bool pattern_defined;
15063   int need_push;
15064   location_t saved_loc = input_location;
15065   bool external_p;
15066
15067   /* This function should only be used to instantiate templates for
15068      functions and static member variables.  */
15069   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
15070               || TREE_CODE (d) == VAR_DECL);
15071
15072   /* Variables are never deferred; if instantiation is required, they
15073      are instantiated right away.  That allows for better code in the
15074      case that an expression refers to the value of the variable --
15075      if the variable has a constant value the referring expression can
15076      take advantage of that fact.  */
15077   if (TREE_CODE (d) == VAR_DECL)
15078     defer_ok = 0;
15079
15080   /* Don't instantiate cloned functions.  Instead, instantiate the
15081      functions they cloned.  */
15082   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
15083     d = DECL_CLONED_FUNCTION (d);
15084
15085   if (DECL_TEMPLATE_INSTANTIATED (d))
15086     /* D has already been instantiated.  It might seem reasonable to
15087        check whether or not D is an explicit instantiation, and, if so,
15088        stop here.  But when an explicit instantiation is deferred
15089        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
15090        is set, even though we still need to do the instantiation.  */
15091     return d;
15092
15093   /* If we already have a specialization of this declaration, then
15094      there's no reason to instantiate it.  Note that
15095      retrieve_specialization gives us both instantiations and
15096      specializations, so we must explicitly check
15097      DECL_TEMPLATE_SPECIALIZATION.  */
15098   gen_tmpl = most_general_template (tmpl);
15099   gen_args = DECL_TI_ARGS (d);
15100   spec = retrieve_specialization (gen_tmpl, gen_args,
15101                                   /*class_specializations_p=*/false);
15102   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
15103     return spec;
15104
15105   /* This needs to happen before any tsubsting.  */
15106   if (! push_tinst_level (d))
15107     return d;
15108
15109   timevar_push (TV_PARSE);
15110
15111   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
15112      for the instantiation.  */
15113   td = template_for_substitution (d);
15114   code_pattern = DECL_TEMPLATE_RESULT (td);
15115
15116   /* We should never be trying to instantiate a member of a class
15117      template or partial specialization.  */
15118   gcc_assert (d != code_pattern);
15119
15120   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
15121       || DECL_TEMPLATE_SPECIALIZATION (td))
15122     /* In the case of a friend template whose definition is provided
15123        outside the class, we may have too many arguments.  Drop the
15124        ones we don't need.  The same is true for specializations.  */
15125     args = get_innermost_template_args
15126       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
15127   else
15128     args = gen_args;
15129
15130   if (TREE_CODE (d) == FUNCTION_DECL)
15131     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
15132   else
15133     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
15134
15135   /* We may be in the middle of deferred access check.  Disable it now.  */
15136   push_deferring_access_checks (dk_no_deferred);
15137
15138   /* Unless an explicit instantiation directive has already determined
15139      the linkage of D, remember that a definition is available for
15140      this entity.  */
15141   if (pattern_defined
15142       && !DECL_INTERFACE_KNOWN (d)
15143       && !DECL_NOT_REALLY_EXTERN (d))
15144     mark_definable (d);
15145
15146   input_location = DECL_SOURCE_LOCATION (d);
15147
15148   /* If D is a member of an explicitly instantiated class template,
15149      and no definition is available, treat it like an implicit
15150      instantiation.  */
15151   if (!pattern_defined && expl_inst_class_mem_p
15152       && DECL_EXPLICIT_INSTANTIATION (d))
15153     {
15154       DECL_NOT_REALLY_EXTERN (d) = 0;
15155       DECL_INTERFACE_KNOWN (d) = 0;
15156       SET_DECL_IMPLICIT_INSTANTIATION (d);
15157     }
15158
15159   if (!defer_ok)
15160     {
15161       /* Recheck the substitutions to obtain any warning messages
15162          about ignoring cv qualifiers.  */
15163       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
15164       tree type = TREE_TYPE (gen);
15165
15166       /* Make sure that we can see identifiers, and compute access
15167          correctly.  D is already the target FUNCTION_DECL with the
15168          right context.  */
15169       push_access_scope (d);
15170
15171       if (TREE_CODE (gen) == FUNCTION_DECL)
15172         {
15173           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
15174           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
15175                                           d);
15176           /* Don't simply tsubst the function type, as that will give
15177              duplicate warnings about poor parameter qualifications.
15178              The function arguments are the same as the decl_arguments
15179              without the top level cv qualifiers.  */
15180           type = TREE_TYPE (type);
15181         }
15182       tsubst (type, gen_args, tf_warning_or_error, d);
15183
15184       pop_access_scope (d);
15185     }
15186
15187   /* Check to see whether we know that this template will be
15188      instantiated in some other file, as with "extern template"
15189      extension.  */
15190   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
15191   /* In general, we do not instantiate such templates...  */
15192   if (external_p
15193       /* ... but we instantiate inline functions so that we can inline
15194          them and ... */
15195       && ! (TREE_CODE (d) == FUNCTION_DECL
15196             && possibly_inlined_p (d))
15197       /* ... we instantiate static data members whose values are
15198          needed in integral constant expressions.  */
15199       && ! (TREE_CODE (d) == VAR_DECL
15200             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
15201     goto out;
15202   /* Defer all other templates, unless we have been explicitly
15203      forbidden from doing so.  */
15204   if (/* If there is no definition, we cannot instantiate the
15205          template.  */
15206       ! pattern_defined
15207       /* If it's OK to postpone instantiation, do so.  */
15208       || defer_ok
15209       /* If this is a static data member that will be defined
15210          elsewhere, we don't want to instantiate the entire data
15211          member, but we do want to instantiate the initializer so that
15212          we can substitute that elsewhere.  */
15213       || (external_p && TREE_CODE (d) == VAR_DECL))
15214     {
15215       /* The definition of the static data member is now required so
15216          we must substitute the initializer.  */
15217       if (TREE_CODE (d) == VAR_DECL
15218           && !DECL_INITIAL (d)
15219           && DECL_INITIAL (code_pattern))
15220         {
15221           tree ns;
15222           tree init;
15223
15224           ns = decl_namespace_context (d);
15225           push_nested_namespace (ns);
15226           push_nested_class (DECL_CONTEXT (d));
15227           init = tsubst_expr (DECL_INITIAL (code_pattern),
15228                               args,
15229                               tf_warning_or_error, NULL_TREE,
15230                               /*integral_constant_expression_p=*/false);
15231           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
15232                           /*asmspec_tree=*/NULL_TREE,
15233                           LOOKUP_ONLYCONVERTING);
15234           pop_nested_class ();
15235           pop_nested_namespace (ns);
15236         }
15237
15238       /* We restore the source position here because it's used by
15239          add_pending_template.  */
15240       input_location = saved_loc;
15241
15242       if (at_eof && !pattern_defined
15243           && DECL_EXPLICIT_INSTANTIATION (d)
15244           && DECL_NOT_REALLY_EXTERN (d))
15245         /* [temp.explicit]
15246
15247            The definition of a non-exported function template, a
15248            non-exported member function template, or a non-exported
15249            member function or static data member of a class template
15250            shall be present in every translation unit in which it is
15251            explicitly instantiated.  */
15252         permerror (input_location,  "explicit instantiation of %qD "
15253                    "but no definition available", d);
15254
15255       /* ??? Historically, we have instantiated inline functions, even
15256          when marked as "extern template".  */
15257       if (!(external_p && TREE_CODE (d) == VAR_DECL))
15258         add_pending_template (d);
15259       goto out;
15260     }
15261   /* Tell the repository that D is available in this translation unit
15262      -- and see if it is supposed to be instantiated here.  */
15263   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
15264     {
15265       /* In a PCH file, despite the fact that the repository hasn't
15266          requested instantiation in the PCH it is still possible that
15267          an instantiation will be required in a file that includes the
15268          PCH.  */
15269       if (pch_file)
15270         add_pending_template (d);
15271       /* Instantiate inline functions so that the inliner can do its
15272          job, even though we'll not be emitting a copy of this
15273          function.  */
15274       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
15275         goto out;
15276     }
15277
15278   need_push = !cfun || !global_bindings_p ();
15279   if (need_push)
15280     push_to_top_level ();
15281
15282   /* Mark D as instantiated so that recursive calls to
15283      instantiate_decl do not try to instantiate it again.  */
15284   DECL_TEMPLATE_INSTANTIATED (d) = 1;
15285
15286   /* Regenerate the declaration in case the template has been modified
15287      by a subsequent redeclaration.  */
15288   regenerate_decl_from_template (d, td);
15289
15290   /* We already set the file and line above.  Reset them now in case
15291      they changed as a result of calling regenerate_decl_from_template.  */
15292   input_location = DECL_SOURCE_LOCATION (d);
15293
15294   if (TREE_CODE (d) == VAR_DECL)
15295     {
15296       tree init;
15297
15298       /* Clear out DECL_RTL; whatever was there before may not be right
15299          since we've reset the type of the declaration.  */
15300       SET_DECL_RTL (d, NULL_RTX);
15301       DECL_IN_AGGR_P (d) = 0;
15302
15303       /* The initializer is placed in DECL_INITIAL by
15304          regenerate_decl_from_template.  Pull it out so that
15305          finish_decl can process it.  */
15306       init = DECL_INITIAL (d);
15307       DECL_INITIAL (d) = NULL_TREE;
15308       DECL_INITIALIZED_P (d) = 0;
15309
15310       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
15311          initializer.  That function will defer actual emission until
15312          we have a chance to determine linkage.  */
15313       DECL_EXTERNAL (d) = 0;
15314
15315       /* Enter the scope of D so that access-checking works correctly.  */
15316       push_nested_class (DECL_CONTEXT (d));
15317       finish_decl (d, init, NULL_TREE);
15318       pop_nested_class ();
15319     }
15320   else if (TREE_CODE (d) == FUNCTION_DECL)
15321     {
15322       htab_t saved_local_specializations;
15323       tree subst_decl;
15324       tree tmpl_parm;
15325       tree spec_parm;
15326
15327       /* Save away the current list, in case we are instantiating one
15328          template from within the body of another.  */
15329       saved_local_specializations = local_specializations;
15330
15331       /* Set up the list of local specializations.  */
15332       local_specializations = htab_create (37,
15333                                            hash_local_specialization,
15334                                            eq_local_specializations,
15335                                            NULL);
15336
15337       /* Set up context.  */
15338       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
15339
15340       /* Create substitution entries for the parameters.  */
15341       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
15342       tmpl_parm = DECL_ARGUMENTS (subst_decl);
15343       spec_parm = DECL_ARGUMENTS (d);
15344       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
15345         {
15346           register_local_specialization (spec_parm, tmpl_parm);
15347           spec_parm = skip_artificial_parms_for (d, spec_parm);
15348           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
15349         }
15350       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15351         {
15352           register_local_specialization (spec_parm, tmpl_parm);
15353           tmpl_parm = TREE_CHAIN (tmpl_parm);
15354           spec_parm = TREE_CHAIN (spec_parm);
15355         }
15356       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15357         {
15358           /* Collect all of the extra "packed" parameters into an
15359              argument pack.  */
15360           tree parmvec;
15361           tree parmtypevec;
15362           tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
15363           tree argtypepack = make_node (TYPE_ARGUMENT_PACK);
15364           int i, len = 0;
15365           tree t;
15366           
15367           /* Count how many parameters remain.  */
15368           for (t = spec_parm; t; t = TREE_CHAIN (t))
15369             len++;
15370
15371           /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
15372           parmvec = make_tree_vec (len);
15373           parmtypevec = make_tree_vec (len);
15374           for(i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
15375             {
15376               TREE_VEC_ELT (parmvec, i) = spec_parm;
15377               TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
15378             }
15379
15380           /* Build the argument packs.  */
15381           SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
15382           SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
15383           TREE_TYPE (argpack) = argtypepack;
15384           
15385           /* Register the (value) argument pack as a specialization of
15386              TMPL_PARM, then move on.  */
15387           register_local_specialization (argpack, tmpl_parm);
15388           tmpl_parm = TREE_CHAIN (tmpl_parm);
15389         }
15390       gcc_assert (!spec_parm);
15391
15392       /* Substitute into the body of the function.  */
15393       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
15394                    tf_warning_or_error, tmpl,
15395                    /*integral_constant_expression_p=*/false);
15396
15397       /* Set the current input_location to the end of the function
15398          so that finish_function knows where we are.  */
15399       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
15400
15401       /* We don't need the local specializations any more.  */
15402       htab_delete (local_specializations);
15403       local_specializations = saved_local_specializations;
15404
15405       /* Finish the function.  */
15406       d = finish_function (0);
15407       expand_or_defer_fn (d);
15408     }
15409
15410   /* We're not deferring instantiation any more.  */
15411   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
15412
15413   if (need_push)
15414     pop_from_top_level ();
15415
15416 out:
15417   input_location = saved_loc;
15418   pop_deferring_access_checks ();
15419   pop_tinst_level ();
15420
15421   timevar_pop (TV_PARSE);
15422
15423   return d;
15424 }
15425
15426 /* Run through the list of templates that we wish we could
15427    instantiate, and instantiate any we can.  RETRIES is the
15428    number of times we retry pending template instantiation.  */
15429
15430 void
15431 instantiate_pending_templates (int retries)
15432 {
15433   int reconsider;
15434   location_t saved_loc = input_location;
15435
15436   /* Instantiating templates may trigger vtable generation.  This in turn
15437      may require further template instantiations.  We place a limit here
15438      to avoid infinite loop.  */
15439   if (pending_templates && retries >= max_tinst_depth)
15440     {
15441       tree decl = pending_templates->tinst->decl;
15442
15443       error ("template instantiation depth exceeds maximum of %d"
15444              " instantiating %q+D, possibly from virtual table generation"
15445              " (use -ftemplate-depth-NN to increase the maximum)",
15446              max_tinst_depth, decl);
15447       if (TREE_CODE (decl) == FUNCTION_DECL)
15448         /* Pretend that we defined it.  */
15449         DECL_INITIAL (decl) = error_mark_node;
15450       return;
15451     }
15452
15453   do
15454     {
15455       struct pending_template **t = &pending_templates;
15456       struct pending_template *last = NULL;
15457       reconsider = 0;
15458       while (*t)
15459         {
15460           tree instantiation = reopen_tinst_level ((*t)->tinst);
15461           bool complete = false;
15462
15463           if (TYPE_P (instantiation))
15464             {
15465               tree fn;
15466
15467               if (!COMPLETE_TYPE_P (instantiation))
15468                 {
15469                   instantiate_class_template (instantiation);
15470                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
15471                     for (fn = TYPE_METHODS (instantiation);
15472                          fn;
15473                          fn = TREE_CHAIN (fn))
15474                       if (! DECL_ARTIFICIAL (fn))
15475                         instantiate_decl (fn,
15476                                           /*defer_ok=*/0,
15477                                           /*expl_inst_class_mem_p=*/false);
15478                   if (COMPLETE_TYPE_P (instantiation))
15479                     reconsider = 1;
15480                 }
15481
15482               complete = COMPLETE_TYPE_P (instantiation);
15483             }
15484           else
15485             {
15486               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
15487                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
15488                 {
15489                   instantiation
15490                     = instantiate_decl (instantiation,
15491                                         /*defer_ok=*/0,
15492                                         /*expl_inst_class_mem_p=*/false);
15493                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
15494                     reconsider = 1;
15495                 }
15496
15497               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
15498                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
15499             }
15500
15501           if (complete)
15502             /* If INSTANTIATION has been instantiated, then we don't
15503                need to consider it again in the future.  */
15504             *t = (*t)->next;
15505           else
15506             {
15507               last = *t;
15508               t = &(*t)->next;
15509             }
15510           tinst_depth = 0;
15511           current_tinst_level = NULL;
15512         }
15513       last_pending_template = last;
15514     }
15515   while (reconsider);
15516
15517   input_location = saved_loc;
15518 }
15519
15520 /* Substitute ARGVEC into T, which is a list of initializers for
15521    either base class or a non-static data member.  The TREE_PURPOSEs
15522    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
15523    instantiate_decl.  */
15524
15525 static tree
15526 tsubst_initializer_list (tree t, tree argvec)
15527 {
15528   tree inits = NULL_TREE;
15529
15530   for (; t; t = TREE_CHAIN (t))
15531     {
15532       tree decl;
15533       tree init;
15534       tree expanded_bases = NULL_TREE;
15535       tree expanded_arguments = NULL_TREE;
15536       int i, len = 1;
15537
15538       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
15539         {
15540           tree expr;
15541           tree arg;
15542
15543           /* Expand the base class expansion type into separate base
15544              classes.  */
15545           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
15546                                                  tf_warning_or_error,
15547                                                  NULL_TREE);
15548           if (expanded_bases == error_mark_node)
15549             continue;
15550           
15551           /* We'll be building separate TREE_LISTs of arguments for
15552              each base.  */
15553           len = TREE_VEC_LENGTH (expanded_bases);
15554           expanded_arguments = make_tree_vec (len);
15555           for (i = 0; i < len; i++)
15556             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
15557
15558           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
15559              expand each argument in the TREE_VALUE of t.  */
15560           expr = make_node (EXPR_PACK_EXPANSION);
15561           PACK_EXPANSION_PARAMETER_PACKS (expr) =
15562             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
15563
15564           if (TREE_VALUE (t) == void_type_node)
15565             /* VOID_TYPE_NODE is used to indicate
15566                value-initialization.  */
15567             {
15568               for (i = 0; i < len; i++)
15569                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
15570             }
15571           else
15572             {
15573               /* Substitute parameter packs into each argument in the
15574                  TREE_LIST.  */
15575               in_base_initializer = 1;
15576               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
15577                 {
15578                   tree expanded_exprs;
15579
15580                   /* Expand the argument.  */
15581                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
15582                   expanded_exprs 
15583                     = tsubst_pack_expansion (expr, argvec,
15584                                              tf_warning_or_error,
15585                                              NULL_TREE);
15586                   if (expanded_exprs == error_mark_node)
15587                     continue;
15588
15589                   /* Prepend each of the expanded expressions to the
15590                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
15591                   for (i = 0; i < len; i++)
15592                     {
15593                       TREE_VEC_ELT (expanded_arguments, i) = 
15594                         tree_cons (NULL_TREE, 
15595                                    TREE_VEC_ELT (expanded_exprs, i),
15596                                    TREE_VEC_ELT (expanded_arguments, i));
15597                     }
15598                 }
15599               in_base_initializer = 0;
15600
15601               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
15602                  since we built them backwards.  */
15603               for (i = 0; i < len; i++)
15604                 {
15605                   TREE_VEC_ELT (expanded_arguments, i) = 
15606                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
15607                 }
15608             }
15609         }
15610
15611       for (i = 0; i < len; ++i)
15612         {
15613           if (expanded_bases)
15614             {
15615               decl = TREE_VEC_ELT (expanded_bases, i);
15616               decl = expand_member_init (decl);
15617               init = TREE_VEC_ELT (expanded_arguments, i);
15618             }
15619           else
15620             {
15621               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
15622                                   tf_warning_or_error, NULL_TREE);
15623
15624               decl = expand_member_init (decl);
15625               if (decl && !DECL_P (decl))
15626                 in_base_initializer = 1;
15627
15628               init = tsubst_expr (TREE_VALUE (t), argvec, 
15629                                   tf_warning_or_error, NULL_TREE,
15630                                   /*integral_constant_expression_p=*/false);
15631               in_base_initializer = 0;
15632             }
15633
15634           if (decl)
15635             {
15636               init = build_tree_list (decl, init);
15637               TREE_CHAIN (init) = inits;
15638               inits = init;
15639             }
15640         }
15641     }
15642   return inits;
15643 }
15644
15645 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
15646
15647 static void
15648 set_current_access_from_decl (tree decl)
15649 {
15650   if (TREE_PRIVATE (decl))
15651     current_access_specifier = access_private_node;
15652   else if (TREE_PROTECTED (decl))
15653     current_access_specifier = access_protected_node;
15654   else
15655     current_access_specifier = access_public_node;
15656 }
15657
15658 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
15659    is the instantiation (which should have been created with
15660    start_enum) and ARGS are the template arguments to use.  */
15661
15662 static void
15663 tsubst_enum (tree tag, tree newtag, tree args)
15664 {
15665   tree e;
15666
15667   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
15668     {
15669       tree value;
15670       tree decl;
15671
15672       decl = TREE_VALUE (e);
15673       /* Note that in a template enum, the TREE_VALUE is the
15674          CONST_DECL, not the corresponding INTEGER_CST.  */
15675       value = tsubst_expr (DECL_INITIAL (decl),
15676                            args, tf_warning_or_error, NULL_TREE,
15677                            /*integral_constant_expression_p=*/true);
15678
15679       /* Give this enumeration constant the correct access.  */
15680       set_current_access_from_decl (decl);
15681
15682       /* Actually build the enumerator itself.  */
15683       build_enumerator (DECL_NAME (decl), value, newtag);
15684     }
15685
15686   finish_enum (newtag);
15687   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
15688     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
15689 }
15690
15691 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
15692    its type -- but without substituting the innermost set of template
15693    arguments.  So, innermost set of template parameters will appear in
15694    the type.  */
15695
15696 tree
15697 get_mostly_instantiated_function_type (tree decl)
15698 {
15699   tree fn_type;
15700   tree tmpl;
15701   tree targs;
15702   tree tparms;
15703   int parm_depth;
15704
15705   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15706   targs = DECL_TI_ARGS (decl);
15707   tparms = DECL_TEMPLATE_PARMS (tmpl);
15708   parm_depth = TMPL_PARMS_DEPTH (tparms);
15709
15710   /* There should be as many levels of arguments as there are levels
15711      of parameters.  */
15712   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
15713
15714   fn_type = TREE_TYPE (tmpl);
15715
15716   if (parm_depth == 1)
15717     /* No substitution is necessary.  */
15718     ;
15719   else
15720     {
15721       int i, save_access_control;
15722       tree partial_args;
15723
15724       /* Replace the innermost level of the TARGS with NULL_TREEs to
15725          let tsubst know not to substitute for those parameters.  */
15726       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
15727       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
15728         SET_TMPL_ARGS_LEVEL (partial_args, i,
15729                              TMPL_ARGS_LEVEL (targs, i));
15730       SET_TMPL_ARGS_LEVEL (partial_args,
15731                            TMPL_ARGS_DEPTH (targs),
15732                            make_tree_vec (DECL_NTPARMS (tmpl)));
15733
15734       /* Disable access control as this function is used only during
15735          name-mangling.  */
15736       save_access_control = flag_access_control;
15737       flag_access_control = 0;
15738
15739       ++processing_template_decl;
15740       /* Now, do the (partial) substitution to figure out the
15741          appropriate function type.  */
15742       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
15743       --processing_template_decl;
15744
15745       /* Substitute into the template parameters to obtain the real
15746          innermost set of parameters.  This step is important if the
15747          innermost set of template parameters contains value
15748          parameters whose types depend on outer template parameters.  */
15749       TREE_VEC_LENGTH (partial_args)--;
15750       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
15751
15752       flag_access_control = save_access_control;
15753     }
15754
15755   return fn_type;
15756 }
15757
15758 /* Return truthvalue if we're processing a template different from
15759    the last one involved in diagnostics.  */
15760 int
15761 problematic_instantiation_changed (void)
15762 {
15763   return last_template_error_tick != tinst_level_tick;
15764 }
15765
15766 /* Remember current template involved in diagnostics.  */
15767 void
15768 record_last_problematic_instantiation (void)
15769 {
15770   last_template_error_tick = tinst_level_tick;
15771 }
15772
15773 struct tinst_level *
15774 current_instantiation (void)
15775 {
15776   return current_tinst_level;
15777 }
15778
15779 /* [temp.param] Check that template non-type parm TYPE is of an allowable
15780    type. Return zero for ok, nonzero for disallowed. Issue error and
15781    warning messages under control of COMPLAIN.  */
15782
15783 static int
15784 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
15785 {
15786   if (INTEGRAL_TYPE_P (type))
15787     return 0;
15788   else if (POINTER_TYPE_P (type))
15789     return 0;
15790   else if (TYPE_PTR_TO_MEMBER_P (type))
15791     return 0;
15792   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
15793     return 0;
15794   else if (TREE_CODE (type) == TYPENAME_TYPE)
15795     return 0;
15796
15797   if (complain & tf_error)
15798     error ("%q#T is not a valid type for a template constant parameter", type);
15799   return 1;
15800 }
15801
15802 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
15803    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
15804
15805 static bool
15806 dependent_type_p_r (tree type)
15807 {
15808   tree scope;
15809
15810   /* [temp.dep.type]
15811
15812      A type is dependent if it is:
15813
15814      -- a template parameter. Template template parameters are types
15815         for us (since TYPE_P holds true for them) so we handle
15816         them here.  */
15817   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
15818       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
15819     return true;
15820   /* -- a qualified-id with a nested-name-specifier which contains a
15821         class-name that names a dependent type or whose unqualified-id
15822         names a dependent type.  */
15823   if (TREE_CODE (type) == TYPENAME_TYPE)
15824     return true;
15825   /* -- a cv-qualified type where the cv-unqualified type is
15826         dependent.  */
15827   type = TYPE_MAIN_VARIANT (type);
15828   /* -- a compound type constructed from any dependent type.  */
15829   if (TYPE_PTR_TO_MEMBER_P (type))
15830     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
15831             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
15832                                            (type)));
15833   else if (TREE_CODE (type) == POINTER_TYPE
15834            || TREE_CODE (type) == REFERENCE_TYPE)
15835     return dependent_type_p (TREE_TYPE (type));
15836   else if (TREE_CODE (type) == FUNCTION_TYPE
15837            || TREE_CODE (type) == METHOD_TYPE)
15838     {
15839       tree arg_type;
15840
15841       if (dependent_type_p (TREE_TYPE (type)))
15842         return true;
15843       for (arg_type = TYPE_ARG_TYPES (type);
15844            arg_type;
15845            arg_type = TREE_CHAIN (arg_type))
15846         if (dependent_type_p (TREE_VALUE (arg_type)))
15847           return true;
15848       return false;
15849     }
15850   /* -- an array type constructed from any dependent type or whose
15851         size is specified by a constant expression that is
15852         value-dependent.  */
15853   if (TREE_CODE (type) == ARRAY_TYPE)
15854     {
15855       if (TYPE_DOMAIN (type)
15856           && dependent_type_p (TYPE_DOMAIN (type)))
15857         return true;
15858       return dependent_type_p (TREE_TYPE (type));
15859     }
15860   else if (TREE_CODE (type) == INTEGER_TYPE
15861            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
15862     {
15863       /* If this is the TYPE_DOMAIN of an array type, consider it
15864          dependent.  */
15865       return (value_dependent_expression_p (TYPE_MAX_VALUE (type))
15866               || type_dependent_expression_p (TYPE_MAX_VALUE (type)));
15867     }
15868
15869   /* -- a template-id in which either the template name is a template
15870      parameter ...  */
15871   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
15872     return true;
15873   /* ... or any of the template arguments is a dependent type or
15874         an expression that is type-dependent or value-dependent.  */
15875   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
15876            && (any_dependent_template_arguments_p
15877                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
15878     return true;
15879
15880   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
15881      argument of the `typeof' expression is not type-dependent, then
15882      it should already been have resolved.  */
15883   if (TREE_CODE (type) == TYPEOF_TYPE
15884       || TREE_CODE (type) == DECLTYPE_TYPE)
15885     return true;
15886
15887   /* A template argument pack is dependent if any of its packed
15888      arguments are.  */
15889   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
15890     {
15891       tree args = ARGUMENT_PACK_ARGS (type);
15892       int i, len = TREE_VEC_LENGTH (args);
15893       for (i = 0; i < len; ++i)
15894         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
15895           return true;
15896     }
15897
15898   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
15899      be template parameters.  */
15900   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
15901     return true;
15902
15903   /* The standard does not specifically mention types that are local
15904      to template functions or local classes, but they should be
15905      considered dependent too.  For example:
15906
15907        template <int I> void f() {
15908          enum E { a = I };
15909          S<sizeof (E)> s;
15910        }
15911
15912      The size of `E' cannot be known until the value of `I' has been
15913      determined.  Therefore, `E' must be considered dependent.  */
15914   scope = TYPE_CONTEXT (type);
15915   if (scope && TYPE_P (scope))
15916     return dependent_type_p (scope);
15917   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
15918     return type_dependent_expression_p (scope);
15919
15920   /* Other types are non-dependent.  */
15921   return false;
15922 }
15923
15924 /* Returns TRUE if TYPE is dependent, in the sense of
15925    [temp.dep.type].  */
15926
15927 bool
15928 dependent_type_p (tree type)
15929 {
15930   /* If there are no template parameters in scope, then there can't be
15931      any dependent types.  */
15932   if (!processing_template_decl)
15933     {
15934       /* If we are not processing a template, then nobody should be
15935          providing us with a dependent type.  */
15936       gcc_assert (type);
15937       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
15938       return false;
15939     }
15940
15941   /* If the type is NULL, we have not computed a type for the entity
15942      in question; in that case, the type is dependent.  */
15943   if (!type)
15944     return true;
15945
15946   /* Erroneous types can be considered non-dependent.  */
15947   if (type == error_mark_node)
15948     return false;
15949
15950   /* If we have not already computed the appropriate value for TYPE,
15951      do so now.  */
15952   if (!TYPE_DEPENDENT_P_VALID (type))
15953     {
15954       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
15955       TYPE_DEPENDENT_P_VALID (type) = 1;
15956     }
15957
15958   return TYPE_DEPENDENT_P (type);
15959 }
15960
15961 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
15962
15963 static bool
15964 dependent_scope_ref_p (tree expression, bool criterion (tree))
15965 {
15966   tree scope;
15967   tree name;
15968
15969   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
15970
15971   if (!TYPE_P (TREE_OPERAND (expression, 0)))
15972     return true;
15973
15974   scope = TREE_OPERAND (expression, 0);
15975   name = TREE_OPERAND (expression, 1);
15976
15977   /* [temp.dep.expr]
15978
15979      An id-expression is type-dependent if it contains a
15980      nested-name-specifier that contains a class-name that names a
15981      dependent type.  */
15982   /* The suggested resolution to Core Issue 2 implies that if the
15983      qualifying type is the current class, then we must peek
15984      inside it.  */
15985   if (DECL_P (name)
15986       && currently_open_class (scope)
15987       && !criterion (name))
15988     return false;
15989   if (dependent_type_p (scope))
15990     return true;
15991
15992   return false;
15993 }
15994
15995 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
15996    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
15997    expression.  */
15998
15999 bool
16000 value_dependent_expression_p (tree expression)
16001 {
16002   if (!processing_template_decl)
16003     return false;
16004
16005   /* A name declared with a dependent type.  */
16006   if (DECL_P (expression) && type_dependent_expression_p (expression))
16007     return true;
16008
16009   switch (TREE_CODE (expression))
16010     {
16011     case IDENTIFIER_NODE:
16012       /* A name that has not been looked up -- must be dependent.  */
16013       return true;
16014
16015     case TEMPLATE_PARM_INDEX:
16016       /* A non-type template parm.  */
16017       return true;
16018
16019     case CONST_DECL:
16020       /* A non-type template parm.  */
16021       if (DECL_TEMPLATE_PARM_P (expression))
16022         return true;
16023       return value_dependent_expression_p (DECL_INITIAL (expression));
16024
16025     case VAR_DECL:
16026        /* A constant with integral or enumeration type and is initialized
16027           with an expression that is value-dependent.  */
16028       if (DECL_INITIAL (expression)
16029           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
16030           && value_dependent_expression_p (DECL_INITIAL (expression)))
16031         return true;
16032       return false;
16033
16034     case DYNAMIC_CAST_EXPR:
16035     case STATIC_CAST_EXPR:
16036     case CONST_CAST_EXPR:
16037     case REINTERPRET_CAST_EXPR:
16038     case CAST_EXPR:
16039       /* These expressions are value-dependent if the type to which
16040          the cast occurs is dependent or the expression being casted
16041          is value-dependent.  */
16042       {
16043         tree type = TREE_TYPE (expression);
16044
16045         if (dependent_type_p (type))
16046           return true;
16047
16048         /* A functional cast has a list of operands.  */
16049         expression = TREE_OPERAND (expression, 0);
16050         if (!expression)
16051           {
16052             /* If there are no operands, it must be an expression such
16053                as "int()". This should not happen for aggregate types
16054                because it would form non-constant expressions.  */
16055             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
16056
16057             return false;
16058           }
16059
16060         if (TREE_CODE (expression) == TREE_LIST)
16061           return any_value_dependent_elements_p (expression);
16062
16063         return value_dependent_expression_p (expression);
16064       }
16065
16066     case SIZEOF_EXPR:
16067     case ALIGNOF_EXPR:
16068       /* A `sizeof' expression is value-dependent if the operand is
16069          type-dependent or is a pack expansion.  */
16070       expression = TREE_OPERAND (expression, 0);
16071       if (PACK_EXPANSION_P (expression))
16072         return true;
16073       else if (TYPE_P (expression))
16074         return dependent_type_p (expression);
16075       return type_dependent_expression_p (expression);
16076
16077     case SCOPE_REF:
16078       return dependent_scope_ref_p (expression, value_dependent_expression_p);
16079
16080     case COMPONENT_REF:
16081       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
16082               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
16083
16084     case CALL_EXPR:
16085       /* A CALL_EXPR may appear in a constant expression if it is a
16086          call to a builtin function, e.g., __builtin_constant_p.  All
16087          such calls are value-dependent.  */
16088       return true;
16089
16090     case NONTYPE_ARGUMENT_PACK:
16091       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
16092          is value-dependent.  */
16093       {
16094         tree values = ARGUMENT_PACK_ARGS (expression);
16095         int i, len = TREE_VEC_LENGTH (values);
16096         
16097         for (i = 0; i < len; ++i)
16098           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
16099             return true;
16100         
16101         return false;
16102       }
16103
16104     case TRAIT_EXPR:
16105       {
16106         tree type2 = TRAIT_EXPR_TYPE2 (expression);
16107         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
16108                 || (type2 ? dependent_type_p (type2) : false));
16109       }
16110
16111     case MODOP_EXPR:
16112       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
16113               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
16114
16115     default:
16116       /* A constant expression is value-dependent if any subexpression is
16117          value-dependent.  */
16118       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
16119         {
16120         case tcc_reference:
16121         case tcc_unary:
16122           return (value_dependent_expression_p
16123                   (TREE_OPERAND (expression, 0)));
16124
16125         case tcc_comparison:
16126         case tcc_binary:
16127           return ((value_dependent_expression_p
16128                    (TREE_OPERAND (expression, 0)))
16129                   || (value_dependent_expression_p
16130                       (TREE_OPERAND (expression, 1))));
16131
16132         case tcc_expression:
16133         case tcc_vl_exp:
16134           {
16135             int i;
16136             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
16137               /* In some cases, some of the operands may be missing.
16138                  (For example, in the case of PREDECREMENT_EXPR, the
16139                  amount to increment by may be missing.)  That doesn't
16140                  make the expression dependent.  */
16141               if (TREE_OPERAND (expression, i)
16142                   && (value_dependent_expression_p
16143                       (TREE_OPERAND (expression, i))))
16144                 return true;
16145             return false;
16146           }
16147
16148         default:
16149           break;
16150         }
16151     }
16152
16153   /* The expression is not value-dependent.  */
16154   return false;
16155 }
16156
16157 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
16158    [temp.dep.expr].  */
16159
16160 bool
16161 type_dependent_expression_p (tree expression)
16162 {
16163   if (!processing_template_decl)
16164     return false;
16165
16166   if (expression == error_mark_node)
16167     return false;
16168
16169   /* An unresolved name is always dependent.  */
16170   if (TREE_CODE (expression) == IDENTIFIER_NODE
16171       || TREE_CODE (expression) == USING_DECL)
16172     return true;
16173
16174   /* Some expression forms are never type-dependent.  */
16175   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
16176       || TREE_CODE (expression) == SIZEOF_EXPR
16177       || TREE_CODE (expression) == ALIGNOF_EXPR
16178       || TREE_CODE (expression) == TRAIT_EXPR
16179       || TREE_CODE (expression) == TYPEID_EXPR
16180       || TREE_CODE (expression) == DELETE_EXPR
16181       || TREE_CODE (expression) == VEC_DELETE_EXPR
16182       || TREE_CODE (expression) == THROW_EXPR)
16183     return false;
16184
16185   /* The types of these expressions depends only on the type to which
16186      the cast occurs.  */
16187   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
16188       || TREE_CODE (expression) == STATIC_CAST_EXPR
16189       || TREE_CODE (expression) == CONST_CAST_EXPR
16190       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
16191       || TREE_CODE (expression) == CAST_EXPR)
16192     return dependent_type_p (TREE_TYPE (expression));
16193
16194   /* The types of these expressions depends only on the type created
16195      by the expression.  */
16196   if (TREE_CODE (expression) == NEW_EXPR
16197       || TREE_CODE (expression) == VEC_NEW_EXPR)
16198     {
16199       /* For NEW_EXPR tree nodes created inside a template, either
16200          the object type itself or a TREE_LIST may appear as the
16201          operand 1.  */
16202       tree type = TREE_OPERAND (expression, 1);
16203       if (TREE_CODE (type) == TREE_LIST)
16204         /* This is an array type.  We need to check array dimensions
16205            as well.  */
16206         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
16207                || value_dependent_expression_p
16208                     (TREE_OPERAND (TREE_VALUE (type), 1));
16209       else
16210         return dependent_type_p (type);
16211     }
16212
16213   if (TREE_CODE (expression) == SCOPE_REF
16214       && dependent_scope_ref_p (expression,
16215                                 type_dependent_expression_p))
16216     return true;
16217
16218   if (TREE_CODE (expression) == FUNCTION_DECL
16219       && DECL_LANG_SPECIFIC (expression)
16220       && DECL_TEMPLATE_INFO (expression)
16221       && (any_dependent_template_arguments_p
16222           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
16223     return true;
16224
16225   if (TREE_CODE (expression) == TEMPLATE_DECL
16226       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
16227     return false;
16228
16229   if (TREE_CODE (expression) == STMT_EXPR)
16230     expression = stmt_expr_value_expr (expression);
16231
16232   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
16233     {
16234       tree elt;
16235       unsigned i;
16236
16237       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
16238         {
16239           if (type_dependent_expression_p (elt))
16240             return true;
16241         }
16242       return false;
16243     }
16244
16245   if (TREE_TYPE (expression) == unknown_type_node)
16246     {
16247       if (TREE_CODE (expression) == ADDR_EXPR)
16248         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
16249       if (TREE_CODE (expression) == COMPONENT_REF
16250           || TREE_CODE (expression) == OFFSET_REF)
16251         {
16252           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
16253             return true;
16254           expression = TREE_OPERAND (expression, 1);
16255           if (TREE_CODE (expression) == IDENTIFIER_NODE)
16256             return false;
16257         }
16258       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
16259       if (TREE_CODE (expression) == SCOPE_REF)
16260         return false;
16261
16262       if (TREE_CODE (expression) == BASELINK)
16263         expression = BASELINK_FUNCTIONS (expression);
16264
16265       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
16266         {
16267           if (any_dependent_template_arguments_p
16268               (TREE_OPERAND (expression, 1)))
16269             return true;
16270           expression = TREE_OPERAND (expression, 0);
16271         }
16272       gcc_assert (TREE_CODE (expression) == OVERLOAD
16273                   || TREE_CODE (expression) == FUNCTION_DECL);
16274
16275       while (expression)
16276         {
16277           if (type_dependent_expression_p (OVL_CURRENT (expression)))
16278             return true;
16279           expression = OVL_NEXT (expression);
16280         }
16281       return false;
16282     }
16283
16284   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
16285
16286   return (dependent_type_p (TREE_TYPE (expression)));
16287 }
16288
16289 /* Returns TRUE if ARGS (a TREE_LIST of arguments to a function call)
16290    contains a type-dependent expression.  */
16291
16292 bool
16293 any_type_dependent_arguments_p (const_tree args)
16294 {
16295   while (args)
16296     {
16297       tree arg = TREE_VALUE (args);
16298
16299       if (type_dependent_expression_p (arg))
16300         return true;
16301       args = TREE_CHAIN (args);
16302     }
16303   return false;
16304 }
16305
16306 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
16307    expressions) contains any value-dependent expressions.  */
16308
16309 bool
16310 any_value_dependent_elements_p (const_tree list)
16311 {
16312   for (; list; list = TREE_CHAIN (list))
16313     if (value_dependent_expression_p (TREE_VALUE (list)))
16314       return true;
16315
16316   return false;
16317 }
16318
16319 /* Returns TRUE if the ARG (a template argument) is dependent.  */
16320
16321 bool
16322 dependent_template_arg_p (tree arg)
16323 {
16324   if (!processing_template_decl)
16325     return false;
16326
16327   if (TREE_CODE (arg) == TEMPLATE_DECL
16328       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16329     return dependent_template_p (arg);
16330   else if (ARGUMENT_PACK_P (arg))
16331     {
16332       tree args = ARGUMENT_PACK_ARGS (arg);
16333       int i, len = TREE_VEC_LENGTH (args);
16334       for (i = 0; i < len; ++i)
16335         {
16336           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16337             return true;
16338         }
16339
16340       return false;
16341     }
16342   else if (TYPE_P (arg))
16343     return dependent_type_p (arg);
16344   else
16345     return (type_dependent_expression_p (arg)
16346             || value_dependent_expression_p (arg));
16347 }
16348
16349 /* Returns true if ARGS (a collection of template arguments) contains
16350    any types that require structural equality testing.  */
16351
16352 bool
16353 any_template_arguments_need_structural_equality_p (tree args)
16354 {
16355   int i;
16356   int j;
16357
16358   if (!args)
16359     return false;
16360   if (args == error_mark_node)
16361     return true;
16362
16363   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16364     {
16365       tree level = TMPL_ARGS_LEVEL (args, i + 1);
16366       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16367         {
16368           tree arg = TREE_VEC_ELT (level, j);
16369           tree packed_args = NULL_TREE;
16370           int k, len = 1;
16371
16372           if (ARGUMENT_PACK_P (arg))
16373             {
16374               /* Look inside the argument pack.  */
16375               packed_args = ARGUMENT_PACK_ARGS (arg);
16376               len = TREE_VEC_LENGTH (packed_args);
16377             }
16378
16379           for (k = 0; k < len; ++k)
16380             {
16381               if (packed_args)
16382                 arg = TREE_VEC_ELT (packed_args, k);
16383
16384               if (error_operand_p (arg))
16385                 return true;
16386               else if (TREE_CODE (arg) == TEMPLATE_DECL
16387                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16388                 continue;
16389               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
16390                 return true;
16391               else if (!TYPE_P (arg) && TREE_TYPE (arg)
16392                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
16393                 return true;
16394             }
16395         }
16396     }
16397
16398   return false;
16399 }
16400
16401 /* Returns true if ARGS (a collection of template arguments) contains
16402    any dependent arguments.  */
16403
16404 bool
16405 any_dependent_template_arguments_p (const_tree args)
16406 {
16407   int i;
16408   int j;
16409
16410   if (!args)
16411     return false;
16412   if (args == error_mark_node)
16413     return true;
16414
16415   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16416     {
16417       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
16418       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16419         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
16420           return true;
16421     }
16422
16423   return false;
16424 }
16425
16426 /* Returns TRUE if the template TMPL is dependent.  */
16427
16428 bool
16429 dependent_template_p (tree tmpl)
16430 {
16431   if (TREE_CODE (tmpl) == OVERLOAD)
16432     {
16433       while (tmpl)
16434         {
16435           if (dependent_template_p (OVL_FUNCTION (tmpl)))
16436             return true;
16437           tmpl = OVL_CHAIN (tmpl);
16438         }
16439       return false;
16440     }
16441
16442   /* Template template parameters are dependent.  */
16443   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
16444       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16445     return true;
16446   /* So are names that have not been looked up.  */
16447   if (TREE_CODE (tmpl) == SCOPE_REF
16448       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
16449     return true;
16450   /* So are member templates of dependent classes.  */
16451   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
16452     return dependent_type_p (DECL_CONTEXT (tmpl));
16453   return false;
16454 }
16455
16456 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
16457
16458 bool
16459 dependent_template_id_p (tree tmpl, tree args)
16460 {
16461   return (dependent_template_p (tmpl)
16462           || any_dependent_template_arguments_p (args));
16463 }
16464
16465 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
16466    is dependent.  */
16467
16468 bool
16469 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
16470 {
16471   int i;
16472
16473   if (!processing_template_decl)
16474     return false;
16475
16476   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
16477     {
16478       tree decl = TREE_VEC_ELT (declv, i);
16479       tree init = TREE_VEC_ELT (initv, i);
16480       tree cond = TREE_VEC_ELT (condv, i);
16481       tree incr = TREE_VEC_ELT (incrv, i);
16482
16483       if (type_dependent_expression_p (decl))
16484         return true;
16485
16486       if (init && type_dependent_expression_p (init))
16487         return true;
16488
16489       if (type_dependent_expression_p (cond))
16490         return true;
16491
16492       if (COMPARISON_CLASS_P (cond)
16493           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
16494               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
16495         return true;
16496
16497       if (TREE_CODE (incr) == MODOP_EXPR)
16498         {
16499           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
16500               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
16501             return true;
16502         }
16503       else if (type_dependent_expression_p (incr))
16504         return true;
16505       else if (TREE_CODE (incr) == MODIFY_EXPR)
16506         {
16507           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
16508             return true;
16509           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
16510             {
16511               tree t = TREE_OPERAND (incr, 1);
16512               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
16513                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
16514                 return true;
16515             }
16516         }
16517     }
16518
16519   return false;
16520 }
16521
16522 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
16523    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
16524    no such TYPE can be found.  Note that this function peers inside
16525    uninstantiated templates and therefore should be used only in
16526    extremely limited situations.  ONLY_CURRENT_P restricts this
16527    peering to the currently open classes hierarchy (which is required
16528    when comparing types).  */
16529
16530 tree
16531 resolve_typename_type (tree type, bool only_current_p)
16532 {
16533   tree scope;
16534   tree name;
16535   tree decl;
16536   int quals;
16537   tree pushed_scope;
16538   tree result;
16539
16540   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
16541
16542   scope = TYPE_CONTEXT (type);
16543   name = TYPE_IDENTIFIER (type);
16544
16545   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
16546      it first before we can figure out what NAME refers to.  */
16547   if (TREE_CODE (scope) == TYPENAME_TYPE)
16548     scope = resolve_typename_type (scope, only_current_p);
16549   /* If we don't know what SCOPE refers to, then we cannot resolve the
16550      TYPENAME_TYPE.  */
16551   if (TREE_CODE (scope) == TYPENAME_TYPE)
16552     return type;
16553   /* If the SCOPE is a template type parameter, we have no way of
16554      resolving the name.  */
16555   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
16556     return type;
16557   /* If the SCOPE is not the current instantiation, there's no reason
16558      to look inside it.  */
16559   if (only_current_p && !currently_open_class (scope))
16560     return type;
16561   /* If SCOPE isn't the template itself, it will not have a valid
16562      TYPE_FIELDS list.  */
16563   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
16564     /* scope is either the template itself or a compatible instantiation
16565        like X<T>, so look up the name in the original template.  */
16566     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
16567   else
16568     /* scope is a partial instantiation, so we can't do the lookup or we
16569        will lose the template arguments.  */
16570     return type;
16571   /* Enter the SCOPE so that name lookup will be resolved as if we
16572      were in the class definition.  In particular, SCOPE will no
16573      longer be considered a dependent type.  */
16574   pushed_scope = push_scope (scope);
16575   /* Look up the declaration.  */
16576   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
16577
16578   result = NULL_TREE;
16579   
16580   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
16581      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
16582   if (!decl)
16583     /*nop*/;
16584   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
16585            && TREE_CODE (decl) == TYPE_DECL)
16586     {
16587       result = TREE_TYPE (decl);
16588       if (result == error_mark_node)
16589         result = NULL_TREE;
16590     }
16591   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
16592            && DECL_CLASS_TEMPLATE_P (decl))
16593     {
16594       tree tmpl;
16595       tree args;
16596       /* Obtain the template and the arguments.  */
16597       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
16598       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
16599       /* Instantiate the template.  */
16600       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
16601                                       /*entering_scope=*/0,
16602                                       tf_error | tf_user);
16603       if (result == error_mark_node)
16604         result = NULL_TREE;
16605     }
16606   
16607   /* Leave the SCOPE.  */
16608   if (pushed_scope)
16609     pop_scope (pushed_scope);
16610
16611   /* If we failed to resolve it, return the original typename.  */
16612   if (!result)
16613     return type;
16614   
16615   /* If lookup found a typename type, resolve that too.  */
16616   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
16617     {
16618       /* Ill-formed programs can cause infinite recursion here, so we
16619          must catch that.  */
16620       TYPENAME_IS_RESOLVING_P (type) = 1;
16621       result = resolve_typename_type (result, only_current_p);
16622       TYPENAME_IS_RESOLVING_P (type) = 0;
16623     }
16624   
16625   /* Qualify the resulting type.  */
16626   quals = cp_type_quals (type);
16627   if (quals)
16628     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
16629
16630   return result;
16631 }
16632
16633 /* EXPR is an expression which is not type-dependent.  Return a proxy
16634    for EXPR that can be used to compute the types of larger
16635    expressions containing EXPR.  */
16636
16637 tree
16638 build_non_dependent_expr (tree expr)
16639 {
16640   tree inner_expr;
16641
16642   /* Preserve null pointer constants so that the type of things like
16643      "p == 0" where "p" is a pointer can be determined.  */
16644   if (null_ptr_cst_p (expr))
16645     return expr;
16646   /* Preserve OVERLOADs; the functions must be available to resolve
16647      types.  */
16648   inner_expr = expr;
16649   if (TREE_CODE (inner_expr) == STMT_EXPR)
16650     inner_expr = stmt_expr_value_expr (inner_expr);
16651   if (TREE_CODE (inner_expr) == ADDR_EXPR)
16652     inner_expr = TREE_OPERAND (inner_expr, 0);
16653   if (TREE_CODE (inner_expr) == COMPONENT_REF)
16654     inner_expr = TREE_OPERAND (inner_expr, 1);
16655   if (is_overloaded_fn (inner_expr)
16656       || TREE_CODE (inner_expr) == OFFSET_REF)
16657     return expr;
16658   /* There is no need to return a proxy for a variable.  */
16659   if (TREE_CODE (expr) == VAR_DECL)
16660     return expr;
16661   /* Preserve string constants; conversions from string constants to
16662      "char *" are allowed, even though normally a "const char *"
16663      cannot be used to initialize a "char *".  */
16664   if (TREE_CODE (expr) == STRING_CST)
16665     return expr;
16666   /* Preserve arithmetic constants, as an optimization -- there is no
16667      reason to create a new node.  */
16668   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
16669     return expr;
16670   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
16671      There is at least one place where we want to know that a
16672      particular expression is a throw-expression: when checking a ?:
16673      expression, there are special rules if the second or third
16674      argument is a throw-expression.  */
16675   if (TREE_CODE (expr) == THROW_EXPR)
16676     return expr;
16677
16678   if (TREE_CODE (expr) == COND_EXPR)
16679     return build3 (COND_EXPR,
16680                    TREE_TYPE (expr),
16681                    TREE_OPERAND (expr, 0),
16682                    (TREE_OPERAND (expr, 1)
16683                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
16684                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
16685                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
16686   if (TREE_CODE (expr) == COMPOUND_EXPR
16687       && !COMPOUND_EXPR_OVERLOADED (expr))
16688     return build2 (COMPOUND_EXPR,
16689                    TREE_TYPE (expr),
16690                    TREE_OPERAND (expr, 0),
16691                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
16692
16693   /* If the type is unknown, it can't really be non-dependent */
16694   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
16695
16696   /* Otherwise, build a NON_DEPENDENT_EXPR.
16697
16698      REFERENCE_TYPEs are not stripped for expressions in templates
16699      because doing so would play havoc with mangling.  Consider, for
16700      example:
16701
16702        template <typename T> void f<T& g>() { g(); }
16703
16704      In the body of "f", the expression for "g" will have
16705      REFERENCE_TYPE, even though the standard says that it should
16706      not.  The reason is that we must preserve the syntactic form of
16707      the expression so that mangling (say) "f<g>" inside the body of
16708      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
16709      stripped here.  */
16710   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
16711 }
16712
16713 /* ARGS is a TREE_LIST of expressions as arguments to a function call.
16714    Return a new TREE_LIST with the various arguments replaced with
16715    equivalent non-dependent expressions.  */
16716
16717 tree
16718 build_non_dependent_args (tree args)
16719 {
16720   tree a;
16721   tree new_args;
16722
16723   new_args = NULL_TREE;
16724   for (a = args; a; a = TREE_CHAIN (a))
16725     new_args = tree_cons (NULL_TREE,
16726                           build_non_dependent_expr (TREE_VALUE (a)),
16727                           new_args);
16728   return nreverse (new_args);
16729 }
16730
16731 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
16732    with a level one deeper than the actual template parms.  */
16733
16734 tree
16735 make_auto (void)
16736 {
16737   tree au;
16738
16739   /* ??? Is it worth caching this for multiple autos at the same level?  */
16740   au = cxx_make_type (TEMPLATE_TYPE_PARM);
16741   TYPE_NAME (au) = build_decl (TYPE_DECL, get_identifier ("auto"), au);
16742   TYPE_STUB_DECL (au) = TYPE_NAME (au);
16743   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
16744     (0, processing_template_decl + 1, processing_template_decl + 1,
16745      TYPE_NAME (au), NULL_TREE);
16746   TYPE_CANONICAL (au) = canonical_type_parameter (au);
16747   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
16748   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
16749
16750   return au;
16751 }
16752
16753 /* Replace auto in TYPE with std::initializer_list<auto>.  */
16754
16755 static tree
16756 listify_autos (tree type, tree auto_node)
16757 {
16758   tree std_init_list = namespace_binding
16759     (get_identifier ("initializer_list"), std_node);
16760   tree argvec;
16761   tree init_auto;
16762   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
16763     {    
16764       error ("deducing auto from brace-enclosed initializer list requires "
16765              "#include <initializer_list>");
16766       return error_mark_node;
16767     }
16768   argvec = make_tree_vec (1);
16769   TREE_VEC_ELT (argvec, 0) = auto_node;
16770   init_auto = lookup_template_class (std_init_list, argvec, NULL_TREE,
16771                                      NULL_TREE, 0, tf_warning_or_error);
16772
16773   TREE_VEC_ELT (argvec, 0) = init_auto;
16774   if (processing_template_decl)
16775     argvec = add_to_template_args (current_template_args (), argvec);
16776   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
16777 }
16778
16779 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
16780    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
16781
16782 tree
16783 do_auto_deduction (tree type, tree init, tree auto_node)
16784 {
16785   tree parms, args, tparms, targs;
16786   int val;
16787
16788   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
16789      with either a new invented type template parameter U or, if the
16790      initializer is a braced-init-list (8.5.4), with
16791      std::initializer_list<U>.  */
16792   if (BRACE_ENCLOSED_INITIALIZER_P (init))
16793     type = listify_autos (type, auto_node);
16794
16795   parms = build_tree_list (NULL_TREE, type);
16796   args = build_tree_list (NULL_TREE, init);
16797   tparms = make_tree_vec (1);
16798   targs = make_tree_vec (1);
16799   TREE_VEC_ELT (tparms, 0)
16800     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
16801   val = type_unification_real (tparms, targs, parms, args, 0,
16802                                DEDUCE_CALL, LOOKUP_NORMAL);
16803   if (val > 0)
16804     {
16805       error ("unable to deduce %qT from %qE", type, init);
16806       return error_mark_node;
16807     }
16808
16809   if (processing_template_decl)
16810     targs = add_to_template_args (current_template_args (), targs);
16811   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
16812 }
16813
16814 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
16815    result.  */
16816
16817 tree
16818 splice_late_return_type (tree type, tree late_return_type)
16819 {
16820   tree argvec;
16821
16822   if (late_return_type == NULL_TREE)
16823     return type;
16824   argvec = make_tree_vec (1);
16825   TREE_VEC_ELT (argvec, 0) = late_return_type;
16826   if (processing_template_decl)
16827     argvec = add_to_template_args (current_template_args (), argvec);
16828   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
16829 }
16830
16831 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
16832
16833 bool
16834 is_auto (const_tree type)
16835 {
16836   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16837       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
16838     return true;
16839   else
16840     return false;
16841 }
16842
16843 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
16844    appear as a type-specifier for the declaration in question, we don't
16845    have to look through the whole type.  */
16846
16847 tree
16848 type_uses_auto (tree type)
16849 {
16850   enum tree_code code;
16851   if (is_auto (type))
16852     return type;
16853
16854   code = TREE_CODE (type);
16855
16856   if (code == POINTER_TYPE || code == REFERENCE_TYPE
16857       || code == OFFSET_TYPE || code == FUNCTION_TYPE
16858       || code == METHOD_TYPE || code == ARRAY_TYPE)
16859     return type_uses_auto (TREE_TYPE (type));
16860
16861   if (TYPE_PTRMEMFUNC_P (type))
16862     return type_uses_auto (TREE_TYPE (TREE_TYPE
16863                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
16864
16865   return NULL_TREE;
16866 }
16867
16868 #include "gt-cp-pt.h"