OSDN Git Service

Fix PR c++/41785
[pf3gnuchains/gcc-fork.git] / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU C++.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009
4    Free Software Foundation, Inc.
5    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
6    Rewritten by Jason Merrill (jason@cygnus.com).
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
14
15 GCC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
24 /* Known bugs or deficiencies include:
25
26      all methods must be provided in header files; can't use a source
27      file that contains only the method templates and "just win".  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "tm.h"
33 #include "obstack.h"
34 #include "tree.h"
35 #include "pointer-set.h"
36 #include "flags.h"
37 #include "c-common.h"
38 #include "cp-tree.h"
39 #include "cp-objcp-common.h"
40 #include "tree-inline.h"
41 #include "decl.h"
42 #include "output.h"
43 #include "except.h"
44 #include "toplev.h"
45 #include "rtl.h"
46 #include "timevar.h"
47 #include "tree-iterator.h"
48 #include "vecprim.h"
49
50 /* The type of functions taking a tree, and some additional data, and
51    returning an int.  */
52 typedef int (*tree_fn_t) (tree, void*);
53
54 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
55    instantiations have been deferred, either because their definitions
56    were not yet available, or because we were putting off doing the work.  */
57 struct GTY (()) pending_template {
58   struct pending_template *next;
59   struct tinst_level *tinst;
60 };
61
62 static GTY(()) struct pending_template *pending_templates;
63 static GTY(()) struct pending_template *last_pending_template;
64
65 int processing_template_parmlist;
66 static int template_header_count;
67
68 static GTY(()) tree saved_trees;
69 static VEC(int,heap) *inline_parm_levels;
70
71 static GTY(()) struct tinst_level *current_tinst_level;
72
73 static GTY(()) tree saved_access_scope;
74
75 /* Live only within one (recursive) call to tsubst_expr.  We use
76    this to pass the statement expression node from the STMT_EXPR
77    to the EXPR_STMT that is its result.  */
78 static tree cur_stmt_expr;
79
80 /* A map from local variable declarations in the body of the template
81    presently being instantiated to the corresponding instantiated
82    local variables.  */
83 static htab_t local_specializations;
84
85 typedef struct GTY(()) spec_entry
86 {
87   tree tmpl;
88   tree args;
89   tree spec;
90 } spec_entry;
91
92 static GTY ((param_is (spec_entry)))
93   htab_t decl_specializations;
94
95 static GTY ((param_is (spec_entry)))
96   htab_t type_specializations;
97
98 /* Contains canonical template parameter types. The vector is indexed by
99    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
100    TREE_LIST, whose TREE_VALUEs contain the canonical template
101    parameters of various types and levels.  */
102 static GTY(()) VEC(tree,gc) *canonical_template_parms;
103
104 #define UNIFY_ALLOW_NONE 0
105 #define UNIFY_ALLOW_MORE_CV_QUAL 1
106 #define UNIFY_ALLOW_LESS_CV_QUAL 2
107 #define UNIFY_ALLOW_DERIVED 4
108 #define UNIFY_ALLOW_INTEGER 8
109 #define UNIFY_ALLOW_OUTER_LEVEL 16
110 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
111 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
112
113 static void push_access_scope (tree);
114 static void pop_access_scope (tree);
115 static bool resolve_overloaded_unification (tree, tree, tree, tree,
116                                             unification_kind_t, int);
117 static int try_one_overload (tree, tree, tree, tree, tree,
118                              unification_kind_t, int, bool);
119 static int unify (tree, tree, tree, tree, int);
120 static void add_pending_template (tree);
121 static int push_tinst_level (tree);
122 static void pop_tinst_level (void);
123 static tree reopen_tinst_level (struct tinst_level *);
124 static tree tsubst_initializer_list (tree, tree);
125 static tree get_class_bindings (tree, tree, tree);
126 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
127                                    bool, bool);
128 static void tsubst_enum (tree, tree, tree);
129 static tree add_to_template_args (tree, tree);
130 static tree add_outermost_template_args (tree, tree);
131 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
132 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
133                                              tree);
134 static int type_unification_real (tree, tree, tree, const tree *,
135                                   unsigned int, int, unification_kind_t, int);
136 static void note_template_header (int);
137 static tree convert_nontype_argument_function (tree, tree);
138 static tree convert_nontype_argument (tree, tree);
139 static tree convert_template_argument (tree, tree, tree,
140                                        tsubst_flags_t, int, tree);
141 static int for_each_template_parm (tree, tree_fn_t, void*,
142                                    struct pointer_set_t*, bool);
143 static tree expand_template_argument_pack (tree);
144 static tree build_template_parm_index (int, int, int, tree, tree);
145 static bool inline_needs_template_parms (tree);
146 static void push_inline_template_parms_recursive (tree, int);
147 static tree retrieve_local_specialization (tree);
148 static void register_local_specialization (tree, tree);
149 static hashval_t hash_specialization (const void *p);
150 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
151 static int mark_template_parm (tree, void *);
152 static int template_parm_this_level_p (tree, void *);
153 static tree tsubst_friend_function (tree, tree);
154 static tree tsubst_friend_class (tree, tree);
155 static int can_complete_type_without_circularity (tree);
156 static tree get_bindings (tree, tree, tree, bool);
157 static int template_decl_level (tree);
158 static int check_cv_quals_for_unify (int, tree, tree);
159 static void template_parm_level_and_index (tree, int*, int*);
160 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
161 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
162 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
163 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
164 static void regenerate_decl_from_template (tree, tree);
165 static tree most_specialized_class (tree, tree);
166 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
167 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
168 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
169 static bool check_specialization_scope (void);
170 static tree process_partial_specialization (tree);
171 static void set_current_access_from_decl (tree);
172 static tree get_template_base (tree, tree, tree, tree);
173 static tree try_class_unification (tree, tree, tree, tree);
174 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
175                                            tree, tree);
176 static bool template_template_parm_bindings_ok_p (tree, tree);
177 static int template_args_equal (tree, tree);
178 static void tsubst_default_arguments (tree);
179 static tree for_each_template_parm_r (tree *, int *, void *);
180 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
181 static void copy_default_args_to_explicit_spec (tree);
182 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
183 static int eq_local_specializations (const void *, const void *);
184 static bool dependent_template_arg_p (tree);
185 static bool any_template_arguments_need_structural_equality_p (tree);
186 static bool dependent_type_p_r (tree);
187 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
188 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
190 static tree tsubst_decl (tree, tree, tsubst_flags_t);
191 static void perform_typedefs_access_check (tree tmpl, tree targs);
192 static void append_type_to_template_for_access_check_1 (tree, tree, tree);
193 static hashval_t iterative_hash_template_arg (tree arg, hashval_t val);
194 static bool primary_template_instantiation_p (const_tree);
195 static tree listify (tree);
196 static tree listify_autos (tree, tree);
197
198 /* Make the current scope suitable for access checking when we are
199    processing T.  T can be FUNCTION_DECL for instantiated function
200    template, or VAR_DECL for static member variable (need by
201    instantiate_decl).  */
202
203 static void
204 push_access_scope (tree t)
205 {
206   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
207               || TREE_CODE (t) == VAR_DECL);
208
209   if (DECL_FRIEND_CONTEXT (t))
210     push_nested_class (DECL_FRIEND_CONTEXT (t));
211   else if (DECL_CLASS_SCOPE_P (t))
212     push_nested_class (DECL_CONTEXT (t));
213   else
214     push_to_top_level ();
215
216   if (TREE_CODE (t) == FUNCTION_DECL)
217     {
218       saved_access_scope = tree_cons
219         (NULL_TREE, current_function_decl, saved_access_scope);
220       current_function_decl = t;
221     }
222 }
223
224 /* Restore the scope set up by push_access_scope.  T is the node we
225    are processing.  */
226
227 static void
228 pop_access_scope (tree t)
229 {
230   if (TREE_CODE (t) == FUNCTION_DECL)
231     {
232       current_function_decl = TREE_VALUE (saved_access_scope);
233       saved_access_scope = TREE_CHAIN (saved_access_scope);
234     }
235
236   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
237     pop_nested_class ();
238   else
239     pop_from_top_level ();
240 }
241
242 /* Do any processing required when DECL (a member template
243    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
244    to DECL, unless it is a specialization, in which case the DECL
245    itself is returned.  */
246
247 tree
248 finish_member_template_decl (tree decl)
249 {
250   if (decl == error_mark_node)
251     return error_mark_node;
252
253   gcc_assert (DECL_P (decl));
254
255   if (TREE_CODE (decl) == TYPE_DECL)
256     {
257       tree type;
258
259       type = TREE_TYPE (decl);
260       if (type == error_mark_node)
261         return error_mark_node;
262       if (MAYBE_CLASS_TYPE_P (type)
263           && CLASSTYPE_TEMPLATE_INFO (type)
264           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
265         {
266           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
267           check_member_template (tmpl);
268           return tmpl;
269         }
270       return NULL_TREE;
271     }
272   else if (TREE_CODE (decl) == FIELD_DECL)
273     error ("data member %qD cannot be a member template", decl);
274   else if (DECL_TEMPLATE_INFO (decl))
275     {
276       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
277         {
278           check_member_template (DECL_TI_TEMPLATE (decl));
279           return DECL_TI_TEMPLATE (decl);
280         }
281       else
282         return decl;
283     }
284   else
285     error ("invalid member template declaration %qD", decl);
286
287   return error_mark_node;
288 }
289
290 /* Return the template info node corresponding to T, whatever T is.  */
291
292 tree
293 get_template_info (const_tree t)
294 {
295   tree tinfo = NULL_TREE;
296
297   if (!t || t == error_mark_node)
298     return NULL;
299
300   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
301     tinfo = DECL_TEMPLATE_INFO (t);
302
303   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
304     t = TREE_TYPE (t);
305
306   if (TAGGED_TYPE_P (t))
307     tinfo = TYPE_TEMPLATE_INFO (t);
308
309   return tinfo;
310 }
311
312 /* Returns the template nesting level of the indicated class TYPE.
313
314    For example, in:
315      template <class T>
316      struct A
317      {
318        template <class U>
319        struct B {};
320      };
321
322    A<T>::B<U> has depth two, while A<T> has depth one.
323    Both A<T>::B<int> and A<int>::B<U> have depth one, if
324    they are instantiations, not specializations.
325
326    This function is guaranteed to return 0 if passed NULL_TREE so
327    that, for example, `template_class_depth (current_class_type)' is
328    always safe.  */
329
330 int
331 template_class_depth (tree type)
332 {
333   int depth;
334
335   for (depth = 0;
336        type && TREE_CODE (type) != NAMESPACE_DECL;
337        type = (TREE_CODE (type) == FUNCTION_DECL)
338          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
339     {
340       tree tinfo = get_template_info (type);
341
342       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
343           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
344         ++depth;
345     }
346
347   return depth;
348 }
349
350 /* Subroutine of maybe_begin_member_template_processing.
351    Returns true if processing DECL needs us to push template parms.  */
352
353 static bool
354 inline_needs_template_parms (tree decl)
355 {
356   if (! DECL_TEMPLATE_INFO (decl))
357     return false;
358
359   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
360           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
361 }
362
363 /* Subroutine of maybe_begin_member_template_processing.
364    Push the template parms in PARMS, starting from LEVELS steps into the
365    chain, and ending at the beginning, since template parms are listed
366    innermost first.  */
367
368 static void
369 push_inline_template_parms_recursive (tree parmlist, int levels)
370 {
371   tree parms = TREE_VALUE (parmlist);
372   int i;
373
374   if (levels > 1)
375     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
376
377   ++processing_template_decl;
378   current_template_parms
379     = tree_cons (size_int (processing_template_decl),
380                  parms, current_template_parms);
381   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
382
383   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
384                NULL);
385   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
386     {
387       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
388
389       if (parm == error_mark_node)
390         continue;
391
392       gcc_assert (DECL_P (parm));
393
394       switch (TREE_CODE (parm))
395         {
396         case TYPE_DECL:
397         case TEMPLATE_DECL:
398           pushdecl (parm);
399           break;
400
401         case PARM_DECL:
402           {
403             /* Make a CONST_DECL as is done in process_template_parm.
404                It is ugly that we recreate this here; the original
405                version built in process_template_parm is no longer
406                available.  */
407             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
408                                     CONST_DECL, DECL_NAME (parm),
409                                     TREE_TYPE (parm));
410             DECL_ARTIFICIAL (decl) = 1;
411             TREE_CONSTANT (decl) = 1;
412             TREE_READONLY (decl) = 1;
413             DECL_INITIAL (decl) = DECL_INITIAL (parm);
414             SET_DECL_TEMPLATE_PARM_P (decl);
415             pushdecl (decl);
416           }
417           break;
418
419         default:
420           gcc_unreachable ();
421         }
422     }
423 }
424
425 /* Restore the template parameter context for a member template or
426    a friend template defined in a class definition.  */
427
428 void
429 maybe_begin_member_template_processing (tree decl)
430 {
431   tree parms;
432   int levels = 0;
433
434   if (inline_needs_template_parms (decl))
435     {
436       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
437       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
438
439       if (DECL_TEMPLATE_SPECIALIZATION (decl))
440         {
441           --levels;
442           parms = TREE_CHAIN (parms);
443         }
444
445       push_inline_template_parms_recursive (parms, levels);
446     }
447
448   /* Remember how many levels of template parameters we pushed so that
449      we can pop them later.  */
450   VEC_safe_push (int, heap, inline_parm_levels, levels);
451 }
452
453 /* Undo the effects of maybe_begin_member_template_processing.  */
454
455 void
456 maybe_end_member_template_processing (void)
457 {
458   int i;
459   int last;
460
461   if (VEC_length (int, inline_parm_levels) == 0)
462     return;
463
464   last = VEC_pop (int, inline_parm_levels);
465   for (i = 0; i < last; ++i)
466     {
467       --processing_template_decl;
468       current_template_parms = TREE_CHAIN (current_template_parms);
469       poplevel (0, 0, 0);
470     }
471 }
472
473 /* Return a new template argument vector which contains all of ARGS,
474    but has as its innermost set of arguments the EXTRA_ARGS.  */
475
476 static tree
477 add_to_template_args (tree args, tree extra_args)
478 {
479   tree new_args;
480   int extra_depth;
481   int i;
482   int j;
483
484   extra_depth = TMPL_ARGS_DEPTH (extra_args);
485   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
486
487   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
488     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
489
490   for (j = 1; j <= extra_depth; ++j, ++i)
491     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
492
493   return new_args;
494 }
495
496 /* Like add_to_template_args, but only the outermost ARGS are added to
497    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
498    (EXTRA_ARGS) levels are added.  This function is used to combine
499    the template arguments from a partial instantiation with the
500    template arguments used to attain the full instantiation from the
501    partial instantiation.  */
502
503 static tree
504 add_outermost_template_args (tree args, tree extra_args)
505 {
506   tree new_args;
507
508   /* If there are more levels of EXTRA_ARGS than there are ARGS,
509      something very fishy is going on.  */
510   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
511
512   /* If *all* the new arguments will be the EXTRA_ARGS, just return
513      them.  */
514   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
515     return extra_args;
516
517   /* For the moment, we make ARGS look like it contains fewer levels.  */
518   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
519
520   new_args = add_to_template_args (args, extra_args);
521
522   /* Now, we restore ARGS to its full dimensions.  */
523   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
524
525   return new_args;
526 }
527
528 /* Return the N levels of innermost template arguments from the ARGS.  */
529
530 tree
531 get_innermost_template_args (tree args, int n)
532 {
533   tree new_args;
534   int extra_levels;
535   int i;
536
537   gcc_assert (n >= 0);
538
539   /* If N is 1, just return the innermost set of template arguments.  */
540   if (n == 1)
541     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
542
543   /* If we're not removing anything, just return the arguments we were
544      given.  */
545   extra_levels = TMPL_ARGS_DEPTH (args) - n;
546   gcc_assert (extra_levels >= 0);
547   if (extra_levels == 0)
548     return args;
549
550   /* Make a new set of arguments, not containing the outer arguments.  */
551   new_args = make_tree_vec (n);
552   for (i = 1; i <= n; ++i)
553     SET_TMPL_ARGS_LEVEL (new_args, i,
554                          TMPL_ARGS_LEVEL (args, i + extra_levels));
555
556   return new_args;
557 }
558
559 /* The inverse of get_innermost_template_args: Return all but the innermost
560    EXTRA_LEVELS levels of template arguments from the ARGS.  */
561
562 static tree
563 strip_innermost_template_args (tree args, int extra_levels)
564 {
565   tree new_args;
566   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
567   int i;
568
569   gcc_assert (n >= 0);
570
571   /* If N is 1, just return the outermost set of template arguments.  */
572   if (n == 1)
573     return TMPL_ARGS_LEVEL (args, 1);
574
575   /* If we're not removing anything, just return the arguments we were
576      given.  */
577   gcc_assert (extra_levels >= 0);
578   if (extra_levels == 0)
579     return args;
580
581   /* Make a new set of arguments, not containing the inner arguments.  */
582   new_args = make_tree_vec (n);
583   for (i = 1; i <= n; ++i)
584     SET_TMPL_ARGS_LEVEL (new_args, i,
585                          TMPL_ARGS_LEVEL (args, i));
586
587   return new_args;
588 }
589
590 /* We've got a template header coming up; push to a new level for storing
591    the parms.  */
592
593 void
594 begin_template_parm_list (void)
595 {
596   /* We use a non-tag-transparent scope here, which causes pushtag to
597      put tags in this scope, rather than in the enclosing class or
598      namespace scope.  This is the right thing, since we want
599      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
600      global template class, push_template_decl handles putting the
601      TEMPLATE_DECL into top-level scope.  For a nested template class,
602      e.g.:
603
604        template <class T> struct S1 {
605          template <class T> struct S2 {};
606        };
607
608      pushtag contains special code to call pushdecl_with_scope on the
609      TEMPLATE_DECL for S2.  */
610   begin_scope (sk_template_parms, NULL);
611   ++processing_template_decl;
612   ++processing_template_parmlist;
613   note_template_header (0);
614 }
615
616 /* This routine is called when a specialization is declared.  If it is
617    invalid to declare a specialization here, an error is reported and
618    false is returned, otherwise this routine will return true.  */
619
620 static bool
621 check_specialization_scope (void)
622 {
623   tree scope = current_scope ();
624
625   /* [temp.expl.spec]
626
627      An explicit specialization shall be declared in the namespace of
628      which the template is a member, or, for member templates, in the
629      namespace of which the enclosing class or enclosing class
630      template is a member.  An explicit specialization of a member
631      function, member class or static data member of a class template
632      shall be declared in the namespace of which the class template
633      is a member.  */
634   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
635     {
636       error ("explicit specialization in non-namespace scope %qD", scope);
637       return false;
638     }
639
640   /* [temp.expl.spec]
641
642      In an explicit specialization declaration for a member of a class
643      template or a member template that appears in namespace scope,
644      the member template and some of its enclosing class templates may
645      remain unspecialized, except that the declaration shall not
646      explicitly specialize a class member template if its enclosing
647      class templates are not explicitly specialized as well.  */
648   if (current_template_parms)
649     {
650       error ("enclosing class templates are not explicitly specialized");
651       return false;
652     }
653
654   return true;
655 }
656
657 /* We've just seen template <>.  */
658
659 bool
660 begin_specialization (void)
661 {
662   begin_scope (sk_template_spec, NULL);
663   note_template_header (1);
664   return check_specialization_scope ();
665 }
666
667 /* Called at then end of processing a declaration preceded by
668    template<>.  */
669
670 void
671 end_specialization (void)
672 {
673   finish_scope ();
674   reset_specialization ();
675 }
676
677 /* Any template <>'s that we have seen thus far are not referring to a
678    function specialization.  */
679
680 void
681 reset_specialization (void)
682 {
683   processing_specialization = 0;
684   template_header_count = 0;
685 }
686
687 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
688    it was of the form template <>.  */
689
690 static void
691 note_template_header (int specialization)
692 {
693   processing_specialization = specialization;
694   template_header_count++;
695 }
696
697 /* We're beginning an explicit instantiation.  */
698
699 void
700 begin_explicit_instantiation (void)
701 {
702   gcc_assert (!processing_explicit_instantiation);
703   processing_explicit_instantiation = true;
704 }
705
706
707 void
708 end_explicit_instantiation (void)
709 {
710   gcc_assert (processing_explicit_instantiation);
711   processing_explicit_instantiation = false;
712 }
713
714 /* An explicit specialization or partial specialization TMPL is being
715    declared.  Check that the namespace in which the specialization is
716    occurring is permissible.  Returns false iff it is invalid to
717    specialize TMPL in the current namespace.  */
718
719 static bool
720 check_specialization_namespace (tree tmpl)
721 {
722   tree tpl_ns = decl_namespace_context (tmpl);
723
724   /* [tmpl.expl.spec]
725
726      An explicit specialization shall be declared in the namespace of
727      which the template is a member, or, for member templates, in the
728      namespace of which the enclosing class or enclosing class
729      template is a member.  An explicit specialization of a member
730      function, member class or static data member of a class template
731      shall be declared in the namespace of which the class template is
732      a member.  */
733   if (is_associated_namespace (current_namespace, tpl_ns))
734     /* Same or super-using namespace.  */
735     return true;
736   else
737     {
738       permerror (input_location, "specialization of %qD in different namespace", tmpl);
739       permerror (input_location, "  from definition of %q+#D", tmpl);
740       return false;
741     }
742 }
743
744 /* SPEC is an explicit instantiation.  Check that it is valid to
745    perform this explicit instantiation in the current namespace.  */
746
747 static void
748 check_explicit_instantiation_namespace (tree spec)
749 {
750   tree ns;
751
752   /* DR 275: An explicit instantiation shall appear in an enclosing
753      namespace of its template.  */
754   ns = decl_namespace_context (spec);
755   if (!is_ancestor (current_namespace, ns))
756     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
757                "(which does not enclose namespace %qD)",
758                spec, current_namespace, ns);
759 }
760
761 /* The TYPE is being declared.  If it is a template type, that means it
762    is a partial specialization.  Do appropriate error-checking.  */
763
764 tree
765 maybe_process_partial_specialization (tree type)
766 {
767   tree context;
768
769   if (type == error_mark_node)
770     return error_mark_node;
771
772   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
773     {
774       error ("name of class shadows template template parameter %qD",
775              TYPE_NAME (type));
776       return error_mark_node;
777     }
778
779   context = TYPE_CONTEXT (type);
780
781   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
782     {
783       /* This is for ordinary explicit specialization and partial
784          specialization of a template class such as:
785
786            template <> class C<int>;
787
788          or:
789
790            template <class T> class C<T*>;
791
792          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
793
794       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
795           && !COMPLETE_TYPE_P (type))
796         {
797           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
798           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
799           if (processing_template_decl)
800             {
801               if (push_template_decl (TYPE_MAIN_DECL (type))
802                   == error_mark_node)
803                 return error_mark_node;
804             }
805         }
806       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
807         error ("specialization of %qT after instantiation", type);
808     }
809   else if (CLASS_TYPE_P (type)
810            && !CLASSTYPE_USE_TEMPLATE (type)
811            && CLASSTYPE_TEMPLATE_INFO (type)
812            && context && CLASS_TYPE_P (context)
813            && CLASSTYPE_TEMPLATE_INFO (context))
814     {
815       /* This is for an explicit specialization of member class
816          template according to [temp.expl.spec/18]:
817
818            template <> template <class U> class C<int>::D;
819
820          The context `C<int>' must be an implicit instantiation.
821          Otherwise this is just a member class template declared
822          earlier like:
823
824            template <> class C<int> { template <class U> class D; };
825            template <> template <class U> class C<int>::D;
826
827          In the first case, `C<int>::D' is a specialization of `C<T>::D'
828          while in the second case, `C<int>::D' is a primary template
829          and `C<T>::D' may not exist.  */
830
831       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
832           && !COMPLETE_TYPE_P (type))
833         {
834           tree t;
835           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
836
837           if (current_namespace
838               != decl_namespace_context (tmpl))
839             {
840               permerror (input_location, "specializing %q#T in different namespace", type);
841               permerror (input_location, "  from definition of %q+#D", tmpl);
842             }
843
844           /* Check for invalid specialization after instantiation:
845
846                template <> template <> class C<int>::D<int>;
847                template <> template <class U> class C<int>::D;  */
848
849           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
850                t; t = TREE_CHAIN (t))
851             {
852               tree inst = TREE_VALUE (t);
853               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
854                 {
855                   /* We already have a full specialization of this partial
856                      instantiation.  Reassign it to the new member
857                      specialization template.  */
858                   spec_entry elt;
859                   spec_entry **slot;
860
861                   elt.tmpl = most_general_template (tmpl);
862                   elt.args = CLASSTYPE_TI_ARGS (inst);
863                   elt.spec = inst;
864
865                   htab_remove_elt (type_specializations, &elt);
866
867                   elt.tmpl = tmpl;
868                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
869
870                   slot = (spec_entry **)
871                     htab_find_slot (type_specializations, &elt, INSERT);
872                   *slot = GGC_NEW (spec_entry);
873                   **slot = elt;
874                 }
875               else if (COMPLETE_TYPE_P (inst) || TYPE_BEING_DEFINED (inst))
876                 /* But if we've had an implicit instantiation, that's a
877                    problem ([temp.expl.spec]/6).  */
878                 error ("specialization %qT after instantiation %qT",
879                        type, inst);
880             }
881
882           /* Mark TYPE as a specialization.  And as a result, we only
883              have one level of template argument for the innermost
884              class template.  */
885           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
886           CLASSTYPE_TI_ARGS (type)
887             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
888         }
889     }
890   else if (processing_specialization)
891     {
892       error ("explicit specialization of non-template %qT", type);
893       return error_mark_node;
894     }
895
896   return type;
897 }
898
899 /* Returns nonzero if we can optimize the retrieval of specializations
900    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
901    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
902
903 static inline bool
904 optimize_specialization_lookup_p (tree tmpl)
905 {
906   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
907           && DECL_CLASS_SCOPE_P (tmpl)
908           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
909              parameter.  */
910           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
911           /* The optimized lookup depends on the fact that the
912              template arguments for the member function template apply
913              purely to the containing class, which is not true if the
914              containing class is an explicit or partial
915              specialization.  */
916           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
917           && !DECL_MEMBER_TEMPLATE_P (tmpl)
918           && !DECL_CONV_FN_P (tmpl)
919           /* It is possible to have a template that is not a member
920              template and is not a member of a template class:
921
922              template <typename T>
923              struct S { friend A::f(); };
924
925              Here, the friend function is a template, but the context does
926              not have template information.  The optimized lookup relies
927              on having ARGS be the template arguments for both the class
928              and the function template.  */
929           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
930 }
931
932 /* Retrieve the specialization (in the sense of [temp.spec] - a
933    specialization is either an instantiation or an explicit
934    specialization) of TMPL for the given template ARGS.  If there is
935    no such specialization, return NULL_TREE.  The ARGS are a vector of
936    arguments, or a vector of vectors of arguments, in the case of
937    templates with more than one level of parameters.
938
939    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
940    then we search for a partial specialization matching ARGS.  This
941    parameter is ignored if TMPL is not a class template.  */
942
943 static tree
944 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
945 {
946   if (args == error_mark_node)
947     return NULL_TREE;
948
949   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
950
951   /* There should be as many levels of arguments as there are
952      levels of parameters.  */
953   gcc_assert (TMPL_ARGS_DEPTH (args)
954               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
955
956   if (optimize_specialization_lookup_p (tmpl))
957     {
958       tree class_template;
959       tree class_specialization;
960       VEC(tree,gc) *methods;
961       tree fns;
962       int idx;
963
964       /* The template arguments actually apply to the containing
965          class.  Find the class specialization with those
966          arguments.  */
967       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
968       class_specialization
969         = retrieve_specialization (class_template, args, 0);
970       if (!class_specialization)
971         return NULL_TREE;
972       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
973          for the specialization.  */
974       idx = class_method_index_for_fn (class_specialization, tmpl);
975       if (idx == -1)
976         return NULL_TREE;
977       /* Iterate through the methods with the indicated name, looking
978          for the one that has an instance of TMPL.  */
979       methods = CLASSTYPE_METHOD_VEC (class_specialization);
980       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
981         {
982           tree fn = OVL_CURRENT (fns);
983           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
984               /* using-declarations can add base methods to the method vec,
985                  and we don't want those here.  */
986               && DECL_CONTEXT (fn) == class_specialization)
987             return fn;
988         }
989       return NULL_TREE;
990     }
991   else
992     {
993       spec_entry *found;
994       spec_entry elt;
995       htab_t specializations;
996
997       elt.tmpl = tmpl;
998       elt.args = args;
999       elt.spec = NULL_TREE;
1000
1001       if (DECL_CLASS_TEMPLATE_P (tmpl))
1002         specializations = type_specializations;
1003       else
1004         specializations = decl_specializations;
1005
1006       if (hash == 0)
1007         hash = hash_specialization (&elt);
1008       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1009       if (found)
1010         return found->spec;
1011     }
1012
1013   return NULL_TREE;
1014 }
1015
1016 /* Like retrieve_specialization, but for local declarations.  */
1017
1018 static tree
1019 retrieve_local_specialization (tree tmpl)
1020 {
1021   tree spec;
1022
1023   if (local_specializations == NULL)
1024     return NULL_TREE;
1025
1026   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1027                                      htab_hash_pointer (tmpl));
1028   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1029 }
1030
1031 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1032
1033 int
1034 is_specialization_of (tree decl, tree tmpl)
1035 {
1036   tree t;
1037
1038   if (TREE_CODE (decl) == FUNCTION_DECL)
1039     {
1040       for (t = decl;
1041            t != NULL_TREE;
1042            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1043         if (t == tmpl)
1044           return 1;
1045     }
1046   else
1047     {
1048       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1049
1050       for (t = TREE_TYPE (decl);
1051            t != NULL_TREE;
1052            t = CLASSTYPE_USE_TEMPLATE (t)
1053              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1054         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1055           return 1;
1056     }
1057
1058   return 0;
1059 }
1060
1061 /* Returns nonzero iff DECL is a specialization of friend declaration
1062    FRIEND_DECL according to [temp.friend].  */
1063
1064 bool
1065 is_specialization_of_friend (tree decl, tree friend_decl)
1066 {
1067   bool need_template = true;
1068   int template_depth;
1069
1070   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1071               || TREE_CODE (decl) == TYPE_DECL);
1072
1073   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1074      of a template class, we want to check if DECL is a specialization
1075      if this.  */
1076   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1077       && DECL_TEMPLATE_INFO (friend_decl)
1078       && !DECL_USE_TEMPLATE (friend_decl))
1079     {
1080       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1081       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1082       need_template = false;
1083     }
1084   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1085            && !PRIMARY_TEMPLATE_P (friend_decl))
1086     need_template = false;
1087
1088   /* There is nothing to do if this is not a template friend.  */
1089   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1090     return false;
1091
1092   if (is_specialization_of (decl, friend_decl))
1093     return true;
1094
1095   /* [temp.friend/6]
1096      A member of a class template may be declared to be a friend of a
1097      non-template class.  In this case, the corresponding member of
1098      every specialization of the class template is a friend of the
1099      class granting friendship.
1100
1101      For example, given a template friend declaration
1102
1103        template <class T> friend void A<T>::f();
1104
1105      the member function below is considered a friend
1106
1107        template <> struct A<int> {
1108          void f();
1109        };
1110
1111      For this type of template friend, TEMPLATE_DEPTH below will be
1112      nonzero.  To determine if DECL is a friend of FRIEND, we first
1113      check if the enclosing class is a specialization of another.  */
1114
1115   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1116   if (template_depth
1117       && DECL_CLASS_SCOPE_P (decl)
1118       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1119                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1120     {
1121       /* Next, we check the members themselves.  In order to handle
1122          a few tricky cases, such as when FRIEND_DECL's are
1123
1124            template <class T> friend void A<T>::g(T t);
1125            template <class T> template <T t> friend void A<T>::h();
1126
1127          and DECL's are
1128
1129            void A<int>::g(int);
1130            template <int> void A<int>::h();
1131
1132          we need to figure out ARGS, the template arguments from
1133          the context of DECL.  This is required for template substitution
1134          of `T' in the function parameter of `g' and template parameter
1135          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1136
1137       tree context = DECL_CONTEXT (decl);
1138       tree args = NULL_TREE;
1139       int current_depth = 0;
1140
1141       while (current_depth < template_depth)
1142         {
1143           if (CLASSTYPE_TEMPLATE_INFO (context))
1144             {
1145               if (current_depth == 0)
1146                 args = TYPE_TI_ARGS (context);
1147               else
1148                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1149               current_depth++;
1150             }
1151           context = TYPE_CONTEXT (context);
1152         }
1153
1154       if (TREE_CODE (decl) == FUNCTION_DECL)
1155         {
1156           bool is_template;
1157           tree friend_type;
1158           tree decl_type;
1159           tree friend_args_type;
1160           tree decl_args_type;
1161
1162           /* Make sure that both DECL and FRIEND_DECL are templates or
1163              non-templates.  */
1164           is_template = DECL_TEMPLATE_INFO (decl)
1165                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1166           if (need_template ^ is_template)
1167             return false;
1168           else if (is_template)
1169             {
1170               /* If both are templates, check template parameter list.  */
1171               tree friend_parms
1172                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1173                                          args, tf_none);
1174               if (!comp_template_parms
1175                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1176                       friend_parms))
1177                 return false;
1178
1179               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1180             }
1181           else
1182             decl_type = TREE_TYPE (decl);
1183
1184           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1185                                               tf_none, NULL_TREE);
1186           if (friend_type == error_mark_node)
1187             return false;
1188
1189           /* Check if return types match.  */
1190           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1191             return false;
1192
1193           /* Check if function parameter types match, ignoring the
1194              `this' parameter.  */
1195           friend_args_type = TYPE_ARG_TYPES (friend_type);
1196           decl_args_type = TYPE_ARG_TYPES (decl_type);
1197           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1198             friend_args_type = TREE_CHAIN (friend_args_type);
1199           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1200             decl_args_type = TREE_CHAIN (decl_args_type);
1201
1202           return compparms (decl_args_type, friend_args_type);
1203         }
1204       else
1205         {
1206           /* DECL is a TYPE_DECL */
1207           bool is_template;
1208           tree decl_type = TREE_TYPE (decl);
1209
1210           /* Make sure that both DECL and FRIEND_DECL are templates or
1211              non-templates.  */
1212           is_template
1213             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1214               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1215
1216           if (need_template ^ is_template)
1217             return false;
1218           else if (is_template)
1219             {
1220               tree friend_parms;
1221               /* If both are templates, check the name of the two
1222                  TEMPLATE_DECL's first because is_friend didn't.  */
1223               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1224                   != DECL_NAME (friend_decl))
1225                 return false;
1226
1227               /* Now check template parameter list.  */
1228               friend_parms
1229                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1230                                          args, tf_none);
1231               return comp_template_parms
1232                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1233                  friend_parms);
1234             }
1235           else
1236             return (DECL_NAME (decl)
1237                     == DECL_NAME (friend_decl));
1238         }
1239     }
1240   return false;
1241 }
1242
1243 /* Register the specialization SPEC as a specialization of TMPL with
1244    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1245    is actually just a friend declaration.  Returns SPEC, or an
1246    equivalent prior declaration, if available.  */
1247
1248 static tree
1249 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1250                          hashval_t hash)
1251 {
1252   tree fn;
1253   spec_entry **slot = NULL;
1254   spec_entry elt;
1255
1256   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1257
1258   if (TREE_CODE (spec) == FUNCTION_DECL
1259       && uses_template_parms (DECL_TI_ARGS (spec)))
1260     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1261        register it; we want the corresponding TEMPLATE_DECL instead.
1262        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1263        the more obvious `uses_template_parms (spec)' to avoid problems
1264        with default function arguments.  In particular, given
1265        something like this:
1266
1267           template <class T> void f(T t1, T t = T())
1268
1269        the default argument expression is not substituted for in an
1270        instantiation unless and until it is actually needed.  */
1271     return spec;
1272
1273   if (optimize_specialization_lookup_p (tmpl))
1274     /* We don't put these specializations in the hash table, but we might
1275        want to give an error about a mismatch.  */
1276     fn = retrieve_specialization (tmpl, args, 0);
1277   else
1278     {
1279       elt.tmpl = tmpl;
1280       elt.args = args;
1281       elt.spec = spec;
1282
1283       if (hash == 0)
1284         hash = hash_specialization (&elt);
1285
1286       slot = (spec_entry **)
1287         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1288       if (*slot)
1289         fn = (*slot)->spec;
1290       else
1291         fn = NULL_TREE;
1292     }
1293
1294   /* We can sometimes try to re-register a specialization that we've
1295      already got.  In particular, regenerate_decl_from_template calls
1296      duplicate_decls which will update the specialization list.  But,
1297      we'll still get called again here anyhow.  It's more convenient
1298      to simply allow this than to try to prevent it.  */
1299   if (fn == spec)
1300     return spec;
1301   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1302     {
1303       if (DECL_TEMPLATE_INSTANTIATION (fn))
1304         {
1305           if (DECL_ODR_USED (fn)
1306               || DECL_EXPLICIT_INSTANTIATION (fn))
1307             {
1308               error ("specialization of %qD after instantiation",
1309                      fn);
1310               return error_mark_node;
1311             }
1312           else
1313             {
1314               tree clone;
1315               /* This situation should occur only if the first
1316                  specialization is an implicit instantiation, the
1317                  second is an explicit specialization, and the
1318                  implicit instantiation has not yet been used.  That
1319                  situation can occur if we have implicitly
1320                  instantiated a member function and then specialized
1321                  it later.
1322
1323                  We can also wind up here if a friend declaration that
1324                  looked like an instantiation turns out to be a
1325                  specialization:
1326
1327                    template <class T> void foo(T);
1328                    class S { friend void foo<>(int) };
1329                    template <> void foo(int);
1330
1331                  We transform the existing DECL in place so that any
1332                  pointers to it become pointers to the updated
1333                  declaration.
1334
1335                  If there was a definition for the template, but not
1336                  for the specialization, we want this to look as if
1337                  there were no definition, and vice versa.  */
1338               DECL_INITIAL (fn) = NULL_TREE;
1339               duplicate_decls (spec, fn, is_friend);
1340               /* The call to duplicate_decls will have applied
1341                  [temp.expl.spec]:
1342
1343                    An explicit specialization of a function template
1344                    is inline only if it is explicitly declared to be,
1345                    and independently of whether its function template
1346                    is.
1347
1348                 to the primary function; now copy the inline bits to
1349                 the various clones.  */
1350               FOR_EACH_CLONE (clone, fn)
1351                 {
1352                   DECL_DECLARED_INLINE_P (clone)
1353                     = DECL_DECLARED_INLINE_P (fn);
1354                   DECL_SOURCE_LOCATION (clone)
1355                     = DECL_SOURCE_LOCATION (fn);
1356                 }
1357               check_specialization_namespace (fn);
1358
1359               return fn;
1360             }
1361         }
1362       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1363         {
1364           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1365             /* Dup decl failed, but this is a new definition. Set the
1366                line number so any errors match this new
1367                definition.  */
1368             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1369
1370           return fn;
1371         }
1372     }
1373   else if (fn)
1374     return duplicate_decls (spec, fn, is_friend);
1375
1376   /* A specialization must be declared in the same namespace as the
1377      template it is specializing.  */
1378   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1379       && !check_specialization_namespace (tmpl))
1380     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1381
1382   if (!optimize_specialization_lookup_p (tmpl))
1383     {
1384       gcc_assert (tmpl && args && spec);
1385       *slot = GGC_NEW (spec_entry);
1386       **slot = elt;
1387       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1388           && PRIMARY_TEMPLATE_P (tmpl)
1389           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1390         /* TMPL is a forward declaration of a template function; keep a list
1391            of all specializations in case we need to reassign them to a friend
1392            template later in tsubst_friend_function.  */
1393         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1394           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1395     }
1396
1397   return spec;
1398 }
1399
1400 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1401    TMPL and ARGS members, ignores SPEC.  */
1402
1403 static int
1404 eq_specializations (const void *p1, const void *p2)
1405 {
1406   const spec_entry *e1 = (const spec_entry *)p1;
1407   const spec_entry *e2 = (const spec_entry *)p2;
1408
1409   return (e1->tmpl == e2->tmpl
1410           && comp_template_args (e1->args, e2->args));
1411 }
1412
1413 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1414
1415 static hashval_t
1416 hash_tmpl_and_args (tree tmpl, tree args)
1417 {
1418   hashval_t val = DECL_UID (tmpl);
1419   return iterative_hash_template_arg (args, val);
1420 }
1421
1422 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1423    ignoring SPEC.  */
1424
1425 static hashval_t
1426 hash_specialization (const void *p)
1427 {
1428   const spec_entry *e = (const spec_entry *)p;
1429   return hash_tmpl_and_args (e->tmpl, e->args);
1430 }
1431
1432 /* Recursively calculate a hash value for a template argument ARG, for use
1433    in the hash tables of template specializations.  */
1434
1435 static hashval_t
1436 iterative_hash_template_arg (tree arg, hashval_t val)
1437 {
1438   unsigned HOST_WIDE_INT i;
1439   enum tree_code code;
1440   char tclass;
1441
1442   if (arg == NULL_TREE)
1443     return iterative_hash_object (arg, val);
1444
1445   if (!TYPE_P (arg))
1446     STRIP_NOPS (arg);
1447
1448   code = TREE_CODE (arg);
1449   tclass = TREE_CODE_CLASS (code);
1450
1451   val = iterative_hash_object (code, val);
1452
1453   switch (code)
1454     {
1455     case ERROR_MARK:
1456       return val;
1457
1458     case IDENTIFIER_NODE:
1459       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1460
1461     case TREE_VEC:
1462       {
1463         int i, len = TREE_VEC_LENGTH (arg);
1464         for (i = 0; i < len; ++i)
1465           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1466         return val;
1467       }
1468
1469     case TYPE_PACK_EXPANSION:
1470     case EXPR_PACK_EXPANSION:
1471       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1472
1473     case ARGUMENT_PACK_SELECT:
1474       /* We can get one of these when re-hashing a previous entry in the middle
1475          of substituting into a pack expansion.  Just look through it...  */
1476       arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1477       /* ...and fall through.  */
1478     case TYPE_ARGUMENT_PACK:
1479     case NONTYPE_ARGUMENT_PACK:
1480       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1481
1482     case TREE_LIST:
1483       for (; arg; arg = TREE_CHAIN (arg))
1484         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1485       return val;
1486
1487     case OVERLOAD:
1488       for (; arg; arg = OVL_CHAIN (arg))
1489         val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1490       return val;
1491
1492     case CONSTRUCTOR:
1493       {
1494         tree field, value;
1495         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1496           {
1497             val = iterative_hash_template_arg (field, val);
1498             val = iterative_hash_template_arg (value, val);
1499           }
1500         return val;
1501       }
1502
1503     case PARM_DECL:
1504       val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1505       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1506
1507     case TARGET_EXPR:
1508       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1509
1510     case PTRMEM_CST:
1511       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1512       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1513
1514     case TEMPLATE_PARM_INDEX:
1515       val = iterative_hash_template_arg
1516         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1517       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1518       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1519
1520     case TRAIT_EXPR:
1521       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1522       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1523       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1524
1525     case BASELINK:
1526       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1527                                          val);
1528       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1529                                           val);
1530
1531     case MODOP_EXPR:
1532       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1533       code = TREE_CODE (TREE_OPERAND (arg, 1));
1534       val = iterative_hash_object (code, val);
1535       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1536
1537     default:
1538       switch (tclass)
1539         {
1540         case tcc_type:
1541           if (TYPE_CANONICAL (arg))
1542             return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1543                                           val);
1544           else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1545             return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1546           /* Otherwise just compare the types during lookup.  */
1547           return val;
1548
1549         case tcc_declaration:
1550         case tcc_constant:
1551           return iterative_hash_expr (arg, val);
1552
1553         default:
1554           gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1555           {
1556             unsigned n = TREE_OPERAND_LENGTH (arg);
1557             for (i = 0; i < n; ++i)
1558               val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1559             return val;
1560           }
1561         }
1562     }
1563   gcc_unreachable ();
1564   return 0;
1565 }
1566
1567 /* Unregister the specialization SPEC as a specialization of TMPL.
1568    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1569    if the SPEC was listed as a specialization of TMPL.
1570
1571    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1572
1573 bool
1574 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1575 {
1576   spec_entry **slot;
1577   spec_entry elt;
1578
1579   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1580   elt.args = TI_ARGS (tinfo);
1581   elt.spec = NULL_TREE;
1582
1583   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1584   if (*slot)
1585     {
1586       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1587       gcc_assert (new_spec != NULL_TREE);
1588       (*slot)->spec = new_spec;
1589       return 1;
1590     }
1591
1592   return 0;
1593 }
1594
1595 /* Compare an entry in the local specializations hash table P1 (which
1596    is really a pointer to a TREE_LIST) with P2 (which is really a
1597    DECL).  */
1598
1599 static int
1600 eq_local_specializations (const void *p1, const void *p2)
1601 {
1602   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1603 }
1604
1605 /* Hash P1, an entry in the local specializations table.  */
1606
1607 static hashval_t
1608 hash_local_specialization (const void* p1)
1609 {
1610   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1611 }
1612
1613 /* Like register_specialization, but for local declarations.  We are
1614    registering SPEC, an instantiation of TMPL.  */
1615
1616 static void
1617 register_local_specialization (tree spec, tree tmpl)
1618 {
1619   void **slot;
1620
1621   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1622                                    htab_hash_pointer (tmpl), INSERT);
1623   *slot = build_tree_list (spec, tmpl);
1624 }
1625
1626 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1627    specialized class.  */
1628
1629 bool
1630 explicit_class_specialization_p (tree type)
1631 {
1632   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1633     return false;
1634   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1635 }
1636
1637 /* Print the list of candidate FNS in an error message.  */
1638
1639 void
1640 print_candidates (tree fns)
1641 {
1642   tree fn;
1643
1644   const char *str = "candidates are:";
1645
1646   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1647     {
1648       tree f;
1649
1650       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1651         error ("%s %+#D", str, OVL_CURRENT (f));
1652       str = "               ";
1653     }
1654 }
1655
1656 /* Returns the template (one of the functions given by TEMPLATE_ID)
1657    which can be specialized to match the indicated DECL with the
1658    explicit template args given in TEMPLATE_ID.  The DECL may be
1659    NULL_TREE if none is available.  In that case, the functions in
1660    TEMPLATE_ID are non-members.
1661
1662    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1663    specialization of a member template.
1664
1665    The TEMPLATE_COUNT is the number of references to qualifying
1666    template classes that appeared in the name of the function. See
1667    check_explicit_specialization for a more accurate description.
1668
1669    TSK indicates what kind of template declaration (if any) is being
1670    declared.  TSK_TEMPLATE indicates that the declaration given by
1671    DECL, though a FUNCTION_DECL, has template parameters, and is
1672    therefore a template function.
1673
1674    The template args (those explicitly specified and those deduced)
1675    are output in a newly created vector *TARGS_OUT.
1676
1677    If it is impossible to determine the result, an error message is
1678    issued.  The error_mark_node is returned to indicate failure.  */
1679
1680 static tree
1681 determine_specialization (tree template_id,
1682                           tree decl,
1683                           tree* targs_out,
1684                           int need_member_template,
1685                           int template_count,
1686                           tmpl_spec_kind tsk)
1687 {
1688   tree fns;
1689   tree targs;
1690   tree explicit_targs;
1691   tree candidates = NULL_TREE;
1692   /* A TREE_LIST of templates of which DECL may be a specialization.
1693      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1694      corresponding TREE_PURPOSE is the set of template arguments that,
1695      when used to instantiate the template, would produce a function
1696      with the signature of DECL.  */
1697   tree templates = NULL_TREE;
1698   int header_count;
1699   struct cp_binding_level *b;
1700
1701   *targs_out = NULL_TREE;
1702
1703   if (template_id == error_mark_node || decl == error_mark_node)
1704     return error_mark_node;
1705
1706   fns = TREE_OPERAND (template_id, 0);
1707   explicit_targs = TREE_OPERAND (template_id, 1);
1708
1709   if (fns == error_mark_node)
1710     return error_mark_node;
1711
1712   /* Check for baselinks.  */
1713   if (BASELINK_P (fns))
1714     fns = BASELINK_FUNCTIONS (fns);
1715
1716   if (!is_overloaded_fn (fns))
1717     {
1718       error ("%qD is not a function template", fns);
1719       return error_mark_node;
1720     }
1721
1722   /* Count the number of template headers specified for this
1723      specialization.  */
1724   header_count = 0;
1725   for (b = current_binding_level;
1726        b->kind == sk_template_parms;
1727        b = b->level_chain)
1728     ++header_count;
1729
1730   for (; fns; fns = OVL_NEXT (fns))
1731     {
1732       tree fn = OVL_CURRENT (fns);
1733
1734       if (TREE_CODE (fn) == TEMPLATE_DECL)
1735         {
1736           tree decl_arg_types;
1737           tree fn_arg_types;
1738
1739           /* In case of explicit specialization, we need to check if
1740              the number of template headers appearing in the specialization
1741              is correct. This is usually done in check_explicit_specialization,
1742              but the check done there cannot be exhaustive when specializing
1743              member functions. Consider the following code:
1744
1745              template <> void A<int>::f(int);
1746              template <> template <> void A<int>::f(int);
1747
1748              Assuming that A<int> is not itself an explicit specialization
1749              already, the first line specializes "f" which is a non-template
1750              member function, whilst the second line specializes "f" which
1751              is a template member function. So both lines are syntactically
1752              correct, and check_explicit_specialization does not reject
1753              them.
1754
1755              Here, we can do better, as we are matching the specialization
1756              against the declarations. We count the number of template
1757              headers, and we check if they match TEMPLATE_COUNT + 1
1758              (TEMPLATE_COUNT is the number of qualifying template classes,
1759              plus there must be another header for the member template
1760              itself).
1761
1762              Notice that if header_count is zero, this is not a
1763              specialization but rather a template instantiation, so there
1764              is no check we can perform here.  */
1765           if (header_count && header_count != template_count + 1)
1766             continue;
1767
1768           /* Check that the number of template arguments at the
1769              innermost level for DECL is the same as for FN.  */
1770           if (current_binding_level->kind == sk_template_parms
1771               && !current_binding_level->explicit_spec_p
1772               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1773                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1774                                       (current_template_parms))))
1775             continue;
1776
1777           /* DECL might be a specialization of FN.  */
1778           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1779           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1780
1781           /* For a non-static member function, we need to make sure
1782              that the const qualification is the same.  Since
1783              get_bindings does not try to merge the "this" parameter,
1784              we must do the comparison explicitly.  */
1785           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1786               && !same_type_p (TREE_VALUE (fn_arg_types),
1787                                TREE_VALUE (decl_arg_types)))
1788             continue;
1789
1790           /* Skip the "this" parameter and, for constructors of
1791              classes with virtual bases, the VTT parameter.  A
1792              full specialization of a constructor will have a VTT
1793              parameter, but a template never will.  */ 
1794           decl_arg_types 
1795             = skip_artificial_parms_for (decl, decl_arg_types);
1796           fn_arg_types 
1797             = skip_artificial_parms_for (fn, fn_arg_types);
1798
1799           /* Check that the number of function parameters matches.
1800              For example,
1801                template <class T> void f(int i = 0);
1802                template <> void f<int>();
1803              The specialization f<int> is invalid but is not caught
1804              by get_bindings below.  */
1805           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1806             continue;
1807
1808           /* Function templates cannot be specializations; there are
1809              no partial specializations of functions.  Therefore, if
1810              the type of DECL does not match FN, there is no
1811              match.  */
1812           if (tsk == tsk_template)
1813             {
1814               if (compparms (fn_arg_types, decl_arg_types))
1815                 candidates = tree_cons (NULL_TREE, fn, candidates);
1816               continue;
1817             }
1818
1819           /* See whether this function might be a specialization of this
1820              template.  */
1821           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1822
1823           if (!targs)
1824             /* We cannot deduce template arguments that when used to
1825                specialize TMPL will produce DECL.  */
1826             continue;
1827
1828           /* Save this template, and the arguments deduced.  */
1829           templates = tree_cons (targs, fn, templates);
1830         }
1831       else if (need_member_template)
1832         /* FN is an ordinary member function, and we need a
1833            specialization of a member template.  */
1834         ;
1835       else if (TREE_CODE (fn) != FUNCTION_DECL)
1836         /* We can get IDENTIFIER_NODEs here in certain erroneous
1837            cases.  */
1838         ;
1839       else if (!DECL_FUNCTION_MEMBER_P (fn))
1840         /* This is just an ordinary non-member function.  Nothing can
1841            be a specialization of that.  */
1842         ;
1843       else if (DECL_ARTIFICIAL (fn))
1844         /* Cannot specialize functions that are created implicitly.  */
1845         ;
1846       else
1847         {
1848           tree decl_arg_types;
1849
1850           /* This is an ordinary member function.  However, since
1851              we're here, we can assume it's enclosing class is a
1852              template class.  For example,
1853
1854                template <typename T> struct S { void f(); };
1855                template <> void S<int>::f() {}
1856
1857              Here, S<int>::f is a non-template, but S<int> is a
1858              template class.  If FN has the same type as DECL, we
1859              might be in business.  */
1860
1861           if (!DECL_TEMPLATE_INFO (fn))
1862             /* Its enclosing class is an explicit specialization
1863                of a template class.  This is not a candidate.  */
1864             continue;
1865
1866           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1867                             TREE_TYPE (TREE_TYPE (fn))))
1868             /* The return types differ.  */
1869             continue;
1870
1871           /* Adjust the type of DECL in case FN is a static member.  */
1872           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1873           if (DECL_STATIC_FUNCTION_P (fn)
1874               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1875             decl_arg_types = TREE_CHAIN (decl_arg_types);
1876
1877           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1878                          decl_arg_types))
1879             /* They match!  */
1880             candidates = tree_cons (NULL_TREE, fn, candidates);
1881         }
1882     }
1883
1884   if (templates && TREE_CHAIN (templates))
1885     {
1886       /* We have:
1887
1888            [temp.expl.spec]
1889
1890            It is possible for a specialization with a given function
1891            signature to be instantiated from more than one function
1892            template.  In such cases, explicit specification of the
1893            template arguments must be used to uniquely identify the
1894            function template specialization being specialized.
1895
1896          Note that here, there's no suggestion that we're supposed to
1897          determine which of the candidate templates is most
1898          specialized.  However, we, also have:
1899
1900            [temp.func.order]
1901
1902            Partial ordering of overloaded function template
1903            declarations is used in the following contexts to select
1904            the function template to which a function template
1905            specialization refers:
1906
1907            -- when an explicit specialization refers to a function
1908               template.
1909
1910          So, we do use the partial ordering rules, at least for now.
1911          This extension can only serve to make invalid programs valid,
1912          so it's safe.  And, there is strong anecdotal evidence that
1913          the committee intended the partial ordering rules to apply;
1914          the EDG front end has that behavior, and John Spicer claims
1915          that the committee simply forgot to delete the wording in
1916          [temp.expl.spec].  */
1917       tree tmpl = most_specialized_instantiation (templates);
1918       if (tmpl != error_mark_node)
1919         {
1920           templates = tmpl;
1921           TREE_CHAIN (templates) = NULL_TREE;
1922         }
1923     }
1924
1925   if (templates == NULL_TREE && candidates == NULL_TREE)
1926     {
1927       error ("template-id %qD for %q+D does not match any template "
1928              "declaration", template_id, decl);
1929       return error_mark_node;
1930     }
1931   else if ((templates && TREE_CHAIN (templates))
1932            || (candidates && TREE_CHAIN (candidates))
1933            || (templates && candidates))
1934     {
1935       error ("ambiguous template specialization %qD for %q+D",
1936              template_id, decl);
1937       chainon (candidates, templates);
1938       print_candidates (candidates);
1939       return error_mark_node;
1940     }
1941
1942   /* We have one, and exactly one, match.  */
1943   if (candidates)
1944     {
1945       tree fn = TREE_VALUE (candidates);
1946       *targs_out = copy_node (DECL_TI_ARGS (fn));
1947       /* DECL is a re-declaration or partial instantiation of a template
1948          function.  */
1949       if (TREE_CODE (fn) == TEMPLATE_DECL)
1950         return fn;
1951       /* It was a specialization of an ordinary member function in a
1952          template class.  */
1953       return DECL_TI_TEMPLATE (fn);
1954     }
1955
1956   /* It was a specialization of a template.  */
1957   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1958   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1959     {
1960       *targs_out = copy_node (targs);
1961       SET_TMPL_ARGS_LEVEL (*targs_out,
1962                            TMPL_ARGS_DEPTH (*targs_out),
1963                            TREE_PURPOSE (templates));
1964     }
1965   else
1966     *targs_out = TREE_PURPOSE (templates);
1967   return TREE_VALUE (templates);
1968 }
1969
1970 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1971    but with the default argument values filled in from those in the
1972    TMPL_TYPES.  */
1973
1974 static tree
1975 copy_default_args_to_explicit_spec_1 (tree spec_types,
1976                                       tree tmpl_types)
1977 {
1978   tree new_spec_types;
1979
1980   if (!spec_types)
1981     return NULL_TREE;
1982
1983   if (spec_types == void_list_node)
1984     return void_list_node;
1985
1986   /* Substitute into the rest of the list.  */
1987   new_spec_types =
1988     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1989                                           TREE_CHAIN (tmpl_types));
1990
1991   /* Add the default argument for this parameter.  */
1992   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1993                          TREE_VALUE (spec_types),
1994                          new_spec_types);
1995 }
1996
1997 /* DECL is an explicit specialization.  Replicate default arguments
1998    from the template it specializes.  (That way, code like:
1999
2000      template <class T> void f(T = 3);
2001      template <> void f(double);
2002      void g () { f (); }
2003
2004    works, as required.)  An alternative approach would be to look up
2005    the correct default arguments at the call-site, but this approach
2006    is consistent with how implicit instantiations are handled.  */
2007
2008 static void
2009 copy_default_args_to_explicit_spec (tree decl)
2010 {
2011   tree tmpl;
2012   tree spec_types;
2013   tree tmpl_types;
2014   tree new_spec_types;
2015   tree old_type;
2016   tree new_type;
2017   tree t;
2018   tree object_type = NULL_TREE;
2019   tree in_charge = NULL_TREE;
2020   tree vtt = NULL_TREE;
2021
2022   /* See if there's anything we need to do.  */
2023   tmpl = DECL_TI_TEMPLATE (decl);
2024   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2025   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2026     if (TREE_PURPOSE (t))
2027       break;
2028   if (!t)
2029     return;
2030
2031   old_type = TREE_TYPE (decl);
2032   spec_types = TYPE_ARG_TYPES (old_type);
2033
2034   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2035     {
2036       /* Remove the this pointer, but remember the object's type for
2037          CV quals.  */
2038       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2039       spec_types = TREE_CHAIN (spec_types);
2040       tmpl_types = TREE_CHAIN (tmpl_types);
2041
2042       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2043         {
2044           /* DECL may contain more parameters than TMPL due to the extra
2045              in-charge parameter in constructors and destructors.  */
2046           in_charge = spec_types;
2047           spec_types = TREE_CHAIN (spec_types);
2048         }
2049       if (DECL_HAS_VTT_PARM_P (decl))
2050         {
2051           vtt = spec_types;
2052           spec_types = TREE_CHAIN (spec_types);
2053         }
2054     }
2055
2056   /* Compute the merged default arguments.  */
2057   new_spec_types =
2058     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2059
2060   /* Compute the new FUNCTION_TYPE.  */
2061   if (object_type)
2062     {
2063       if (vtt)
2064         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2065                                          TREE_VALUE (vtt),
2066                                          new_spec_types);
2067
2068       if (in_charge)
2069         /* Put the in-charge parameter back.  */
2070         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2071                                          TREE_VALUE (in_charge),
2072                                          new_spec_types);
2073
2074       new_type = build_method_type_directly (object_type,
2075                                              TREE_TYPE (old_type),
2076                                              new_spec_types);
2077     }
2078   else
2079     new_type = build_function_type (TREE_TYPE (old_type),
2080                                     new_spec_types);
2081   new_type = cp_build_type_attribute_variant (new_type,
2082                                               TYPE_ATTRIBUTES (old_type));
2083   new_type = build_exception_variant (new_type,
2084                                       TYPE_RAISES_EXCEPTIONS (old_type));
2085   TREE_TYPE (decl) = new_type;
2086 }
2087
2088 /* Check to see if the function just declared, as indicated in
2089    DECLARATOR, and in DECL, is a specialization of a function
2090    template.  We may also discover that the declaration is an explicit
2091    instantiation at this point.
2092
2093    Returns DECL, or an equivalent declaration that should be used
2094    instead if all goes well.  Issues an error message if something is
2095    amiss.  Returns error_mark_node if the error is not easily
2096    recoverable.
2097
2098    FLAGS is a bitmask consisting of the following flags:
2099
2100    2: The function has a definition.
2101    4: The function is a friend.
2102
2103    The TEMPLATE_COUNT is the number of references to qualifying
2104    template classes that appeared in the name of the function.  For
2105    example, in
2106
2107      template <class T> struct S { void f(); };
2108      void S<int>::f();
2109
2110    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2111    classes are not counted in the TEMPLATE_COUNT, so that in
2112
2113      template <class T> struct S {};
2114      template <> struct S<int> { void f(); }
2115      template <> void S<int>::f();
2116
2117    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2118    invalid; there should be no template <>.)
2119
2120    If the function is a specialization, it is marked as such via
2121    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2122    is set up correctly, and it is added to the list of specializations
2123    for that template.  */
2124
2125 tree
2126 check_explicit_specialization (tree declarator,
2127                                tree decl,
2128                                int template_count,
2129                                int flags)
2130 {
2131   int have_def = flags & 2;
2132   int is_friend = flags & 4;
2133   int specialization = 0;
2134   int explicit_instantiation = 0;
2135   int member_specialization = 0;
2136   tree ctype = DECL_CLASS_CONTEXT (decl);
2137   tree dname = DECL_NAME (decl);
2138   tmpl_spec_kind tsk;
2139
2140   if (is_friend)
2141     {
2142       if (!processing_specialization)
2143         tsk = tsk_none;
2144       else
2145         tsk = tsk_excessive_parms;
2146     }
2147   else
2148     tsk = current_tmpl_spec_kind (template_count);
2149
2150   switch (tsk)
2151     {
2152     case tsk_none:
2153       if (processing_specialization)
2154         {
2155           specialization = 1;
2156           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2157         }
2158       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2159         {
2160           if (is_friend)
2161             /* This could be something like:
2162
2163                template <class T> void f(T);
2164                class S { friend void f<>(int); }  */
2165             specialization = 1;
2166           else
2167             {
2168               /* This case handles bogus declarations like template <>
2169                  template <class T> void f<int>(); */
2170
2171               error ("template-id %qD in declaration of primary template",
2172                      declarator);
2173               return decl;
2174             }
2175         }
2176       break;
2177
2178     case tsk_invalid_member_spec:
2179       /* The error has already been reported in
2180          check_specialization_scope.  */
2181       return error_mark_node;
2182
2183     case tsk_invalid_expl_inst:
2184       error ("template parameter list used in explicit instantiation");
2185
2186       /* Fall through.  */
2187
2188     case tsk_expl_inst:
2189       if (have_def)
2190         error ("definition provided for explicit instantiation");
2191
2192       explicit_instantiation = 1;
2193       break;
2194
2195     case tsk_excessive_parms:
2196     case tsk_insufficient_parms:
2197       if (tsk == tsk_excessive_parms)
2198         error ("too many template parameter lists in declaration of %qD",
2199                decl);
2200       else if (template_header_count)
2201         error("too few template parameter lists in declaration of %qD", decl);
2202       else
2203         error("explicit specialization of %qD must be introduced by "
2204               "%<template <>%>", decl);
2205
2206       /* Fall through.  */
2207     case tsk_expl_spec:
2208       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2209       if (ctype)
2210         member_specialization = 1;
2211       else
2212         specialization = 1;
2213       break;
2214
2215     case tsk_template:
2216       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2217         {
2218           /* This case handles bogus declarations like template <>
2219              template <class T> void f<int>(); */
2220
2221           if (uses_template_parms (declarator))
2222             error ("function template partial specialization %qD "
2223                    "is not allowed", declarator);
2224           else
2225             error ("template-id %qD in declaration of primary template",
2226                    declarator);
2227           return decl;
2228         }
2229
2230       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2231         /* This is a specialization of a member template, without
2232            specialization the containing class.  Something like:
2233
2234              template <class T> struct S {
2235                template <class U> void f (U);
2236              };
2237              template <> template <class U> void S<int>::f(U) {}
2238
2239            That's a specialization -- but of the entire template.  */
2240         specialization = 1;
2241       break;
2242
2243     default:
2244       gcc_unreachable ();
2245     }
2246
2247   if (specialization || member_specialization)
2248     {
2249       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2250       for (; t; t = TREE_CHAIN (t))
2251         if (TREE_PURPOSE (t))
2252           {
2253             permerror (input_location, 
2254                        "default argument specified in explicit specialization");
2255             break;
2256           }
2257     }
2258
2259   if (specialization || member_specialization || explicit_instantiation)
2260     {
2261       tree tmpl = NULL_TREE;
2262       tree targs = NULL_TREE;
2263
2264       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2265       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2266         {
2267           tree fns;
2268
2269           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2270           if (ctype)
2271             fns = dname;
2272           else
2273             {
2274               /* If there is no class context, the explicit instantiation
2275                  must be at namespace scope.  */
2276               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2277
2278               /* Find the namespace binding, using the declaration
2279                  context.  */
2280               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2281                                            false, true);
2282               if (fns == error_mark_node || !is_overloaded_fn (fns))
2283                 {
2284                   error ("%qD is not a template function", dname);
2285                   fns = error_mark_node;
2286                 }
2287               else
2288                 {
2289                   tree fn = OVL_CURRENT (fns);
2290                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2291                                                 CP_DECL_CONTEXT (fn)))
2292                     error ("%qD is not declared in %qD",
2293                            decl, current_namespace);
2294                 }
2295             }
2296
2297           declarator = lookup_template_function (fns, NULL_TREE);
2298         }
2299
2300       if (declarator == error_mark_node)
2301         return error_mark_node;
2302
2303       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2304         {
2305           if (!explicit_instantiation)
2306             /* A specialization in class scope.  This is invalid,
2307                but the error will already have been flagged by
2308                check_specialization_scope.  */
2309             return error_mark_node;
2310           else
2311             {
2312               /* It's not valid to write an explicit instantiation in
2313                  class scope, e.g.:
2314
2315                    class C { template void f(); }
2316
2317                    This case is caught by the parser.  However, on
2318                    something like:
2319
2320                    template class C { void f(); };
2321
2322                    (which is invalid) we can get here.  The error will be
2323                    issued later.  */
2324               ;
2325             }
2326
2327           return decl;
2328         }
2329       else if (ctype != NULL_TREE
2330                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2331                    IDENTIFIER_NODE))
2332         {
2333           /* Find the list of functions in ctype that have the same
2334              name as the declared function.  */
2335           tree name = TREE_OPERAND (declarator, 0);
2336           tree fns = NULL_TREE;
2337           int idx;
2338
2339           if (constructor_name_p (name, ctype))
2340             {
2341               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2342
2343               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2344                   : !CLASSTYPE_DESTRUCTORS (ctype))
2345                 {
2346                   /* From [temp.expl.spec]:
2347
2348                      If such an explicit specialization for the member
2349                      of a class template names an implicitly-declared
2350                      special member function (clause _special_), the
2351                      program is ill-formed.
2352
2353                      Similar language is found in [temp.explicit].  */
2354                   error ("specialization of implicitly-declared special member function");
2355                   return error_mark_node;
2356                 }
2357
2358               name = is_constructor ? ctor_identifier : dtor_identifier;
2359             }
2360
2361           if (!DECL_CONV_FN_P (decl))
2362             {
2363               idx = lookup_fnfields_1 (ctype, name);
2364               if (idx >= 0)
2365                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2366             }
2367           else
2368             {
2369               VEC(tree,gc) *methods;
2370               tree ovl;
2371
2372               /* For a type-conversion operator, we cannot do a
2373                  name-based lookup.  We might be looking for `operator
2374                  int' which will be a specialization of `operator T'.
2375                  So, we find *all* the conversion operators, and then
2376                  select from them.  */
2377               fns = NULL_TREE;
2378
2379               methods = CLASSTYPE_METHOD_VEC (ctype);
2380               if (methods)
2381                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2382                      VEC_iterate (tree, methods, idx, ovl);
2383                      ++idx)
2384                   {
2385                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2386                       /* There are no more conversion functions.  */
2387                       break;
2388
2389                     /* Glue all these conversion functions together
2390                        with those we already have.  */
2391                     for (; ovl; ovl = OVL_NEXT (ovl))
2392                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2393                   }
2394             }
2395
2396           if (fns == NULL_TREE)
2397             {
2398               error ("no member function %qD declared in %qT", name, ctype);
2399               return error_mark_node;
2400             }
2401           else
2402             TREE_OPERAND (declarator, 0) = fns;
2403         }
2404
2405       /* Figure out what exactly is being specialized at this point.
2406          Note that for an explicit instantiation, even one for a
2407          member function, we cannot tell apriori whether the
2408          instantiation is for a member template, or just a member
2409          function of a template class.  Even if a member template is
2410          being instantiated, the member template arguments may be
2411          elided if they can be deduced from the rest of the
2412          declaration.  */
2413       tmpl = determine_specialization (declarator, decl,
2414                                        &targs,
2415                                        member_specialization,
2416                                        template_count,
2417                                        tsk);
2418
2419       if (!tmpl || tmpl == error_mark_node)
2420         /* We couldn't figure out what this declaration was
2421            specializing.  */
2422         return error_mark_node;
2423       else
2424         {
2425           tree gen_tmpl = most_general_template (tmpl);
2426
2427           if (explicit_instantiation)
2428             {
2429               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2430                  is done by do_decl_instantiation later.  */
2431
2432               int arg_depth = TMPL_ARGS_DEPTH (targs);
2433               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2434
2435               if (arg_depth > parm_depth)
2436                 {
2437                   /* If TMPL is not the most general template (for
2438                      example, if TMPL is a friend template that is
2439                      injected into namespace scope), then there will
2440                      be too many levels of TARGS.  Remove some of them
2441                      here.  */
2442                   int i;
2443                   tree new_targs;
2444
2445                   new_targs = make_tree_vec (parm_depth);
2446                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2447                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2448                       = TREE_VEC_ELT (targs, i);
2449                   targs = new_targs;
2450                 }
2451
2452               return instantiate_template (tmpl, targs, tf_error);
2453             }
2454
2455           /* If we thought that the DECL was a member function, but it
2456              turns out to be specializing a static member function,
2457              make DECL a static member function as well.  */
2458           if (DECL_STATIC_FUNCTION_P (tmpl)
2459               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2460             revert_static_member_fn (decl);
2461
2462           /* If this is a specialization of a member template of a
2463              template class, we want to return the TEMPLATE_DECL, not
2464              the specialization of it.  */
2465           if (tsk == tsk_template)
2466             {
2467               tree result = DECL_TEMPLATE_RESULT (tmpl);
2468               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2469               DECL_INITIAL (result) = NULL_TREE;
2470               if (have_def)
2471                 {
2472                   tree parm;
2473                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2474                   DECL_SOURCE_LOCATION (result)
2475                     = DECL_SOURCE_LOCATION (decl);
2476                   /* We want to use the argument list specified in the
2477                      definition, not in the original declaration.  */
2478                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2479                   for (parm = DECL_ARGUMENTS (result); parm;
2480                        parm = TREE_CHAIN (parm))
2481                     DECL_CONTEXT (parm) = result;
2482                 }
2483               return register_specialization (tmpl, gen_tmpl, targs,
2484                                               is_friend, 0);
2485             }
2486
2487           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2488           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2489
2490           /* Inherit default function arguments from the template
2491              DECL is specializing.  */
2492           copy_default_args_to_explicit_spec (decl);
2493
2494           /* This specialization has the same protection as the
2495              template it specializes.  */
2496           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2497           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2498
2499           /* 7.1.1-1 [dcl.stc]
2500
2501              A storage-class-specifier shall not be specified in an
2502              explicit specialization...
2503
2504              The parser rejects these, so unless action is taken here,
2505              explicit function specializations will always appear with
2506              global linkage.
2507
2508              The action recommended by the C++ CWG in response to C++
2509              defect report 605 is to make the storage class and linkage
2510              of the explicit specialization match the templated function:
2511
2512              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2513            */
2514           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2515             {
2516               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2517               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2518
2519               /* This specialization has the same linkage and visibility as
2520                  the function template it specializes.  */
2521               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2522               if (! TREE_PUBLIC (decl))
2523                 {
2524                   DECL_INTERFACE_KNOWN (decl) = 1;
2525                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2526                 }
2527               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2528               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2529                 {
2530                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2531                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2532                 }
2533             }
2534
2535           /* If DECL is a friend declaration, declared using an
2536              unqualified name, the namespace associated with DECL may
2537              have been set incorrectly.  For example, in:
2538
2539                template <typename T> void f(T);
2540                namespace N {
2541                  struct S { friend void f<int>(int); }
2542                }
2543
2544              we will have set the DECL_CONTEXT for the friend
2545              declaration to N, rather than to the global namespace.  */
2546           if (DECL_NAMESPACE_SCOPE_P (decl))
2547             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2548
2549           if (is_friend && !have_def)
2550             /* This is not really a declaration of a specialization.
2551                It's just the name of an instantiation.  But, it's not
2552                a request for an instantiation, either.  */
2553             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2554           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2555             /* This is indeed a specialization.  In case of constructors
2556                and destructors, we need in-charge and not-in-charge
2557                versions in V3 ABI.  */
2558             clone_function_decl (decl, /*update_method_vec_p=*/0);
2559
2560           /* Register this specialization so that we can find it
2561              again.  */
2562           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2563         }
2564     }
2565
2566   return decl;
2567 }
2568
2569 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2570    parameters.  These are represented in the same format used for
2571    DECL_TEMPLATE_PARMS.  */
2572
2573 int
2574 comp_template_parms (const_tree parms1, const_tree parms2)
2575 {
2576   const_tree p1;
2577   const_tree p2;
2578
2579   if (parms1 == parms2)
2580     return 1;
2581
2582   for (p1 = parms1, p2 = parms2;
2583        p1 != NULL_TREE && p2 != NULL_TREE;
2584        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2585     {
2586       tree t1 = TREE_VALUE (p1);
2587       tree t2 = TREE_VALUE (p2);
2588       int i;
2589
2590       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2591       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2592
2593       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2594         return 0;
2595
2596       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2597         {
2598           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2599           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2600
2601           /* If either of the template parameters are invalid, assume
2602              they match for the sake of error recovery. */
2603           if (parm1 == error_mark_node || parm2 == error_mark_node)
2604             return 1;
2605
2606           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2607             return 0;
2608
2609           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2610               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2611                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2612             continue;
2613           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2614             return 0;
2615         }
2616     }
2617
2618   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2619     /* One set of parameters has more parameters lists than the
2620        other.  */
2621     return 0;
2622
2623   return 1;
2624 }
2625
2626 /* Determine whether PARM is a parameter pack.  */
2627
2628 bool 
2629 template_parameter_pack_p (const_tree parm)
2630 {
2631   /* Determine if we have a non-type template parameter pack.  */
2632   if (TREE_CODE (parm) == PARM_DECL)
2633     return (DECL_TEMPLATE_PARM_P (parm) 
2634             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2635
2636   /* If this is a list of template parameters, we could get a
2637      TYPE_DECL or a TEMPLATE_DECL.  */ 
2638   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2639     parm = TREE_TYPE (parm);
2640
2641   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2642            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2643           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2644 }
2645
2646 /* Determine if T is a function parameter pack.  */
2647
2648 bool
2649 function_parameter_pack_p (const_tree t)
2650 {
2651   if (t && TREE_CODE (t) == PARM_DECL)
2652     return FUNCTION_PARAMETER_PACK_P (t);
2653   return false;
2654 }
2655
2656 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2657    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2658
2659 tree
2660 get_function_template_decl (const_tree primary_func_tmpl_inst)
2661 {
2662   if (! primary_func_tmpl_inst
2663       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2664       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2665     return NULL;
2666
2667   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2668 }
2669
2670 /* Return true iff the function parameter PARAM_DECL was expanded
2671    from the function parameter pack PACK.  */
2672
2673 bool
2674 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2675 {
2676     if (DECL_ARTIFICIAL (param_decl)
2677         || !function_parameter_pack_p (pack))
2678       return false;
2679
2680     gcc_assert (DECL_NAME (param_decl) && DECL_NAME (pack));
2681
2682     /* The parameter pack and its pack arguments have the same
2683        DECL_PARM_INDEX.  */
2684     return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2685 }
2686
2687 /* Determine whether ARGS describes a variadic template args list,
2688    i.e., one that is terminated by a template argument pack.  */
2689
2690 static bool 
2691 template_args_variadic_p (tree args)
2692 {
2693   int nargs;
2694   tree last_parm;
2695
2696   if (args == NULL_TREE)
2697     return false;
2698
2699   args = INNERMOST_TEMPLATE_ARGS (args);
2700   nargs = TREE_VEC_LENGTH (args);
2701
2702   if (nargs == 0)
2703     return false;
2704
2705   last_parm = TREE_VEC_ELT (args, nargs - 1);
2706
2707   return ARGUMENT_PACK_P (last_parm);
2708 }
2709
2710 /* Generate a new name for the parameter pack name NAME (an
2711    IDENTIFIER_NODE) that incorporates its */
2712
2713 static tree
2714 make_ith_pack_parameter_name (tree name, int i)
2715 {
2716   /* Munge the name to include the parameter index.  */
2717 #define NUMBUF_LEN 128
2718   char numbuf[NUMBUF_LEN];
2719   char* newname;
2720   int newname_len;
2721
2722   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2723   newname_len = IDENTIFIER_LENGTH (name)
2724                 + strlen (numbuf) + 2;
2725   newname = (char*)alloca (newname_len);
2726   snprintf (newname, newname_len,
2727             "%s#%i", IDENTIFIER_POINTER (name), i);
2728   return get_identifier (newname);
2729 }
2730
2731 /* Return true if T is a primary function
2732    or class template instantiation.  */
2733
2734 static bool
2735 primary_template_instantiation_p (const_tree t)
2736 {
2737   if (!t)
2738     return false;
2739
2740   if (TREE_CODE (t) == FUNCTION_DECL)
2741     return DECL_LANG_SPECIFIC (t)
2742            && DECL_TEMPLATE_INSTANTIATION (t)
2743            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2744   else if (CLASS_TYPE_P (t))
2745     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2746            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2747   return false;
2748 }
2749
2750 /* Return true if PARM is a template template parameter.  */
2751
2752 bool
2753 template_template_parameter_p (const_tree parm)
2754 {
2755   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2756 }
2757
2758 /* Return the template parameters of T if T is a
2759    primary template instantiation, NULL otherwise.  */
2760
2761 tree
2762 get_primary_template_innermost_parameters (const_tree t)
2763 {
2764   tree parms = NULL, template_info = NULL;
2765
2766   if ((template_info = get_template_info (t))
2767       && primary_template_instantiation_p (t))
2768     parms = INNERMOST_TEMPLATE_PARMS
2769         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2770
2771   return parms;
2772 }
2773
2774 /* Returns the template arguments of T if T is a template instantiation,
2775    NULL otherwise.  */
2776
2777 tree
2778 get_template_innermost_arguments (const_tree t)
2779 {
2780   tree args = NULL, template_info = NULL;
2781
2782   if ((template_info = get_template_info (t))
2783       && TI_ARGS (template_info))
2784     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2785
2786   return args;
2787 }
2788
2789 /* Return the argument pack elements of T if T is a template argument pack,
2790    NULL otherwise.  */
2791
2792 tree
2793 get_template_argument_pack_elems (const_tree t)
2794 {
2795   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2796       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2797     return NULL;
2798
2799   return ARGUMENT_PACK_ARGS (t);
2800 }
2801
2802 /* Structure used to track the progress of find_parameter_packs_r.  */
2803 struct find_parameter_pack_data 
2804 {
2805   /* TREE_LIST that will contain all of the parameter packs found by
2806      the traversal.  */
2807   tree* parameter_packs;
2808
2809   /* Set of AST nodes that have been visited by the traversal.  */
2810   struct pointer_set_t *visited;
2811 };
2812
2813 /* Identifies all of the argument packs that occur in a template
2814    argument and appends them to the TREE_LIST inside DATA, which is a
2815    find_parameter_pack_data structure. This is a subroutine of
2816    make_pack_expansion and uses_parameter_packs.  */
2817 static tree
2818 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2819 {
2820   tree t = *tp;
2821   struct find_parameter_pack_data* ppd = 
2822     (struct find_parameter_pack_data*)data;
2823   bool parameter_pack_p = false;
2824
2825   /* Identify whether this is a parameter pack or not.  */
2826   switch (TREE_CODE (t))
2827     {
2828     case TEMPLATE_PARM_INDEX:
2829       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2830         parameter_pack_p = true;
2831       break;
2832
2833     case TEMPLATE_TYPE_PARM:
2834     case TEMPLATE_TEMPLATE_PARM:
2835       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2836         parameter_pack_p = true;
2837       break;
2838
2839     case PARM_DECL:
2840       if (FUNCTION_PARAMETER_PACK_P (t))
2841         {
2842           /* We don't want to walk into the type of a PARM_DECL,
2843              because we don't want to see the type parameter pack.  */
2844           *walk_subtrees = 0;
2845           parameter_pack_p = true;
2846         }
2847       break;
2848
2849     default:
2850       /* Not a parameter pack.  */
2851       break;
2852     }
2853
2854   if (parameter_pack_p)
2855     {
2856       /* Add this parameter pack to the list.  */
2857       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2858     }
2859
2860   if (TYPE_P (t))
2861     cp_walk_tree (&TYPE_CONTEXT (t), 
2862                   &find_parameter_packs_r, ppd, ppd->visited);
2863
2864   /* This switch statement will return immediately if we don't find a
2865      parameter pack.  */
2866   switch (TREE_CODE (t)) 
2867     {
2868     case TEMPLATE_PARM_INDEX:
2869       return NULL_TREE;
2870
2871     case BOUND_TEMPLATE_TEMPLATE_PARM:
2872       /* Check the template itself.  */
2873       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2874                     &find_parameter_packs_r, ppd, ppd->visited);
2875       /* Check the template arguments.  */
2876       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2877                     ppd->visited);
2878       *walk_subtrees = 0;
2879       return NULL_TREE;
2880
2881     case TEMPLATE_TYPE_PARM:
2882     case TEMPLATE_TEMPLATE_PARM:
2883       return NULL_TREE;
2884
2885     case PARM_DECL:
2886       return NULL_TREE;
2887
2888     case RECORD_TYPE:
2889       if (TYPE_PTRMEMFUNC_P (t))
2890         return NULL_TREE;
2891       /* Fall through.  */
2892
2893     case UNION_TYPE:
2894     case ENUMERAL_TYPE:
2895       if (TYPE_TEMPLATE_INFO (t))
2896         cp_walk_tree (&TREE_VALUE (TYPE_TEMPLATE_INFO (t)), 
2897                       &find_parameter_packs_r, ppd, ppd->visited);
2898
2899       *walk_subtrees = 0;
2900       return NULL_TREE;
2901
2902     case TEMPLATE_DECL:
2903       cp_walk_tree (&TREE_TYPE (t),
2904                     &find_parameter_packs_r, ppd, ppd->visited);
2905       return NULL_TREE;
2906  
2907     case TYPENAME_TYPE:
2908       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2909                    ppd, ppd->visited);
2910       *walk_subtrees = 0;
2911       return NULL_TREE;
2912       
2913     case TYPE_PACK_EXPANSION:
2914     case EXPR_PACK_EXPANSION:
2915       *walk_subtrees = 0;
2916       return NULL_TREE;
2917
2918     case INTEGER_TYPE:
2919       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2920                     ppd, ppd->visited);
2921       *walk_subtrees = 0;
2922       return NULL_TREE;
2923
2924     case IDENTIFIER_NODE:
2925       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2926                     ppd->visited);
2927       *walk_subtrees = 0;
2928       return NULL_TREE;
2929
2930     default:
2931       return NULL_TREE;
2932     }
2933
2934   return NULL_TREE;
2935 }
2936
2937 /* Determines if the expression or type T uses any parameter packs.  */
2938 bool
2939 uses_parameter_packs (tree t)
2940 {
2941   tree parameter_packs = NULL_TREE;
2942   struct find_parameter_pack_data ppd;
2943   ppd.parameter_packs = &parameter_packs;
2944   ppd.visited = pointer_set_create ();
2945   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2946   pointer_set_destroy (ppd.visited);
2947   return parameter_packs != NULL_TREE;
2948 }
2949
2950 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2951    representation a base-class initializer into a parameter pack
2952    expansion. If all goes well, the resulting node will be an
2953    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2954    respectively.  */
2955 tree 
2956 make_pack_expansion (tree arg)
2957 {
2958   tree result;
2959   tree parameter_packs = NULL_TREE;
2960   bool for_types = false;
2961   struct find_parameter_pack_data ppd;
2962
2963   if (!arg || arg == error_mark_node)
2964     return arg;
2965
2966   if (TREE_CODE (arg) == TREE_LIST)
2967     {
2968       /* The only time we will see a TREE_LIST here is for a base
2969          class initializer.  In this case, the TREE_PURPOSE will be a
2970          _TYPE node (representing the base class expansion we're
2971          initializing) and the TREE_VALUE will be a TREE_LIST
2972          containing the initialization arguments. 
2973
2974          The resulting expansion looks somewhat different from most
2975          expansions. Rather than returning just one _EXPANSION, we
2976          return a TREE_LIST whose TREE_PURPOSE is a
2977          TYPE_PACK_EXPANSION containing the bases that will be
2978          initialized.  The TREE_VALUE will be identical to the
2979          original TREE_VALUE, which is a list of arguments that will
2980          be passed to each base.  We do not introduce any new pack
2981          expansion nodes into the TREE_VALUE (although it is possible
2982          that some already exist), because the TREE_PURPOSE and
2983          TREE_VALUE all need to be expanded together with the same
2984          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2985          resulting TREE_PURPOSE will mention the parameter packs in
2986          both the bases and the arguments to the bases.  */
2987       tree purpose;
2988       tree value;
2989       tree parameter_packs = NULL_TREE;
2990
2991       /* Determine which parameter packs will be used by the base
2992          class expansion.  */
2993       ppd.visited = pointer_set_create ();
2994       ppd.parameter_packs = &parameter_packs;
2995       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
2996                     &ppd, ppd.visited);
2997
2998       if (parameter_packs == NULL_TREE)
2999         {
3000           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3001           pointer_set_destroy (ppd.visited);
3002           return error_mark_node;
3003         }
3004
3005       if (TREE_VALUE (arg) != void_type_node)
3006         {
3007           /* Collect the sets of parameter packs used in each of the
3008              initialization arguments.  */
3009           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3010             {
3011               /* Determine which parameter packs will be expanded in this
3012                  argument.  */
3013               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3014                             &ppd, ppd.visited);
3015             }
3016         }
3017
3018       pointer_set_destroy (ppd.visited);
3019
3020       /* Create the pack expansion type for the base type.  */
3021       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3022       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3023       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3024
3025       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3026          they will rarely be compared to anything.  */
3027       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3028
3029       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3030     }
3031
3032   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3033     for_types = true;
3034
3035   /* Build the PACK_EXPANSION_* node.  */
3036   result = for_types
3037      ? cxx_make_type (TYPE_PACK_EXPANSION)
3038      : make_node (EXPR_PACK_EXPANSION);
3039   SET_PACK_EXPANSION_PATTERN (result, arg);
3040   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3041     {
3042       /* Propagate type and const-expression information.  */
3043       TREE_TYPE (result) = TREE_TYPE (arg);
3044       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3045     }
3046   else
3047     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3048        they will rarely be compared to anything.  */
3049     SET_TYPE_STRUCTURAL_EQUALITY (result);
3050
3051   /* Determine which parameter packs will be expanded.  */
3052   ppd.parameter_packs = &parameter_packs;
3053   ppd.visited = pointer_set_create ();
3054   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3055   pointer_set_destroy (ppd.visited);
3056
3057   /* Make sure we found some parameter packs.  */
3058   if (parameter_packs == NULL_TREE)
3059     {
3060       if (TYPE_P (arg))
3061         error ("expansion pattern %<%T%> contains no argument packs", arg);
3062       else
3063         error ("expansion pattern %<%E%> contains no argument packs", arg);
3064       return error_mark_node;
3065     }
3066   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3067
3068   return result;
3069 }
3070
3071 /* Checks T for any "bare" parameter packs, which have not yet been
3072    expanded, and issues an error if any are found. This operation can
3073    only be done on full expressions or types (e.g., an expression
3074    statement, "if" condition, etc.), because we could have expressions like:
3075
3076      foo(f(g(h(args)))...)
3077
3078    where "args" is a parameter pack. check_for_bare_parameter_packs
3079    should not be called for the subexpressions args, h(args),
3080    g(h(args)), or f(g(h(args))), because we would produce erroneous
3081    error messages. 
3082
3083    Returns TRUE and emits an error if there were bare parameter packs,
3084    returns FALSE otherwise.  */
3085 bool 
3086 check_for_bare_parameter_packs (tree t)
3087 {
3088   tree parameter_packs = NULL_TREE;
3089   struct find_parameter_pack_data ppd;
3090
3091   if (!processing_template_decl || !t || t == error_mark_node)
3092     return false;
3093
3094   if (TREE_CODE (t) == TYPE_DECL)
3095     t = TREE_TYPE (t);
3096
3097   ppd.parameter_packs = &parameter_packs;
3098   ppd.visited = pointer_set_create ();
3099   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3100   pointer_set_destroy (ppd.visited);
3101
3102   if (parameter_packs) 
3103     {
3104       error ("parameter packs not expanded with %<...%>:");
3105       while (parameter_packs)
3106         {
3107           tree pack = TREE_VALUE (parameter_packs);
3108           tree name = NULL_TREE;
3109
3110           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3111               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3112             name = TYPE_NAME (pack);
3113           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3114             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3115           else
3116             name = DECL_NAME (pack);
3117
3118           if (name)
3119             inform (input_location, "        %qD", name);
3120           else
3121             inform (input_location, "        <anonymous>");
3122
3123           parameter_packs = TREE_CHAIN (parameter_packs);
3124         }
3125
3126       return true;
3127     }
3128
3129   return false;
3130 }
3131
3132 /* Expand any parameter packs that occur in the template arguments in
3133    ARGS.  */
3134 tree
3135 expand_template_argument_pack (tree args)
3136 {
3137   tree result_args = NULL_TREE;
3138   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3139   int num_result_args = -1;
3140
3141   /* First, determine if we need to expand anything, and the number of
3142      slots we'll need.  */
3143   for (in_arg = 0; in_arg < nargs; ++in_arg)
3144     {
3145       tree arg = TREE_VEC_ELT (args, in_arg);
3146       if (ARGUMENT_PACK_P (arg))
3147         {
3148           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3149           if (num_result_args < 0)
3150             num_result_args = in_arg + num_packed;
3151           else
3152             num_result_args += num_packed;
3153         }
3154       else
3155         {
3156           if (num_result_args >= 0)
3157             num_result_args++;
3158         }
3159     }
3160
3161   /* If no expansion is necessary, we're done.  */
3162   if (num_result_args < 0)
3163     return args;
3164
3165   /* Expand arguments.  */
3166   result_args = make_tree_vec (num_result_args);
3167   for (in_arg = 0; in_arg < nargs; ++in_arg)
3168     {
3169       tree arg = TREE_VEC_ELT (args, in_arg);
3170       if (ARGUMENT_PACK_P (arg))
3171         {
3172           tree packed = ARGUMENT_PACK_ARGS (arg);
3173           int i, num_packed = TREE_VEC_LENGTH (packed);
3174           for (i = 0; i < num_packed; ++i, ++out_arg)
3175             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3176         }
3177       else
3178         {
3179           TREE_VEC_ELT (result_args, out_arg) = arg;
3180           ++out_arg;
3181         }
3182     }
3183
3184   return result_args;
3185 }
3186
3187 /* Checks if DECL shadows a template parameter.
3188
3189    [temp.local]: A template-parameter shall not be redeclared within its
3190    scope (including nested scopes).
3191
3192    Emits an error and returns TRUE if the DECL shadows a parameter,
3193    returns FALSE otherwise.  */
3194
3195 bool
3196 check_template_shadow (tree decl)
3197 {
3198   tree olddecl;
3199
3200   /* If we're not in a template, we can't possibly shadow a template
3201      parameter.  */
3202   if (!current_template_parms)
3203     return true;
3204
3205   /* Figure out what we're shadowing.  */
3206   if (TREE_CODE (decl) == OVERLOAD)
3207     decl = OVL_CURRENT (decl);
3208   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3209
3210   /* If there's no previous binding for this name, we're not shadowing
3211      anything, let alone a template parameter.  */
3212   if (!olddecl)
3213     return true;
3214
3215   /* If we're not shadowing a template parameter, we're done.  Note
3216      that OLDDECL might be an OVERLOAD (or perhaps even an
3217      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3218      node.  */
3219   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3220     return true;
3221
3222   /* We check for decl != olddecl to avoid bogus errors for using a
3223      name inside a class.  We check TPFI to avoid duplicate errors for
3224      inline member templates.  */
3225   if (decl == olddecl
3226       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3227     return true;
3228
3229   error ("declaration of %q+#D", decl);
3230   error (" shadows template parm %q+#D", olddecl);
3231   return false;
3232 }
3233
3234 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3235    ORIG_LEVEL, DECL, and TYPE.  */
3236
3237 static tree
3238 build_template_parm_index (int index,
3239                            int level,
3240                            int orig_level,
3241                            tree decl,
3242                            tree type)
3243 {
3244   tree t = make_node (TEMPLATE_PARM_INDEX);
3245   TEMPLATE_PARM_IDX (t) = index;
3246   TEMPLATE_PARM_LEVEL (t) = level;
3247   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3248   TEMPLATE_PARM_DECL (t) = decl;
3249   TREE_TYPE (t) = type;
3250   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3251   TREE_READONLY (t) = TREE_READONLY (decl);
3252
3253   return t;
3254 }
3255
3256 /* Find the canonical type parameter for the given template type
3257    parameter.  Returns the canonical type parameter, which may be TYPE
3258    if no such parameter existed.  */
3259 static tree
3260 canonical_type_parameter (tree type)
3261 {
3262   tree list;
3263   int idx = TEMPLATE_TYPE_IDX (type);
3264   if (!canonical_template_parms)
3265     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3266
3267   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3268     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3269
3270   list = VEC_index (tree, canonical_template_parms, idx);
3271   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3272     list = TREE_CHAIN (list);
3273
3274   if (list)
3275     return TREE_VALUE (list);
3276   else
3277     {
3278       VEC_replace(tree, canonical_template_parms, idx,
3279                   tree_cons (NULL_TREE, type, 
3280                              VEC_index (tree, canonical_template_parms, idx)));
3281       return type;
3282     }
3283 }
3284
3285 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3286    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3287    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3288    new one is created.  */
3289
3290 static tree
3291 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3292                             tsubst_flags_t complain)
3293 {
3294   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3295       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3296           != TEMPLATE_PARM_LEVEL (index) - levels))
3297     {
3298       tree orig_decl = TEMPLATE_PARM_DECL (index);
3299       tree decl, t;
3300
3301       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3302                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3303       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3304       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3305       DECL_ARTIFICIAL (decl) = 1;
3306       SET_DECL_TEMPLATE_PARM_P (decl);
3307
3308       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3309                                      TEMPLATE_PARM_LEVEL (index) - levels,
3310                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3311                                      decl, type);
3312       TEMPLATE_PARM_DESCENDANTS (index) = t;
3313       TEMPLATE_PARM_PARAMETER_PACK (t) 
3314         = TEMPLATE_PARM_PARAMETER_PACK (index);
3315
3316         /* Template template parameters need this.  */
3317       if (TREE_CODE (decl) == TEMPLATE_DECL)
3318         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3319           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3320            args, complain);
3321     }
3322
3323   return TEMPLATE_PARM_DESCENDANTS (index);
3324 }
3325
3326 /* Process information from new template parameter PARM and append it to the
3327    LIST being built.  This new parameter is a non-type parameter iff
3328    IS_NON_TYPE is true. This new parameter is a parameter
3329    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3330    PARM_LOC.  */
3331
3332 tree
3333 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3334                        bool is_parameter_pack)
3335 {
3336   tree decl = 0;
3337   tree defval;
3338   tree err_parm_list;
3339   int idx = 0;
3340
3341   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3342   defval = TREE_PURPOSE (parm);
3343
3344   if (list)
3345     {
3346       tree p = tree_last (list);
3347
3348       if (p && TREE_VALUE (p) != error_mark_node)
3349         {
3350           p = TREE_VALUE (p);
3351           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3352             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3353           else
3354             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3355         }
3356
3357       ++idx;
3358     }
3359   else
3360     idx = 0;
3361
3362   if (is_non_type)
3363     {
3364       parm = TREE_VALUE (parm);
3365
3366       SET_DECL_TEMPLATE_PARM_P (parm);
3367
3368       if (TREE_TYPE (parm) == error_mark_node)
3369         {
3370           err_parm_list = build_tree_list (defval, parm);
3371           TREE_VALUE (err_parm_list) = error_mark_node;
3372            return chainon (list, err_parm_list);
3373         }
3374       else
3375       {
3376         /* [temp.param]
3377
3378            The top-level cv-qualifiers on the template-parameter are
3379            ignored when determining its type.  */
3380         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3381         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3382           {
3383             err_parm_list = build_tree_list (defval, parm);
3384             TREE_VALUE (err_parm_list) = error_mark_node;
3385              return chainon (list, err_parm_list);
3386           }
3387
3388         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3389           {
3390             /* This template parameter is not a parameter pack, but it
3391                should be. Complain about "bare" parameter packs.  */
3392             check_for_bare_parameter_packs (TREE_TYPE (parm));
3393             
3394             /* Recover by calling this a parameter pack.  */
3395             is_parameter_pack = true;
3396           }
3397       }
3398
3399       /* A template parameter is not modifiable.  */
3400       TREE_CONSTANT (parm) = 1;
3401       TREE_READONLY (parm) = 1;
3402       decl = build_decl (parm_loc,
3403                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3404       TREE_CONSTANT (decl) = 1;
3405       TREE_READONLY (decl) = 1;
3406       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3407         = build_template_parm_index (idx, processing_template_decl,
3408                                      processing_template_decl,
3409                                      decl, TREE_TYPE (parm));
3410
3411       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3412         = is_parameter_pack;
3413     }
3414   else
3415     {
3416       tree t;
3417       parm = TREE_VALUE (TREE_VALUE (parm));
3418
3419       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3420         {
3421           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3422           /* This is for distinguishing between real templates and template
3423              template parameters */
3424           TREE_TYPE (parm) = t;
3425           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3426           decl = parm;
3427         }
3428       else
3429         {
3430           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3431           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3432           decl = build_decl (parm_loc,
3433                              TYPE_DECL, parm, t);
3434         }
3435
3436       TYPE_NAME (t) = decl;
3437       TYPE_STUB_DECL (t) = decl;
3438       parm = decl;
3439       TEMPLATE_TYPE_PARM_INDEX (t)
3440         = build_template_parm_index (idx, processing_template_decl,
3441                                      processing_template_decl,
3442                                      decl, TREE_TYPE (parm));
3443       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3444       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3445     }
3446   DECL_ARTIFICIAL (decl) = 1;
3447   SET_DECL_TEMPLATE_PARM_P (decl);
3448   pushdecl (decl);
3449   parm = build_tree_list (defval, parm);
3450   return chainon (list, parm);
3451 }
3452
3453 /* The end of a template parameter list has been reached.  Process the
3454    tree list into a parameter vector, converting each parameter into a more
3455    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3456    as PARM_DECLs.  */
3457
3458 tree
3459 end_template_parm_list (tree parms)
3460 {
3461   int nparms;
3462   tree parm, next;
3463   tree saved_parmlist = make_tree_vec (list_length (parms));
3464
3465   current_template_parms
3466     = tree_cons (size_int (processing_template_decl),
3467                  saved_parmlist, current_template_parms);
3468
3469   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3470     {
3471       next = TREE_CHAIN (parm);
3472       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3473       TREE_CHAIN (parm) = NULL_TREE;
3474     }
3475
3476   --processing_template_parmlist;
3477
3478   return saved_parmlist;
3479 }
3480
3481 /* end_template_decl is called after a template declaration is seen.  */
3482
3483 void
3484 end_template_decl (void)
3485 {
3486   reset_specialization ();
3487
3488   if (! processing_template_decl)
3489     return;
3490
3491   /* This matches the pushlevel in begin_template_parm_list.  */
3492   finish_scope ();
3493
3494   --processing_template_decl;
3495   current_template_parms = TREE_CHAIN (current_template_parms);
3496 }
3497
3498 /* Within the declaration of a template, return all levels of template
3499    parameters that apply.  The template parameters are represented as
3500    a TREE_VEC, in the form documented in cp-tree.h for template
3501    arguments.  */
3502
3503 static tree
3504 current_template_args (void)
3505 {
3506   tree header;
3507   tree args = NULL_TREE;
3508   int length = TMPL_PARMS_DEPTH (current_template_parms);
3509   int l = length;
3510
3511   /* If there is only one level of template parameters, we do not
3512      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3513      TREE_VEC containing the arguments.  */
3514   if (length > 1)
3515     args = make_tree_vec (length);
3516
3517   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3518     {
3519       tree a = copy_node (TREE_VALUE (header));
3520       int i;
3521
3522       TREE_TYPE (a) = NULL_TREE;
3523       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3524         {
3525           tree t = TREE_VEC_ELT (a, i);
3526
3527           /* T will be a list if we are called from within a
3528              begin/end_template_parm_list pair, but a vector directly
3529              if within a begin/end_member_template_processing pair.  */
3530           if (TREE_CODE (t) == TREE_LIST)
3531             {
3532               t = TREE_VALUE (t);
3533
3534               if (!error_operand_p (t))
3535                 {
3536                   if (TREE_CODE (t) == TYPE_DECL
3537                       || TREE_CODE (t) == TEMPLATE_DECL)
3538                     {
3539                       t = TREE_TYPE (t);
3540                       
3541                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3542                         {
3543                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3544                              with a single element, which expands T.  */
3545                           tree vec = make_tree_vec (1);
3546                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3547                           
3548                           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3549                           SET_ARGUMENT_PACK_ARGS (t, vec);
3550                         }
3551                     }
3552                   else
3553                     {
3554                       t = DECL_INITIAL (t);
3555                       
3556                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3557                         {
3558                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3559                              with a single element, which expands T.  */
3560                           tree vec = make_tree_vec (1);
3561                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3562                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3563                           
3564                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3565                           SET_ARGUMENT_PACK_ARGS (t, vec);
3566                           TREE_TYPE (t) = type;
3567                         }
3568                     }
3569                   TREE_VEC_ELT (a, i) = t;
3570                 }
3571             }
3572         }
3573
3574       if (length > 1)
3575         TREE_VEC_ELT (args, --l) = a;
3576       else
3577         args = a;
3578     }
3579
3580   return args;
3581 }
3582
3583 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3584    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3585    a member template.  Used by push_template_decl below.  */
3586
3587 static tree
3588 build_template_decl (tree decl, tree parms, bool member_template_p)
3589 {
3590   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3591   DECL_TEMPLATE_PARMS (tmpl) = parms;
3592   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3593   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3594
3595   return tmpl;
3596 }
3597
3598 struct template_parm_data
3599 {
3600   /* The level of the template parameters we are currently
3601      processing.  */
3602   int level;
3603
3604   /* The index of the specialization argument we are currently
3605      processing.  */
3606   int current_arg;
3607
3608   /* An array whose size is the number of template parameters.  The
3609      elements are nonzero if the parameter has been used in any one
3610      of the arguments processed so far.  */
3611   int* parms;
3612
3613   /* An array whose size is the number of template arguments.  The
3614      elements are nonzero if the argument makes use of template
3615      parameters of this level.  */
3616   int* arg_uses_template_parms;
3617 };
3618
3619 /* Subroutine of push_template_decl used to see if each template
3620    parameter in a partial specialization is used in the explicit
3621    argument list.  If T is of the LEVEL given in DATA (which is
3622    treated as a template_parm_data*), then DATA->PARMS is marked
3623    appropriately.  */
3624
3625 static int
3626 mark_template_parm (tree t, void* data)
3627 {
3628   int level;
3629   int idx;
3630   struct template_parm_data* tpd = (struct template_parm_data*) data;
3631
3632   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3633     {
3634       level = TEMPLATE_PARM_LEVEL (t);
3635       idx = TEMPLATE_PARM_IDX (t);
3636     }
3637   else
3638     {
3639       level = TEMPLATE_TYPE_LEVEL (t);
3640       idx = TEMPLATE_TYPE_IDX (t);
3641     }
3642
3643   if (level == tpd->level)
3644     {
3645       tpd->parms[idx] = 1;
3646       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3647     }
3648
3649   /* Return zero so that for_each_template_parm will continue the
3650      traversal of the tree; we want to mark *every* template parm.  */
3651   return 0;
3652 }
3653
3654 /* Process the partial specialization DECL.  */
3655
3656 static tree
3657 process_partial_specialization (tree decl)
3658 {
3659   tree type = TREE_TYPE (decl);
3660   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3661   tree specargs = CLASSTYPE_TI_ARGS (type);
3662   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3663   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3664   tree inner_parms;
3665   int nargs = TREE_VEC_LENGTH (inner_args);
3666   int ntparms;
3667   int  i;
3668   int did_error_intro = 0;
3669   struct template_parm_data tpd;
3670   struct template_parm_data tpd2;
3671
3672   gcc_assert (current_template_parms);
3673
3674   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3675   ntparms = TREE_VEC_LENGTH (inner_parms);
3676
3677   /* We check that each of the template parameters given in the
3678      partial specialization is used in the argument list to the
3679      specialization.  For example:
3680
3681        template <class T> struct S;
3682        template <class T> struct S<T*>;
3683
3684      The second declaration is OK because `T*' uses the template
3685      parameter T, whereas
3686
3687        template <class T> struct S<int>;
3688
3689      is no good.  Even trickier is:
3690
3691        template <class T>
3692        struct S1
3693        {
3694           template <class U>
3695           struct S2;
3696           template <class U>
3697           struct S2<T>;
3698        };
3699
3700      The S2<T> declaration is actually invalid; it is a
3701      full-specialization.  Of course,
3702
3703           template <class U>
3704           struct S2<T (*)(U)>;
3705
3706      or some such would have been OK.  */
3707   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3708   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3709   memset (tpd.parms, 0, sizeof (int) * ntparms);
3710
3711   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3712   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3713   for (i = 0; i < nargs; ++i)
3714     {
3715       tpd.current_arg = i;
3716       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3717                               &mark_template_parm,
3718                               &tpd,
3719                               NULL,
3720                               /*include_nondeduced_p=*/false);
3721     }
3722   for (i = 0; i < ntparms; ++i)
3723     if (tpd.parms[i] == 0)
3724       {
3725         /* One of the template parms was not used in the
3726            specialization.  */
3727         if (!did_error_intro)
3728           {
3729             error ("template parameters not used in partial specialization:");
3730             did_error_intro = 1;
3731           }
3732
3733         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3734       }
3735
3736   /* [temp.class.spec]
3737
3738      The argument list of the specialization shall not be identical to
3739      the implicit argument list of the primary template.  */
3740   if (comp_template_args
3741       (inner_args,
3742        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3743                                                    (maintmpl)))))
3744     error ("partial specialization %qT does not specialize any template arguments", type);
3745
3746   /* [temp.class.spec]
3747
3748      A partially specialized non-type argument expression shall not
3749      involve template parameters of the partial specialization except
3750      when the argument expression is a simple identifier.
3751
3752      The type of a template parameter corresponding to a specialized
3753      non-type argument shall not be dependent on a parameter of the
3754      specialization. 
3755
3756      Also, we verify that pack expansions only occur at the
3757      end of the argument list.  */
3758   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3759   tpd2.parms = 0;
3760   for (i = 0; i < nargs; ++i)
3761     {
3762       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3763       tree arg = TREE_VEC_ELT (inner_args, i);
3764       tree packed_args = NULL_TREE;
3765       int j, len = 1;
3766
3767       if (ARGUMENT_PACK_P (arg))
3768         {
3769           /* Extract the arguments from the argument pack. We'll be
3770              iterating over these in the following loop.  */
3771           packed_args = ARGUMENT_PACK_ARGS (arg);
3772           len = TREE_VEC_LENGTH (packed_args);
3773         }
3774
3775       for (j = 0; j < len; j++)
3776         {
3777           if (packed_args)
3778             /* Get the Jth argument in the parameter pack.  */
3779             arg = TREE_VEC_ELT (packed_args, j);
3780
3781           if (PACK_EXPANSION_P (arg))
3782             {
3783               /* Pack expansions must come at the end of the
3784                  argument list.  */
3785               if ((packed_args && j < len - 1)
3786                   || (!packed_args && i < nargs - 1))
3787                 {
3788                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3789                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3790                   else
3791                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3792
3793                   if (packed_args)
3794                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3795                 }
3796             }
3797
3798           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3799             /* We only care about the pattern.  */
3800             arg = PACK_EXPANSION_PATTERN (arg);
3801
3802           if (/* These first two lines are the `non-type' bit.  */
3803               !TYPE_P (arg)
3804               && TREE_CODE (arg) != TEMPLATE_DECL
3805               /* This next line is the `argument expression is not just a
3806                  simple identifier' condition and also the `specialized
3807                  non-type argument' bit.  */
3808               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3809             {
3810               if ((!packed_args && tpd.arg_uses_template_parms[i])
3811                   || (packed_args && uses_template_parms (arg)))
3812                 error ("template argument %qE involves template parameter(s)",
3813                        arg);
3814               else 
3815                 {
3816                   /* Look at the corresponding template parameter,
3817                      marking which template parameters its type depends
3818                      upon.  */
3819                   tree type = TREE_TYPE (parm);
3820
3821                   if (!tpd2.parms)
3822                     {
3823                       /* We haven't yet initialized TPD2.  Do so now.  */
3824                       tpd2.arg_uses_template_parms 
3825                         = (int *) alloca (sizeof (int) * nargs);
3826                       /* The number of parameters here is the number in the
3827                          main template, which, as checked in the assertion
3828                          above, is NARGS.  */
3829                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3830                       tpd2.level = 
3831                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3832                     }
3833
3834                   /* Mark the template parameters.  But this time, we're
3835                      looking for the template parameters of the main
3836                      template, not in the specialization.  */
3837                   tpd2.current_arg = i;
3838                   tpd2.arg_uses_template_parms[i] = 0;
3839                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3840                   for_each_template_parm (type,
3841                                           &mark_template_parm,
3842                                           &tpd2,
3843                                           NULL,
3844                                           /*include_nondeduced_p=*/false);
3845
3846                   if (tpd2.arg_uses_template_parms [i])
3847                     {
3848                       /* The type depended on some template parameters.
3849                          If they are fully specialized in the
3850                          specialization, that's OK.  */
3851                       int j;
3852                       for (j = 0; j < nargs; ++j)
3853                         if (tpd2.parms[j] != 0
3854                             && tpd.arg_uses_template_parms [j])
3855                           {
3856                             error ("type %qT of template argument %qE depends "
3857                                    "on template parameter(s)", 
3858                                    type,
3859                                    arg);
3860                             break;
3861                           }
3862                     }
3863                 }
3864             }
3865         }
3866     }
3867
3868   /* We should only get here once.  */
3869   gcc_assert (!COMPLETE_TYPE_P (type));
3870
3871   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3872     = tree_cons (specargs, inner_parms,
3873                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3874   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3875   return decl;
3876 }
3877
3878 /* Check that a template declaration's use of default arguments and
3879    parameter packs is not invalid.  Here, PARMS are the template
3880    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3881    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3882    specialization.
3883    
3884
3885    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3886    declaration (but not a definition); 1 indicates a declaration, 2
3887    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3888    emitted for extraneous default arguments.
3889
3890    Returns TRUE if there were no errors found, FALSE otherwise. */
3891
3892 bool
3893 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3894                          int is_partial, int is_friend_decl)
3895 {
3896   const char *msg;
3897   int last_level_to_check;
3898   tree parm_level;
3899   bool no_errors = true;
3900
3901   /* [temp.param]
3902
3903      A default template-argument shall not be specified in a
3904      function template declaration or a function template definition, nor
3905      in the template-parameter-list of the definition of a member of a
3906      class template.  */
3907
3908   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3909     /* You can't have a function template declaration in a local
3910        scope, nor you can you define a member of a class template in a
3911        local scope.  */
3912     return true;
3913
3914   if (current_class_type
3915       && !TYPE_BEING_DEFINED (current_class_type)
3916       && DECL_LANG_SPECIFIC (decl)
3917       && DECL_DECLARES_FUNCTION_P (decl)
3918       /* If this is either a friend defined in the scope of the class
3919          or a member function.  */
3920       && (DECL_FUNCTION_MEMBER_P (decl)
3921           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3922           : DECL_FRIEND_CONTEXT (decl)
3923           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3924           : false)
3925       /* And, if it was a member function, it really was defined in
3926          the scope of the class.  */
3927       && (!DECL_FUNCTION_MEMBER_P (decl)
3928           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3929     /* We already checked these parameters when the template was
3930        declared, so there's no need to do it again now.  This function
3931        was defined in class scope, but we're processing it's body now
3932        that the class is complete.  */
3933     return true;
3934
3935   /* Core issue 226 (C++0x only): the following only applies to class
3936      templates.  */
3937   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3938     {
3939       /* [temp.param]
3940
3941          If a template-parameter has a default template-argument, all
3942          subsequent template-parameters shall have a default
3943          template-argument supplied.  */
3944       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3945         {
3946           tree inner_parms = TREE_VALUE (parm_level);
3947           int ntparms = TREE_VEC_LENGTH (inner_parms);
3948           int seen_def_arg_p = 0;
3949           int i;
3950
3951           for (i = 0; i < ntparms; ++i)
3952             {
3953               tree parm = TREE_VEC_ELT (inner_parms, i);
3954
3955               if (parm == error_mark_node)
3956                 continue;
3957
3958               if (TREE_PURPOSE (parm))
3959                 seen_def_arg_p = 1;
3960               else if (seen_def_arg_p
3961                        && !template_parameter_pack_p (TREE_VALUE (parm)))
3962                 {
3963                   error ("no default argument for %qD", TREE_VALUE (parm));
3964                   /* For better subsequent error-recovery, we indicate that
3965                      there should have been a default argument.  */
3966                   TREE_PURPOSE (parm) = error_mark_node;
3967                   no_errors = false;
3968                 }
3969               else if (is_primary
3970                        && !is_partial
3971                        && !is_friend_decl
3972                        /* Don't complain about an enclosing partial
3973                           specialization.  */
3974                        && parm_level == parms
3975                        && TREE_CODE (decl) == TYPE_DECL
3976                        && i < ntparms - 1
3977                        && template_parameter_pack_p (TREE_VALUE (parm)))
3978                 {
3979                   /* A primary class template can only have one
3980                      parameter pack, at the end of the template
3981                      parameter list.  */
3982
3983                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
3984                     error ("parameter pack %qE must be at the end of the"
3985                            " template parameter list", TREE_VALUE (parm));
3986                   else
3987                     error ("parameter pack %qT must be at the end of the"
3988                            " template parameter list", 
3989                            TREE_TYPE (TREE_VALUE (parm)));
3990
3991                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
3992                     = error_mark_node;
3993                   no_errors = false;
3994                 }
3995             }
3996         }
3997     }
3998
3999   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4000       || is_partial 
4001       || !is_primary
4002       || is_friend_decl)
4003     /* For an ordinary class template, default template arguments are
4004        allowed at the innermost level, e.g.:
4005          template <class T = int>
4006          struct S {};
4007        but, in a partial specialization, they're not allowed even
4008        there, as we have in [temp.class.spec]:
4009
4010          The template parameter list of a specialization shall not
4011          contain default template argument values.
4012
4013        So, for a partial specialization, or for a function template
4014        (in C++98/C++03), we look at all of them.  */
4015     ;
4016   else
4017     /* But, for a primary class template that is not a partial
4018        specialization we look at all template parameters except the
4019        innermost ones.  */
4020     parms = TREE_CHAIN (parms);
4021
4022   /* Figure out what error message to issue.  */
4023   if (is_friend_decl == 2)
4024     msg = "default template arguments may not be used in function template friend re-declaration";
4025   else if (is_friend_decl)
4026     msg = "default template arguments may not be used in function template friend declarations";
4027   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4028     msg = ("default template arguments may not be used in function templates "
4029            "without -std=c++0x or -std=gnu++0x");
4030   else if (is_partial)
4031     msg = "default template arguments may not be used in partial specializations";
4032   else
4033     msg = "default argument for template parameter for class enclosing %qD";
4034
4035   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4036     /* If we're inside a class definition, there's no need to
4037        examine the parameters to the class itself.  On the one
4038        hand, they will be checked when the class is defined, and,
4039        on the other, default arguments are valid in things like:
4040          template <class T = double>
4041          struct S { template <class U> void f(U); };
4042        Here the default argument for `S' has no bearing on the
4043        declaration of `f'.  */
4044     last_level_to_check = template_class_depth (current_class_type) + 1;
4045   else
4046     /* Check everything.  */
4047     last_level_to_check = 0;
4048
4049   for (parm_level = parms;
4050        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4051        parm_level = TREE_CHAIN (parm_level))
4052     {
4053       tree inner_parms = TREE_VALUE (parm_level);
4054       int i;
4055       int ntparms;
4056
4057       ntparms = TREE_VEC_LENGTH (inner_parms);
4058       for (i = 0; i < ntparms; ++i)
4059         {
4060           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4061             continue;
4062
4063           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4064             {
4065               if (msg)
4066                 {
4067                   no_errors = false;
4068                   if (is_friend_decl == 2)
4069                     return no_errors;
4070
4071                   error (msg, decl);
4072                   msg = 0;
4073                 }
4074
4075               /* Clear out the default argument so that we are not
4076                  confused later.  */
4077               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4078             }
4079         }
4080
4081       /* At this point, if we're still interested in issuing messages,
4082          they must apply to classes surrounding the object declared.  */
4083       if (msg)
4084         msg = "default argument for template parameter for class enclosing %qD";
4085     }
4086
4087   return no_errors;
4088 }
4089
4090 /* Worker for push_template_decl_real, called via
4091    for_each_template_parm.  DATA is really an int, indicating the
4092    level of the parameters we are interested in.  If T is a template
4093    parameter of that level, return nonzero.  */
4094
4095 static int
4096 template_parm_this_level_p (tree t, void* data)
4097 {
4098   int this_level = *(int *)data;
4099   int level;
4100
4101   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4102     level = TEMPLATE_PARM_LEVEL (t);
4103   else
4104     level = TEMPLATE_TYPE_LEVEL (t);
4105   return level == this_level;
4106 }
4107
4108 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4109    parameters given by current_template_args, or reuses a
4110    previously existing one, if appropriate.  Returns the DECL, or an
4111    equivalent one, if it is replaced via a call to duplicate_decls.
4112
4113    If IS_FRIEND is true, DECL is a friend declaration.  */
4114
4115 tree
4116 push_template_decl_real (tree decl, bool is_friend)
4117 {
4118   tree tmpl;
4119   tree args;
4120   tree info;
4121   tree ctx;
4122   int primary;
4123   int is_partial;
4124   int new_template_p = 0;
4125   /* True if the template is a member template, in the sense of
4126      [temp.mem].  */
4127   bool member_template_p = false;
4128
4129   if (decl == error_mark_node || !current_template_parms)
4130     return error_mark_node;
4131
4132   /* See if this is a partial specialization.  */
4133   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4134                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4135                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4136
4137   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4138     is_friend = true;
4139
4140   if (is_friend)
4141     /* For a friend, we want the context of the friend function, not
4142        the type of which it is a friend.  */
4143     ctx = DECL_CONTEXT (decl);
4144   else if (CP_DECL_CONTEXT (decl)
4145            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4146     /* In the case of a virtual function, we want the class in which
4147        it is defined.  */
4148     ctx = CP_DECL_CONTEXT (decl);
4149   else
4150     /* Otherwise, if we're currently defining some class, the DECL
4151        is assumed to be a member of the class.  */
4152     ctx = current_scope ();
4153
4154   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4155     ctx = NULL_TREE;
4156
4157   if (!DECL_CONTEXT (decl))
4158     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4159
4160   /* See if this is a primary template.  */
4161   if (is_friend && ctx)
4162     /* A friend template that specifies a class context, i.e.
4163          template <typename T> friend void A<T>::f();
4164        is not primary.  */
4165     primary = 0;
4166   else
4167     primary = template_parm_scope_p ();
4168
4169   if (primary)
4170     {
4171       if (DECL_CLASS_SCOPE_P (decl))
4172         member_template_p = true;
4173       if (TREE_CODE (decl) == TYPE_DECL
4174           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4175         {
4176           error ("template class without a name");
4177           return error_mark_node;
4178         }
4179       else if (TREE_CODE (decl) == FUNCTION_DECL)
4180         {
4181           if (DECL_DESTRUCTOR_P (decl))
4182             {
4183               /* [temp.mem]
4184
4185                  A destructor shall not be a member template.  */
4186               error ("destructor %qD declared as member template", decl);
4187               return error_mark_node;
4188             }
4189           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4190               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4191                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4192                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4193                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4194                       == void_list_node)))
4195             {
4196               /* [basic.stc.dynamic.allocation]
4197
4198                  An allocation function can be a function
4199                  template. ... Template allocation functions shall
4200                  have two or more parameters.  */
4201               error ("invalid template declaration of %qD", decl);
4202               return error_mark_node;
4203             }
4204         }
4205       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4206                && CLASS_TYPE_P (TREE_TYPE (decl)))
4207         /* OK */;
4208       else
4209         {
4210           error ("template declaration of %q#D", decl);
4211           return error_mark_node;
4212         }
4213     }
4214
4215   /* Check to see that the rules regarding the use of default
4216      arguments are not being violated.  */
4217   check_default_tmpl_args (decl, current_template_parms,
4218                            primary, is_partial, /*is_friend_decl=*/0);
4219
4220   /* Ensure that there are no parameter packs in the type of this
4221      declaration that have not been expanded.  */
4222   if (TREE_CODE (decl) == FUNCTION_DECL)
4223     {
4224       /* Check each of the arguments individually to see if there are
4225          any bare parameter packs.  */
4226       tree type = TREE_TYPE (decl);
4227       tree arg = DECL_ARGUMENTS (decl);
4228       tree argtype = TYPE_ARG_TYPES (type);
4229
4230       while (arg && argtype)
4231         {
4232           if (!FUNCTION_PARAMETER_PACK_P (arg)
4233               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4234             {
4235             /* This is a PARM_DECL that contains unexpanded parameter
4236                packs. We have already complained about this in the
4237                check_for_bare_parameter_packs call, so just replace
4238                these types with ERROR_MARK_NODE.  */
4239               TREE_TYPE (arg) = error_mark_node;
4240               TREE_VALUE (argtype) = error_mark_node;
4241             }
4242
4243           arg = TREE_CHAIN (arg);
4244           argtype = TREE_CHAIN (argtype);
4245         }
4246
4247       /* Check for bare parameter packs in the return type and the
4248          exception specifiers.  */
4249       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4250         /* Errors were already issued, set return type to int
4251            as the frontend doesn't expect error_mark_node as
4252            the return type.  */
4253         TREE_TYPE (type) = integer_type_node;
4254       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4255         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4256     }
4257   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4258     {
4259       TREE_TYPE (decl) = error_mark_node;
4260       return error_mark_node;
4261     }
4262
4263   if (is_partial)
4264     return process_partial_specialization (decl);
4265
4266   args = current_template_args ();
4267
4268   if (!ctx
4269       || TREE_CODE (ctx) == FUNCTION_DECL
4270       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4271       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4272     {
4273       if (DECL_LANG_SPECIFIC (decl)
4274           && DECL_TEMPLATE_INFO (decl)
4275           && DECL_TI_TEMPLATE (decl))
4276         tmpl = DECL_TI_TEMPLATE (decl);
4277       /* If DECL is a TYPE_DECL for a class-template, then there won't
4278          be DECL_LANG_SPECIFIC.  The information equivalent to
4279          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4280       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4281                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4282                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4283         {
4284           /* Since a template declaration already existed for this
4285              class-type, we must be redeclaring it here.  Make sure
4286              that the redeclaration is valid.  */
4287           redeclare_class_template (TREE_TYPE (decl),
4288                                     current_template_parms);
4289           /* We don't need to create a new TEMPLATE_DECL; just use the
4290              one we already had.  */
4291           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4292         }
4293       else
4294         {
4295           tmpl = build_template_decl (decl, current_template_parms,
4296                                       member_template_p);
4297           new_template_p = 1;
4298
4299           if (DECL_LANG_SPECIFIC (decl)
4300               && DECL_TEMPLATE_SPECIALIZATION (decl))
4301             {
4302               /* A specialization of a member template of a template
4303                  class.  */
4304               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4305               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4306               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4307             }
4308         }
4309     }
4310   else
4311     {
4312       tree a, t, current, parms;
4313       int i;
4314       tree tinfo = get_template_info (decl);
4315
4316       if (!tinfo)
4317         {
4318           error ("template definition of non-template %q#D", decl);
4319           return error_mark_node;
4320         }
4321
4322       tmpl = TI_TEMPLATE (tinfo);
4323
4324       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4325           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4326           && DECL_TEMPLATE_SPECIALIZATION (decl)
4327           && DECL_MEMBER_TEMPLATE_P (tmpl))
4328         {
4329           tree new_tmpl;
4330
4331           /* The declaration is a specialization of a member
4332              template, declared outside the class.  Therefore, the
4333              innermost template arguments will be NULL, so we
4334              replace them with the arguments determined by the
4335              earlier call to check_explicit_specialization.  */
4336           args = DECL_TI_ARGS (decl);
4337
4338           new_tmpl
4339             = build_template_decl (decl, current_template_parms,
4340                                    member_template_p);
4341           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4342           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4343           DECL_TI_TEMPLATE (decl) = new_tmpl;
4344           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4345           DECL_TEMPLATE_INFO (new_tmpl)
4346             = tree_cons (tmpl, args, NULL_TREE);
4347
4348           register_specialization (new_tmpl,
4349                                    most_general_template (tmpl),
4350                                    args,
4351                                    is_friend, 0);
4352           return decl;
4353         }
4354
4355       /* Make sure the template headers we got make sense.  */
4356
4357       parms = DECL_TEMPLATE_PARMS (tmpl);
4358       i = TMPL_PARMS_DEPTH (parms);
4359       if (TMPL_ARGS_DEPTH (args) != i)
4360         {
4361           error ("expected %d levels of template parms for %q#D, got %d",
4362                  i, decl, TMPL_ARGS_DEPTH (args));
4363         }
4364       else
4365         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4366           {
4367             a = TMPL_ARGS_LEVEL (args, i);
4368             t = INNERMOST_TEMPLATE_PARMS (parms);
4369
4370             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4371               {
4372                 if (current == decl)
4373                   error ("got %d template parameters for %q#D",
4374                          TREE_VEC_LENGTH (a), decl);
4375                 else
4376                   error ("got %d template parameters for %q#T",
4377                          TREE_VEC_LENGTH (a), current);
4378                 error ("  but %d required", TREE_VEC_LENGTH (t));
4379                 return error_mark_node;
4380               }
4381
4382             if (current == decl)
4383               current = ctx;
4384             else
4385               current = (TYPE_P (current)
4386                          ? TYPE_CONTEXT (current)
4387                          : DECL_CONTEXT (current));
4388           }
4389
4390       /* Check that the parms are used in the appropriate qualifying scopes
4391          in the declarator.  */
4392       if (!comp_template_args
4393           (TI_ARGS (tinfo),
4394            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4395         {
4396           error ("\
4397 template arguments to %qD do not match original template %qD",
4398                  decl, DECL_TEMPLATE_RESULT (tmpl));
4399           if (!uses_template_parms (TI_ARGS (tinfo)))
4400             inform (input_location, "use template<> for an explicit specialization");
4401           /* Avoid crash in import_export_decl.  */
4402           DECL_INTERFACE_KNOWN (decl) = 1;
4403           return error_mark_node;
4404         }
4405     }
4406
4407   DECL_TEMPLATE_RESULT (tmpl) = decl;
4408   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4409
4410   /* Push template declarations for global functions and types.  Note
4411      that we do not try to push a global template friend declared in a
4412      template class; such a thing may well depend on the template
4413      parameters of the class.  */
4414   if (new_template_p && !ctx
4415       && !(is_friend && template_class_depth (current_class_type) > 0))
4416     {
4417       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4418       if (tmpl == error_mark_node)
4419         return error_mark_node;
4420
4421       /* Hide template friend classes that haven't been declared yet.  */
4422       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4423         {
4424           DECL_ANTICIPATED (tmpl) = 1;
4425           DECL_FRIEND_P (tmpl) = 1;
4426         }
4427     }
4428
4429   if (primary)
4430     {
4431       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4432       int i;
4433
4434       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4435       if (DECL_CONV_FN_P (tmpl))
4436         {
4437           int depth = TMPL_PARMS_DEPTH (parms);
4438
4439           /* It is a conversion operator. See if the type converted to
4440              depends on innermost template operands.  */
4441
4442           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4443                                          depth))
4444             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4445         }
4446
4447       /* Give template template parms a DECL_CONTEXT of the template
4448          for which they are a parameter.  */
4449       parms = INNERMOST_TEMPLATE_PARMS (parms);
4450       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4451         {
4452           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4453           if (TREE_CODE (parm) == TEMPLATE_DECL)
4454             DECL_CONTEXT (parm) = tmpl;
4455         }
4456     }
4457
4458   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4459      back to its most general template.  If TMPL is a specialization,
4460      ARGS may only have the innermost set of arguments.  Add the missing
4461      argument levels if necessary.  */
4462   if (DECL_TEMPLATE_INFO (tmpl))
4463     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4464
4465   info = tree_cons (tmpl, args, NULL_TREE);
4466
4467   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4468     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4469   else if (DECL_LANG_SPECIFIC (decl))
4470     DECL_TEMPLATE_INFO (decl) = info;
4471
4472   return DECL_TEMPLATE_RESULT (tmpl);
4473 }
4474
4475 tree
4476 push_template_decl (tree decl)
4477 {
4478   return push_template_decl_real (decl, false);
4479 }
4480
4481 /* Called when a class template TYPE is redeclared with the indicated
4482    template PARMS, e.g.:
4483
4484      template <class T> struct S;
4485      template <class T> struct S {};  */
4486
4487 bool
4488 redeclare_class_template (tree type, tree parms)
4489 {
4490   tree tmpl;
4491   tree tmpl_parms;
4492   int i;
4493
4494   if (!TYPE_TEMPLATE_INFO (type))
4495     {
4496       error ("%qT is not a template type", type);
4497       return false;
4498     }
4499
4500   tmpl = TYPE_TI_TEMPLATE (type);
4501   if (!PRIMARY_TEMPLATE_P (tmpl))
4502     /* The type is nested in some template class.  Nothing to worry
4503        about here; there are no new template parameters for the nested
4504        type.  */
4505     return true;
4506
4507   if (!parms)
4508     {
4509       error ("template specifiers not specified in declaration of %qD",
4510              tmpl);
4511       return false;
4512     }
4513
4514   parms = INNERMOST_TEMPLATE_PARMS (parms);
4515   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4516
4517   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4518     {
4519       error ("redeclared with %d template parameter(s)", 
4520              TREE_VEC_LENGTH (parms));
4521       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4522              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4523       return false;
4524     }
4525
4526   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4527     {
4528       tree tmpl_parm;
4529       tree parm;
4530       tree tmpl_default;
4531       tree parm_default;
4532
4533       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4534           || TREE_VEC_ELT (parms, i) == error_mark_node)
4535         continue;
4536
4537       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4538       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4539       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4540       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4541
4542       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4543          TEMPLATE_DECL.  */
4544       if (tmpl_parm != error_mark_node
4545           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4546               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4547                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4548               || (TREE_CODE (tmpl_parm) != PARM_DECL
4549                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4550                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4551               || (TREE_CODE (tmpl_parm) == PARM_DECL
4552                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4553                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4554         {
4555           error ("template parameter %q+#D", tmpl_parm);
4556           error ("redeclared here as %q#D", parm);
4557           return false;
4558         }
4559
4560       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4561         {
4562           /* We have in [temp.param]:
4563
4564              A template-parameter may not be given default arguments
4565              by two different declarations in the same scope.  */
4566           error_at (input_location, "redefinition of default argument for %q#D", parm);
4567           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4568                   "original definition appeared here");
4569           return false;
4570         }
4571
4572       if (parm_default != NULL_TREE)
4573         /* Update the previous template parameters (which are the ones
4574            that will really count) with the new default value.  */
4575         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4576       else if (tmpl_default != NULL_TREE)
4577         /* Update the new parameters, too; they'll be used as the
4578            parameters for any members.  */
4579         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4580     }
4581
4582     return true;
4583 }
4584
4585 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4586    (possibly simplified) expression.  */
4587
4588 tree
4589 fold_non_dependent_expr (tree expr)
4590 {
4591   if (expr == NULL_TREE)
4592     return NULL_TREE;
4593
4594   /* If we're in a template, but EXPR isn't value dependent, simplify
4595      it.  We're supposed to treat:
4596
4597        template <typename T> void f(T[1 + 1]);
4598        template <typename T> void f(T[2]);
4599
4600      as two declarations of the same function, for example.  */
4601   if (processing_template_decl
4602       && !type_dependent_expression_p (expr)
4603       && !value_dependent_expression_p (expr))
4604     {
4605       HOST_WIDE_INT saved_processing_template_decl;
4606
4607       saved_processing_template_decl = processing_template_decl;
4608       processing_template_decl = 0;
4609       expr = tsubst_copy_and_build (expr,
4610                                     /*args=*/NULL_TREE,
4611                                     tf_error,
4612                                     /*in_decl=*/NULL_TREE,
4613                                     /*function_p=*/false,
4614                                     /*integral_constant_expression_p=*/true);
4615       processing_template_decl = saved_processing_template_decl;
4616     }
4617   return expr;
4618 }
4619
4620 /* EXPR is an expression which is used in a constant-expression context.
4621    For instance, it could be a VAR_DECL with a constant initializer.
4622    Extract the innermost constant expression.
4623
4624    This is basically a more powerful version of
4625    integral_constant_value, which can be used also in templates where
4626    initializers can maintain a syntactic rather than semantic form
4627    (even if they are non-dependent, for access-checking purposes).  */
4628
4629 static tree
4630 fold_decl_constant_value (tree expr)
4631 {
4632   tree const_expr = expr;
4633   do
4634     {
4635       expr = fold_non_dependent_expr (const_expr);
4636       const_expr = integral_constant_value (expr);
4637     }
4638   while (expr != const_expr);
4639
4640   return expr;
4641 }
4642
4643 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4644    must be a function or a pointer-to-function type, as specified
4645    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4646    and check that the resulting function has external linkage.  */
4647
4648 static tree
4649 convert_nontype_argument_function (tree type, tree expr)
4650 {
4651   tree fns = expr;
4652   tree fn, fn_no_ptr;
4653
4654   fn = instantiate_type (type, fns, tf_none);
4655   if (fn == error_mark_node)
4656     return error_mark_node;
4657
4658   fn_no_ptr = fn;
4659   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4660     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4661   if (TREE_CODE (fn_no_ptr) == BASELINK)
4662     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4663  
4664   /* [temp.arg.nontype]/1
4665
4666      A template-argument for a non-type, non-template template-parameter
4667      shall be one of:
4668      [...]
4669      -- the address of an object or function with external linkage.  */
4670   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4671     {
4672       error ("%qE is not a valid template argument for type %qT "
4673              "because function %qD has not external linkage",
4674              expr, type, fn_no_ptr);
4675       return NULL_TREE;
4676     }
4677
4678   return fn;
4679 }
4680
4681 /* Attempt to convert the non-type template parameter EXPR to the
4682    indicated TYPE.  If the conversion is successful, return the
4683    converted value.  If the conversion is unsuccessful, return
4684    NULL_TREE if we issued an error message, or error_mark_node if we
4685    did not.  We issue error messages for out-and-out bad template
4686    parameters, but not simply because the conversion failed, since we
4687    might be just trying to do argument deduction.  Both TYPE and EXPR
4688    must be non-dependent.
4689
4690    The conversion follows the special rules described in
4691    [temp.arg.nontype], and it is much more strict than an implicit
4692    conversion.
4693
4694    This function is called twice for each template argument (see
4695    lookup_template_class for a more accurate description of this
4696    problem). This means that we need to handle expressions which
4697    are not valid in a C++ source, but can be created from the
4698    first call (for instance, casts to perform conversions). These
4699    hacks can go away after we fix the double coercion problem.  */
4700
4701 static tree
4702 convert_nontype_argument (tree type, tree expr)
4703 {
4704   tree expr_type;
4705
4706   /* Detect immediately string literals as invalid non-type argument.
4707      This special-case is not needed for correctness (we would easily
4708      catch this later), but only to provide better diagnostic for this
4709      common user mistake. As suggested by DR 100, we do not mention
4710      linkage issues in the diagnostic as this is not the point.  */
4711   if (TREE_CODE (expr) == STRING_CST)
4712     {
4713       error ("%qE is not a valid template argument for type %qT "
4714              "because string literals can never be used in this context",
4715              expr, type);
4716       return NULL_TREE;
4717     }
4718
4719   /* If we are in a template, EXPR may be non-dependent, but still
4720      have a syntactic, rather than semantic, form.  For example, EXPR
4721      might be a SCOPE_REF, rather than the VAR_DECL to which the
4722      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4723      so that access checking can be performed when the template is
4724      instantiated -- but here we need the resolved form so that we can
4725      convert the argument.  */
4726   expr = fold_non_dependent_expr (expr);
4727   if (error_operand_p (expr))
4728     return error_mark_node;
4729   expr_type = TREE_TYPE (expr);
4730
4731   /* HACK: Due to double coercion, we can get a
4732      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4733      which is the tree that we built on the first call (see
4734      below when coercing to reference to object or to reference to
4735      function). We just strip everything and get to the arg.
4736      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4737      for examples.  */
4738   if (TREE_CODE (expr) == NOP_EXPR)
4739     {
4740       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4741         {
4742           /* ??? Maybe we could use convert_from_reference here, but we
4743              would need to relax its constraints because the NOP_EXPR
4744              could actually change the type to something more cv-qualified,
4745              and this is not folded by convert_from_reference.  */
4746           tree addr = TREE_OPERAND (expr, 0);
4747           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4748           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4749           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4750           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4751                       (TREE_TYPE (expr_type),
4752                        TREE_TYPE (TREE_TYPE (addr))));
4753
4754           expr = TREE_OPERAND (addr, 0);
4755           expr_type = TREE_TYPE (expr);
4756         }
4757
4758       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4759          parameter is a pointer to object, through decay and
4760          qualification conversion. Let's strip everything.  */
4761       else if (TYPE_PTROBV_P (type))
4762         {
4763           STRIP_NOPS (expr);
4764           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4765           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4766           /* Skip the ADDR_EXPR only if it is part of the decay for
4767              an array. Otherwise, it is part of the original argument
4768              in the source code.  */
4769           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4770             expr = TREE_OPERAND (expr, 0);
4771           expr_type = TREE_TYPE (expr);
4772         }
4773     }
4774
4775   /* [temp.arg.nontype]/5, bullet 1
4776
4777      For a non-type template-parameter of integral or enumeration type,
4778      integral promotions (_conv.prom_) and integral conversions
4779      (_conv.integral_) are applied.  */
4780   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4781     {
4782       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4783         return error_mark_node;
4784
4785       expr = fold_decl_constant_value (expr);
4786       /* Notice that there are constant expressions like '4 % 0' which
4787          do not fold into integer constants.  */
4788       if (TREE_CODE (expr) != INTEGER_CST)
4789         {
4790           error ("%qE is not a valid template argument for type %qT "
4791                  "because it is a non-constant expression", expr, type);
4792           return NULL_TREE;
4793         }
4794
4795       /* At this point, an implicit conversion does what we want,
4796          because we already know that the expression is of integral
4797          type.  */
4798       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4799       if (expr == error_mark_node)
4800         return error_mark_node;
4801
4802       /* Conversion was allowed: fold it to a bare integer constant.  */
4803       expr = fold (expr);
4804     }
4805   /* [temp.arg.nontype]/5, bullet 2
4806
4807      For a non-type template-parameter of type pointer to object,
4808      qualification conversions (_conv.qual_) and the array-to-pointer
4809      conversion (_conv.array_) are applied.  */
4810   else if (TYPE_PTROBV_P (type))
4811     {
4812       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4813
4814          A template-argument for a non-type, non-template template-parameter
4815          shall be one of: [...]
4816
4817          -- the name of a non-type template-parameter;
4818          -- the address of an object or function with external linkage, [...]
4819             expressed as "& id-expression" where the & is optional if the name
4820             refers to a function or array, or if the corresponding
4821             template-parameter is a reference.
4822
4823         Here, we do not care about functions, as they are invalid anyway
4824         for a parameter of type pointer-to-object.  */
4825
4826       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4827         /* Non-type template parameters are OK.  */
4828         ;
4829       else if (TREE_CODE (expr) != ADDR_EXPR
4830                && TREE_CODE (expr_type) != ARRAY_TYPE)
4831         {
4832           if (TREE_CODE (expr) == VAR_DECL)
4833             {
4834               error ("%qD is not a valid template argument "
4835                      "because %qD is a variable, not the address of "
4836                      "a variable",
4837                      expr, expr);
4838               return NULL_TREE;
4839             }
4840           /* Other values, like integer constants, might be valid
4841              non-type arguments of some other type.  */
4842           return error_mark_node;
4843         }
4844       else
4845         {
4846           tree decl;
4847
4848           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4849                   ? TREE_OPERAND (expr, 0) : expr);
4850           if (TREE_CODE (decl) != VAR_DECL)
4851             {
4852               error ("%qE is not a valid template argument of type %qT "
4853                      "because %qE is not a variable",
4854                      expr, type, decl);
4855               return NULL_TREE;
4856             }
4857           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4858             {
4859               error ("%qE is not a valid template argument of type %qT "
4860                      "because %qD does not have external linkage",
4861                      expr, type, decl);
4862               return NULL_TREE;
4863             }
4864         }
4865
4866       expr = decay_conversion (expr);
4867       if (expr == error_mark_node)
4868         return error_mark_node;
4869
4870       expr = perform_qualification_conversions (type, expr);
4871       if (expr == error_mark_node)
4872         return error_mark_node;
4873     }
4874   /* [temp.arg.nontype]/5, bullet 3
4875
4876      For a non-type template-parameter of type reference to object, no
4877      conversions apply. The type referred to by the reference may be more
4878      cv-qualified than the (otherwise identical) type of the
4879      template-argument. The template-parameter is bound directly to the
4880      template-argument, which must be an lvalue.  */
4881   else if (TYPE_REF_OBJ_P (type))
4882     {
4883       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4884                                                       expr_type))
4885         return error_mark_node;
4886
4887       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4888         {
4889           error ("%qE is not a valid template argument for type %qT "
4890                  "because of conflicts in cv-qualification", expr, type);
4891           return NULL_TREE;
4892         }
4893
4894       if (!real_lvalue_p (expr))
4895         {
4896           error ("%qE is not a valid template argument for type %qT "
4897                  "because it is not an lvalue", expr, type);
4898           return NULL_TREE;
4899         }
4900
4901       /* [temp.arg.nontype]/1
4902
4903          A template-argument for a non-type, non-template template-parameter
4904          shall be one of: [...]
4905
4906          -- the address of an object or function with external linkage.  */
4907       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4908         {
4909           error ("%qE is not a valid template argument for type %qT "
4910                  "because object %qD has not external linkage",
4911                  expr, type, expr);
4912           return NULL_TREE;
4913         }
4914
4915       expr = build_nop (type, build_address (expr));
4916     }
4917   /* [temp.arg.nontype]/5, bullet 4
4918
4919      For a non-type template-parameter of type pointer to function, only
4920      the function-to-pointer conversion (_conv.func_) is applied. If the
4921      template-argument represents a set of overloaded functions (or a
4922      pointer to such), the matching function is selected from the set
4923      (_over.over_).  */
4924   else if (TYPE_PTRFN_P (type))
4925     {
4926       /* If the argument is a template-id, we might not have enough
4927          context information to decay the pointer.  */
4928       if (!type_unknown_p (expr_type))
4929         {
4930           expr = decay_conversion (expr);
4931           if (expr == error_mark_node)
4932             return error_mark_node;
4933         }
4934
4935       expr = convert_nontype_argument_function (type, expr);
4936       if (!expr || expr == error_mark_node)
4937         return expr;
4938
4939       if (TREE_CODE (expr) != ADDR_EXPR)
4940         {
4941           error ("%qE is not a valid template argument for type %qT", expr, type);
4942           error ("it must be the address of a function with external linkage");
4943           return NULL_TREE;
4944         }
4945     }
4946   /* [temp.arg.nontype]/5, bullet 5
4947
4948      For a non-type template-parameter of type reference to function, no
4949      conversions apply. If the template-argument represents a set of
4950      overloaded functions, the matching function is selected from the set
4951      (_over.over_).  */
4952   else if (TYPE_REFFN_P (type))
4953     {
4954       if (TREE_CODE (expr) == ADDR_EXPR)
4955         {
4956           error ("%qE is not a valid template argument for type %qT "
4957                  "because it is a pointer", expr, type);
4958           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
4959           return NULL_TREE;
4960         }
4961
4962       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4963       if (!expr || expr == error_mark_node)
4964         return expr;
4965
4966       expr = build_nop (type, build_address (expr));
4967     }
4968   /* [temp.arg.nontype]/5, bullet 6
4969
4970      For a non-type template-parameter of type pointer to member function,
4971      no conversions apply. If the template-argument represents a set of
4972      overloaded member functions, the matching member function is selected
4973      from the set (_over.over_).  */
4974   else if (TYPE_PTRMEMFUNC_P (type))
4975     {
4976       expr = instantiate_type (type, expr, tf_none);
4977       if (expr == error_mark_node)
4978         return error_mark_node;
4979
4980       /* There is no way to disable standard conversions in
4981          resolve_address_of_overloaded_function (called by
4982          instantiate_type). It is possible that the call succeeded by
4983          converting &B::I to &D::I (where B is a base of D), so we need
4984          to reject this conversion here.
4985
4986          Actually, even if there was a way to disable standard conversions,
4987          it would still be better to reject them here so that we can
4988          provide a superior diagnostic.  */
4989       if (!same_type_p (TREE_TYPE (expr), type))
4990         {
4991           /* Make sure we are just one standard conversion off.  */
4992           gcc_assert (can_convert (type, TREE_TYPE (expr)));
4993           error ("%qE is not a valid template argument for type %qT "
4994                  "because it is of type %qT", expr, type,
4995                  TREE_TYPE (expr));
4996           inform (input_location, "standard conversions are not allowed in this context");
4997           return NULL_TREE;
4998         }
4999     }
5000   /* [temp.arg.nontype]/5, bullet 7
5001
5002      For a non-type template-parameter of type pointer to data member,
5003      qualification conversions (_conv.qual_) are applied.  */
5004   else if (TYPE_PTRMEM_P (type))
5005     {
5006       expr = perform_qualification_conversions (type, expr);
5007       if (expr == error_mark_node)
5008         return expr;
5009     }
5010   /* A template non-type parameter must be one of the above.  */
5011   else
5012     gcc_unreachable ();
5013
5014   /* Sanity check: did we actually convert the argument to the
5015      right type?  */
5016   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5017   return expr;
5018 }
5019
5020 /* Subroutine of coerce_template_template_parms, which returns 1 if
5021    PARM_PARM and ARG_PARM match using the rule for the template
5022    parameters of template template parameters. Both PARM and ARG are
5023    template parameters; the rest of the arguments are the same as for
5024    coerce_template_template_parms.
5025  */
5026 static int
5027 coerce_template_template_parm (tree parm,
5028                               tree arg,
5029                               tsubst_flags_t complain,
5030                               tree in_decl,
5031                               tree outer_args)
5032 {
5033   if (arg == NULL_TREE || arg == error_mark_node
5034       || parm == NULL_TREE || parm == error_mark_node)
5035     return 0;
5036   
5037   if (TREE_CODE (arg) != TREE_CODE (parm))
5038     return 0;
5039   
5040   switch (TREE_CODE (parm))
5041     {
5042     case TEMPLATE_DECL:
5043       /* We encounter instantiations of templates like
5044          template <template <template <class> class> class TT>
5045          class C;  */
5046       {
5047         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5048         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5049         
5050         if (!coerce_template_template_parms
5051             (parmparm, argparm, complain, in_decl, outer_args))
5052           return 0;
5053       }
5054       /* Fall through.  */
5055       
5056     case TYPE_DECL:
5057       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5058           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5059         /* Argument is a parameter pack but parameter is not.  */
5060         return 0;
5061       break;
5062       
5063     case PARM_DECL:
5064       /* The tsubst call is used to handle cases such as
5065          
5066            template <int> class C {};
5067            template <class T, template <T> class TT> class D {};
5068            D<int, C> d;
5069
5070          i.e. the parameter list of TT depends on earlier parameters.  */
5071       if (!uses_template_parms (TREE_TYPE (arg))
5072           && !same_type_p
5073                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5074                  TREE_TYPE (arg)))
5075         return 0;
5076       
5077       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5078           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5079         /* Argument is a parameter pack but parameter is not.  */
5080         return 0;
5081       
5082       break;
5083
5084     default:
5085       gcc_unreachable ();
5086     }
5087
5088   return 1;
5089 }
5090
5091
5092 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5093    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5094    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5095    or PARM_DECL.
5096
5097    Consider the example:
5098      template <class T> class A;
5099      template<template <class U> class TT> class B;
5100
5101    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5102    the parameters to A, and OUTER_ARGS contains A.  */
5103
5104 static int
5105 coerce_template_template_parms (tree parm_parms,
5106                                 tree arg_parms,
5107                                 tsubst_flags_t complain,
5108                                 tree in_decl,
5109                                 tree outer_args)
5110 {
5111   int nparms, nargs, i;
5112   tree parm, arg;
5113   int variadic_p = 0;
5114
5115   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5116   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5117
5118   nparms = TREE_VEC_LENGTH (parm_parms);
5119   nargs = TREE_VEC_LENGTH (arg_parms);
5120
5121   /* Determine whether we have a parameter pack at the end of the
5122      template template parameter's template parameter list.  */
5123   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5124     {
5125       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5126       
5127       if (parm == error_mark_node)
5128         return 0;
5129
5130       switch (TREE_CODE (parm))
5131         {
5132         case TEMPLATE_DECL:
5133         case TYPE_DECL:
5134           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5135             variadic_p = 1;
5136           break;
5137           
5138         case PARM_DECL:
5139           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5140             variadic_p = 1;
5141           break;
5142           
5143         default:
5144           gcc_unreachable ();
5145         }
5146     }
5147  
5148   if (nargs != nparms
5149       && !(variadic_p && nargs >= nparms - 1))
5150     return 0;
5151
5152   /* Check all of the template parameters except the parameter pack at
5153      the end (if any).  */
5154   for (i = 0; i < nparms - variadic_p; ++i)
5155     {
5156       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5157           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5158         continue;
5159
5160       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5161       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5162
5163       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5164                                           outer_args))
5165         return 0;
5166
5167     }
5168
5169   if (variadic_p)
5170     {
5171       /* Check each of the template parameters in the template
5172          argument against the template parameter pack at the end of
5173          the template template parameter.  */
5174       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5175         return 0;
5176
5177       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5178
5179       for (; i < nargs; ++i)
5180         {
5181           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5182             continue;
5183  
5184           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5185  
5186           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5187                                               outer_args))
5188             return 0;
5189         }
5190     }
5191
5192   return 1;
5193 }
5194
5195 /* Verifies that the deduced template arguments (in TARGS) for the
5196    template template parameters (in TPARMS) represent valid bindings,
5197    by comparing the template parameter list of each template argument
5198    to the template parameter list of its corresponding template
5199    template parameter, in accordance with DR150. This
5200    routine can only be called after all template arguments have been
5201    deduced. It will return TRUE if all of the template template
5202    parameter bindings are okay, FALSE otherwise.  */
5203 bool 
5204 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5205 {
5206   int i, ntparms = TREE_VEC_LENGTH (tparms);
5207   bool ret = true;
5208
5209   /* We're dealing with template parms in this process.  */
5210   ++processing_template_decl;
5211
5212   targs = INNERMOST_TEMPLATE_ARGS (targs);
5213
5214   for (i = 0; i < ntparms; ++i)
5215     {
5216       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5217       tree targ = TREE_VEC_ELT (targs, i);
5218
5219       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5220         {
5221           tree packed_args = NULL_TREE;
5222           int idx, len = 1;
5223
5224           if (ARGUMENT_PACK_P (targ))
5225             {
5226               /* Look inside the argument pack.  */
5227               packed_args = ARGUMENT_PACK_ARGS (targ);
5228               len = TREE_VEC_LENGTH (packed_args);
5229             }
5230
5231           for (idx = 0; idx < len; ++idx)
5232             {
5233               tree targ_parms = NULL_TREE;
5234
5235               if (packed_args)
5236                 /* Extract the next argument from the argument
5237                    pack.  */
5238                 targ = TREE_VEC_ELT (packed_args, idx);
5239
5240               if (PACK_EXPANSION_P (targ))
5241                 /* Look at the pattern of the pack expansion.  */
5242                 targ = PACK_EXPANSION_PATTERN (targ);
5243
5244               /* Extract the template parameters from the template
5245                  argument.  */
5246               if (TREE_CODE (targ) == TEMPLATE_DECL)
5247                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5248               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5249                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5250
5251               /* Verify that we can coerce the template template
5252                  parameters from the template argument to the template
5253                  parameter.  This requires an exact match.  */
5254               if (targ_parms
5255                   && !coerce_template_template_parms
5256                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5257                         targ_parms,
5258                         tf_none,
5259                         tparm,
5260                         targs))
5261                 {
5262                   ret = false;
5263                   goto out;
5264                 }
5265             }
5266         }
5267     }
5268
5269  out:
5270
5271   --processing_template_decl;
5272   return ret;
5273 }
5274
5275 /* Convert the indicated template ARG as necessary to match the
5276    indicated template PARM.  Returns the converted ARG, or
5277    error_mark_node if the conversion was unsuccessful.  Error and
5278    warning messages are issued under control of COMPLAIN.  This
5279    conversion is for the Ith parameter in the parameter list.  ARGS is
5280    the full set of template arguments deduced so far.  */
5281
5282 static tree
5283 convert_template_argument (tree parm,
5284                            tree arg,
5285                            tree args,
5286                            tsubst_flags_t complain,
5287                            int i,
5288                            tree in_decl)
5289 {
5290   tree orig_arg;
5291   tree val;
5292   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5293
5294   if (TREE_CODE (arg) == TREE_LIST
5295       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5296     {
5297       /* The template argument was the name of some
5298          member function.  That's usually
5299          invalid, but static members are OK.  In any
5300          case, grab the underlying fields/functions
5301          and issue an error later if required.  */
5302       orig_arg = TREE_VALUE (arg);
5303       TREE_TYPE (arg) = unknown_type_node;
5304     }
5305
5306   orig_arg = arg;
5307
5308   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5309   requires_type = (TREE_CODE (parm) == TYPE_DECL
5310                    || requires_tmpl_type);
5311
5312   /* When determining whether an argument pack expansion is a template,
5313      look at the pattern.  */
5314   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5315     arg = PACK_EXPANSION_PATTERN (arg);
5316
5317   is_tmpl_type = 
5318     ((TREE_CODE (arg) == TEMPLATE_DECL
5319       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5320      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5321      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5322
5323   if (is_tmpl_type
5324       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5325           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5326     arg = TYPE_STUB_DECL (arg);
5327
5328   is_type = TYPE_P (arg) || is_tmpl_type;
5329
5330   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5331       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5332     {
5333       permerror (input_location, "to refer to a type member of a template parameter, "
5334                  "use %<typename %E%>", orig_arg);
5335
5336       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5337                                      TREE_OPERAND (arg, 1),
5338                                      typename_type,
5339                                      complain & tf_error);
5340       arg = orig_arg;
5341       is_type = 1;
5342     }
5343   if (is_type != requires_type)
5344     {
5345       if (in_decl)
5346         {
5347           if (complain & tf_error)
5348             {
5349               error ("type/value mismatch at argument %d in template "
5350                      "parameter list for %qD",
5351                      i + 1, in_decl);
5352               if (is_type)
5353                 error ("  expected a constant of type %qT, got %qT",
5354                        TREE_TYPE (parm),
5355                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5356               else if (requires_tmpl_type)
5357                 error ("  expected a class template, got %qE", orig_arg);
5358               else
5359                 error ("  expected a type, got %qE", orig_arg);
5360             }
5361         }
5362       return error_mark_node;
5363     }
5364   if (is_tmpl_type ^ requires_tmpl_type)
5365     {
5366       if (in_decl && (complain & tf_error))
5367         {
5368           error ("type/value mismatch at argument %d in template "
5369                  "parameter list for %qD",
5370                  i + 1, in_decl);
5371           if (is_tmpl_type)
5372             error ("  expected a type, got %qT", DECL_NAME (arg));
5373           else
5374             error ("  expected a class template, got %qT", orig_arg);
5375         }
5376       return error_mark_node;
5377     }
5378
5379   if (is_type)
5380     {
5381       if (requires_tmpl_type)
5382         {
5383           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5384             /* The number of argument required is not known yet.
5385                Just accept it for now.  */
5386             val = TREE_TYPE (arg);
5387           else
5388             {
5389               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5390               tree argparm;
5391
5392               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5393
5394               if (coerce_template_template_parms (parmparm, argparm,
5395                                                   complain, in_decl,
5396                                                   args))
5397                 {
5398                   val = orig_arg;
5399
5400                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5401                      TEMPLATE_DECL.  */
5402                   if (val != error_mark_node)
5403                     {
5404                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5405                         val = TREE_TYPE (val);
5406                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
5407                                && DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
5408                         {
5409                           val = TREE_TYPE (arg);
5410                           val = make_pack_expansion (val);
5411                         }
5412                     }
5413                 }
5414               else
5415                 {
5416                   if (in_decl && (complain & tf_error))
5417                     {
5418                       error ("type/value mismatch at argument %d in "
5419                              "template parameter list for %qD",
5420                              i + 1, in_decl);
5421                       error ("  expected a template of type %qD, got %qD",
5422                              parm, orig_arg);
5423                     }
5424
5425                   val = error_mark_node;
5426                 }
5427             }
5428         }
5429       else
5430         val = orig_arg;
5431       /* We only form one instance of each template specialization.
5432          Therefore, if we use a non-canonical variant (i.e., a
5433          typedef), any future messages referring to the type will use
5434          the typedef, which is confusing if those future uses do not
5435          themselves also use the typedef.  */
5436       if (TYPE_P (val))
5437         val = strip_typedefs (val);
5438     }
5439   else
5440     {
5441       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5442
5443       if (invalid_nontype_parm_type_p (t, complain))
5444         return error_mark_node;
5445
5446       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5447         {
5448           if (same_type_p (t, TREE_TYPE (orig_arg)))
5449             val = orig_arg;
5450           else
5451             {
5452               /* Not sure if this is reachable, but it doesn't hurt
5453                  to be robust.  */
5454               error ("type mismatch in nontype parameter pack");
5455               val = error_mark_node;
5456             }
5457         }
5458       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5459         /* We used to call digest_init here.  However, digest_init
5460            will report errors, which we don't want when complain
5461            is zero.  More importantly, digest_init will try too
5462            hard to convert things: for example, `0' should not be
5463            converted to pointer type at this point according to
5464            the standard.  Accepting this is not merely an
5465            extension, since deciding whether or not these
5466            conversions can occur is part of determining which
5467            function template to call, or whether a given explicit
5468            argument specification is valid.  */
5469         val = convert_nontype_argument (t, orig_arg);
5470       else
5471         val = orig_arg;
5472
5473       if (val == NULL_TREE)
5474         val = error_mark_node;
5475       else if (val == error_mark_node && (complain & tf_error))
5476         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5477     }
5478
5479   return val;
5480 }
5481
5482 /* Coerces the remaining template arguments in INNER_ARGS (from
5483    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5484    Returns the coerced argument pack. PARM_IDX is the position of this
5485    parameter in the template parameter list. ARGS is the original
5486    template argument list.  */
5487 static tree
5488 coerce_template_parameter_pack (tree parms,
5489                                 int parm_idx,
5490                                 tree args,
5491                                 tree inner_args,
5492                                 int arg_idx,
5493                                 tree new_args,
5494                                 int* lost,
5495                                 tree in_decl,
5496                                 tsubst_flags_t complain)
5497 {
5498   tree parm = TREE_VEC_ELT (parms, parm_idx);
5499   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5500   tree packed_args;
5501   tree argument_pack;
5502   tree packed_types = NULL_TREE;
5503
5504   if (arg_idx > nargs)
5505     arg_idx = nargs;
5506
5507   packed_args = make_tree_vec (nargs - arg_idx);
5508
5509   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5510       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5511     {
5512       /* When the template parameter is a non-type template
5513          parameter pack whose type uses parameter packs, we need
5514          to look at each of the template arguments
5515          separately. Build a vector of the types for these
5516          non-type template parameters in PACKED_TYPES.  */
5517       tree expansion 
5518         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5519       packed_types = tsubst_pack_expansion (expansion, args,
5520                                             complain, in_decl);
5521
5522       if (packed_types == error_mark_node)
5523         return error_mark_node;
5524
5525       /* Check that we have the right number of arguments.  */
5526       if (arg_idx < nargs
5527           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5528           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5529         {
5530           int needed_parms 
5531             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5532           error ("wrong number of template arguments (%d, should be %d)",
5533                  nargs, needed_parms);
5534           return error_mark_node;
5535         }
5536
5537       /* If we aren't able to check the actual arguments now
5538          (because they haven't been expanded yet), we can at least
5539          verify that all of the types used for the non-type
5540          template parameter pack are, in fact, valid for non-type
5541          template parameters.  */
5542       if (arg_idx < nargs 
5543           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5544         {
5545           int j, len = TREE_VEC_LENGTH (packed_types);
5546           for (j = 0; j < len; ++j)
5547             {
5548               tree t = TREE_VEC_ELT (packed_types, j);
5549               if (invalid_nontype_parm_type_p (t, complain))
5550                 return error_mark_node;
5551             }
5552         }
5553     }
5554
5555   /* Convert the remaining arguments, which will be a part of the
5556      parameter pack "parm".  */
5557   for (; arg_idx < nargs; ++arg_idx)
5558     {
5559       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5560       tree actual_parm = TREE_VALUE (parm);
5561
5562       if (packed_types && !PACK_EXPANSION_P (arg))
5563         {
5564           /* When we have a vector of types (corresponding to the
5565              non-type template parameter pack that uses parameter
5566              packs in its type, as mention above), and the
5567              argument is not an expansion (which expands to a
5568              currently unknown number of arguments), clone the
5569              parm and give it the next type in PACKED_TYPES.  */
5570           actual_parm = copy_node (actual_parm);
5571           TREE_TYPE (actual_parm) = 
5572             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5573         }
5574
5575       if (arg != error_mark_node)
5576         arg = convert_template_argument (actual_parm, 
5577                                          arg, new_args, complain, parm_idx,
5578                                          in_decl);
5579       if (arg == error_mark_node)
5580         (*lost)++;
5581       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5582     }
5583
5584   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5585       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5586     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5587   else
5588     {
5589       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5590       TREE_TYPE (argument_pack) 
5591         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5592       TREE_CONSTANT (argument_pack) = 1;
5593     }
5594
5595   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5596   return argument_pack;
5597 }
5598
5599 /* Convert all template arguments to their appropriate types, and
5600    return a vector containing the innermost resulting template
5601    arguments.  If any error occurs, return error_mark_node. Error and
5602    warning messages are issued under control of COMPLAIN.
5603
5604    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5605    for arguments not specified in ARGS.  Otherwise, if
5606    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5607    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5608    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5609    ARGS.  */
5610
5611 static tree
5612 coerce_template_parms (tree parms,
5613                        tree args,
5614                        tree in_decl,
5615                        tsubst_flags_t complain,
5616                        bool require_all_args,
5617                        bool use_default_args)
5618 {
5619   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5620   tree inner_args;
5621   tree new_args;
5622   tree new_inner_args;
5623   int saved_unevaluated_operand;
5624   int saved_inhibit_evaluation_warnings;
5625
5626   /* When used as a boolean value, indicates whether this is a
5627      variadic template parameter list. Since it's an int, we can also
5628      subtract it from nparms to get the number of non-variadic
5629      parameters.  */
5630   int variadic_p = 0;
5631
5632   nparms = TREE_VEC_LENGTH (parms);
5633
5634   /* Determine if there are any parameter packs.  */
5635   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5636     {
5637       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5638       if (template_parameter_pack_p (tparm))
5639         ++variadic_p;
5640     }
5641
5642   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5643   /* If there are 0 or 1 parameter packs, we need to expand any argument
5644      packs so that we can deduce a parameter pack from some non-packed args
5645      followed by an argument pack, as in variadic85.C.  If there are more
5646      than that, we need to leave argument packs intact so the arguments are
5647      assigned to the right parameter packs.  This should only happen when
5648      dealing with a nested class inside a partial specialization of a class
5649      template, as in variadic92.C.  */
5650   if (variadic_p <= 1)
5651     inner_args = expand_template_argument_pack (inner_args);
5652
5653   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5654   if ((nargs > nparms && !variadic_p)
5655       || (nargs < nparms - variadic_p
5656           && require_all_args
5657           && (!use_default_args
5658               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5659                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5660     {
5661       if (complain & tf_error)
5662         {
5663           const char *or_more = "";
5664           if (variadic_p)
5665             {
5666               or_more = " or more";
5667               --nparms;
5668             }
5669
5670           error ("wrong number of template arguments (%d, should be %d%s)",
5671                  nargs, nparms, or_more);
5672
5673           if (in_decl)
5674             error ("provided for %q+D", in_decl);
5675         }
5676
5677       return error_mark_node;
5678     }
5679
5680   /* We need to evaluate the template arguments, even though this
5681      template-id may be nested within a "sizeof".  */
5682   saved_unevaluated_operand = cp_unevaluated_operand;
5683   cp_unevaluated_operand = 0;
5684   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5685   c_inhibit_evaluation_warnings = 0;
5686   new_inner_args = make_tree_vec (nparms);
5687   new_args = add_outermost_template_args (args, new_inner_args);
5688   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5689     {
5690       tree arg;
5691       tree parm;
5692
5693       /* Get the Ith template parameter.  */
5694       parm = TREE_VEC_ELT (parms, parm_idx);
5695  
5696       if (parm == error_mark_node)
5697       {
5698         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5699         continue;
5700       }
5701
5702       /* Calculate the next argument.  */
5703       if (arg_idx < nargs)
5704         arg = TREE_VEC_ELT (inner_args, arg_idx);
5705       else
5706         arg = NULL_TREE;
5707
5708       if (template_parameter_pack_p (TREE_VALUE (parm))
5709           && !(arg && ARGUMENT_PACK_P (arg)))
5710         {
5711           /* All remaining arguments will be placed in the
5712              template parameter pack PARM.  */
5713           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5714                                                 inner_args, arg_idx,
5715                                                 new_args, &lost,
5716                                                 in_decl, complain);
5717
5718           /* Store this argument.  */
5719           if (arg == error_mark_node)
5720             lost++;
5721           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5722
5723           /* We are done with all of the arguments.  */
5724           arg_idx = nargs;
5725           
5726           continue;
5727         }
5728       else if (arg)
5729         {
5730           if (PACK_EXPANSION_P (arg))
5731             {
5732               if (complain & tf_error)
5733                 {
5734                   /* FIXME this restriction was removed by N2555; see
5735                      bug 35722.  */
5736                   /* If ARG is a pack expansion, but PARM is not a
5737                      template parameter pack (if it were, we would have
5738                      handled it above), we're trying to expand into a
5739                      fixed-length argument list.  */
5740                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5741                     sorry ("cannot expand %<%E%> into a fixed-length "
5742                            "argument list", arg);
5743                   else
5744                     sorry ("cannot expand %<%T%> into a fixed-length "
5745                            "argument list", arg);
5746                 }
5747               return error_mark_node;
5748             }
5749         }
5750       else if (require_all_args)
5751         /* There must be a default arg in this case.  */
5752         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5753                                    complain, in_decl);
5754       else
5755         break;
5756
5757       if (arg == error_mark_node)
5758         {
5759           if (complain & tf_error)
5760             error ("template argument %d is invalid", arg_idx + 1);
5761         }
5762       else if (!arg)
5763         /* This only occurs if there was an error in the template
5764            parameter list itself (which we would already have
5765            reported) that we are trying to recover from, e.g., a class
5766            template with a parameter list such as
5767            template<typename..., typename>.  */
5768         return error_mark_node;
5769       else
5770         arg = convert_template_argument (TREE_VALUE (parm),
5771                                          arg, new_args, complain, 
5772                                          parm_idx, in_decl);
5773
5774       if (arg == error_mark_node)
5775         lost++;
5776       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5777     }
5778   cp_unevaluated_operand = saved_unevaluated_operand;
5779   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
5780
5781   if (lost)
5782     return error_mark_node;
5783
5784   return new_inner_args;
5785 }
5786
5787 /* Returns 1 if template args OT and NT are equivalent.  */
5788
5789 static int
5790 template_args_equal (tree ot, tree nt)
5791 {
5792   if (nt == ot)
5793     return 1;
5794
5795   if (TREE_CODE (nt) == TREE_VEC)
5796     /* For member templates */
5797     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5798   else if (PACK_EXPANSION_P (ot))
5799     return PACK_EXPANSION_P (nt) 
5800       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5801                               PACK_EXPANSION_PATTERN (nt));
5802   else if (ARGUMENT_PACK_P (ot))
5803     {
5804       int i, len;
5805       tree opack, npack;
5806
5807       if (!ARGUMENT_PACK_P (nt))
5808         return 0;
5809
5810       opack = ARGUMENT_PACK_ARGS (ot);
5811       npack = ARGUMENT_PACK_ARGS (nt);
5812       len = TREE_VEC_LENGTH (opack);
5813       if (TREE_VEC_LENGTH (npack) != len)
5814         return 0;
5815       for (i = 0; i < len; ++i)
5816         if (!template_args_equal (TREE_VEC_ELT (opack, i),
5817                                   TREE_VEC_ELT (npack, i)))
5818           return 0;
5819       return 1;
5820     }
5821   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
5822     {
5823       /* We get here probably because we are in the middle of substituting
5824          into the pattern of a pack expansion. In that case the
5825          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
5826          interested in. So we want to use the initial pack argument for
5827          the comparison.  */
5828       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
5829       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
5830         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
5831       return template_args_equal (ot, nt);
5832     }
5833   else if (TYPE_P (nt))
5834     return TYPE_P (ot) && same_type_p (ot, nt);
5835   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5836     return 0;
5837   else
5838     return cp_tree_equal (ot, nt);
5839 }
5840
5841 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5842    of template arguments.  Returns 0 otherwise.  */
5843
5844 int
5845 comp_template_args (tree oldargs, tree newargs)
5846 {
5847   int i;
5848
5849   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5850     return 0;
5851
5852   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5853     {
5854       tree nt = TREE_VEC_ELT (newargs, i);
5855       tree ot = TREE_VEC_ELT (oldargs, i);
5856
5857       if (! template_args_equal (ot, nt))
5858         return 0;
5859     }
5860   return 1;
5861 }
5862
5863 static void
5864 add_pending_template (tree d)
5865 {
5866   tree ti = (TYPE_P (d)
5867              ? CLASSTYPE_TEMPLATE_INFO (d)
5868              : DECL_TEMPLATE_INFO (d));
5869   struct pending_template *pt;
5870   int level;
5871
5872   if (TI_PENDING_TEMPLATE_FLAG (ti))
5873     return;
5874
5875   /* We are called both from instantiate_decl, where we've already had a
5876      tinst_level pushed, and instantiate_template, where we haven't.
5877      Compensate.  */
5878   level = !current_tinst_level || current_tinst_level->decl != d;
5879
5880   if (level)
5881     push_tinst_level (d);
5882
5883   pt = GGC_NEW (struct pending_template);
5884   pt->next = NULL;
5885   pt->tinst = current_tinst_level;
5886   if (last_pending_template)
5887     last_pending_template->next = pt;
5888   else
5889     pending_templates = pt;
5890
5891   last_pending_template = pt;
5892
5893   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5894
5895   if (level)
5896     pop_tinst_level ();
5897 }
5898
5899
5900 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5901    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5902    documentation for TEMPLATE_ID_EXPR.  */
5903
5904 tree
5905 lookup_template_function (tree fns, tree arglist)
5906 {
5907   tree type;
5908
5909   if (fns == error_mark_node || arglist == error_mark_node)
5910     return error_mark_node;
5911
5912   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5913   gcc_assert (fns && (is_overloaded_fn (fns)
5914                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5915
5916   if (BASELINK_P (fns))
5917     {
5918       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5919                                          unknown_type_node,
5920                                          BASELINK_FUNCTIONS (fns),
5921                                          arglist);
5922       return fns;
5923     }
5924
5925   type = TREE_TYPE (fns);
5926   if (TREE_CODE (fns) == OVERLOAD || !type)
5927     type = unknown_type_node;
5928
5929   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5930 }
5931
5932 /* Within the scope of a template class S<T>, the name S gets bound
5933    (in build_self_reference) to a TYPE_DECL for the class, not a
5934    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5935    or one of its enclosing classes, and that type is a template,
5936    return the associated TEMPLATE_DECL.  Otherwise, the original
5937    DECL is returned.  */
5938
5939 tree
5940 maybe_get_template_decl_from_type_decl (tree decl)
5941 {
5942   return (decl != NULL_TREE
5943           && TREE_CODE (decl) == TYPE_DECL
5944           && DECL_ARTIFICIAL (decl)
5945           && CLASS_TYPE_P (TREE_TYPE (decl))
5946           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5947     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5948 }
5949
5950 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5951    parameters, find the desired type.
5952
5953    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5954
5955    IN_DECL, if non-NULL, is the template declaration we are trying to
5956    instantiate.
5957
5958    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5959    the class we are looking up.
5960
5961    Issue error and warning messages under control of COMPLAIN.
5962
5963    If the template class is really a local class in a template
5964    function, then the FUNCTION_CONTEXT is the function in which it is
5965    being instantiated.
5966
5967    ??? Note that this function is currently called *twice* for each
5968    template-id: the first time from the parser, while creating the
5969    incomplete type (finish_template_type), and the second type during the
5970    real instantiation (instantiate_template_class). This is surely something
5971    that we want to avoid. It also causes some problems with argument
5972    coercion (see convert_nontype_argument for more information on this).  */
5973
5974 tree
5975 lookup_template_class (tree d1,
5976                        tree arglist,
5977                        tree in_decl,
5978                        tree context,
5979                        int entering_scope,
5980                        tsubst_flags_t complain)
5981 {
5982   tree templ = NULL_TREE, parmlist;
5983   tree t;
5984   spec_entry **slot;
5985   spec_entry *entry;
5986   spec_entry elt;
5987   hashval_t hash;
5988
5989   timevar_push (TV_NAME_LOOKUP);
5990
5991   if (TREE_CODE (d1) == IDENTIFIER_NODE)
5992     {
5993       tree value = innermost_non_namespace_value (d1);
5994       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
5995         templ = value;
5996       else
5997         {
5998           if (context)
5999             push_decl_namespace (context);
6000           templ = lookup_name (d1);
6001           templ = maybe_get_template_decl_from_type_decl (templ);
6002           if (context)
6003             pop_decl_namespace ();
6004         }
6005       if (templ)
6006         context = DECL_CONTEXT (templ);
6007     }
6008   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6009     {
6010       tree type = TREE_TYPE (d1);
6011
6012       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6013          an implicit typename for the second A.  Deal with it.  */
6014       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6015         type = TREE_TYPE (type);
6016
6017       if (CLASSTYPE_TEMPLATE_INFO (type))
6018         {
6019           templ = CLASSTYPE_TI_TEMPLATE (type);
6020           d1 = DECL_NAME (templ);
6021         }
6022     }
6023   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6024            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6025     {
6026       templ = TYPE_TI_TEMPLATE (d1);
6027       d1 = DECL_NAME (templ);
6028     }
6029   else if (TREE_CODE (d1) == TEMPLATE_DECL
6030            && DECL_TEMPLATE_RESULT (d1)
6031            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6032     {
6033       templ = d1;
6034       d1 = DECL_NAME (templ);
6035       context = DECL_CONTEXT (templ);
6036     }
6037
6038   /* Issue an error message if we didn't find a template.  */
6039   if (! templ)
6040     {
6041       if (complain & tf_error)
6042         error ("%qT is not a template", d1);
6043       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6044     }
6045
6046   if (TREE_CODE (templ) != TEMPLATE_DECL
6047          /* Make sure it's a user visible template, if it was named by
6048             the user.  */
6049       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6050           && !PRIMARY_TEMPLATE_P (templ)))
6051     {
6052       if (complain & tf_error)
6053         {
6054           error ("non-template type %qT used as a template", d1);
6055           if (in_decl)
6056             error ("for template declaration %q+D", in_decl);
6057         }
6058       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6059     }
6060
6061   complain &= ~tf_user;
6062
6063   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6064     {
6065       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6066          template arguments */
6067
6068       tree parm;
6069       tree arglist2;
6070       tree outer;
6071
6072       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6073
6074       /* Consider an example where a template template parameter declared as
6075
6076            template <class T, class U = std::allocator<T> > class TT
6077
6078          The template parameter level of T and U are one level larger than
6079          of TT.  To proper process the default argument of U, say when an
6080          instantiation `TT<int>' is seen, we need to build the full
6081          arguments containing {int} as the innermost level.  Outer levels,
6082          available when not appearing as default template argument, can be
6083          obtained from the arguments of the enclosing template.
6084
6085          Suppose that TT is later substituted with std::vector.  The above
6086          instantiation is `TT<int, std::allocator<T> >' with TT at
6087          level 1, and T at level 2, while the template arguments at level 1
6088          becomes {std::vector} and the inner level 2 is {int}.  */
6089
6090       outer = DECL_CONTEXT (templ);
6091       if (outer)
6092         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6093       else if (current_template_parms)
6094         /* This is an argument of the current template, so we haven't set
6095            DECL_CONTEXT yet.  */
6096         outer = current_template_args ();
6097
6098       if (outer)
6099         arglist = add_to_template_args (outer, arglist);
6100
6101       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6102                                         complain,
6103                                         /*require_all_args=*/true,
6104                                         /*use_default_args=*/true);
6105       if (arglist2 == error_mark_node
6106           || (!uses_template_parms (arglist2)
6107               && check_instantiated_args (templ, arglist2, complain)))
6108         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6109
6110       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6111       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6112     }
6113   else
6114     {
6115       tree template_type = TREE_TYPE (templ);
6116       tree gen_tmpl;
6117       tree type_decl;
6118       tree found = NULL_TREE;
6119       int arg_depth;
6120       int parm_depth;
6121       int is_partial_instantiation;
6122
6123       gen_tmpl = most_general_template (templ);
6124       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6125       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6126       arg_depth = TMPL_ARGS_DEPTH (arglist);
6127
6128       if (arg_depth == 1 && parm_depth > 1)
6129         {
6130           /* We've been given an incomplete set of template arguments.
6131              For example, given:
6132
6133                template <class T> struct S1 {
6134                  template <class U> struct S2 {};
6135                  template <class U> struct S2<U*> {};
6136                 };
6137
6138              we will be called with an ARGLIST of `U*', but the
6139              TEMPLATE will be `template <class T> template
6140              <class U> struct S1<T>::S2'.  We must fill in the missing
6141              arguments.  */
6142           arglist
6143             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6144                                            arglist);
6145           arg_depth = TMPL_ARGS_DEPTH (arglist);
6146         }
6147
6148       /* Now we should have enough arguments.  */
6149       gcc_assert (parm_depth == arg_depth);
6150
6151       /* From here on, we're only interested in the most general
6152          template.  */
6153
6154       /* Calculate the BOUND_ARGS.  These will be the args that are
6155          actually tsubst'd into the definition to create the
6156          instantiation.  */
6157       if (parm_depth > 1)
6158         {
6159           /* We have multiple levels of arguments to coerce, at once.  */
6160           int i;
6161           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6162
6163           tree bound_args = make_tree_vec (parm_depth);
6164
6165           for (i = saved_depth,
6166                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6167                i > 0 && t != NULL_TREE;
6168                --i, t = TREE_CHAIN (t))
6169             {
6170               tree a = coerce_template_parms (TREE_VALUE (t),
6171                                               arglist, gen_tmpl,
6172                                               complain,
6173                                               /*require_all_args=*/true,
6174                                               /*use_default_args=*/true);
6175
6176               /* Don't process further if one of the levels fails.  */
6177               if (a == error_mark_node)
6178                 {
6179                   /* Restore the ARGLIST to its full size.  */
6180                   TREE_VEC_LENGTH (arglist) = saved_depth;
6181                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6182                 }
6183
6184               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6185
6186               /* We temporarily reduce the length of the ARGLIST so
6187                  that coerce_template_parms will see only the arguments
6188                  corresponding to the template parameters it is
6189                  examining.  */
6190               TREE_VEC_LENGTH (arglist)--;
6191             }
6192
6193           /* Restore the ARGLIST to its full size.  */
6194           TREE_VEC_LENGTH (arglist) = saved_depth;
6195
6196           arglist = bound_args;
6197         }
6198       else
6199         arglist
6200           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6201                                    INNERMOST_TEMPLATE_ARGS (arglist),
6202                                    gen_tmpl,
6203                                    complain,
6204                                    /*require_all_args=*/true,
6205                                    /*use_default_args=*/true);
6206
6207       if (arglist == error_mark_node)
6208         /* We were unable to bind the arguments.  */
6209         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6210
6211       /* In the scope of a template class, explicit references to the
6212          template class refer to the type of the template, not any
6213          instantiation of it.  For example, in:
6214
6215            template <class T> class C { void f(C<T>); }
6216
6217          the `C<T>' is just the same as `C'.  Outside of the
6218          class, however, such a reference is an instantiation.  */
6219       if ((entering_scope
6220            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6221            || currently_open_class (template_type))
6222           /* comp_template_args is expensive, check it last.  */
6223           && comp_template_args (TYPE_TI_ARGS (template_type),
6224                                  arglist))
6225         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6226
6227       /* If we already have this specialization, return it.  */
6228       elt.tmpl = gen_tmpl;
6229       elt.args = arglist;
6230       hash = hash_specialization (&elt);
6231       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6232                                                   &elt, hash);
6233
6234       if (entry)
6235         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6236
6237       /* This type is a "partial instantiation" if any of the template
6238          arguments still involve template parameters.  Note that we set
6239          IS_PARTIAL_INSTANTIATION for partial specializations as
6240          well.  */
6241       is_partial_instantiation = uses_template_parms (arglist);
6242
6243       /* If the deduced arguments are invalid, then the binding
6244          failed.  */
6245       if (!is_partial_instantiation
6246           && check_instantiated_args (gen_tmpl,
6247                                       INNERMOST_TEMPLATE_ARGS (arglist),
6248                                       complain))
6249         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6250
6251       if (!is_partial_instantiation
6252           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6253           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6254           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6255         {
6256           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6257                                       DECL_NAME (gen_tmpl),
6258                                       /*tag_scope=*/ts_global);
6259           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6260         }
6261
6262       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6263                         complain, in_decl);
6264       if (!context)
6265         context = global_namespace;
6266
6267       /* Create the type.  */
6268       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6269         {
6270           if (!is_partial_instantiation)
6271             {
6272               set_current_access_from_decl (TYPE_NAME (template_type));
6273               t = start_enum (TYPE_IDENTIFIER (template_type),
6274                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6275                                       arglist, complain, in_decl),
6276                               SCOPED_ENUM_P (template_type));
6277             }
6278           else
6279             {
6280               /* We don't want to call start_enum for this type, since
6281                  the values for the enumeration constants may involve
6282                  template parameters.  And, no one should be interested
6283                  in the enumeration constants for such a type.  */
6284               t = cxx_make_type (ENUMERAL_TYPE);
6285               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6286             }
6287         }
6288       else
6289         {
6290           t = make_class_type (TREE_CODE (template_type));
6291           CLASSTYPE_DECLARED_CLASS (t)
6292             = CLASSTYPE_DECLARED_CLASS (template_type);
6293           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6294           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6295
6296           /* A local class.  Make sure the decl gets registered properly.  */
6297           if (context == current_function_decl)
6298             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6299
6300           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6301             /* This instantiation is another name for the primary
6302                template type. Set the TYPE_CANONICAL field
6303                appropriately. */
6304             TYPE_CANONICAL (t) = template_type;
6305           else if (any_template_arguments_need_structural_equality_p (arglist))
6306             /* Some of the template arguments require structural
6307                equality testing, so this template class requires
6308                structural equality testing. */
6309             SET_TYPE_STRUCTURAL_EQUALITY (t);
6310         }
6311
6312       /* If we called start_enum or pushtag above, this information
6313          will already be set up.  */
6314       if (!TYPE_NAME (t))
6315         {
6316           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6317
6318           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6319           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6320           TYPE_STUB_DECL (t) = type_decl;
6321           DECL_SOURCE_LOCATION (type_decl)
6322             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6323         }
6324       else
6325         type_decl = TYPE_NAME (t);
6326
6327       TREE_PRIVATE (type_decl)
6328         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6329       TREE_PROTECTED (type_decl)
6330         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6331       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6332         {
6333           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6334           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6335         }
6336
6337       /* Set up the template information.  We have to figure out which
6338          template is the immediate parent if this is a full
6339          instantiation.  */
6340       if (parm_depth == 1 || is_partial_instantiation
6341           || !PRIMARY_TEMPLATE_P (gen_tmpl))
6342         /* This case is easy; there are no member templates involved.  */
6343         found = gen_tmpl;
6344       else
6345         {
6346           /* This is a full instantiation of a member template.  Find
6347              the partial instantiation of which this is an instance.  */
6348
6349           /* Temporarily reduce by one the number of levels in the ARGLIST
6350              so as to avoid comparing the last set of arguments.  */
6351           TREE_VEC_LENGTH (arglist)--;
6352           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6353           TREE_VEC_LENGTH (arglist)++;
6354           found = CLASSTYPE_TI_TEMPLATE (found);
6355         }
6356
6357       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
6358
6359       elt.spec = t;
6360       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6361                                                        &elt, hash, INSERT);
6362       *slot = GGC_NEW (spec_entry);
6363       **slot = elt;
6364
6365       /* Note this use of the partial instantiation so we can check it
6366          later in maybe_process_partial_specialization.  */
6367       DECL_TEMPLATE_INSTANTIATIONS (templ)
6368         = tree_cons (arglist, t,
6369                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6370
6371       if (TREE_CODE (t) == ENUMERAL_TYPE
6372           && !is_partial_instantiation)
6373         /* Now that the type has been registered on the instantiations
6374            list, we set up the enumerators.  Because the enumeration
6375            constants may involve the enumeration type itself, we make
6376            sure to register the type first, and then create the
6377            constants.  That way, doing tsubst_expr for the enumeration
6378            constants won't result in recursive calls here; we'll find
6379            the instantiation and exit above.  */
6380         tsubst_enum (template_type, t, arglist);
6381
6382       if (is_partial_instantiation)
6383         /* If the type makes use of template parameters, the
6384            code that generates debugging information will crash.  */
6385         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6386
6387       /* Possibly limit visibility based on template args.  */
6388       TREE_PUBLIC (type_decl) = 1;
6389       determine_visibility (type_decl);
6390
6391       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6392     }
6393   timevar_pop (TV_NAME_LOOKUP);
6394 }
6395 \f
6396 struct pair_fn_data
6397 {
6398   tree_fn_t fn;
6399   void *data;
6400   /* True when we should also visit template parameters that occur in
6401      non-deduced contexts.  */
6402   bool include_nondeduced_p;
6403   struct pointer_set_t *visited;
6404 };
6405
6406 /* Called from for_each_template_parm via walk_tree.  */
6407
6408 static tree
6409 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6410 {
6411   tree t = *tp;
6412   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6413   tree_fn_t fn = pfd->fn;
6414   void *data = pfd->data;
6415
6416   if (TYPE_P (t)
6417       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6418       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6419                                  pfd->include_nondeduced_p))
6420     return error_mark_node;
6421
6422   switch (TREE_CODE (t))
6423     {
6424     case RECORD_TYPE:
6425       if (TYPE_PTRMEMFUNC_P (t))
6426         break;
6427       /* Fall through.  */
6428
6429     case UNION_TYPE:
6430     case ENUMERAL_TYPE:
6431       if (!TYPE_TEMPLATE_INFO (t))
6432         *walk_subtrees = 0;
6433       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
6434                                        fn, data, pfd->visited, 
6435                                        pfd->include_nondeduced_p))
6436         return error_mark_node;
6437       break;
6438
6439     case INTEGER_TYPE:
6440       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6441                                   fn, data, pfd->visited, 
6442                                   pfd->include_nondeduced_p)
6443           || for_each_template_parm (TYPE_MAX_VALUE (t),
6444                                      fn, data, pfd->visited,
6445                                      pfd->include_nondeduced_p))
6446         return error_mark_node;
6447       break;
6448
6449     case METHOD_TYPE:
6450       /* Since we're not going to walk subtrees, we have to do this
6451          explicitly here.  */
6452       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6453                                   pfd->visited, pfd->include_nondeduced_p))
6454         return error_mark_node;
6455       /* Fall through.  */
6456
6457     case FUNCTION_TYPE:
6458       /* Check the return type.  */
6459       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6460                                   pfd->include_nondeduced_p))
6461         return error_mark_node;
6462
6463       /* Check the parameter types.  Since default arguments are not
6464          instantiated until they are needed, the TYPE_ARG_TYPES may
6465          contain expressions that involve template parameters.  But,
6466          no-one should be looking at them yet.  And, once they're
6467          instantiated, they don't contain template parameters, so
6468          there's no point in looking at them then, either.  */
6469       {
6470         tree parm;
6471
6472         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6473           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6474                                       pfd->visited, pfd->include_nondeduced_p))
6475             return error_mark_node;
6476
6477         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6478            want walk_tree walking into them itself.  */
6479         *walk_subtrees = 0;
6480       }
6481       break;
6482
6483     case TYPEOF_TYPE:
6484       if (pfd->include_nondeduced_p
6485           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6486                                      pfd->visited, 
6487                                      pfd->include_nondeduced_p))
6488         return error_mark_node;
6489       break;
6490
6491     case FUNCTION_DECL:
6492     case VAR_DECL:
6493       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6494           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6495                                      pfd->visited, pfd->include_nondeduced_p))
6496         return error_mark_node;
6497       /* Fall through.  */
6498
6499     case PARM_DECL:
6500     case CONST_DECL:
6501       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6502           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6503                                      pfd->visited, pfd->include_nondeduced_p))
6504         return error_mark_node;
6505       if (DECL_CONTEXT (t)
6506           && pfd->include_nondeduced_p
6507           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6508                                      pfd->visited, pfd->include_nondeduced_p))
6509         return error_mark_node;
6510       break;
6511
6512     case BOUND_TEMPLATE_TEMPLATE_PARM:
6513       /* Record template parameters such as `T' inside `TT<T>'.  */
6514       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6515                                   pfd->include_nondeduced_p))
6516         return error_mark_node;
6517       /* Fall through.  */
6518
6519     case TEMPLATE_TEMPLATE_PARM:
6520     case TEMPLATE_TYPE_PARM:
6521     case TEMPLATE_PARM_INDEX:
6522       if (fn && (*fn)(t, data))
6523         return error_mark_node;
6524       else if (!fn)
6525         return error_mark_node;
6526       break;
6527
6528     case TEMPLATE_DECL:
6529       /* A template template parameter is encountered.  */
6530       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6531           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6532                                      pfd->include_nondeduced_p))
6533         return error_mark_node;
6534
6535       /* Already substituted template template parameter */
6536       *walk_subtrees = 0;
6537       break;
6538
6539     case TYPENAME_TYPE:
6540       if (!fn
6541           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6542                                      data, pfd->visited, 
6543                                      pfd->include_nondeduced_p))
6544         return error_mark_node;
6545       break;
6546
6547     case CONSTRUCTOR:
6548       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6549           && pfd->include_nondeduced_p
6550           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6551                                      (TREE_TYPE (t)), fn, data,
6552                                      pfd->visited, pfd->include_nondeduced_p))
6553         return error_mark_node;
6554       break;
6555
6556     case INDIRECT_REF:
6557     case COMPONENT_REF:
6558       /* If there's no type, then this thing must be some expression
6559          involving template parameters.  */
6560       if (!fn && !TREE_TYPE (t))
6561         return error_mark_node;
6562       break;
6563
6564     case MODOP_EXPR:
6565     case CAST_EXPR:
6566     case REINTERPRET_CAST_EXPR:
6567     case CONST_CAST_EXPR:
6568     case STATIC_CAST_EXPR:
6569     case DYNAMIC_CAST_EXPR:
6570     case ARROW_EXPR:
6571     case DOTSTAR_EXPR:
6572     case TYPEID_EXPR:
6573     case PSEUDO_DTOR_EXPR:
6574       if (!fn)
6575         return error_mark_node;
6576       break;
6577
6578     default:
6579       break;
6580     }
6581
6582   /* We didn't find any template parameters we liked.  */
6583   return NULL_TREE;
6584 }
6585
6586 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6587    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6588    call FN with the parameter and the DATA.
6589    If FN returns nonzero, the iteration is terminated, and
6590    for_each_template_parm returns 1.  Otherwise, the iteration
6591    continues.  If FN never returns a nonzero value, the value
6592    returned by for_each_template_parm is 0.  If FN is NULL, it is
6593    considered to be the function which always returns 1.
6594
6595    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6596    parameters that occur in non-deduced contexts.  When false, only
6597    visits those template parameters that can be deduced.  */
6598
6599 static int
6600 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6601                         struct pointer_set_t *visited,
6602                         bool include_nondeduced_p)
6603 {
6604   struct pair_fn_data pfd;
6605   int result;
6606
6607   /* Set up.  */
6608   pfd.fn = fn;
6609   pfd.data = data;
6610   pfd.include_nondeduced_p = include_nondeduced_p;
6611
6612   /* Walk the tree.  (Conceptually, we would like to walk without
6613      duplicates, but for_each_template_parm_r recursively calls
6614      for_each_template_parm, so we would need to reorganize a fair
6615      bit to use walk_tree_without_duplicates, so we keep our own
6616      visited list.)  */
6617   if (visited)
6618     pfd.visited = visited;
6619   else
6620     pfd.visited = pointer_set_create ();
6621   result = cp_walk_tree (&t,
6622                          for_each_template_parm_r,
6623                          &pfd,
6624                          pfd.visited) != NULL_TREE;
6625
6626   /* Clean up.  */
6627   if (!visited)
6628     {
6629       pointer_set_destroy (pfd.visited);
6630       pfd.visited = 0;
6631     }
6632
6633   return result;
6634 }
6635
6636 /* Returns true if T depends on any template parameter.  */
6637
6638 int
6639 uses_template_parms (tree t)
6640 {
6641   bool dependent_p;
6642   int saved_processing_template_decl;
6643
6644   saved_processing_template_decl = processing_template_decl;
6645   if (!saved_processing_template_decl)
6646     processing_template_decl = 1;
6647   if (TYPE_P (t))
6648     dependent_p = dependent_type_p (t);
6649   else if (TREE_CODE (t) == TREE_VEC)
6650     dependent_p = any_dependent_template_arguments_p (t);
6651   else if (TREE_CODE (t) == TREE_LIST)
6652     dependent_p = (uses_template_parms (TREE_VALUE (t))
6653                    || uses_template_parms (TREE_CHAIN (t)));
6654   else if (TREE_CODE (t) == TYPE_DECL)
6655     dependent_p = dependent_type_p (TREE_TYPE (t));
6656   else if (DECL_P (t)
6657            || EXPR_P (t)
6658            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6659            || TREE_CODE (t) == OVERLOAD
6660            || TREE_CODE (t) == BASELINK
6661            || TREE_CODE (t) == IDENTIFIER_NODE
6662            || TREE_CODE (t) == TRAIT_EXPR
6663            || TREE_CODE (t) == CONSTRUCTOR
6664            || CONSTANT_CLASS_P (t))
6665     dependent_p = (type_dependent_expression_p (t)
6666                    || value_dependent_expression_p (t));
6667   else
6668     {
6669       gcc_assert (t == error_mark_node);
6670       dependent_p = false;
6671     }
6672
6673   processing_template_decl = saved_processing_template_decl;
6674
6675   return dependent_p;
6676 }
6677
6678 /* Returns true if T depends on any template parameter with level LEVEL.  */
6679
6680 int
6681 uses_template_parms_level (tree t, int level)
6682 {
6683   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6684                                  /*include_nondeduced_p=*/true);
6685 }
6686
6687 static int tinst_depth;
6688 extern int max_tinst_depth;
6689 #ifdef GATHER_STATISTICS
6690 int depth_reached;
6691 #endif
6692 static int tinst_level_tick;
6693 static int last_template_error_tick;
6694
6695 /* We're starting to instantiate D; record the template instantiation context
6696    for diagnostics and to restore it later.  */
6697
6698 static int
6699 push_tinst_level (tree d)
6700 {
6701   struct tinst_level *new_level;
6702
6703   if (tinst_depth >= max_tinst_depth)
6704     {
6705       /* If the instantiation in question still has unbound template parms,
6706          we don't really care if we can't instantiate it, so just return.
6707          This happens with base instantiation for implicit `typename'.  */
6708       if (uses_template_parms (d))
6709         return 0;
6710
6711       last_template_error_tick = tinst_level_tick;
6712       error ("template instantiation depth exceeds maximum of %d (use "
6713              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6714              max_tinst_depth, d);
6715
6716       print_instantiation_context ();
6717
6718       return 0;
6719     }
6720
6721   new_level = GGC_NEW (struct tinst_level);
6722   new_level->decl = d;
6723   new_level->locus = input_location;
6724   new_level->in_system_header_p = in_system_header;
6725   new_level->next = current_tinst_level;
6726   current_tinst_level = new_level;
6727
6728   ++tinst_depth;
6729 #ifdef GATHER_STATISTICS
6730   if (tinst_depth > depth_reached)
6731     depth_reached = tinst_depth;
6732 #endif
6733
6734   ++tinst_level_tick;
6735   return 1;
6736 }
6737
6738 /* We're done instantiating this template; return to the instantiation
6739    context.  */
6740
6741 static void
6742 pop_tinst_level (void)
6743 {
6744   /* Restore the filename and line number stashed away when we started
6745      this instantiation.  */
6746   input_location = current_tinst_level->locus;
6747   current_tinst_level = current_tinst_level->next;
6748   --tinst_depth;
6749   ++tinst_level_tick;
6750 }
6751
6752 /* We're instantiating a deferred template; restore the template
6753    instantiation context in which the instantiation was requested, which
6754    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6755
6756 static tree
6757 reopen_tinst_level (struct tinst_level *level)
6758 {
6759   struct tinst_level *t;
6760
6761   tinst_depth = 0;
6762   for (t = level; t; t = t->next)
6763     ++tinst_depth;
6764
6765   current_tinst_level = level;
6766   pop_tinst_level ();
6767   return level->decl;
6768 }
6769
6770 /* Returns the TINST_LEVEL which gives the original instantiation
6771    context.  */
6772
6773 struct tinst_level *
6774 outermost_tinst_level (void)
6775 {
6776   struct tinst_level *level = current_tinst_level;
6777   if (level)
6778     while (level->next)
6779       level = level->next;
6780   return level;
6781 }
6782
6783 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
6784
6785 bool
6786 parameter_of_template_p (tree parm, tree templ)
6787 {
6788   tree parms;
6789   int i;
6790
6791   if (!parm || !templ)
6792     return false;
6793
6794   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
6795   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6796
6797   parms = DECL_TEMPLATE_PARMS (templ);
6798   parms = INNERMOST_TEMPLATE_PARMS (parms);
6799
6800   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
6801     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
6802       return true;
6803
6804   return false;
6805 }
6806
6807 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6808    vector of template arguments, as for tsubst.
6809
6810    Returns an appropriate tsubst'd friend declaration.  */
6811
6812 static tree
6813 tsubst_friend_function (tree decl, tree args)
6814 {
6815   tree new_friend;
6816
6817   if (TREE_CODE (decl) == FUNCTION_DECL
6818       && DECL_TEMPLATE_INSTANTIATION (decl)
6819       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6820     /* This was a friend declared with an explicit template
6821        argument list, e.g.:
6822
6823        friend void f<>(T);
6824
6825        to indicate that f was a template instantiation, not a new
6826        function declaration.  Now, we have to figure out what
6827        instantiation of what template.  */
6828     {
6829       tree template_id, arglist, fns;
6830       tree new_args;
6831       tree tmpl;
6832       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6833
6834       /* Friend functions are looked up in the containing namespace scope.
6835          We must enter that scope, to avoid finding member functions of the
6836          current class with same name.  */
6837       push_nested_namespace (ns);
6838       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6839                          tf_warning_or_error, NULL_TREE,
6840                          /*integral_constant_expression_p=*/false);
6841       pop_nested_namespace (ns);
6842       arglist = tsubst (DECL_TI_ARGS (decl), args,
6843                         tf_warning_or_error, NULL_TREE);
6844       template_id = lookup_template_function (fns, arglist);
6845
6846       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6847       tmpl = determine_specialization (template_id, new_friend,
6848                                        &new_args,
6849                                        /*need_member_template=*/0,
6850                                        TREE_VEC_LENGTH (args),
6851                                        tsk_none);
6852       return instantiate_template (tmpl, new_args, tf_error);
6853     }
6854
6855   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6856
6857   /* The NEW_FRIEND will look like an instantiation, to the
6858      compiler, but is not an instantiation from the point of view of
6859      the language.  For example, we might have had:
6860
6861      template <class T> struct S {
6862        template <class U> friend void f(T, U);
6863      };
6864
6865      Then, in S<int>, template <class U> void f(int, U) is not an
6866      instantiation of anything.  */
6867   if (new_friend == error_mark_node)
6868     return error_mark_node;
6869
6870   DECL_USE_TEMPLATE (new_friend) = 0;
6871   if (TREE_CODE (decl) == TEMPLATE_DECL)
6872     {
6873       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6874       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6875         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6876     }
6877
6878   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6879      is not a template instantiation and should not be mangled like
6880      one.  Therefore, we forget the mangling here; we'll recompute it
6881      later if we need it.  */
6882   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6883     {
6884       SET_DECL_RTL (new_friend, NULL_RTX);
6885       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6886     }
6887
6888   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6889     {
6890       tree old_decl;
6891       tree new_friend_template_info;
6892       tree new_friend_result_template_info;
6893       tree ns;
6894       int  new_friend_is_defn;
6895
6896       /* We must save some information from NEW_FRIEND before calling
6897          duplicate decls since that function will free NEW_FRIEND if
6898          possible.  */
6899       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6900       new_friend_is_defn =
6901             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6902                            (template_for_substitution (new_friend)))
6903              != NULL_TREE);
6904       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6905         {
6906           /* This declaration is a `primary' template.  */
6907           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6908
6909           new_friend_result_template_info
6910             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6911         }
6912       else
6913         new_friend_result_template_info = NULL_TREE;
6914
6915       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6916       if (new_friend_is_defn)
6917         DECL_INITIAL (new_friend) = error_mark_node;
6918
6919       /* Inside pushdecl_namespace_level, we will push into the
6920          current namespace. However, the friend function should go
6921          into the namespace of the template.  */
6922       ns = decl_namespace_context (new_friend);
6923       push_nested_namespace (ns);
6924       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6925       pop_nested_namespace (ns);
6926
6927       if (old_decl == error_mark_node)
6928         return error_mark_node;
6929
6930       if (old_decl != new_friend)
6931         {
6932           /* This new friend declaration matched an existing
6933              declaration.  For example, given:
6934
6935                template <class T> void f(T);
6936                template <class U> class C {
6937                  template <class T> friend void f(T) {}
6938                };
6939
6940              the friend declaration actually provides the definition
6941              of `f', once C has been instantiated for some type.  So,
6942              old_decl will be the out-of-class template declaration,
6943              while new_friend is the in-class definition.
6944
6945              But, if `f' was called before this point, the
6946              instantiation of `f' will have DECL_TI_ARGS corresponding
6947              to `T' but not to `U', references to which might appear
6948              in the definition of `f'.  Previously, the most general
6949              template for an instantiation of `f' was the out-of-class
6950              version; now it is the in-class version.  Therefore, we
6951              run through all specialization of `f', adding to their
6952              DECL_TI_ARGS appropriately.  In particular, they need a
6953              new set of outer arguments, corresponding to the
6954              arguments for this class instantiation.
6955
6956              The same situation can arise with something like this:
6957
6958                friend void f(int);
6959                template <class T> class C {
6960                  friend void f(T) {}
6961                };
6962
6963              when `C<int>' is instantiated.  Now, `f(int)' is defined
6964              in the class.  */
6965
6966           if (!new_friend_is_defn)
6967             /* On the other hand, if the in-class declaration does
6968                *not* provide a definition, then we don't want to alter
6969                existing definitions.  We can just leave everything
6970                alone.  */
6971             ;
6972           else
6973             {
6974               tree new_template = TI_TEMPLATE (new_friend_template_info);
6975               tree new_args = TI_ARGS (new_friend_template_info);
6976
6977               /* Overwrite whatever template info was there before, if
6978                  any, with the new template information pertaining to
6979                  the declaration.  */
6980               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
6981
6982               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
6983                 /* We should have called reregister_specialization in
6984                    duplicate_decls.  */
6985                 gcc_assert (retrieve_specialization (new_template,
6986                                                      new_args, 0)
6987                             == old_decl);
6988               else
6989                 {
6990                   tree t;
6991
6992                   /* Indicate that the old function template is a partial
6993                      instantiation.  */
6994                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
6995                     = new_friend_result_template_info;
6996
6997                   gcc_assert (new_template
6998                               == most_general_template (new_template));
6999                   gcc_assert (new_template != old_decl);
7000
7001                   /* Reassign any specializations already in the hash table
7002                      to the new more general template, and add the
7003                      additional template args.  */
7004                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7005                        t != NULL_TREE;
7006                        t = TREE_CHAIN (t))
7007                     {
7008                       tree spec = TREE_VALUE (t);
7009                       spec_entry elt;
7010
7011                       elt.tmpl = old_decl;
7012                       elt.args = DECL_TI_ARGS (spec);
7013                       elt.spec = NULL_TREE;
7014
7015                       htab_remove_elt (decl_specializations, &elt);
7016
7017                       DECL_TI_ARGS (spec)
7018                         = add_outermost_template_args (new_args,
7019                                                        DECL_TI_ARGS (spec));
7020
7021                       register_specialization
7022                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7023
7024                     }
7025                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7026                 }
7027             }
7028
7029           /* The information from NEW_FRIEND has been merged into OLD_DECL
7030              by duplicate_decls.  */
7031           new_friend = old_decl;
7032         }
7033     }
7034   else
7035     {
7036       tree context = DECL_CONTEXT (new_friend);
7037       bool dependent_p;
7038
7039       /* In the code
7040            template <class T> class C {
7041              template <class U> friend void C1<U>::f (); // case 1
7042              friend void C2<T>::f ();                    // case 2
7043            };
7044          we only need to make sure CONTEXT is a complete type for
7045          case 2.  To distinguish between the two cases, we note that
7046          CONTEXT of case 1 remains dependent type after tsubst while
7047          this isn't true for case 2.  */
7048       ++processing_template_decl;
7049       dependent_p = dependent_type_p (context);
7050       --processing_template_decl;
7051
7052       if (!dependent_p
7053           && !complete_type_or_else (context, NULL_TREE))
7054         return error_mark_node;
7055
7056       if (COMPLETE_TYPE_P (context))
7057         {
7058           /* Check to see that the declaration is really present, and,
7059              possibly obtain an improved declaration.  */
7060           tree fn = check_classfn (context,
7061                                    new_friend, NULL_TREE);
7062
7063           if (fn)
7064             new_friend = fn;
7065         }
7066     }
7067
7068   return new_friend;
7069 }
7070
7071 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7072    template arguments, as for tsubst.
7073
7074    Returns an appropriate tsubst'd friend type or error_mark_node on
7075    failure.  */
7076
7077 static tree
7078 tsubst_friend_class (tree friend_tmpl, tree args)
7079 {
7080   tree friend_type;
7081   tree tmpl;
7082   tree context;
7083
7084   context = DECL_CONTEXT (friend_tmpl);
7085
7086   if (context)
7087     {
7088       if (TREE_CODE (context) == NAMESPACE_DECL)
7089         push_nested_namespace (context);
7090       else
7091         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7092     }
7093
7094   /* Look for a class template declaration.  We look for hidden names
7095      because two friend declarations of the same template are the
7096      same.  For example, in:
7097
7098        struct A { 
7099          template <typename> friend class F;
7100        };
7101        template <typename> struct B { 
7102          template <typename> friend class F;
7103        };
7104
7105      both F templates are the same.  */
7106   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7107                            /*block_p=*/true, 0, 
7108                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7109
7110   /* But, if we don't find one, it might be because we're in a
7111      situation like this:
7112
7113        template <class T>
7114        struct S {
7115          template <class U>
7116          friend struct S;
7117        };
7118
7119      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7120      for `S<int>', not the TEMPLATE_DECL.  */
7121   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7122     {
7123       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7124       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7125     }
7126
7127   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7128     {
7129       /* The friend template has already been declared.  Just
7130          check to see that the declarations match, and install any new
7131          default parameters.  We must tsubst the default parameters,
7132          of course.  We only need the innermost template parameters
7133          because that is all that redeclare_class_template will look
7134          at.  */
7135       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7136           > TMPL_ARGS_DEPTH (args))
7137         {
7138           tree parms;
7139           location_t saved_input_location;
7140           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7141                                          args, tf_warning_or_error);
7142
7143           saved_input_location = input_location;
7144           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7145           redeclare_class_template (TREE_TYPE (tmpl), parms);
7146           input_location = saved_input_location;
7147           
7148         }
7149
7150       friend_type = TREE_TYPE (tmpl);
7151     }
7152   else
7153     {
7154       /* The friend template has not already been declared.  In this
7155          case, the instantiation of the template class will cause the
7156          injection of this template into the global scope.  */
7157       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7158       if (tmpl == error_mark_node)
7159         return error_mark_node;
7160
7161       /* The new TMPL is not an instantiation of anything, so we
7162          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7163          the new type because that is supposed to be the corresponding
7164          template decl, i.e., TMPL.  */
7165       DECL_USE_TEMPLATE (tmpl) = 0;
7166       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7167       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7168       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7169         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7170
7171       /* Inject this template into the global scope.  */
7172       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7173     }
7174
7175   if (context)
7176     {
7177       if (TREE_CODE (context) == NAMESPACE_DECL)
7178         pop_nested_namespace (context);
7179       else
7180         pop_nested_class ();
7181     }
7182
7183   return friend_type;
7184 }
7185
7186 /* Returns zero if TYPE cannot be completed later due to circularity.
7187    Otherwise returns one.  */
7188
7189 static int
7190 can_complete_type_without_circularity (tree type)
7191 {
7192   if (type == NULL_TREE || type == error_mark_node)
7193     return 0;
7194   else if (COMPLETE_TYPE_P (type))
7195     return 1;
7196   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7197     return can_complete_type_without_circularity (TREE_TYPE (type));
7198   else if (CLASS_TYPE_P (type)
7199            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7200     return 0;
7201   else
7202     return 1;
7203 }
7204
7205 /* Apply any attributes which had to be deferred until instantiation
7206    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7207    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7208
7209 static void
7210 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7211                                 tree args, tsubst_flags_t complain, tree in_decl)
7212 {
7213   tree last_dep = NULL_TREE;
7214   tree t;
7215   tree *p;
7216
7217   for (t = attributes; t; t = TREE_CHAIN (t))
7218     if (ATTR_IS_DEPENDENT (t))
7219       {
7220         last_dep = t;
7221         attributes = copy_list (attributes);
7222         break;
7223       }
7224
7225   if (DECL_P (*decl_p))
7226     {
7227       if (TREE_TYPE (*decl_p) == error_mark_node)
7228         return;
7229       p = &DECL_ATTRIBUTES (*decl_p);
7230     }
7231   else
7232     p = &TYPE_ATTRIBUTES (*decl_p);
7233
7234   if (last_dep)
7235     {
7236       tree late_attrs = NULL_TREE;
7237       tree *q = &late_attrs;
7238
7239       for (*p = attributes; *p; )
7240         {
7241           t = *p;
7242           if (ATTR_IS_DEPENDENT (t))
7243             {
7244               *p = TREE_CHAIN (t);
7245               TREE_CHAIN (t) = NULL_TREE;
7246               /* If the first attribute argument is an identifier, don't
7247                  pass it through tsubst.  Attributes like mode, format,
7248                  cleanup and several target specific attributes expect it
7249                  unmodified.  */
7250               if (TREE_VALUE (t)
7251                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7252                   && TREE_VALUE (TREE_VALUE (t))
7253                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7254                       == IDENTIFIER_NODE))
7255                 {
7256                   tree chain
7257                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7258                                    in_decl,
7259                                    /*integral_constant_expression_p=*/false);
7260                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7261                     TREE_VALUE (t)
7262                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7263                                    chain);
7264                 }
7265               else
7266                 TREE_VALUE (t)
7267                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7268                                  /*integral_constant_expression_p=*/false);
7269               *q = t;
7270               q = &TREE_CHAIN (t);
7271             }
7272           else
7273             p = &TREE_CHAIN (t);
7274         }
7275
7276       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7277     }
7278 }
7279
7280 /* Perform (or defer) access check for typedefs that were referenced
7281    from within the template TMPL code.
7282    This is a subroutine of instantiate_template and instantiate_class_template.
7283    TMPL is the template to consider and TARGS is the list of arguments of
7284    that template.  */
7285
7286 static void
7287 perform_typedefs_access_check (tree tmpl, tree targs)
7288 {
7289   tree t;
7290
7291   if (!tmpl
7292       || (!CLASS_TYPE_P (tmpl)
7293           && TREE_CODE (tmpl) != FUNCTION_DECL))
7294     return;
7295
7296   for (t = get_types_needing_access_check (tmpl); t; t = TREE_CHAIN (t))
7297     {
7298       tree type_decl = TREE_PURPOSE (t);
7299       tree type_scope = TREE_VALUE (t);
7300
7301       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7302         continue;
7303
7304       if (uses_template_parms (type_decl))
7305         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7306       if (uses_template_parms (type_scope))
7307         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7308
7309       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7310                                      type_decl, type_decl);
7311     }
7312 }
7313
7314 tree
7315 instantiate_class_template (tree type)
7316 {
7317   tree templ, args, pattern, t, member;
7318   tree typedecl;
7319   tree pbinfo;
7320   tree base_list;
7321
7322   if (type == error_mark_node)
7323     return error_mark_node;
7324
7325   if (TYPE_BEING_DEFINED (type)
7326       || COMPLETE_TYPE_P (type)
7327       || dependent_type_p (type))
7328     return type;
7329
7330   /* Figure out which template is being instantiated.  */
7331   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7332   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7333
7334   /* Determine what specialization of the original template to
7335      instantiate.  */
7336   t = most_specialized_class (type, templ);
7337   if (t == error_mark_node)
7338     {
7339       TYPE_BEING_DEFINED (type) = 1;
7340       return error_mark_node;
7341     }
7342   else if (t)
7343     {
7344       /* This TYPE is actually an instantiation of a partial
7345          specialization.  We replace the innermost set of ARGS with
7346          the arguments appropriate for substitution.  For example,
7347          given:
7348
7349            template <class T> struct S {};
7350            template <class T> struct S<T*> {};
7351
7352          and supposing that we are instantiating S<int*>, ARGS will
7353          presently be {int*} -- but we need {int}.  */
7354       pattern = TREE_TYPE (t);
7355       args = TREE_PURPOSE (t);
7356     }
7357   else
7358     {
7359       pattern = TREE_TYPE (templ);
7360       args = CLASSTYPE_TI_ARGS (type);
7361     }
7362
7363   /* If the template we're instantiating is incomplete, then clearly
7364      there's nothing we can do.  */
7365   if (!COMPLETE_TYPE_P (pattern))
7366     return type;
7367
7368   /* If we've recursively instantiated too many templates, stop.  */
7369   if (! push_tinst_level (type))
7370     return type;
7371
7372   /* Now we're really doing the instantiation.  Mark the type as in
7373      the process of being defined.  */
7374   TYPE_BEING_DEFINED (type) = 1;
7375
7376   /* We may be in the middle of deferred access check.  Disable
7377      it now.  */
7378   push_deferring_access_checks (dk_no_deferred);
7379
7380   push_to_top_level ();
7381
7382   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7383
7384   /* Set the input location to the most specialized template definition.
7385      This is needed if tsubsting causes an error.  */
7386   typedecl = TYPE_MAIN_DECL (pattern);
7387   input_location = DECL_SOURCE_LOCATION (typedecl);
7388
7389   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7390   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7391   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7392   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7393   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7394   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7395   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7396   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7397   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7398   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7399   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7400   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7401   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7402   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7403   if (ANON_AGGR_TYPE_P (pattern))
7404     SET_ANON_AGGR_TYPE_P (type);
7405   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7406     {
7407       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7408       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7409     }
7410
7411   pbinfo = TYPE_BINFO (pattern);
7412
7413   /* We should never instantiate a nested class before its enclosing
7414      class; we need to look up the nested class by name before we can
7415      instantiate it, and that lookup should instantiate the enclosing
7416      class.  */
7417   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7418               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7419               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7420
7421   base_list = NULL_TREE;
7422   if (BINFO_N_BASE_BINFOS (pbinfo))
7423     {
7424       tree pbase_binfo;
7425       tree context = TYPE_CONTEXT (type);
7426       tree pushed_scope;
7427       int i;
7428
7429       /* We must enter the scope containing the type, as that is where
7430          the accessibility of types named in dependent bases are
7431          looked up from.  */
7432       pushed_scope = push_scope (context ? context : global_namespace);
7433
7434       /* Substitute into each of the bases to determine the actual
7435          basetypes.  */
7436       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7437         {
7438           tree base;
7439           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7440           tree expanded_bases = NULL_TREE;
7441           int idx, len = 1;
7442
7443           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7444             {
7445               expanded_bases = 
7446                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7447                                        args, tf_error, NULL_TREE);
7448               if (expanded_bases == error_mark_node)
7449                 continue;
7450
7451               len = TREE_VEC_LENGTH (expanded_bases);
7452             }
7453
7454           for (idx = 0; idx < len; idx++)
7455             {
7456               if (expanded_bases)
7457                 /* Extract the already-expanded base class.  */
7458                 base = TREE_VEC_ELT (expanded_bases, idx);
7459               else
7460                 /* Substitute to figure out the base class.  */
7461                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7462                                NULL_TREE);
7463
7464               if (base == error_mark_node)
7465                 continue;
7466
7467               base_list = tree_cons (access, base, base_list);
7468               if (BINFO_VIRTUAL_P (pbase_binfo))
7469                 TREE_TYPE (base_list) = integer_type_node;
7470             }
7471         }
7472
7473       /* The list is now in reverse order; correct that.  */
7474       base_list = nreverse (base_list);
7475
7476       if (pushed_scope)
7477         pop_scope (pushed_scope);
7478     }
7479   /* Now call xref_basetypes to set up all the base-class
7480      information.  */
7481   xref_basetypes (type, base_list);
7482
7483   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7484                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7485                                   args, tf_error, NULL_TREE);
7486
7487   /* Now that our base classes are set up, enter the scope of the
7488      class, so that name lookups into base classes, etc. will work
7489      correctly.  This is precisely analogous to what we do in
7490      begin_class_definition when defining an ordinary non-template
7491      class, except we also need to push the enclosing classes.  */
7492   push_nested_class (type);
7493
7494   /* Now members are processed in the order of declaration.  */
7495   for (member = CLASSTYPE_DECL_LIST (pattern);
7496        member; member = TREE_CHAIN (member))
7497     {
7498       tree t = TREE_VALUE (member);
7499
7500       if (TREE_PURPOSE (member))
7501         {
7502           if (TYPE_P (t))
7503             {
7504               /* Build new CLASSTYPE_NESTED_UTDS.  */
7505
7506               tree newtag;
7507               bool class_template_p;
7508
7509               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7510                                   && TYPE_LANG_SPECIFIC (t)
7511                                   && CLASSTYPE_IS_TEMPLATE (t));
7512               /* If the member is a class template, then -- even after
7513                  substitution -- there may be dependent types in the
7514                  template argument list for the class.  We increment
7515                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7516                  that function will assume that no types are dependent
7517                  when outside of a template.  */
7518               if (class_template_p)
7519                 ++processing_template_decl;
7520               newtag = tsubst (t, args, tf_error, NULL_TREE);
7521               if (class_template_p)
7522                 --processing_template_decl;
7523               if (newtag == error_mark_node)
7524                 continue;
7525
7526               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7527                 {
7528                   tree name = TYPE_IDENTIFIER (t);
7529
7530                   if (class_template_p)
7531                     /* Unfortunately, lookup_template_class sets
7532                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7533                        instantiation (i.e., for the type of a member
7534                        template class nested within a template class.)
7535                        This behavior is required for
7536                        maybe_process_partial_specialization to work
7537                        correctly, but is not accurate in this case;
7538                        the TAG is not an instantiation of anything.
7539                        (The corresponding TEMPLATE_DECL is an
7540                        instantiation, but the TYPE is not.) */
7541                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7542
7543                   /* Now, we call pushtag to put this NEWTAG into the scope of
7544                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7545                      pushtag calling push_template_decl.  We don't have to do
7546                      this for enums because it will already have been done in
7547                      tsubst_enum.  */
7548                   if (name)
7549                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7550                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7551                 }
7552             }
7553           else if (TREE_CODE (t) == FUNCTION_DECL
7554                    || DECL_FUNCTION_TEMPLATE_P (t))
7555             {
7556               /* Build new TYPE_METHODS.  */
7557               tree r;
7558
7559               if (TREE_CODE (t) == TEMPLATE_DECL)
7560                 ++processing_template_decl;
7561               r = tsubst (t, args, tf_error, NULL_TREE);
7562               if (TREE_CODE (t) == TEMPLATE_DECL)
7563                 --processing_template_decl;
7564               set_current_access_from_decl (r);
7565               finish_member_declaration (r);
7566             }
7567           else
7568             {
7569               /* Build new TYPE_FIELDS.  */
7570               if (TREE_CODE (t) == STATIC_ASSERT)
7571                 {
7572                   tree condition = 
7573                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7574                                  tf_warning_or_error, NULL_TREE,
7575                                  /*integral_constant_expression_p=*/true);
7576                   finish_static_assert (condition,
7577                                         STATIC_ASSERT_MESSAGE (t), 
7578                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7579                                         /*member_p=*/true);
7580                 }
7581               else if (TREE_CODE (t) != CONST_DECL)
7582                 {
7583                   tree r;
7584
7585                   /* The file and line for this declaration, to
7586                      assist in error message reporting.  Since we
7587                      called push_tinst_level above, we don't need to
7588                      restore these.  */
7589                   input_location = DECL_SOURCE_LOCATION (t);
7590
7591                   if (TREE_CODE (t) == TEMPLATE_DECL)
7592                     ++processing_template_decl;
7593                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7594                   if (TREE_CODE (t) == TEMPLATE_DECL)
7595                     --processing_template_decl;
7596                   if (TREE_CODE (r) == VAR_DECL)
7597                     {
7598                       /* In [temp.inst]:
7599
7600                            [t]he initialization (and any associated
7601                            side-effects) of a static data member does
7602                            not occur unless the static data member is
7603                            itself used in a way that requires the
7604                            definition of the static data member to
7605                            exist.
7606
7607                          Therefore, we do not substitute into the
7608                          initialized for the static data member here.  */
7609                       finish_static_data_member_decl
7610                         (r,
7611                          /*init=*/NULL_TREE,
7612                          /*init_const_expr_p=*/false,
7613                          /*asmspec_tree=*/NULL_TREE,
7614                          /*flags=*/0);
7615                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7616                         check_static_variable_definition (r, TREE_TYPE (r));
7617                     }
7618                   else if (TREE_CODE (r) == FIELD_DECL)
7619                     {
7620                       /* Determine whether R has a valid type and can be
7621                          completed later.  If R is invalid, then it is
7622                          replaced by error_mark_node so that it will not be
7623                          added to TYPE_FIELDS.  */
7624                       tree rtype = TREE_TYPE (r);
7625                       if (can_complete_type_without_circularity (rtype))
7626                         complete_type (rtype);
7627
7628                       if (!COMPLETE_TYPE_P (rtype))
7629                         {
7630                           cxx_incomplete_type_error (r, rtype);
7631                           r = error_mark_node;
7632                         }
7633                     }
7634
7635                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7636                      such a thing will already have been added to the field
7637                      list by tsubst_enum in finish_member_declaration in the
7638                      CLASSTYPE_NESTED_UTDS case above.  */
7639                   if (!(TREE_CODE (r) == TYPE_DECL
7640                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7641                         && DECL_ARTIFICIAL (r)))
7642                     {
7643                       set_current_access_from_decl (r);
7644                       finish_member_declaration (r);
7645                     }
7646                 }
7647             }
7648         }
7649       else
7650         {
7651           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7652             {
7653               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7654
7655               tree friend_type = t;
7656               bool adjust_processing_template_decl = false;
7657
7658               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7659                 {
7660                   /* template <class T> friend class C;  */
7661                   friend_type = tsubst_friend_class (friend_type, args);
7662                   adjust_processing_template_decl = true;
7663                 }
7664               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7665                 {
7666                   /* template <class T> friend class C::D;  */
7667                   friend_type = tsubst (friend_type, args,
7668                                         tf_warning_or_error, NULL_TREE);
7669                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7670                     friend_type = TREE_TYPE (friend_type);
7671                   adjust_processing_template_decl = true;
7672                 }
7673               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7674                 {
7675                   /* This could be either
7676
7677                        friend class T::C;
7678
7679                      when dependent_type_p is false or
7680
7681                        template <class U> friend class T::C;
7682
7683                      otherwise.  */
7684                   friend_type = tsubst (friend_type, args,
7685                                         tf_warning_or_error, NULL_TREE);
7686                   /* Bump processing_template_decl for correct
7687                      dependent_type_p calculation.  */
7688                   ++processing_template_decl;
7689                   if (dependent_type_p (friend_type))
7690                     adjust_processing_template_decl = true;
7691                   --processing_template_decl;
7692                 }
7693               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7694                        && hidden_name_p (TYPE_NAME (friend_type)))
7695                 {
7696                   /* friend class C;
7697
7698                      where C hasn't been declared yet.  Let's lookup name
7699                      from namespace scope directly, bypassing any name that
7700                      come from dependent base class.  */
7701                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7702
7703                   /* The call to xref_tag_from_type does injection for friend
7704                      classes.  */
7705                   push_nested_namespace (ns);
7706                   friend_type =
7707                     xref_tag_from_type (friend_type, NULL_TREE,
7708                                         /*tag_scope=*/ts_current);
7709                   pop_nested_namespace (ns);
7710                 }
7711               else if (uses_template_parms (friend_type))
7712                 /* friend class C<T>;  */
7713                 friend_type = tsubst (friend_type, args,
7714                                       tf_warning_or_error, NULL_TREE);
7715               /* Otherwise it's
7716
7717                    friend class C;
7718
7719                  where C is already declared or
7720
7721                    friend class C<int>;
7722
7723                  We don't have to do anything in these cases.  */
7724
7725               if (adjust_processing_template_decl)
7726                 /* Trick make_friend_class into realizing that the friend
7727                    we're adding is a template, not an ordinary class.  It's
7728                    important that we use make_friend_class since it will
7729                    perform some error-checking and output cross-reference
7730                    information.  */
7731                 ++processing_template_decl;
7732
7733               if (friend_type != error_mark_node)
7734                 make_friend_class (type, friend_type, /*complain=*/false);
7735
7736               if (adjust_processing_template_decl)
7737                 --processing_template_decl;
7738             }
7739           else
7740             {
7741               /* Build new DECL_FRIENDLIST.  */
7742               tree r;
7743
7744               /* The file and line for this declaration, to
7745                  assist in error message reporting.  Since we
7746                  called push_tinst_level above, we don't need to
7747                  restore these.  */
7748               input_location = DECL_SOURCE_LOCATION (t);
7749
7750               if (TREE_CODE (t) == TEMPLATE_DECL)
7751                 {
7752                   ++processing_template_decl;
7753                   push_deferring_access_checks (dk_no_check);
7754                 }
7755
7756               r = tsubst_friend_function (t, args);
7757               add_friend (type, r, /*complain=*/false);
7758               if (TREE_CODE (t) == TEMPLATE_DECL)
7759                 {
7760                   pop_deferring_access_checks ();
7761                   --processing_template_decl;
7762                 }
7763             }
7764         }
7765     }
7766
7767   /* Set the file and line number information to whatever is given for
7768      the class itself.  This puts error messages involving generated
7769      implicit functions at a predictable point, and the same point
7770      that would be used for non-template classes.  */
7771   input_location = DECL_SOURCE_LOCATION (typedecl);
7772
7773   unreverse_member_declarations (type);
7774   finish_struct_1 (type);
7775   TYPE_BEING_DEFINED (type) = 0;
7776
7777   /* Now that the class is complete, instantiate default arguments for
7778      any member functions.  We don't do this earlier because the
7779      default arguments may reference members of the class.  */
7780   if (!PRIMARY_TEMPLATE_P (templ))
7781     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7782       if (TREE_CODE (t) == FUNCTION_DECL
7783           /* Implicitly generated member functions will not have template
7784              information; they are not instantiations, but instead are
7785              created "fresh" for each instantiation.  */
7786           && DECL_TEMPLATE_INFO (t))
7787         tsubst_default_arguments (t);
7788
7789   /* Some typedefs referenced from within the template code need to be access
7790      checked at template instantiation time, i.e now. These types were
7791      added to the template at parsing time. Let's get those and perform
7792      the access checks then.  */
7793   perform_typedefs_access_check (pattern, args);
7794   perform_deferred_access_checks ();
7795   pop_nested_class ();
7796   pop_from_top_level ();
7797   pop_deferring_access_checks ();
7798   pop_tinst_level ();
7799
7800   /* The vtable for a template class can be emitted in any translation
7801      unit in which the class is instantiated.  When there is no key
7802      method, however, finish_struct_1 will already have added TYPE to
7803      the keyed_classes list.  */
7804   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7805     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7806
7807   return type;
7808 }
7809
7810 static tree
7811 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7812 {
7813   tree r;
7814
7815   if (!t)
7816     r = t;
7817   else if (TYPE_P (t))
7818     r = tsubst (t, args, complain, in_decl);
7819   else
7820     {
7821       r = tsubst_expr (t, args, complain, in_decl,
7822                        /*integral_constant_expression_p=*/true);
7823       r = fold_non_dependent_expr (r);
7824     }
7825   return r;
7826 }
7827
7828 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
7829    NONTYPE_ARGUMENT_PACK.  */
7830
7831 static tree
7832 make_fnparm_pack (tree spec_parm)
7833 {
7834   /* Collect all of the extra "packed" parameters into an
7835      argument pack.  */
7836   tree parmvec;
7837   tree parmtypevec;
7838   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
7839   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
7840   int i, len = list_length (spec_parm);
7841
7842   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
7843   parmvec = make_tree_vec (len);
7844   parmtypevec = make_tree_vec (len);
7845   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
7846     {
7847       TREE_VEC_ELT (parmvec, i) = spec_parm;
7848       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
7849     }
7850
7851   /* Build the argument packs.  */
7852   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
7853   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
7854   TREE_TYPE (argpack) = argtypepack;
7855
7856   return argpack;
7857 }        
7858
7859 /* Substitute ARGS into T, which is an pack expansion
7860    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7861    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7862    (if only a partial substitution could be performed) or
7863    ERROR_MARK_NODE if there was an error.  */
7864 tree
7865 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7866                        tree in_decl)
7867 {
7868   tree pattern;
7869   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7870   tree first_arg_pack; int i, len = -1;
7871   tree result;
7872   int incomplete = 0;
7873   bool very_local_specializations = false;
7874
7875   gcc_assert (PACK_EXPANSION_P (t));
7876   pattern = PACK_EXPANSION_PATTERN (t);
7877
7878   /* Determine the argument packs that will instantiate the parameter
7879      packs used in the expansion expression. While we're at it,
7880      compute the number of arguments to be expanded and make sure it
7881      is consistent.  */
7882   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7883        pack = TREE_CHAIN (pack))
7884     {
7885       tree parm_pack = TREE_VALUE (pack);
7886       tree arg_pack = NULL_TREE;
7887       tree orig_arg = NULL_TREE;
7888
7889       if (TREE_CODE (parm_pack) == PARM_DECL)
7890         {
7891           arg_pack = retrieve_local_specialization (parm_pack);
7892           if (arg_pack == NULL_TREE)
7893             {
7894               /* This can happen for a parameter name used later in a function
7895                  declaration (such as in a late-specified return type).  Just
7896                  make a dummy decl, since it's only used for its type.  */
7897               gcc_assert (cp_unevaluated_operand != 0);
7898               arg_pack = tsubst_decl (parm_pack, args, complain);
7899               arg_pack = make_fnparm_pack (arg_pack);
7900             }
7901         }
7902       else
7903         {
7904           int level, idx, levels;
7905           template_parm_level_and_index (parm_pack, &level, &idx);
7906
7907           levels = TMPL_ARGS_DEPTH (args);
7908           if (level <= levels)
7909             arg_pack = TMPL_ARG (args, level, idx);
7910         }
7911
7912       orig_arg = arg_pack;
7913       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7914         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7915       
7916       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7917         /* This can only happen if we forget to expand an argument
7918            pack somewhere else. Just return an error, silently.  */
7919         {
7920           result = make_tree_vec (1);
7921           TREE_VEC_ELT (result, 0) = error_mark_node;
7922           return result;
7923         }
7924
7925       if (arg_pack
7926           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
7927           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
7928         {
7929           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
7930           tree pattern = PACK_EXPANSION_PATTERN (expansion);
7931           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
7932               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
7933             /* The argument pack that the parameter maps to is just an
7934                expansion of the parameter itself, such as one would
7935                find in the implicit typedef of a class inside the
7936                class itself.  Consider this parameter "unsubstituted",
7937                so that we will maintain the outer pack expansion.  */
7938             arg_pack = NULL_TREE;
7939         }
7940           
7941       if (arg_pack)
7942         {
7943           int my_len = 
7944             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7945
7946           /* It's all-or-nothing with incomplete argument packs.  */
7947           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7948             return error_mark_node;
7949           
7950           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7951             incomplete = 1;
7952
7953           if (len < 0)
7954             {
7955               len = my_len;
7956               first_arg_pack = arg_pack;
7957             }
7958           else if (len != my_len)
7959             {
7960               if (incomplete)
7961                 /* We got explicit args for some packs but not others;
7962                    do nothing now and try again after deduction.  */
7963                 return t;
7964               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
7965                 error ("mismatched argument pack lengths while expanding "
7966                        "%<%T%>",
7967                        pattern);
7968               else
7969                 error ("mismatched argument pack lengths while expanding "
7970                        "%<%E%>",
7971                        pattern);
7972               return error_mark_node;
7973             }
7974
7975           /* Keep track of the parameter packs and their corresponding
7976              argument packs.  */
7977           packs = tree_cons (parm_pack, arg_pack, packs);
7978           TREE_TYPE (packs) = orig_arg;
7979         }
7980       else
7981         /* We can't substitute for this parameter pack.  */
7982         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
7983                                          TREE_VALUE (pack),
7984                                          unsubstituted_packs);
7985     }
7986
7987   /* We cannot expand this expansion expression, because we don't have
7988      all of the argument packs we need. Substitute into the pattern
7989      and return a PACK_EXPANSION_*. The caller will need to deal with
7990      that.  */
7991   if (unsubstituted_packs)
7992     {
7993       tree new_pat;
7994       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7995         new_pat = tsubst_expr (pattern, args, complain, in_decl,
7996                                /*integral_constant_expression_p=*/false);
7997       else
7998         new_pat = tsubst (pattern, args, complain, in_decl);
7999       return make_pack_expansion (new_pat);
8000     }
8001
8002   /* We could not find any argument packs that work.  */
8003   if (len < 0)
8004     return error_mark_node;
8005
8006   if (!local_specializations)
8007     {
8008       /* We're in a late-specified return type, so we don't have a local
8009          specializations table.  Create one for doing this expansion.  */
8010       very_local_specializations = true;
8011       local_specializations = htab_create (37,
8012                                            hash_local_specialization,
8013                                            eq_local_specializations,
8014                                            NULL);
8015     }
8016
8017   /* For each argument in each argument pack, substitute into the
8018      pattern.  */
8019   result = make_tree_vec (len + incomplete);
8020   for (i = 0; i < len + incomplete; ++i)
8021     {
8022       /* For parameter pack, change the substitution of the parameter
8023          pack to the ith argument in its argument pack, then expand
8024          the pattern.  */
8025       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8026         {
8027           tree parm = TREE_PURPOSE (pack);
8028
8029           if (TREE_CODE (parm) == PARM_DECL)
8030             {
8031               /* Select the Ith argument from the pack.  */
8032               tree arg = make_node (ARGUMENT_PACK_SELECT);
8033               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8034               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8035               mark_used (parm);
8036               register_local_specialization (arg, parm);
8037             }
8038           else
8039             {
8040               tree value = parm;
8041               int idx, level;
8042               template_parm_level_and_index (parm, &level, &idx);
8043               
8044               if (i < len) 
8045                 {
8046                   /* Select the Ith argument from the pack. */
8047                   value = make_node (ARGUMENT_PACK_SELECT);
8048                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8049                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8050                 }
8051
8052               /* Update the corresponding argument.  */
8053               TMPL_ARG (args, level, idx) = value;
8054             }
8055         }
8056
8057       /* Substitute into the PATTERN with the altered arguments.  */
8058       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8059         TREE_VEC_ELT (result, i) = 
8060           tsubst_expr (pattern, args, complain, in_decl,
8061                        /*integral_constant_expression_p=*/false);
8062       else
8063         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8064
8065       if (i == len)
8066         /* When we have incomplete argument packs, the last "expanded"
8067            result is itself a pack expansion, which allows us
8068            to deduce more arguments.  */
8069         TREE_VEC_ELT (result, i) = 
8070           make_pack_expansion (TREE_VEC_ELT (result, i));
8071
8072       if (TREE_VEC_ELT (result, i) == error_mark_node)
8073         {
8074           result = error_mark_node;
8075           break;
8076         }
8077     }
8078
8079   /* Update ARGS to restore the substitution from parameter packs to
8080      their argument packs.  */
8081   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8082     {
8083       tree parm = TREE_PURPOSE (pack);
8084
8085       if (TREE_CODE (parm) == PARM_DECL)
8086         register_local_specialization (TREE_TYPE (pack), parm);
8087       else
8088         {
8089           int idx, level;
8090           template_parm_level_and_index (parm, &level, &idx);
8091           
8092           /* Update the corresponding argument.  */
8093           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8094             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8095               TREE_TYPE (pack);
8096           else
8097             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8098         }
8099     }
8100
8101   if (very_local_specializations)
8102     {
8103       htab_delete (local_specializations);
8104       local_specializations = NULL;
8105     }
8106   
8107   return result;
8108 }
8109
8110 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8111    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8112    parameter packs; all parms generated from a function parameter pack will
8113    have the same DECL_PARM_INDEX.  */
8114
8115 tree
8116 get_pattern_parm (tree parm, tree tmpl)
8117 {
8118   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8119   tree patparm;
8120
8121   if (DECL_ARTIFICIAL (parm))
8122     {
8123       for (patparm = DECL_ARGUMENTS (pattern);
8124            patparm; patparm = TREE_CHAIN (patparm))
8125         if (DECL_ARTIFICIAL (patparm)
8126             && DECL_NAME (parm) == DECL_NAME (patparm))
8127           break;
8128     }
8129   else
8130     {
8131       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8132       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8133       gcc_assert (DECL_PARM_INDEX (patparm)
8134                   == DECL_PARM_INDEX (parm));
8135     }
8136
8137   return patparm;
8138 }
8139
8140 /* Substitute ARGS into the vector or list of template arguments T.  */
8141
8142 static tree
8143 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8144 {
8145   tree orig_t = t;
8146   int len = TREE_VEC_LENGTH (t);
8147   int need_new = 0, i, expanded_len_adjust = 0, out;
8148   tree *elts = (tree *) alloca (len * sizeof (tree));
8149
8150   for (i = 0; i < len; i++)
8151     {
8152       tree orig_arg = TREE_VEC_ELT (t, i);
8153       tree new_arg;
8154
8155       if (TREE_CODE (orig_arg) == TREE_VEC)
8156         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8157       else if (PACK_EXPANSION_P (orig_arg))
8158         {
8159           /* Substitute into an expansion expression.  */
8160           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8161
8162           if (TREE_CODE (new_arg) == TREE_VEC)
8163             /* Add to the expanded length adjustment the number of
8164                expanded arguments. We subtract one from this
8165                measurement, because the argument pack expression
8166                itself is already counted as 1 in
8167                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8168                the argument pack is empty.  */
8169             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8170         }
8171       else if (ARGUMENT_PACK_P (orig_arg))
8172         {
8173           /* Substitute into each of the arguments.  */
8174           new_arg = TYPE_P (orig_arg)
8175             ? cxx_make_type (TREE_CODE (orig_arg))
8176             : make_node (TREE_CODE (orig_arg));
8177           
8178           SET_ARGUMENT_PACK_ARGS (
8179             new_arg,
8180             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8181                                   args, complain, in_decl));
8182
8183           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8184             new_arg = error_mark_node;
8185
8186           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8187             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8188                                           complain, in_decl);
8189             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8190
8191             if (TREE_TYPE (new_arg) == error_mark_node)
8192               new_arg = error_mark_node;
8193           }
8194         }
8195       else
8196         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8197
8198       if (new_arg == error_mark_node)
8199         return error_mark_node;
8200
8201       elts[i] = new_arg;
8202       if (new_arg != orig_arg)
8203         need_new = 1;
8204     }
8205
8206   if (!need_new)
8207     return t;
8208
8209   /* Make space for the expanded arguments coming from template
8210      argument packs.  */
8211   t = make_tree_vec (len + expanded_len_adjust);
8212   for (i = 0, out = 0; i < len; i++)
8213     {
8214       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8215            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8216           && TREE_CODE (elts[i]) == TREE_VEC)
8217         {
8218           int idx;
8219
8220           /* Now expand the template argument pack "in place".  */
8221           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8222             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8223         }
8224       else
8225         {
8226           TREE_VEC_ELT (t, out) = elts[i];
8227           out++;
8228         }
8229     }
8230
8231   return t;
8232 }
8233
8234 /* Return the result of substituting ARGS into the template parameters
8235    given by PARMS.  If there are m levels of ARGS and m + n levels of
8236    PARMS, then the result will contain n levels of PARMS.  For
8237    example, if PARMS is `template <class T> template <class U>
8238    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8239    result will be `template <int*, double, class V>'.  */
8240
8241 static tree
8242 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8243 {
8244   tree r = NULL_TREE;
8245   tree* new_parms;
8246
8247   /* When substituting into a template, we must set
8248      PROCESSING_TEMPLATE_DECL as the template parameters may be
8249      dependent if they are based on one-another, and the dependency
8250      predicates are short-circuit outside of templates.  */
8251   ++processing_template_decl;
8252
8253   for (new_parms = &r;
8254        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8255        new_parms = &(TREE_CHAIN (*new_parms)),
8256          parms = TREE_CHAIN (parms))
8257     {
8258       tree new_vec =
8259         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8260       int i;
8261
8262       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8263         {
8264           tree tuple;
8265           tree default_value;
8266           tree parm_decl;
8267
8268           if (parms == error_mark_node)
8269             continue;
8270
8271           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8272
8273           if (tuple == error_mark_node)
8274             continue;
8275
8276           default_value = TREE_PURPOSE (tuple);
8277           parm_decl = TREE_VALUE (tuple);
8278
8279           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8280           if (TREE_CODE (parm_decl) == PARM_DECL
8281               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8282             parm_decl = error_mark_node;
8283           default_value = tsubst_template_arg (default_value, args,
8284                                                complain, NULL_TREE);
8285
8286           tuple = build_tree_list (default_value, parm_decl);
8287           TREE_VEC_ELT (new_vec, i) = tuple;
8288         }
8289
8290       *new_parms =
8291         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8292                              - TMPL_ARGS_DEPTH (args)),
8293                    new_vec, NULL_TREE);
8294     }
8295
8296   --processing_template_decl;
8297
8298   return r;
8299 }
8300
8301 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8302    type T.  If T is not an aggregate or enumeration type, it is
8303    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8304    ENTERING_SCOPE is nonzero, T is the context for a template which
8305    we are presently tsubst'ing.  Return the substituted value.  */
8306
8307 static tree
8308 tsubst_aggr_type (tree t,
8309                   tree args,
8310                   tsubst_flags_t complain,
8311                   tree in_decl,
8312                   int entering_scope)
8313 {
8314   if (t == NULL_TREE)
8315     return NULL_TREE;
8316
8317   switch (TREE_CODE (t))
8318     {
8319     case RECORD_TYPE:
8320       if (TYPE_PTRMEMFUNC_P (t))
8321         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8322
8323       /* Else fall through.  */
8324     case ENUMERAL_TYPE:
8325     case UNION_TYPE:
8326       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8327         {
8328           tree argvec;
8329           tree context;
8330           tree r;
8331           int saved_unevaluated_operand;
8332           int saved_inhibit_evaluation_warnings;
8333
8334           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8335           saved_unevaluated_operand = cp_unevaluated_operand;
8336           cp_unevaluated_operand = 0;
8337           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8338           c_inhibit_evaluation_warnings = 0;
8339
8340           /* First, determine the context for the type we are looking
8341              up.  */
8342           context = TYPE_CONTEXT (t);
8343           if (context)
8344             {
8345               context = tsubst_aggr_type (context, args, complain,
8346                                           in_decl, /*entering_scope=*/1);
8347               /* If context is a nested class inside a class template,
8348                  it may still need to be instantiated (c++/33959).  */
8349               if (TYPE_P (context))
8350                 context = complete_type (context);
8351             }
8352
8353           /* Then, figure out what arguments are appropriate for the
8354              type we are trying to find.  For example, given:
8355
8356                template <class T> struct S;
8357                template <class T, class U> void f(T, U) { S<U> su; }
8358
8359              and supposing that we are instantiating f<int, double>,
8360              then our ARGS will be {int, double}, but, when looking up
8361              S we only want {double}.  */
8362           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8363                                          complain, in_decl);
8364           if (argvec == error_mark_node)
8365             r = error_mark_node;
8366           else
8367             {
8368               r = lookup_template_class (t, argvec, in_decl, context,
8369                                          entering_scope, complain);
8370               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8371             }
8372
8373           cp_unevaluated_operand = saved_unevaluated_operand;
8374           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8375
8376           return r;
8377         }
8378       else
8379         /* This is not a template type, so there's nothing to do.  */
8380         return t;
8381
8382     default:
8383       return tsubst (t, args, complain, in_decl);
8384     }
8385 }
8386
8387 /* Substitute into the default argument ARG (a default argument for
8388    FN), which has the indicated TYPE.  */
8389
8390 tree
8391 tsubst_default_argument (tree fn, tree type, tree arg)
8392 {
8393   tree saved_class_ptr = NULL_TREE;
8394   tree saved_class_ref = NULL_TREE;
8395
8396   /* This default argument came from a template.  Instantiate the
8397      default argument here, not in tsubst.  In the case of
8398      something like:
8399
8400        template <class T>
8401        struct S {
8402          static T t();
8403          void f(T = t());
8404        };
8405
8406      we must be careful to do name lookup in the scope of S<T>,
8407      rather than in the current class.  */
8408   push_access_scope (fn);
8409   /* The "this" pointer is not valid in a default argument.  */
8410   if (cfun)
8411     {
8412       saved_class_ptr = current_class_ptr;
8413       cp_function_chain->x_current_class_ptr = NULL_TREE;
8414       saved_class_ref = current_class_ref;
8415       cp_function_chain->x_current_class_ref = NULL_TREE;
8416     }
8417
8418   push_deferring_access_checks(dk_no_deferred);
8419   /* The default argument expression may cause implicitly defined
8420      member functions to be synthesized, which will result in garbage
8421      collection.  We must treat this situation as if we were within
8422      the body of function so as to avoid collecting live data on the
8423      stack.  */
8424   ++function_depth;
8425   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8426                      tf_warning_or_error, NULL_TREE,
8427                      /*integral_constant_expression_p=*/false);
8428   --function_depth;
8429   pop_deferring_access_checks();
8430
8431   /* Restore the "this" pointer.  */
8432   if (cfun)
8433     {
8434       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8435       cp_function_chain->x_current_class_ref = saved_class_ref;
8436     }
8437
8438   /* Make sure the default argument is reasonable.  */
8439   arg = check_default_argument (type, arg);
8440
8441   pop_access_scope (fn);
8442
8443   return arg;
8444 }
8445
8446 /* Substitute into all the default arguments for FN.  */
8447
8448 static void
8449 tsubst_default_arguments (tree fn)
8450 {
8451   tree arg;
8452   tree tmpl_args;
8453
8454   tmpl_args = DECL_TI_ARGS (fn);
8455
8456   /* If this function is not yet instantiated, we certainly don't need
8457      its default arguments.  */
8458   if (uses_template_parms (tmpl_args))
8459     return;
8460
8461   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8462        arg;
8463        arg = TREE_CHAIN (arg))
8464     if (TREE_PURPOSE (arg))
8465       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8466                                                     TREE_VALUE (arg),
8467                                                     TREE_PURPOSE (arg));
8468 }
8469
8470 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8471    result of the substitution.  Issue error and warning messages under
8472    control of COMPLAIN.  */
8473
8474 static tree
8475 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8476 {
8477 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8478   location_t saved_loc;
8479   tree r = NULL_TREE;
8480   tree in_decl = t;
8481   hashval_t hash = 0;
8482
8483   /* Set the filename and linenumber to improve error-reporting.  */
8484   saved_loc = input_location;
8485   input_location = DECL_SOURCE_LOCATION (t);
8486
8487   switch (TREE_CODE (t))
8488     {
8489     case TEMPLATE_DECL:
8490       {
8491         /* We can get here when processing a member function template,
8492            member class template, or template template parameter.  */
8493         tree decl = DECL_TEMPLATE_RESULT (t);
8494         tree spec;
8495         tree tmpl_args;
8496         tree full_args;
8497
8498         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8499           {
8500             /* Template template parameter is treated here.  */
8501             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8502             if (new_type == error_mark_node)
8503               RETURN (error_mark_node);
8504
8505             r = copy_decl (t);
8506             TREE_CHAIN (r) = NULL_TREE;
8507             TREE_TYPE (r) = new_type;
8508             DECL_TEMPLATE_RESULT (r)
8509               = build_decl (DECL_SOURCE_LOCATION (decl),
8510                             TYPE_DECL, DECL_NAME (decl), new_type);
8511             DECL_TEMPLATE_PARMS (r)
8512               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8513                                        complain);
8514             TYPE_NAME (new_type) = r;
8515             break;
8516           }
8517
8518         /* We might already have an instance of this template.
8519            The ARGS are for the surrounding class type, so the
8520            full args contain the tsubst'd args for the context,
8521            plus the innermost args from the template decl.  */
8522         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8523           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8524           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8525         /* Because this is a template, the arguments will still be
8526            dependent, even after substitution.  If
8527            PROCESSING_TEMPLATE_DECL is not set, the dependency
8528            predicates will short-circuit.  */
8529         ++processing_template_decl;
8530         full_args = tsubst_template_args (tmpl_args, args,
8531                                           complain, in_decl);
8532         --processing_template_decl;
8533         if (full_args == error_mark_node)
8534           RETURN (error_mark_node);
8535
8536         /* If this is a default template template argument,
8537            tsubst might not have changed anything.  */
8538         if (full_args == tmpl_args)
8539           RETURN (t);
8540
8541         hash = hash_tmpl_and_args (t, full_args);
8542         spec = retrieve_specialization (t, full_args, hash);
8543         if (spec != NULL_TREE)
8544           {
8545             r = spec;
8546             break;
8547           }
8548
8549         /* Make a new template decl.  It will be similar to the
8550            original, but will record the current template arguments.
8551            We also create a new function declaration, which is just
8552            like the old one, but points to this new template, rather
8553            than the old one.  */
8554         r = copy_decl (t);
8555         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8556         TREE_CHAIN (r) = NULL_TREE;
8557
8558         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
8559
8560         if (TREE_CODE (decl) == TYPE_DECL)
8561           {
8562             tree new_type;
8563             ++processing_template_decl;
8564             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8565             --processing_template_decl;
8566             if (new_type == error_mark_node)
8567               RETURN (error_mark_node);
8568
8569             TREE_TYPE (r) = new_type;
8570             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8571             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8572             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8573             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8574           }
8575         else
8576           {
8577             tree new_decl;
8578             ++processing_template_decl;
8579             new_decl = tsubst (decl, args, complain, in_decl);
8580             --processing_template_decl;
8581             if (new_decl == error_mark_node)
8582               RETURN (error_mark_node);
8583
8584             DECL_TEMPLATE_RESULT (r) = new_decl;
8585             DECL_TI_TEMPLATE (new_decl) = r;
8586             TREE_TYPE (r) = TREE_TYPE (new_decl);
8587             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8588             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8589           }
8590
8591         SET_DECL_IMPLICIT_INSTANTIATION (r);
8592         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8593         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8594
8595         /* The template parameters for this new template are all the
8596            template parameters for the old template, except the
8597            outermost level of parameters.  */
8598         DECL_TEMPLATE_PARMS (r)
8599           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8600                                    complain);
8601
8602         if (PRIMARY_TEMPLATE_P (t))
8603           DECL_PRIMARY_TEMPLATE (r) = r;
8604
8605         if (TREE_CODE (decl) != TYPE_DECL)
8606           /* Record this non-type partial instantiation.  */
8607           register_specialization (r, t,
8608                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8609                                    false, hash);
8610       }
8611       break;
8612
8613     case FUNCTION_DECL:
8614       {
8615         tree ctx;
8616         tree argvec = NULL_TREE;
8617         tree *friends;
8618         tree gen_tmpl;
8619         tree type;
8620         int member;
8621         int args_depth;
8622         int parms_depth;
8623
8624         /* Nobody should be tsubst'ing into non-template functions.  */
8625         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8626
8627         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8628           {
8629             tree spec;
8630             bool dependent_p;
8631
8632             /* If T is not dependent, just return it.  We have to
8633                increment PROCESSING_TEMPLATE_DECL because
8634                value_dependent_expression_p assumes that nothing is
8635                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8636             ++processing_template_decl;
8637             dependent_p = value_dependent_expression_p (t);
8638             --processing_template_decl;
8639             if (!dependent_p)
8640               RETURN (t);
8641
8642             /* Calculate the most general template of which R is a
8643                specialization, and the complete set of arguments used to
8644                specialize R.  */
8645             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8646             argvec = tsubst_template_args (DECL_TI_ARGS
8647                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8648                                            args, complain, in_decl);
8649
8650             /* Check to see if we already have this specialization.  */
8651             hash = hash_tmpl_and_args (gen_tmpl, argvec);
8652             spec = retrieve_specialization (gen_tmpl, argvec, hash);
8653
8654             if (spec)
8655               {
8656                 r = spec;
8657                 break;
8658               }
8659
8660             /* We can see more levels of arguments than parameters if
8661                there was a specialization of a member template, like
8662                this:
8663
8664                  template <class T> struct S { template <class U> void f(); }
8665                  template <> template <class U> void S<int>::f(U);
8666
8667                Here, we'll be substituting into the specialization,
8668                because that's where we can find the code we actually
8669                want to generate, but we'll have enough arguments for
8670                the most general template.
8671
8672                We also deal with the peculiar case:
8673
8674                  template <class T> struct S {
8675                    template <class U> friend void f();
8676                  };
8677                  template <class U> void f() {}
8678                  template S<int>;
8679                  template void f<double>();
8680
8681                Here, the ARGS for the instantiation of will be {int,
8682                double}.  But, we only need as many ARGS as there are
8683                levels of template parameters in CODE_PATTERN.  We are
8684                careful not to get fooled into reducing the ARGS in
8685                situations like:
8686
8687                  template <class T> struct S { template <class U> void f(U); }
8688                  template <class T> template <> void S<T>::f(int) {}
8689
8690                which we can spot because the pattern will be a
8691                specialization in this case.  */
8692             args_depth = TMPL_ARGS_DEPTH (args);
8693             parms_depth =
8694               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8695             if (args_depth > parms_depth
8696                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8697               args = get_innermost_template_args (args, parms_depth);
8698           }
8699         else
8700           {
8701             /* This special case arises when we have something like this:
8702
8703                  template <class T> struct S {
8704                    friend void f<int>(int, double);
8705                  };
8706
8707                Here, the DECL_TI_TEMPLATE for the friend declaration
8708                will be an IDENTIFIER_NODE.  We are being called from
8709                tsubst_friend_function, and we want only to create a
8710                new decl (R) with appropriate types so that we can call
8711                determine_specialization.  */
8712             gen_tmpl = NULL_TREE;
8713           }
8714
8715         if (DECL_CLASS_SCOPE_P (t))
8716           {
8717             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8718               member = 2;
8719             else
8720               member = 1;
8721             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8722                                     complain, t, /*entering_scope=*/1);
8723           }
8724         else
8725           {
8726             member = 0;
8727             ctx = DECL_CONTEXT (t);
8728           }
8729         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8730         if (type == error_mark_node)
8731           RETURN (error_mark_node);
8732
8733         /* We do NOT check for matching decls pushed separately at this
8734            point, as they may not represent instantiations of this
8735            template, and in any case are considered separate under the
8736            discrete model.  */
8737         r = copy_decl (t);
8738         DECL_USE_TEMPLATE (r) = 0;
8739         TREE_TYPE (r) = type;
8740         /* Clear out the mangled name and RTL for the instantiation.  */
8741         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8742         SET_DECL_RTL (r, NULL_RTX);
8743         /* Leave DECL_INITIAL set on deleted instantiations.  */
8744         if (!DECL_DELETED_FN (r))
8745           DECL_INITIAL (r) = NULL_TREE;
8746         DECL_CONTEXT (r) = ctx;
8747
8748         if (member && DECL_CONV_FN_P (r))
8749           /* Type-conversion operator.  Reconstruct the name, in
8750              case it's the name of one of the template's parameters.  */
8751           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8752
8753         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8754                                      complain, t);
8755         DECL_RESULT (r) = NULL_TREE;
8756
8757         TREE_STATIC (r) = 0;
8758         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8759         DECL_EXTERNAL (r) = 1;
8760         /* If this is an instantiation of a function with internal
8761            linkage, we already know what object file linkage will be
8762            assigned to the instantiation.  */
8763         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8764         DECL_DEFER_OUTPUT (r) = 0;
8765         TREE_CHAIN (r) = NULL_TREE;
8766         DECL_PENDING_INLINE_INFO (r) = 0;
8767         DECL_PENDING_INLINE_P (r) = 0;
8768         DECL_SAVED_TREE (r) = NULL_TREE;
8769         DECL_STRUCT_FUNCTION (r) = NULL;
8770         TREE_USED (r) = 0;
8771         /* We'll re-clone as appropriate in instantiate_template.  */
8772         DECL_CLONED_FUNCTION (r) = NULL_TREE;
8773
8774         /* If we aren't complaining now, return on error before we register
8775            the specialization so that we'll complain eventually.  */
8776         if ((complain & tf_error) == 0
8777             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
8778             && !grok_op_properties (r, /*complain=*/false))
8779           RETURN (error_mark_node);
8780
8781         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8782            this in the special friend case mentioned above where
8783            GEN_TMPL is NULL.  */
8784         if (gen_tmpl)
8785           {
8786             DECL_TEMPLATE_INFO (r)
8787               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8788             SET_DECL_IMPLICIT_INSTANTIATION (r);
8789             register_specialization (r, gen_tmpl, argvec, false, hash);
8790
8791             /* We're not supposed to instantiate default arguments
8792                until they are called, for a template.  But, for a
8793                declaration like:
8794
8795                  template <class T> void f ()
8796                  { extern void g(int i = T()); }
8797
8798                we should do the substitution when the template is
8799                instantiated.  We handle the member function case in
8800                instantiate_class_template since the default arguments
8801                might refer to other members of the class.  */
8802             if (!member
8803                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8804                 && !uses_template_parms (argvec))
8805               tsubst_default_arguments (r);
8806           }
8807         else
8808           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8809
8810         /* Copy the list of befriending classes.  */
8811         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8812              *friends;
8813              friends = &TREE_CHAIN (*friends))
8814           {
8815             *friends = copy_node (*friends);
8816             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8817                                             args, complain,
8818                                             in_decl);
8819           }
8820
8821         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8822           {
8823             maybe_retrofit_in_chrg (r);
8824             if (DECL_CONSTRUCTOR_P (r))
8825               grok_ctor_properties (ctx, r);
8826             /* If this is an instantiation of a member template, clone it.
8827                If it isn't, that'll be handled by
8828                clone_constructors_and_destructors.  */
8829             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8830               clone_function_decl (r, /*update_method_vec_p=*/0);
8831           }
8832         else if ((complain & tf_error) != 0
8833                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
8834                  && !grok_op_properties (r, /*complain=*/true))
8835           RETURN (error_mark_node);
8836
8837         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8838           SET_DECL_FRIEND_CONTEXT (r,
8839                                    tsubst (DECL_FRIEND_CONTEXT (t),
8840                                             args, complain, in_decl));
8841
8842         /* Possibly limit visibility based on template args.  */
8843         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8844         if (DECL_VISIBILITY_SPECIFIED (t))
8845           {
8846             DECL_VISIBILITY_SPECIFIED (r) = 0;
8847             DECL_ATTRIBUTES (r)
8848               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8849           }
8850         determine_visibility (r);
8851
8852         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8853                                         args, complain, in_decl);
8854       }
8855       break;
8856
8857     case PARM_DECL:
8858       {
8859         tree type = NULL_TREE;
8860         int i, len = 1;
8861         tree expanded_types = NULL_TREE;
8862         tree prev_r = NULL_TREE;
8863         tree first_r = NULL_TREE;
8864
8865         if (FUNCTION_PARAMETER_PACK_P (t))
8866           {
8867             /* If there is a local specialization that isn't a
8868                parameter pack, it means that we're doing a "simple"
8869                substitution from inside tsubst_pack_expansion. Just
8870                return the local specialization (which will be a single
8871                parm).  */
8872             tree spec = retrieve_local_specialization (t);
8873             if (spec 
8874                 && TREE_CODE (spec) == PARM_DECL
8875                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8876               RETURN (spec);
8877
8878             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8879                the parameters in this function parameter pack.  */
8880             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8881                                                     complain, in_decl);
8882             if (TREE_CODE (expanded_types) == TREE_VEC)
8883               {
8884                 len = TREE_VEC_LENGTH (expanded_types);
8885
8886                 /* Zero-length parameter packs are boring. Just substitute
8887                    into the chain.  */
8888                 if (len == 0)
8889                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
8890                                   TREE_CHAIN (t)));
8891               }
8892             else
8893               {
8894                 /* All we did was update the type. Make a note of that.  */
8895                 type = expanded_types;
8896                 expanded_types = NULL_TREE;
8897               }
8898           }
8899
8900         /* Loop through all of the parameter's we'll build. When T is
8901            a function parameter pack, LEN is the number of expanded
8902            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8903         r = NULL_TREE;
8904         for (i = 0; i < len; ++i)
8905           {
8906             prev_r = r;
8907             r = copy_node (t);
8908             if (DECL_TEMPLATE_PARM_P (t))
8909               SET_DECL_TEMPLATE_PARM_P (r);
8910
8911             /* An argument of a function parameter pack is not a parameter
8912                pack.  */
8913             FUNCTION_PARAMETER_PACK_P (r) = false;
8914
8915             if (expanded_types)
8916               /* We're on the Ith parameter of the function parameter
8917                  pack.  */
8918               {
8919                 /* Get the Ith type.  */
8920                 type = TREE_VEC_ELT (expanded_types, i);
8921
8922                 if (DECL_NAME (r))
8923                   /* Rename the parameter to include the index.  */
8924                   DECL_NAME (r) =
8925                     make_ith_pack_parameter_name (DECL_NAME (r), i);
8926               }
8927             else if (!type)
8928               /* We're dealing with a normal parameter.  */
8929               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8930
8931             type = type_decays_to (type);
8932             TREE_TYPE (r) = type;
8933             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8934
8935             if (DECL_INITIAL (r))
8936               {
8937                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
8938                   DECL_INITIAL (r) = TREE_TYPE (r);
8939                 else
8940                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
8941                                              complain, in_decl);
8942               }
8943
8944             DECL_CONTEXT (r) = NULL_TREE;
8945
8946             if (!DECL_TEMPLATE_PARM_P (r))
8947               DECL_ARG_TYPE (r) = type_passed_as (type);
8948
8949             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8950                                             args, complain, in_decl);
8951
8952             /* Keep track of the first new parameter we
8953                generate. That's what will be returned to the
8954                caller.  */
8955             if (!first_r)
8956               first_r = r;
8957
8958             /* Build a proper chain of parameters when substituting
8959                into a function parameter pack.  */
8960             if (prev_r)
8961               TREE_CHAIN (prev_r) = r;
8962           }
8963
8964         if (TREE_CHAIN (t))
8965           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
8966                                    complain, TREE_CHAIN (t));
8967
8968         /* FIRST_R contains the start of the chain we've built.  */
8969         r = first_r;
8970       }
8971       break;
8972
8973     case FIELD_DECL:
8974       {
8975         tree type;
8976
8977         r = copy_decl (t);
8978         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8979         if (type == error_mark_node)
8980           RETURN (error_mark_node);
8981         TREE_TYPE (r) = type;
8982         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8983
8984         /* DECL_INITIAL gives the number of bits in a bit-field.  */
8985         DECL_INITIAL (r)
8986           = tsubst_expr (DECL_INITIAL (t), args,
8987                          complain, in_decl,
8988                          /*integral_constant_expression_p=*/true);
8989         /* We don't have to set DECL_CONTEXT here; it is set by
8990            finish_member_declaration.  */
8991         TREE_CHAIN (r) = NULL_TREE;
8992         if (VOID_TYPE_P (type))
8993           error ("instantiation of %q+D as type %qT", r, type);
8994
8995         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8996                                         args, complain, in_decl);
8997       }
8998       break;
8999
9000     case USING_DECL:
9001       /* We reach here only for member using decls.  */
9002       if (DECL_DEPENDENT_P (t))
9003         {
9004           r = do_class_using_decl
9005             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9006              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9007           if (!r)
9008             r = error_mark_node;
9009           else
9010             {
9011               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9012               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9013             }
9014         }
9015       else
9016         {
9017           r = copy_node (t);
9018           TREE_CHAIN (r) = NULL_TREE;
9019         }
9020       break;
9021
9022     case TYPE_DECL:
9023     case VAR_DECL:
9024       {
9025         tree argvec = NULL_TREE;
9026         tree gen_tmpl = NULL_TREE;
9027         tree spec;
9028         tree tmpl = NULL_TREE;
9029         tree ctx;
9030         tree type = NULL_TREE;
9031         bool local_p;
9032
9033         if (TREE_CODE (t) == TYPE_DECL
9034             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9035           {
9036             /* If this is the canonical decl, we don't have to
9037                mess with instantiations, and often we can't (for
9038                typename, template type parms and such).  Note that
9039                TYPE_NAME is not correct for the above test if
9040                we've copied the type for a typedef.  */
9041             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9042             if (type == error_mark_node)
9043               RETURN (error_mark_node);
9044             r = TYPE_NAME (type);
9045             break;
9046           }
9047
9048         /* Check to see if we already have the specialization we
9049            need.  */
9050         spec = NULL_TREE;
9051         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9052           {
9053             /* T is a static data member or namespace-scope entity.
9054                We have to substitute into namespace-scope variables
9055                (even though such entities are never templates) because
9056                of cases like:
9057                
9058                  template <class T> void f() { extern T t; }
9059
9060                where the entity referenced is not known until
9061                instantiation time.  */
9062             local_p = false;
9063             ctx = DECL_CONTEXT (t);
9064             if (DECL_CLASS_SCOPE_P (t))
9065               {
9066                 ctx = tsubst_aggr_type (ctx, args,
9067                                         complain,
9068                                         in_decl, /*entering_scope=*/1);
9069                 /* If CTX is unchanged, then T is in fact the
9070                    specialization we want.  That situation occurs when
9071                    referencing a static data member within in its own
9072                    class.  We can use pointer equality, rather than
9073                    same_type_p, because DECL_CONTEXT is always
9074                    canonical.  */
9075                 if (ctx == DECL_CONTEXT (t))
9076                   spec = t;
9077               }
9078
9079             if (!spec)
9080               {
9081                 tmpl = DECL_TI_TEMPLATE (t);
9082                 gen_tmpl = most_general_template (tmpl);
9083                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9084                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9085                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9086               }
9087           }
9088         else
9089           {
9090             /* A local variable.  */
9091             local_p = true;
9092             /* Subsequent calls to pushdecl will fill this in.  */
9093             ctx = NULL_TREE;
9094             spec = retrieve_local_specialization (t);
9095           }
9096         /* If we already have the specialization we need, there is
9097            nothing more to do.  */ 
9098         if (spec)
9099           {
9100             r = spec;
9101             break;
9102           }
9103
9104         /* Create a new node for the specialization we need.  */
9105         r = copy_decl (t);
9106         if (type == NULL_TREE)
9107           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9108         if (TREE_CODE (r) == VAR_DECL)
9109           {
9110             /* Even if the original location is out of scope, the
9111                newly substituted one is not.  */
9112             DECL_DEAD_FOR_LOCAL (r) = 0;
9113             DECL_INITIALIZED_P (r) = 0;
9114             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9115             if (type == error_mark_node)
9116               RETURN (error_mark_node);
9117             if (TREE_CODE (type) == FUNCTION_TYPE)
9118               {
9119                 /* It may seem that this case cannot occur, since:
9120
9121                      typedef void f();
9122                      void g() { f x; }
9123
9124                    declares a function, not a variable.  However:
9125       
9126                      typedef void f();
9127                      template <typename T> void g() { T t; }
9128                      template void g<f>();
9129
9130                    is an attempt to declare a variable with function
9131                    type.  */
9132                 error ("variable %qD has function type",
9133                        /* R is not yet sufficiently initialized, so we
9134                           just use its name.  */
9135                        DECL_NAME (r));
9136                 RETURN (error_mark_node);
9137               }
9138             type = complete_type (type);
9139             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9140               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9141             type = check_var_type (DECL_NAME (r), type);
9142
9143             if (DECL_HAS_VALUE_EXPR_P (t))
9144               {
9145                 tree ve = DECL_VALUE_EXPR (t);
9146                 ve = tsubst_expr (ve, args, complain, in_decl,
9147                                   /*constant_expression_p=*/false);
9148                 SET_DECL_VALUE_EXPR (r, ve);
9149               }
9150           }
9151         else if (DECL_SELF_REFERENCE_P (t))
9152           SET_DECL_SELF_REFERENCE_P (r);
9153         TREE_TYPE (r) = type;
9154         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9155         DECL_CONTEXT (r) = ctx;
9156         /* Clear out the mangled name and RTL for the instantiation.  */
9157         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9158         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9159           SET_DECL_RTL (r, NULL_RTX);
9160         /* The initializer must not be expanded until it is required;
9161            see [temp.inst].  */
9162         DECL_INITIAL (r) = NULL_TREE;
9163         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9164           SET_DECL_RTL (r, NULL_RTX);
9165         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9166         if (TREE_CODE (r) == VAR_DECL)
9167           {
9168             /* Possibly limit visibility based on template args.  */
9169             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9170             if (DECL_VISIBILITY_SPECIFIED (t))
9171               {
9172                 DECL_VISIBILITY_SPECIFIED (r) = 0;
9173                 DECL_ATTRIBUTES (r)
9174                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9175               }
9176             determine_visibility (r);
9177           }
9178         /* Preserve a typedef that names a type.  */
9179         else if (TREE_CODE (r) == TYPE_DECL
9180                  && DECL_ORIGINAL_TYPE (t)
9181                  && type != error_mark_node)
9182           {
9183             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
9184                                              args, complain, in_decl);
9185             TREE_TYPE (r) = type = build_variant_type_copy (type);
9186             TYPE_NAME (type) = r;
9187           }
9188
9189         if (!local_p)
9190           {
9191             /* A static data member declaration is always marked
9192                external when it is declared in-class, even if an
9193                initializer is present.  We mimic the non-template
9194                processing here.  */
9195             DECL_EXTERNAL (r) = 1;
9196
9197             register_specialization (r, gen_tmpl, argvec, false, hash);
9198             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
9199             SET_DECL_IMPLICIT_INSTANTIATION (r);
9200           }
9201         else if (cp_unevaluated_operand)
9202           {
9203             /* We're substituting this var in a decltype outside of its
9204                scope, such as for a lambda return type.  Don't add it to
9205                local_specializations, do perform auto deduction.  */
9206             tree auto_node = type_uses_auto (type);
9207             tree init
9208               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9209                              /*constant_expression_p=*/false);
9210
9211             if (auto_node && init && describable_type (init))
9212               {
9213                 type = do_auto_deduction (type, init, auto_node);
9214                 TREE_TYPE (r) = type;
9215               }
9216           }
9217         else
9218           register_local_specialization (r, t);
9219
9220         TREE_CHAIN (r) = NULL_TREE;
9221
9222         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9223                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
9224                                         args, complain, in_decl);
9225         layout_decl (r, 0);
9226       }
9227       break;
9228
9229     default:
9230       gcc_unreachable ();
9231     }
9232 #undef RETURN
9233
9234  out:
9235   /* Restore the file and line information.  */
9236   input_location = saved_loc;
9237
9238   return r;
9239 }
9240
9241 /* Substitute into the ARG_TYPES of a function type.  */
9242
9243 static tree
9244 tsubst_arg_types (tree arg_types,
9245                   tree args,
9246                   tsubst_flags_t complain,
9247                   tree in_decl)
9248 {
9249   tree remaining_arg_types;
9250   tree type = NULL_TREE;
9251   int i = 1;
9252   tree expanded_args = NULL_TREE;
9253   tree default_arg;
9254
9255   if (!arg_types || arg_types == void_list_node)
9256     return arg_types;
9257
9258   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9259                                           args, complain, in_decl);
9260   if (remaining_arg_types == error_mark_node)
9261     return error_mark_node;
9262
9263   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9264     {
9265       /* For a pack expansion, perform substitution on the
9266          entire expression. Later on, we'll handle the arguments
9267          one-by-one.  */
9268       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9269                                             args, complain, in_decl);
9270
9271       if (TREE_CODE (expanded_args) == TREE_VEC)
9272         /* So that we'll spin through the parameters, one by one.  */
9273         i = TREE_VEC_LENGTH (expanded_args);
9274       else
9275         {
9276           /* We only partially substituted into the parameter
9277              pack. Our type is TYPE_PACK_EXPANSION.  */
9278           type = expanded_args;
9279           expanded_args = NULL_TREE;
9280         }
9281     }
9282
9283   while (i > 0) {
9284     --i;
9285     
9286     if (expanded_args)
9287       type = TREE_VEC_ELT (expanded_args, i);
9288     else if (!type)
9289       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9290
9291     if (type == error_mark_node)
9292       return error_mark_node;
9293     if (VOID_TYPE_P (type))
9294       {
9295         if (complain & tf_error)
9296           {
9297             error ("invalid parameter type %qT", type);
9298             if (in_decl)
9299               error ("in declaration %q+D", in_decl);
9300           }
9301         return error_mark_node;
9302     }
9303     
9304     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9305        top-level qualifiers as required.  */
9306     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9307
9308     /* We do not substitute into default arguments here.  The standard
9309        mandates that they be instantiated only when needed, which is
9310        done in build_over_call.  */
9311     default_arg = TREE_PURPOSE (arg_types);
9312
9313     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9314       {
9315         /* We've instantiated a template before its default arguments
9316            have been parsed.  This can happen for a nested template
9317            class, and is not an error unless we require the default
9318            argument in a call of this function.  */
9319         remaining_arg_types = 
9320           tree_cons (default_arg, type, remaining_arg_types);
9321         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9322                        remaining_arg_types);
9323       }
9324     else
9325       remaining_arg_types = 
9326         hash_tree_cons (default_arg, type, remaining_arg_types);
9327   }
9328         
9329   return remaining_arg_types;
9330 }
9331
9332 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9333    *not* handle the exception-specification for FNTYPE, because the
9334    initial substitution of explicitly provided template parameters
9335    during argument deduction forbids substitution into the
9336    exception-specification:
9337
9338      [temp.deduct]
9339
9340      All references in the function type of the function template to  the
9341      corresponding template parameters are replaced by the specified tem-
9342      plate argument values.  If a substitution in a template parameter or
9343      in  the function type of the function template results in an invalid
9344      type, type deduction fails.  [Note: The equivalent  substitution  in
9345      exception specifications is done only when the function is instanti-
9346      ated, at which point a program is  ill-formed  if  the  substitution
9347      results in an invalid type.]  */
9348
9349 static tree
9350 tsubst_function_type (tree t,
9351                       tree args,
9352                       tsubst_flags_t complain,
9353                       tree in_decl)
9354 {
9355   tree return_type;
9356   tree arg_types;
9357   tree fntype;
9358
9359   /* The TYPE_CONTEXT is not used for function/method types.  */
9360   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9361
9362   /* Substitute the return type.  */
9363   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9364   if (return_type == error_mark_node)
9365     return error_mark_node;
9366   /* The standard does not presently indicate that creation of a
9367      function type with an invalid return type is a deduction failure.
9368      However, that is clearly analogous to creating an array of "void"
9369      or a reference to a reference.  This is core issue #486.  */
9370   if (TREE_CODE (return_type) == ARRAY_TYPE
9371       || TREE_CODE (return_type) == FUNCTION_TYPE)
9372     {
9373       if (complain & tf_error)
9374         {
9375           if (TREE_CODE (return_type) == ARRAY_TYPE)
9376             error ("function returning an array");
9377           else
9378             error ("function returning a function");
9379         }
9380       return error_mark_node;
9381     }
9382
9383   /* Substitute the argument types.  */
9384   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9385                                 complain, in_decl);
9386   if (arg_types == error_mark_node)
9387     return error_mark_node;
9388
9389   /* Construct a new type node and return it.  */
9390   if (TREE_CODE (t) == FUNCTION_TYPE)
9391     fntype = build_function_type (return_type, arg_types);
9392   else
9393     {
9394       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9395       if (! MAYBE_CLASS_TYPE_P (r))
9396         {
9397           /* [temp.deduct]
9398
9399              Type deduction may fail for any of the following
9400              reasons:
9401
9402              -- Attempting to create "pointer to member of T" when T
9403              is not a class type.  */
9404           if (complain & tf_error)
9405             error ("creating pointer to member function of non-class type %qT",
9406                       r);
9407           return error_mark_node;
9408         }
9409
9410       fntype = build_method_type_directly (r, return_type,
9411                                            TREE_CHAIN (arg_types));
9412     }
9413   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9414   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9415
9416   return fntype;
9417 }
9418
9419 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9420    ARGS into that specification, and return the substituted
9421    specification.  If there is no specification, return NULL_TREE.  */
9422
9423 static tree
9424 tsubst_exception_specification (tree fntype,
9425                                 tree args,
9426                                 tsubst_flags_t complain,
9427                                 tree in_decl)
9428 {
9429   tree specs;
9430   tree new_specs;
9431
9432   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9433   new_specs = NULL_TREE;
9434   if (specs)
9435     {
9436       if (! TREE_VALUE (specs))
9437         new_specs = specs;
9438       else
9439         while (specs)
9440           {
9441             tree spec;
9442             int i, len = 1;
9443             tree expanded_specs = NULL_TREE;
9444
9445             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9446               {
9447                 /* Expand the pack expansion type.  */
9448                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9449                                                        args, complain,
9450                                                        in_decl);
9451
9452                 if (expanded_specs == error_mark_node)
9453                   return error_mark_node;
9454                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9455                   len = TREE_VEC_LENGTH (expanded_specs);
9456                 else
9457                   {
9458                     /* We're substituting into a member template, so
9459                        we got a TYPE_PACK_EXPANSION back.  Add that
9460                        expansion and move on.  */
9461                     gcc_assert (TREE_CODE (expanded_specs) 
9462                                 == TYPE_PACK_EXPANSION);
9463                     new_specs = add_exception_specifier (new_specs,
9464                                                          expanded_specs,
9465                                                          complain);
9466                     specs = TREE_CHAIN (specs);
9467                     continue;
9468                   }
9469               }
9470
9471             for (i = 0; i < len; ++i)
9472               {
9473                 if (expanded_specs)
9474                   spec = TREE_VEC_ELT (expanded_specs, i);
9475                 else
9476                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9477                 if (spec == error_mark_node)
9478                   return spec;
9479                 new_specs = add_exception_specifier (new_specs, spec, 
9480                                                      complain);
9481               }
9482
9483             specs = TREE_CHAIN (specs);
9484           }
9485     }
9486   return new_specs;
9487 }
9488
9489 /* Take the tree structure T and replace template parameters used
9490    therein with the argument vector ARGS.  IN_DECL is an associated
9491    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9492    Issue error and warning messages under control of COMPLAIN.  Note
9493    that we must be relatively non-tolerant of extensions here, in
9494    order to preserve conformance; if we allow substitutions that
9495    should not be allowed, we may allow argument deductions that should
9496    not succeed, and therefore report ambiguous overload situations
9497    where there are none.  In theory, we could allow the substitution,
9498    but indicate that it should have failed, and allow our caller to
9499    make sure that the right thing happens, but we don't try to do this
9500    yet.
9501
9502    This function is used for dealing with types, decls and the like;
9503    for expressions, use tsubst_expr or tsubst_copy.  */
9504
9505 tree
9506 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9507 {
9508   tree type, r;
9509
9510   if (t == NULL_TREE || t == error_mark_node
9511       || t == integer_type_node
9512       || t == void_type_node
9513       || t == char_type_node
9514       || t == unknown_type_node
9515       || TREE_CODE (t) == NAMESPACE_DECL)
9516     return t;
9517
9518   if (DECL_P (t))
9519     return tsubst_decl (t, args, complain);
9520
9521   if (args == NULL_TREE)
9522     return t;
9523
9524   if (TREE_CODE (t) == IDENTIFIER_NODE)
9525     type = IDENTIFIER_TYPE_VALUE (t);
9526   else
9527     type = TREE_TYPE (t);
9528
9529   gcc_assert (type != unknown_type_node);
9530
9531   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9532      such as attribute aligned.  */
9533   if (TYPE_P (t)
9534       && TYPE_NAME (t)
9535       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9536     {
9537       tree decl = TYPE_NAME (t);
9538       
9539       if (DECL_CLASS_SCOPE_P (decl)
9540           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9541           && uses_template_parms (DECL_CONTEXT (decl)))
9542         {
9543           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9544           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9545           r = retrieve_specialization (tmpl, gen_args, 0);
9546         }
9547       else if (DECL_FUNCTION_SCOPE_P (decl)
9548                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9549                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9550         r = retrieve_local_specialization (decl);
9551       else
9552         /* The typedef is from a non-template context.  */
9553         return t;
9554
9555       if (r)
9556         {
9557           r = TREE_TYPE (r);
9558           r = cp_build_qualified_type_real
9559             (r, cp_type_quals (t) | cp_type_quals (r),
9560              complain | tf_ignore_bad_quals);
9561           return r;
9562         }
9563       /* Else we must be instantiating the typedef, so fall through.  */
9564     }
9565
9566   if (type
9567       && TREE_CODE (t) != TYPENAME_TYPE
9568       && TREE_CODE (t) != IDENTIFIER_NODE
9569       && TREE_CODE (t) != FUNCTION_TYPE
9570       && TREE_CODE (t) != METHOD_TYPE)
9571     type = tsubst (type, args, complain, in_decl);
9572   if (type == error_mark_node)
9573     return error_mark_node;
9574
9575   switch (TREE_CODE (t))
9576     {
9577     case RECORD_TYPE:
9578     case UNION_TYPE:
9579     case ENUMERAL_TYPE:
9580       return tsubst_aggr_type (t, args, complain, in_decl,
9581                                /*entering_scope=*/0);
9582
9583     case ERROR_MARK:
9584     case IDENTIFIER_NODE:
9585     case VOID_TYPE:
9586     case REAL_TYPE:
9587     case COMPLEX_TYPE:
9588     case VECTOR_TYPE:
9589     case BOOLEAN_TYPE:
9590     case INTEGER_CST:
9591     case REAL_CST:
9592     case STRING_CST:
9593       return t;
9594
9595     case INTEGER_TYPE:
9596       if (t == integer_type_node)
9597         return t;
9598
9599       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9600           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9601         return t;
9602
9603       {
9604         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9605
9606         max = tsubst_expr (omax, args, complain, in_decl,
9607                            /*integral_constant_expression_p=*/false);
9608
9609         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9610            needed.  */
9611         if (TREE_CODE (max) == NOP_EXPR
9612             && TREE_SIDE_EFFECTS (omax)
9613             && !TREE_TYPE (max))
9614           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9615
9616         max = fold_decl_constant_value (max);
9617
9618         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9619            with TREE_SIDE_EFFECTS that indicates this is not an integral
9620            constant expression.  */
9621         if (processing_template_decl
9622             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9623           {
9624             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9625             TREE_SIDE_EFFECTS (max) = 1;
9626           }
9627
9628         if (TREE_CODE (max) != INTEGER_CST
9629             && !at_function_scope_p ()
9630             && !TREE_SIDE_EFFECTS (max)
9631             && !value_dependent_expression_p (max))
9632           {
9633             if (complain & tf_error)
9634               error ("array bound is not an integer constant");
9635             return error_mark_node;
9636           }
9637
9638         /* [temp.deduct]
9639
9640            Type deduction may fail for any of the following
9641            reasons:
9642
9643              Attempting to create an array with a size that is
9644              zero or negative.  */
9645         if (integer_zerop (max) && !(complain & tf_error))
9646           /* We must fail if performing argument deduction (as
9647              indicated by the state of complain), so that
9648              another substitution can be found.  */
9649           return error_mark_node;
9650         else if (TREE_CODE (max) == INTEGER_CST
9651                  && INT_CST_LT (max, integer_zero_node))
9652           {
9653             if (complain & tf_error)
9654               error ("creating array with negative size (%qE)", max);
9655
9656             return error_mark_node;
9657           }
9658
9659         return compute_array_index_type (NULL_TREE, max);
9660       }
9661
9662     case TEMPLATE_TYPE_PARM:
9663     case TEMPLATE_TEMPLATE_PARM:
9664     case BOUND_TEMPLATE_TEMPLATE_PARM:
9665     case TEMPLATE_PARM_INDEX:
9666       {
9667         int idx;
9668         int level;
9669         int levels;
9670         tree arg = NULL_TREE;
9671
9672         r = NULL_TREE;
9673
9674         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9675         template_parm_level_and_index (t, &level, &idx); 
9676
9677         levels = TMPL_ARGS_DEPTH (args);
9678         if (level <= levels)
9679           {
9680             arg = TMPL_ARG (args, level, idx);
9681
9682             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9683               /* See through ARGUMENT_PACK_SELECT arguments. */
9684               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9685           }
9686
9687         if (arg == error_mark_node)
9688           return error_mark_node;
9689         else if (arg != NULL_TREE)
9690           {
9691             if (ARGUMENT_PACK_P (arg))
9692               /* If ARG is an argument pack, we don't actually want to
9693                  perform a substitution here, because substitutions
9694                  for argument packs are only done
9695                  element-by-element. We can get to this point when
9696                  substituting the type of a non-type template
9697                  parameter pack, when that type actually contains
9698                  template parameter packs from an outer template, e.g.,
9699
9700                  template<typename... Types> struct A {
9701                    template<Types... Values> struct B { };
9702                  };  */
9703               return t;
9704
9705             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9706               {
9707                 int quals;
9708                 gcc_assert (TYPE_P (arg));
9709
9710                 /* cv-quals from the template are discarded when
9711                    substituting in a function or reference type.  */
9712                 if (TREE_CODE (arg) == FUNCTION_TYPE
9713                     || TREE_CODE (arg) == METHOD_TYPE
9714                     || TREE_CODE (arg) == REFERENCE_TYPE)
9715                   quals = cp_type_quals (arg);
9716                 else
9717                   quals = cp_type_quals (arg) | cp_type_quals (t);
9718                   
9719                 return cp_build_qualified_type_real
9720                   (arg, quals, complain | tf_ignore_bad_quals);
9721               }
9722             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9723               {
9724                 /* We are processing a type constructed from a
9725                    template template parameter.  */
9726                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9727                                       args, complain, in_decl);
9728                 if (argvec == error_mark_node)
9729                   return error_mark_node;
9730
9731                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9732                    are resolving nested-types in the signature of a
9733                    member function templates.  Otherwise ARG is a
9734                    TEMPLATE_DECL and is the real template to be
9735                    instantiated.  */
9736                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9737                   arg = TYPE_NAME (arg);
9738
9739                 r = lookup_template_class (arg,
9740                                            argvec, in_decl,
9741                                            DECL_CONTEXT (arg),
9742                                             /*entering_scope=*/0,
9743                                            complain);
9744                 return cp_build_qualified_type_real
9745                   (r, TYPE_QUALS (t), complain);
9746               }
9747             else
9748               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9749               return arg;
9750           }
9751
9752         if (level == 1)
9753           /* This can happen during the attempted tsubst'ing in
9754              unify.  This means that we don't yet have any information
9755              about the template parameter in question.  */
9756           return t;
9757
9758         /* If we get here, we must have been looking at a parm for a
9759            more deeply nested template.  Make a new version of this
9760            template parameter, but with a lower level.  */
9761         switch (TREE_CODE (t))
9762           {
9763           case TEMPLATE_TYPE_PARM:
9764           case TEMPLATE_TEMPLATE_PARM:
9765           case BOUND_TEMPLATE_TEMPLATE_PARM:
9766             if (cp_type_quals (t))
9767               {
9768                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9769                 r = cp_build_qualified_type_real
9770                   (r, cp_type_quals (t),
9771                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9772                                ? tf_ignore_bad_quals : 0));
9773               }
9774             else
9775               {
9776                 r = copy_type (t);
9777                 TEMPLATE_TYPE_PARM_INDEX (r)
9778                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9779                                                 r, levels, args, complain);
9780                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9781                 TYPE_MAIN_VARIANT (r) = r;
9782                 TYPE_POINTER_TO (r) = NULL_TREE;
9783                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9784
9785                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9786                   /* We have reduced the level of the template
9787                      template parameter, but not the levels of its
9788                      template parameters, so canonical_type_parameter
9789                      will not be able to find the canonical template
9790                      template parameter for this level. Thus, we
9791                      require structural equality checking to compare
9792                      TEMPLATE_TEMPLATE_PARMs. */
9793                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9794                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9795                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9796                 else
9797                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9798
9799                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9800                   {
9801                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9802                                           complain, in_decl);
9803                     if (argvec == error_mark_node)
9804                       return error_mark_node;
9805
9806                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9807                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9808                   }
9809               }
9810             break;
9811
9812           case TEMPLATE_PARM_INDEX:
9813             r = reduce_template_parm_level (t, type, levels, args, complain);
9814             break;
9815
9816           default:
9817             gcc_unreachable ();
9818           }
9819
9820         return r;
9821       }
9822
9823     case TREE_LIST:
9824       {
9825         tree purpose, value, chain;
9826
9827         if (t == void_list_node)
9828           return t;
9829
9830         purpose = TREE_PURPOSE (t);
9831         if (purpose)
9832           {
9833             purpose = tsubst (purpose, args, complain, in_decl);
9834             if (purpose == error_mark_node)
9835               return error_mark_node;
9836           }
9837         value = TREE_VALUE (t);
9838         if (value)
9839           {
9840             value = tsubst (value, args, complain, in_decl);
9841             if (value == error_mark_node)
9842               return error_mark_node;
9843           }
9844         chain = TREE_CHAIN (t);
9845         if (chain && chain != void_type_node)
9846           {
9847             chain = tsubst (chain, args, complain, in_decl);
9848             if (chain == error_mark_node)
9849               return error_mark_node;
9850           }
9851         if (purpose == TREE_PURPOSE (t)
9852             && value == TREE_VALUE (t)
9853             && chain == TREE_CHAIN (t))
9854           return t;
9855         return hash_tree_cons (purpose, value, chain);
9856       }
9857
9858     case TREE_BINFO:
9859       /* We should never be tsubsting a binfo.  */
9860       gcc_unreachable ();
9861
9862     case TREE_VEC:
9863       /* A vector of template arguments.  */
9864       gcc_assert (!type);
9865       return tsubst_template_args (t, args, complain, in_decl);
9866
9867     case POINTER_TYPE:
9868     case REFERENCE_TYPE:
9869       {
9870         enum tree_code code;
9871
9872         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9873           return t;
9874
9875         code = TREE_CODE (t);
9876
9877
9878         /* [temp.deduct]
9879
9880            Type deduction may fail for any of the following
9881            reasons:
9882
9883            -- Attempting to create a pointer to reference type.
9884            -- Attempting to create a reference to a reference type or
9885               a reference to void.
9886
9887           Core issue 106 says that creating a reference to a reference
9888           during instantiation is no longer a cause for failure. We
9889           only enforce this check in strict C++98 mode.  */
9890         if ((TREE_CODE (type) == REFERENCE_TYPE
9891              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9892             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9893           {
9894             static location_t last_loc;
9895
9896             /* We keep track of the last time we issued this error
9897                message to avoid spewing a ton of messages during a
9898                single bad template instantiation.  */
9899             if (complain & tf_error
9900                 && last_loc != input_location)
9901               {
9902                 if (TREE_CODE (type) == VOID_TYPE)
9903                   error ("forming reference to void");
9904                 else
9905                   error ("forming %s to reference type %qT",
9906                          (code == POINTER_TYPE) ? "pointer" : "reference",
9907                          type);
9908                 last_loc = input_location;
9909               }
9910
9911             return error_mark_node;
9912           }
9913         else if (code == POINTER_TYPE)
9914           {
9915             r = build_pointer_type (type);
9916             if (TREE_CODE (type) == METHOD_TYPE)
9917               r = build_ptrmemfunc_type (r);
9918           }
9919         else if (TREE_CODE (type) == REFERENCE_TYPE)
9920           /* In C++0x, during template argument substitution, when there is an
9921              attempt to create a reference to a reference type, reference
9922              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9923
9924              "If a template-argument for a template-parameter T names a type
9925              that is a reference to a type A, an attempt to create the type
9926              'lvalue reference to cv T' creates the type 'lvalue reference to
9927              A,' while an attempt to create the type type rvalue reference to
9928              cv T' creates the type T"
9929           */
9930           r = cp_build_reference_type
9931               (TREE_TYPE (type),
9932                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9933         else
9934           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9935         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9936
9937         if (r != error_mark_node)
9938           /* Will this ever be needed for TYPE_..._TO values?  */
9939           layout_type (r);
9940
9941         return r;
9942       }
9943     case OFFSET_TYPE:
9944       {
9945         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9946         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
9947           {
9948             /* [temp.deduct]
9949
9950                Type deduction may fail for any of the following
9951                reasons:
9952
9953                -- Attempting to create "pointer to member of T" when T
9954                   is not a class type.  */
9955             if (complain & tf_error)
9956               error ("creating pointer to member of non-class type %qT", r);
9957             return error_mark_node;
9958           }
9959         if (TREE_CODE (type) == REFERENCE_TYPE)
9960           {
9961             if (complain & tf_error)
9962               error ("creating pointer to member reference type %qT", type);
9963             return error_mark_node;
9964           }
9965         if (TREE_CODE (type) == VOID_TYPE)
9966           {
9967             if (complain & tf_error)
9968               error ("creating pointer to member of type void");
9969             return error_mark_node;
9970           }
9971         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
9972         if (TREE_CODE (type) == FUNCTION_TYPE)
9973           {
9974             /* The type of the implicit object parameter gets its
9975                cv-qualifiers from the FUNCTION_TYPE. */
9976             tree method_type;
9977             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
9978                                                       cp_type_quals (type));
9979             tree memptr;
9980             method_type = build_method_type_directly (this_type,
9981                                                       TREE_TYPE (type),
9982                                                       TYPE_ARG_TYPES (type));
9983             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
9984             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
9985                                                  complain);
9986           }
9987         else
9988           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
9989                                                TYPE_QUALS (t),
9990                                                complain);
9991       }
9992     case FUNCTION_TYPE:
9993     case METHOD_TYPE:
9994       {
9995         tree fntype;
9996         tree specs;
9997         fntype = tsubst_function_type (t, args, complain, in_decl);
9998         if (fntype == error_mark_node)
9999           return error_mark_node;
10000
10001         /* Substitute the exception specification.  */
10002         specs = tsubst_exception_specification (t, args, complain,
10003                                                 in_decl);
10004         if (specs == error_mark_node)
10005           return error_mark_node;
10006         if (specs)
10007           fntype = build_exception_variant (fntype, specs);
10008         return fntype;
10009       }
10010     case ARRAY_TYPE:
10011       {
10012         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10013         if (domain == error_mark_node)
10014           return error_mark_node;
10015
10016         /* As an optimization, we avoid regenerating the array type if
10017            it will obviously be the same as T.  */
10018         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10019           return t;
10020
10021         /* These checks should match the ones in grokdeclarator.
10022
10023            [temp.deduct]
10024
10025            The deduction may fail for any of the following reasons:
10026
10027            -- Attempting to create an array with an element type that
10028               is void, a function type, or a reference type, or [DR337]
10029               an abstract class type.  */
10030         if (TREE_CODE (type) == VOID_TYPE
10031             || TREE_CODE (type) == FUNCTION_TYPE
10032             || TREE_CODE (type) == REFERENCE_TYPE)
10033           {
10034             if (complain & tf_error)
10035               error ("creating array of %qT", type);
10036             return error_mark_node;
10037           }
10038         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10039           {
10040             if (complain & tf_error)
10041               error ("creating array of %qT, which is an abstract class type",
10042                      type);
10043             return error_mark_node;
10044           }
10045
10046         r = build_cplus_array_type (type, domain);
10047
10048         if (TYPE_USER_ALIGN (t))
10049           {
10050             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10051             TYPE_USER_ALIGN (r) = 1;
10052           }
10053
10054         return r;
10055       }
10056
10057     case PLUS_EXPR:
10058     case MINUS_EXPR:
10059       {
10060         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10061         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10062
10063         if (e1 == error_mark_node || e2 == error_mark_node)
10064           return error_mark_node;
10065
10066         return fold_build2_loc (input_location,
10067                             TREE_CODE (t), TREE_TYPE (t), e1, e2);
10068       }
10069
10070     case NEGATE_EXPR:
10071     case NOP_EXPR:
10072       {
10073         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10074         if (e == error_mark_node)
10075           return error_mark_node;
10076
10077         return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
10078       }
10079
10080     case TYPENAME_TYPE:
10081       {
10082         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10083                                      in_decl, /*entering_scope=*/1);
10084         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10085                               complain, in_decl);
10086
10087         if (ctx == error_mark_node || f == error_mark_node)
10088           return error_mark_node;
10089
10090         if (!MAYBE_CLASS_TYPE_P (ctx))
10091           {
10092             if (complain & tf_error)
10093               error ("%qT is not a class, struct, or union type", ctx);
10094             return error_mark_node;
10095           }
10096         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10097           {
10098             /* Normally, make_typename_type does not require that the CTX
10099                have complete type in order to allow things like:
10100
10101                  template <class T> struct S { typename S<T>::X Y; };
10102
10103                But, such constructs have already been resolved by this
10104                point, so here CTX really should have complete type, unless
10105                it's a partial instantiation.  */
10106             if (!(complain & tf_no_class_instantiations))
10107               ctx = complete_type (ctx);
10108             if (!COMPLETE_TYPE_P (ctx))
10109               {
10110                 if (complain & tf_error)
10111                   cxx_incomplete_type_error (NULL_TREE, ctx);
10112                 return error_mark_node;
10113               }
10114           }
10115
10116         f = make_typename_type (ctx, f, typename_type,
10117                                 (complain & tf_error) | tf_keep_type_decl);
10118         if (f == error_mark_node)
10119           return f;
10120         if (TREE_CODE (f) == TYPE_DECL)
10121           {
10122             complain |= tf_ignore_bad_quals;
10123             f = TREE_TYPE (f);
10124           }
10125
10126         if (TREE_CODE (f) != TYPENAME_TYPE)
10127           {
10128             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10129               error ("%qT resolves to %qT, which is not an enumeration type",
10130                      t, f);
10131             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10132               error ("%qT resolves to %qT, which is is not a class type",
10133                      t, f);
10134           }
10135
10136         return cp_build_qualified_type_real
10137           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10138       }
10139
10140     case UNBOUND_CLASS_TEMPLATE:
10141       {
10142         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10143                                      in_decl, /*entering_scope=*/1);
10144         tree name = TYPE_IDENTIFIER (t);
10145         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10146
10147         if (ctx == error_mark_node || name == error_mark_node)
10148           return error_mark_node;
10149
10150         if (parm_list)
10151           parm_list = tsubst_template_parms (parm_list, args, complain);
10152         return make_unbound_class_template (ctx, name, parm_list, complain);
10153       }
10154
10155     case INDIRECT_REF:
10156     case ADDR_EXPR:
10157     case CALL_EXPR:
10158       gcc_unreachable ();
10159
10160     case ARRAY_REF:
10161       {
10162         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10163         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10164                                /*integral_constant_expression_p=*/false);
10165         if (e1 == error_mark_node || e2 == error_mark_node)
10166           return error_mark_node;
10167
10168         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10169       }
10170
10171     case SCOPE_REF:
10172       {
10173         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10174         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10175         if (e1 == error_mark_node || e2 == error_mark_node)
10176           return error_mark_node;
10177
10178         return build_qualified_name (/*type=*/NULL_TREE,
10179                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10180       }
10181
10182     case TYPEOF_TYPE:
10183       {
10184         tree type;
10185
10186         type = finish_typeof (tsubst_expr 
10187                               (TYPEOF_TYPE_EXPR (t), args,
10188                                complain, in_decl,
10189                                /*integral_constant_expression_p=*/false));
10190         return cp_build_qualified_type_real (type,
10191                                              cp_type_quals (t)
10192                                              | cp_type_quals (type),
10193                                              complain);
10194       }
10195
10196     case DECLTYPE_TYPE:
10197       {
10198         tree type;
10199
10200         ++cp_unevaluated_operand;
10201         ++c_inhibit_evaluation_warnings;
10202
10203         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10204                             complain, in_decl,
10205                             /*integral_constant_expression_p=*/false);
10206
10207         --cp_unevaluated_operand;
10208         --c_inhibit_evaluation_warnings;
10209
10210         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10211           type = lambda_capture_field_type (type);
10212         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10213           type = lambda_return_type (type);
10214         else
10215           type = finish_decltype_type
10216             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10217         return cp_build_qualified_type_real (type,
10218                                              cp_type_quals (t)
10219                                              | cp_type_quals (type),
10220                                              complain);
10221       }
10222
10223     case TYPE_ARGUMENT_PACK:
10224     case NONTYPE_ARGUMENT_PACK:
10225       {
10226         tree r = TYPE_P (t)
10227           ? cxx_make_type (TREE_CODE (t))
10228           : make_node (TREE_CODE (t));
10229         tree packed_out = 
10230           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10231                                 args,
10232                                 complain,
10233                                 in_decl);
10234         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10235
10236         /* For template nontype argument packs, also substitute into
10237            the type.  */
10238         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10239           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10240
10241         return r;
10242       }
10243       break;
10244
10245     default:
10246       sorry ("use of %qs in template",
10247              tree_code_name [(int) TREE_CODE (t)]);
10248       return error_mark_node;
10249     }
10250 }
10251
10252 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10253    type of the expression on the left-hand side of the "." or "->"
10254    operator.  */
10255
10256 static tree
10257 tsubst_baselink (tree baselink, tree object_type,
10258                  tree args, tsubst_flags_t complain, tree in_decl)
10259 {
10260     tree name;
10261     tree qualifying_scope;
10262     tree fns;
10263     tree optype;
10264     tree template_args = 0;
10265     bool template_id_p = false;
10266
10267     /* A baselink indicates a function from a base class.  Both the
10268        BASELINK_ACCESS_BINFO and the base class referenced may
10269        indicate bases of the template class, rather than the
10270        instantiated class.  In addition, lookups that were not
10271        ambiguous before may be ambiguous now.  Therefore, we perform
10272        the lookup again.  */
10273     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10274     qualifying_scope = tsubst (qualifying_scope, args,
10275                                complain, in_decl);
10276     fns = BASELINK_FUNCTIONS (baselink);
10277     optype = BASELINK_OPTYPE (baselink);
10278     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10279       {
10280         template_id_p = true;
10281         template_args = TREE_OPERAND (fns, 1);
10282         fns = TREE_OPERAND (fns, 0);
10283         if (template_args)
10284           template_args = tsubst_template_args (template_args, args,
10285                                                 complain, in_decl);
10286       }
10287     name = DECL_NAME (get_first_fn (fns));
10288     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10289
10290     /* If lookup found a single function, mark it as used at this
10291        point.  (If it lookup found multiple functions the one selected
10292        later by overload resolution will be marked as used at that
10293        point.)  */
10294     if (BASELINK_P (baselink))
10295       fns = BASELINK_FUNCTIONS (baselink);
10296     if (!template_id_p && !really_overloaded_fn (fns))
10297       mark_used (OVL_CURRENT (fns));
10298
10299     /* Add back the template arguments, if present.  */
10300     if (BASELINK_P (baselink) && template_id_p)
10301       BASELINK_FUNCTIONS (baselink)
10302         = build_nt (TEMPLATE_ID_EXPR,
10303                     BASELINK_FUNCTIONS (baselink),
10304                     template_args);
10305     /* Update the conversion operator type.  */
10306     BASELINK_OPTYPE (baselink) 
10307       = tsubst (optype, args, complain, in_decl);
10308
10309     if (!object_type)
10310       object_type = current_class_type;
10311     return adjust_result_of_qualified_name_lookup (baselink,
10312                                                    qualifying_scope,
10313                                                    object_type);
10314 }
10315
10316 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10317    true if the qualified-id will be a postfix-expression in-and-of
10318    itself; false if more of the postfix-expression follows the
10319    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10320    of "&".  */
10321
10322 static tree
10323 tsubst_qualified_id (tree qualified_id, tree args,
10324                      tsubst_flags_t complain, tree in_decl,
10325                      bool done, bool address_p)
10326 {
10327   tree expr;
10328   tree scope;
10329   tree name;
10330   bool is_template;
10331   tree template_args;
10332
10333   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10334
10335   /* Figure out what name to look up.  */
10336   name = TREE_OPERAND (qualified_id, 1);
10337   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10338     {
10339       is_template = true;
10340       template_args = TREE_OPERAND (name, 1);
10341       if (template_args)
10342         template_args = tsubst_template_args (template_args, args,
10343                                               complain, in_decl);
10344       name = TREE_OPERAND (name, 0);
10345     }
10346   else
10347     {
10348       is_template = false;
10349       template_args = NULL_TREE;
10350     }
10351
10352   /* Substitute into the qualifying scope.  When there are no ARGS, we
10353      are just trying to simplify a non-dependent expression.  In that
10354      case the qualifying scope may be dependent, and, in any case,
10355      substituting will not help.  */
10356   scope = TREE_OPERAND (qualified_id, 0);
10357   if (args)
10358     {
10359       scope = tsubst (scope, args, complain, in_decl);
10360       expr = tsubst_copy (name, args, complain, in_decl);
10361     }
10362   else
10363     expr = name;
10364
10365   if (dependent_type_p (scope))
10366     {
10367       tree type = NULL_TREE;
10368       if (DECL_P (expr) && !dependent_scope_p (scope))
10369         type = TREE_TYPE (expr);
10370       return build_qualified_name (type, scope, expr,
10371                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10372     }
10373
10374   if (!BASELINK_P (name) && !DECL_P (expr))
10375     {
10376       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10377         {
10378           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10379           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10380             {
10381               error ("qualifying type %qT does not match destructor name ~%qT",
10382                      scope, TREE_OPERAND (expr, 0));
10383               expr = error_mark_node;
10384             }
10385           else
10386             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10387                                           /*is_type_p=*/0, false);
10388         }
10389       else
10390         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10391       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10392                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10393         {
10394           if (complain & tf_error)
10395             {
10396               error ("dependent-name %qE is parsed as a non-type, but "
10397                      "instantiation yields a type", qualified_id);
10398               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10399             }
10400           return error_mark_node;
10401         }
10402     }
10403
10404   if (DECL_P (expr))
10405     {
10406       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10407                                            scope);
10408       /* Remember that there was a reference to this entity.  */
10409       mark_used (expr);
10410     }
10411
10412   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10413     {
10414       if (complain & tf_error)
10415         qualified_name_lookup_error (scope,
10416                                      TREE_OPERAND (qualified_id, 1),
10417                                      expr, input_location);
10418       return error_mark_node;
10419     }
10420
10421   if (is_template)
10422     expr = lookup_template_function (expr, template_args);
10423
10424   if (expr == error_mark_node && complain & tf_error)
10425     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10426                                  expr, input_location);
10427   else if (TYPE_P (scope))
10428     {
10429       expr = (adjust_result_of_qualified_name_lookup
10430               (expr, scope, current_class_type));
10431       expr = (finish_qualified_id_expr
10432               (scope, expr, done, address_p,
10433                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10434                /*template_arg_p=*/false));
10435     }
10436
10437   /* Expressions do not generally have reference type.  */
10438   if (TREE_CODE (expr) != SCOPE_REF
10439       /* However, if we're about to form a pointer-to-member, we just
10440          want the referenced member referenced.  */
10441       && TREE_CODE (expr) != OFFSET_REF)
10442     expr = convert_from_reference (expr);
10443
10444   return expr;
10445 }
10446
10447 /* Like tsubst, but deals with expressions.  This function just replaces
10448    template parms; to finish processing the resultant expression, use
10449    tsubst_expr.  */
10450
10451 static tree
10452 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10453 {
10454   enum tree_code code;
10455   tree r;
10456
10457   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10458     return t;
10459
10460   code = TREE_CODE (t);
10461
10462   switch (code)
10463     {
10464     case PARM_DECL:
10465       r = retrieve_local_specialization (t);
10466
10467       if (r == NULL)
10468         {
10469           tree c;
10470           /* This can happen for a parameter name used later in a function
10471              declaration (such as in a late-specified return type).  Just
10472              make a dummy decl, since it's only used for its type.  */
10473           gcc_assert (cp_unevaluated_operand != 0);
10474           /* We copy T because want to tsubst the PARM_DECL only,
10475              not the following PARM_DECLs that are chained to T.  */
10476           c = copy_node (t);
10477           r = tsubst_decl (c, args, complain);
10478           /* Give it the template pattern as its context; its true context
10479              hasn't been instantiated yet and this is good enough for
10480              mangling.  */
10481           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10482         }
10483       
10484       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10485         r = ARGUMENT_PACK_SELECT_ARG (r);
10486       mark_used (r);
10487       return r;
10488
10489     case CONST_DECL:
10490       {
10491         tree enum_type;
10492         tree v;
10493
10494         if (DECL_TEMPLATE_PARM_P (t))
10495           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10496         /* There is no need to substitute into namespace-scope
10497            enumerators.  */
10498         if (DECL_NAMESPACE_SCOPE_P (t))
10499           return t;
10500         /* If ARGS is NULL, then T is known to be non-dependent.  */
10501         if (args == NULL_TREE)
10502           return integral_constant_value (t);
10503
10504         /* Unfortunately, we cannot just call lookup_name here.
10505            Consider:
10506
10507              template <int I> int f() {
10508              enum E { a = I };
10509              struct S { void g() { E e = a; } };
10510              };
10511
10512            When we instantiate f<7>::S::g(), say, lookup_name is not
10513            clever enough to find f<7>::a.  */
10514         enum_type
10515           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10516                               /*entering_scope=*/0);
10517
10518         for (v = TYPE_VALUES (enum_type);
10519              v != NULL_TREE;
10520              v = TREE_CHAIN (v))
10521           if (TREE_PURPOSE (v) == DECL_NAME (t))
10522             return TREE_VALUE (v);
10523
10524           /* We didn't find the name.  That should never happen; if
10525              name-lookup found it during preliminary parsing, we
10526              should find it again here during instantiation.  */
10527         gcc_unreachable ();
10528       }
10529       return t;
10530
10531     case FIELD_DECL:
10532       if (DECL_CONTEXT (t))
10533         {
10534           tree ctx;
10535
10536           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10537                                   /*entering_scope=*/1);
10538           if (ctx != DECL_CONTEXT (t))
10539             {
10540               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10541               if (!r)
10542                 {
10543                   if (complain & tf_error)
10544                     error ("using invalid field %qD", t);
10545                   return error_mark_node;
10546                 }
10547               return r;
10548             }
10549         }
10550
10551       return t;
10552
10553     case VAR_DECL:
10554     case FUNCTION_DECL:
10555       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10556           || local_variable_p (t))
10557         t = tsubst (t, args, complain, in_decl);
10558       mark_used (t);
10559       return t;
10560
10561     case BASELINK:
10562       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10563
10564     case TEMPLATE_DECL:
10565       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10566         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10567                        args, complain, in_decl);
10568       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10569         return tsubst (t, args, complain, in_decl);
10570       else if (DECL_CLASS_SCOPE_P (t)
10571                && uses_template_parms (DECL_CONTEXT (t)))
10572         {
10573           /* Template template argument like the following example need
10574              special treatment:
10575
10576                template <template <class> class TT> struct C {};
10577                template <class T> struct D {
10578                  template <class U> struct E {};
10579                  C<E> c;                                // #1
10580                };
10581                D<int> d;                                // #2
10582
10583              We are processing the template argument `E' in #1 for
10584              the template instantiation #2.  Originally, `E' is a
10585              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10586              have to substitute this with one having context `D<int>'.  */
10587
10588           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10589           return lookup_field (context, DECL_NAME(t), 0, false);
10590         }
10591       else
10592         /* Ordinary template template argument.  */
10593         return t;
10594
10595     case CAST_EXPR:
10596     case REINTERPRET_CAST_EXPR:
10597     case CONST_CAST_EXPR:
10598     case STATIC_CAST_EXPR:
10599     case DYNAMIC_CAST_EXPR:
10600     case NOP_EXPR:
10601       return build1
10602         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10603          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10604
10605     case SIZEOF_EXPR:
10606       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10607         {
10608           /* We only want to compute the number of arguments.  */
10609           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10610                                                 complain, in_decl);
10611           int len = 0;
10612
10613           if (TREE_CODE (expanded) == TREE_VEC)
10614             len = TREE_VEC_LENGTH (expanded);
10615
10616           if (expanded == error_mark_node)
10617             return error_mark_node;
10618           else if (PACK_EXPANSION_P (expanded)
10619                    || (TREE_CODE (expanded) == TREE_VEC
10620                        && len > 0
10621                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10622             {
10623               if (TREE_CODE (expanded) == TREE_VEC)
10624                 expanded = TREE_VEC_ELT (expanded, len - 1);
10625
10626               if (TYPE_P (expanded))
10627                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10628                                                    complain & tf_error);
10629               else
10630                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10631                                                    complain & tf_error);
10632             }
10633           else
10634             return build_int_cst (size_type_node, len);
10635         }
10636       /* Fall through */
10637
10638     case INDIRECT_REF:
10639     case NEGATE_EXPR:
10640     case TRUTH_NOT_EXPR:
10641     case BIT_NOT_EXPR:
10642     case ADDR_EXPR:
10643     case UNARY_PLUS_EXPR:      /* Unary + */
10644     case ALIGNOF_EXPR:
10645     case ARROW_EXPR:
10646     case THROW_EXPR:
10647     case TYPEID_EXPR:
10648     case REALPART_EXPR:
10649     case IMAGPART_EXPR:
10650       return build1
10651         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10652          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10653
10654     case COMPONENT_REF:
10655       {
10656         tree object;
10657         tree name;
10658
10659         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10660         name = TREE_OPERAND (t, 1);
10661         if (TREE_CODE (name) == BIT_NOT_EXPR)
10662           {
10663             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10664                                 complain, in_decl);
10665             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10666           }
10667         else if (TREE_CODE (name) == SCOPE_REF
10668                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10669           {
10670             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10671                                      complain, in_decl);
10672             name = TREE_OPERAND (name, 1);
10673             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10674                                 complain, in_decl);
10675             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10676             name = build_qualified_name (/*type=*/NULL_TREE,
10677                                          base, name,
10678                                          /*template_p=*/false);
10679           }
10680         else if (TREE_CODE (name) == BASELINK)
10681           name = tsubst_baselink (name,
10682                                   non_reference (TREE_TYPE (object)),
10683                                   args, complain,
10684                                   in_decl);
10685         else
10686           name = tsubst_copy (name, args, complain, in_decl);
10687         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10688       }
10689
10690     case PLUS_EXPR:
10691     case MINUS_EXPR:
10692     case MULT_EXPR:
10693     case TRUNC_DIV_EXPR:
10694     case CEIL_DIV_EXPR:
10695     case FLOOR_DIV_EXPR:
10696     case ROUND_DIV_EXPR:
10697     case EXACT_DIV_EXPR:
10698     case BIT_AND_EXPR:
10699     case BIT_IOR_EXPR:
10700     case BIT_XOR_EXPR:
10701     case TRUNC_MOD_EXPR:
10702     case FLOOR_MOD_EXPR:
10703     case TRUTH_ANDIF_EXPR:
10704     case TRUTH_ORIF_EXPR:
10705     case TRUTH_AND_EXPR:
10706     case TRUTH_OR_EXPR:
10707     case RSHIFT_EXPR:
10708     case LSHIFT_EXPR:
10709     case RROTATE_EXPR:
10710     case LROTATE_EXPR:
10711     case EQ_EXPR:
10712     case NE_EXPR:
10713     case MAX_EXPR:
10714     case MIN_EXPR:
10715     case LE_EXPR:
10716     case GE_EXPR:
10717     case LT_EXPR:
10718     case GT_EXPR:
10719     case COMPOUND_EXPR:
10720     case DOTSTAR_EXPR:
10721     case MEMBER_REF:
10722     case PREDECREMENT_EXPR:
10723     case PREINCREMENT_EXPR:
10724     case POSTDECREMENT_EXPR:
10725     case POSTINCREMENT_EXPR:
10726       return build_nt
10727         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10728          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10729
10730     case SCOPE_REF:
10731       return build_qualified_name (/*type=*/NULL_TREE,
10732                                    tsubst_copy (TREE_OPERAND (t, 0),
10733                                                 args, complain, in_decl),
10734                                    tsubst_copy (TREE_OPERAND (t, 1),
10735                                                 args, complain, in_decl),
10736                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10737
10738     case ARRAY_REF:
10739       return build_nt
10740         (ARRAY_REF,
10741          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10742          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10743          NULL_TREE, NULL_TREE);
10744
10745     case CALL_EXPR:
10746       {
10747         int n = VL_EXP_OPERAND_LENGTH (t);
10748         tree result = build_vl_exp (CALL_EXPR, n);
10749         int i;
10750         for (i = 0; i < n; i++)
10751           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10752                                              complain, in_decl);
10753         return result;
10754       }
10755
10756     case COND_EXPR:
10757     case MODOP_EXPR:
10758     case PSEUDO_DTOR_EXPR:
10759       {
10760         r = build_nt
10761           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10762            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10763            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10764         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10765         return r;
10766       }
10767
10768     case NEW_EXPR:
10769       {
10770         r = build_nt
10771         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10772          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10773          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10774         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10775         return r;
10776       }
10777
10778     case DELETE_EXPR:
10779       {
10780         r = build_nt
10781         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10782          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10783         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10784         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10785         return r;
10786       }
10787
10788     case TEMPLATE_ID_EXPR:
10789       {
10790         /* Substituted template arguments */
10791         tree fn = TREE_OPERAND (t, 0);
10792         tree targs = TREE_OPERAND (t, 1);
10793
10794         fn = tsubst_copy (fn, args, complain, in_decl);
10795         if (targs)
10796           targs = tsubst_template_args (targs, args, complain, in_decl);
10797
10798         return lookup_template_function (fn, targs);
10799       }
10800
10801     case TREE_LIST:
10802       {
10803         tree purpose, value, chain;
10804
10805         if (t == void_list_node)
10806           return t;
10807
10808         purpose = TREE_PURPOSE (t);
10809         if (purpose)
10810           purpose = tsubst_copy (purpose, args, complain, in_decl);
10811         value = TREE_VALUE (t);
10812         if (value)
10813           value = tsubst_copy (value, args, complain, in_decl);
10814         chain = TREE_CHAIN (t);
10815         if (chain && chain != void_type_node)
10816           chain = tsubst_copy (chain, args, complain, in_decl);
10817         if (purpose == TREE_PURPOSE (t)
10818             && value == TREE_VALUE (t)
10819             && chain == TREE_CHAIN (t))
10820           return t;
10821         return tree_cons (purpose, value, chain);
10822       }
10823
10824     case RECORD_TYPE:
10825     case UNION_TYPE:
10826     case ENUMERAL_TYPE:
10827     case INTEGER_TYPE:
10828     case TEMPLATE_TYPE_PARM:
10829     case TEMPLATE_TEMPLATE_PARM:
10830     case BOUND_TEMPLATE_TEMPLATE_PARM:
10831     case TEMPLATE_PARM_INDEX:
10832     case POINTER_TYPE:
10833     case REFERENCE_TYPE:
10834     case OFFSET_TYPE:
10835     case FUNCTION_TYPE:
10836     case METHOD_TYPE:
10837     case ARRAY_TYPE:
10838     case TYPENAME_TYPE:
10839     case UNBOUND_CLASS_TEMPLATE:
10840     case TYPEOF_TYPE:
10841     case DECLTYPE_TYPE:
10842     case TYPE_DECL:
10843       return tsubst (t, args, complain, in_decl);
10844
10845     case IDENTIFIER_NODE:
10846       if (IDENTIFIER_TYPENAME_P (t))
10847         {
10848           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10849           return mangle_conv_op_name_for_type (new_type);
10850         }
10851       else
10852         return t;
10853
10854     case CONSTRUCTOR:
10855       /* This is handled by tsubst_copy_and_build.  */
10856       gcc_unreachable ();
10857
10858     case VA_ARG_EXPR:
10859       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10860                                           in_decl),
10861                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10862
10863     case CLEANUP_POINT_EXPR:
10864       /* We shouldn't have built any of these during initial template
10865          generation.  Instead, they should be built during instantiation
10866          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10867       gcc_unreachable ();
10868
10869     case OFFSET_REF:
10870       mark_used (TREE_OPERAND (t, 1));
10871       return t;
10872
10873     case EXPR_PACK_EXPANSION:
10874       error ("invalid use of pack expansion expression");
10875       return error_mark_node;
10876
10877     case NONTYPE_ARGUMENT_PACK:
10878       error ("use %<...%> to expand argument pack");
10879       return error_mark_node;
10880
10881     default:
10882       return t;
10883     }
10884 }
10885
10886 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10887
10888 static tree
10889 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10890                     tree in_decl)
10891 {
10892   tree new_clauses = NULL, nc, oc;
10893
10894   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10895     {
10896       nc = copy_node (oc);
10897       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10898       new_clauses = nc;
10899
10900       switch (OMP_CLAUSE_CODE (nc))
10901         {
10902         case OMP_CLAUSE_LASTPRIVATE:
10903           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
10904             {
10905               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
10906               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
10907                            in_decl, /*integral_constant_expression_p=*/false);
10908               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
10909                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
10910             }
10911           /* FALLTHRU */
10912         case OMP_CLAUSE_PRIVATE:
10913         case OMP_CLAUSE_SHARED:
10914         case OMP_CLAUSE_FIRSTPRIVATE:
10915         case OMP_CLAUSE_REDUCTION:
10916         case OMP_CLAUSE_COPYIN:
10917         case OMP_CLAUSE_COPYPRIVATE:
10918         case OMP_CLAUSE_IF:
10919         case OMP_CLAUSE_NUM_THREADS:
10920         case OMP_CLAUSE_SCHEDULE:
10921         case OMP_CLAUSE_COLLAPSE:
10922           OMP_CLAUSE_OPERAND (nc, 0)
10923             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10924                            in_decl, /*integral_constant_expression_p=*/false);
10925           break;
10926         case OMP_CLAUSE_NOWAIT:
10927         case OMP_CLAUSE_ORDERED:
10928         case OMP_CLAUSE_DEFAULT:
10929         case OMP_CLAUSE_UNTIED:
10930           break;
10931         default:
10932           gcc_unreachable ();
10933         }
10934     }
10935
10936   return finish_omp_clauses (nreverse (new_clauses));
10937 }
10938
10939 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10940
10941 static tree
10942 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10943                           tree in_decl)
10944 {
10945 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10946
10947   tree purpose, value, chain;
10948
10949   if (t == NULL)
10950     return t;
10951
10952   if (TREE_CODE (t) != TREE_LIST)
10953     return tsubst_copy_and_build (t, args, complain, in_decl,
10954                                   /*function_p=*/false,
10955                                   /*integral_constant_expression_p=*/false);
10956
10957   if (t == void_list_node)
10958     return t;
10959
10960   purpose = TREE_PURPOSE (t);
10961   if (purpose)
10962     purpose = RECUR (purpose);
10963   value = TREE_VALUE (t);
10964   if (value && TREE_CODE (value) != LABEL_DECL)
10965     value = RECUR (value);
10966   chain = TREE_CHAIN (t);
10967   if (chain && chain != void_type_node)
10968     chain = RECUR (chain);
10969   return tree_cons (purpose, value, chain);
10970 #undef RECUR
10971 }
10972
10973 /* Substitute one OMP_FOR iterator.  */
10974
10975 static void
10976 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
10977                          tree condv, tree incrv, tree *clauses,
10978                          tree args, tsubst_flags_t complain, tree in_decl,
10979                          bool integral_constant_expression_p)
10980 {
10981 #define RECUR(NODE)                             \
10982   tsubst_expr ((NODE), args, complain, in_decl, \
10983                integral_constant_expression_p)
10984   tree decl, init, cond, incr, auto_node;
10985
10986   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
10987   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10988   decl = RECUR (TREE_OPERAND (init, 0));
10989   init = TREE_OPERAND (init, 1);
10990   auto_node = type_uses_auto (TREE_TYPE (decl));
10991   if (auto_node && init)
10992     {
10993       tree init_expr = init;
10994       if (TREE_CODE (init_expr) == DECL_EXPR)
10995         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
10996       init_expr = RECUR (init_expr);
10997       TREE_TYPE (decl)
10998         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
10999     }
11000   gcc_assert (!type_dependent_expression_p (decl));
11001
11002   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11003     {
11004       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11005       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11006       if (TREE_CODE (incr) == MODIFY_EXPR)
11007         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11008                                     RECUR (TREE_OPERAND (incr, 1)),
11009                                     complain);
11010       else
11011         incr = RECUR (incr);
11012       TREE_VEC_ELT (declv, i) = decl;
11013       TREE_VEC_ELT (initv, i) = init;
11014       TREE_VEC_ELT (condv, i) = cond;
11015       TREE_VEC_ELT (incrv, i) = incr;
11016       return;
11017     }
11018
11019   if (init && TREE_CODE (init) != DECL_EXPR)
11020     {
11021       tree c;
11022       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11023         {
11024           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11025                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11026               && OMP_CLAUSE_DECL (c) == decl)
11027             break;
11028           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11029                    && OMP_CLAUSE_DECL (c) == decl)
11030             error ("iteration variable %qD should not be firstprivate", decl);
11031           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11032                    && OMP_CLAUSE_DECL (c) == decl)
11033             error ("iteration variable %qD should not be reduction", decl);
11034         }
11035       if (c == NULL)
11036         {
11037           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11038           OMP_CLAUSE_DECL (c) = decl;
11039           c = finish_omp_clauses (c);
11040           if (c)
11041             {
11042               OMP_CLAUSE_CHAIN (c) = *clauses;
11043               *clauses = c;
11044             }
11045         }
11046     }
11047   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11048   if (COMPARISON_CLASS_P (cond))
11049     cond = build2 (TREE_CODE (cond), boolean_type_node,
11050                    RECUR (TREE_OPERAND (cond, 0)),
11051                    RECUR (TREE_OPERAND (cond, 1)));
11052   else
11053     cond = RECUR (cond);
11054   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11055   switch (TREE_CODE (incr))
11056     {
11057     case PREINCREMENT_EXPR:
11058     case PREDECREMENT_EXPR:
11059     case POSTINCREMENT_EXPR:
11060     case POSTDECREMENT_EXPR:
11061       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11062                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11063       break;
11064     case MODIFY_EXPR:
11065       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11066           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11067         {
11068           tree rhs = TREE_OPERAND (incr, 1);
11069           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11070                          RECUR (TREE_OPERAND (incr, 0)),
11071                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11072                                  RECUR (TREE_OPERAND (rhs, 0)),
11073                                  RECUR (TREE_OPERAND (rhs, 1))));
11074         }
11075       else
11076         incr = RECUR (incr);
11077       break;
11078     case MODOP_EXPR:
11079       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11080           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11081         {
11082           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11083           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11084                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11085                                  TREE_TYPE (decl), lhs,
11086                                  RECUR (TREE_OPERAND (incr, 2))));
11087         }
11088       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11089                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11090                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11091         {
11092           tree rhs = TREE_OPERAND (incr, 2);
11093           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11094                          RECUR (TREE_OPERAND (incr, 0)),
11095                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11096                                  RECUR (TREE_OPERAND (rhs, 0)),
11097                                  RECUR (TREE_OPERAND (rhs, 1))));
11098         }
11099       else
11100         incr = RECUR (incr);
11101       break;
11102     default:
11103       incr = RECUR (incr);
11104       break;
11105     }
11106
11107   TREE_VEC_ELT (declv, i) = decl;
11108   TREE_VEC_ELT (initv, i) = init;
11109   TREE_VEC_ELT (condv, i) = cond;
11110   TREE_VEC_ELT (incrv, i) = incr;
11111 #undef RECUR
11112 }
11113
11114 /* Like tsubst_copy for expressions, etc. but also does semantic
11115    processing.  */
11116
11117 static tree
11118 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11119              bool integral_constant_expression_p)
11120 {
11121 #define RECUR(NODE)                             \
11122   tsubst_expr ((NODE), args, complain, in_decl, \
11123                integral_constant_expression_p)
11124
11125   tree stmt, tmp;
11126
11127   if (t == NULL_TREE || t == error_mark_node)
11128     return t;
11129
11130   if (EXPR_HAS_LOCATION (t))
11131     input_location = EXPR_LOCATION (t);
11132   if (STATEMENT_CODE_P (TREE_CODE (t)))
11133     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11134
11135   switch (TREE_CODE (t))
11136     {
11137     case STATEMENT_LIST:
11138       {
11139         tree_stmt_iterator i;
11140         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11141           RECUR (tsi_stmt (i));
11142         break;
11143       }
11144
11145     case CTOR_INITIALIZER:
11146       finish_mem_initializers (tsubst_initializer_list
11147                                (TREE_OPERAND (t, 0), args));
11148       break;
11149
11150     case RETURN_EXPR:
11151       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11152       break;
11153
11154     case EXPR_STMT:
11155       tmp = RECUR (EXPR_STMT_EXPR (t));
11156       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11157         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11158       else
11159         finish_expr_stmt (tmp);
11160       break;
11161
11162     case USING_STMT:
11163       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11164       break;
11165
11166     case DECL_EXPR:
11167       {
11168         tree decl;
11169         tree init;
11170
11171         decl = DECL_EXPR_DECL (t);
11172         if (TREE_CODE (decl) == LABEL_DECL)
11173           finish_label_decl (DECL_NAME (decl));
11174         else if (TREE_CODE (decl) == USING_DECL)
11175           {
11176             tree scope = USING_DECL_SCOPE (decl);
11177             tree name = DECL_NAME (decl);
11178             tree decl;
11179
11180             scope = RECUR (scope);
11181             decl = lookup_qualified_name (scope, name,
11182                                           /*is_type_p=*/false,
11183                                           /*complain=*/false);
11184             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11185               qualified_name_lookup_error (scope, name, decl, input_location);
11186             else
11187               do_local_using_decl (decl, scope, name);
11188           }
11189         else
11190           {
11191             init = DECL_INITIAL (decl);
11192             decl = tsubst (decl, args, complain, in_decl);
11193             if (decl != error_mark_node)
11194               {
11195                 /* By marking the declaration as instantiated, we avoid
11196                    trying to instantiate it.  Since instantiate_decl can't
11197                    handle local variables, and since we've already done
11198                    all that needs to be done, that's the right thing to
11199                    do.  */
11200                 if (TREE_CODE (decl) == VAR_DECL)
11201                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11202                 if (TREE_CODE (decl) == VAR_DECL
11203                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11204                   /* Anonymous aggregates are a special case.  */
11205                   finish_anon_union (decl);
11206                 else
11207                   {
11208                     maybe_push_decl (decl);
11209                     if (TREE_CODE (decl) == VAR_DECL
11210                         && DECL_PRETTY_FUNCTION_P (decl))
11211                       {
11212                         /* For __PRETTY_FUNCTION__ we have to adjust the
11213                            initializer.  */
11214                         const char *const name
11215                           = cxx_printable_name (current_function_decl, 2);
11216                         init = cp_fname_init (name, &TREE_TYPE (decl));
11217                       }
11218                     else
11219                       {
11220                         tree t = RECUR (init);
11221
11222                         if (init && !t)
11223                           /* If we had an initializer but it
11224                              instantiated to nothing,
11225                              value-initialize the object.  This will
11226                              only occur when the initializer was a
11227                              pack expansion where the parameter packs
11228                              used in that expansion were of length
11229                              zero.  */
11230                           init = build_value_init (TREE_TYPE (decl));
11231                         else
11232                           init = t;
11233                       }
11234
11235                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11236                   }
11237               }
11238           }
11239
11240         /* A DECL_EXPR can also be used as an expression, in the condition
11241            clause of an if/for/while construct.  */
11242         return decl;
11243       }
11244
11245     case FOR_STMT:
11246       stmt = begin_for_stmt ();
11247                           RECUR (FOR_INIT_STMT (t));
11248       finish_for_init_stmt (stmt);
11249       tmp = RECUR (FOR_COND (t));
11250       finish_for_cond (tmp, stmt);
11251       tmp = RECUR (FOR_EXPR (t));
11252       finish_for_expr (tmp, stmt);
11253       RECUR (FOR_BODY (t));
11254       finish_for_stmt (stmt);
11255       break;
11256
11257     case WHILE_STMT:
11258       stmt = begin_while_stmt ();
11259       tmp = RECUR (WHILE_COND (t));
11260       finish_while_stmt_cond (tmp, stmt);
11261       RECUR (WHILE_BODY (t));
11262       finish_while_stmt (stmt);
11263       break;
11264
11265     case DO_STMT:
11266       stmt = begin_do_stmt ();
11267       RECUR (DO_BODY (t));
11268       finish_do_body (stmt);
11269       tmp = RECUR (DO_COND (t));
11270       finish_do_stmt (tmp, stmt);
11271       break;
11272
11273     case IF_STMT:
11274       stmt = begin_if_stmt ();
11275       tmp = RECUR (IF_COND (t));
11276       finish_if_stmt_cond (tmp, stmt);
11277       RECUR (THEN_CLAUSE (t));
11278       finish_then_clause (stmt);
11279
11280       if (ELSE_CLAUSE (t))
11281         {
11282           begin_else_clause (stmt);
11283           RECUR (ELSE_CLAUSE (t));
11284           finish_else_clause (stmt);
11285         }
11286
11287       finish_if_stmt (stmt);
11288       break;
11289
11290     case BIND_EXPR:
11291       if (BIND_EXPR_BODY_BLOCK (t))
11292         stmt = begin_function_body ();
11293       else
11294         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11295                                     ? BCS_TRY_BLOCK : 0);
11296
11297       RECUR (BIND_EXPR_BODY (t));
11298
11299       if (BIND_EXPR_BODY_BLOCK (t))
11300         finish_function_body (stmt);
11301       else
11302         finish_compound_stmt (stmt);
11303       break;
11304
11305     case BREAK_STMT:
11306       finish_break_stmt ();
11307       break;
11308
11309     case CONTINUE_STMT:
11310       finish_continue_stmt ();
11311       break;
11312
11313     case SWITCH_STMT:
11314       stmt = begin_switch_stmt ();
11315       tmp = RECUR (SWITCH_STMT_COND (t));
11316       finish_switch_cond (tmp, stmt);
11317       RECUR (SWITCH_STMT_BODY (t));
11318       finish_switch_stmt (stmt);
11319       break;
11320
11321     case CASE_LABEL_EXPR:
11322       finish_case_label (EXPR_LOCATION (t),
11323                          RECUR (CASE_LOW (t)),
11324                          RECUR (CASE_HIGH (t)));
11325       break;
11326
11327     case LABEL_EXPR:
11328       {
11329         tree decl = LABEL_EXPR_LABEL (t);
11330         tree label;
11331
11332         label = finish_label_stmt (DECL_NAME (decl));
11333         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11334           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11335       }
11336       break;
11337
11338     case GOTO_EXPR:
11339       tmp = GOTO_DESTINATION (t);
11340       if (TREE_CODE (tmp) != LABEL_DECL)
11341         /* Computed goto's must be tsubst'd into.  On the other hand,
11342            non-computed gotos must not be; the identifier in question
11343            will have no binding.  */
11344         tmp = RECUR (tmp);
11345       else
11346         tmp = DECL_NAME (tmp);
11347       finish_goto_stmt (tmp);
11348       break;
11349
11350     case ASM_EXPR:
11351       tmp = finish_asm_stmt
11352         (ASM_VOLATILE_P (t),
11353          RECUR (ASM_STRING (t)),
11354          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11355          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11356          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11357          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11358       {
11359         tree asm_expr = tmp;
11360         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11361           asm_expr = TREE_OPERAND (asm_expr, 0);
11362         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11363       }
11364       break;
11365
11366     case TRY_BLOCK:
11367       if (CLEANUP_P (t))
11368         {
11369           stmt = begin_try_block ();
11370           RECUR (TRY_STMTS (t));
11371           finish_cleanup_try_block (stmt);
11372           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11373         }
11374       else
11375         {
11376           tree compound_stmt = NULL_TREE;
11377
11378           if (FN_TRY_BLOCK_P (t))
11379             stmt = begin_function_try_block (&compound_stmt);
11380           else
11381             stmt = begin_try_block ();
11382
11383           RECUR (TRY_STMTS (t));
11384
11385           if (FN_TRY_BLOCK_P (t))
11386             finish_function_try_block (stmt);
11387           else
11388             finish_try_block (stmt);
11389
11390           RECUR (TRY_HANDLERS (t));
11391           if (FN_TRY_BLOCK_P (t))
11392             finish_function_handler_sequence (stmt, compound_stmt);
11393           else
11394             finish_handler_sequence (stmt);
11395         }
11396       break;
11397
11398     case HANDLER:
11399       {
11400         tree decl = HANDLER_PARMS (t);
11401
11402         if (decl)
11403           {
11404             decl = tsubst (decl, args, complain, in_decl);
11405             /* Prevent instantiate_decl from trying to instantiate
11406                this variable.  We've already done all that needs to be
11407                done.  */
11408             if (decl != error_mark_node)
11409               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11410           }
11411         stmt = begin_handler ();
11412         finish_handler_parms (decl, stmt);
11413         RECUR (HANDLER_BODY (t));
11414         finish_handler (stmt);
11415       }
11416       break;
11417
11418     case TAG_DEFN:
11419       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11420       break;
11421
11422     case STATIC_ASSERT:
11423       {
11424         tree condition = 
11425           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11426                        args,
11427                        complain, in_decl,
11428                        /*integral_constant_expression_p=*/true);
11429         finish_static_assert (condition,
11430                               STATIC_ASSERT_MESSAGE (t),
11431                               STATIC_ASSERT_SOURCE_LOCATION (t),
11432                               /*member_p=*/false);
11433       }
11434       break;
11435
11436     case OMP_PARALLEL:
11437       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11438                                 args, complain, in_decl);
11439       stmt = begin_omp_parallel ();
11440       RECUR (OMP_PARALLEL_BODY (t));
11441       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11442         = OMP_PARALLEL_COMBINED (t);
11443       break;
11444
11445     case OMP_TASK:
11446       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11447                                 args, complain, in_decl);
11448       stmt = begin_omp_task ();
11449       RECUR (OMP_TASK_BODY (t));
11450       finish_omp_task (tmp, stmt);
11451       break;
11452
11453     case OMP_FOR:
11454       {
11455         tree clauses, body, pre_body;
11456         tree declv, initv, condv, incrv;
11457         int i;
11458
11459         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11460                                       args, complain, in_decl);
11461         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11462         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11463         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11464         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11465
11466         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11467           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11468                                    &clauses, args, complain, in_decl,
11469                                    integral_constant_expression_p);
11470
11471         stmt = begin_omp_structured_block ();
11472
11473         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11474           if (TREE_VEC_ELT (initv, i) == NULL
11475               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11476             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11477           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11478             {
11479               tree init = RECUR (TREE_VEC_ELT (initv, i));
11480               gcc_assert (init == TREE_VEC_ELT (declv, i));
11481               TREE_VEC_ELT (initv, i) = NULL_TREE;
11482             }
11483           else
11484             {
11485               tree decl_expr = TREE_VEC_ELT (initv, i);
11486               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11487               gcc_assert (init != NULL);
11488               TREE_VEC_ELT (initv, i) = RECUR (init);
11489               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11490               RECUR (decl_expr);
11491               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11492             }
11493
11494         pre_body = push_stmt_list ();
11495         RECUR (OMP_FOR_PRE_BODY (t));
11496         pre_body = pop_stmt_list (pre_body);
11497
11498         body = push_stmt_list ();
11499         RECUR (OMP_FOR_BODY (t));
11500         body = pop_stmt_list (body);
11501
11502         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11503                             body, pre_body, clauses);
11504
11505         add_stmt (finish_omp_structured_block (stmt));
11506       }
11507       break;
11508
11509     case OMP_SECTIONS:
11510     case OMP_SINGLE:
11511       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11512       stmt = push_stmt_list ();
11513       RECUR (OMP_BODY (t));
11514       stmt = pop_stmt_list (stmt);
11515
11516       t = copy_node (t);
11517       OMP_BODY (t) = stmt;
11518       OMP_CLAUSES (t) = tmp;
11519       add_stmt (t);
11520       break;
11521
11522     case OMP_SECTION:
11523     case OMP_CRITICAL:
11524     case OMP_MASTER:
11525     case OMP_ORDERED:
11526       stmt = push_stmt_list ();
11527       RECUR (OMP_BODY (t));
11528       stmt = pop_stmt_list (stmt);
11529
11530       t = copy_node (t);
11531       OMP_BODY (t) = stmt;
11532       add_stmt (t);
11533       break;
11534
11535     case OMP_ATOMIC:
11536       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11537       {
11538         tree op1 = TREE_OPERAND (t, 1);
11539         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11540         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11541         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11542       }
11543       break;
11544
11545     case EXPR_PACK_EXPANSION:
11546       error ("invalid use of pack expansion expression");
11547       return error_mark_node;
11548
11549     case NONTYPE_ARGUMENT_PACK:
11550       error ("use %<...%> to expand argument pack");
11551       return error_mark_node;
11552
11553     default:
11554       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11555
11556       return tsubst_copy_and_build (t, args, complain, in_decl,
11557                                     /*function_p=*/false,
11558                                     integral_constant_expression_p);
11559     }
11560
11561   return NULL_TREE;
11562 #undef RECUR
11563 }
11564
11565 /* T is a postfix-expression that is not being used in a function
11566    call.  Return the substituted version of T.  */
11567
11568 static tree
11569 tsubst_non_call_postfix_expression (tree t, tree args,
11570                                     tsubst_flags_t complain,
11571                                     tree in_decl)
11572 {
11573   if (TREE_CODE (t) == SCOPE_REF)
11574     t = tsubst_qualified_id (t, args, complain, in_decl,
11575                              /*done=*/false, /*address_p=*/false);
11576   else
11577     t = tsubst_copy_and_build (t, args, complain, in_decl,
11578                                /*function_p=*/false,
11579                                /*integral_constant_expression_p=*/false);
11580
11581   return t;
11582 }
11583
11584 /* Like tsubst but deals with expressions and performs semantic
11585    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11586
11587 tree
11588 tsubst_copy_and_build (tree t,
11589                        tree args,
11590                        tsubst_flags_t complain,
11591                        tree in_decl,
11592                        bool function_p,
11593                        bool integral_constant_expression_p)
11594 {
11595 #define RECUR(NODE)                                             \
11596   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11597                          /*function_p=*/false,                  \
11598                          integral_constant_expression_p)
11599
11600   tree op1;
11601
11602   if (t == NULL_TREE || t == error_mark_node)
11603     return t;
11604
11605   switch (TREE_CODE (t))
11606     {
11607     case USING_DECL:
11608       t = DECL_NAME (t);
11609       /* Fall through.  */
11610     case IDENTIFIER_NODE:
11611       {
11612         tree decl;
11613         cp_id_kind idk;
11614         bool non_integral_constant_expression_p;
11615         const char *error_msg;
11616
11617         if (IDENTIFIER_TYPENAME_P (t))
11618           {
11619             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11620             t = mangle_conv_op_name_for_type (new_type);
11621           }
11622
11623         /* Look up the name.  */
11624         decl = lookup_name (t);
11625
11626         /* By convention, expressions use ERROR_MARK_NODE to indicate
11627            failure, not NULL_TREE.  */
11628         if (decl == NULL_TREE)
11629           decl = error_mark_node;
11630
11631         decl = finish_id_expression (t, decl, NULL_TREE,
11632                                      &idk,
11633                                      integral_constant_expression_p,
11634                                      /*allow_non_integral_constant_expression_p=*/false,
11635                                      &non_integral_constant_expression_p,
11636                                      /*template_p=*/false,
11637                                      /*done=*/true,
11638                                      /*address_p=*/false,
11639                                      /*template_arg_p=*/false,
11640                                      &error_msg,
11641                                      input_location);
11642         if (error_msg)
11643           error (error_msg);
11644         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11645           decl = unqualified_name_lookup_error (decl);
11646         return decl;
11647       }
11648
11649     case TEMPLATE_ID_EXPR:
11650       {
11651         tree object;
11652         tree templ = RECUR (TREE_OPERAND (t, 0));
11653         tree targs = TREE_OPERAND (t, 1);
11654
11655         if (targs)
11656           targs = tsubst_template_args (targs, args, complain, in_decl);
11657
11658         if (TREE_CODE (templ) == COMPONENT_REF)
11659           {
11660             object = TREE_OPERAND (templ, 0);
11661             templ = TREE_OPERAND (templ, 1);
11662           }
11663         else
11664           object = NULL_TREE;
11665         templ = lookup_template_function (templ, targs);
11666
11667         if (object)
11668           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11669                          object, templ, NULL_TREE);
11670         else
11671           return baselink_for_fns (templ);
11672       }
11673
11674     case INDIRECT_REF:
11675       {
11676         tree r = RECUR (TREE_OPERAND (t, 0));
11677
11678         if (REFERENCE_REF_P (t))
11679           {
11680             /* A type conversion to reference type will be enclosed in
11681                such an indirect ref, but the substitution of the cast
11682                will have also added such an indirect ref.  */
11683             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11684               r = convert_from_reference (r);
11685           }
11686         else
11687           r = build_x_indirect_ref (r, "unary *", complain);
11688         return r;
11689       }
11690
11691     case NOP_EXPR:
11692       return build_nop
11693         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11694          RECUR (TREE_OPERAND (t, 0)));
11695
11696     case CAST_EXPR:
11697     case REINTERPRET_CAST_EXPR:
11698     case CONST_CAST_EXPR:
11699     case DYNAMIC_CAST_EXPR:
11700     case STATIC_CAST_EXPR:
11701       {
11702         tree type;
11703         tree op;
11704
11705         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11706         if (integral_constant_expression_p
11707             && !cast_valid_in_integral_constant_expression_p (type))
11708           {
11709             if (complain & tf_error)
11710               error ("a cast to a type other than an integral or "
11711                      "enumeration type cannot appear in a constant-expression");
11712             return error_mark_node; 
11713           }
11714
11715         op = RECUR (TREE_OPERAND (t, 0));
11716
11717         switch (TREE_CODE (t))
11718           {
11719           case CAST_EXPR:
11720             return build_functional_cast (type, op, complain);
11721           case REINTERPRET_CAST_EXPR:
11722             return build_reinterpret_cast (type, op, complain);
11723           case CONST_CAST_EXPR:
11724             return build_const_cast (type, op, complain);
11725           case DYNAMIC_CAST_EXPR:
11726             return build_dynamic_cast (type, op, complain);
11727           case STATIC_CAST_EXPR:
11728             return build_static_cast (type, op, complain);
11729           default:
11730             gcc_unreachable ();
11731           }
11732       }
11733
11734     case POSTDECREMENT_EXPR:
11735     case POSTINCREMENT_EXPR:
11736       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11737                                                 args, complain, in_decl);
11738       return build_x_unary_op (TREE_CODE (t), op1, complain);
11739
11740     case PREDECREMENT_EXPR:
11741     case PREINCREMENT_EXPR:
11742     case NEGATE_EXPR:
11743     case BIT_NOT_EXPR:
11744     case ABS_EXPR:
11745     case TRUTH_NOT_EXPR:
11746     case UNARY_PLUS_EXPR:  /* Unary + */
11747     case REALPART_EXPR:
11748     case IMAGPART_EXPR:
11749       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11750                                complain);
11751
11752     case ADDR_EXPR:
11753       op1 = TREE_OPERAND (t, 0);
11754       if (TREE_CODE (op1) == SCOPE_REF)
11755         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11756                                    /*done=*/true, /*address_p=*/true);
11757       else
11758         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11759                                                   in_decl);
11760       if (TREE_CODE (op1) == LABEL_DECL)
11761         return finish_label_address_expr (DECL_NAME (op1),
11762                                           EXPR_LOCATION (op1));
11763       return build_x_unary_op (ADDR_EXPR, op1, complain);
11764
11765     case PLUS_EXPR:
11766     case MINUS_EXPR:
11767     case MULT_EXPR:
11768     case TRUNC_DIV_EXPR:
11769     case CEIL_DIV_EXPR:
11770     case FLOOR_DIV_EXPR:
11771     case ROUND_DIV_EXPR:
11772     case EXACT_DIV_EXPR:
11773     case BIT_AND_EXPR:
11774     case BIT_IOR_EXPR:
11775     case BIT_XOR_EXPR:
11776     case TRUNC_MOD_EXPR:
11777     case FLOOR_MOD_EXPR:
11778     case TRUTH_ANDIF_EXPR:
11779     case TRUTH_ORIF_EXPR:
11780     case TRUTH_AND_EXPR:
11781     case TRUTH_OR_EXPR:
11782     case RSHIFT_EXPR:
11783     case LSHIFT_EXPR:
11784     case RROTATE_EXPR:
11785     case LROTATE_EXPR:
11786     case EQ_EXPR:
11787     case NE_EXPR:
11788     case MAX_EXPR:
11789     case MIN_EXPR:
11790     case LE_EXPR:
11791     case GE_EXPR:
11792     case LT_EXPR:
11793     case GT_EXPR:
11794     case MEMBER_REF:
11795     case DOTSTAR_EXPR:
11796       return build_x_binary_op
11797         (TREE_CODE (t),
11798          RECUR (TREE_OPERAND (t, 0)),
11799          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11800           ? ERROR_MARK
11801           : TREE_CODE (TREE_OPERAND (t, 0))),
11802          RECUR (TREE_OPERAND (t, 1)),
11803          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11804           ? ERROR_MARK
11805           : TREE_CODE (TREE_OPERAND (t, 1))),
11806          /*overloaded_p=*/NULL,
11807          complain);
11808
11809     case SCOPE_REF:
11810       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11811                                   /*address_p=*/false);
11812     case ARRAY_REF:
11813       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11814                                                 args, complain, in_decl);
11815       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11816
11817     case SIZEOF_EXPR:
11818       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11819         return tsubst_copy (t, args, complain, in_decl);
11820       /* Fall through */
11821       
11822     case ALIGNOF_EXPR:
11823       op1 = TREE_OPERAND (t, 0);
11824       if (!args)
11825         {
11826           /* When there are no ARGS, we are trying to evaluate a
11827              non-dependent expression from the parser.  Trying to do
11828              the substitutions may not work.  */
11829           if (!TYPE_P (op1))
11830             op1 = TREE_TYPE (op1);
11831         }
11832       else
11833         {
11834           ++cp_unevaluated_operand;
11835           ++c_inhibit_evaluation_warnings;
11836           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11837                                        /*function_p=*/false,
11838                                        /*integral_constant_expression_p=*/false);
11839           --cp_unevaluated_operand;
11840           --c_inhibit_evaluation_warnings;
11841         }
11842       if (TYPE_P (op1))
11843         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11844                                            complain & tf_error);
11845       else
11846         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11847                                            complain & tf_error);
11848
11849     case MODOP_EXPR:
11850       {
11851         tree r = build_x_modify_expr
11852           (RECUR (TREE_OPERAND (t, 0)),
11853            TREE_CODE (TREE_OPERAND (t, 1)),
11854            RECUR (TREE_OPERAND (t, 2)),
11855            complain);
11856         /* TREE_NO_WARNING must be set if either the expression was
11857            parenthesized or it uses an operator such as >>= rather
11858            than plain assignment.  In the former case, it was already
11859            set and must be copied.  In the latter case,
11860            build_x_modify_expr sets it and it must not be reset
11861            here.  */
11862         if (TREE_NO_WARNING (t))
11863           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11864         return r;
11865       }
11866
11867     case ARROW_EXPR:
11868       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11869                                                 args, complain, in_decl);
11870       /* Remember that there was a reference to this entity.  */
11871       if (DECL_P (op1))
11872         mark_used (op1);
11873       return build_x_arrow (op1);
11874
11875     case NEW_EXPR:
11876       {
11877         tree placement = RECUR (TREE_OPERAND (t, 0));
11878         tree init = RECUR (TREE_OPERAND (t, 3));
11879         VEC(tree,gc) *placement_vec;
11880         VEC(tree,gc) *init_vec;
11881         tree ret;
11882
11883         if (placement == NULL_TREE)
11884           placement_vec = NULL;
11885         else
11886           {
11887             placement_vec = make_tree_vector ();
11888             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
11889               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
11890           }
11891
11892         /* If there was an initializer in the original tree, but it
11893            instantiated to an empty list, then we should pass a
11894            non-NULL empty vector to tell build_new that it was an
11895            empty initializer() rather than no initializer.  This can
11896            only happen when the initializer is a pack expansion whose
11897            parameter packs are of length zero.  */
11898         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
11899           init_vec = NULL;
11900         else
11901           {
11902             init_vec = make_tree_vector ();
11903             if (init == void_zero_node)
11904               gcc_assert (init_vec != NULL);
11905             else
11906               {
11907                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
11908                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
11909               }
11910           }
11911
11912         ret = build_new (&placement_vec,
11913                          RECUR (TREE_OPERAND (t, 1)),
11914                          RECUR (TREE_OPERAND (t, 2)),
11915                          &init_vec,
11916                          NEW_EXPR_USE_GLOBAL (t),
11917                          complain);
11918
11919         if (placement_vec != NULL)
11920           release_tree_vector (placement_vec);
11921         if (init_vec != NULL)
11922           release_tree_vector (init_vec);
11923
11924         return ret;
11925       }
11926
11927     case DELETE_EXPR:
11928      return delete_sanity
11929        (RECUR (TREE_OPERAND (t, 0)),
11930         RECUR (TREE_OPERAND (t, 1)),
11931         DELETE_EXPR_USE_VEC (t),
11932         DELETE_EXPR_USE_GLOBAL (t));
11933
11934     case COMPOUND_EXPR:
11935       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
11936                                     RECUR (TREE_OPERAND (t, 1)),
11937                                     complain);
11938
11939     case CALL_EXPR:
11940       {
11941         tree function;
11942         VEC(tree,gc) *call_args;
11943         unsigned int nargs, i;
11944         bool qualified_p;
11945         bool koenig_p;
11946         tree ret;
11947
11948         function = CALL_EXPR_FN (t);
11949         /* When we parsed the expression,  we determined whether or
11950            not Koenig lookup should be performed.  */
11951         koenig_p = KOENIG_LOOKUP_P (t);
11952         if (TREE_CODE (function) == SCOPE_REF)
11953           {
11954             qualified_p = true;
11955             function = tsubst_qualified_id (function, args, complain, in_decl,
11956                                             /*done=*/false,
11957                                             /*address_p=*/false);
11958           }
11959         else
11960           {
11961             if (TREE_CODE (function) == COMPONENT_REF)
11962               {
11963                 tree op = TREE_OPERAND (function, 1);
11964
11965                 qualified_p = (TREE_CODE (op) == SCOPE_REF
11966                                || (BASELINK_P (op)
11967                                    && BASELINK_QUALIFIED_P (op)));
11968               }
11969             else
11970               qualified_p = false;
11971
11972             function = tsubst_copy_and_build (function, args, complain,
11973                                               in_decl,
11974                                               !qualified_p,
11975                                               integral_constant_expression_p);
11976
11977             if (BASELINK_P (function))
11978               qualified_p = true;
11979           }
11980
11981         nargs = call_expr_nargs (t);
11982         call_args = make_tree_vector ();
11983         for (i = 0; i < nargs; ++i)
11984           {
11985             tree arg = CALL_EXPR_ARG (t, i);
11986
11987             if (!PACK_EXPANSION_P (arg))
11988               VEC_safe_push (tree, gc, call_args,
11989                              RECUR (CALL_EXPR_ARG (t, i)));
11990             else
11991               {
11992                 /* Expand the pack expansion and push each entry onto
11993                    CALL_ARGS.  */
11994                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
11995                 if (TREE_CODE (arg) == TREE_VEC)
11996                   {
11997                     unsigned int len, j;
11998
11999                     len = TREE_VEC_LENGTH (arg);
12000                     for (j = 0; j < len; ++j)
12001                       {
12002                         tree value = TREE_VEC_ELT (arg, j);
12003                         if (value != NULL_TREE)
12004                           value = convert_from_reference (value);
12005                         VEC_safe_push (tree, gc, call_args, value);
12006                       }
12007                   }
12008                 else
12009                   {
12010                     /* A partial substitution.  Add one entry.  */
12011                     VEC_safe_push (tree, gc, call_args, arg);
12012                   }
12013               }
12014           }
12015
12016         /* We do not perform argument-dependent lookup if normal
12017            lookup finds a non-function, in accordance with the
12018            expected resolution of DR 218.  */
12019         if (koenig_p
12020             && ((is_overloaded_fn (function)
12021                  /* If lookup found a member function, the Koenig lookup is
12022                     not appropriate, even if an unqualified-name was used
12023                     to denote the function.  */
12024                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12025                 || TREE_CODE (function) == IDENTIFIER_NODE)
12026             /* Only do this when substitution turns a dependent call
12027                into a non-dependent call.  */
12028             && type_dependent_expression_p_push (t)
12029             && !any_type_dependent_arguments_p (call_args))
12030           function = perform_koenig_lookup (function, call_args);
12031
12032         if (TREE_CODE (function) == IDENTIFIER_NODE)
12033           {
12034             unqualified_name_lookup_error (function);
12035             release_tree_vector (call_args);
12036             return error_mark_node;
12037           }
12038
12039         /* Remember that there was a reference to this entity.  */
12040         if (DECL_P (function))
12041           mark_used (function);
12042
12043         if (TREE_CODE (function) == OFFSET_REF)
12044           ret = build_offset_ref_call_from_tree (function, &call_args);
12045         else if (TREE_CODE (function) == COMPONENT_REF)
12046           {
12047             if (!BASELINK_P (TREE_OPERAND (function, 1)))
12048               ret = finish_call_expr (function, &call_args,
12049                                        /*disallow_virtual=*/false,
12050                                        /*koenig_p=*/false,
12051                                        complain);
12052             else
12053               ret = (build_new_method_call
12054                       (TREE_OPERAND (function, 0),
12055                        TREE_OPERAND (function, 1),
12056                        &call_args, NULL_TREE,
12057                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12058                        /*fn_p=*/NULL,
12059                        complain));
12060           }
12061         else
12062           ret = finish_call_expr (function, &call_args,
12063                                   /*disallow_virtual=*/qualified_p,
12064                                   koenig_p,
12065                                   complain);
12066
12067         release_tree_vector (call_args);
12068
12069         return ret;
12070       }
12071
12072     case COND_EXPR:
12073       return build_x_conditional_expr
12074         (RECUR (TREE_OPERAND (t, 0)),
12075          RECUR (TREE_OPERAND (t, 1)),
12076          RECUR (TREE_OPERAND (t, 2)),
12077          complain);
12078
12079     case PSEUDO_DTOR_EXPR:
12080       return finish_pseudo_destructor_expr
12081         (RECUR (TREE_OPERAND (t, 0)),
12082          RECUR (TREE_OPERAND (t, 1)),
12083          RECUR (TREE_OPERAND (t, 2)));
12084
12085     case TREE_LIST:
12086       {
12087         tree purpose, value, chain;
12088
12089         if (t == void_list_node)
12090           return t;
12091
12092         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12093             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12094           {
12095             /* We have pack expansions, so expand those and
12096                create a new list out of it.  */
12097             tree purposevec = NULL_TREE;
12098             tree valuevec = NULL_TREE;
12099             tree chain;
12100             int i, len = -1;
12101
12102             /* Expand the argument expressions.  */
12103             if (TREE_PURPOSE (t))
12104               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12105                                                  complain, in_decl);
12106             if (TREE_VALUE (t))
12107               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12108                                                complain, in_decl);
12109
12110             /* Build the rest of the list.  */
12111             chain = TREE_CHAIN (t);
12112             if (chain && chain != void_type_node)
12113               chain = RECUR (chain);
12114
12115             /* Determine the number of arguments.  */
12116             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12117               {
12118                 len = TREE_VEC_LENGTH (purposevec);
12119                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12120               }
12121             else if (TREE_CODE (valuevec) == TREE_VEC)
12122               len = TREE_VEC_LENGTH (valuevec);
12123             else
12124               {
12125                 /* Since we only performed a partial substitution into
12126                    the argument pack, we only return a single list
12127                    node.  */
12128                 if (purposevec == TREE_PURPOSE (t)
12129                     && valuevec == TREE_VALUE (t)
12130                     && chain == TREE_CHAIN (t))
12131                   return t;
12132
12133                 return tree_cons (purposevec, valuevec, chain);
12134               }
12135             
12136             /* Convert the argument vectors into a TREE_LIST */
12137             i = len;
12138             while (i > 0)
12139               {
12140                 /* Grab the Ith values.  */
12141                 i--;
12142                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12143                                      : NULL_TREE;
12144                 value 
12145                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12146                              : NULL_TREE;
12147
12148                 /* Build the list (backwards).  */
12149                 chain = tree_cons (purpose, value, chain);
12150               }
12151
12152             return chain;
12153           }
12154
12155         purpose = TREE_PURPOSE (t);
12156         if (purpose)
12157           purpose = RECUR (purpose);
12158         value = TREE_VALUE (t);
12159         if (value)
12160           value = RECUR (value);
12161         chain = TREE_CHAIN (t);
12162         if (chain && chain != void_type_node)
12163           chain = RECUR (chain);
12164         if (purpose == TREE_PURPOSE (t)
12165             && value == TREE_VALUE (t)
12166             && chain == TREE_CHAIN (t))
12167           return t;
12168         return tree_cons (purpose, value, chain);
12169       }
12170
12171     case COMPONENT_REF:
12172       {
12173         tree object;
12174         tree object_type;
12175         tree member;
12176
12177         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12178                                                      args, complain, in_decl);
12179         /* Remember that there was a reference to this entity.  */
12180         if (DECL_P (object))
12181           mark_used (object);
12182         object_type = TREE_TYPE (object);
12183
12184         member = TREE_OPERAND (t, 1);
12185         if (BASELINK_P (member))
12186           member = tsubst_baselink (member,
12187                                     non_reference (TREE_TYPE (object)),
12188                                     args, complain, in_decl);
12189         else
12190           member = tsubst_copy (member, args, complain, in_decl);
12191         if (member == error_mark_node)
12192           return error_mark_node;
12193
12194         if (object_type && !CLASS_TYPE_P (object_type))
12195           {
12196             if (SCALAR_TYPE_P (object_type))
12197               {
12198                 tree s = NULL_TREE;
12199                 tree dtor = member;
12200
12201                 if (TREE_CODE (dtor) == SCOPE_REF)
12202                   {
12203                     s = TREE_OPERAND (dtor, 0);
12204                     dtor = TREE_OPERAND (dtor, 1);
12205                   }
12206                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12207                   {
12208                     dtor = TREE_OPERAND (dtor, 0);
12209                     if (TYPE_P (dtor))
12210                       return finish_pseudo_destructor_expr (object, s, dtor);
12211                   }
12212               }
12213           }
12214         else if (TREE_CODE (member) == SCOPE_REF
12215                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12216           {
12217             tree tmpl;
12218             tree args;
12219
12220             /* Lookup the template functions now that we know what the
12221                scope is.  */
12222             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12223             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12224             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12225                                             /*is_type_p=*/false,
12226                                             /*complain=*/false);
12227             if (BASELINK_P (member))
12228               {
12229                 BASELINK_FUNCTIONS (member)
12230                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12231                               args);
12232                 member = (adjust_result_of_qualified_name_lookup
12233                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12234                            object_type));
12235               }
12236             else
12237               {
12238                 qualified_name_lookup_error (object_type, tmpl, member,
12239                                              input_location);
12240                 return error_mark_node;
12241               }
12242           }
12243         else if (TREE_CODE (member) == SCOPE_REF
12244                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12245                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12246           {
12247             if (complain & tf_error)
12248               {
12249                 if (TYPE_P (TREE_OPERAND (member, 0)))
12250                   error ("%qT is not a class or namespace",
12251                          TREE_OPERAND (member, 0));
12252                 else
12253                   error ("%qD is not a class or namespace",
12254                          TREE_OPERAND (member, 0));
12255               }
12256             return error_mark_node;
12257           }
12258         else if (TREE_CODE (member) == FIELD_DECL)
12259           return finish_non_static_data_member (member, object, NULL_TREE);
12260
12261         return finish_class_member_access_expr (object, member,
12262                                                 /*template_p=*/false,
12263                                                 complain);
12264       }
12265
12266     case THROW_EXPR:
12267       return build_throw
12268         (RECUR (TREE_OPERAND (t, 0)));
12269
12270     case CONSTRUCTOR:
12271       {
12272         VEC(constructor_elt,gc) *n;
12273         constructor_elt *ce;
12274         unsigned HOST_WIDE_INT idx;
12275         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12276         bool process_index_p;
12277         int newlen;
12278         bool need_copy_p = false;
12279         tree r;
12280
12281         if (type == error_mark_node)
12282           return error_mark_node;
12283
12284         /* digest_init will do the wrong thing if we let it.  */
12285         if (type && TYPE_PTRMEMFUNC_P (type))
12286           return t;
12287
12288         /* We do not want to process the index of aggregate
12289            initializers as they are identifier nodes which will be
12290            looked up by digest_init.  */
12291         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12292
12293         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12294         newlen = VEC_length (constructor_elt, n);
12295         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12296           {
12297             if (ce->index && process_index_p)
12298               ce->index = RECUR (ce->index);
12299
12300             if (PACK_EXPANSION_P (ce->value))
12301               {
12302                 /* Substitute into the pack expansion.  */
12303                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12304                                                   in_decl);
12305
12306                 if (ce->value == error_mark_node)
12307                   ;
12308                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12309                   /* Just move the argument into place.  */
12310                   ce->value = TREE_VEC_ELT (ce->value, 0);
12311                 else
12312                   {
12313                     /* Update the length of the final CONSTRUCTOR
12314                        arguments vector, and note that we will need to
12315                        copy.*/
12316                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12317                     need_copy_p = true;
12318                   }
12319               }
12320             else
12321               ce->value = RECUR (ce->value);
12322           }
12323
12324         if (need_copy_p)
12325           {
12326             VEC(constructor_elt,gc) *old_n = n;
12327
12328             n = VEC_alloc (constructor_elt, gc, newlen);
12329             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
12330                  idx++)
12331               {
12332                 if (TREE_CODE (ce->value) == TREE_VEC)
12333                   {
12334                     int i, len = TREE_VEC_LENGTH (ce->value);
12335                     for (i = 0; i < len; ++i)
12336                       CONSTRUCTOR_APPEND_ELT (n, 0,
12337                                               TREE_VEC_ELT (ce->value, i));
12338                   }
12339                 else
12340                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12341               }
12342           }
12343
12344         r = build_constructor (init_list_type_node, n);
12345         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12346
12347         if (TREE_HAS_CONSTRUCTOR (t))
12348           return finish_compound_literal (type, r);
12349
12350         return r;
12351       }
12352
12353     case TYPEID_EXPR:
12354       {
12355         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12356         if (TYPE_P (operand_0))
12357           return get_typeid (operand_0);
12358         return build_typeid (operand_0);
12359       }
12360
12361     case VAR_DECL:
12362       if (!args)
12363         return t;
12364       /* Fall through */
12365
12366     case PARM_DECL:
12367       {
12368         tree r = tsubst_copy (t, args, complain, in_decl);
12369
12370         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12371           /* If the original type was a reference, we'll be wrapped in
12372              the appropriate INDIRECT_REF.  */
12373           r = convert_from_reference (r);
12374         return r;
12375       }
12376
12377     case VA_ARG_EXPR:
12378       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12379                              tsubst_copy (TREE_TYPE (t), args, complain,
12380                                           in_decl));
12381
12382     case OFFSETOF_EXPR:
12383       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12384
12385     case TRAIT_EXPR:
12386       {
12387         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12388                                   complain, in_decl);
12389
12390         tree type2 = TRAIT_EXPR_TYPE2 (t);
12391         if (type2)
12392           type2 = tsubst_copy (type2, args, complain, in_decl);
12393         
12394         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12395       }
12396
12397     case STMT_EXPR:
12398       {
12399         tree old_stmt_expr = cur_stmt_expr;
12400         tree stmt_expr = begin_stmt_expr ();
12401
12402         cur_stmt_expr = stmt_expr;
12403         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12404                      integral_constant_expression_p);
12405         stmt_expr = finish_stmt_expr (stmt_expr, false);
12406         cur_stmt_expr = old_stmt_expr;
12407
12408         return stmt_expr;
12409       }
12410
12411     case CONST_DECL:
12412       t = tsubst_copy (t, args, complain, in_decl);
12413       /* As in finish_id_expression, we resolve enumeration constants
12414          to their underlying values.  */
12415       if (TREE_CODE (t) == CONST_DECL)
12416         {
12417           used_types_insert (TREE_TYPE (t));
12418           return DECL_INITIAL (t);
12419         }
12420       return t;
12421
12422     case LAMBDA_EXPR:
12423       {
12424         tree r = build_lambda_expr ();
12425
12426         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12427         TREE_TYPE (r) = type;
12428         CLASSTYPE_LAMBDA_EXPR (type) = r;
12429
12430         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12431           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12432         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12433         LAMBDA_EXPR_DISCRIMINATOR (r)
12434           = (LAMBDA_EXPR_DISCRIMINATOR (t));
12435         LAMBDA_EXPR_CAPTURE_LIST (r)
12436           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12437         LAMBDA_EXPR_THIS_CAPTURE (r)
12438           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12439         LAMBDA_EXPR_EXTRA_SCOPE (r)
12440           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12441
12442         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12443         determine_visibility (TYPE_NAME (type));
12444         /* Now that we know visibility, instantiate the type so we have a
12445            declaration of the op() for later calls to lambda_function.  */
12446         complete_type (type);
12447
12448         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12449         if (type)
12450           apply_lambda_return_type (r, type);
12451
12452         return build_lambda_object (r);
12453       }
12454
12455     default:
12456       /* Handle Objective-C++ constructs, if appropriate.  */
12457       {
12458         tree subst
12459           = objcp_tsubst_copy_and_build (t, args, complain,
12460                                          in_decl, /*function_p=*/false);
12461         if (subst)
12462           return subst;
12463       }
12464       return tsubst_copy (t, args, complain, in_decl);
12465     }
12466
12467 #undef RECUR
12468 }
12469
12470 /* Verify that the instantiated ARGS are valid. For type arguments,
12471    make sure that the type is not variably modified. For non-type arguments,
12472    make sure they are constants if they are integral or enumerations.
12473    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12474
12475 static bool
12476 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12477 {
12478   if (ARGUMENT_PACK_P (t))
12479     {
12480       tree vec = ARGUMENT_PACK_ARGS (t);
12481       int len = TREE_VEC_LENGTH (vec);
12482       bool result = false;
12483       int i;
12484
12485       for (i = 0; i < len; ++i)
12486         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12487           result = true;
12488       return result;
12489     }
12490   else if (TYPE_P (t))
12491     {
12492       if (variably_modified_type_p (t, NULL_TREE))
12493         {
12494           if (complain & tf_error)
12495             error ("%qT is a variably modified type", t);
12496           return true;
12497         }
12498     }
12499   /* A non-type argument of integral or enumerated type must be a
12500      constant.  */
12501   else if (TREE_TYPE (t)
12502            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12503            && !TREE_CONSTANT (t))
12504     {
12505       if (complain & tf_error)
12506         error ("integral expression %qE is not constant", t);
12507       return true;
12508     }
12509   return false;
12510 }
12511
12512 static bool
12513 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12514 {
12515   int ix, len = DECL_NTPARMS (tmpl);
12516   bool result = false;
12517
12518   for (ix = 0; ix != len; ix++)
12519     {
12520       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12521         result = true;
12522     }
12523   if (result && (complain & tf_error))
12524     error ("  trying to instantiate %qD", tmpl);
12525   return result;
12526 }
12527
12528 /* Instantiate the indicated variable or function template TMPL with
12529    the template arguments in TARG_PTR.  */
12530
12531 tree
12532 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
12533 {
12534   tree targ_ptr = orig_args;
12535   tree fndecl;
12536   tree gen_tmpl;
12537   tree spec;
12538   HOST_WIDE_INT saved_processing_template_decl;
12539
12540   if (tmpl == error_mark_node)
12541     return error_mark_node;
12542
12543   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12544
12545   /* If this function is a clone, handle it specially.  */
12546   if (DECL_CLONED_FUNCTION_P (tmpl))
12547     {
12548       tree spec;
12549       tree clone;
12550
12551       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
12552          DECL_CLONED_FUNCTION.  */
12553       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
12554                                    targ_ptr, complain);
12555       if (spec == error_mark_node)
12556         return error_mark_node;
12557
12558       /* Look for the clone.  */
12559       FOR_EACH_CLONE (clone, spec)
12560         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12561           return clone;
12562       /* We should always have found the clone by now.  */
12563       gcc_unreachable ();
12564       return NULL_TREE;
12565     }
12566
12567   /* Check to see if we already have this specialization.  */
12568   gen_tmpl = most_general_template (tmpl);
12569   if (tmpl != gen_tmpl)
12570     /* The TMPL is a partial instantiation.  To get a full set of
12571        arguments we must add the arguments used to perform the
12572        partial instantiation.  */
12573     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12574                                             targ_ptr);
12575
12576   /* It would be nice to avoid hashing here and then again in tsubst_decl,
12577      but it doesn't seem to be on the hot path.  */
12578   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
12579
12580   gcc_assert (tmpl == gen_tmpl
12581               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
12582                   == spec)
12583               || fndecl == NULL_TREE);
12584
12585   if (spec != NULL_TREE)
12586     return spec;
12587
12588   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12589                                complain))
12590     return error_mark_node;
12591
12592   /* We are building a FUNCTION_DECL, during which the access of its
12593      parameters and return types have to be checked.  However this
12594      FUNCTION_DECL which is the desired context for access checking
12595      is not built yet.  We solve this chicken-and-egg problem by
12596      deferring all checks until we have the FUNCTION_DECL.  */
12597   push_deferring_access_checks (dk_deferred);
12598
12599   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12600      (because, for example, we have encountered a non-dependent
12601      function call in the body of a template function and must now
12602      determine which of several overloaded functions will be called),
12603      within the instantiation itself we are not processing a
12604      template.  */  
12605   saved_processing_template_decl = processing_template_decl;
12606   processing_template_decl = 0;
12607   /* Substitute template parameters to obtain the specialization.  */
12608   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12609                    targ_ptr, complain, gen_tmpl);
12610   processing_template_decl = saved_processing_template_decl;
12611   if (fndecl == error_mark_node)
12612     return error_mark_node;
12613
12614   /* Now we know the specialization, compute access previously
12615      deferred.  */
12616   push_access_scope (fndecl);
12617
12618   /* Some typedefs referenced from within the template code need to be access
12619      checked at template instantiation time, i.e now. These types were
12620      added to the template at parsing time. Let's get those and perfom
12621      the acces checks then.  */
12622   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
12623   perform_deferred_access_checks ();
12624   pop_access_scope (fndecl);
12625   pop_deferring_access_checks ();
12626
12627   /* The DECL_TI_TEMPLATE should always be the immediate parent
12628      template, not the most general template.  */
12629   DECL_TI_TEMPLATE (fndecl) = tmpl;
12630
12631   /* If we've just instantiated the main entry point for a function,
12632      instantiate all the alternate entry points as well.  We do this
12633      by cloning the instantiation of the main entry point, not by
12634      instantiating the template clones.  */
12635   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
12636     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
12637
12638   return fndecl;
12639 }
12640
12641 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
12642    NARGS elements of the arguments that are being used when calling
12643    it.  TARGS is a vector into which the deduced template arguments
12644    are placed.
12645
12646    Return zero for success, 2 for an incomplete match that doesn't resolve
12647    all the types, and 1 for complete failure.  An error message will be
12648    printed only for an incomplete match.
12649
12650    If FN is a conversion operator, or we are trying to produce a specific
12651    specialization, RETURN_TYPE is the return type desired.
12652
12653    The EXPLICIT_TARGS are explicit template arguments provided via a
12654    template-id.
12655
12656    The parameter STRICT is one of:
12657
12658    DEDUCE_CALL:
12659      We are deducing arguments for a function call, as in
12660      [temp.deduct.call].
12661
12662    DEDUCE_CONV:
12663      We are deducing arguments for a conversion function, as in
12664      [temp.deduct.conv].
12665
12666    DEDUCE_EXACT:
12667      We are deducing arguments when doing an explicit instantiation
12668      as in [temp.explicit], when determining an explicit specialization
12669      as in [temp.expl.spec], or when taking the address of a function
12670      template, as in [temp.deduct.funcaddr].  */
12671
12672 int
12673 fn_type_unification (tree fn,
12674                      tree explicit_targs,
12675                      tree targs,
12676                      const tree *args,
12677                      unsigned int nargs,
12678                      tree return_type,
12679                      unification_kind_t strict,
12680                      int flags)
12681 {
12682   tree parms;
12683   tree fntype;
12684   int result;
12685   bool incomplete_argument_packs_p = false;
12686
12687   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12688
12689   fntype = TREE_TYPE (fn);
12690   if (explicit_targs)
12691     {
12692       /* [temp.deduct]
12693
12694          The specified template arguments must match the template
12695          parameters in kind (i.e., type, nontype, template), and there
12696          must not be more arguments than there are parameters;
12697          otherwise type deduction fails.
12698
12699          Nontype arguments must match the types of the corresponding
12700          nontype template parameters, or must be convertible to the
12701          types of the corresponding nontype parameters as specified in
12702          _temp.arg.nontype_, otherwise type deduction fails.
12703
12704          All references in the function type of the function template
12705          to the corresponding template parameters are replaced by the
12706          specified template argument values.  If a substitution in a
12707          template parameter or in the function type of the function
12708          template results in an invalid type, type deduction fails.  */
12709       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12710       int i, len = TREE_VEC_LENGTH (tparms);
12711       tree converted_args;
12712       bool incomplete = false;
12713
12714       if (explicit_targs == error_mark_node)
12715         return 1;
12716
12717       converted_args
12718         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12719                                   /*require_all_args=*/false,
12720                                   /*use_default_args=*/false));
12721       if (converted_args == error_mark_node)
12722         return 1;
12723
12724       /* Substitute the explicit args into the function type.  This is
12725          necessary so that, for instance, explicitly declared function
12726          arguments can match null pointed constants.  If we were given
12727          an incomplete set of explicit args, we must not do semantic
12728          processing during substitution as we could create partial
12729          instantiations.  */
12730       for (i = 0; i < len; i++)
12731         {
12732           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12733           bool parameter_pack = false;
12734
12735           /* Dig out the actual parm.  */
12736           if (TREE_CODE (parm) == TYPE_DECL
12737               || TREE_CODE (parm) == TEMPLATE_DECL)
12738             {
12739               parm = TREE_TYPE (parm);
12740               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12741             }
12742           else if (TREE_CODE (parm) == PARM_DECL)
12743             {
12744               parm = DECL_INITIAL (parm);
12745               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12746             }
12747
12748           if (parameter_pack)
12749             {
12750               int level, idx;
12751               tree targ;
12752               template_parm_level_and_index (parm, &level, &idx);
12753
12754               /* Mark the argument pack as "incomplete". We could
12755                  still deduce more arguments during unification.  */
12756               targ = TMPL_ARG (converted_args, level, idx);
12757               if (targ)
12758                 {
12759                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12760                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12761                     = ARGUMENT_PACK_ARGS (targ);
12762                 }
12763
12764               /* We have some incomplete argument packs.  */
12765               incomplete_argument_packs_p = true;
12766             }
12767         }
12768
12769       if (incomplete_argument_packs_p)
12770         /* Any substitution is guaranteed to be incomplete if there
12771            are incomplete argument packs, because we can still deduce
12772            more arguments.  */
12773         incomplete = 1;
12774       else
12775         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12776
12777       processing_template_decl += incomplete;
12778       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12779       processing_template_decl -= incomplete;
12780
12781       if (fntype == error_mark_node)
12782         return 1;
12783
12784       /* Place the explicitly specified arguments in TARGS.  */
12785       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12786         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12787     }
12788
12789   /* Never do unification on the 'this' parameter.  */
12790   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12791
12792   if (return_type)
12793     {
12794       tree *new_args;
12795
12796       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12797       new_args = XALLOCAVEC (tree, nargs + 1);
12798       new_args[0] = return_type;
12799       memcpy (new_args + 1, args, nargs * sizeof (tree));
12800       args = new_args;
12801       ++nargs;
12802     }
12803
12804   /* We allow incomplete unification without an error message here
12805      because the standard doesn't seem to explicitly prohibit it.  Our
12806      callers must be ready to deal with unification failures in any
12807      event.  */
12808   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12809                                   targs, parms, args, nargs, /*subr=*/0,
12810                                   strict, flags);
12811
12812   if (result == 0 && incomplete_argument_packs_p)
12813     {
12814       int i, len = NUM_TMPL_ARGS (targs);
12815
12816       /* Clear the "incomplete" flags on all argument packs.  */
12817       for (i = 0; i < len; i++)
12818         {
12819           tree arg = TREE_VEC_ELT (targs, i);
12820           if (ARGUMENT_PACK_P (arg))
12821             {
12822               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12823               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12824             }
12825         }
12826     }
12827
12828   /* Now that we have bindings for all of the template arguments,
12829      ensure that the arguments deduced for the template template
12830      parameters have compatible template parameter lists.  We cannot
12831      check this property before we have deduced all template
12832      arguments, because the template parameter types of a template
12833      template parameter might depend on prior template parameters
12834      deduced after the template template parameter.  The following
12835      ill-formed example illustrates this issue:
12836
12837        template<typename T, template<T> class C> void f(C<5>, T);
12838
12839        template<int N> struct X {};
12840
12841        void g() {
12842          f(X<5>(), 5l); // error: template argument deduction fails
12843        }
12844
12845      The template parameter list of 'C' depends on the template type
12846      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
12847      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
12848      time that we deduce 'C'.  */
12849   if (result == 0
12850       && !template_template_parm_bindings_ok_p 
12851            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
12852     return 1;
12853
12854   if (result == 0)
12855     /* All is well so far.  Now, check:
12856
12857        [temp.deduct]
12858
12859        When all template arguments have been deduced, all uses of
12860        template parameters in nondeduced contexts are replaced with
12861        the corresponding deduced argument values.  If the
12862        substitution results in an invalid type, as described above,
12863        type deduction fails.  */
12864     {
12865       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
12866       if (substed == error_mark_node)
12867         return 1;
12868
12869       /* If we're looking for an exact match, check that what we got
12870          is indeed an exact match.  It might not be if some template
12871          parameters are used in non-deduced contexts.  */
12872       if (strict == DEDUCE_EXACT)
12873         {
12874           unsigned int i;
12875
12876           tree sarg
12877             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
12878           if (return_type)
12879             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
12880           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
12881             if (!same_type_p (args[i], TREE_VALUE (sarg)))
12882               return 1;
12883         }
12884     }
12885
12886   return result;
12887 }
12888
12889 /* Adjust types before performing type deduction, as described in
12890    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
12891    sections are symmetric.  PARM is the type of a function parameter
12892    or the return type of the conversion function.  ARG is the type of
12893    the argument passed to the call, or the type of the value
12894    initialized with the result of the conversion function.
12895    ARG_EXPR is the original argument expression, which may be null.  */
12896
12897 static int
12898 maybe_adjust_types_for_deduction (unification_kind_t strict,
12899                                   tree* parm,
12900                                   tree* arg,
12901                                   tree arg_expr)
12902 {
12903   int result = 0;
12904
12905   switch (strict)
12906     {
12907     case DEDUCE_CALL:
12908       break;
12909
12910     case DEDUCE_CONV:
12911       {
12912         /* Swap PARM and ARG throughout the remainder of this
12913            function; the handling is precisely symmetric since PARM
12914            will initialize ARG rather than vice versa.  */
12915         tree* temp = parm;
12916         parm = arg;
12917         arg = temp;
12918         break;
12919       }
12920
12921     case DEDUCE_EXACT:
12922       /* Core issue #873: Do the DR606 thing (see below) for these cases,
12923          too, but here handle it by stripping the reference from PARM
12924          rather than by adding it to ARG.  */
12925       if (TREE_CODE (*parm) == REFERENCE_TYPE
12926           && TYPE_REF_IS_RVALUE (*parm)
12927           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
12928           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
12929           && TREE_CODE (*arg) == REFERENCE_TYPE
12930           && !TYPE_REF_IS_RVALUE (*arg))
12931         *parm = TREE_TYPE (*parm);
12932       /* Nothing else to do in this case.  */
12933       return 0;
12934
12935     default:
12936       gcc_unreachable ();
12937     }
12938
12939   if (TREE_CODE (*parm) != REFERENCE_TYPE)
12940     {
12941       /* [temp.deduct.call]
12942
12943          If P is not a reference type:
12944
12945          --If A is an array type, the pointer type produced by the
12946          array-to-pointer standard conversion (_conv.array_) is
12947          used in place of A for type deduction; otherwise,
12948
12949          --If A is a function type, the pointer type produced by
12950          the function-to-pointer standard conversion
12951          (_conv.func_) is used in place of A for type deduction;
12952          otherwise,
12953
12954          --If A is a cv-qualified type, the top level
12955          cv-qualifiers of A's type are ignored for type
12956          deduction.  */
12957       if (TREE_CODE (*arg) == ARRAY_TYPE)
12958         *arg = build_pointer_type (TREE_TYPE (*arg));
12959       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
12960         *arg = build_pointer_type (*arg);
12961       else
12962         *arg = TYPE_MAIN_VARIANT (*arg);
12963     }
12964
12965   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
12966      of the form T&&, where T is a template parameter, and the argument
12967      is an lvalue, T is deduced as A& */
12968   if (TREE_CODE (*parm) == REFERENCE_TYPE
12969       && TYPE_REF_IS_RVALUE (*parm)
12970       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
12971       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
12972       && arg_expr && real_lvalue_p (arg_expr))
12973     *arg = build_reference_type (*arg);
12974
12975   /* [temp.deduct.call]
12976
12977      If P is a cv-qualified type, the top level cv-qualifiers
12978      of P's type are ignored for type deduction.  If P is a
12979      reference type, the type referred to by P is used for
12980      type deduction.  */
12981   *parm = TYPE_MAIN_VARIANT (*parm);
12982   if (TREE_CODE (*parm) == REFERENCE_TYPE)
12983     {
12984       *parm = TREE_TYPE (*parm);
12985       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12986     }
12987
12988   /* DR 322. For conversion deduction, remove a reference type on parm
12989      too (which has been swapped into ARG).  */
12990   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
12991     *arg = TREE_TYPE (*arg);
12992
12993   return result;
12994 }
12995
12996 /* Most parms like fn_type_unification.
12997
12998    If SUBR is 1, we're being called recursively (to unify the
12999    arguments of a function or method parameter of a function
13000    template). */
13001
13002 static int
13003 type_unification_real (tree tparms,
13004                        tree targs,
13005                        tree xparms,
13006                        const tree *xargs,
13007                        unsigned int xnargs,
13008                        int subr,
13009                        unification_kind_t strict,
13010                        int flags)
13011 {
13012   tree parm, arg, arg_expr;
13013   int i;
13014   int ntparms = TREE_VEC_LENGTH (tparms);
13015   int sub_strict;
13016   int saw_undeduced = 0;
13017   tree parms;
13018   const tree *args;
13019   unsigned int nargs;
13020   unsigned int ia;
13021
13022   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13023   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13024   gcc_assert (ntparms > 0);
13025
13026   switch (strict)
13027     {
13028     case DEDUCE_CALL:
13029       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13030                     | UNIFY_ALLOW_DERIVED);
13031       break;
13032
13033     case DEDUCE_CONV:
13034       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13035       break;
13036
13037     case DEDUCE_EXACT:
13038       sub_strict = UNIFY_ALLOW_NONE;
13039       break;
13040
13041     default:
13042       gcc_unreachable ();
13043     }
13044
13045  again:
13046   parms = xparms;
13047   args = xargs;
13048   nargs = xnargs;
13049
13050   ia = 0;
13051   while (parms && parms != void_list_node
13052          && ia < nargs)
13053     {
13054       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13055         break;
13056
13057       parm = TREE_VALUE (parms);
13058       parms = TREE_CHAIN (parms);
13059       arg = args[ia];
13060       ++ia;
13061       arg_expr = NULL;
13062
13063       if (arg == error_mark_node)
13064         return 1;
13065       if (arg == unknown_type_node)
13066         /* We can't deduce anything from this, but we might get all the
13067            template args from other function args.  */
13068         continue;
13069
13070       /* Conversions will be performed on a function argument that
13071          corresponds with a function parameter that contains only
13072          non-deducible template parameters and explicitly specified
13073          template parameters.  */
13074       if (!uses_template_parms (parm))
13075         {
13076           tree type;
13077
13078           if (!TYPE_P (arg))
13079             type = TREE_TYPE (arg);
13080           else
13081             type = arg;
13082
13083           if (same_type_p (parm, type))
13084             continue;
13085           if (strict != DEDUCE_EXACT
13086               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13087                                   flags))
13088             continue;
13089
13090           return 1;
13091         }
13092
13093       if (!TYPE_P (arg))
13094         {
13095           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13096           if (type_unknown_p (arg))
13097             {
13098               /* [temp.deduct.type] 
13099
13100                  A template-argument can be deduced from a pointer to
13101                  function or pointer to member function argument if
13102                  the set of overloaded functions does not contain
13103                  function templates and at most one of a set of
13104                  overloaded functions provides a unique match.  */
13105               if (resolve_overloaded_unification
13106                   (tparms, targs, parm, arg, strict, sub_strict))
13107                 continue;
13108
13109               return 1;
13110             }
13111           arg_expr = arg;
13112           arg = unlowered_expr_type (arg);
13113           if (arg == error_mark_node)
13114             return 1;
13115         }
13116
13117       {
13118         int arg_strict = sub_strict;
13119
13120         if (!subr)
13121           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13122                                                           arg_expr);
13123
13124         if (arg == init_list_type_node && arg_expr)
13125           arg = arg_expr;
13126         if (unify (tparms, targs, parm, arg, arg_strict))
13127           return 1;
13128       }
13129     }
13130
13131
13132   if (parms 
13133       && parms != void_list_node
13134       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13135     {
13136       /* Unify the remaining arguments with the pack expansion type.  */
13137       tree argvec;
13138       tree parmvec = make_tree_vec (1);
13139
13140       /* Allocate a TREE_VEC and copy in all of the arguments */ 
13141       argvec = make_tree_vec (nargs - ia);
13142       for (i = 0; ia < nargs; ++ia, ++i)
13143         TREE_VEC_ELT (argvec, i) = args[ia];
13144
13145       /* Copy the parameter into parmvec.  */
13146       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13147       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13148                                 /*call_args_p=*/true, /*subr=*/subr))
13149         return 1;
13150
13151       /* Advance to the end of the list of parameters.  */
13152       parms = TREE_CHAIN (parms);
13153     }
13154
13155   /* Fail if we've reached the end of the parm list, and more args
13156      are present, and the parm list isn't variadic.  */
13157   if (ia < nargs && parms == void_list_node)
13158     return 1;
13159   /* Fail if parms are left and they don't have default values.  */
13160   if (parms && parms != void_list_node
13161       && TREE_PURPOSE (parms) == NULL_TREE)
13162     return 1;
13163
13164   if (!subr)
13165     for (i = 0; i < ntparms; i++)
13166       if (!TREE_VEC_ELT (targs, i))
13167         {
13168           tree tparm;
13169
13170           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13171             continue;
13172
13173           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13174
13175           /* If this is an undeduced nontype parameter that depends on
13176              a type parameter, try another pass; its type may have been
13177              deduced from a later argument than the one from which
13178              this parameter can be deduced.  */
13179           if (TREE_CODE (tparm) == PARM_DECL
13180               && uses_template_parms (TREE_TYPE (tparm))
13181               && !saw_undeduced++)
13182             goto again;
13183
13184           /* Core issue #226 (C++0x) [temp.deduct]:
13185
13186                If a template argument has not been deduced, its
13187                default template argument, if any, is used. 
13188
13189              When we are in C++98 mode, TREE_PURPOSE will either
13190              be NULL_TREE or ERROR_MARK_NODE, so we do not need
13191              to explicitly check cxx_dialect here.  */
13192           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13193             {
13194               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13195               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13196               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13197               arg = convert_template_argument (parm, arg, targs, tf_none,
13198                                                i, NULL_TREE);
13199               if (arg == error_mark_node)
13200                 return 1;
13201               else
13202                 {
13203                   TREE_VEC_ELT (targs, i) = arg;
13204                   continue;
13205                 }
13206             }
13207
13208           /* If the type parameter is a parameter pack, then it will
13209              be deduced to an empty parameter pack.  */
13210           if (template_parameter_pack_p (tparm))
13211             {
13212               tree arg;
13213
13214               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13215                 {
13216                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13217                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13218                   TREE_CONSTANT (arg) = 1;
13219                 }
13220               else
13221                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13222
13223               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13224
13225               TREE_VEC_ELT (targs, i) = arg;
13226               continue;
13227             }
13228
13229           return 2;
13230         }
13231
13232   return 0;
13233 }
13234
13235 /* Subroutine of type_unification_real.  Args are like the variables
13236    at the call site.  ARG is an overloaded function (or template-id);
13237    we try deducing template args from each of the overloads, and if
13238    only one succeeds, we go with that.  Modifies TARGS and returns
13239    true on success.  */
13240
13241 static bool
13242 resolve_overloaded_unification (tree tparms,
13243                                 tree targs,
13244                                 tree parm,
13245                                 tree arg,
13246                                 unification_kind_t strict,
13247                                 int sub_strict)
13248 {
13249   tree tempargs = copy_node (targs);
13250   int good = 0;
13251   tree goodfn = NULL_TREE;
13252   bool addr_p;
13253
13254   if (TREE_CODE (arg) == ADDR_EXPR)
13255     {
13256       arg = TREE_OPERAND (arg, 0);
13257       addr_p = true;
13258     }
13259   else
13260     addr_p = false;
13261
13262   if (TREE_CODE (arg) == COMPONENT_REF)
13263     /* Handle `&x' where `x' is some static or non-static member
13264        function name.  */
13265     arg = TREE_OPERAND (arg, 1);
13266
13267   if (TREE_CODE (arg) == OFFSET_REF)
13268     arg = TREE_OPERAND (arg, 1);
13269
13270   /* Strip baselink information.  */
13271   if (BASELINK_P (arg))
13272     arg = BASELINK_FUNCTIONS (arg);
13273
13274   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13275     {
13276       /* If we got some explicit template args, we need to plug them into
13277          the affected templates before we try to unify, in case the
13278          explicit args will completely resolve the templates in question.  */
13279
13280       tree expl_subargs = TREE_OPERAND (arg, 1);
13281       arg = TREE_OPERAND (arg, 0);
13282
13283       for (; arg; arg = OVL_NEXT (arg))
13284         {
13285           tree fn = OVL_CURRENT (arg);
13286           tree subargs, elem;
13287
13288           if (TREE_CODE (fn) != TEMPLATE_DECL)
13289             continue;
13290
13291           ++processing_template_decl;
13292           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13293                                   expl_subargs, /*check_ret=*/false);
13294           if (subargs)
13295             {
13296               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13297               if (try_one_overload (tparms, targs, tempargs, parm,
13298                                     elem, strict, sub_strict, addr_p)
13299                   && (!goodfn || !decls_match (goodfn, elem)))
13300                 {
13301                   goodfn = elem;
13302                   ++good;
13303                 }
13304             }
13305           --processing_template_decl;
13306         }
13307     }
13308   else if (TREE_CODE (arg) != OVERLOAD
13309            && TREE_CODE (arg) != FUNCTION_DECL)
13310     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13311        -- but the deduction does not succeed because the expression is
13312        not just the function on its own.  */
13313     return false;
13314   else
13315     for (; arg; arg = OVL_NEXT (arg))
13316       if (try_one_overload (tparms, targs, tempargs, parm,
13317                             TREE_TYPE (OVL_CURRENT (arg)),
13318                             strict, sub_strict, addr_p)
13319           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13320         {
13321           goodfn = OVL_CURRENT (arg);
13322           ++good;
13323         }
13324
13325   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13326      to function or pointer to member function argument if the set of
13327      overloaded functions does not contain function templates and at most
13328      one of a set of overloaded functions provides a unique match.
13329
13330      So if we found multiple possibilities, we return success but don't
13331      deduce anything.  */
13332
13333   if (good == 1)
13334     {
13335       int i = TREE_VEC_LENGTH (targs);
13336       for (; i--; )
13337         if (TREE_VEC_ELT (tempargs, i))
13338           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13339     }
13340   if (good)
13341     return true;
13342
13343   return false;
13344 }
13345
13346 /* Core DR 115: In contexts where deduction is done and fails, or in
13347    contexts where deduction is not done, if a template argument list is
13348    specified and it, along with any default template arguments, identifies
13349    a single function template specialization, then the template-id is an
13350    lvalue for the function template specialization.  */
13351
13352 tree
13353 resolve_nondeduced_context (tree orig_expr)
13354 {
13355   tree expr, offset, baselink;
13356   bool addr;
13357
13358   if (!type_unknown_p (orig_expr))
13359     return orig_expr;
13360
13361   expr = orig_expr;
13362   addr = false;
13363   offset = NULL_TREE;
13364   baselink = NULL_TREE;
13365
13366   if (TREE_CODE (expr) == ADDR_EXPR)
13367     {
13368       expr = TREE_OPERAND (expr, 0);
13369       addr = true;
13370     }
13371   if (TREE_CODE (expr) == OFFSET_REF)
13372     {
13373       offset = expr;
13374       expr = TREE_OPERAND (expr, 1);
13375     }
13376   if (TREE_CODE (expr) == BASELINK)
13377     {
13378       baselink = expr;
13379       expr = BASELINK_FUNCTIONS (expr);
13380     }
13381
13382   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13383     {
13384       int good = 0;
13385       tree goodfn = NULL_TREE;
13386
13387       /* If we got some explicit template args, we need to plug them into
13388          the affected templates before we try to unify, in case the
13389          explicit args will completely resolve the templates in question.  */
13390
13391       tree expl_subargs = TREE_OPERAND (expr, 1);
13392       tree arg = TREE_OPERAND (expr, 0);
13393       tree badfn = NULL_TREE;
13394       tree badargs = NULL_TREE;
13395
13396       for (; arg; arg = OVL_NEXT (arg))
13397         {
13398           tree fn = OVL_CURRENT (arg);
13399           tree subargs, elem;
13400
13401           if (TREE_CODE (fn) != TEMPLATE_DECL)
13402             continue;
13403
13404           ++processing_template_decl;
13405           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13406                                   expl_subargs, /*check_ret=*/false);
13407           if (subargs && !any_dependent_template_arguments_p (subargs))
13408             {
13409               elem = instantiate_template (fn, subargs, tf_none);
13410               if (elem == error_mark_node)
13411                 {
13412                   badfn = fn;
13413                   badargs = subargs;
13414                 }
13415               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13416                 {
13417                   goodfn = elem;
13418                   ++good;
13419                 }
13420             }
13421           --processing_template_decl;
13422         }
13423       if (good == 1)
13424         {
13425           expr = goodfn;
13426           if (baselink)
13427             expr = build_baselink (BASELINK_BINFO (baselink),
13428                                    BASELINK_ACCESS_BINFO (baselink),
13429                                    expr, BASELINK_OPTYPE (baselink));
13430           if (offset)
13431             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13432                            TREE_OPERAND (offset, 0), expr);
13433           if (addr)
13434             expr = build_address (expr);
13435           return expr;
13436         }
13437       else if (good == 0 && badargs)
13438         /* There were no good options and at least one bad one, so let the
13439            user know what the problem is.  */
13440         instantiate_template (badfn, badargs, tf_warning_or_error);
13441     }
13442   return orig_expr;
13443 }
13444
13445 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13446    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13447    different overloads deduce different arguments for a given parm.
13448    ADDR_P is true if the expression for which deduction is being
13449    performed was of the form "& fn" rather than simply "fn".
13450
13451    Returns 1 on success.  */
13452
13453 static int
13454 try_one_overload (tree tparms,
13455                   tree orig_targs,
13456                   tree targs,
13457                   tree parm,
13458                   tree arg,
13459                   unification_kind_t strict,
13460                   int sub_strict,
13461                   bool addr_p)
13462 {
13463   int nargs;
13464   tree tempargs;
13465   int i;
13466
13467   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13468      to function or pointer to member function argument if the set of
13469      overloaded functions does not contain function templates and at most
13470      one of a set of overloaded functions provides a unique match.
13471
13472      So if this is a template, just return success.  */
13473
13474   if (uses_template_parms (arg))
13475     return 1;
13476
13477   if (TREE_CODE (arg) == METHOD_TYPE)
13478     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13479   else if (addr_p)
13480     arg = build_pointer_type (arg);
13481
13482   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13483
13484   /* We don't copy orig_targs for this because if we have already deduced
13485      some template args from previous args, unify would complain when we
13486      try to deduce a template parameter for the same argument, even though
13487      there isn't really a conflict.  */
13488   nargs = TREE_VEC_LENGTH (targs);
13489   tempargs = make_tree_vec (nargs);
13490
13491   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13492     return 0;
13493
13494   /* First make sure we didn't deduce anything that conflicts with
13495      explicitly specified args.  */
13496   for (i = nargs; i--; )
13497     {
13498       tree elt = TREE_VEC_ELT (tempargs, i);
13499       tree oldelt = TREE_VEC_ELT (orig_targs, i);
13500
13501       if (!elt)
13502         /*NOP*/;
13503       else if (uses_template_parms (elt))
13504         /* Since we're unifying against ourselves, we will fill in
13505            template args used in the function parm list with our own
13506            template parms.  Discard them.  */
13507         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13508       else if (oldelt && !template_args_equal (oldelt, elt))
13509         return 0;
13510     }
13511
13512   for (i = nargs; i--; )
13513     {
13514       tree elt = TREE_VEC_ELT (tempargs, i);
13515
13516       if (elt)
13517         TREE_VEC_ELT (targs, i) = elt;
13518     }
13519
13520   return 1;
13521 }
13522
13523 /* PARM is a template class (perhaps with unbound template
13524    parameters).  ARG is a fully instantiated type.  If ARG can be
13525    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
13526    TARGS are as for unify.  */
13527
13528 static tree
13529 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
13530 {
13531   tree copy_of_targs;
13532
13533   if (!CLASSTYPE_TEMPLATE_INFO (arg)
13534       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
13535           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
13536     return NULL_TREE;
13537
13538   /* We need to make a new template argument vector for the call to
13539      unify.  If we used TARGS, we'd clutter it up with the result of
13540      the attempted unification, even if this class didn't work out.
13541      We also don't want to commit ourselves to all the unifications
13542      we've already done, since unification is supposed to be done on
13543      an argument-by-argument basis.  In other words, consider the
13544      following pathological case:
13545
13546        template <int I, int J, int K>
13547        struct S {};
13548
13549        template <int I, int J>
13550        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
13551
13552        template <int I, int J, int K>
13553        void f(S<I, J, K>, S<I, I, I>);
13554
13555        void g() {
13556          S<0, 0, 0> s0;
13557          S<0, 1, 2> s2;
13558
13559          f(s0, s2);
13560        }
13561
13562      Now, by the time we consider the unification involving `s2', we
13563      already know that we must have `f<0, 0, 0>'.  But, even though
13564      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
13565      because there are two ways to unify base classes of S<0, 1, 2>
13566      with S<I, I, I>.  If we kept the already deduced knowledge, we
13567      would reject the possibility I=1.  */
13568   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
13569
13570   /* If unification failed, we're done.  */
13571   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
13572              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
13573     return NULL_TREE;
13574
13575   return arg;
13576 }
13577
13578 /* Given a template type PARM and a class type ARG, find the unique
13579    base type in ARG that is an instance of PARM.  We do not examine
13580    ARG itself; only its base-classes.  If there is not exactly one
13581    appropriate base class, return NULL_TREE.  PARM may be the type of
13582    a partial specialization, as well as a plain template type.  Used
13583    by unify.  */
13584
13585 static tree
13586 get_template_base (tree tparms, tree targs, tree parm, tree arg)
13587 {
13588   tree rval = NULL_TREE;
13589   tree binfo;
13590
13591   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
13592
13593   binfo = TYPE_BINFO (complete_type (arg));
13594   if (!binfo)
13595     /* The type could not be completed.  */
13596     return NULL_TREE;
13597
13598   /* Walk in inheritance graph order.  The search order is not
13599      important, and this avoids multiple walks of virtual bases.  */
13600   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
13601     {
13602       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
13603
13604       if (r)
13605         {
13606           /* If there is more than one satisfactory baseclass, then:
13607
13608                [temp.deduct.call]
13609
13610               If they yield more than one possible deduced A, the type
13611               deduction fails.
13612
13613              applies.  */
13614           if (rval && !same_type_p (r, rval))
13615             return NULL_TREE;
13616
13617           rval = r;
13618         }
13619     }
13620
13621   return rval;
13622 }
13623
13624 /* Returns the level of DECL, which declares a template parameter.  */
13625
13626 static int
13627 template_decl_level (tree decl)
13628 {
13629   switch (TREE_CODE (decl))
13630     {
13631     case TYPE_DECL:
13632     case TEMPLATE_DECL:
13633       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
13634
13635     case PARM_DECL:
13636       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
13637
13638     default:
13639       gcc_unreachable ();
13640     }
13641   return 0;
13642 }
13643
13644 /* Decide whether ARG can be unified with PARM, considering only the
13645    cv-qualifiers of each type, given STRICT as documented for unify.
13646    Returns nonzero iff the unification is OK on that basis.  */
13647
13648 static int
13649 check_cv_quals_for_unify (int strict, tree arg, tree parm)
13650 {
13651   int arg_quals = cp_type_quals (arg);
13652   int parm_quals = cp_type_quals (parm);
13653
13654   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13655       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13656     {
13657       /*  Although a CVR qualifier is ignored when being applied to a
13658           substituted template parameter ([8.3.2]/1 for example), that
13659           does not apply during deduction [14.8.2.4]/1, (even though
13660           that is not explicitly mentioned, [14.8.2.4]/9 indicates
13661           this).  Except when we're allowing additional CV qualifiers
13662           at the outer level [14.8.2.1]/3,1st bullet.  */
13663       if ((TREE_CODE (arg) == REFERENCE_TYPE
13664            || TREE_CODE (arg) == FUNCTION_TYPE
13665            || TREE_CODE (arg) == METHOD_TYPE)
13666           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
13667         return 0;
13668
13669       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
13670           && (parm_quals & TYPE_QUAL_RESTRICT))
13671         return 0;
13672     }
13673
13674   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13675       && (arg_quals & parm_quals) != parm_quals)
13676     return 0;
13677
13678   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
13679       && (parm_quals & arg_quals) != arg_quals)
13680     return 0;
13681
13682   return 1;
13683 }
13684
13685 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
13686 void 
13687 template_parm_level_and_index (tree parm, int* level, int* index)
13688 {
13689   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13690       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13691       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13692     {
13693       *index = TEMPLATE_TYPE_IDX (parm);
13694       *level = TEMPLATE_TYPE_LEVEL (parm);
13695     }
13696   else
13697     {
13698       *index = TEMPLATE_PARM_IDX (parm);
13699       *level = TEMPLATE_PARM_LEVEL (parm);
13700     }
13701 }
13702
13703 /* Unifies the remaining arguments in PACKED_ARGS with the pack
13704    expansion at the end of PACKED_PARMS. Returns 0 if the type
13705    deduction succeeds, 1 otherwise. STRICT is the same as in
13706    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
13707    call argument list. We'll need to adjust the arguments to make them
13708    types. SUBR tells us if this is from a recursive call to
13709    type_unification_real.  */
13710 int
13711 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
13712                       tree packed_args, int strict, bool call_args_p,
13713                       bool subr)
13714 {
13715   tree parm 
13716     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
13717   tree pattern = PACK_EXPANSION_PATTERN (parm);
13718   tree pack, packs = NULL_TREE;
13719   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
13720   int len = TREE_VEC_LENGTH (packed_args);
13721
13722   /* Determine the parameter packs we will be deducing from the
13723      pattern, and record their current deductions.  */
13724   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
13725        pack; pack = TREE_CHAIN (pack))
13726     {
13727       tree parm_pack = TREE_VALUE (pack);
13728       int idx, level;
13729
13730       /* Determine the index and level of this parameter pack.  */
13731       template_parm_level_and_index (parm_pack, &level, &idx);
13732
13733       /* Keep track of the parameter packs and their corresponding
13734          argument packs.  */
13735       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
13736       TREE_TYPE (packs) = make_tree_vec (len - start);
13737     }
13738   
13739   /* Loop through all of the arguments that have not yet been
13740      unified and unify each with the pattern.  */
13741   for (i = start; i < len; i++)
13742     {
13743       tree parm = pattern;
13744
13745       /* For each parameter pack, clear out the deduced value so that
13746          we can deduce it again.  */
13747       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13748         {
13749           int idx, level;
13750           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13751
13752           TMPL_ARG (targs, level, idx) = NULL_TREE;
13753         }
13754
13755       /* Unify the pattern with the current argument.  */
13756       {
13757         tree arg = TREE_VEC_ELT (packed_args, i);
13758         tree arg_expr = NULL_TREE;
13759         int arg_strict = strict;
13760         bool skip_arg_p = false;
13761
13762         if (call_args_p)
13763           {
13764             int sub_strict;
13765
13766             /* This mirrors what we do in type_unification_real.  */
13767             switch (strict)
13768               {
13769               case DEDUCE_CALL:
13770                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
13771                               | UNIFY_ALLOW_MORE_CV_QUAL
13772                               | UNIFY_ALLOW_DERIVED);
13773                 break;
13774                 
13775               case DEDUCE_CONV:
13776                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13777                 break;
13778                 
13779               case DEDUCE_EXACT:
13780                 sub_strict = UNIFY_ALLOW_NONE;
13781                 break;
13782                 
13783               default:
13784                 gcc_unreachable ();
13785               }
13786
13787             if (!TYPE_P (arg))
13788               {
13789                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13790                 if (type_unknown_p (arg))
13791                   {
13792                     /* [temp.deduct.type] A template-argument can be
13793                        deduced from a pointer to function or pointer
13794                        to member function argument if the set of
13795                        overloaded functions does not contain function
13796                        templates and at most one of a set of
13797                        overloaded functions provides a unique
13798                        match.  */
13799
13800                     if (resolve_overloaded_unification
13801                         (tparms, targs, parm, arg,
13802                          (unification_kind_t) strict,
13803                          sub_strict)
13804                         != 0)
13805                       return 1;
13806                     skip_arg_p = true;
13807                   }
13808
13809                 if (!skip_arg_p)
13810                   {
13811                     arg_expr = arg;
13812                     arg = unlowered_expr_type (arg);
13813                     if (arg == error_mark_node)
13814                       return 1;
13815                   }
13816               }
13817       
13818             arg_strict = sub_strict;
13819
13820             if (!subr)
13821               arg_strict |= 
13822                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
13823                                                   &parm, &arg, arg_expr);
13824           }
13825
13826         if (!skip_arg_p)
13827           {
13828             if (unify (tparms, targs, parm, arg, arg_strict))
13829               return 1;
13830           }
13831       }
13832
13833       /* For each parameter pack, collect the deduced value.  */
13834       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13835         {
13836           int idx, level;
13837           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13838
13839           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
13840             TMPL_ARG (targs, level, idx);
13841         }
13842     }
13843
13844   /* Verify that the results of unification with the parameter packs
13845      produce results consistent with what we've seen before, and make
13846      the deduced argument packs available.  */
13847   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13848     {
13849       tree old_pack = TREE_VALUE (pack);
13850       tree new_args = TREE_TYPE (pack);
13851       int i, len = TREE_VEC_LENGTH (new_args);
13852       bool nondeduced_p = false;
13853
13854       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
13855          actually deduce anything.  */
13856       for (i = 0; i < len && !nondeduced_p; ++i)
13857         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
13858           nondeduced_p = true;
13859       if (nondeduced_p)
13860         continue;
13861
13862       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
13863         {
13864           /* Prepend the explicit arguments onto NEW_ARGS.  */
13865           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13866           tree old_args = new_args;
13867           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
13868           int len = explicit_len + TREE_VEC_LENGTH (old_args);
13869
13870           /* Copy the explicit arguments.  */
13871           new_args = make_tree_vec (len);
13872           for (i = 0; i < explicit_len; i++)
13873             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
13874
13875           /* Copy the deduced arguments.  */
13876           for (; i < len; i++)
13877             TREE_VEC_ELT (new_args, i) =
13878               TREE_VEC_ELT (old_args, i - explicit_len);
13879         }
13880
13881       if (!old_pack)
13882         {
13883           tree result;
13884           int idx, level;
13885           
13886           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13887
13888           /* Build the deduced *_ARGUMENT_PACK.  */
13889           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
13890             {
13891               result = make_node (NONTYPE_ARGUMENT_PACK);
13892               TREE_TYPE (result) = 
13893                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
13894               TREE_CONSTANT (result) = 1;
13895             }
13896           else
13897             result = cxx_make_type (TYPE_ARGUMENT_PACK);
13898
13899           SET_ARGUMENT_PACK_ARGS (result, new_args);
13900
13901           /* Note the deduced argument packs for this parameter
13902              pack.  */
13903           TMPL_ARG (targs, level, idx) = result;
13904         }
13905       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
13906                && (ARGUMENT_PACK_ARGS (old_pack) 
13907                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
13908         {
13909           /* We only had the explicitly-provided arguments before, but
13910              now we have a complete set of arguments.  */
13911           int idx, level;
13912           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13913           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13914
13915           /* Keep the original deduced argument pack.  */
13916           TMPL_ARG (targs, level, idx) = old_pack;
13917
13918           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
13919           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
13920           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
13921         }
13922       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
13923                                     new_args))
13924         /* Inconsistent unification of this parameter pack.  */
13925         return 1;
13926       else
13927         {
13928           int idx, level;
13929           
13930           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13931
13932           /* Keep the original deduced argument pack.  */
13933           TMPL_ARG (targs, level, idx) = old_pack;
13934         }
13935     }
13936
13937   return 0;
13938 }
13939
13940 /* Deduce the value of template parameters.  TPARMS is the (innermost)
13941    set of template parameters to a template.  TARGS is the bindings
13942    for those template parameters, as determined thus far; TARGS may
13943    include template arguments for outer levels of template parameters
13944    as well.  PARM is a parameter to a template function, or a
13945    subcomponent of that parameter; ARG is the corresponding argument.
13946    This function attempts to match PARM with ARG in a manner
13947    consistent with the existing assignments in TARGS.  If more values
13948    are deduced, then TARGS is updated.
13949
13950    Returns 0 if the type deduction succeeds, 1 otherwise.  The
13951    parameter STRICT is a bitwise or of the following flags:
13952
13953      UNIFY_ALLOW_NONE:
13954        Require an exact match between PARM and ARG.
13955      UNIFY_ALLOW_MORE_CV_QUAL:
13956        Allow the deduced ARG to be more cv-qualified (by qualification
13957        conversion) than ARG.
13958      UNIFY_ALLOW_LESS_CV_QUAL:
13959        Allow the deduced ARG to be less cv-qualified than ARG.
13960      UNIFY_ALLOW_DERIVED:
13961        Allow the deduced ARG to be a template base class of ARG,
13962        or a pointer to a template base class of the type pointed to by
13963        ARG.
13964      UNIFY_ALLOW_INTEGER:
13965        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
13966        case for more information.
13967      UNIFY_ALLOW_OUTER_LEVEL:
13968        This is the outermost level of a deduction. Used to determine validity
13969        of qualification conversions. A valid qualification conversion must
13970        have const qualified pointers leading up to the inner type which
13971        requires additional CV quals, except at the outer level, where const
13972        is not required [conv.qual]. It would be normal to set this flag in
13973        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
13974      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
13975        This is the outermost level of a deduction, and PARM can be more CV
13976        qualified at this point.
13977      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
13978        This is the outermost level of a deduction, and PARM can be less CV
13979        qualified at this point.  */
13980
13981 static int
13982 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
13983 {
13984   int idx;
13985   tree targ;
13986   tree tparm;
13987   int strict_in = strict;
13988
13989   /* I don't think this will do the right thing with respect to types.
13990      But the only case I've seen it in so far has been array bounds, where
13991      signedness is the only information lost, and I think that will be
13992      okay.  */
13993   while (TREE_CODE (parm) == NOP_EXPR)
13994     parm = TREE_OPERAND (parm, 0);
13995
13996   if (arg == error_mark_node)
13997     return 1;
13998   if (arg == unknown_type_node
13999       || arg == init_list_type_node)
14000     /* We can't deduce anything from this, but we might get all the
14001        template args from other function args.  */
14002     return 0;
14003
14004   /* If PARM uses template parameters, then we can't bail out here,
14005      even if ARG == PARM, since we won't record unifications for the
14006      template parameters.  We might need them if we're trying to
14007      figure out which of two things is more specialized.  */
14008   if (arg == parm && !uses_template_parms (parm))
14009     return 0;
14010
14011   /* Handle init lists early, so the rest of the function can assume
14012      we're dealing with a type. */
14013   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14014     {
14015       tree elt, elttype;
14016       unsigned i;
14017       tree orig_parm = parm;
14018
14019       /* Replace T with std::initializer_list<T> for deduction.  */
14020       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14021           && flag_deduce_init_list)
14022         parm = listify (parm);
14023
14024       if (!is_std_init_list (parm))
14025         /* We can only deduce from an initializer list argument if the
14026            parameter is std::initializer_list; otherwise this is a
14027            non-deduced context. */
14028         return 0;
14029
14030       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14031
14032       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14033         {
14034           int elt_strict = strict;
14035           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14036             {
14037               tree type = TREE_TYPE (elt);
14038               /* It should only be possible to get here for a call.  */
14039               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14040               elt_strict |= maybe_adjust_types_for_deduction
14041                 (DEDUCE_CALL, &elttype, &type, elt);
14042               elt = type;
14043             }
14044
14045           if (unify (tparms, targs, elttype, elt, elt_strict))
14046             return 1;
14047         }
14048
14049       /* If the std::initializer_list<T> deduction worked, replace the
14050          deduced A with std::initializer_list<A>.  */
14051       if (orig_parm != parm)
14052         {
14053           idx = TEMPLATE_TYPE_IDX (orig_parm);
14054           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14055           targ = listify (targ);
14056           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14057         }
14058       return 0;
14059     }
14060
14061   /* Immediately reject some pairs that won't unify because of
14062      cv-qualification mismatches.  */
14063   if (TREE_CODE (arg) == TREE_CODE (parm)
14064       && TYPE_P (arg)
14065       /* It is the elements of the array which hold the cv quals of an array
14066          type, and the elements might be template type parms. We'll check
14067          when we recurse.  */
14068       && TREE_CODE (arg) != ARRAY_TYPE
14069       /* We check the cv-qualifiers when unifying with template type
14070          parameters below.  We want to allow ARG `const T' to unify with
14071          PARM `T' for example, when computing which of two templates
14072          is more specialized, for example.  */
14073       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14074       && !check_cv_quals_for_unify (strict_in, arg, parm))
14075     return 1;
14076
14077   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14078       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14079     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14080   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14081   strict &= ~UNIFY_ALLOW_DERIVED;
14082   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14083   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14084
14085   switch (TREE_CODE (parm))
14086     {
14087     case TYPENAME_TYPE:
14088     case SCOPE_REF:
14089     case UNBOUND_CLASS_TEMPLATE:
14090       /* In a type which contains a nested-name-specifier, template
14091          argument values cannot be deduced for template parameters used
14092          within the nested-name-specifier.  */
14093       return 0;
14094
14095     case TEMPLATE_TYPE_PARM:
14096     case TEMPLATE_TEMPLATE_PARM:
14097     case BOUND_TEMPLATE_TEMPLATE_PARM:
14098       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14099       if (tparm == error_mark_node)
14100         return 1;
14101
14102       if (TEMPLATE_TYPE_LEVEL (parm)
14103           != template_decl_level (tparm))
14104         /* The PARM is not one we're trying to unify.  Just check
14105            to see if it matches ARG.  */
14106         return (TREE_CODE (arg) == TREE_CODE (parm)
14107                 && same_type_p (parm, arg)) ? 0 : 1;
14108       idx = TEMPLATE_TYPE_IDX (parm);
14109       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14110       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14111
14112       /* Check for mixed types and values.  */
14113       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14114            && TREE_CODE (tparm) != TYPE_DECL)
14115           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14116               && TREE_CODE (tparm) != TEMPLATE_DECL))
14117         return 1;
14118
14119       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14120         {
14121           /* ARG must be constructed from a template class or a template
14122              template parameter.  */
14123           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14124               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14125             return 1;
14126
14127           {
14128             tree parmvec = TYPE_TI_ARGS (parm);
14129             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14130             tree parm_parms 
14131               = DECL_INNERMOST_TEMPLATE_PARMS
14132                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14133             int i, len;
14134             int parm_variadic_p = 0;
14135
14136             /* The resolution to DR150 makes clear that default
14137                arguments for an N-argument may not be used to bind T
14138                to a template template parameter with fewer than N
14139                parameters.  It is not safe to permit the binding of
14140                default arguments as an extension, as that may change
14141                the meaning of a conforming program.  Consider:
14142
14143                   struct Dense { static const unsigned int dim = 1; };
14144
14145                   template <template <typename> class View,
14146                             typename Block>
14147                   void operator+(float, View<Block> const&);
14148
14149                   template <typename Block,
14150                             unsigned int Dim = Block::dim>
14151                   struct Lvalue_proxy { operator float() const; };
14152
14153                   void
14154                   test_1d (void) {
14155                     Lvalue_proxy<Dense> p;
14156                     float b;
14157                     b + p;
14158                   }
14159
14160               Here, if Lvalue_proxy is permitted to bind to View, then
14161               the global operator+ will be used; if they are not, the
14162               Lvalue_proxy will be converted to float.  */
14163             if (coerce_template_parms (parm_parms,
14164                                        argvec,
14165                                        TYPE_TI_TEMPLATE (parm),
14166                                        tf_none,
14167                                        /*require_all_args=*/true,
14168                                        /*use_default_args=*/false)
14169                 == error_mark_node)
14170               return 1;
14171
14172             /* Deduce arguments T, i from TT<T> or TT<i>.
14173                We check each element of PARMVEC and ARGVEC individually
14174                rather than the whole TREE_VEC since they can have
14175                different number of elements.  */
14176
14177             parmvec = expand_template_argument_pack (parmvec);
14178             argvec = expand_template_argument_pack (argvec);
14179
14180             len = TREE_VEC_LENGTH (parmvec);
14181
14182             /* Check if the parameters end in a pack, making them
14183                variadic.  */
14184             if (len > 0
14185                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14186               parm_variadic_p = 1;
14187             
14188             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14189               return 1;
14190
14191              for (i = 0; i < len - parm_variadic_p; ++i)
14192               {
14193                 if (unify (tparms, targs,
14194                            TREE_VEC_ELT (parmvec, i),
14195                            TREE_VEC_ELT (argvec, i),
14196                            UNIFY_ALLOW_NONE))
14197                   return 1;
14198               }
14199
14200             if (parm_variadic_p
14201                 && unify_pack_expansion (tparms, targs,
14202                                          parmvec, argvec,
14203                                          UNIFY_ALLOW_NONE,
14204                                          /*call_args_p=*/false,
14205                                          /*subr=*/false))
14206               return 1;
14207           }
14208           arg = TYPE_TI_TEMPLATE (arg);
14209
14210           /* Fall through to deduce template name.  */
14211         }
14212
14213       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14214           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14215         {
14216           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14217
14218           /* Simple cases: Value already set, does match or doesn't.  */
14219           if (targ != NULL_TREE && template_args_equal (targ, arg))
14220             return 0;
14221           else if (targ)
14222             return 1;
14223         }
14224       else
14225         {
14226           /* If PARM is `const T' and ARG is only `int', we don't have
14227              a match unless we are allowing additional qualification.
14228              If ARG is `const int' and PARM is just `T' that's OK;
14229              that binds `const int' to `T'.  */
14230           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14231                                          arg, parm))
14232             return 1;
14233
14234           /* Consider the case where ARG is `const volatile int' and
14235              PARM is `const T'.  Then, T should be `volatile int'.  */
14236           arg = cp_build_qualified_type_real
14237             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14238           if (arg == error_mark_node)
14239             return 1;
14240
14241           /* Simple cases: Value already set, does match or doesn't.  */
14242           if (targ != NULL_TREE && same_type_p (targ, arg))
14243             return 0;
14244           else if (targ)
14245             return 1;
14246
14247           /* Make sure that ARG is not a variable-sized array.  (Note
14248              that were talking about variable-sized arrays (like
14249              `int[n]'), rather than arrays of unknown size (like
14250              `int[]').)  We'll get very confused by such a type since
14251              the bound of the array will not be computable in an
14252              instantiation.  Besides, such types are not allowed in
14253              ISO C++, so we can do as we please here.  */
14254           if (variably_modified_type_p (arg, NULL_TREE))
14255             return 1;
14256
14257           /* Strip typedefs as in convert_template_argument.  */
14258           arg = strip_typedefs (arg);
14259         }
14260
14261       /* If ARG is a parameter pack or an expansion, we cannot unify
14262          against it unless PARM is also a parameter pack.  */
14263       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14264           && !template_parameter_pack_p (parm))
14265         return 1;
14266
14267       /* If the argument deduction results is a METHOD_TYPE,
14268          then there is a problem.
14269          METHOD_TYPE doesn't map to any real C++ type the result of
14270          the deduction can not be of that type.  */
14271       if (TREE_CODE (arg) == METHOD_TYPE)
14272         return 1;
14273
14274       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14275       return 0;
14276
14277     case TEMPLATE_PARM_INDEX:
14278       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14279       if (tparm == error_mark_node)
14280         return 1;
14281
14282       if (TEMPLATE_PARM_LEVEL (parm)
14283           != template_decl_level (tparm))
14284         /* The PARM is not one we're trying to unify.  Just check
14285            to see if it matches ARG.  */
14286         return !(TREE_CODE (arg) == TREE_CODE (parm)
14287                  && cp_tree_equal (parm, arg));
14288
14289       idx = TEMPLATE_PARM_IDX (parm);
14290       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14291
14292       if (targ)
14293         return !cp_tree_equal (targ, arg);
14294
14295       /* [temp.deduct.type] If, in the declaration of a function template
14296          with a non-type template-parameter, the non-type
14297          template-parameter is used in an expression in the function
14298          parameter-list and, if the corresponding template-argument is
14299          deduced, the template-argument type shall match the type of the
14300          template-parameter exactly, except that a template-argument
14301          deduced from an array bound may be of any integral type.
14302          The non-type parameter might use already deduced type parameters.  */
14303       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14304       if (!TREE_TYPE (arg))
14305         /* Template-parameter dependent expression.  Just accept it for now.
14306            It will later be processed in convert_template_argument.  */
14307         ;
14308       else if (same_type_p (TREE_TYPE (arg), tparm))
14309         /* OK */;
14310       else if ((strict & UNIFY_ALLOW_INTEGER)
14311                && (TREE_CODE (tparm) == INTEGER_TYPE
14312                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
14313         /* Convert the ARG to the type of PARM; the deduced non-type
14314            template argument must exactly match the types of the
14315            corresponding parameter.  */
14316         arg = fold (build_nop (tparm, arg));
14317       else if (uses_template_parms (tparm))
14318         /* We haven't deduced the type of this parameter yet.  Try again
14319            later.  */
14320         return 0;
14321       else
14322         return 1;
14323
14324       /* If ARG is a parameter pack or an expansion, we cannot unify
14325          against it unless PARM is also a parameter pack.  */
14326       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14327           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14328         return 1;
14329
14330       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14331       return 0;
14332
14333     case PTRMEM_CST:
14334      {
14335         /* A pointer-to-member constant can be unified only with
14336          another constant.  */
14337       if (TREE_CODE (arg) != PTRMEM_CST)
14338         return 1;
14339
14340       /* Just unify the class member. It would be useless (and possibly
14341          wrong, depending on the strict flags) to unify also
14342          PTRMEM_CST_CLASS, because we want to be sure that both parm and
14343          arg refer to the same variable, even if through different
14344          classes. For instance:
14345
14346          struct A { int x; };
14347          struct B : A { };
14348
14349          Unification of &A::x and &B::x must succeed.  */
14350       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14351                     PTRMEM_CST_MEMBER (arg), strict);
14352      }
14353
14354     case POINTER_TYPE:
14355       {
14356         if (TREE_CODE (arg) != POINTER_TYPE)
14357           return 1;
14358
14359         /* [temp.deduct.call]
14360
14361            A can be another pointer or pointer to member type that can
14362            be converted to the deduced A via a qualification
14363            conversion (_conv.qual_).
14364
14365            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14366            This will allow for additional cv-qualification of the
14367            pointed-to types if appropriate.  */
14368
14369         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14370           /* The derived-to-base conversion only persists through one
14371              level of pointers.  */
14372           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14373
14374         return unify (tparms, targs, TREE_TYPE (parm),
14375                       TREE_TYPE (arg), strict);
14376       }
14377
14378     case REFERENCE_TYPE:
14379       if (TREE_CODE (arg) != REFERENCE_TYPE)
14380         return 1;
14381       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14382                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14383
14384     case ARRAY_TYPE:
14385       if (TREE_CODE (arg) != ARRAY_TYPE)
14386         return 1;
14387       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14388           != (TYPE_DOMAIN (arg) == NULL_TREE))
14389         return 1;
14390       if (TYPE_DOMAIN (parm) != NULL_TREE)
14391         {
14392           tree parm_max;
14393           tree arg_max;
14394           bool parm_cst;
14395           bool arg_cst;
14396
14397           /* Our representation of array types uses "N - 1" as the
14398              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14399              not an integer constant.  We cannot unify arbitrarily
14400              complex expressions, so we eliminate the MINUS_EXPRs
14401              here.  */
14402           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14403           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14404           if (!parm_cst)
14405             {
14406               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14407               parm_max = TREE_OPERAND (parm_max, 0);
14408             }
14409           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14410           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14411           if (!arg_cst)
14412             {
14413               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14414                  trying to unify the type of a variable with the type
14415                  of a template parameter.  For example:
14416
14417                    template <unsigned int N>
14418                    void f (char (&) [N]);
14419                    int g(); 
14420                    void h(int i) {
14421                      char a[g(i)];
14422                      f(a); 
14423                    }
14424
14425                 Here, the type of the ARG will be "int [g(i)]", and
14426                 may be a SAVE_EXPR, etc.  */
14427               if (TREE_CODE (arg_max) != MINUS_EXPR)
14428                 return 1;
14429               arg_max = TREE_OPERAND (arg_max, 0);
14430             }
14431
14432           /* If only one of the bounds used a MINUS_EXPR, compensate
14433              by adding one to the other bound.  */
14434           if (parm_cst && !arg_cst)
14435             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14436                                     integer_type_node,
14437                                     parm_max,
14438                                     integer_one_node);
14439           else if (arg_cst && !parm_cst)
14440             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14441                                    integer_type_node,
14442                                    arg_max,
14443                                    integer_one_node);
14444
14445           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14446             return 1;
14447         }
14448       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14449                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14450
14451     case REAL_TYPE:
14452     case COMPLEX_TYPE:
14453     case VECTOR_TYPE:
14454     case INTEGER_TYPE:
14455     case BOOLEAN_TYPE:
14456     case ENUMERAL_TYPE:
14457     case VOID_TYPE:
14458       if (TREE_CODE (arg) != TREE_CODE (parm))
14459         return 1;
14460
14461       /* We have already checked cv-qualification at the top of the
14462          function.  */
14463       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14464         return 1;
14465
14466       /* As far as unification is concerned, this wins.  Later checks
14467          will invalidate it if necessary.  */
14468       return 0;
14469
14470       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14471       /* Type INTEGER_CST can come from ordinary constant template args.  */
14472     case INTEGER_CST:
14473       while (TREE_CODE (arg) == NOP_EXPR)
14474         arg = TREE_OPERAND (arg, 0);
14475
14476       if (TREE_CODE (arg) != INTEGER_CST)
14477         return 1;
14478       return !tree_int_cst_equal (parm, arg);
14479
14480     case TREE_VEC:
14481       {
14482         int i;
14483         if (TREE_CODE (arg) != TREE_VEC)
14484           return 1;
14485         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14486           return 1;
14487         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14488           if (unify (tparms, targs,
14489                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14490                      UNIFY_ALLOW_NONE))
14491             return 1;
14492         return 0;
14493       }
14494
14495     case RECORD_TYPE:
14496     case UNION_TYPE:
14497       if (TREE_CODE (arg) != TREE_CODE (parm))
14498         return 1;
14499
14500       if (TYPE_PTRMEMFUNC_P (parm))
14501         {
14502           if (!TYPE_PTRMEMFUNC_P (arg))
14503             return 1;
14504
14505           return unify (tparms, targs,
14506                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
14507                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
14508                         strict);
14509         }
14510
14511       if (CLASSTYPE_TEMPLATE_INFO (parm))
14512         {
14513           tree t = NULL_TREE;
14514
14515           if (strict_in & UNIFY_ALLOW_DERIVED)
14516             {
14517               /* First, we try to unify the PARM and ARG directly.  */
14518               t = try_class_unification (tparms, targs,
14519                                          parm, arg);
14520
14521               if (!t)
14522                 {
14523                   /* Fallback to the special case allowed in
14524                      [temp.deduct.call]:
14525
14526                        If P is a class, and P has the form
14527                        template-id, then A can be a derived class of
14528                        the deduced A.  Likewise, if P is a pointer to
14529                        a class of the form template-id, A can be a
14530                        pointer to a derived class pointed to by the
14531                        deduced A.  */
14532                   t = get_template_base (tparms, targs, parm, arg);
14533
14534                   if (!t)
14535                     return 1;
14536                 }
14537             }
14538           else if (CLASSTYPE_TEMPLATE_INFO (arg)
14539                    && (CLASSTYPE_TI_TEMPLATE (parm)
14540                        == CLASSTYPE_TI_TEMPLATE (arg)))
14541             /* Perhaps PARM is something like S<U> and ARG is S<int>.
14542                Then, we should unify `int' and `U'.  */
14543             t = arg;
14544           else
14545             /* There's no chance of unification succeeding.  */
14546             return 1;
14547
14548           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
14549                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
14550         }
14551       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
14552         return 1;
14553       return 0;
14554
14555     case METHOD_TYPE:
14556     case FUNCTION_TYPE:
14557       {
14558         unsigned int nargs;
14559         tree *args;
14560         tree a;
14561         unsigned int i;
14562
14563         if (TREE_CODE (arg) != TREE_CODE (parm))
14564           return 1;
14565
14566         /* CV qualifications for methods can never be deduced, they must
14567            match exactly.  We need to check them explicitly here,
14568            because type_unification_real treats them as any other
14569            cv-qualified parameter.  */
14570         if (TREE_CODE (parm) == METHOD_TYPE
14571             && (!check_cv_quals_for_unify
14572                 (UNIFY_ALLOW_NONE,
14573                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
14574                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
14575           return 1;
14576
14577         if (unify (tparms, targs, TREE_TYPE (parm),
14578                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
14579           return 1;
14580
14581         nargs = list_length (TYPE_ARG_TYPES (arg));
14582         args = XALLOCAVEC (tree, nargs);
14583         for (a = TYPE_ARG_TYPES (arg), i = 0;
14584              a != NULL_TREE && a != void_list_node;
14585              a = TREE_CHAIN (a), ++i)
14586           args[i] = TREE_VALUE (a);
14587         nargs = i;
14588
14589         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
14590                                       args, nargs, 1, DEDUCE_EXACT,
14591                                       LOOKUP_NORMAL);
14592       }
14593
14594     case OFFSET_TYPE:
14595       /* Unify a pointer to member with a pointer to member function, which
14596          deduces the type of the member as a function type. */
14597       if (TYPE_PTRMEMFUNC_P (arg))
14598         {
14599           tree method_type;
14600           tree fntype;
14601           cp_cv_quals cv_quals;
14602
14603           /* Check top-level cv qualifiers */
14604           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
14605             return 1;
14606
14607           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14608                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
14609             return 1;
14610
14611           /* Determine the type of the function we are unifying against. */
14612           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
14613           fntype =
14614             build_function_type (TREE_TYPE (method_type),
14615                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
14616
14617           /* Extract the cv-qualifiers of the member function from the
14618              implicit object parameter and place them on the function
14619              type to be restored later. */
14620           cv_quals =
14621             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
14622           fntype = build_qualified_type (fntype, cv_quals);
14623           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
14624         }
14625
14626       if (TREE_CODE (arg) != OFFSET_TYPE)
14627         return 1;
14628       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14629                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
14630         return 1;
14631       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14632                     strict);
14633
14634     case CONST_DECL:
14635       if (DECL_TEMPLATE_PARM_P (parm))
14636         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
14637       if (arg != integral_constant_value (parm))
14638         return 1;
14639       return 0;
14640
14641     case FIELD_DECL:
14642     case TEMPLATE_DECL:
14643       /* Matched cases are handled by the ARG == PARM test above.  */
14644       return 1;
14645
14646     case TYPE_ARGUMENT_PACK:
14647     case NONTYPE_ARGUMENT_PACK:
14648       {
14649         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
14650         tree packed_args = ARGUMENT_PACK_ARGS (arg);
14651         int i, len = TREE_VEC_LENGTH (packed_parms);
14652         int argslen = TREE_VEC_LENGTH (packed_args);
14653         int parm_variadic_p = 0;
14654
14655         for (i = 0; i < len; ++i)
14656           {
14657             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
14658               {
14659                 if (i == len - 1)
14660                   /* We can unify against something with a trailing
14661                      parameter pack.  */
14662                   parm_variadic_p = 1;
14663                 else
14664                   /* Since there is something following the pack
14665                      expansion, we cannot unify this template argument
14666                      list.  */
14667                   return 0;
14668               }
14669           }
14670           
14671
14672         /* If we don't have enough arguments to satisfy the parameters
14673            (not counting the pack expression at the end), or we have
14674            too many arguments for a parameter list that doesn't end in
14675            a pack expression, we can't unify.  */
14676         if (argslen < (len - parm_variadic_p)
14677             || (argslen > len && !parm_variadic_p))
14678           return 1;
14679
14680         /* Unify all of the parameters that precede the (optional)
14681            pack expression.  */
14682         for (i = 0; i < len - parm_variadic_p; ++i)
14683           {
14684             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
14685                        TREE_VEC_ELT (packed_args, i), strict))
14686               return 1;
14687           }
14688
14689         if (parm_variadic_p)
14690           return unify_pack_expansion (tparms, targs, 
14691                                        packed_parms, packed_args,
14692                                        strict, /*call_args_p=*/false,
14693                                        /*subr=*/false);
14694         return 0;
14695       }
14696
14697       break;
14698
14699     case TYPEOF_TYPE:
14700     case DECLTYPE_TYPE:
14701       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
14702          nodes.  */
14703       return 0;
14704
14705     case ERROR_MARK:
14706       /* Unification fails if we hit an error node.  */
14707       return 1;
14708
14709     default:
14710       gcc_assert (EXPR_P (parm));
14711
14712       /* We must be looking at an expression.  This can happen with
14713          something like:
14714
14715            template <int I>
14716            void foo(S<I>, S<I + 2>);
14717
14718          This is a "nondeduced context":
14719
14720            [deduct.type]
14721
14722            The nondeduced contexts are:
14723
14724            --A type that is a template-id in which one or more of
14725              the template-arguments is an expression that references
14726              a template-parameter.
14727
14728          In these cases, we assume deduction succeeded, but don't
14729          actually infer any unifications.  */
14730
14731       if (!uses_template_parms (parm)
14732           && !template_args_equal (parm, arg))
14733         return 1;
14734       else
14735         return 0;
14736     }
14737 }
14738 \f
14739 /* Note that DECL can be defined in this translation unit, if
14740    required.  */
14741
14742 static void
14743 mark_definable (tree decl)
14744 {
14745   tree clone;
14746   DECL_NOT_REALLY_EXTERN (decl) = 1;
14747   FOR_EACH_CLONE (clone, decl)
14748     DECL_NOT_REALLY_EXTERN (clone) = 1;
14749 }
14750
14751 /* Called if RESULT is explicitly instantiated, or is a member of an
14752    explicitly instantiated class.  */
14753
14754 void
14755 mark_decl_instantiated (tree result, int extern_p)
14756 {
14757   SET_DECL_EXPLICIT_INSTANTIATION (result);
14758
14759   /* If this entity has already been written out, it's too late to
14760      make any modifications.  */
14761   if (TREE_ASM_WRITTEN (result))
14762     return;
14763
14764   if (TREE_CODE (result) != FUNCTION_DECL)
14765     /* The TREE_PUBLIC flag for function declarations will have been
14766        set correctly by tsubst.  */
14767     TREE_PUBLIC (result) = 1;
14768
14769   /* This might have been set by an earlier implicit instantiation.  */
14770   DECL_COMDAT (result) = 0;
14771
14772   if (extern_p)
14773     DECL_NOT_REALLY_EXTERN (result) = 0;
14774   else
14775     {
14776       mark_definable (result);
14777       /* Always make artificials weak.  */
14778       if (DECL_ARTIFICIAL (result) && flag_weak)
14779         comdat_linkage (result);
14780       /* For WIN32 we also want to put explicit instantiations in
14781          linkonce sections.  */
14782       else if (TREE_PUBLIC (result))
14783         maybe_make_one_only (result);
14784     }
14785
14786   /* If EXTERN_P, then this function will not be emitted -- unless
14787      followed by an explicit instantiation, at which point its linkage
14788      will be adjusted.  If !EXTERN_P, then this function will be
14789      emitted here.  In neither circumstance do we want
14790      import_export_decl to adjust the linkage.  */
14791   DECL_INTERFACE_KNOWN (result) = 1;
14792 }
14793
14794 /* Given two function templates PAT1 and PAT2, return:
14795
14796    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
14797    -1 if PAT2 is more specialized than PAT1.
14798    0 if neither is more specialized.
14799
14800    LEN indicates the number of parameters we should consider
14801    (defaulted parameters should not be considered).
14802
14803    The 1998 std underspecified function template partial ordering, and
14804    DR214 addresses the issue.  We take pairs of arguments, one from
14805    each of the templates, and deduce them against each other.  One of
14806    the templates will be more specialized if all the *other*
14807    template's arguments deduce against its arguments and at least one
14808    of its arguments *does* *not* deduce against the other template's
14809    corresponding argument.  Deduction is done as for class templates.
14810    The arguments used in deduction have reference and top level cv
14811    qualifiers removed.  Iff both arguments were originally reference
14812    types *and* deduction succeeds in both directions, the template
14813    with the more cv-qualified argument wins for that pairing (if
14814    neither is more cv-qualified, they both are equal).  Unlike regular
14815    deduction, after all the arguments have been deduced in this way,
14816    we do *not* verify the deduced template argument values can be
14817    substituted into non-deduced contexts, nor do we have to verify
14818    that all template arguments have been deduced.  */
14819
14820 int
14821 more_specialized_fn (tree pat1, tree pat2, int len)
14822 {
14823   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
14824   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
14825   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
14826   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
14827   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
14828   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
14829   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
14830   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
14831   int better1 = 0;
14832   int better2 = 0;
14833
14834   /* Remove the this parameter from non-static member functions.  If
14835      one is a non-static member function and the other is not a static
14836      member function, remove the first parameter from that function
14837      also.  This situation occurs for operator functions where we
14838      locate both a member function (with this pointer) and non-member
14839      operator (with explicit first operand).  */
14840   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
14841     {
14842       len--; /* LEN is the number of significant arguments for DECL1 */
14843       args1 = TREE_CHAIN (args1);
14844       if (!DECL_STATIC_FUNCTION_P (decl2))
14845         args2 = TREE_CHAIN (args2);
14846     }
14847   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
14848     {
14849       args2 = TREE_CHAIN (args2);
14850       if (!DECL_STATIC_FUNCTION_P (decl1))
14851         {
14852           len--;
14853           args1 = TREE_CHAIN (args1);
14854         }
14855     }
14856
14857   /* If only one is a conversion operator, they are unordered.  */
14858   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
14859     return 0;
14860
14861   /* Consider the return type for a conversion function */
14862   if (DECL_CONV_FN_P (decl1))
14863     {
14864       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
14865       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
14866       len++;
14867     }
14868
14869   processing_template_decl++;
14870
14871   while (len--
14872          /* Stop when an ellipsis is seen.  */
14873          && args1 != NULL_TREE && args2 != NULL_TREE)
14874     {
14875       tree arg1 = TREE_VALUE (args1);
14876       tree arg2 = TREE_VALUE (args2);
14877       int deduce1, deduce2;
14878       int quals1 = -1;
14879       int quals2 = -1;
14880
14881       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14882           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14883         {
14884           /* When both arguments are pack expansions, we need only
14885              unify the patterns themselves.  */
14886           arg1 = PACK_EXPANSION_PATTERN (arg1);
14887           arg2 = PACK_EXPANSION_PATTERN (arg2);
14888
14889           /* This is the last comparison we need to do.  */
14890           len = 0;
14891         }
14892
14893       if (TREE_CODE (arg1) == REFERENCE_TYPE)
14894         {
14895           arg1 = TREE_TYPE (arg1);
14896           quals1 = cp_type_quals (arg1);
14897         }
14898
14899       if (TREE_CODE (arg2) == REFERENCE_TYPE)
14900         {
14901           arg2 = TREE_TYPE (arg2);
14902           quals2 = cp_type_quals (arg2);
14903         }
14904
14905       if ((quals1 < 0) != (quals2 < 0))
14906         {
14907           /* Only of the args is a reference, see if we should apply
14908              array/function pointer decay to it.  This is not part of
14909              DR214, but is, IMHO, consistent with the deduction rules
14910              for the function call itself, and with our earlier
14911              implementation of the underspecified partial ordering
14912              rules.  (nathan).  */
14913           if (quals1 >= 0)
14914             {
14915               switch (TREE_CODE (arg1))
14916                 {
14917                 case ARRAY_TYPE:
14918                   arg1 = TREE_TYPE (arg1);
14919                   /* FALLTHROUGH. */
14920                 case FUNCTION_TYPE:
14921                   arg1 = build_pointer_type (arg1);
14922                   break;
14923
14924                 default:
14925                   break;
14926                 }
14927             }
14928           else
14929             {
14930               switch (TREE_CODE (arg2))
14931                 {
14932                 case ARRAY_TYPE:
14933                   arg2 = TREE_TYPE (arg2);
14934                   /* FALLTHROUGH. */
14935                 case FUNCTION_TYPE:
14936                   arg2 = build_pointer_type (arg2);
14937                   break;
14938
14939                 default:
14940                   break;
14941                 }
14942             }
14943         }
14944
14945       arg1 = TYPE_MAIN_VARIANT (arg1);
14946       arg2 = TYPE_MAIN_VARIANT (arg2);
14947
14948       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
14949         {
14950           int i, len2 = list_length (args2);
14951           tree parmvec = make_tree_vec (1);
14952           tree argvec = make_tree_vec (len2);
14953           tree ta = args2;
14954
14955           /* Setup the parameter vector, which contains only ARG1.  */
14956           TREE_VEC_ELT (parmvec, 0) = arg1;
14957
14958           /* Setup the argument vector, which contains the remaining
14959              arguments.  */
14960           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
14961             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14962
14963           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
14964                                            argvec, UNIFY_ALLOW_NONE, 
14965                                            /*call_args_p=*/false, 
14966                                            /*subr=*/0);
14967
14968           /* We cannot deduce in the other direction, because ARG1 is
14969              a pack expansion but ARG2 is not.  */
14970           deduce2 = 0;
14971         }
14972       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14973         {
14974           int i, len1 = list_length (args1);
14975           tree parmvec = make_tree_vec (1);
14976           tree argvec = make_tree_vec (len1);
14977           tree ta = args1;
14978
14979           /* Setup the parameter vector, which contains only ARG1.  */
14980           TREE_VEC_ELT (parmvec, 0) = arg2;
14981
14982           /* Setup the argument vector, which contains the remaining
14983              arguments.  */
14984           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
14985             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14986
14987           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
14988                                            argvec, UNIFY_ALLOW_NONE, 
14989                                            /*call_args_p=*/false, 
14990                                            /*subr=*/0);
14991
14992           /* We cannot deduce in the other direction, because ARG2 is
14993              a pack expansion but ARG1 is not.*/
14994           deduce1 = 0;
14995         }
14996
14997       else
14998         {
14999           /* The normal case, where neither argument is a pack
15000              expansion.  */
15001           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15002           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15003         }
15004
15005       if (!deduce1)
15006         better2 = -1;
15007       if (!deduce2)
15008         better1 = -1;
15009       if (better1 < 0 && better2 < 0)
15010         /* We've failed to deduce something in either direction.
15011            These must be unordered.  */
15012         break;
15013
15014       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
15015         {
15016           /* Deduces in both directions, see if quals can
15017              disambiguate.  Pretend the worse one failed to deduce. */
15018           if ((quals1 & quals2) == quals2)
15019             deduce1 = 0;
15020           if ((quals1 & quals2) == quals1)
15021             deduce2 = 0;
15022         }
15023       if (deduce1 && !deduce2 && !better2)
15024         better2 = 1;
15025       if (deduce2 && !deduce1 && !better1)
15026         better1 = 1;
15027
15028       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15029           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15030         /* We have already processed all of the arguments in our
15031            handing of the pack expansion type.  */
15032         len = 0;
15033
15034       args1 = TREE_CHAIN (args1);
15035       args2 = TREE_CHAIN (args2);
15036     }
15037
15038   processing_template_decl--;
15039
15040   /* All things being equal, if the next argument is a pack expansion
15041      for one function but not for the other, prefer the
15042      non-variadic function.  */
15043   if ((better1 > 0) - (better2 > 0) == 0
15044       && args1 && TREE_VALUE (args1)
15045       && args2 && TREE_VALUE (args2))
15046     {
15047       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
15048         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
15049       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
15050         return 1;
15051     }
15052
15053   return (better1 > 0) - (better2 > 0);
15054 }
15055
15056 /* Determine which of two partial specializations is more specialized.
15057
15058    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15059    to the first partial specialization.  The TREE_VALUE is the
15060    innermost set of template parameters for the partial
15061    specialization.  PAT2 is similar, but for the second template.
15062
15063    Return 1 if the first partial specialization is more specialized;
15064    -1 if the second is more specialized; 0 if neither is more
15065    specialized.
15066
15067    See [temp.class.order] for information about determining which of
15068    two templates is more specialized.  */
15069
15070 static int
15071 more_specialized_class (tree pat1, tree pat2)
15072 {
15073   tree targs;
15074   tree tmpl1, tmpl2;
15075   int winner = 0;
15076   bool any_deductions = false;
15077
15078   tmpl1 = TREE_TYPE (pat1);
15079   tmpl2 = TREE_TYPE (pat2);
15080
15081   /* Just like what happens for functions, if we are ordering between
15082      different class template specializations, we may encounter dependent
15083      types in the arguments, and we need our dependency check functions
15084      to behave correctly.  */
15085   ++processing_template_decl;
15086   targs = get_class_bindings (TREE_VALUE (pat1),
15087                               CLASSTYPE_TI_ARGS (tmpl1),
15088                               CLASSTYPE_TI_ARGS (tmpl2));
15089   if (targs)
15090     {
15091       --winner;
15092       any_deductions = true;
15093     }
15094
15095   targs = get_class_bindings (TREE_VALUE (pat2),
15096                               CLASSTYPE_TI_ARGS (tmpl2),
15097                               CLASSTYPE_TI_ARGS (tmpl1));
15098   if (targs)
15099     {
15100       ++winner;
15101       any_deductions = true;
15102     }
15103   --processing_template_decl;
15104
15105   /* In the case of a tie where at least one of the class templates
15106      has a parameter pack at the end, the template with the most
15107      non-packed parameters wins.  */
15108   if (winner == 0
15109       && any_deductions
15110       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15111           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15112     {
15113       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15114       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15115       int len1 = TREE_VEC_LENGTH (args1);
15116       int len2 = TREE_VEC_LENGTH (args2);
15117
15118       /* We don't count the pack expansion at the end.  */
15119       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15120         --len1;
15121       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15122         --len2;
15123
15124       if (len1 > len2)
15125         return 1;
15126       else if (len1 < len2)
15127         return -1;
15128     }
15129
15130   return winner;
15131 }
15132
15133 /* Return the template arguments that will produce the function signature
15134    DECL from the function template FN, with the explicit template
15135    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15136    also match.  Return NULL_TREE if no satisfactory arguments could be
15137    found.  */
15138
15139 static tree
15140 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15141 {
15142   int ntparms = DECL_NTPARMS (fn);
15143   tree targs = make_tree_vec (ntparms);
15144   tree decl_type;
15145   tree decl_arg_types;
15146   tree *args;
15147   unsigned int nargs, ix;
15148   tree arg;
15149
15150   /* Substitute the explicit template arguments into the type of DECL.
15151      The call to fn_type_unification will handle substitution into the
15152      FN.  */
15153   decl_type = TREE_TYPE (decl);
15154   if (explicit_args && uses_template_parms (decl_type))
15155     {
15156       tree tmpl;
15157       tree converted_args;
15158
15159       if (DECL_TEMPLATE_INFO (decl))
15160         tmpl = DECL_TI_TEMPLATE (decl);
15161       else
15162         /* We can get here for some invalid specializations.  */
15163         return NULL_TREE;
15164
15165       converted_args
15166         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15167                                  explicit_args, NULL_TREE,
15168                                  tf_none,
15169                                  /*require_all_args=*/false,
15170                                  /*use_default_args=*/false);
15171       if (converted_args == error_mark_node)
15172         return NULL_TREE;
15173
15174       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15175       if (decl_type == error_mark_node)
15176         return NULL_TREE;
15177     }
15178
15179   /* Never do unification on the 'this' parameter.  */
15180   decl_arg_types = skip_artificial_parms_for (decl, 
15181                                               TYPE_ARG_TYPES (decl_type));
15182
15183   nargs = list_length (decl_arg_types);
15184   args = XALLOCAVEC (tree, nargs);
15185   for (arg = decl_arg_types, ix = 0;
15186        arg != NULL_TREE && arg != void_list_node;
15187        arg = TREE_CHAIN (arg), ++ix)
15188     args[ix] = TREE_VALUE (arg);
15189
15190   if (fn_type_unification (fn, explicit_args, targs,
15191                            args, ix,
15192                            (check_rettype || DECL_CONV_FN_P (fn)
15193                             ? TREE_TYPE (decl_type) : NULL_TREE),
15194                            DEDUCE_EXACT, LOOKUP_NORMAL))
15195     return NULL_TREE;
15196
15197   return targs;
15198 }
15199
15200 /* Return the innermost template arguments that, when applied to a
15201    template specialization whose innermost template parameters are
15202    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15203    ARGS.
15204
15205    For example, suppose we have:
15206
15207      template <class T, class U> struct S {};
15208      template <class T> struct S<T*, int> {};
15209
15210    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15211    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15212    int}.  The resulting vector will be {double}, indicating that `T'
15213    is bound to `double'.  */
15214
15215 static tree
15216 get_class_bindings (tree tparms, tree spec_args, tree args)
15217 {
15218   int i, ntparms = TREE_VEC_LENGTH (tparms);
15219   tree deduced_args;
15220   tree innermost_deduced_args;
15221
15222   innermost_deduced_args = make_tree_vec (ntparms);
15223   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15224     {
15225       deduced_args = copy_node (args);
15226       SET_TMPL_ARGS_LEVEL (deduced_args,
15227                            TMPL_ARGS_DEPTH (deduced_args),
15228                            innermost_deduced_args);
15229     }
15230   else
15231     deduced_args = innermost_deduced_args;
15232
15233   if (unify (tparms, deduced_args,
15234              INNERMOST_TEMPLATE_ARGS (spec_args),
15235              INNERMOST_TEMPLATE_ARGS (args),
15236              UNIFY_ALLOW_NONE))
15237     return NULL_TREE;
15238
15239   for (i =  0; i < ntparms; ++i)
15240     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15241       return NULL_TREE;
15242
15243   /* Verify that nondeduced template arguments agree with the type
15244      obtained from argument deduction.
15245
15246      For example:
15247
15248        struct A { typedef int X; };
15249        template <class T, class U> struct C {};
15250        template <class T> struct C<T, typename T::X> {};
15251
15252      Then with the instantiation `C<A, int>', we can deduce that
15253      `T' is `A' but unify () does not check whether `typename T::X'
15254      is `int'.  */
15255   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15256   if (spec_args == error_mark_node
15257       /* We only need to check the innermost arguments; the other
15258          arguments will always agree.  */
15259       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15260                               INNERMOST_TEMPLATE_ARGS (args)))
15261     return NULL_TREE;
15262
15263   /* Now that we have bindings for all of the template arguments,
15264      ensure that the arguments deduced for the template template
15265      parameters have compatible template parameter lists.  See the use
15266      of template_template_parm_bindings_ok_p in fn_type_unification
15267      for more information.  */
15268   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15269     return NULL_TREE;
15270
15271   return deduced_args;
15272 }
15273
15274 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15275    Return the TREE_LIST node with the most specialized template, if
15276    any.  If there is no most specialized template, the error_mark_node
15277    is returned.
15278
15279    Note that this function does not look at, or modify, the
15280    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15281    returned is one of the elements of INSTANTIATIONS, callers may
15282    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15283    and retrieve it from the value returned.  */
15284
15285 tree
15286 most_specialized_instantiation (tree templates)
15287 {
15288   tree fn, champ;
15289
15290   ++processing_template_decl;
15291
15292   champ = templates;
15293   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15294     {
15295       int fate = 0;
15296
15297       if (get_bindings (TREE_VALUE (champ),
15298                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15299                         NULL_TREE, /*check_ret=*/false))
15300         fate--;
15301
15302       if (get_bindings (TREE_VALUE (fn),
15303                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15304                         NULL_TREE, /*check_ret=*/false))
15305         fate++;
15306
15307       if (fate == -1)
15308         champ = fn;
15309       else if (!fate)
15310         {
15311           /* Equally specialized, move to next function.  If there
15312              is no next function, nothing's most specialized.  */
15313           fn = TREE_CHAIN (fn);
15314           champ = fn;
15315           if (!fn)
15316             break;
15317         }
15318     }
15319
15320   if (champ)
15321     /* Now verify that champ is better than everything earlier in the
15322        instantiation list.  */
15323     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15324       if (get_bindings (TREE_VALUE (champ),
15325                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15326                         NULL_TREE, /*check_ret=*/false)
15327           || !get_bindings (TREE_VALUE (fn),
15328                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15329                             NULL_TREE, /*check_ret=*/false))
15330         {
15331           champ = NULL_TREE;
15332           break;
15333         }
15334
15335   processing_template_decl--;
15336
15337   if (!champ)
15338     return error_mark_node;
15339
15340   return champ;
15341 }
15342
15343 /* If DECL is a specialization of some template, return the most
15344    general such template.  Otherwise, returns NULL_TREE.
15345
15346    For example, given:
15347
15348      template <class T> struct S { template <class U> void f(U); };
15349
15350    if TMPL is `template <class U> void S<int>::f(U)' this will return
15351    the full template.  This function will not trace past partial
15352    specializations, however.  For example, given in addition:
15353
15354      template <class T> struct S<T*> { template <class U> void f(U); };
15355
15356    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15357    `template <class T> template <class U> S<T*>::f(U)'.  */
15358
15359 tree
15360 most_general_template (tree decl)
15361 {
15362   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15363      an immediate specialization.  */
15364   if (TREE_CODE (decl) == FUNCTION_DECL)
15365     {
15366       if (DECL_TEMPLATE_INFO (decl)) {
15367         decl = DECL_TI_TEMPLATE (decl);
15368
15369         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15370            template friend.  */
15371         if (TREE_CODE (decl) != TEMPLATE_DECL)
15372           return NULL_TREE;
15373       } else
15374         return NULL_TREE;
15375     }
15376
15377   /* Look for more and more general templates.  */
15378   while (DECL_TEMPLATE_INFO (decl))
15379     {
15380       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15381          (See cp-tree.h for details.)  */
15382       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15383         break;
15384
15385       if (CLASS_TYPE_P (TREE_TYPE (decl))
15386           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15387         break;
15388
15389       /* Stop if we run into an explicitly specialized class template.  */
15390       if (!DECL_NAMESPACE_SCOPE_P (decl)
15391           && DECL_CONTEXT (decl)
15392           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15393         break;
15394
15395       decl = DECL_TI_TEMPLATE (decl);
15396     }
15397
15398   return decl;
15399 }
15400
15401 /* Return the most specialized of the class template partial
15402    specializations of TMPL which can produce TYPE, a specialization of
15403    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15404    a _TYPE node corresponding to the partial specialization, while the
15405    TREE_PURPOSE is the set of template arguments that must be
15406    substituted into the TREE_TYPE in order to generate TYPE.
15407
15408    If the choice of partial specialization is ambiguous, a diagnostic
15409    is issued, and the error_mark_node is returned.  If there are no
15410    partial specializations of TMPL matching TYPE, then NULL_TREE is
15411    returned.  */
15412
15413 static tree
15414 most_specialized_class (tree type, tree tmpl)
15415 {
15416   tree list = NULL_TREE;
15417   tree t;
15418   tree champ;
15419   int fate;
15420   bool ambiguous_p;
15421   tree args;
15422   tree outer_args = NULL_TREE;
15423
15424   tmpl = most_general_template (tmpl);
15425   args = CLASSTYPE_TI_ARGS (type);
15426
15427   /* For determining which partial specialization to use, only the
15428      innermost args are interesting.  */
15429   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15430     {
15431       outer_args = strip_innermost_template_args (args, 1);
15432       args = INNERMOST_TEMPLATE_ARGS (args);
15433     }
15434
15435   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15436     {
15437       tree partial_spec_args;
15438       tree spec_args;
15439       tree parms = TREE_VALUE (t);
15440
15441       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15442       if (outer_args)
15443         {
15444           int i;
15445
15446           ++processing_template_decl;
15447
15448           /* Discard the outer levels of args, and then substitute in the
15449              template args from the enclosing class.  */
15450           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
15451           partial_spec_args = tsubst_template_args
15452             (partial_spec_args, outer_args, tf_none, NULL_TREE);
15453
15454           /* PARMS already refers to just the innermost parms, but the
15455              template parms in partial_spec_args had their levels lowered
15456              by tsubst, so we need to do the same for the parm list.  We
15457              can't just tsubst the TREE_VEC itself, as tsubst wants to
15458              treat a TREE_VEC as an argument vector.  */
15459           parms = copy_node (parms);
15460           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
15461             TREE_VEC_ELT (parms, i) =
15462               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
15463
15464           --processing_template_decl;
15465         }
15466       spec_args = get_class_bindings (parms,
15467                                       partial_spec_args,
15468                                       args);
15469       if (spec_args)
15470         {
15471           if (outer_args)
15472             spec_args = add_to_template_args (outer_args, spec_args);
15473           list = tree_cons (spec_args, TREE_VALUE (t), list);
15474           TREE_TYPE (list) = TREE_TYPE (t);
15475         }
15476     }
15477
15478   if (! list)
15479     return NULL_TREE;
15480
15481   ambiguous_p = false;
15482   t = list;
15483   champ = t;
15484   t = TREE_CHAIN (t);
15485   for (; t; t = TREE_CHAIN (t))
15486     {
15487       fate = more_specialized_class (champ, t);
15488       if (fate == 1)
15489         ;
15490       else
15491         {
15492           if (fate == 0)
15493             {
15494               t = TREE_CHAIN (t);
15495               if (! t)
15496                 {
15497                   ambiguous_p = true;
15498                   break;
15499                 }
15500             }
15501           champ = t;
15502         }
15503     }
15504
15505   if (!ambiguous_p)
15506     for (t = list; t && t != champ; t = TREE_CHAIN (t))
15507       {
15508         fate = more_specialized_class (champ, t);
15509         if (fate != 1)
15510           {
15511             ambiguous_p = true;
15512             break;
15513           }
15514       }
15515
15516   if (ambiguous_p)
15517     {
15518       const char *str = "candidates are:";
15519       error ("ambiguous class template instantiation for %q#T", type);
15520       for (t = list; t; t = TREE_CHAIN (t))
15521         {
15522           error ("%s %+#T", str, TREE_TYPE (t));
15523           str = "               ";
15524         }
15525       return error_mark_node;
15526     }
15527
15528   return champ;
15529 }
15530
15531 /* Explicitly instantiate DECL.  */
15532
15533 void
15534 do_decl_instantiation (tree decl, tree storage)
15535 {
15536   tree result = NULL_TREE;
15537   int extern_p = 0;
15538
15539   if (!decl || decl == error_mark_node)
15540     /* An error occurred, for which grokdeclarator has already issued
15541        an appropriate message.  */
15542     return;
15543   else if (! DECL_LANG_SPECIFIC (decl))
15544     {
15545       error ("explicit instantiation of non-template %q#D", decl);
15546       return;
15547     }
15548   else if (TREE_CODE (decl) == VAR_DECL)
15549     {
15550       /* There is an asymmetry here in the way VAR_DECLs and
15551          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
15552          the latter, the DECL we get back will be marked as a
15553          template instantiation, and the appropriate
15554          DECL_TEMPLATE_INFO will be set up.  This does not happen for
15555          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
15556          should handle VAR_DECLs as it currently handles
15557          FUNCTION_DECLs.  */
15558       if (!DECL_CLASS_SCOPE_P (decl))
15559         {
15560           error ("%qD is not a static data member of a class template", decl);
15561           return;
15562         }
15563       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
15564       if (!result || TREE_CODE (result) != VAR_DECL)
15565         {
15566           error ("no matching template for %qD found", decl);
15567           return;
15568         }
15569       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
15570         {
15571           error ("type %qT for explicit instantiation %qD does not match "
15572                  "declared type %qT", TREE_TYPE (result), decl,
15573                  TREE_TYPE (decl));
15574           return;
15575         }
15576     }
15577   else if (TREE_CODE (decl) != FUNCTION_DECL)
15578     {
15579       error ("explicit instantiation of %q#D", decl);
15580       return;
15581     }
15582   else
15583     result = decl;
15584
15585   /* Check for various error cases.  Note that if the explicit
15586      instantiation is valid the RESULT will currently be marked as an
15587      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
15588      until we get here.  */
15589
15590   if (DECL_TEMPLATE_SPECIALIZATION (result))
15591     {
15592       /* DR 259 [temp.spec].
15593
15594          Both an explicit instantiation and a declaration of an explicit
15595          specialization shall not appear in a program unless the explicit
15596          instantiation follows a declaration of the explicit specialization.
15597
15598          For a given set of template parameters, if an explicit
15599          instantiation of a template appears after a declaration of an
15600          explicit specialization for that template, the explicit
15601          instantiation has no effect.  */
15602       return;
15603     }
15604   else if (DECL_EXPLICIT_INSTANTIATION (result))
15605     {
15606       /* [temp.spec]
15607
15608          No program shall explicitly instantiate any template more
15609          than once.
15610
15611          We check DECL_NOT_REALLY_EXTERN so as not to complain when
15612          the first instantiation was `extern' and the second is not,
15613          and EXTERN_P for the opposite case.  */
15614       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
15615         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
15616       /* If an "extern" explicit instantiation follows an ordinary
15617          explicit instantiation, the template is instantiated.  */
15618       if (extern_p)
15619         return;
15620     }
15621   else if (!DECL_IMPLICIT_INSTANTIATION (result))
15622     {
15623       error ("no matching template for %qD found", result);
15624       return;
15625     }
15626   else if (!DECL_TEMPLATE_INFO (result))
15627     {
15628       permerror (input_location, "explicit instantiation of non-template %q#D", result);
15629       return;
15630     }
15631
15632   if (storage == NULL_TREE)
15633     ;
15634   else if (storage == ridpointers[(int) RID_EXTERN])
15635     {
15636       if (!in_system_header && (cxx_dialect == cxx98))
15637         pedwarn (input_location, OPT_pedantic, 
15638                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
15639                  "instantiations");
15640       extern_p = 1;
15641     }
15642   else
15643     error ("storage class %qD applied to template instantiation", storage);
15644
15645   check_explicit_instantiation_namespace (result);
15646   mark_decl_instantiated (result, extern_p);
15647   if (! extern_p)
15648     instantiate_decl (result, /*defer_ok=*/1,
15649                       /*expl_inst_class_mem_p=*/false);
15650 }
15651
15652 static void
15653 mark_class_instantiated (tree t, int extern_p)
15654 {
15655   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
15656   SET_CLASSTYPE_INTERFACE_KNOWN (t);
15657   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
15658   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
15659   if (! extern_p)
15660     {
15661       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
15662       rest_of_type_compilation (t, 1);
15663     }
15664 }
15665
15666 /* Called from do_type_instantiation through binding_table_foreach to
15667    do recursive instantiation for the type bound in ENTRY.  */
15668 static void
15669 bt_instantiate_type_proc (binding_entry entry, void *data)
15670 {
15671   tree storage = *(tree *) data;
15672
15673   if (MAYBE_CLASS_TYPE_P (entry->type)
15674       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
15675     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
15676 }
15677
15678 /* Called from do_type_instantiation to instantiate a member
15679    (a member function or a static member variable) of an
15680    explicitly instantiated class template.  */
15681 static void
15682 instantiate_class_member (tree decl, int extern_p)
15683 {
15684   mark_decl_instantiated (decl, extern_p);
15685   if (! extern_p)
15686     instantiate_decl (decl, /*defer_ok=*/1,
15687                       /*expl_inst_class_mem_p=*/true);
15688 }
15689
15690 /* Perform an explicit instantiation of template class T.  STORAGE, if
15691    non-null, is the RID for extern, inline or static.  COMPLAIN is
15692    nonzero if this is called from the parser, zero if called recursively,
15693    since the standard is unclear (as detailed below).  */
15694
15695 void
15696 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
15697 {
15698   int extern_p = 0;
15699   int nomem_p = 0;
15700   int static_p = 0;
15701   int previous_instantiation_extern_p = 0;
15702
15703   if (TREE_CODE (t) == TYPE_DECL)
15704     t = TREE_TYPE (t);
15705
15706   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
15707     {
15708       error ("explicit instantiation of non-template type %qT", t);
15709       return;
15710     }
15711
15712   complete_type (t);
15713
15714   if (!COMPLETE_TYPE_P (t))
15715     {
15716       if (complain & tf_error)
15717         error ("explicit instantiation of %q#T before definition of template",
15718                t);
15719       return;
15720     }
15721
15722   if (storage != NULL_TREE)
15723     {
15724       if (!in_system_header)
15725         {
15726           if (storage == ridpointers[(int) RID_EXTERN])
15727             {
15728               if (cxx_dialect == cxx98)
15729                 pedwarn (input_location, OPT_pedantic, 
15730                          "ISO C++ 1998 forbids the use of %<extern%> on "
15731                          "explicit instantiations");
15732             }
15733           else
15734             pedwarn (input_location, OPT_pedantic, 
15735                      "ISO C++ forbids the use of %qE"
15736                      " on explicit instantiations", storage);
15737         }
15738
15739       if (storage == ridpointers[(int) RID_INLINE])
15740         nomem_p = 1;
15741       else if (storage == ridpointers[(int) RID_EXTERN])
15742         extern_p = 1;
15743       else if (storage == ridpointers[(int) RID_STATIC])
15744         static_p = 1;
15745       else
15746         {
15747           error ("storage class %qD applied to template instantiation",
15748                  storage);
15749           extern_p = 0;
15750         }
15751     }
15752
15753   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
15754     {
15755       /* DR 259 [temp.spec].
15756
15757          Both an explicit instantiation and a declaration of an explicit
15758          specialization shall not appear in a program unless the explicit
15759          instantiation follows a declaration of the explicit specialization.
15760
15761          For a given set of template parameters, if an explicit
15762          instantiation of a template appears after a declaration of an
15763          explicit specialization for that template, the explicit
15764          instantiation has no effect.  */
15765       return;
15766     }
15767   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
15768     {
15769       /* [temp.spec]
15770
15771          No program shall explicitly instantiate any template more
15772          than once.
15773
15774          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
15775          instantiation was `extern'.  If EXTERN_P then the second is.
15776          These cases are OK.  */
15777       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
15778
15779       if (!previous_instantiation_extern_p && !extern_p
15780           && (complain & tf_error))
15781         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
15782
15783       /* If we've already instantiated the template, just return now.  */
15784       if (!CLASSTYPE_INTERFACE_ONLY (t))
15785         return;
15786     }
15787
15788   check_explicit_instantiation_namespace (TYPE_NAME (t));
15789   mark_class_instantiated (t, extern_p);
15790
15791   if (nomem_p)
15792     return;
15793
15794   {
15795     tree tmp;
15796
15797     /* In contrast to implicit instantiation, where only the
15798        declarations, and not the definitions, of members are
15799        instantiated, we have here:
15800
15801          [temp.explicit]
15802
15803          The explicit instantiation of a class template specialization
15804          implies the instantiation of all of its members not
15805          previously explicitly specialized in the translation unit
15806          containing the explicit instantiation.
15807
15808        Of course, we can't instantiate member template classes, since
15809        we don't have any arguments for them.  Note that the standard
15810        is unclear on whether the instantiation of the members are
15811        *explicit* instantiations or not.  However, the most natural
15812        interpretation is that it should be an explicit instantiation.  */
15813
15814     if (! static_p)
15815       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
15816         if (TREE_CODE (tmp) == FUNCTION_DECL
15817             && DECL_TEMPLATE_INSTANTIATION (tmp))
15818           instantiate_class_member (tmp, extern_p);
15819
15820     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
15821       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
15822         instantiate_class_member (tmp, extern_p);
15823
15824     if (CLASSTYPE_NESTED_UTDS (t))
15825       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
15826                              bt_instantiate_type_proc, &storage);
15827   }
15828 }
15829
15830 /* Given a function DECL, which is a specialization of TMPL, modify
15831    DECL to be a re-instantiation of TMPL with the same template
15832    arguments.  TMPL should be the template into which tsubst'ing
15833    should occur for DECL, not the most general template.
15834
15835    One reason for doing this is a scenario like this:
15836
15837      template <class T>
15838      void f(const T&, int i);
15839
15840      void g() { f(3, 7); }
15841
15842      template <class T>
15843      void f(const T& t, const int i) { }
15844
15845    Note that when the template is first instantiated, with
15846    instantiate_template, the resulting DECL will have no name for the
15847    first parameter, and the wrong type for the second.  So, when we go
15848    to instantiate the DECL, we regenerate it.  */
15849
15850 static void
15851 regenerate_decl_from_template (tree decl, tree tmpl)
15852 {
15853   /* The arguments used to instantiate DECL, from the most general
15854      template.  */
15855   tree args;
15856   tree code_pattern;
15857
15858   args = DECL_TI_ARGS (decl);
15859   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
15860
15861   /* Make sure that we can see identifiers, and compute access
15862      correctly.  */
15863   push_access_scope (decl);
15864
15865   if (TREE_CODE (decl) == FUNCTION_DECL)
15866     {
15867       tree decl_parm;
15868       tree pattern_parm;
15869       tree specs;
15870       int args_depth;
15871       int parms_depth;
15872
15873       args_depth = TMPL_ARGS_DEPTH (args);
15874       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
15875       if (args_depth > parms_depth)
15876         args = get_innermost_template_args (args, parms_depth);
15877
15878       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
15879                                               args, tf_error, NULL_TREE);
15880       if (specs)
15881         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
15882                                                     specs);
15883
15884       /* Merge parameter declarations.  */
15885       decl_parm = skip_artificial_parms_for (decl,
15886                                              DECL_ARGUMENTS (decl));
15887       pattern_parm
15888         = skip_artificial_parms_for (code_pattern,
15889                                      DECL_ARGUMENTS (code_pattern));
15890       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
15891         {
15892           tree parm_type;
15893           tree attributes;
15894           
15895           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15896             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
15897           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
15898                               NULL_TREE);
15899           parm_type = type_decays_to (parm_type);
15900           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15901             TREE_TYPE (decl_parm) = parm_type;
15902           attributes = DECL_ATTRIBUTES (pattern_parm);
15903           if (DECL_ATTRIBUTES (decl_parm) != attributes)
15904             {
15905               DECL_ATTRIBUTES (decl_parm) = attributes;
15906               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15907             }
15908           decl_parm = TREE_CHAIN (decl_parm);
15909           pattern_parm = TREE_CHAIN (pattern_parm);
15910         }
15911       /* Merge any parameters that match with the function parameter
15912          pack.  */
15913       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
15914         {
15915           int i, len;
15916           tree expanded_types;
15917           /* Expand the TYPE_PACK_EXPANSION that provides the types for
15918              the parameters in this function parameter pack.  */
15919           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
15920                                                  args, tf_error, NULL_TREE);
15921           len = TREE_VEC_LENGTH (expanded_types);
15922           for (i = 0; i < len; i++)
15923             {
15924               tree parm_type;
15925               tree attributes;
15926           
15927               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15928                 /* Rename the parameter to include the index.  */
15929                 DECL_NAME (decl_parm) = 
15930                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
15931               parm_type = TREE_VEC_ELT (expanded_types, i);
15932               parm_type = type_decays_to (parm_type);
15933               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15934                 TREE_TYPE (decl_parm) = parm_type;
15935               attributes = DECL_ATTRIBUTES (pattern_parm);
15936               if (DECL_ATTRIBUTES (decl_parm) != attributes)
15937                 {
15938                   DECL_ATTRIBUTES (decl_parm) = attributes;
15939                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15940                 }
15941               decl_parm = TREE_CHAIN (decl_parm);
15942             }
15943         }
15944       /* Merge additional specifiers from the CODE_PATTERN.  */
15945       if (DECL_DECLARED_INLINE_P (code_pattern)
15946           && !DECL_DECLARED_INLINE_P (decl))
15947         DECL_DECLARED_INLINE_P (decl) = 1;
15948     }
15949   else if (TREE_CODE (decl) == VAR_DECL)
15950     DECL_INITIAL (decl) =
15951       tsubst_expr (DECL_INITIAL (code_pattern), args,
15952                    tf_error, DECL_TI_TEMPLATE (decl),
15953                    /*integral_constant_expression_p=*/false);
15954   else
15955     gcc_unreachable ();
15956
15957   pop_access_scope (decl);
15958 }
15959
15960 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
15961    substituted to get DECL.  */
15962
15963 tree
15964 template_for_substitution (tree decl)
15965 {
15966   tree tmpl = DECL_TI_TEMPLATE (decl);
15967
15968   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
15969      for the instantiation.  This is not always the most general
15970      template.  Consider, for example:
15971
15972         template <class T>
15973         struct S { template <class U> void f();
15974                    template <> void f<int>(); };
15975
15976      and an instantiation of S<double>::f<int>.  We want TD to be the
15977      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
15978   while (/* An instantiation cannot have a definition, so we need a
15979             more general template.  */
15980          DECL_TEMPLATE_INSTANTIATION (tmpl)
15981            /* We must also deal with friend templates.  Given:
15982
15983                 template <class T> struct S {
15984                   template <class U> friend void f() {};
15985                 };
15986
15987               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
15988               so far as the language is concerned, but that's still
15989               where we get the pattern for the instantiation from.  On
15990               other hand, if the definition comes outside the class, say:
15991
15992                 template <class T> struct S {
15993                   template <class U> friend void f();
15994                 };
15995                 template <class U> friend void f() {}
15996
15997               we don't need to look any further.  That's what the check for
15998               DECL_INITIAL is for.  */
15999           || (TREE_CODE (decl) == FUNCTION_DECL
16000               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16001               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16002     {
16003       /* The present template, TD, should not be a definition.  If it
16004          were a definition, we should be using it!  Note that we
16005          cannot restructure the loop to just keep going until we find
16006          a template with a definition, since that might go too far if
16007          a specialization was declared, but not defined.  */
16008       gcc_assert (TREE_CODE (decl) != VAR_DECL
16009                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16010
16011       /* Fetch the more general template.  */
16012       tmpl = DECL_TI_TEMPLATE (tmpl);
16013     }
16014
16015   return tmpl;
16016 }
16017
16018 /* Returns true if we need to instantiate this template instance even if we
16019    know we aren't going to emit it..  */
16020
16021 bool
16022 always_instantiate_p (tree decl)
16023 {
16024   /* We always instantiate inline functions so that we can inline them.  An
16025      explicit instantiation declaration prohibits implicit instantiation of
16026      non-inline functions.  With high levels of optimization, we would
16027      normally inline non-inline functions -- but we're not allowed to do
16028      that for "extern template" functions.  Therefore, we check
16029      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16030   return ((TREE_CODE (decl) == FUNCTION_DECL
16031            && DECL_DECLARED_INLINE_P (decl))
16032           /* And we need to instantiate static data members so that
16033              their initializers are available in integral constant
16034              expressions.  */
16035           || (TREE_CODE (decl) == VAR_DECL
16036               && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16037 }
16038
16039 /* Produce the definition of D, a _DECL generated from a template.  If
16040    DEFER_OK is nonzero, then we don't have to actually do the
16041    instantiation now; we just have to do it sometime.  Normally it is
16042    an error if this is an explicit instantiation but D is undefined.
16043    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16044    explicitly instantiated class template.  */
16045
16046 tree
16047 instantiate_decl (tree d, int defer_ok,
16048                   bool expl_inst_class_mem_p)
16049 {
16050   tree tmpl = DECL_TI_TEMPLATE (d);
16051   tree gen_args;
16052   tree args;
16053   tree td;
16054   tree code_pattern;
16055   tree spec;
16056   tree gen_tmpl;
16057   bool pattern_defined;
16058   int need_push;
16059   location_t saved_loc = input_location;
16060   bool external_p;
16061
16062   /* This function should only be used to instantiate templates for
16063      functions and static member variables.  */
16064   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16065               || TREE_CODE (d) == VAR_DECL);
16066
16067   /* Variables are never deferred; if instantiation is required, they
16068      are instantiated right away.  That allows for better code in the
16069      case that an expression refers to the value of the variable --
16070      if the variable has a constant value the referring expression can
16071      take advantage of that fact.  */
16072   if (TREE_CODE (d) == VAR_DECL)
16073     defer_ok = 0;
16074
16075   /* Don't instantiate cloned functions.  Instead, instantiate the
16076      functions they cloned.  */
16077   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16078     d = DECL_CLONED_FUNCTION (d);
16079
16080   if (DECL_TEMPLATE_INSTANTIATED (d)
16081       || DECL_TEMPLATE_SPECIALIZATION (d))
16082     /* D has already been instantiated or explicitly specialized, so
16083        there's nothing for us to do here.
16084
16085        It might seem reasonable to check whether or not D is an explicit
16086        instantiation, and, if so, stop here.  But when an explicit
16087        instantiation is deferred until the end of the compilation,
16088        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16089        the instantiation.  */
16090     return d;
16091
16092   /* Check to see whether we know that this template will be
16093      instantiated in some other file, as with "extern template"
16094      extension.  */
16095   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16096
16097   /* In general, we do not instantiate such templates.  */
16098   if (external_p && !always_instantiate_p (d))
16099     return d;
16100
16101   gen_tmpl = most_general_template (tmpl);
16102   gen_args = DECL_TI_ARGS (d);
16103
16104   if (tmpl != gen_tmpl)
16105     /* We should already have the extra args.  */
16106     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16107                 == TMPL_ARGS_DEPTH (gen_args));
16108   /* And what's in the hash table should match D.  */
16109   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16110               || spec == NULL_TREE);
16111
16112   /* This needs to happen before any tsubsting.  */
16113   if (! push_tinst_level (d))
16114     return d;
16115
16116   timevar_push (TV_PARSE);
16117
16118   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16119      for the instantiation.  */
16120   td = template_for_substitution (d);
16121   code_pattern = DECL_TEMPLATE_RESULT (td);
16122
16123   /* We should never be trying to instantiate a member of a class
16124      template or partial specialization.  */
16125   gcc_assert (d != code_pattern);
16126
16127   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16128       || DECL_TEMPLATE_SPECIALIZATION (td))
16129     /* In the case of a friend template whose definition is provided
16130        outside the class, we may have too many arguments.  Drop the
16131        ones we don't need.  The same is true for specializations.  */
16132     args = get_innermost_template_args
16133       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16134   else
16135     args = gen_args;
16136
16137   if (TREE_CODE (d) == FUNCTION_DECL)
16138     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16139   else
16140     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16141
16142   /* We may be in the middle of deferred access check.  Disable it now.  */
16143   push_deferring_access_checks (dk_no_deferred);
16144
16145   /* Unless an explicit instantiation directive has already determined
16146      the linkage of D, remember that a definition is available for
16147      this entity.  */
16148   if (pattern_defined
16149       && !DECL_INTERFACE_KNOWN (d)
16150       && !DECL_NOT_REALLY_EXTERN (d))
16151     mark_definable (d);
16152
16153   input_location = DECL_SOURCE_LOCATION (d);
16154
16155   /* If D is a member of an explicitly instantiated class template,
16156      and no definition is available, treat it like an implicit
16157      instantiation.  */
16158   if (!pattern_defined && expl_inst_class_mem_p
16159       && DECL_EXPLICIT_INSTANTIATION (d))
16160     {
16161       DECL_NOT_REALLY_EXTERN (d) = 0;
16162       DECL_INTERFACE_KNOWN (d) = 0;
16163       SET_DECL_IMPLICIT_INSTANTIATION (d);
16164     }
16165
16166   /* Recheck the substitutions to obtain any warning messages
16167      about ignoring cv qualifiers.  Don't do this for artificial decls,
16168      as it breaks the context-sensitive substitution for lambda op(). */
16169   if (!defer_ok && !DECL_ARTIFICIAL (d))
16170     {
16171       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16172       tree type = TREE_TYPE (gen);
16173
16174       /* Make sure that we can see identifiers, and compute access
16175          correctly.  D is already the target FUNCTION_DECL with the
16176          right context.  */
16177       push_access_scope (d);
16178
16179       if (TREE_CODE (gen) == FUNCTION_DECL)
16180         {
16181           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16182           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16183                                           d);
16184           /* Don't simply tsubst the function type, as that will give
16185              duplicate warnings about poor parameter qualifications.
16186              The function arguments are the same as the decl_arguments
16187              without the top level cv qualifiers.  */
16188           type = TREE_TYPE (type);
16189         }
16190       tsubst (type, gen_args, tf_warning_or_error, d);
16191
16192       pop_access_scope (d);
16193     }
16194
16195   /* Defer all other templates, unless we have been explicitly
16196      forbidden from doing so.  */
16197   if (/* If there is no definition, we cannot instantiate the
16198          template.  */
16199       ! pattern_defined
16200       /* If it's OK to postpone instantiation, do so.  */
16201       || defer_ok
16202       /* If this is a static data member that will be defined
16203          elsewhere, we don't want to instantiate the entire data
16204          member, but we do want to instantiate the initializer so that
16205          we can substitute that elsewhere.  */
16206       || (external_p && TREE_CODE (d) == VAR_DECL))
16207     {
16208       /* The definition of the static data member is now required so
16209          we must substitute the initializer.  */
16210       if (TREE_CODE (d) == VAR_DECL
16211           && !DECL_INITIAL (d)
16212           && DECL_INITIAL (code_pattern))
16213         {
16214           tree ns;
16215           tree init;
16216
16217           ns = decl_namespace_context (d);
16218           push_nested_namespace (ns);
16219           push_nested_class (DECL_CONTEXT (d));
16220           init = tsubst_expr (DECL_INITIAL (code_pattern),
16221                               args,
16222                               tf_warning_or_error, NULL_TREE,
16223                               /*integral_constant_expression_p=*/false);
16224           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16225                           /*asmspec_tree=*/NULL_TREE,
16226                           LOOKUP_ONLYCONVERTING);
16227           pop_nested_class ();
16228           pop_nested_namespace (ns);
16229         }
16230
16231       /* We restore the source position here because it's used by
16232          add_pending_template.  */
16233       input_location = saved_loc;
16234
16235       if (at_eof && !pattern_defined
16236           && DECL_EXPLICIT_INSTANTIATION (d)
16237           && DECL_NOT_REALLY_EXTERN (d))
16238         /* [temp.explicit]
16239
16240            The definition of a non-exported function template, a
16241            non-exported member function template, or a non-exported
16242            member function or static data member of a class template
16243            shall be present in every translation unit in which it is
16244            explicitly instantiated.  */
16245         permerror (input_location,  "explicit instantiation of %qD "
16246                    "but no definition available", d);
16247
16248       /* ??? Historically, we have instantiated inline functions, even
16249          when marked as "extern template".  */
16250       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16251         add_pending_template (d);
16252       goto out;
16253     }
16254   /* Tell the repository that D is available in this translation unit
16255      -- and see if it is supposed to be instantiated here.  */
16256   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16257     {
16258       /* In a PCH file, despite the fact that the repository hasn't
16259          requested instantiation in the PCH it is still possible that
16260          an instantiation will be required in a file that includes the
16261          PCH.  */
16262       if (pch_file)
16263         add_pending_template (d);
16264       /* Instantiate inline functions so that the inliner can do its
16265          job, even though we'll not be emitting a copy of this
16266          function.  */
16267       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16268         goto out;
16269     }
16270
16271   need_push = !cfun || !global_bindings_p ();
16272   if (need_push)
16273     push_to_top_level ();
16274
16275   /* Mark D as instantiated so that recursive calls to
16276      instantiate_decl do not try to instantiate it again.  */
16277   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16278
16279   /* Regenerate the declaration in case the template has been modified
16280      by a subsequent redeclaration.  */
16281   regenerate_decl_from_template (d, td);
16282
16283   /* We already set the file and line above.  Reset them now in case
16284      they changed as a result of calling regenerate_decl_from_template.  */
16285   input_location = DECL_SOURCE_LOCATION (d);
16286
16287   if (TREE_CODE (d) == VAR_DECL)
16288     {
16289       tree init;
16290
16291       /* Clear out DECL_RTL; whatever was there before may not be right
16292          since we've reset the type of the declaration.  */
16293       SET_DECL_RTL (d, NULL_RTX);
16294       DECL_IN_AGGR_P (d) = 0;
16295
16296       /* The initializer is placed in DECL_INITIAL by
16297          regenerate_decl_from_template.  Pull it out so that
16298          cp_finish_decl can process it.  */
16299       init = DECL_INITIAL (d);
16300       DECL_INITIAL (d) = NULL_TREE;
16301       DECL_INITIALIZED_P (d) = 0;
16302
16303       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16304          initializer.  That function will defer actual emission until
16305          we have a chance to determine linkage.  */
16306       DECL_EXTERNAL (d) = 0;
16307
16308       /* Enter the scope of D so that access-checking works correctly.  */
16309       push_nested_class (DECL_CONTEXT (d));
16310       cp_finish_decl (d, init, false, NULL_TREE, 0);
16311       pop_nested_class ();
16312     }
16313   else if (TREE_CODE (d) == FUNCTION_DECL)
16314     {
16315       htab_t saved_local_specializations;
16316       tree subst_decl;
16317       tree tmpl_parm;
16318       tree spec_parm;
16319
16320       /* Save away the current list, in case we are instantiating one
16321          template from within the body of another.  */
16322       saved_local_specializations = local_specializations;
16323
16324       /* Set up the list of local specializations.  */
16325       local_specializations = htab_create (37,
16326                                            hash_local_specialization,
16327                                            eq_local_specializations,
16328                                            NULL);
16329
16330       /* Set up context.  */
16331       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16332
16333       /* Create substitution entries for the parameters.  */
16334       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16335       tmpl_parm = DECL_ARGUMENTS (subst_decl);
16336       spec_parm = DECL_ARGUMENTS (d);
16337       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16338         {
16339           register_local_specialization (spec_parm, tmpl_parm);
16340           spec_parm = skip_artificial_parms_for (d, spec_parm);
16341           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16342         }
16343       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16344         {
16345           register_local_specialization (spec_parm, tmpl_parm);
16346           tmpl_parm = TREE_CHAIN (tmpl_parm);
16347           spec_parm = TREE_CHAIN (spec_parm);
16348         }
16349       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16350         {
16351           /* Register the (value) argument pack as a specialization of
16352              TMPL_PARM, then move on.  */
16353           tree argpack = make_fnparm_pack (spec_parm);
16354           register_local_specialization (argpack, tmpl_parm);
16355           tmpl_parm = TREE_CHAIN (tmpl_parm);
16356           spec_parm = NULL_TREE;
16357         }
16358       gcc_assert (!spec_parm);
16359
16360       /* Substitute into the body of the function.  */
16361       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16362                    tf_warning_or_error, tmpl,
16363                    /*integral_constant_expression_p=*/false);
16364
16365       /* Set the current input_location to the end of the function
16366          so that finish_function knows where we are.  */
16367       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16368
16369       /* We don't need the local specializations any more.  */
16370       htab_delete (local_specializations);
16371       local_specializations = saved_local_specializations;
16372
16373       /* Finish the function.  */
16374       d = finish_function (0);
16375       expand_or_defer_fn (d);
16376     }
16377
16378   /* We're not deferring instantiation any more.  */
16379   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16380
16381   if (need_push)
16382     pop_from_top_level ();
16383
16384 out:
16385   input_location = saved_loc;
16386   pop_deferring_access_checks ();
16387   pop_tinst_level ();
16388
16389   timevar_pop (TV_PARSE);
16390
16391   return d;
16392 }
16393
16394 /* Run through the list of templates that we wish we could
16395    instantiate, and instantiate any we can.  RETRIES is the
16396    number of times we retry pending template instantiation.  */
16397
16398 void
16399 instantiate_pending_templates (int retries)
16400 {
16401   int reconsider;
16402   location_t saved_loc = input_location;
16403
16404   /* Instantiating templates may trigger vtable generation.  This in turn
16405      may require further template instantiations.  We place a limit here
16406      to avoid infinite loop.  */
16407   if (pending_templates && retries >= max_tinst_depth)
16408     {
16409       tree decl = pending_templates->tinst->decl;
16410
16411       error ("template instantiation depth exceeds maximum of %d"
16412              " instantiating %q+D, possibly from virtual table generation"
16413              " (use -ftemplate-depth-NN to increase the maximum)",
16414              max_tinst_depth, decl);
16415       if (TREE_CODE (decl) == FUNCTION_DECL)
16416         /* Pretend that we defined it.  */
16417         DECL_INITIAL (decl) = error_mark_node;
16418       return;
16419     }
16420
16421   do
16422     {
16423       struct pending_template **t = &pending_templates;
16424       struct pending_template *last = NULL;
16425       reconsider = 0;
16426       while (*t)
16427         {
16428           tree instantiation = reopen_tinst_level ((*t)->tinst);
16429           bool complete = false;
16430
16431           if (TYPE_P (instantiation))
16432             {
16433               tree fn;
16434
16435               if (!COMPLETE_TYPE_P (instantiation))
16436                 {
16437                   instantiate_class_template (instantiation);
16438                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
16439                     for (fn = TYPE_METHODS (instantiation);
16440                          fn;
16441                          fn = TREE_CHAIN (fn))
16442                       if (! DECL_ARTIFICIAL (fn))
16443                         instantiate_decl (fn,
16444                                           /*defer_ok=*/0,
16445                                           /*expl_inst_class_mem_p=*/false);
16446                   if (COMPLETE_TYPE_P (instantiation))
16447                     reconsider = 1;
16448                 }
16449
16450               complete = COMPLETE_TYPE_P (instantiation);
16451             }
16452           else
16453             {
16454               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
16455                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
16456                 {
16457                   instantiation
16458                     = instantiate_decl (instantiation,
16459                                         /*defer_ok=*/0,
16460                                         /*expl_inst_class_mem_p=*/false);
16461                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
16462                     reconsider = 1;
16463                 }
16464
16465               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
16466                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
16467             }
16468
16469           if (complete)
16470             /* If INSTANTIATION has been instantiated, then we don't
16471                need to consider it again in the future.  */
16472             *t = (*t)->next;
16473           else
16474             {
16475               last = *t;
16476               t = &(*t)->next;
16477             }
16478           tinst_depth = 0;
16479           current_tinst_level = NULL;
16480         }
16481       last_pending_template = last;
16482     }
16483   while (reconsider);
16484
16485   input_location = saved_loc;
16486 }
16487
16488 /* Substitute ARGVEC into T, which is a list of initializers for
16489    either base class or a non-static data member.  The TREE_PURPOSEs
16490    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
16491    instantiate_decl.  */
16492
16493 static tree
16494 tsubst_initializer_list (tree t, tree argvec)
16495 {
16496   tree inits = NULL_TREE;
16497
16498   for (; t; t = TREE_CHAIN (t))
16499     {
16500       tree decl;
16501       tree init;
16502       tree expanded_bases = NULL_TREE;
16503       tree expanded_arguments = NULL_TREE;
16504       int i, len = 1;
16505
16506       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
16507         {
16508           tree expr;
16509           tree arg;
16510
16511           /* Expand the base class expansion type into separate base
16512              classes.  */
16513           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
16514                                                  tf_warning_or_error,
16515                                                  NULL_TREE);
16516           if (expanded_bases == error_mark_node)
16517             continue;
16518           
16519           /* We'll be building separate TREE_LISTs of arguments for
16520              each base.  */
16521           len = TREE_VEC_LENGTH (expanded_bases);
16522           expanded_arguments = make_tree_vec (len);
16523           for (i = 0; i < len; i++)
16524             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
16525
16526           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
16527              expand each argument in the TREE_VALUE of t.  */
16528           expr = make_node (EXPR_PACK_EXPANSION);
16529           PACK_EXPANSION_PARAMETER_PACKS (expr) =
16530             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
16531
16532           if (TREE_VALUE (t) == void_type_node)
16533             /* VOID_TYPE_NODE is used to indicate
16534                value-initialization.  */
16535             {
16536               for (i = 0; i < len; i++)
16537                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
16538             }
16539           else
16540             {
16541               /* Substitute parameter packs into each argument in the
16542                  TREE_LIST.  */
16543               in_base_initializer = 1;
16544               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
16545                 {
16546                   tree expanded_exprs;
16547
16548                   /* Expand the argument.  */
16549                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
16550                   expanded_exprs 
16551                     = tsubst_pack_expansion (expr, argvec,
16552                                              tf_warning_or_error,
16553                                              NULL_TREE);
16554                   if (expanded_exprs == error_mark_node)
16555                     continue;
16556
16557                   /* Prepend each of the expanded expressions to the
16558                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
16559                   for (i = 0; i < len; i++)
16560                     {
16561                       TREE_VEC_ELT (expanded_arguments, i) = 
16562                         tree_cons (NULL_TREE, 
16563                                    TREE_VEC_ELT (expanded_exprs, i),
16564                                    TREE_VEC_ELT (expanded_arguments, i));
16565                     }
16566                 }
16567               in_base_initializer = 0;
16568
16569               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
16570                  since we built them backwards.  */
16571               for (i = 0; i < len; i++)
16572                 {
16573                   TREE_VEC_ELT (expanded_arguments, i) = 
16574                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
16575                 }
16576             }
16577         }
16578
16579       for (i = 0; i < len; ++i)
16580         {
16581           if (expanded_bases)
16582             {
16583               decl = TREE_VEC_ELT (expanded_bases, i);
16584               decl = expand_member_init (decl);
16585               init = TREE_VEC_ELT (expanded_arguments, i);
16586             }
16587           else
16588             {
16589               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
16590                                   tf_warning_or_error, NULL_TREE);
16591
16592               decl = expand_member_init (decl);
16593               if (decl && !DECL_P (decl))
16594                 in_base_initializer = 1;
16595
16596               init = tsubst_expr (TREE_VALUE (t), argvec, 
16597                                   tf_warning_or_error, NULL_TREE,
16598                                   /*integral_constant_expression_p=*/false);
16599               in_base_initializer = 0;
16600             }
16601
16602           if (decl)
16603             {
16604               init = build_tree_list (decl, init);
16605               TREE_CHAIN (init) = inits;
16606               inits = init;
16607             }
16608         }
16609     }
16610   return inits;
16611 }
16612
16613 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
16614
16615 static void
16616 set_current_access_from_decl (tree decl)
16617 {
16618   if (TREE_PRIVATE (decl))
16619     current_access_specifier = access_private_node;
16620   else if (TREE_PROTECTED (decl))
16621     current_access_specifier = access_protected_node;
16622   else
16623     current_access_specifier = access_public_node;
16624 }
16625
16626 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
16627    is the instantiation (which should have been created with
16628    start_enum) and ARGS are the template arguments to use.  */
16629
16630 static void
16631 tsubst_enum (tree tag, tree newtag, tree args)
16632 {
16633   tree e;
16634
16635   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
16636     {
16637       tree value;
16638       tree decl;
16639
16640       decl = TREE_VALUE (e);
16641       /* Note that in a template enum, the TREE_VALUE is the
16642          CONST_DECL, not the corresponding INTEGER_CST.  */
16643       value = tsubst_expr (DECL_INITIAL (decl),
16644                            args, tf_warning_or_error, NULL_TREE,
16645                            /*integral_constant_expression_p=*/true);
16646
16647       /* Give this enumeration constant the correct access.  */
16648       set_current_access_from_decl (decl);
16649
16650       /* Actually build the enumerator itself.  */
16651       build_enumerator (DECL_NAME (decl), value, newtag);
16652     }
16653
16654   finish_enum (newtag);
16655   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
16656     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
16657 }
16658
16659 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
16660    its type -- but without substituting the innermost set of template
16661    arguments.  So, innermost set of template parameters will appear in
16662    the type.  */
16663
16664 tree
16665 get_mostly_instantiated_function_type (tree decl)
16666 {
16667   tree fn_type;
16668   tree tmpl;
16669   tree targs;
16670   tree tparms;
16671   int parm_depth;
16672
16673   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16674   targs = DECL_TI_ARGS (decl);
16675   tparms = DECL_TEMPLATE_PARMS (tmpl);
16676   parm_depth = TMPL_PARMS_DEPTH (tparms);
16677
16678   /* There should be as many levels of arguments as there are levels
16679      of parameters.  */
16680   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
16681
16682   fn_type = TREE_TYPE (tmpl);
16683
16684   if (parm_depth == 1)
16685     /* No substitution is necessary.  */
16686     ;
16687   else
16688     {
16689       int i, save_access_control;
16690       tree partial_args;
16691
16692       /* Replace the innermost level of the TARGS with NULL_TREEs to
16693          let tsubst know not to substitute for those parameters.  */
16694       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
16695       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
16696         SET_TMPL_ARGS_LEVEL (partial_args, i,
16697                              TMPL_ARGS_LEVEL (targs, i));
16698       SET_TMPL_ARGS_LEVEL (partial_args,
16699                            TMPL_ARGS_DEPTH (targs),
16700                            make_tree_vec (DECL_NTPARMS (tmpl)));
16701
16702       /* Disable access control as this function is used only during
16703          name-mangling.  */
16704       save_access_control = flag_access_control;
16705       flag_access_control = 0;
16706
16707       ++processing_template_decl;
16708       /* Now, do the (partial) substitution to figure out the
16709          appropriate function type.  */
16710       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
16711       --processing_template_decl;
16712
16713       /* Substitute into the template parameters to obtain the real
16714          innermost set of parameters.  This step is important if the
16715          innermost set of template parameters contains value
16716          parameters whose types depend on outer template parameters.  */
16717       TREE_VEC_LENGTH (partial_args)--;
16718       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
16719
16720       flag_access_control = save_access_control;
16721     }
16722
16723   return fn_type;
16724 }
16725
16726 /* Return truthvalue if we're processing a template different from
16727    the last one involved in diagnostics.  */
16728 int
16729 problematic_instantiation_changed (void)
16730 {
16731   return last_template_error_tick != tinst_level_tick;
16732 }
16733
16734 /* Remember current template involved in diagnostics.  */
16735 void
16736 record_last_problematic_instantiation (void)
16737 {
16738   last_template_error_tick = tinst_level_tick;
16739 }
16740
16741 struct tinst_level *
16742 current_instantiation (void)
16743 {
16744   return current_tinst_level;
16745 }
16746
16747 /* [temp.param] Check that template non-type parm TYPE is of an allowable
16748    type. Return zero for ok, nonzero for disallowed. Issue error and
16749    warning messages under control of COMPLAIN.  */
16750
16751 static int
16752 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
16753 {
16754   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
16755     return 0;
16756   else if (POINTER_TYPE_P (type))
16757     return 0;
16758   else if (TYPE_PTR_TO_MEMBER_P (type))
16759     return 0;
16760   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16761     return 0;
16762   else if (TREE_CODE (type) == TYPENAME_TYPE)
16763     return 0;
16764
16765   if (complain & tf_error)
16766     error ("%q#T is not a valid type for a template constant parameter", type);
16767   return 1;
16768 }
16769
16770 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
16771    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
16772
16773 static bool
16774 dependent_type_p_r (tree type)
16775 {
16776   tree scope;
16777
16778   /* [temp.dep.type]
16779
16780      A type is dependent if it is:
16781
16782      -- a template parameter. Template template parameters are types
16783         for us (since TYPE_P holds true for them) so we handle
16784         them here.  */
16785   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16786       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
16787     return true;
16788   /* -- a qualified-id with a nested-name-specifier which contains a
16789         class-name that names a dependent type or whose unqualified-id
16790         names a dependent type.  */
16791   if (TREE_CODE (type) == TYPENAME_TYPE)
16792     return true;
16793   /* -- a cv-qualified type where the cv-unqualified type is
16794         dependent.  */
16795   type = TYPE_MAIN_VARIANT (type);
16796   /* -- a compound type constructed from any dependent type.  */
16797   if (TYPE_PTR_TO_MEMBER_P (type))
16798     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
16799             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
16800                                            (type)));
16801   else if (TREE_CODE (type) == POINTER_TYPE
16802            || TREE_CODE (type) == REFERENCE_TYPE)
16803     return dependent_type_p (TREE_TYPE (type));
16804   else if (TREE_CODE (type) == FUNCTION_TYPE
16805            || TREE_CODE (type) == METHOD_TYPE)
16806     {
16807       tree arg_type;
16808
16809       if (dependent_type_p (TREE_TYPE (type)))
16810         return true;
16811       for (arg_type = TYPE_ARG_TYPES (type);
16812            arg_type;
16813            arg_type = TREE_CHAIN (arg_type))
16814         if (dependent_type_p (TREE_VALUE (arg_type)))
16815           return true;
16816       return false;
16817     }
16818   /* -- an array type constructed from any dependent type or whose
16819         size is specified by a constant expression that is
16820         value-dependent.  */
16821   if (TREE_CODE (type) == ARRAY_TYPE)
16822     {
16823       if (TYPE_DOMAIN (type)
16824           && dependent_type_p (TYPE_DOMAIN (type)))
16825         return true;
16826       return dependent_type_p (TREE_TYPE (type));
16827     }
16828   else if (TREE_CODE (type) == INTEGER_TYPE
16829            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
16830     {
16831       /* If this is the TYPE_DOMAIN of an array type, consider it
16832          dependent.  We already checked for value-dependence in
16833          compute_array_index_type.  */
16834       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
16835     }
16836
16837   /* -- a template-id in which either the template name is a template
16838      parameter ...  */
16839   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
16840     return true;
16841   /* ... or any of the template arguments is a dependent type or
16842         an expression that is type-dependent or value-dependent.  */
16843   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
16844            && (any_dependent_template_arguments_p
16845                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
16846     return true;
16847
16848   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
16849      argument of the `typeof' expression is not type-dependent, then
16850      it should already been have resolved.  */
16851   if (TREE_CODE (type) == TYPEOF_TYPE
16852       || TREE_CODE (type) == DECLTYPE_TYPE)
16853     return true;
16854
16855   /* A template argument pack is dependent if any of its packed
16856      arguments are.  */
16857   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
16858     {
16859       tree args = ARGUMENT_PACK_ARGS (type);
16860       int i, len = TREE_VEC_LENGTH (args);
16861       for (i = 0; i < len; ++i)
16862         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16863           return true;
16864     }
16865
16866   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
16867      be template parameters.  */
16868   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
16869     return true;
16870
16871   /* The standard does not specifically mention types that are local
16872      to template functions or local classes, but they should be
16873      considered dependent too.  For example:
16874
16875        template <int I> void f() {
16876          enum E { a = I };
16877          S<sizeof (E)> s;
16878        }
16879
16880      The size of `E' cannot be known until the value of `I' has been
16881      determined.  Therefore, `E' must be considered dependent.  */
16882   scope = TYPE_CONTEXT (type);
16883   if (scope && TYPE_P (scope))
16884     return dependent_type_p (scope);
16885   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
16886     return type_dependent_expression_p (scope);
16887
16888   /* Other types are non-dependent.  */
16889   return false;
16890 }
16891
16892 /* Returns TRUE if TYPE is dependent, in the sense of
16893    [temp.dep.type].  */
16894
16895 bool
16896 dependent_type_p (tree type)
16897 {
16898   /* If there are no template parameters in scope, then there can't be
16899      any dependent types.  */
16900   if (!processing_template_decl)
16901     {
16902       /* If we are not processing a template, then nobody should be
16903          providing us with a dependent type.  */
16904       gcc_assert (type);
16905       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
16906       return false;
16907     }
16908
16909   /* If the type is NULL, we have not computed a type for the entity
16910      in question; in that case, the type is dependent.  */
16911   if (!type)
16912     return true;
16913
16914   /* Erroneous types can be considered non-dependent.  */
16915   if (type == error_mark_node)
16916     return false;
16917
16918   /* If we have not already computed the appropriate value for TYPE,
16919      do so now.  */
16920   if (!TYPE_DEPENDENT_P_VALID (type))
16921     {
16922       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
16923       TYPE_DEPENDENT_P_VALID (type) = 1;
16924     }
16925
16926   return TYPE_DEPENDENT_P (type);
16927 }
16928
16929 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
16930    lookup.  In other words, a dependent type that is not the current
16931    instantiation.  */
16932
16933 bool
16934 dependent_scope_p (tree scope)
16935 {
16936   return (scope && TYPE_P (scope) && dependent_type_p (scope)
16937           && !currently_open_class (scope));
16938 }
16939
16940 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
16941
16942 static bool
16943 dependent_scope_ref_p (tree expression, bool criterion (tree))
16944 {
16945   tree scope;
16946   tree name;
16947
16948   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
16949
16950   if (!TYPE_P (TREE_OPERAND (expression, 0)))
16951     return true;
16952
16953   scope = TREE_OPERAND (expression, 0);
16954   name = TREE_OPERAND (expression, 1);
16955
16956   /* [temp.dep.expr]
16957
16958      An id-expression is type-dependent if it contains a
16959      nested-name-specifier that contains a class-name that names a
16960      dependent type.  */
16961   /* The suggested resolution to Core Issue 224 implies that if the
16962      qualifying type is the current class, then we must peek
16963      inside it.  */
16964   if (DECL_P (name)
16965       && currently_open_class (scope)
16966       && !criterion (name))
16967     return false;
16968   if (dependent_type_p (scope))
16969     return true;
16970
16971   return false;
16972 }
16973
16974 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
16975    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
16976    expression.  */
16977
16978 bool
16979 value_dependent_expression_p (tree expression)
16980 {
16981   if (!processing_template_decl)
16982     return false;
16983
16984   /* A name declared with a dependent type.  */
16985   if (DECL_P (expression) && type_dependent_expression_p (expression))
16986     return true;
16987
16988   switch (TREE_CODE (expression))
16989     {
16990     case IDENTIFIER_NODE:
16991       /* A name that has not been looked up -- must be dependent.  */
16992       return true;
16993
16994     case TEMPLATE_PARM_INDEX:
16995       /* A non-type template parm.  */
16996       return true;
16997
16998     case CONST_DECL:
16999       /* A non-type template parm.  */
17000       if (DECL_TEMPLATE_PARM_P (expression))
17001         return true;
17002       return value_dependent_expression_p (DECL_INITIAL (expression));
17003
17004     case VAR_DECL:
17005        /* A constant with integral or enumeration type and is initialized
17006           with an expression that is value-dependent.  */
17007       if (DECL_INITIAL (expression)
17008           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17009           && value_dependent_expression_p (DECL_INITIAL (expression)))
17010         return true;
17011       return false;
17012
17013     case DYNAMIC_CAST_EXPR:
17014     case STATIC_CAST_EXPR:
17015     case CONST_CAST_EXPR:
17016     case REINTERPRET_CAST_EXPR:
17017     case CAST_EXPR:
17018       /* These expressions are value-dependent if the type to which
17019          the cast occurs is dependent or the expression being casted
17020          is value-dependent.  */
17021       {
17022         tree type = TREE_TYPE (expression);
17023
17024         if (dependent_type_p (type))
17025           return true;
17026
17027         /* A functional cast has a list of operands.  */
17028         expression = TREE_OPERAND (expression, 0);
17029         if (!expression)
17030           {
17031             /* If there are no operands, it must be an expression such
17032                as "int()". This should not happen for aggregate types
17033                because it would form non-constant expressions.  */
17034             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17035
17036             return false;
17037           }
17038
17039         if (TREE_CODE (expression) == TREE_LIST)
17040           return any_value_dependent_elements_p (expression);
17041
17042         return value_dependent_expression_p (expression);
17043       }
17044
17045     case SIZEOF_EXPR:
17046     case ALIGNOF_EXPR:
17047       /* A `sizeof' expression is value-dependent if the operand is
17048          type-dependent or is a pack expansion.  */
17049       expression = TREE_OPERAND (expression, 0);
17050       if (PACK_EXPANSION_P (expression))
17051         return true;
17052       else if (TYPE_P (expression))
17053         return dependent_type_p (expression);
17054       return type_dependent_expression_p (expression);
17055
17056     case SCOPE_REF:
17057       return dependent_scope_ref_p (expression, value_dependent_expression_p);
17058
17059     case COMPONENT_REF:
17060       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17061               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17062
17063     case CALL_EXPR:
17064       /* A CALL_EXPR may appear in a constant expression if it is a
17065          call to a builtin function, e.g., __builtin_constant_p.  All
17066          such calls are value-dependent.  */
17067       return true;
17068
17069     case NONTYPE_ARGUMENT_PACK:
17070       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17071          is value-dependent.  */
17072       {
17073         tree values = ARGUMENT_PACK_ARGS (expression);
17074         int i, len = TREE_VEC_LENGTH (values);
17075         
17076         for (i = 0; i < len; ++i)
17077           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17078             return true;
17079         
17080         return false;
17081       }
17082
17083     case TRAIT_EXPR:
17084       {
17085         tree type2 = TRAIT_EXPR_TYPE2 (expression);
17086         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17087                 || (type2 ? dependent_type_p (type2) : false));
17088       }
17089
17090     case MODOP_EXPR:
17091       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17092               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17093
17094     default:
17095       /* A constant expression is value-dependent if any subexpression is
17096          value-dependent.  */
17097       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17098         {
17099         case tcc_reference:
17100         case tcc_unary:
17101           return (value_dependent_expression_p
17102                   (TREE_OPERAND (expression, 0)));
17103
17104         case tcc_comparison:
17105         case tcc_binary:
17106           return ((value_dependent_expression_p
17107                    (TREE_OPERAND (expression, 0)))
17108                   || (value_dependent_expression_p
17109                       (TREE_OPERAND (expression, 1))));
17110
17111         case tcc_expression:
17112         case tcc_vl_exp:
17113           {
17114             int i;
17115             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17116               /* In some cases, some of the operands may be missing.
17117                  (For example, in the case of PREDECREMENT_EXPR, the
17118                  amount to increment by may be missing.)  That doesn't
17119                  make the expression dependent.  */
17120               if (TREE_OPERAND (expression, i)
17121                   && (value_dependent_expression_p
17122                       (TREE_OPERAND (expression, i))))
17123                 return true;
17124             return false;
17125           }
17126
17127         default:
17128           break;
17129         }
17130     }
17131
17132   /* The expression is not value-dependent.  */
17133   return false;
17134 }
17135
17136 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17137    [temp.dep.expr].  */
17138
17139 bool
17140 type_dependent_expression_p (tree expression)
17141 {
17142   if (!processing_template_decl)
17143     return false;
17144
17145   if (expression == error_mark_node)
17146     return false;
17147
17148   /* An unresolved name is always dependent.  */
17149   if (TREE_CODE (expression) == IDENTIFIER_NODE
17150       || TREE_CODE (expression) == USING_DECL)
17151     return true;
17152
17153   /* Some expression forms are never type-dependent.  */
17154   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17155       || TREE_CODE (expression) == SIZEOF_EXPR
17156       || TREE_CODE (expression) == ALIGNOF_EXPR
17157       || TREE_CODE (expression) == TRAIT_EXPR
17158       || TREE_CODE (expression) == TYPEID_EXPR
17159       || TREE_CODE (expression) == DELETE_EXPR
17160       || TREE_CODE (expression) == VEC_DELETE_EXPR
17161       || TREE_CODE (expression) == THROW_EXPR)
17162     return false;
17163
17164   /* The types of these expressions depends only on the type to which
17165      the cast occurs.  */
17166   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17167       || TREE_CODE (expression) == STATIC_CAST_EXPR
17168       || TREE_CODE (expression) == CONST_CAST_EXPR
17169       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17170       || TREE_CODE (expression) == CAST_EXPR)
17171     return dependent_type_p (TREE_TYPE (expression));
17172
17173   /* The types of these expressions depends only on the type created
17174      by the expression.  */
17175   if (TREE_CODE (expression) == NEW_EXPR
17176       || TREE_CODE (expression) == VEC_NEW_EXPR)
17177     {
17178       /* For NEW_EXPR tree nodes created inside a template, either
17179          the object type itself or a TREE_LIST may appear as the
17180          operand 1.  */
17181       tree type = TREE_OPERAND (expression, 1);
17182       if (TREE_CODE (type) == TREE_LIST)
17183         /* This is an array type.  We need to check array dimensions
17184            as well.  */
17185         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17186                || value_dependent_expression_p
17187                     (TREE_OPERAND (TREE_VALUE (type), 1));
17188       else
17189         return dependent_type_p (type);
17190     }
17191
17192   if (TREE_CODE (expression) == SCOPE_REF
17193       && dependent_scope_ref_p (expression,
17194                                 type_dependent_expression_p))
17195     return true;
17196
17197   if (TREE_CODE (expression) == FUNCTION_DECL
17198       && DECL_LANG_SPECIFIC (expression)
17199       && DECL_TEMPLATE_INFO (expression)
17200       && (any_dependent_template_arguments_p
17201           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17202     return true;
17203
17204   if (TREE_CODE (expression) == TEMPLATE_DECL
17205       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17206     return false;
17207
17208   if (TREE_CODE (expression) == STMT_EXPR)
17209     expression = stmt_expr_value_expr (expression);
17210
17211   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17212     {
17213       tree elt;
17214       unsigned i;
17215
17216       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17217         {
17218           if (type_dependent_expression_p (elt))
17219             return true;
17220         }
17221       return false;
17222     }
17223
17224   if (TREE_TYPE (expression) == unknown_type_node)
17225     {
17226       if (TREE_CODE (expression) == ADDR_EXPR)
17227         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17228       if (TREE_CODE (expression) == COMPONENT_REF
17229           || TREE_CODE (expression) == OFFSET_REF)
17230         {
17231           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17232             return true;
17233           expression = TREE_OPERAND (expression, 1);
17234           if (TREE_CODE (expression) == IDENTIFIER_NODE)
17235             return false;
17236         }
17237       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17238       if (TREE_CODE (expression) == SCOPE_REF)
17239         return false;
17240
17241       if (TREE_CODE (expression) == BASELINK)
17242         expression = BASELINK_FUNCTIONS (expression);
17243
17244       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17245         {
17246           if (any_dependent_template_arguments_p
17247               (TREE_OPERAND (expression, 1)))
17248             return true;
17249           expression = TREE_OPERAND (expression, 0);
17250         }
17251       gcc_assert (TREE_CODE (expression) == OVERLOAD
17252                   || TREE_CODE (expression) == FUNCTION_DECL);
17253
17254       while (expression)
17255         {
17256           if (type_dependent_expression_p (OVL_CURRENT (expression)))
17257             return true;
17258           expression = OVL_NEXT (expression);
17259         }
17260       return false;
17261     }
17262
17263   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17264
17265   return (dependent_type_p (TREE_TYPE (expression)));
17266 }
17267
17268 /* Like type_dependent_expression_p, but it also works while not processing
17269    a template definition, i.e. during substitution or mangling.  */
17270
17271 bool
17272 type_dependent_expression_p_push (tree expr)
17273 {
17274   bool b;
17275   ++processing_template_decl;
17276   b = type_dependent_expression_p (expr);
17277   --processing_template_decl;
17278   return b;
17279 }
17280
17281 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17282
17283 bool
17284 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17285 {
17286   unsigned int i;
17287   tree arg;
17288
17289   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
17290     {
17291       if (type_dependent_expression_p (arg))
17292         return true;
17293     }
17294   return false;
17295 }
17296
17297 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17298    expressions) contains any value-dependent expressions.  */
17299
17300 bool
17301 any_value_dependent_elements_p (const_tree list)
17302 {
17303   for (; list; list = TREE_CHAIN (list))
17304     if (value_dependent_expression_p (TREE_VALUE (list)))
17305       return true;
17306
17307   return false;
17308 }
17309
17310 /* Returns TRUE if the ARG (a template argument) is dependent.  */
17311
17312 bool
17313 dependent_template_arg_p (tree arg)
17314 {
17315   if (!processing_template_decl)
17316     return false;
17317
17318   if (TREE_CODE (arg) == TEMPLATE_DECL
17319       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17320     return dependent_template_p (arg);
17321   else if (ARGUMENT_PACK_P (arg))
17322     {
17323       tree args = ARGUMENT_PACK_ARGS (arg);
17324       int i, len = TREE_VEC_LENGTH (args);
17325       for (i = 0; i < len; ++i)
17326         {
17327           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17328             return true;
17329         }
17330
17331       return false;
17332     }
17333   else if (TYPE_P (arg))
17334     return dependent_type_p (arg);
17335   else
17336     return (type_dependent_expression_p (arg)
17337             || value_dependent_expression_p (arg));
17338 }
17339
17340 /* Returns true if ARGS (a collection of template arguments) contains
17341    any types that require structural equality testing.  */
17342
17343 bool
17344 any_template_arguments_need_structural_equality_p (tree args)
17345 {
17346   int i;
17347   int j;
17348
17349   if (!args)
17350     return false;
17351   if (args == error_mark_node)
17352     return true;
17353
17354   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17355     {
17356       tree level = TMPL_ARGS_LEVEL (args, i + 1);
17357       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17358         {
17359           tree arg = TREE_VEC_ELT (level, j);
17360           tree packed_args = NULL_TREE;
17361           int k, len = 1;
17362
17363           if (ARGUMENT_PACK_P (arg))
17364             {
17365               /* Look inside the argument pack.  */
17366               packed_args = ARGUMENT_PACK_ARGS (arg);
17367               len = TREE_VEC_LENGTH (packed_args);
17368             }
17369
17370           for (k = 0; k < len; ++k)
17371             {
17372               if (packed_args)
17373                 arg = TREE_VEC_ELT (packed_args, k);
17374
17375               if (error_operand_p (arg))
17376                 return true;
17377               else if (TREE_CODE (arg) == TEMPLATE_DECL
17378                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17379                 continue;
17380               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17381                 return true;
17382               else if (!TYPE_P (arg) && TREE_TYPE (arg)
17383                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17384                 return true;
17385             }
17386         }
17387     }
17388
17389   return false;
17390 }
17391
17392 /* Returns true if ARGS (a collection of template arguments) contains
17393    any dependent arguments.  */
17394
17395 bool
17396 any_dependent_template_arguments_p (const_tree args)
17397 {
17398   int i;
17399   int j;
17400
17401   if (!args)
17402     return false;
17403   if (args == error_mark_node)
17404     return true;
17405
17406   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17407     {
17408       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17409       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17410         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17411           return true;
17412     }
17413
17414   return false;
17415 }
17416
17417 /* Returns TRUE if the template TMPL is dependent.  */
17418
17419 bool
17420 dependent_template_p (tree tmpl)
17421 {
17422   if (TREE_CODE (tmpl) == OVERLOAD)
17423     {
17424       while (tmpl)
17425         {
17426           if (dependent_template_p (OVL_FUNCTION (tmpl)))
17427             return true;
17428           tmpl = OVL_CHAIN (tmpl);
17429         }
17430       return false;
17431     }
17432
17433   /* Template template parameters are dependent.  */
17434   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
17435       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
17436     return true;
17437   /* So are names that have not been looked up.  */
17438   if (TREE_CODE (tmpl) == SCOPE_REF
17439       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
17440     return true;
17441   /* So are member templates of dependent classes.  */
17442   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
17443     return dependent_type_p (DECL_CONTEXT (tmpl));
17444   return false;
17445 }
17446
17447 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
17448
17449 bool
17450 dependent_template_id_p (tree tmpl, tree args)
17451 {
17452   return (dependent_template_p (tmpl)
17453           || any_dependent_template_arguments_p (args));
17454 }
17455
17456 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
17457    is dependent.  */
17458
17459 bool
17460 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
17461 {
17462   int i;
17463
17464   if (!processing_template_decl)
17465     return false;
17466
17467   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
17468     {
17469       tree decl = TREE_VEC_ELT (declv, i);
17470       tree init = TREE_VEC_ELT (initv, i);
17471       tree cond = TREE_VEC_ELT (condv, i);
17472       tree incr = TREE_VEC_ELT (incrv, i);
17473
17474       if (type_dependent_expression_p (decl))
17475         return true;
17476
17477       if (init && type_dependent_expression_p (init))
17478         return true;
17479
17480       if (type_dependent_expression_p (cond))
17481         return true;
17482
17483       if (COMPARISON_CLASS_P (cond)
17484           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
17485               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
17486         return true;
17487
17488       if (TREE_CODE (incr) == MODOP_EXPR)
17489         {
17490           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
17491               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
17492             return true;
17493         }
17494       else if (type_dependent_expression_p (incr))
17495         return true;
17496       else if (TREE_CODE (incr) == MODIFY_EXPR)
17497         {
17498           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
17499             return true;
17500           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
17501             {
17502               tree t = TREE_OPERAND (incr, 1);
17503               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
17504                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
17505                 return true;
17506             }
17507         }
17508     }
17509
17510   return false;
17511 }
17512
17513 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
17514    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
17515    no such TYPE can be found.  Note that this function peers inside
17516    uninstantiated templates and therefore should be used only in
17517    extremely limited situations.  ONLY_CURRENT_P restricts this
17518    peering to the currently open classes hierarchy (which is required
17519    when comparing types).  */
17520
17521 tree
17522 resolve_typename_type (tree type, bool only_current_p)
17523 {
17524   tree scope;
17525   tree name;
17526   tree decl;
17527   int quals;
17528   tree pushed_scope;
17529   tree result;
17530
17531   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
17532
17533   scope = TYPE_CONTEXT (type);
17534   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
17535      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
17536      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
17537      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
17538      identifier  of the TYPENAME_TYPE anymore.
17539      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
17540      TYPENAME_TYPE instead, we avoid messing up with a possible
17541      typedef variant case.  */
17542   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
17543
17544   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
17545      it first before we can figure out what NAME refers to.  */
17546   if (TREE_CODE (scope) == TYPENAME_TYPE)
17547     scope = resolve_typename_type (scope, only_current_p);
17548   /* If we don't know what SCOPE refers to, then we cannot resolve the
17549      TYPENAME_TYPE.  */
17550   if (TREE_CODE (scope) == TYPENAME_TYPE)
17551     return type;
17552   /* If the SCOPE is a template type parameter, we have no way of
17553      resolving the name.  */
17554   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
17555     return type;
17556   /* If the SCOPE is not the current instantiation, there's no reason
17557      to look inside it.  */
17558   if (only_current_p && !currently_open_class (scope))
17559     return type;
17560   /* If SCOPE isn't the template itself, it will not have a valid
17561      TYPE_FIELDS list.  */
17562   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
17563     /* scope is either the template itself or a compatible instantiation
17564        like X<T>, so look up the name in the original template.  */
17565     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
17566   else
17567     /* scope is a partial instantiation, so we can't do the lookup or we
17568        will lose the template arguments.  */
17569     return type;
17570   /* Enter the SCOPE so that name lookup will be resolved as if we
17571      were in the class definition.  In particular, SCOPE will no
17572      longer be considered a dependent type.  */
17573   pushed_scope = push_scope (scope);
17574   /* Look up the declaration.  */
17575   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
17576
17577   result = NULL_TREE;
17578   
17579   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
17580      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
17581   if (!decl)
17582     /*nop*/;
17583   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
17584            && TREE_CODE (decl) == TYPE_DECL)
17585     {
17586       result = TREE_TYPE (decl);
17587       if (result == error_mark_node)
17588         result = NULL_TREE;
17589     }
17590   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
17591            && DECL_CLASS_TEMPLATE_P (decl))
17592     {
17593       tree tmpl;
17594       tree args;
17595       /* Obtain the template and the arguments.  */
17596       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
17597       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
17598       /* Instantiate the template.  */
17599       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
17600                                       /*entering_scope=*/0,
17601                                       tf_error | tf_user);
17602       if (result == error_mark_node)
17603         result = NULL_TREE;
17604     }
17605   
17606   /* Leave the SCOPE.  */
17607   if (pushed_scope)
17608     pop_scope (pushed_scope);
17609
17610   /* If we failed to resolve it, return the original typename.  */
17611   if (!result)
17612     return type;
17613   
17614   /* If lookup found a typename type, resolve that too.  */
17615   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
17616     {
17617       /* Ill-formed programs can cause infinite recursion here, so we
17618          must catch that.  */
17619       TYPENAME_IS_RESOLVING_P (type) = 1;
17620       result = resolve_typename_type (result, only_current_p);
17621       TYPENAME_IS_RESOLVING_P (type) = 0;
17622     }
17623   
17624   /* Qualify the resulting type.  */
17625   quals = cp_type_quals (type);
17626   if (quals)
17627     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
17628
17629   return result;
17630 }
17631
17632 /* EXPR is an expression which is not type-dependent.  Return a proxy
17633    for EXPR that can be used to compute the types of larger
17634    expressions containing EXPR.  */
17635
17636 tree
17637 build_non_dependent_expr (tree expr)
17638 {
17639   tree inner_expr;
17640
17641   /* Preserve null pointer constants so that the type of things like
17642      "p == 0" where "p" is a pointer can be determined.  */
17643   if (null_ptr_cst_p (expr))
17644     return expr;
17645   /* Preserve OVERLOADs; the functions must be available to resolve
17646      types.  */
17647   inner_expr = expr;
17648   if (TREE_CODE (inner_expr) == STMT_EXPR)
17649     inner_expr = stmt_expr_value_expr (inner_expr);
17650   if (TREE_CODE (inner_expr) == ADDR_EXPR)
17651     inner_expr = TREE_OPERAND (inner_expr, 0);
17652   if (TREE_CODE (inner_expr) == COMPONENT_REF)
17653     inner_expr = TREE_OPERAND (inner_expr, 1);
17654   if (is_overloaded_fn (inner_expr)
17655       || TREE_CODE (inner_expr) == OFFSET_REF)
17656     return expr;
17657   /* There is no need to return a proxy for a variable.  */
17658   if (TREE_CODE (expr) == VAR_DECL)
17659     return expr;
17660   /* Preserve string constants; conversions from string constants to
17661      "char *" are allowed, even though normally a "const char *"
17662      cannot be used to initialize a "char *".  */
17663   if (TREE_CODE (expr) == STRING_CST)
17664     return expr;
17665   /* Preserve arithmetic constants, as an optimization -- there is no
17666      reason to create a new node.  */
17667   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
17668     return expr;
17669   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
17670      There is at least one place where we want to know that a
17671      particular expression is a throw-expression: when checking a ?:
17672      expression, there are special rules if the second or third
17673      argument is a throw-expression.  */
17674   if (TREE_CODE (expr) == THROW_EXPR)
17675     return expr;
17676
17677   if (TREE_CODE (expr) == COND_EXPR)
17678     return build3 (COND_EXPR,
17679                    TREE_TYPE (expr),
17680                    TREE_OPERAND (expr, 0),
17681                    (TREE_OPERAND (expr, 1)
17682                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
17683                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
17684                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
17685   if (TREE_CODE (expr) == COMPOUND_EXPR
17686       && !COMPOUND_EXPR_OVERLOADED (expr))
17687     return build2 (COMPOUND_EXPR,
17688                    TREE_TYPE (expr),
17689                    TREE_OPERAND (expr, 0),
17690                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
17691
17692   /* If the type is unknown, it can't really be non-dependent */
17693   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
17694
17695   /* Otherwise, build a NON_DEPENDENT_EXPR.
17696
17697      REFERENCE_TYPEs are not stripped for expressions in templates
17698      because doing so would play havoc with mangling.  Consider, for
17699      example:
17700
17701        template <typename T> void f<T& g>() { g(); }
17702
17703      In the body of "f", the expression for "g" will have
17704      REFERENCE_TYPE, even though the standard says that it should
17705      not.  The reason is that we must preserve the syntactic form of
17706      the expression so that mangling (say) "f<g>" inside the body of
17707      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
17708      stripped here.  */
17709   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
17710 }
17711
17712 /* ARGS is a vector of expressions as arguments to a function call.
17713    Replace the arguments with equivalent non-dependent expressions.
17714    This modifies ARGS in place.  */
17715
17716 void
17717 make_args_non_dependent (VEC(tree,gc) *args)
17718 {
17719   unsigned int ix;
17720   tree arg;
17721
17722   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
17723     {
17724       tree newarg = build_non_dependent_expr (arg);
17725       if (newarg != arg)
17726         VEC_replace (tree, args, ix, newarg);
17727     }
17728 }
17729
17730 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
17731    with a level one deeper than the actual template parms.  */
17732
17733 tree
17734 make_auto (void)
17735 {
17736   tree au;
17737
17738   /* ??? Is it worth caching this for multiple autos at the same level?  */
17739   au = cxx_make_type (TEMPLATE_TYPE_PARM);
17740   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
17741                                TYPE_DECL, get_identifier ("auto"), au);
17742   TYPE_STUB_DECL (au) = TYPE_NAME (au);
17743   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
17744     (0, processing_template_decl + 1, processing_template_decl + 1,
17745      TYPE_NAME (au), NULL_TREE);
17746   TYPE_CANONICAL (au) = canonical_type_parameter (au);
17747   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
17748   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
17749
17750   return au;
17751 }
17752
17753 /* Given type ARG, return std::initializer_list<ARG>.  */
17754
17755 static tree
17756 listify (tree arg)
17757 {
17758   tree std_init_list = namespace_binding
17759     (get_identifier ("initializer_list"), std_node);
17760   tree argvec;
17761   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
17762     {    
17763       error ("deducing from brace-enclosed initializer list requires "
17764              "#include <initializer_list>");
17765       return error_mark_node;
17766     }
17767   argvec = make_tree_vec (1);
17768   TREE_VEC_ELT (argvec, 0) = arg;
17769   return lookup_template_class (std_init_list, argvec, NULL_TREE,
17770                                 NULL_TREE, 0, tf_warning_or_error);
17771 }
17772
17773 /* Replace auto in TYPE with std::initializer_list<auto>.  */
17774
17775 static tree
17776 listify_autos (tree type, tree auto_node)
17777 {
17778   tree init_auto = listify (auto_node);
17779   tree argvec = make_tree_vec (1);
17780   TREE_VEC_ELT (argvec, 0) = init_auto;
17781   if (processing_template_decl)
17782     argvec = add_to_template_args (current_template_args (), argvec);
17783   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17784 }
17785
17786 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
17787    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
17788
17789 tree
17790 do_auto_deduction (tree type, tree init, tree auto_node)
17791 {
17792   tree parms, tparms, targs;
17793   tree args[1];
17794   int val;
17795
17796   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
17797      with either a new invented type template parameter U or, if the
17798      initializer is a braced-init-list (8.5.4), with
17799      std::initializer_list<U>.  */
17800   if (BRACE_ENCLOSED_INITIALIZER_P (init))
17801     type = listify_autos (type, auto_node);
17802
17803   parms = build_tree_list (NULL_TREE, type);
17804   args[0] = init;
17805   tparms = make_tree_vec (1);
17806   targs = make_tree_vec (1);
17807   TREE_VEC_ELT (tparms, 0)
17808     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
17809   val = type_unification_real (tparms, targs, parms, args, 1, 0,
17810                                DEDUCE_CALL, LOOKUP_NORMAL);
17811   if (val > 0)
17812     {
17813       error ("unable to deduce %qT from %qE", type, init);
17814       return error_mark_node;
17815     }
17816
17817   if (processing_template_decl)
17818     targs = add_to_template_args (current_template_args (), targs);
17819   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
17820 }
17821
17822 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
17823    result.  */
17824
17825 tree
17826 splice_late_return_type (tree type, tree late_return_type)
17827 {
17828   tree argvec;
17829
17830   if (late_return_type == NULL_TREE)
17831     return type;
17832   argvec = make_tree_vec (1);
17833   TREE_VEC_ELT (argvec, 0) = late_return_type;
17834   if (processing_template_decl)
17835     argvec = add_to_template_args (current_template_args (), argvec);
17836   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17837 }
17838
17839 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
17840
17841 bool
17842 is_auto (const_tree type)
17843 {
17844   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17845       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
17846     return true;
17847   else
17848     return false;
17849 }
17850
17851 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
17852    appear as a type-specifier for the declaration in question, we don't
17853    have to look through the whole type.  */
17854
17855 tree
17856 type_uses_auto (tree type)
17857 {
17858   enum tree_code code;
17859   if (is_auto (type))
17860     return type;
17861
17862   code = TREE_CODE (type);
17863
17864   if (code == POINTER_TYPE || code == REFERENCE_TYPE
17865       || code == OFFSET_TYPE || code == FUNCTION_TYPE
17866       || code == METHOD_TYPE || code == ARRAY_TYPE)
17867     return type_uses_auto (TREE_TYPE (type));
17868
17869   if (TYPE_PTRMEMFUNC_P (type))
17870     return type_uses_auto (TREE_TYPE (TREE_TYPE
17871                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
17872
17873   return NULL_TREE;
17874 }
17875
17876 /* For a given template T, return the list of typedefs referenced
17877    in T for which access check is needed at T instantiation time.
17878    T is either  a FUNCTION_DECL or a RECORD_TYPE.
17879    Those typedefs were added to T by the function
17880    append_type_to_template_for_access_check.  */
17881
17882 tree
17883 get_types_needing_access_check (tree t)
17884 {
17885   tree ti, result = NULL_TREE;
17886
17887   if (!t || t == error_mark_node)
17888     return t;
17889
17890   if (!(ti = get_template_info (t)))
17891     return NULL_TREE;
17892
17893   if (CLASS_TYPE_P (t)
17894       || TREE_CODE (t) == FUNCTION_DECL)
17895     {
17896       if (!TI_TEMPLATE (ti))
17897         return NULL_TREE;
17898
17899       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
17900     }
17901
17902   return result;
17903 }
17904
17905 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
17906    tied to T. That list of typedefs will be access checked at
17907    T instantiation time.
17908    T is either a FUNCTION_DECL or a RECORD_TYPE.
17909    TYPE_DECL is a TYPE_DECL node representing a typedef.
17910    SCOPE is the scope through which TYPE_DECL is accessed.
17911
17912    This function is a subroutine of
17913    append_type_to_template_for_access_check.  */
17914
17915 static void
17916 append_type_to_template_for_access_check_1 (tree t,
17917                                             tree type_decl,
17918                                             tree scope)
17919 {
17920   tree ti;
17921
17922   if (!t || t == error_mark_node)
17923     return;
17924
17925   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
17926                || CLASS_TYPE_P (t))
17927               && type_decl
17928               && TREE_CODE (type_decl) == TYPE_DECL
17929               && scope);
17930
17931   if (!(ti = get_template_info (t)))
17932     return;
17933
17934   gcc_assert (TI_TEMPLATE (ti));
17935
17936   TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti) =
17937     tree_cons (type_decl, scope, TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti));
17938 }
17939
17940 /* Append TYPE_DECL to the template TEMPL.
17941    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
17942    At TEMPL instanciation time, TYPE_DECL will be checked to see
17943    if it can be accessed through SCOPE.
17944
17945    e.g. consider the following code snippet:
17946
17947      class C
17948      {
17949        typedef int myint;
17950      };
17951
17952      template<class U> struct S
17953      {
17954        C::myint mi;
17955      };
17956
17957      S<char> s;
17958
17959    At S<char> instantiation time, we need to check the access of C::myint
17960    In other words, we need to check the access of the myint typedef through
17961    the C scope. For that purpose, this function will add the myint typedef
17962    and the scope C through which its being accessed to a list of typedefs
17963    tied to the template S. That list will be walked at template instantiation
17964    time and access check performed on each typedefs it contains.
17965    Note that this particular code snippet should yield an error because
17966    myint is private to C.  */
17967
17968 void
17969 append_type_to_template_for_access_check (tree templ,
17970                                           tree type_decl,
17971                                           tree scope)
17972 {
17973   tree node;
17974
17975   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
17976
17977   /* Make sure we don't append the type to the template twice.  */
17978   for (node = get_types_needing_access_check (templ);
17979        node;
17980        node = TREE_CHAIN (node))
17981     {
17982       tree decl = TREE_PURPOSE (node);
17983       tree type_scope = TREE_VALUE (node);
17984
17985       if (decl == type_decl && type_scope == scope)
17986         return;
17987     }
17988
17989   append_type_to_template_for_access_check_1 (templ, type_decl, scope);
17990 }
17991
17992 /* Set up the hash tables for template instantiations.  */
17993
17994 void
17995 init_template_processing (void)
17996 {
17997   decl_specializations = htab_create_ggc (37,
17998                                           hash_specialization,
17999                                           eq_specializations,
18000                                           ggc_free);
18001   type_specializations = htab_create_ggc (37,
18002                                           hash_specialization,
18003                                           eq_specializations,
18004                                           ggc_free);
18005 }
18006
18007 #include "gt-cp-pt.h"