OSDN Git Service

PR c++/41994
[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       if (!DECL_ARTIFICIAL (arg))
1505         val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1506       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1507
1508     case TARGET_EXPR:
1509       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1510
1511     case PTRMEM_CST:
1512       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1513       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1514
1515     case TEMPLATE_PARM_INDEX:
1516       val = iterative_hash_template_arg
1517         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1518       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1519       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1520
1521     case TRAIT_EXPR:
1522       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1523       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1524       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1525
1526     case BASELINK:
1527       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1528                                          val);
1529       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1530                                           val);
1531
1532     case MODOP_EXPR:
1533       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1534       code = TREE_CODE (TREE_OPERAND (arg, 1));
1535       val = iterative_hash_object (code, val);
1536       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1537
1538     default:
1539       switch (tclass)
1540         {
1541         case tcc_type:
1542           if (TYPE_CANONICAL (arg))
1543             return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1544                                           val);
1545           else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1546             return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1547           /* Otherwise just compare the types during lookup.  */
1548           return val;
1549
1550         case tcc_declaration:
1551         case tcc_constant:
1552           return iterative_hash_expr (arg, val);
1553
1554         default:
1555           gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1556           {
1557             unsigned n = TREE_OPERAND_LENGTH (arg);
1558             for (i = 0; i < n; ++i)
1559               val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1560             return val;
1561           }
1562         }
1563     }
1564   gcc_unreachable ();
1565   return 0;
1566 }
1567
1568 /* Unregister the specialization SPEC as a specialization of TMPL.
1569    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1570    if the SPEC was listed as a specialization of TMPL.
1571
1572    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1573
1574 bool
1575 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1576 {
1577   spec_entry **slot;
1578   spec_entry elt;
1579
1580   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1581   elt.args = TI_ARGS (tinfo);
1582   elt.spec = NULL_TREE;
1583
1584   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1585   if (*slot)
1586     {
1587       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1588       gcc_assert (new_spec != NULL_TREE);
1589       (*slot)->spec = new_spec;
1590       return 1;
1591     }
1592
1593   return 0;
1594 }
1595
1596 /* Compare an entry in the local specializations hash table P1 (which
1597    is really a pointer to a TREE_LIST) with P2 (which is really a
1598    DECL).  */
1599
1600 static int
1601 eq_local_specializations (const void *p1, const void *p2)
1602 {
1603   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1604 }
1605
1606 /* Hash P1, an entry in the local specializations table.  */
1607
1608 static hashval_t
1609 hash_local_specialization (const void* p1)
1610 {
1611   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1612 }
1613
1614 /* Like register_specialization, but for local declarations.  We are
1615    registering SPEC, an instantiation of TMPL.  */
1616
1617 static void
1618 register_local_specialization (tree spec, tree tmpl)
1619 {
1620   void **slot;
1621
1622   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1623                                    htab_hash_pointer (tmpl), INSERT);
1624   *slot = build_tree_list (spec, tmpl);
1625 }
1626
1627 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1628    specialized class.  */
1629
1630 bool
1631 explicit_class_specialization_p (tree type)
1632 {
1633   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1634     return false;
1635   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1636 }
1637
1638 /* Print the list of candidate FNS in an error message.  */
1639
1640 void
1641 print_candidates (tree fns)
1642 {
1643   tree fn;
1644   tree f;
1645
1646   const char *str = "candidates are:";
1647
1648   if (is_overloaded_fn (fns))
1649     {
1650       for (f = fns; f; f = OVL_NEXT (f))
1651         {
1652           error ("%s %+#D", str, OVL_CURRENT (f));
1653           str = "               ";
1654         }
1655     }
1656   else for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1657     {
1658       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1659         error ("%s %+#D", str, OVL_CURRENT (f));
1660       str = "               ";
1661     }
1662 }
1663
1664 /* Returns the template (one of the functions given by TEMPLATE_ID)
1665    which can be specialized to match the indicated DECL with the
1666    explicit template args given in TEMPLATE_ID.  The DECL may be
1667    NULL_TREE if none is available.  In that case, the functions in
1668    TEMPLATE_ID are non-members.
1669
1670    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1671    specialization of a member template.
1672
1673    The TEMPLATE_COUNT is the number of references to qualifying
1674    template classes that appeared in the name of the function. See
1675    check_explicit_specialization for a more accurate description.
1676
1677    TSK indicates what kind of template declaration (if any) is being
1678    declared.  TSK_TEMPLATE indicates that the declaration given by
1679    DECL, though a FUNCTION_DECL, has template parameters, and is
1680    therefore a template function.
1681
1682    The template args (those explicitly specified and those deduced)
1683    are output in a newly created vector *TARGS_OUT.
1684
1685    If it is impossible to determine the result, an error message is
1686    issued.  The error_mark_node is returned to indicate failure.  */
1687
1688 static tree
1689 determine_specialization (tree template_id,
1690                           tree decl,
1691                           tree* targs_out,
1692                           int need_member_template,
1693                           int template_count,
1694                           tmpl_spec_kind tsk)
1695 {
1696   tree fns;
1697   tree targs;
1698   tree explicit_targs;
1699   tree candidates = NULL_TREE;
1700   /* A TREE_LIST of templates of which DECL may be a specialization.
1701      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1702      corresponding TREE_PURPOSE is the set of template arguments that,
1703      when used to instantiate the template, would produce a function
1704      with the signature of DECL.  */
1705   tree templates = NULL_TREE;
1706   int header_count;
1707   struct cp_binding_level *b;
1708
1709   *targs_out = NULL_TREE;
1710
1711   if (template_id == error_mark_node || decl == error_mark_node)
1712     return error_mark_node;
1713
1714   fns = TREE_OPERAND (template_id, 0);
1715   explicit_targs = TREE_OPERAND (template_id, 1);
1716
1717   if (fns == error_mark_node)
1718     return error_mark_node;
1719
1720   /* Check for baselinks.  */
1721   if (BASELINK_P (fns))
1722     fns = BASELINK_FUNCTIONS (fns);
1723
1724   if (!is_overloaded_fn (fns))
1725     {
1726       error ("%qD is not a function template", fns);
1727       return error_mark_node;
1728     }
1729
1730   /* Count the number of template headers specified for this
1731      specialization.  */
1732   header_count = 0;
1733   for (b = current_binding_level;
1734        b->kind == sk_template_parms;
1735        b = b->level_chain)
1736     ++header_count;
1737
1738   for (; fns; fns = OVL_NEXT (fns))
1739     {
1740       tree fn = OVL_CURRENT (fns);
1741
1742       if (TREE_CODE (fn) == TEMPLATE_DECL)
1743         {
1744           tree decl_arg_types;
1745           tree fn_arg_types;
1746
1747           /* In case of explicit specialization, we need to check if
1748              the number of template headers appearing in the specialization
1749              is correct. This is usually done in check_explicit_specialization,
1750              but the check done there cannot be exhaustive when specializing
1751              member functions. Consider the following code:
1752
1753              template <> void A<int>::f(int);
1754              template <> template <> void A<int>::f(int);
1755
1756              Assuming that A<int> is not itself an explicit specialization
1757              already, the first line specializes "f" which is a non-template
1758              member function, whilst the second line specializes "f" which
1759              is a template member function. So both lines are syntactically
1760              correct, and check_explicit_specialization does not reject
1761              them.
1762
1763              Here, we can do better, as we are matching the specialization
1764              against the declarations. We count the number of template
1765              headers, and we check if they match TEMPLATE_COUNT + 1
1766              (TEMPLATE_COUNT is the number of qualifying template classes,
1767              plus there must be another header for the member template
1768              itself).
1769
1770              Notice that if header_count is zero, this is not a
1771              specialization but rather a template instantiation, so there
1772              is no check we can perform here.  */
1773           if (header_count && header_count != template_count + 1)
1774             continue;
1775
1776           /* Check that the number of template arguments at the
1777              innermost level for DECL is the same as for FN.  */
1778           if (current_binding_level->kind == sk_template_parms
1779               && !current_binding_level->explicit_spec_p
1780               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1781                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1782                                       (current_template_parms))))
1783             continue;
1784
1785           /* DECL might be a specialization of FN.  */
1786           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1787           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1788
1789           /* For a non-static member function, we need to make sure
1790              that the const qualification is the same.  Since
1791              get_bindings does not try to merge the "this" parameter,
1792              we must do the comparison explicitly.  */
1793           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1794               && !same_type_p (TREE_VALUE (fn_arg_types),
1795                                TREE_VALUE (decl_arg_types)))
1796             continue;
1797
1798           /* Skip the "this" parameter and, for constructors of
1799              classes with virtual bases, the VTT parameter.  A
1800              full specialization of a constructor will have a VTT
1801              parameter, but a template never will.  */ 
1802           decl_arg_types 
1803             = skip_artificial_parms_for (decl, decl_arg_types);
1804           fn_arg_types 
1805             = skip_artificial_parms_for (fn, fn_arg_types);
1806
1807           /* Check that the number of function parameters matches.
1808              For example,
1809                template <class T> void f(int i = 0);
1810                template <> void f<int>();
1811              The specialization f<int> is invalid but is not caught
1812              by get_bindings below.  */
1813           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1814             continue;
1815
1816           /* Function templates cannot be specializations; there are
1817              no partial specializations of functions.  Therefore, if
1818              the type of DECL does not match FN, there is no
1819              match.  */
1820           if (tsk == tsk_template)
1821             {
1822               if (compparms (fn_arg_types, decl_arg_types))
1823                 candidates = tree_cons (NULL_TREE, fn, candidates);
1824               continue;
1825             }
1826
1827           /* See whether this function might be a specialization of this
1828              template.  */
1829           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1830
1831           if (!targs)
1832             /* We cannot deduce template arguments that when used to
1833                specialize TMPL will produce DECL.  */
1834             continue;
1835
1836           /* Save this template, and the arguments deduced.  */
1837           templates = tree_cons (targs, fn, templates);
1838         }
1839       else if (need_member_template)
1840         /* FN is an ordinary member function, and we need a
1841            specialization of a member template.  */
1842         ;
1843       else if (TREE_CODE (fn) != FUNCTION_DECL)
1844         /* We can get IDENTIFIER_NODEs here in certain erroneous
1845            cases.  */
1846         ;
1847       else if (!DECL_FUNCTION_MEMBER_P (fn))
1848         /* This is just an ordinary non-member function.  Nothing can
1849            be a specialization of that.  */
1850         ;
1851       else if (DECL_ARTIFICIAL (fn))
1852         /* Cannot specialize functions that are created implicitly.  */
1853         ;
1854       else
1855         {
1856           tree decl_arg_types;
1857
1858           /* This is an ordinary member function.  However, since
1859              we're here, we can assume it's enclosing class is a
1860              template class.  For example,
1861
1862                template <typename T> struct S { void f(); };
1863                template <> void S<int>::f() {}
1864
1865              Here, S<int>::f is a non-template, but S<int> is a
1866              template class.  If FN has the same type as DECL, we
1867              might be in business.  */
1868
1869           if (!DECL_TEMPLATE_INFO (fn))
1870             /* Its enclosing class is an explicit specialization
1871                of a template class.  This is not a candidate.  */
1872             continue;
1873
1874           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1875                             TREE_TYPE (TREE_TYPE (fn))))
1876             /* The return types differ.  */
1877             continue;
1878
1879           /* Adjust the type of DECL in case FN is a static member.  */
1880           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1881           if (DECL_STATIC_FUNCTION_P (fn)
1882               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1883             decl_arg_types = TREE_CHAIN (decl_arg_types);
1884
1885           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1886                          decl_arg_types))
1887             /* They match!  */
1888             candidates = tree_cons (NULL_TREE, fn, candidates);
1889         }
1890     }
1891
1892   if (templates && TREE_CHAIN (templates))
1893     {
1894       /* We have:
1895
1896            [temp.expl.spec]
1897
1898            It is possible for a specialization with a given function
1899            signature to be instantiated from more than one function
1900            template.  In such cases, explicit specification of the
1901            template arguments must be used to uniquely identify the
1902            function template specialization being specialized.
1903
1904          Note that here, there's no suggestion that we're supposed to
1905          determine which of the candidate templates is most
1906          specialized.  However, we, also have:
1907
1908            [temp.func.order]
1909
1910            Partial ordering of overloaded function template
1911            declarations is used in the following contexts to select
1912            the function template to which a function template
1913            specialization refers:
1914
1915            -- when an explicit specialization refers to a function
1916               template.
1917
1918          So, we do use the partial ordering rules, at least for now.
1919          This extension can only serve to make invalid programs valid,
1920          so it's safe.  And, there is strong anecdotal evidence that
1921          the committee intended the partial ordering rules to apply;
1922          the EDG front end has that behavior, and John Spicer claims
1923          that the committee simply forgot to delete the wording in
1924          [temp.expl.spec].  */
1925       tree tmpl = most_specialized_instantiation (templates);
1926       if (tmpl != error_mark_node)
1927         {
1928           templates = tmpl;
1929           TREE_CHAIN (templates) = NULL_TREE;
1930         }
1931     }
1932
1933   if (templates == NULL_TREE && candidates == NULL_TREE)
1934     {
1935       error ("template-id %qD for %q+D does not match any template "
1936              "declaration", template_id, decl);
1937       return error_mark_node;
1938     }
1939   else if ((templates && TREE_CHAIN (templates))
1940            || (candidates && TREE_CHAIN (candidates))
1941            || (templates && candidates))
1942     {
1943       error ("ambiguous template specialization %qD for %q+D",
1944              template_id, decl);
1945       chainon (candidates, templates);
1946       print_candidates (candidates);
1947       return error_mark_node;
1948     }
1949
1950   /* We have one, and exactly one, match.  */
1951   if (candidates)
1952     {
1953       tree fn = TREE_VALUE (candidates);
1954       *targs_out = copy_node (DECL_TI_ARGS (fn));
1955       /* DECL is a re-declaration or partial instantiation of a template
1956          function.  */
1957       if (TREE_CODE (fn) == TEMPLATE_DECL)
1958         return fn;
1959       /* It was a specialization of an ordinary member function in a
1960          template class.  */
1961       return DECL_TI_TEMPLATE (fn);
1962     }
1963
1964   /* It was a specialization of a template.  */
1965   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1966   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1967     {
1968       *targs_out = copy_node (targs);
1969       SET_TMPL_ARGS_LEVEL (*targs_out,
1970                            TMPL_ARGS_DEPTH (*targs_out),
1971                            TREE_PURPOSE (templates));
1972     }
1973   else
1974     *targs_out = TREE_PURPOSE (templates);
1975   return TREE_VALUE (templates);
1976 }
1977
1978 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1979    but with the default argument values filled in from those in the
1980    TMPL_TYPES.  */
1981
1982 static tree
1983 copy_default_args_to_explicit_spec_1 (tree spec_types,
1984                                       tree tmpl_types)
1985 {
1986   tree new_spec_types;
1987
1988   if (!spec_types)
1989     return NULL_TREE;
1990
1991   if (spec_types == void_list_node)
1992     return void_list_node;
1993
1994   /* Substitute into the rest of the list.  */
1995   new_spec_types =
1996     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1997                                           TREE_CHAIN (tmpl_types));
1998
1999   /* Add the default argument for this parameter.  */
2000   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2001                          TREE_VALUE (spec_types),
2002                          new_spec_types);
2003 }
2004
2005 /* DECL is an explicit specialization.  Replicate default arguments
2006    from the template it specializes.  (That way, code like:
2007
2008      template <class T> void f(T = 3);
2009      template <> void f(double);
2010      void g () { f (); }
2011
2012    works, as required.)  An alternative approach would be to look up
2013    the correct default arguments at the call-site, but this approach
2014    is consistent with how implicit instantiations are handled.  */
2015
2016 static void
2017 copy_default_args_to_explicit_spec (tree decl)
2018 {
2019   tree tmpl;
2020   tree spec_types;
2021   tree tmpl_types;
2022   tree new_spec_types;
2023   tree old_type;
2024   tree new_type;
2025   tree t;
2026   tree object_type = NULL_TREE;
2027   tree in_charge = NULL_TREE;
2028   tree vtt = NULL_TREE;
2029
2030   /* See if there's anything we need to do.  */
2031   tmpl = DECL_TI_TEMPLATE (decl);
2032   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2033   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2034     if (TREE_PURPOSE (t))
2035       break;
2036   if (!t)
2037     return;
2038
2039   old_type = TREE_TYPE (decl);
2040   spec_types = TYPE_ARG_TYPES (old_type);
2041
2042   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2043     {
2044       /* Remove the this pointer, but remember the object's type for
2045          CV quals.  */
2046       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2047       spec_types = TREE_CHAIN (spec_types);
2048       tmpl_types = TREE_CHAIN (tmpl_types);
2049
2050       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2051         {
2052           /* DECL may contain more parameters than TMPL due to the extra
2053              in-charge parameter in constructors and destructors.  */
2054           in_charge = spec_types;
2055           spec_types = TREE_CHAIN (spec_types);
2056         }
2057       if (DECL_HAS_VTT_PARM_P (decl))
2058         {
2059           vtt = spec_types;
2060           spec_types = TREE_CHAIN (spec_types);
2061         }
2062     }
2063
2064   /* Compute the merged default arguments.  */
2065   new_spec_types =
2066     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2067
2068   /* Compute the new FUNCTION_TYPE.  */
2069   if (object_type)
2070     {
2071       if (vtt)
2072         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2073                                          TREE_VALUE (vtt),
2074                                          new_spec_types);
2075
2076       if (in_charge)
2077         /* Put the in-charge parameter back.  */
2078         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2079                                          TREE_VALUE (in_charge),
2080                                          new_spec_types);
2081
2082       new_type = build_method_type_directly (object_type,
2083                                              TREE_TYPE (old_type),
2084                                              new_spec_types);
2085     }
2086   else
2087     new_type = build_function_type (TREE_TYPE (old_type),
2088                                     new_spec_types);
2089   new_type = cp_build_type_attribute_variant (new_type,
2090                                               TYPE_ATTRIBUTES (old_type));
2091   new_type = build_exception_variant (new_type,
2092                                       TYPE_RAISES_EXCEPTIONS (old_type));
2093   TREE_TYPE (decl) = new_type;
2094 }
2095
2096 /* Check to see if the function just declared, as indicated in
2097    DECLARATOR, and in DECL, is a specialization of a function
2098    template.  We may also discover that the declaration is an explicit
2099    instantiation at this point.
2100
2101    Returns DECL, or an equivalent declaration that should be used
2102    instead if all goes well.  Issues an error message if something is
2103    amiss.  Returns error_mark_node if the error is not easily
2104    recoverable.
2105
2106    FLAGS is a bitmask consisting of the following flags:
2107
2108    2: The function has a definition.
2109    4: The function is a friend.
2110
2111    The TEMPLATE_COUNT is the number of references to qualifying
2112    template classes that appeared in the name of the function.  For
2113    example, in
2114
2115      template <class T> struct S { void f(); };
2116      void S<int>::f();
2117
2118    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2119    classes are not counted in the TEMPLATE_COUNT, so that in
2120
2121      template <class T> struct S {};
2122      template <> struct S<int> { void f(); }
2123      template <> void S<int>::f();
2124
2125    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2126    invalid; there should be no template <>.)
2127
2128    If the function is a specialization, it is marked as such via
2129    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2130    is set up correctly, and it is added to the list of specializations
2131    for that template.  */
2132
2133 tree
2134 check_explicit_specialization (tree declarator,
2135                                tree decl,
2136                                int template_count,
2137                                int flags)
2138 {
2139   int have_def = flags & 2;
2140   int is_friend = flags & 4;
2141   int specialization = 0;
2142   int explicit_instantiation = 0;
2143   int member_specialization = 0;
2144   tree ctype = DECL_CLASS_CONTEXT (decl);
2145   tree dname = DECL_NAME (decl);
2146   tmpl_spec_kind tsk;
2147
2148   if (is_friend)
2149     {
2150       if (!processing_specialization)
2151         tsk = tsk_none;
2152       else
2153         tsk = tsk_excessive_parms;
2154     }
2155   else
2156     tsk = current_tmpl_spec_kind (template_count);
2157
2158   switch (tsk)
2159     {
2160     case tsk_none:
2161       if (processing_specialization)
2162         {
2163           specialization = 1;
2164           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2165         }
2166       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2167         {
2168           if (is_friend)
2169             /* This could be something like:
2170
2171                template <class T> void f(T);
2172                class S { friend void f<>(int); }  */
2173             specialization = 1;
2174           else
2175             {
2176               /* This case handles bogus declarations like template <>
2177                  template <class T> void f<int>(); */
2178
2179               error ("template-id %qD in declaration of primary template",
2180                      declarator);
2181               return decl;
2182             }
2183         }
2184       break;
2185
2186     case tsk_invalid_member_spec:
2187       /* The error has already been reported in
2188          check_specialization_scope.  */
2189       return error_mark_node;
2190
2191     case tsk_invalid_expl_inst:
2192       error ("template parameter list used in explicit instantiation");
2193
2194       /* Fall through.  */
2195
2196     case tsk_expl_inst:
2197       if (have_def)
2198         error ("definition provided for explicit instantiation");
2199
2200       explicit_instantiation = 1;
2201       break;
2202
2203     case tsk_excessive_parms:
2204     case tsk_insufficient_parms:
2205       if (tsk == tsk_excessive_parms)
2206         error ("too many template parameter lists in declaration of %qD",
2207                decl);
2208       else if (template_header_count)
2209         error("too few template parameter lists in declaration of %qD", decl);
2210       else
2211         error("explicit specialization of %qD must be introduced by "
2212               "%<template <>%>", decl);
2213
2214       /* Fall through.  */
2215     case tsk_expl_spec:
2216       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2217       if (ctype)
2218         member_specialization = 1;
2219       else
2220         specialization = 1;
2221       break;
2222
2223     case tsk_template:
2224       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2225         {
2226           /* This case handles bogus declarations like template <>
2227              template <class T> void f<int>(); */
2228
2229           if (uses_template_parms (declarator))
2230             error ("function template partial specialization %qD "
2231                    "is not allowed", declarator);
2232           else
2233             error ("template-id %qD in declaration of primary template",
2234                    declarator);
2235           return decl;
2236         }
2237
2238       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2239         /* This is a specialization of a member template, without
2240            specialization the containing class.  Something like:
2241
2242              template <class T> struct S {
2243                template <class U> void f (U);
2244              };
2245              template <> template <class U> void S<int>::f(U) {}
2246
2247            That's a specialization -- but of the entire template.  */
2248         specialization = 1;
2249       break;
2250
2251     default:
2252       gcc_unreachable ();
2253     }
2254
2255   if (specialization || member_specialization)
2256     {
2257       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2258       for (; t; t = TREE_CHAIN (t))
2259         if (TREE_PURPOSE (t))
2260           {
2261             permerror (input_location, 
2262                        "default argument specified in explicit specialization");
2263             break;
2264           }
2265     }
2266
2267   if (specialization || member_specialization || explicit_instantiation)
2268     {
2269       tree tmpl = NULL_TREE;
2270       tree targs = NULL_TREE;
2271
2272       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2273       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2274         {
2275           tree fns;
2276
2277           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2278           if (ctype)
2279             fns = dname;
2280           else
2281             {
2282               /* If there is no class context, the explicit instantiation
2283                  must be at namespace scope.  */
2284               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2285
2286               /* Find the namespace binding, using the declaration
2287                  context.  */
2288               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2289                                            false, true);
2290               if (fns == error_mark_node || !is_overloaded_fn (fns))
2291                 {
2292                   error ("%qD is not a template function", dname);
2293                   fns = error_mark_node;
2294                 }
2295               else
2296                 {
2297                   tree fn = OVL_CURRENT (fns);
2298                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2299                                                 CP_DECL_CONTEXT (fn)))
2300                     error ("%qD is not declared in %qD",
2301                            decl, current_namespace);
2302                 }
2303             }
2304
2305           declarator = lookup_template_function (fns, NULL_TREE);
2306         }
2307
2308       if (declarator == error_mark_node)
2309         return error_mark_node;
2310
2311       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2312         {
2313           if (!explicit_instantiation)
2314             /* A specialization in class scope.  This is invalid,
2315                but the error will already have been flagged by
2316                check_specialization_scope.  */
2317             return error_mark_node;
2318           else
2319             {
2320               /* It's not valid to write an explicit instantiation in
2321                  class scope, e.g.:
2322
2323                    class C { template void f(); }
2324
2325                    This case is caught by the parser.  However, on
2326                    something like:
2327
2328                    template class C { void f(); };
2329
2330                    (which is invalid) we can get here.  The error will be
2331                    issued later.  */
2332               ;
2333             }
2334
2335           return decl;
2336         }
2337       else if (ctype != NULL_TREE
2338                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2339                    IDENTIFIER_NODE))
2340         {
2341           /* Find the list of functions in ctype that have the same
2342              name as the declared function.  */
2343           tree name = TREE_OPERAND (declarator, 0);
2344           tree fns = NULL_TREE;
2345           int idx;
2346
2347           if (constructor_name_p (name, ctype))
2348             {
2349               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2350
2351               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2352                   : !CLASSTYPE_DESTRUCTORS (ctype))
2353                 {
2354                   /* From [temp.expl.spec]:
2355
2356                      If such an explicit specialization for the member
2357                      of a class template names an implicitly-declared
2358                      special member function (clause _special_), the
2359                      program is ill-formed.
2360
2361                      Similar language is found in [temp.explicit].  */
2362                   error ("specialization of implicitly-declared special member function");
2363                   return error_mark_node;
2364                 }
2365
2366               name = is_constructor ? ctor_identifier : dtor_identifier;
2367             }
2368
2369           if (!DECL_CONV_FN_P (decl))
2370             {
2371               idx = lookup_fnfields_1 (ctype, name);
2372               if (idx >= 0)
2373                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2374             }
2375           else
2376             {
2377               VEC(tree,gc) *methods;
2378               tree ovl;
2379
2380               /* For a type-conversion operator, we cannot do a
2381                  name-based lookup.  We might be looking for `operator
2382                  int' which will be a specialization of `operator T'.
2383                  So, we find *all* the conversion operators, and then
2384                  select from them.  */
2385               fns = NULL_TREE;
2386
2387               methods = CLASSTYPE_METHOD_VEC (ctype);
2388               if (methods)
2389                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2390                      VEC_iterate (tree, methods, idx, ovl);
2391                      ++idx)
2392                   {
2393                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2394                       /* There are no more conversion functions.  */
2395                       break;
2396
2397                     /* Glue all these conversion functions together
2398                        with those we already have.  */
2399                     for (; ovl; ovl = OVL_NEXT (ovl))
2400                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2401                   }
2402             }
2403
2404           if (fns == NULL_TREE)
2405             {
2406               error ("no member function %qD declared in %qT", name, ctype);
2407               return error_mark_node;
2408             }
2409           else
2410             TREE_OPERAND (declarator, 0) = fns;
2411         }
2412
2413       /* Figure out what exactly is being specialized at this point.
2414          Note that for an explicit instantiation, even one for a
2415          member function, we cannot tell apriori whether the
2416          instantiation is for a member template, or just a member
2417          function of a template class.  Even if a member template is
2418          being instantiated, the member template arguments may be
2419          elided if they can be deduced from the rest of the
2420          declaration.  */
2421       tmpl = determine_specialization (declarator, decl,
2422                                        &targs,
2423                                        member_specialization,
2424                                        template_count,
2425                                        tsk);
2426
2427       if (!tmpl || tmpl == error_mark_node)
2428         /* We couldn't figure out what this declaration was
2429            specializing.  */
2430         return error_mark_node;
2431       else
2432         {
2433           tree gen_tmpl = most_general_template (tmpl);
2434
2435           if (explicit_instantiation)
2436             {
2437               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2438                  is done by do_decl_instantiation later.  */
2439
2440               int arg_depth = TMPL_ARGS_DEPTH (targs);
2441               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2442
2443               if (arg_depth > parm_depth)
2444                 {
2445                   /* If TMPL is not the most general template (for
2446                      example, if TMPL is a friend template that is
2447                      injected into namespace scope), then there will
2448                      be too many levels of TARGS.  Remove some of them
2449                      here.  */
2450                   int i;
2451                   tree new_targs;
2452
2453                   new_targs = make_tree_vec (parm_depth);
2454                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2455                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2456                       = TREE_VEC_ELT (targs, i);
2457                   targs = new_targs;
2458                 }
2459
2460               return instantiate_template (tmpl, targs, tf_error);
2461             }
2462
2463           /* If we thought that the DECL was a member function, but it
2464              turns out to be specializing a static member function,
2465              make DECL a static member function as well.  */
2466           if (DECL_STATIC_FUNCTION_P (tmpl)
2467               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2468             revert_static_member_fn (decl);
2469
2470           /* If this is a specialization of a member template of a
2471              template class, we want to return the TEMPLATE_DECL, not
2472              the specialization of it.  */
2473           if (tsk == tsk_template)
2474             {
2475               tree result = DECL_TEMPLATE_RESULT (tmpl);
2476               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2477               DECL_INITIAL (result) = NULL_TREE;
2478               if (have_def)
2479                 {
2480                   tree parm;
2481                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2482                   DECL_SOURCE_LOCATION (result)
2483                     = DECL_SOURCE_LOCATION (decl);
2484                   /* We want to use the argument list specified in the
2485                      definition, not in the original declaration.  */
2486                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2487                   for (parm = DECL_ARGUMENTS (result); parm;
2488                        parm = TREE_CHAIN (parm))
2489                     DECL_CONTEXT (parm) = result;
2490                 }
2491               return register_specialization (tmpl, gen_tmpl, targs,
2492                                               is_friend, 0);
2493             }
2494
2495           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2496           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2497
2498           /* Inherit default function arguments from the template
2499              DECL is specializing.  */
2500           copy_default_args_to_explicit_spec (decl);
2501
2502           /* This specialization has the same protection as the
2503              template it specializes.  */
2504           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2505           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2506
2507           /* 7.1.1-1 [dcl.stc]
2508
2509              A storage-class-specifier shall not be specified in an
2510              explicit specialization...
2511
2512              The parser rejects these, so unless action is taken here,
2513              explicit function specializations will always appear with
2514              global linkage.
2515
2516              The action recommended by the C++ CWG in response to C++
2517              defect report 605 is to make the storage class and linkage
2518              of the explicit specialization match the templated function:
2519
2520              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2521            */
2522           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2523             {
2524               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2525               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2526
2527               /* This specialization has the same linkage and visibility as
2528                  the function template it specializes.  */
2529               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2530               if (! TREE_PUBLIC (decl))
2531                 {
2532                   DECL_INTERFACE_KNOWN (decl) = 1;
2533                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2534                 }
2535               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2536               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2537                 {
2538                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2539                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2540                 }
2541             }
2542
2543           /* If DECL is a friend declaration, declared using an
2544              unqualified name, the namespace associated with DECL may
2545              have been set incorrectly.  For example, in:
2546
2547                template <typename T> void f(T);
2548                namespace N {
2549                  struct S { friend void f<int>(int); }
2550                }
2551
2552              we will have set the DECL_CONTEXT for the friend
2553              declaration to N, rather than to the global namespace.  */
2554           if (DECL_NAMESPACE_SCOPE_P (decl))
2555             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2556
2557           if (is_friend && !have_def)
2558             /* This is not really a declaration of a specialization.
2559                It's just the name of an instantiation.  But, it's not
2560                a request for an instantiation, either.  */
2561             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2562           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2563             /* This is indeed a specialization.  In case of constructors
2564                and destructors, we need in-charge and not-in-charge
2565                versions in V3 ABI.  */
2566             clone_function_decl (decl, /*update_method_vec_p=*/0);
2567
2568           /* Register this specialization so that we can find it
2569              again.  */
2570           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2571         }
2572     }
2573
2574   return decl;
2575 }
2576
2577 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2578    parameters.  These are represented in the same format used for
2579    DECL_TEMPLATE_PARMS.  */
2580
2581 int
2582 comp_template_parms (const_tree parms1, const_tree parms2)
2583 {
2584   const_tree p1;
2585   const_tree p2;
2586
2587   if (parms1 == parms2)
2588     return 1;
2589
2590   for (p1 = parms1, p2 = parms2;
2591        p1 != NULL_TREE && p2 != NULL_TREE;
2592        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2593     {
2594       tree t1 = TREE_VALUE (p1);
2595       tree t2 = TREE_VALUE (p2);
2596       int i;
2597
2598       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2599       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2600
2601       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2602         return 0;
2603
2604       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2605         {
2606           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2607           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2608
2609           /* If either of the template parameters are invalid, assume
2610              they match for the sake of error recovery. */
2611           if (parm1 == error_mark_node || parm2 == error_mark_node)
2612             return 1;
2613
2614           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2615             return 0;
2616
2617           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2618               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2619                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2620             continue;
2621           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2622             return 0;
2623         }
2624     }
2625
2626   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2627     /* One set of parameters has more parameters lists than the
2628        other.  */
2629     return 0;
2630
2631   return 1;
2632 }
2633
2634 /* Determine whether PARM is a parameter pack.  */
2635
2636 bool 
2637 template_parameter_pack_p (const_tree parm)
2638 {
2639   /* Determine if we have a non-type template parameter pack.  */
2640   if (TREE_CODE (parm) == PARM_DECL)
2641     return (DECL_TEMPLATE_PARM_P (parm) 
2642             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2643
2644   /* If this is a list of template parameters, we could get a
2645      TYPE_DECL or a TEMPLATE_DECL.  */ 
2646   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2647     parm = TREE_TYPE (parm);
2648
2649   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2650            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2651           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2652 }
2653
2654 /* Determine if T is a function parameter pack.  */
2655
2656 bool
2657 function_parameter_pack_p (const_tree t)
2658 {
2659   if (t && TREE_CODE (t) == PARM_DECL)
2660     return FUNCTION_PARAMETER_PACK_P (t);
2661   return false;
2662 }
2663
2664 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2665    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2666
2667 tree
2668 get_function_template_decl (const_tree primary_func_tmpl_inst)
2669 {
2670   if (! primary_func_tmpl_inst
2671       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2672       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2673     return NULL;
2674
2675   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2676 }
2677
2678 /* Return true iff the function parameter PARAM_DECL was expanded
2679    from the function parameter pack PACK.  */
2680
2681 bool
2682 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2683 {
2684     if (DECL_ARTIFICIAL (param_decl)
2685         || !function_parameter_pack_p (pack))
2686       return false;
2687
2688     gcc_assert (DECL_NAME (param_decl) && DECL_NAME (pack));
2689
2690     /* The parameter pack and its pack arguments have the same
2691        DECL_PARM_INDEX.  */
2692     return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2693 }
2694
2695 /* Determine whether ARGS describes a variadic template args list,
2696    i.e., one that is terminated by a template argument pack.  */
2697
2698 static bool 
2699 template_args_variadic_p (tree args)
2700 {
2701   int nargs;
2702   tree last_parm;
2703
2704   if (args == NULL_TREE)
2705     return false;
2706
2707   args = INNERMOST_TEMPLATE_ARGS (args);
2708   nargs = TREE_VEC_LENGTH (args);
2709
2710   if (nargs == 0)
2711     return false;
2712
2713   last_parm = TREE_VEC_ELT (args, nargs - 1);
2714
2715   return ARGUMENT_PACK_P (last_parm);
2716 }
2717
2718 /* Generate a new name for the parameter pack name NAME (an
2719    IDENTIFIER_NODE) that incorporates its */
2720
2721 static tree
2722 make_ith_pack_parameter_name (tree name, int i)
2723 {
2724   /* Munge the name to include the parameter index.  */
2725 #define NUMBUF_LEN 128
2726   char numbuf[NUMBUF_LEN];
2727   char* newname;
2728   int newname_len;
2729
2730   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2731   newname_len = IDENTIFIER_LENGTH (name)
2732                 + strlen (numbuf) + 2;
2733   newname = (char*)alloca (newname_len);
2734   snprintf (newname, newname_len,
2735             "%s#%i", IDENTIFIER_POINTER (name), i);
2736   return get_identifier (newname);
2737 }
2738
2739 /* Return true if T is a primary function
2740    or class template instantiation.  */
2741
2742 static bool
2743 primary_template_instantiation_p (const_tree t)
2744 {
2745   if (!t)
2746     return false;
2747
2748   if (TREE_CODE (t) == FUNCTION_DECL)
2749     return DECL_LANG_SPECIFIC (t)
2750            && DECL_TEMPLATE_INSTANTIATION (t)
2751            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2752   else if (CLASS_TYPE_P (t))
2753     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2754            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2755   return false;
2756 }
2757
2758 /* Return true if PARM is a template template parameter.  */
2759
2760 bool
2761 template_template_parameter_p (const_tree parm)
2762 {
2763   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2764 }
2765
2766 /* Return the template parameters of T if T is a
2767    primary template instantiation, NULL otherwise.  */
2768
2769 tree
2770 get_primary_template_innermost_parameters (const_tree t)
2771 {
2772   tree parms = NULL, template_info = NULL;
2773
2774   if ((template_info = get_template_info (t))
2775       && primary_template_instantiation_p (t))
2776     parms = INNERMOST_TEMPLATE_PARMS
2777         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2778
2779   return parms;
2780 }
2781
2782 /* Returns the template arguments of T if T is a template instantiation,
2783    NULL otherwise.  */
2784
2785 tree
2786 get_template_innermost_arguments (const_tree t)
2787 {
2788   tree args = NULL, template_info = NULL;
2789
2790   if ((template_info = get_template_info (t))
2791       && TI_ARGS (template_info))
2792     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2793
2794   return args;
2795 }
2796
2797 /* Return the argument pack elements of T if T is a template argument pack,
2798    NULL otherwise.  */
2799
2800 tree
2801 get_template_argument_pack_elems (const_tree t)
2802 {
2803   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2804       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2805     return NULL;
2806
2807   return ARGUMENT_PACK_ARGS (t);
2808 }
2809
2810 /* Structure used to track the progress of find_parameter_packs_r.  */
2811 struct find_parameter_pack_data 
2812 {
2813   /* TREE_LIST that will contain all of the parameter packs found by
2814      the traversal.  */
2815   tree* parameter_packs;
2816
2817   /* Set of AST nodes that have been visited by the traversal.  */
2818   struct pointer_set_t *visited;
2819 };
2820
2821 /* Identifies all of the argument packs that occur in a template
2822    argument and appends them to the TREE_LIST inside DATA, which is a
2823    find_parameter_pack_data structure. This is a subroutine of
2824    make_pack_expansion and uses_parameter_packs.  */
2825 static tree
2826 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2827 {
2828   tree t = *tp;
2829   struct find_parameter_pack_data* ppd = 
2830     (struct find_parameter_pack_data*)data;
2831   bool parameter_pack_p = false;
2832
2833   /* Identify whether this is a parameter pack or not.  */
2834   switch (TREE_CODE (t))
2835     {
2836     case TEMPLATE_PARM_INDEX:
2837       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2838         parameter_pack_p = true;
2839       break;
2840
2841     case TEMPLATE_TYPE_PARM:
2842     case TEMPLATE_TEMPLATE_PARM:
2843       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2844         parameter_pack_p = true;
2845       break;
2846
2847     case PARM_DECL:
2848       if (FUNCTION_PARAMETER_PACK_P (t))
2849         {
2850           /* We don't want to walk into the type of a PARM_DECL,
2851              because we don't want to see the type parameter pack.  */
2852           *walk_subtrees = 0;
2853           parameter_pack_p = true;
2854         }
2855       break;
2856
2857     default:
2858       /* Not a parameter pack.  */
2859       break;
2860     }
2861
2862   if (parameter_pack_p)
2863     {
2864       /* Add this parameter pack to the list.  */
2865       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2866     }
2867
2868   if (TYPE_P (t))
2869     cp_walk_tree (&TYPE_CONTEXT (t), 
2870                   &find_parameter_packs_r, ppd, ppd->visited);
2871
2872   /* This switch statement will return immediately if we don't find a
2873      parameter pack.  */
2874   switch (TREE_CODE (t)) 
2875     {
2876     case TEMPLATE_PARM_INDEX:
2877       return NULL_TREE;
2878
2879     case BOUND_TEMPLATE_TEMPLATE_PARM:
2880       /* Check the template itself.  */
2881       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2882                     &find_parameter_packs_r, ppd, ppd->visited);
2883       /* Check the template arguments.  */
2884       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2885                     ppd->visited);
2886       *walk_subtrees = 0;
2887       return NULL_TREE;
2888
2889     case TEMPLATE_TYPE_PARM:
2890     case TEMPLATE_TEMPLATE_PARM:
2891       return NULL_TREE;
2892
2893     case PARM_DECL:
2894       return NULL_TREE;
2895
2896     case RECORD_TYPE:
2897       if (TYPE_PTRMEMFUNC_P (t))
2898         return NULL_TREE;
2899       /* Fall through.  */
2900
2901     case UNION_TYPE:
2902     case ENUMERAL_TYPE:
2903       if (TYPE_TEMPLATE_INFO (t))
2904         cp_walk_tree (&TREE_VALUE (TYPE_TEMPLATE_INFO (t)), 
2905                       &find_parameter_packs_r, ppd, ppd->visited);
2906
2907       *walk_subtrees = 0;
2908       return NULL_TREE;
2909
2910     case TEMPLATE_DECL:
2911       cp_walk_tree (&TREE_TYPE (t),
2912                     &find_parameter_packs_r, ppd, ppd->visited);
2913       return NULL_TREE;
2914  
2915     case TYPENAME_TYPE:
2916       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2917                    ppd, ppd->visited);
2918       *walk_subtrees = 0;
2919       return NULL_TREE;
2920       
2921     case TYPE_PACK_EXPANSION:
2922     case EXPR_PACK_EXPANSION:
2923       *walk_subtrees = 0;
2924       return NULL_TREE;
2925
2926     case INTEGER_TYPE:
2927       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2928                     ppd, ppd->visited);
2929       *walk_subtrees = 0;
2930       return NULL_TREE;
2931
2932     case IDENTIFIER_NODE:
2933       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2934                     ppd->visited);
2935       *walk_subtrees = 0;
2936       return NULL_TREE;
2937
2938     default:
2939       return NULL_TREE;
2940     }
2941
2942   return NULL_TREE;
2943 }
2944
2945 /* Determines if the expression or type T uses any parameter packs.  */
2946 bool
2947 uses_parameter_packs (tree t)
2948 {
2949   tree parameter_packs = NULL_TREE;
2950   struct find_parameter_pack_data ppd;
2951   ppd.parameter_packs = &parameter_packs;
2952   ppd.visited = pointer_set_create ();
2953   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2954   pointer_set_destroy (ppd.visited);
2955   return parameter_packs != NULL_TREE;
2956 }
2957
2958 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2959    representation a base-class initializer into a parameter pack
2960    expansion. If all goes well, the resulting node will be an
2961    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2962    respectively.  */
2963 tree 
2964 make_pack_expansion (tree arg)
2965 {
2966   tree result;
2967   tree parameter_packs = NULL_TREE;
2968   bool for_types = false;
2969   struct find_parameter_pack_data ppd;
2970
2971   if (!arg || arg == error_mark_node)
2972     return arg;
2973
2974   if (TREE_CODE (arg) == TREE_LIST)
2975     {
2976       /* The only time we will see a TREE_LIST here is for a base
2977          class initializer.  In this case, the TREE_PURPOSE will be a
2978          _TYPE node (representing the base class expansion we're
2979          initializing) and the TREE_VALUE will be a TREE_LIST
2980          containing the initialization arguments. 
2981
2982          The resulting expansion looks somewhat different from most
2983          expansions. Rather than returning just one _EXPANSION, we
2984          return a TREE_LIST whose TREE_PURPOSE is a
2985          TYPE_PACK_EXPANSION containing the bases that will be
2986          initialized.  The TREE_VALUE will be identical to the
2987          original TREE_VALUE, which is a list of arguments that will
2988          be passed to each base.  We do not introduce any new pack
2989          expansion nodes into the TREE_VALUE (although it is possible
2990          that some already exist), because the TREE_PURPOSE and
2991          TREE_VALUE all need to be expanded together with the same
2992          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2993          resulting TREE_PURPOSE will mention the parameter packs in
2994          both the bases and the arguments to the bases.  */
2995       tree purpose;
2996       tree value;
2997       tree parameter_packs = NULL_TREE;
2998
2999       /* Determine which parameter packs will be used by the base
3000          class expansion.  */
3001       ppd.visited = pointer_set_create ();
3002       ppd.parameter_packs = &parameter_packs;
3003       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3004                     &ppd, ppd.visited);
3005
3006       if (parameter_packs == NULL_TREE)
3007         {
3008           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3009           pointer_set_destroy (ppd.visited);
3010           return error_mark_node;
3011         }
3012
3013       if (TREE_VALUE (arg) != void_type_node)
3014         {
3015           /* Collect the sets of parameter packs used in each of the
3016              initialization arguments.  */
3017           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3018             {
3019               /* Determine which parameter packs will be expanded in this
3020                  argument.  */
3021               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3022                             &ppd, ppd.visited);
3023             }
3024         }
3025
3026       pointer_set_destroy (ppd.visited);
3027
3028       /* Create the pack expansion type for the base type.  */
3029       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3030       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3031       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3032
3033       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3034          they will rarely be compared to anything.  */
3035       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3036
3037       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3038     }
3039
3040   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3041     for_types = true;
3042
3043   /* Build the PACK_EXPANSION_* node.  */
3044   result = for_types
3045      ? cxx_make_type (TYPE_PACK_EXPANSION)
3046      : make_node (EXPR_PACK_EXPANSION);
3047   SET_PACK_EXPANSION_PATTERN (result, arg);
3048   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3049     {
3050       /* Propagate type and const-expression information.  */
3051       TREE_TYPE (result) = TREE_TYPE (arg);
3052       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3053     }
3054   else
3055     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3056        they will rarely be compared to anything.  */
3057     SET_TYPE_STRUCTURAL_EQUALITY (result);
3058
3059   /* Determine which parameter packs will be expanded.  */
3060   ppd.parameter_packs = &parameter_packs;
3061   ppd.visited = pointer_set_create ();
3062   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3063   pointer_set_destroy (ppd.visited);
3064
3065   /* Make sure we found some parameter packs.  */
3066   if (parameter_packs == NULL_TREE)
3067     {
3068       if (TYPE_P (arg))
3069         error ("expansion pattern %<%T%> contains no argument packs", arg);
3070       else
3071         error ("expansion pattern %<%E%> contains no argument packs", arg);
3072       return error_mark_node;
3073     }
3074   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3075
3076   return result;
3077 }
3078
3079 /* Checks T for any "bare" parameter packs, which have not yet been
3080    expanded, and issues an error if any are found. This operation can
3081    only be done on full expressions or types (e.g., an expression
3082    statement, "if" condition, etc.), because we could have expressions like:
3083
3084      foo(f(g(h(args)))...)
3085
3086    where "args" is a parameter pack. check_for_bare_parameter_packs
3087    should not be called for the subexpressions args, h(args),
3088    g(h(args)), or f(g(h(args))), because we would produce erroneous
3089    error messages. 
3090
3091    Returns TRUE and emits an error if there were bare parameter packs,
3092    returns FALSE otherwise.  */
3093 bool 
3094 check_for_bare_parameter_packs (tree t)
3095 {
3096   tree parameter_packs = NULL_TREE;
3097   struct find_parameter_pack_data ppd;
3098
3099   if (!processing_template_decl || !t || t == error_mark_node)
3100     return false;
3101
3102   if (TREE_CODE (t) == TYPE_DECL)
3103     t = TREE_TYPE (t);
3104
3105   ppd.parameter_packs = &parameter_packs;
3106   ppd.visited = pointer_set_create ();
3107   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3108   pointer_set_destroy (ppd.visited);
3109
3110   if (parameter_packs) 
3111     {
3112       error ("parameter packs not expanded with %<...%>:");
3113       while (parameter_packs)
3114         {
3115           tree pack = TREE_VALUE (parameter_packs);
3116           tree name = NULL_TREE;
3117
3118           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3119               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3120             name = TYPE_NAME (pack);
3121           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3122             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3123           else
3124             name = DECL_NAME (pack);
3125
3126           if (name)
3127             inform (input_location, "        %qD", name);
3128           else
3129             inform (input_location, "        <anonymous>");
3130
3131           parameter_packs = TREE_CHAIN (parameter_packs);
3132         }
3133
3134       return true;
3135     }
3136
3137   return false;
3138 }
3139
3140 /* Expand any parameter packs that occur in the template arguments in
3141    ARGS.  */
3142 tree
3143 expand_template_argument_pack (tree args)
3144 {
3145   tree result_args = NULL_TREE;
3146   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3147   int num_result_args = -1;
3148
3149   /* First, determine if we need to expand anything, and the number of
3150      slots we'll need.  */
3151   for (in_arg = 0; in_arg < nargs; ++in_arg)
3152     {
3153       tree arg = TREE_VEC_ELT (args, in_arg);
3154       if (ARGUMENT_PACK_P (arg))
3155         {
3156           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3157           if (num_result_args < 0)
3158             num_result_args = in_arg + num_packed;
3159           else
3160             num_result_args += num_packed;
3161         }
3162       else
3163         {
3164           if (num_result_args >= 0)
3165             num_result_args++;
3166         }
3167     }
3168
3169   /* If no expansion is necessary, we're done.  */
3170   if (num_result_args < 0)
3171     return args;
3172
3173   /* Expand arguments.  */
3174   result_args = make_tree_vec (num_result_args);
3175   for (in_arg = 0; in_arg < nargs; ++in_arg)
3176     {
3177       tree arg = TREE_VEC_ELT (args, in_arg);
3178       if (ARGUMENT_PACK_P (arg))
3179         {
3180           tree packed = ARGUMENT_PACK_ARGS (arg);
3181           int i, num_packed = TREE_VEC_LENGTH (packed);
3182           for (i = 0; i < num_packed; ++i, ++out_arg)
3183             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3184         }
3185       else
3186         {
3187           TREE_VEC_ELT (result_args, out_arg) = arg;
3188           ++out_arg;
3189         }
3190     }
3191
3192   return result_args;
3193 }
3194
3195 /* Checks if DECL shadows a template parameter.
3196
3197    [temp.local]: A template-parameter shall not be redeclared within its
3198    scope (including nested scopes).
3199
3200    Emits an error and returns TRUE if the DECL shadows a parameter,
3201    returns FALSE otherwise.  */
3202
3203 bool
3204 check_template_shadow (tree decl)
3205 {
3206   tree olddecl;
3207
3208   /* If we're not in a template, we can't possibly shadow a template
3209      parameter.  */
3210   if (!current_template_parms)
3211     return true;
3212
3213   /* Figure out what we're shadowing.  */
3214   if (TREE_CODE (decl) == OVERLOAD)
3215     decl = OVL_CURRENT (decl);
3216   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3217
3218   /* If there's no previous binding for this name, we're not shadowing
3219      anything, let alone a template parameter.  */
3220   if (!olddecl)
3221     return true;
3222
3223   /* If we're not shadowing a template parameter, we're done.  Note
3224      that OLDDECL might be an OVERLOAD (or perhaps even an
3225      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3226      node.  */
3227   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3228     return true;
3229
3230   /* We check for decl != olddecl to avoid bogus errors for using a
3231      name inside a class.  We check TPFI to avoid duplicate errors for
3232      inline member templates.  */
3233   if (decl == olddecl
3234       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3235     return true;
3236
3237   error ("declaration of %q+#D", decl);
3238   error (" shadows template parm %q+#D", olddecl);
3239   return false;
3240 }
3241
3242 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3243    ORIG_LEVEL, DECL, and TYPE.  */
3244
3245 static tree
3246 build_template_parm_index (int index,
3247                            int level,
3248                            int orig_level,
3249                            tree decl,
3250                            tree type)
3251 {
3252   tree t = make_node (TEMPLATE_PARM_INDEX);
3253   TEMPLATE_PARM_IDX (t) = index;
3254   TEMPLATE_PARM_LEVEL (t) = level;
3255   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3256   TEMPLATE_PARM_DECL (t) = decl;
3257   TREE_TYPE (t) = type;
3258   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3259   TREE_READONLY (t) = TREE_READONLY (decl);
3260
3261   return t;
3262 }
3263
3264 /* Find the canonical type parameter for the given template type
3265    parameter.  Returns the canonical type parameter, which may be TYPE
3266    if no such parameter existed.  */
3267 static tree
3268 canonical_type_parameter (tree type)
3269 {
3270   tree list;
3271   int idx = TEMPLATE_TYPE_IDX (type);
3272   if (!canonical_template_parms)
3273     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3274
3275   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3276     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3277
3278   list = VEC_index (tree, canonical_template_parms, idx);
3279   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3280     list = TREE_CHAIN (list);
3281
3282   if (list)
3283     return TREE_VALUE (list);
3284   else
3285     {
3286       VEC_replace(tree, canonical_template_parms, idx,
3287                   tree_cons (NULL_TREE, type, 
3288                              VEC_index (tree, canonical_template_parms, idx)));
3289       return type;
3290     }
3291 }
3292
3293 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3294    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3295    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3296    new one is created.  */
3297
3298 static tree
3299 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3300                             tsubst_flags_t complain)
3301 {
3302   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3303       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3304           != TEMPLATE_PARM_LEVEL (index) - levels))
3305     {
3306       tree orig_decl = TEMPLATE_PARM_DECL (index);
3307       tree decl, t;
3308
3309       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3310                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3311       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3312       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3313       DECL_ARTIFICIAL (decl) = 1;
3314       SET_DECL_TEMPLATE_PARM_P (decl);
3315
3316       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3317                                      TEMPLATE_PARM_LEVEL (index) - levels,
3318                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3319                                      decl, type);
3320       TEMPLATE_PARM_DESCENDANTS (index) = t;
3321       TEMPLATE_PARM_PARAMETER_PACK (t) 
3322         = TEMPLATE_PARM_PARAMETER_PACK (index);
3323
3324         /* Template template parameters need this.  */
3325       if (TREE_CODE (decl) == TEMPLATE_DECL)
3326         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3327           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3328            args, complain);
3329     }
3330
3331   return TEMPLATE_PARM_DESCENDANTS (index);
3332 }
3333
3334 /* Process information from new template parameter PARM and append it to the
3335    LIST being built.  This new parameter is a non-type parameter iff
3336    IS_NON_TYPE is true. This new parameter is a parameter
3337    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3338    PARM_LOC.  */
3339
3340 tree
3341 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3342                        bool is_parameter_pack)
3343 {
3344   tree decl = 0;
3345   tree defval;
3346   tree err_parm_list;
3347   int idx = 0;
3348
3349   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3350   defval = TREE_PURPOSE (parm);
3351
3352   if (list)
3353     {
3354       tree p = tree_last (list);
3355
3356       if (p && TREE_VALUE (p) != error_mark_node)
3357         {
3358           p = TREE_VALUE (p);
3359           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3360             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3361           else
3362             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3363         }
3364
3365       ++idx;
3366     }
3367   else
3368     idx = 0;
3369
3370   if (is_non_type)
3371     {
3372       parm = TREE_VALUE (parm);
3373
3374       SET_DECL_TEMPLATE_PARM_P (parm);
3375
3376       if (TREE_TYPE (parm) == error_mark_node)
3377         {
3378           err_parm_list = build_tree_list (defval, parm);
3379           TREE_VALUE (err_parm_list) = error_mark_node;
3380            return chainon (list, err_parm_list);
3381         }
3382       else
3383       {
3384         /* [temp.param]
3385
3386            The top-level cv-qualifiers on the template-parameter are
3387            ignored when determining its type.  */
3388         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3389         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3390           {
3391             err_parm_list = build_tree_list (defval, parm);
3392             TREE_VALUE (err_parm_list) = error_mark_node;
3393              return chainon (list, err_parm_list);
3394           }
3395
3396         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3397           {
3398             /* This template parameter is not a parameter pack, but it
3399                should be. Complain about "bare" parameter packs.  */
3400             check_for_bare_parameter_packs (TREE_TYPE (parm));
3401             
3402             /* Recover by calling this a parameter pack.  */
3403             is_parameter_pack = true;
3404           }
3405       }
3406
3407       /* A template parameter is not modifiable.  */
3408       TREE_CONSTANT (parm) = 1;
3409       TREE_READONLY (parm) = 1;
3410       decl = build_decl (parm_loc,
3411                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3412       TREE_CONSTANT (decl) = 1;
3413       TREE_READONLY (decl) = 1;
3414       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3415         = build_template_parm_index (idx, processing_template_decl,
3416                                      processing_template_decl,
3417                                      decl, TREE_TYPE (parm));
3418
3419       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3420         = is_parameter_pack;
3421     }
3422   else
3423     {
3424       tree t;
3425       parm = TREE_VALUE (TREE_VALUE (parm));
3426
3427       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3428         {
3429           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3430           /* This is for distinguishing between real templates and template
3431              template parameters */
3432           TREE_TYPE (parm) = t;
3433           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3434           decl = parm;
3435         }
3436       else
3437         {
3438           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3439           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3440           decl = build_decl (parm_loc,
3441                              TYPE_DECL, parm, t);
3442         }
3443
3444       TYPE_NAME (t) = decl;
3445       TYPE_STUB_DECL (t) = decl;
3446       parm = decl;
3447       TEMPLATE_TYPE_PARM_INDEX (t)
3448         = build_template_parm_index (idx, processing_template_decl,
3449                                      processing_template_decl,
3450                                      decl, TREE_TYPE (parm));
3451       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3452       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3453     }
3454   DECL_ARTIFICIAL (decl) = 1;
3455   SET_DECL_TEMPLATE_PARM_P (decl);
3456   pushdecl (decl);
3457   parm = build_tree_list (defval, parm);
3458   return chainon (list, parm);
3459 }
3460
3461 /* The end of a template parameter list has been reached.  Process the
3462    tree list into a parameter vector, converting each parameter into a more
3463    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3464    as PARM_DECLs.  */
3465
3466 tree
3467 end_template_parm_list (tree parms)
3468 {
3469   int nparms;
3470   tree parm, next;
3471   tree saved_parmlist = make_tree_vec (list_length (parms));
3472
3473   current_template_parms
3474     = tree_cons (size_int (processing_template_decl),
3475                  saved_parmlist, current_template_parms);
3476
3477   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3478     {
3479       next = TREE_CHAIN (parm);
3480       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3481       TREE_CHAIN (parm) = NULL_TREE;
3482     }
3483
3484   --processing_template_parmlist;
3485
3486   return saved_parmlist;
3487 }
3488
3489 /* end_template_decl is called after a template declaration is seen.  */
3490
3491 void
3492 end_template_decl (void)
3493 {
3494   reset_specialization ();
3495
3496   if (! processing_template_decl)
3497     return;
3498
3499   /* This matches the pushlevel in begin_template_parm_list.  */
3500   finish_scope ();
3501
3502   --processing_template_decl;
3503   current_template_parms = TREE_CHAIN (current_template_parms);
3504 }
3505
3506 /* Within the declaration of a template, return all levels of template
3507    parameters that apply.  The template parameters are represented as
3508    a TREE_VEC, in the form documented in cp-tree.h for template
3509    arguments.  */
3510
3511 static tree
3512 current_template_args (void)
3513 {
3514   tree header;
3515   tree args = NULL_TREE;
3516   int length = TMPL_PARMS_DEPTH (current_template_parms);
3517   int l = length;
3518
3519   /* If there is only one level of template parameters, we do not
3520      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3521      TREE_VEC containing the arguments.  */
3522   if (length > 1)
3523     args = make_tree_vec (length);
3524
3525   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3526     {
3527       tree a = copy_node (TREE_VALUE (header));
3528       int i;
3529
3530       TREE_TYPE (a) = NULL_TREE;
3531       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3532         {
3533           tree t = TREE_VEC_ELT (a, i);
3534
3535           /* T will be a list if we are called from within a
3536              begin/end_template_parm_list pair, but a vector directly
3537              if within a begin/end_member_template_processing pair.  */
3538           if (TREE_CODE (t) == TREE_LIST)
3539             {
3540               t = TREE_VALUE (t);
3541
3542               if (!error_operand_p (t))
3543                 {
3544                   if (TREE_CODE (t) == TYPE_DECL
3545                       || TREE_CODE (t) == TEMPLATE_DECL)
3546                     {
3547                       t = TREE_TYPE (t);
3548                       
3549                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3550                         {
3551                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3552                              with a single element, which expands T.  */
3553                           tree vec = make_tree_vec (1);
3554                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3555                           
3556                           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3557                           SET_ARGUMENT_PACK_ARGS (t, vec);
3558                         }
3559                     }
3560                   else
3561                     {
3562                       t = DECL_INITIAL (t);
3563                       
3564                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3565                         {
3566                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3567                              with a single element, which expands T.  */
3568                           tree vec = make_tree_vec (1);
3569                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3570                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3571                           
3572                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3573                           SET_ARGUMENT_PACK_ARGS (t, vec);
3574                           TREE_TYPE (t) = type;
3575                         }
3576                     }
3577                   TREE_VEC_ELT (a, i) = t;
3578                 }
3579             }
3580         }
3581
3582       if (length > 1)
3583         TREE_VEC_ELT (args, --l) = a;
3584       else
3585         args = a;
3586     }
3587
3588   return args;
3589 }
3590
3591 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3592    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3593    a member template.  Used by push_template_decl below.  */
3594
3595 static tree
3596 build_template_decl (tree decl, tree parms, bool member_template_p)
3597 {
3598   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3599   DECL_TEMPLATE_PARMS (tmpl) = parms;
3600   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3601   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3602
3603   return tmpl;
3604 }
3605
3606 struct template_parm_data
3607 {
3608   /* The level of the template parameters we are currently
3609      processing.  */
3610   int level;
3611
3612   /* The index of the specialization argument we are currently
3613      processing.  */
3614   int current_arg;
3615
3616   /* An array whose size is the number of template parameters.  The
3617      elements are nonzero if the parameter has been used in any one
3618      of the arguments processed so far.  */
3619   int* parms;
3620
3621   /* An array whose size is the number of template arguments.  The
3622      elements are nonzero if the argument makes use of template
3623      parameters of this level.  */
3624   int* arg_uses_template_parms;
3625 };
3626
3627 /* Subroutine of push_template_decl used to see if each template
3628    parameter in a partial specialization is used in the explicit
3629    argument list.  If T is of the LEVEL given in DATA (which is
3630    treated as a template_parm_data*), then DATA->PARMS is marked
3631    appropriately.  */
3632
3633 static int
3634 mark_template_parm (tree t, void* data)
3635 {
3636   int level;
3637   int idx;
3638   struct template_parm_data* tpd = (struct template_parm_data*) data;
3639
3640   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3641     {
3642       level = TEMPLATE_PARM_LEVEL (t);
3643       idx = TEMPLATE_PARM_IDX (t);
3644     }
3645   else
3646     {
3647       level = TEMPLATE_TYPE_LEVEL (t);
3648       idx = TEMPLATE_TYPE_IDX (t);
3649     }
3650
3651   if (level == tpd->level)
3652     {
3653       tpd->parms[idx] = 1;
3654       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3655     }
3656
3657   /* Return zero so that for_each_template_parm will continue the
3658      traversal of the tree; we want to mark *every* template parm.  */
3659   return 0;
3660 }
3661
3662 /* Process the partial specialization DECL.  */
3663
3664 static tree
3665 process_partial_specialization (tree decl)
3666 {
3667   tree type = TREE_TYPE (decl);
3668   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3669   tree specargs = CLASSTYPE_TI_ARGS (type);
3670   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3671   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3672   tree inner_parms;
3673   int nargs = TREE_VEC_LENGTH (inner_args);
3674   int ntparms;
3675   int  i;
3676   int did_error_intro = 0;
3677   struct template_parm_data tpd;
3678   struct template_parm_data tpd2;
3679
3680   gcc_assert (current_template_parms);
3681
3682   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3683   ntparms = TREE_VEC_LENGTH (inner_parms);
3684
3685   /* We check that each of the template parameters given in the
3686      partial specialization is used in the argument list to the
3687      specialization.  For example:
3688
3689        template <class T> struct S;
3690        template <class T> struct S<T*>;
3691
3692      The second declaration is OK because `T*' uses the template
3693      parameter T, whereas
3694
3695        template <class T> struct S<int>;
3696
3697      is no good.  Even trickier is:
3698
3699        template <class T>
3700        struct S1
3701        {
3702           template <class U>
3703           struct S2;
3704           template <class U>
3705           struct S2<T>;
3706        };
3707
3708      The S2<T> declaration is actually invalid; it is a
3709      full-specialization.  Of course,
3710
3711           template <class U>
3712           struct S2<T (*)(U)>;
3713
3714      or some such would have been OK.  */
3715   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3716   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3717   memset (tpd.parms, 0, sizeof (int) * ntparms);
3718
3719   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3720   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3721   for (i = 0; i < nargs; ++i)
3722     {
3723       tpd.current_arg = i;
3724       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3725                               &mark_template_parm,
3726                               &tpd,
3727                               NULL,
3728                               /*include_nondeduced_p=*/false);
3729     }
3730   for (i = 0; i < ntparms; ++i)
3731     if (tpd.parms[i] == 0)
3732       {
3733         /* One of the template parms was not used in the
3734            specialization.  */
3735         if (!did_error_intro)
3736           {
3737             error ("template parameters not used in partial specialization:");
3738             did_error_intro = 1;
3739           }
3740
3741         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3742       }
3743
3744   /* [temp.class.spec]
3745
3746      The argument list of the specialization shall not be identical to
3747      the implicit argument list of the primary template.  */
3748   if (comp_template_args
3749       (inner_args,
3750        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3751                                                    (maintmpl)))))
3752     error ("partial specialization %qT does not specialize any template arguments", type);
3753
3754   /* [temp.class.spec]
3755
3756      A partially specialized non-type argument expression shall not
3757      involve template parameters of the partial specialization except
3758      when the argument expression is a simple identifier.
3759
3760      The type of a template parameter corresponding to a specialized
3761      non-type argument shall not be dependent on a parameter of the
3762      specialization. 
3763
3764      Also, we verify that pack expansions only occur at the
3765      end of the argument list.  */
3766   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3767   tpd2.parms = 0;
3768   for (i = 0; i < nargs; ++i)
3769     {
3770       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3771       tree arg = TREE_VEC_ELT (inner_args, i);
3772       tree packed_args = NULL_TREE;
3773       int j, len = 1;
3774
3775       if (ARGUMENT_PACK_P (arg))
3776         {
3777           /* Extract the arguments from the argument pack. We'll be
3778              iterating over these in the following loop.  */
3779           packed_args = ARGUMENT_PACK_ARGS (arg);
3780           len = TREE_VEC_LENGTH (packed_args);
3781         }
3782
3783       for (j = 0; j < len; j++)
3784         {
3785           if (packed_args)
3786             /* Get the Jth argument in the parameter pack.  */
3787             arg = TREE_VEC_ELT (packed_args, j);
3788
3789           if (PACK_EXPANSION_P (arg))
3790             {
3791               /* Pack expansions must come at the end of the
3792                  argument list.  */
3793               if ((packed_args && j < len - 1)
3794                   || (!packed_args && i < nargs - 1))
3795                 {
3796                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3797                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3798                   else
3799                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3800
3801                   if (packed_args)
3802                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3803                 }
3804             }
3805
3806           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3807             /* We only care about the pattern.  */
3808             arg = PACK_EXPANSION_PATTERN (arg);
3809
3810           if (/* These first two lines are the `non-type' bit.  */
3811               !TYPE_P (arg)
3812               && TREE_CODE (arg) != TEMPLATE_DECL
3813               /* This next line is the `argument expression is not just a
3814                  simple identifier' condition and also the `specialized
3815                  non-type argument' bit.  */
3816               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3817             {
3818               if ((!packed_args && tpd.arg_uses_template_parms[i])
3819                   || (packed_args && uses_template_parms (arg)))
3820                 error ("template argument %qE involves template parameter(s)",
3821                        arg);
3822               else 
3823                 {
3824                   /* Look at the corresponding template parameter,
3825                      marking which template parameters its type depends
3826                      upon.  */
3827                   tree type = TREE_TYPE (parm);
3828
3829                   if (!tpd2.parms)
3830                     {
3831                       /* We haven't yet initialized TPD2.  Do so now.  */
3832                       tpd2.arg_uses_template_parms 
3833                         = (int *) alloca (sizeof (int) * nargs);
3834                       /* The number of parameters here is the number in the
3835                          main template, which, as checked in the assertion
3836                          above, is NARGS.  */
3837                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3838                       tpd2.level = 
3839                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3840                     }
3841
3842                   /* Mark the template parameters.  But this time, we're
3843                      looking for the template parameters of the main
3844                      template, not in the specialization.  */
3845                   tpd2.current_arg = i;
3846                   tpd2.arg_uses_template_parms[i] = 0;
3847                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3848                   for_each_template_parm (type,
3849                                           &mark_template_parm,
3850                                           &tpd2,
3851                                           NULL,
3852                                           /*include_nondeduced_p=*/false);
3853
3854                   if (tpd2.arg_uses_template_parms [i])
3855                     {
3856                       /* The type depended on some template parameters.
3857                          If they are fully specialized in the
3858                          specialization, that's OK.  */
3859                       int j;
3860                       for (j = 0; j < nargs; ++j)
3861                         if (tpd2.parms[j] != 0
3862                             && tpd.arg_uses_template_parms [j])
3863                           {
3864                             error ("type %qT of template argument %qE depends "
3865                                    "on template parameter(s)", 
3866                                    type,
3867                                    arg);
3868                             break;
3869                           }
3870                     }
3871                 }
3872             }
3873         }
3874     }
3875
3876   /* We should only get here once.  */
3877   gcc_assert (!COMPLETE_TYPE_P (type));
3878
3879   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3880     = tree_cons (specargs, inner_parms,
3881                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3882   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3883   return decl;
3884 }
3885
3886 /* Check that a template declaration's use of default arguments and
3887    parameter packs is not invalid.  Here, PARMS are the template
3888    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3889    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3890    specialization.
3891    
3892
3893    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3894    declaration (but not a definition); 1 indicates a declaration, 2
3895    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3896    emitted for extraneous default arguments.
3897
3898    Returns TRUE if there were no errors found, FALSE otherwise. */
3899
3900 bool
3901 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3902                          int is_partial, int is_friend_decl)
3903 {
3904   const char *msg;
3905   int last_level_to_check;
3906   tree parm_level;
3907   bool no_errors = true;
3908
3909   /* [temp.param]
3910
3911      A default template-argument shall not be specified in a
3912      function template declaration or a function template definition, nor
3913      in the template-parameter-list of the definition of a member of a
3914      class template.  */
3915
3916   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3917     /* You can't have a function template declaration in a local
3918        scope, nor you can you define a member of a class template in a
3919        local scope.  */
3920     return true;
3921
3922   if (current_class_type
3923       && !TYPE_BEING_DEFINED (current_class_type)
3924       && DECL_LANG_SPECIFIC (decl)
3925       && DECL_DECLARES_FUNCTION_P (decl)
3926       /* If this is either a friend defined in the scope of the class
3927          or a member function.  */
3928       && (DECL_FUNCTION_MEMBER_P (decl)
3929           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3930           : DECL_FRIEND_CONTEXT (decl)
3931           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3932           : false)
3933       /* And, if it was a member function, it really was defined in
3934          the scope of the class.  */
3935       && (!DECL_FUNCTION_MEMBER_P (decl)
3936           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3937     /* We already checked these parameters when the template was
3938        declared, so there's no need to do it again now.  This function
3939        was defined in class scope, but we're processing it's body now
3940        that the class is complete.  */
3941     return true;
3942
3943   /* Core issue 226 (C++0x only): the following only applies to class
3944      templates.  */
3945   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3946     {
3947       /* [temp.param]
3948
3949          If a template-parameter has a default template-argument, all
3950          subsequent template-parameters shall have a default
3951          template-argument supplied.  */
3952       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3953         {
3954           tree inner_parms = TREE_VALUE (parm_level);
3955           int ntparms = TREE_VEC_LENGTH (inner_parms);
3956           int seen_def_arg_p = 0;
3957           int i;
3958
3959           for (i = 0; i < ntparms; ++i)
3960             {
3961               tree parm = TREE_VEC_ELT (inner_parms, i);
3962
3963               if (parm == error_mark_node)
3964                 continue;
3965
3966               if (TREE_PURPOSE (parm))
3967                 seen_def_arg_p = 1;
3968               else if (seen_def_arg_p
3969                        && !template_parameter_pack_p (TREE_VALUE (parm)))
3970                 {
3971                   error ("no default argument for %qD", TREE_VALUE (parm));
3972                   /* For better subsequent error-recovery, we indicate that
3973                      there should have been a default argument.  */
3974                   TREE_PURPOSE (parm) = error_mark_node;
3975                   no_errors = false;
3976                 }
3977               else if (is_primary
3978                        && !is_partial
3979                        && !is_friend_decl
3980                        /* Don't complain about an enclosing partial
3981                           specialization.  */
3982                        && parm_level == parms
3983                        && TREE_CODE (decl) == TYPE_DECL
3984                        && i < ntparms - 1
3985                        && template_parameter_pack_p (TREE_VALUE (parm)))
3986                 {
3987                   /* A primary class template can only have one
3988                      parameter pack, at the end of the template
3989                      parameter list.  */
3990
3991                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
3992                     error ("parameter pack %qE must be at the end of the"
3993                            " template parameter list", TREE_VALUE (parm));
3994                   else
3995                     error ("parameter pack %qT must be at the end of the"
3996                            " template parameter list", 
3997                            TREE_TYPE (TREE_VALUE (parm)));
3998
3999                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4000                     = error_mark_node;
4001                   no_errors = false;
4002                 }
4003             }
4004         }
4005     }
4006
4007   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4008       || is_partial 
4009       || !is_primary
4010       || is_friend_decl)
4011     /* For an ordinary class template, default template arguments are
4012        allowed at the innermost level, e.g.:
4013          template <class T = int>
4014          struct S {};
4015        but, in a partial specialization, they're not allowed even
4016        there, as we have in [temp.class.spec]:
4017
4018          The template parameter list of a specialization shall not
4019          contain default template argument values.
4020
4021        So, for a partial specialization, or for a function template
4022        (in C++98/C++03), we look at all of them.  */
4023     ;
4024   else
4025     /* But, for a primary class template that is not a partial
4026        specialization we look at all template parameters except the
4027        innermost ones.  */
4028     parms = TREE_CHAIN (parms);
4029
4030   /* Figure out what error message to issue.  */
4031   if (is_friend_decl == 2)
4032     msg = "default template arguments may not be used in function template friend re-declaration";
4033   else if (is_friend_decl)
4034     msg = "default template arguments may not be used in function template friend declarations";
4035   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4036     msg = ("default template arguments may not be used in function templates "
4037            "without -std=c++0x or -std=gnu++0x");
4038   else if (is_partial)
4039     msg = "default template arguments may not be used in partial specializations";
4040   else
4041     msg = "default argument for template parameter for class enclosing %qD";
4042
4043   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4044     /* If we're inside a class definition, there's no need to
4045        examine the parameters to the class itself.  On the one
4046        hand, they will be checked when the class is defined, and,
4047        on the other, default arguments are valid in things like:
4048          template <class T = double>
4049          struct S { template <class U> void f(U); };
4050        Here the default argument for `S' has no bearing on the
4051        declaration of `f'.  */
4052     last_level_to_check = template_class_depth (current_class_type) + 1;
4053   else
4054     /* Check everything.  */
4055     last_level_to_check = 0;
4056
4057   for (parm_level = parms;
4058        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4059        parm_level = TREE_CHAIN (parm_level))
4060     {
4061       tree inner_parms = TREE_VALUE (parm_level);
4062       int i;
4063       int ntparms;
4064
4065       ntparms = TREE_VEC_LENGTH (inner_parms);
4066       for (i = 0; i < ntparms; ++i)
4067         {
4068           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4069             continue;
4070
4071           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4072             {
4073               if (msg)
4074                 {
4075                   no_errors = false;
4076                   if (is_friend_decl == 2)
4077                     return no_errors;
4078
4079                   error (msg, decl);
4080                   msg = 0;
4081                 }
4082
4083               /* Clear out the default argument so that we are not
4084                  confused later.  */
4085               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4086             }
4087         }
4088
4089       /* At this point, if we're still interested in issuing messages,
4090          they must apply to classes surrounding the object declared.  */
4091       if (msg)
4092         msg = "default argument for template parameter for class enclosing %qD";
4093     }
4094
4095   return no_errors;
4096 }
4097
4098 /* Worker for push_template_decl_real, called via
4099    for_each_template_parm.  DATA is really an int, indicating the
4100    level of the parameters we are interested in.  If T is a template
4101    parameter of that level, return nonzero.  */
4102
4103 static int
4104 template_parm_this_level_p (tree t, void* data)
4105 {
4106   int this_level = *(int *)data;
4107   int level;
4108
4109   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4110     level = TEMPLATE_PARM_LEVEL (t);
4111   else
4112     level = TEMPLATE_TYPE_LEVEL (t);
4113   return level == this_level;
4114 }
4115
4116 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4117    parameters given by current_template_args, or reuses a
4118    previously existing one, if appropriate.  Returns the DECL, or an
4119    equivalent one, if it is replaced via a call to duplicate_decls.
4120
4121    If IS_FRIEND is true, DECL is a friend declaration.  */
4122
4123 tree
4124 push_template_decl_real (tree decl, bool is_friend)
4125 {
4126   tree tmpl;
4127   tree args;
4128   tree info;
4129   tree ctx;
4130   int primary;
4131   int is_partial;
4132   int new_template_p = 0;
4133   /* True if the template is a member template, in the sense of
4134      [temp.mem].  */
4135   bool member_template_p = false;
4136
4137   if (decl == error_mark_node || !current_template_parms)
4138     return error_mark_node;
4139
4140   /* See if this is a partial specialization.  */
4141   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4142                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4143                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4144
4145   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4146     is_friend = true;
4147
4148   if (is_friend)
4149     /* For a friend, we want the context of the friend function, not
4150        the type of which it is a friend.  */
4151     ctx = DECL_CONTEXT (decl);
4152   else if (CP_DECL_CONTEXT (decl)
4153            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4154     /* In the case of a virtual function, we want the class in which
4155        it is defined.  */
4156     ctx = CP_DECL_CONTEXT (decl);
4157   else
4158     /* Otherwise, if we're currently defining some class, the DECL
4159        is assumed to be a member of the class.  */
4160     ctx = current_scope ();
4161
4162   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4163     ctx = NULL_TREE;
4164
4165   if (!DECL_CONTEXT (decl))
4166     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4167
4168   /* See if this is a primary template.  */
4169   if (is_friend && ctx)
4170     /* A friend template that specifies a class context, i.e.
4171          template <typename T> friend void A<T>::f();
4172        is not primary.  */
4173     primary = 0;
4174   else
4175     primary = template_parm_scope_p ();
4176
4177   if (primary)
4178     {
4179       if (DECL_CLASS_SCOPE_P (decl))
4180         member_template_p = true;
4181       if (TREE_CODE (decl) == TYPE_DECL
4182           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4183         {
4184           error ("template class without a name");
4185           return error_mark_node;
4186         }
4187       else if (TREE_CODE (decl) == FUNCTION_DECL)
4188         {
4189           if (DECL_DESTRUCTOR_P (decl))
4190             {
4191               /* [temp.mem]
4192
4193                  A destructor shall not be a member template.  */
4194               error ("destructor %qD declared as member template", decl);
4195               return error_mark_node;
4196             }
4197           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4198               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4199                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4200                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4201                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4202                       == void_list_node)))
4203             {
4204               /* [basic.stc.dynamic.allocation]
4205
4206                  An allocation function can be a function
4207                  template. ... Template allocation functions shall
4208                  have two or more parameters.  */
4209               error ("invalid template declaration of %qD", decl);
4210               return error_mark_node;
4211             }
4212         }
4213       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4214                && CLASS_TYPE_P (TREE_TYPE (decl)))
4215         /* OK */;
4216       else
4217         {
4218           error ("template declaration of %q#D", decl);
4219           return error_mark_node;
4220         }
4221     }
4222
4223   /* Check to see that the rules regarding the use of default
4224      arguments are not being violated.  */
4225   check_default_tmpl_args (decl, current_template_parms,
4226                            primary, is_partial, /*is_friend_decl=*/0);
4227
4228   /* Ensure that there are no parameter packs in the type of this
4229      declaration that have not been expanded.  */
4230   if (TREE_CODE (decl) == FUNCTION_DECL)
4231     {
4232       /* Check each of the arguments individually to see if there are
4233          any bare parameter packs.  */
4234       tree type = TREE_TYPE (decl);
4235       tree arg = DECL_ARGUMENTS (decl);
4236       tree argtype = TYPE_ARG_TYPES (type);
4237
4238       while (arg && argtype)
4239         {
4240           if (!FUNCTION_PARAMETER_PACK_P (arg)
4241               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4242             {
4243             /* This is a PARM_DECL that contains unexpanded parameter
4244                packs. We have already complained about this in the
4245                check_for_bare_parameter_packs call, so just replace
4246                these types with ERROR_MARK_NODE.  */
4247               TREE_TYPE (arg) = error_mark_node;
4248               TREE_VALUE (argtype) = error_mark_node;
4249             }
4250
4251           arg = TREE_CHAIN (arg);
4252           argtype = TREE_CHAIN (argtype);
4253         }
4254
4255       /* Check for bare parameter packs in the return type and the
4256          exception specifiers.  */
4257       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4258         /* Errors were already issued, set return type to int
4259            as the frontend doesn't expect error_mark_node as
4260            the return type.  */
4261         TREE_TYPE (type) = integer_type_node;
4262       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4263         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4264     }
4265   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4266     {
4267       TREE_TYPE (decl) = error_mark_node;
4268       return error_mark_node;
4269     }
4270
4271   if (is_partial)
4272     return process_partial_specialization (decl);
4273
4274   args = current_template_args ();
4275
4276   if (!ctx
4277       || TREE_CODE (ctx) == FUNCTION_DECL
4278       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4279       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4280     {
4281       if (DECL_LANG_SPECIFIC (decl)
4282           && DECL_TEMPLATE_INFO (decl)
4283           && DECL_TI_TEMPLATE (decl))
4284         tmpl = DECL_TI_TEMPLATE (decl);
4285       /* If DECL is a TYPE_DECL for a class-template, then there won't
4286          be DECL_LANG_SPECIFIC.  The information equivalent to
4287          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4288       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4289                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4290                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4291         {
4292           /* Since a template declaration already existed for this
4293              class-type, we must be redeclaring it here.  Make sure
4294              that the redeclaration is valid.  */
4295           redeclare_class_template (TREE_TYPE (decl),
4296                                     current_template_parms);
4297           /* We don't need to create a new TEMPLATE_DECL; just use the
4298              one we already had.  */
4299           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4300         }
4301       else
4302         {
4303           tmpl = build_template_decl (decl, current_template_parms,
4304                                       member_template_p);
4305           new_template_p = 1;
4306
4307           if (DECL_LANG_SPECIFIC (decl)
4308               && DECL_TEMPLATE_SPECIALIZATION (decl))
4309             {
4310               /* A specialization of a member template of a template
4311                  class.  */
4312               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4313               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4314               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4315             }
4316         }
4317     }
4318   else
4319     {
4320       tree a, t, current, parms;
4321       int i;
4322       tree tinfo = get_template_info (decl);
4323
4324       if (!tinfo)
4325         {
4326           error ("template definition of non-template %q#D", decl);
4327           return error_mark_node;
4328         }
4329
4330       tmpl = TI_TEMPLATE (tinfo);
4331
4332       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4333           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4334           && DECL_TEMPLATE_SPECIALIZATION (decl)
4335           && DECL_MEMBER_TEMPLATE_P (tmpl))
4336         {
4337           tree new_tmpl;
4338
4339           /* The declaration is a specialization of a member
4340              template, declared outside the class.  Therefore, the
4341              innermost template arguments will be NULL, so we
4342              replace them with the arguments determined by the
4343              earlier call to check_explicit_specialization.  */
4344           args = DECL_TI_ARGS (decl);
4345
4346           new_tmpl
4347             = build_template_decl (decl, current_template_parms,
4348                                    member_template_p);
4349           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4350           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4351           DECL_TI_TEMPLATE (decl) = new_tmpl;
4352           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4353           DECL_TEMPLATE_INFO (new_tmpl)
4354             = tree_cons (tmpl, args, NULL_TREE);
4355
4356           register_specialization (new_tmpl,
4357                                    most_general_template (tmpl),
4358                                    args,
4359                                    is_friend, 0);
4360           return decl;
4361         }
4362
4363       /* Make sure the template headers we got make sense.  */
4364
4365       parms = DECL_TEMPLATE_PARMS (tmpl);
4366       i = TMPL_PARMS_DEPTH (parms);
4367       if (TMPL_ARGS_DEPTH (args) != i)
4368         {
4369           error ("expected %d levels of template parms for %q#D, got %d",
4370                  i, decl, TMPL_ARGS_DEPTH (args));
4371         }
4372       else
4373         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4374           {
4375             a = TMPL_ARGS_LEVEL (args, i);
4376             t = INNERMOST_TEMPLATE_PARMS (parms);
4377
4378             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4379               {
4380                 if (current == decl)
4381                   error ("got %d template parameters for %q#D",
4382                          TREE_VEC_LENGTH (a), decl);
4383                 else
4384                   error ("got %d template parameters for %q#T",
4385                          TREE_VEC_LENGTH (a), current);
4386                 error ("  but %d required", TREE_VEC_LENGTH (t));
4387                 return error_mark_node;
4388               }
4389
4390             if (current == decl)
4391               current = ctx;
4392             else
4393               current = (TYPE_P (current)
4394                          ? TYPE_CONTEXT (current)
4395                          : DECL_CONTEXT (current));
4396           }
4397
4398       /* Check that the parms are used in the appropriate qualifying scopes
4399          in the declarator.  */
4400       if (!comp_template_args
4401           (TI_ARGS (tinfo),
4402            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4403         {
4404           error ("\
4405 template arguments to %qD do not match original template %qD",
4406                  decl, DECL_TEMPLATE_RESULT (tmpl));
4407           if (!uses_template_parms (TI_ARGS (tinfo)))
4408             inform (input_location, "use template<> for an explicit specialization");
4409           /* Avoid crash in import_export_decl.  */
4410           DECL_INTERFACE_KNOWN (decl) = 1;
4411           return error_mark_node;
4412         }
4413     }
4414
4415   DECL_TEMPLATE_RESULT (tmpl) = decl;
4416   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4417
4418   /* Push template declarations for global functions and types.  Note
4419      that we do not try to push a global template friend declared in a
4420      template class; such a thing may well depend on the template
4421      parameters of the class.  */
4422   if (new_template_p && !ctx
4423       && !(is_friend && template_class_depth (current_class_type) > 0))
4424     {
4425       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4426       if (tmpl == error_mark_node)
4427         return error_mark_node;
4428
4429       /* Hide template friend classes that haven't been declared yet.  */
4430       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4431         {
4432           DECL_ANTICIPATED (tmpl) = 1;
4433           DECL_FRIEND_P (tmpl) = 1;
4434         }
4435     }
4436
4437   if (primary)
4438     {
4439       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4440       int i;
4441
4442       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4443       if (DECL_CONV_FN_P (tmpl))
4444         {
4445           int depth = TMPL_PARMS_DEPTH (parms);
4446
4447           /* It is a conversion operator. See if the type converted to
4448              depends on innermost template operands.  */
4449
4450           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4451                                          depth))
4452             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4453         }
4454
4455       /* Give template template parms a DECL_CONTEXT of the template
4456          for which they are a parameter.  */
4457       parms = INNERMOST_TEMPLATE_PARMS (parms);
4458       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4459         {
4460           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4461           if (TREE_CODE (parm) == TEMPLATE_DECL)
4462             DECL_CONTEXT (parm) = tmpl;
4463         }
4464     }
4465
4466   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4467      back to its most general template.  If TMPL is a specialization,
4468      ARGS may only have the innermost set of arguments.  Add the missing
4469      argument levels if necessary.  */
4470   if (DECL_TEMPLATE_INFO (tmpl))
4471     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4472
4473   info = tree_cons (tmpl, args, NULL_TREE);
4474
4475   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4476     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4477   else if (DECL_LANG_SPECIFIC (decl))
4478     DECL_TEMPLATE_INFO (decl) = info;
4479
4480   return DECL_TEMPLATE_RESULT (tmpl);
4481 }
4482
4483 tree
4484 push_template_decl (tree decl)
4485 {
4486   return push_template_decl_real (decl, false);
4487 }
4488
4489 /* Called when a class template TYPE is redeclared with the indicated
4490    template PARMS, e.g.:
4491
4492      template <class T> struct S;
4493      template <class T> struct S {};  */
4494
4495 bool
4496 redeclare_class_template (tree type, tree parms)
4497 {
4498   tree tmpl;
4499   tree tmpl_parms;
4500   int i;
4501
4502   if (!TYPE_TEMPLATE_INFO (type))
4503     {
4504       error ("%qT is not a template type", type);
4505       return false;
4506     }
4507
4508   tmpl = TYPE_TI_TEMPLATE (type);
4509   if (!PRIMARY_TEMPLATE_P (tmpl))
4510     /* The type is nested in some template class.  Nothing to worry
4511        about here; there are no new template parameters for the nested
4512        type.  */
4513     return true;
4514
4515   if (!parms)
4516     {
4517       error ("template specifiers not specified in declaration of %qD",
4518              tmpl);
4519       return false;
4520     }
4521
4522   parms = INNERMOST_TEMPLATE_PARMS (parms);
4523   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4524
4525   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4526     {
4527       error ("redeclared with %d template parameter(s)", 
4528              TREE_VEC_LENGTH (parms));
4529       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4530              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4531       return false;
4532     }
4533
4534   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4535     {
4536       tree tmpl_parm;
4537       tree parm;
4538       tree tmpl_default;
4539       tree parm_default;
4540
4541       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4542           || TREE_VEC_ELT (parms, i) == error_mark_node)
4543         continue;
4544
4545       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4546       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4547       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4548       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4549
4550       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4551          TEMPLATE_DECL.  */
4552       if (tmpl_parm != error_mark_node
4553           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4554               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4555                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4556               || (TREE_CODE (tmpl_parm) != PARM_DECL
4557                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4558                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4559               || (TREE_CODE (tmpl_parm) == PARM_DECL
4560                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4561                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4562         {
4563           error ("template parameter %q+#D", tmpl_parm);
4564           error ("redeclared here as %q#D", parm);
4565           return false;
4566         }
4567
4568       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4569         {
4570           /* We have in [temp.param]:
4571
4572              A template-parameter may not be given default arguments
4573              by two different declarations in the same scope.  */
4574           error_at (input_location, "redefinition of default argument for %q#D", parm);
4575           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4576                   "original definition appeared here");
4577           return false;
4578         }
4579
4580       if (parm_default != NULL_TREE)
4581         /* Update the previous template parameters (which are the ones
4582            that will really count) with the new default value.  */
4583         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4584       else if (tmpl_default != NULL_TREE)
4585         /* Update the new parameters, too; they'll be used as the
4586            parameters for any members.  */
4587         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4588     }
4589
4590     return true;
4591 }
4592
4593 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4594    (possibly simplified) expression.  */
4595
4596 tree
4597 fold_non_dependent_expr (tree expr)
4598 {
4599   if (expr == NULL_TREE)
4600     return NULL_TREE;
4601
4602   /* If we're in a template, but EXPR isn't value dependent, simplify
4603      it.  We're supposed to treat:
4604
4605        template <typename T> void f(T[1 + 1]);
4606        template <typename T> void f(T[2]);
4607
4608      as two declarations of the same function, for example.  */
4609   if (processing_template_decl
4610       && !type_dependent_expression_p (expr)
4611       && !value_dependent_expression_p (expr))
4612     {
4613       HOST_WIDE_INT saved_processing_template_decl;
4614
4615       saved_processing_template_decl = processing_template_decl;
4616       processing_template_decl = 0;
4617       expr = tsubst_copy_and_build (expr,
4618                                     /*args=*/NULL_TREE,
4619                                     tf_error,
4620                                     /*in_decl=*/NULL_TREE,
4621                                     /*function_p=*/false,
4622                                     /*integral_constant_expression_p=*/true);
4623       processing_template_decl = saved_processing_template_decl;
4624     }
4625   return expr;
4626 }
4627
4628 /* EXPR is an expression which is used in a constant-expression context.
4629    For instance, it could be a VAR_DECL with a constant initializer.
4630    Extract the innermost constant expression.
4631
4632    This is basically a more powerful version of
4633    integral_constant_value, which can be used also in templates where
4634    initializers can maintain a syntactic rather than semantic form
4635    (even if they are non-dependent, for access-checking purposes).  */
4636
4637 static tree
4638 fold_decl_constant_value (tree expr)
4639 {
4640   tree const_expr = expr;
4641   do
4642     {
4643       expr = fold_non_dependent_expr (const_expr);
4644       const_expr = integral_constant_value (expr);
4645     }
4646   while (expr != const_expr);
4647
4648   return expr;
4649 }
4650
4651 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4652    must be a function or a pointer-to-function type, as specified
4653    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4654    and check that the resulting function has external linkage.  */
4655
4656 static tree
4657 convert_nontype_argument_function (tree type, tree expr)
4658 {
4659   tree fns = expr;
4660   tree fn, fn_no_ptr;
4661
4662   fn = instantiate_type (type, fns, tf_none);
4663   if (fn == error_mark_node)
4664     return error_mark_node;
4665
4666   fn_no_ptr = fn;
4667   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4668     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4669   if (TREE_CODE (fn_no_ptr) == BASELINK)
4670     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4671  
4672   /* [temp.arg.nontype]/1
4673
4674      A template-argument for a non-type, non-template template-parameter
4675      shall be one of:
4676      [...]
4677      -- the address of an object or function with external linkage.  */
4678   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4679     {
4680       error ("%qE is not a valid template argument for type %qT "
4681              "because function %qD has not external linkage",
4682              expr, type, fn_no_ptr);
4683       return NULL_TREE;
4684     }
4685
4686   return fn;
4687 }
4688
4689 /* Subroutine of convert_nontype_argument.
4690    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4691    Emit an error otherwise.  */
4692
4693 static bool
4694 check_valid_ptrmem_cst_expr (tree type, tree expr)
4695 {
4696   STRIP_NOPS (expr);
4697   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4698     return true;
4699   error ("%qE is not a valid template argument for type %qT",
4700          expr, type);
4701   error ("it must be a pointer-to-member of the form `&X::Y'");
4702   return false;
4703 }
4704
4705 /* Attempt to convert the non-type template parameter EXPR to the
4706    indicated TYPE.  If the conversion is successful, return the
4707    converted value.  If the conversion is unsuccessful, return
4708    NULL_TREE if we issued an error message, or error_mark_node if we
4709    did not.  We issue error messages for out-and-out bad template
4710    parameters, but not simply because the conversion failed, since we
4711    might be just trying to do argument deduction.  Both TYPE and EXPR
4712    must be non-dependent.
4713
4714    The conversion follows the special rules described in
4715    [temp.arg.nontype], and it is much more strict than an implicit
4716    conversion.
4717
4718    This function is called twice for each template argument (see
4719    lookup_template_class for a more accurate description of this
4720    problem). This means that we need to handle expressions which
4721    are not valid in a C++ source, but can be created from the
4722    first call (for instance, casts to perform conversions). These
4723    hacks can go away after we fix the double coercion problem.  */
4724
4725 static tree
4726 convert_nontype_argument (tree type, tree expr)
4727 {
4728   tree expr_type;
4729
4730   /* Detect immediately string literals as invalid non-type argument.
4731      This special-case is not needed for correctness (we would easily
4732      catch this later), but only to provide better diagnostic for this
4733      common user mistake. As suggested by DR 100, we do not mention
4734      linkage issues in the diagnostic as this is not the point.  */
4735   if (TREE_CODE (expr) == STRING_CST)
4736     {
4737       error ("%qE is not a valid template argument for type %qT "
4738              "because string literals can never be used in this context",
4739              expr, type);
4740       return NULL_TREE;
4741     }
4742
4743   /* If we are in a template, EXPR may be non-dependent, but still
4744      have a syntactic, rather than semantic, form.  For example, EXPR
4745      might be a SCOPE_REF, rather than the VAR_DECL to which the
4746      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4747      so that access checking can be performed when the template is
4748      instantiated -- but here we need the resolved form so that we can
4749      convert the argument.  */
4750   expr = fold_non_dependent_expr (expr);
4751   if (error_operand_p (expr))
4752     return error_mark_node;
4753   expr_type = TREE_TYPE (expr);
4754
4755   /* HACK: Due to double coercion, we can get a
4756      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4757      which is the tree that we built on the first call (see
4758      below when coercing to reference to object or to reference to
4759      function). We just strip everything and get to the arg.
4760      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4761      for examples.  */
4762   if (TREE_CODE (expr) == NOP_EXPR)
4763     {
4764       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4765         {
4766           /* ??? Maybe we could use convert_from_reference here, but we
4767              would need to relax its constraints because the NOP_EXPR
4768              could actually change the type to something more cv-qualified,
4769              and this is not folded by convert_from_reference.  */
4770           tree addr = TREE_OPERAND (expr, 0);
4771           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4772           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4773           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4774           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4775                       (TREE_TYPE (expr_type),
4776                        TREE_TYPE (TREE_TYPE (addr))));
4777
4778           expr = TREE_OPERAND (addr, 0);
4779           expr_type = TREE_TYPE (expr);
4780         }
4781
4782       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4783          parameter is a pointer to object, through decay and
4784          qualification conversion. Let's strip everything.  */
4785       else if (TYPE_PTROBV_P (type))
4786         {
4787           STRIP_NOPS (expr);
4788           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4789           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4790           /* Skip the ADDR_EXPR only if it is part of the decay for
4791              an array. Otherwise, it is part of the original argument
4792              in the source code.  */
4793           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4794             expr = TREE_OPERAND (expr, 0);
4795           expr_type = TREE_TYPE (expr);
4796         }
4797     }
4798
4799   /* [temp.arg.nontype]/5, bullet 1
4800
4801      For a non-type template-parameter of integral or enumeration type,
4802      integral promotions (_conv.prom_) and integral conversions
4803      (_conv.integral_) are applied.  */
4804   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4805     {
4806       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4807         return error_mark_node;
4808
4809       expr = fold_decl_constant_value (expr);
4810       /* Notice that there are constant expressions like '4 % 0' which
4811          do not fold into integer constants.  */
4812       if (TREE_CODE (expr) != INTEGER_CST)
4813         {
4814           error ("%qE is not a valid template argument for type %qT "
4815                  "because it is a non-constant expression", expr, type);
4816           return NULL_TREE;
4817         }
4818
4819       /* At this point, an implicit conversion does what we want,
4820          because we already know that the expression is of integral
4821          type.  */
4822       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4823       if (expr == error_mark_node)
4824         return error_mark_node;
4825
4826       /* Conversion was allowed: fold it to a bare integer constant.  */
4827       expr = fold (expr);
4828     }
4829   /* [temp.arg.nontype]/5, bullet 2
4830
4831      For a non-type template-parameter of type pointer to object,
4832      qualification conversions (_conv.qual_) and the array-to-pointer
4833      conversion (_conv.array_) are applied.  */
4834   else if (TYPE_PTROBV_P (type))
4835     {
4836       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4837
4838          A template-argument for a non-type, non-template template-parameter
4839          shall be one of: [...]
4840
4841          -- the name of a non-type template-parameter;
4842          -- the address of an object or function with external linkage, [...]
4843             expressed as "& id-expression" where the & is optional if the name
4844             refers to a function or array, or if the corresponding
4845             template-parameter is a reference.
4846
4847         Here, we do not care about functions, as they are invalid anyway
4848         for a parameter of type pointer-to-object.  */
4849
4850       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4851         /* Non-type template parameters are OK.  */
4852         ;
4853       else if (TREE_CODE (expr) != ADDR_EXPR
4854                && TREE_CODE (expr_type) != ARRAY_TYPE)
4855         {
4856           if (TREE_CODE (expr) == VAR_DECL)
4857             {
4858               error ("%qD is not a valid template argument "
4859                      "because %qD is a variable, not the address of "
4860                      "a variable",
4861                      expr, expr);
4862               return NULL_TREE;
4863             }
4864           /* Other values, like integer constants, might be valid
4865              non-type arguments of some other type.  */
4866           return error_mark_node;
4867         }
4868       else
4869         {
4870           tree decl;
4871
4872           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4873                   ? TREE_OPERAND (expr, 0) : expr);
4874           if (TREE_CODE (decl) != VAR_DECL)
4875             {
4876               error ("%qE is not a valid template argument of type %qT "
4877                      "because %qE is not a variable",
4878                      expr, type, decl);
4879               return NULL_TREE;
4880             }
4881           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4882             {
4883               error ("%qE is not a valid template argument of type %qT "
4884                      "because %qD does not have external linkage",
4885                      expr, type, decl);
4886               return NULL_TREE;
4887             }
4888         }
4889
4890       expr = decay_conversion (expr);
4891       if (expr == error_mark_node)
4892         return error_mark_node;
4893
4894       expr = perform_qualification_conversions (type, expr);
4895       if (expr == error_mark_node)
4896         return error_mark_node;
4897     }
4898   /* [temp.arg.nontype]/5, bullet 3
4899
4900      For a non-type template-parameter of type reference to object, no
4901      conversions apply. The type referred to by the reference may be more
4902      cv-qualified than the (otherwise identical) type of the
4903      template-argument. The template-parameter is bound directly to the
4904      template-argument, which must be an lvalue.  */
4905   else if (TYPE_REF_OBJ_P (type))
4906     {
4907       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4908                                                       expr_type))
4909         return error_mark_node;
4910
4911       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4912         {
4913           error ("%qE is not a valid template argument for type %qT "
4914                  "because of conflicts in cv-qualification", expr, type);
4915           return NULL_TREE;
4916         }
4917
4918       if (!real_lvalue_p (expr))
4919         {
4920           error ("%qE is not a valid template argument for type %qT "
4921                  "because it is not an lvalue", expr, type);
4922           return NULL_TREE;
4923         }
4924
4925       /* [temp.arg.nontype]/1
4926
4927          A template-argument for a non-type, non-template template-parameter
4928          shall be one of: [...]
4929
4930          -- the address of an object or function with external linkage.  */
4931       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4932         {
4933           error ("%qE is not a valid template argument for type %qT "
4934                  "because object %qD has not external linkage",
4935                  expr, type, expr);
4936           return NULL_TREE;
4937         }
4938
4939       expr = build_nop (type, build_address (expr));
4940     }
4941   /* [temp.arg.nontype]/5, bullet 4
4942
4943      For a non-type template-parameter of type pointer to function, only
4944      the function-to-pointer conversion (_conv.func_) is applied. If the
4945      template-argument represents a set of overloaded functions (or a
4946      pointer to such), the matching function is selected from the set
4947      (_over.over_).  */
4948   else if (TYPE_PTRFN_P (type))
4949     {
4950       /* If the argument is a template-id, we might not have enough
4951          context information to decay the pointer.  */
4952       if (!type_unknown_p (expr_type))
4953         {
4954           expr = decay_conversion (expr);
4955           if (expr == error_mark_node)
4956             return error_mark_node;
4957         }
4958
4959       expr = convert_nontype_argument_function (type, expr);
4960       if (!expr || expr == error_mark_node)
4961         return expr;
4962
4963       if (TREE_CODE (expr) != ADDR_EXPR)
4964         {
4965           error ("%qE is not a valid template argument for type %qT", expr, type);
4966           error ("it must be the address of a function with external linkage");
4967           return NULL_TREE;
4968         }
4969     }
4970   /* [temp.arg.nontype]/5, bullet 5
4971
4972      For a non-type template-parameter of type reference to function, no
4973      conversions apply. If the template-argument represents a set of
4974      overloaded functions, the matching function is selected from the set
4975      (_over.over_).  */
4976   else if (TYPE_REFFN_P (type))
4977     {
4978       if (TREE_CODE (expr) == ADDR_EXPR)
4979         {
4980           error ("%qE is not a valid template argument for type %qT "
4981                  "because it is a pointer", expr, type);
4982           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
4983           return NULL_TREE;
4984         }
4985
4986       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4987       if (!expr || expr == error_mark_node)
4988         return expr;
4989
4990       expr = build_nop (type, build_address (expr));
4991     }
4992   /* [temp.arg.nontype]/5, bullet 6
4993
4994      For a non-type template-parameter of type pointer to member function,
4995      no conversions apply. If the template-argument represents a set of
4996      overloaded member functions, the matching member function is selected
4997      from the set (_over.over_).  */
4998   else if (TYPE_PTRMEMFUNC_P (type))
4999     {
5000       expr = instantiate_type (type, expr, tf_none);
5001       if (expr == error_mark_node)
5002         return error_mark_node;
5003
5004       /* [temp.arg.nontype] bullet 1 says the pointer to member
5005          expression must be a pointer-to-member constant.  */
5006       if (!check_valid_ptrmem_cst_expr (type, expr))
5007         return error_mark_node;
5008
5009       /* There is no way to disable standard conversions in
5010          resolve_address_of_overloaded_function (called by
5011          instantiate_type). It is possible that the call succeeded by
5012          converting &B::I to &D::I (where B is a base of D), so we need
5013          to reject this conversion here.
5014
5015          Actually, even if there was a way to disable standard conversions,
5016          it would still be better to reject them here so that we can
5017          provide a superior diagnostic.  */
5018       if (!same_type_p (TREE_TYPE (expr), type))
5019         {
5020           /* Make sure we are just one standard conversion off.  */
5021           gcc_assert (can_convert (type, TREE_TYPE (expr)));
5022           error ("%qE is not a valid template argument for type %qT "
5023                  "because it is of type %qT", expr, type,
5024                  TREE_TYPE (expr));
5025           inform (input_location, "standard conversions are not allowed in this context");
5026           return NULL_TREE;
5027         }
5028     }
5029   /* [temp.arg.nontype]/5, bullet 7
5030
5031      For a non-type template-parameter of type pointer to data member,
5032      qualification conversions (_conv.qual_) are applied.  */
5033   else if (TYPE_PTRMEM_P (type))
5034     {
5035       /* [temp.arg.nontype] bullet 1 says the pointer to member
5036          expression must be a pointer-to-member constant.  */
5037       if (!check_valid_ptrmem_cst_expr (type, expr))
5038         return error_mark_node;
5039
5040       expr = perform_qualification_conversions (type, expr);
5041       if (expr == error_mark_node)
5042         return expr;
5043     }
5044   /* A template non-type parameter must be one of the above.  */
5045   else
5046     gcc_unreachable ();
5047
5048   /* Sanity check: did we actually convert the argument to the
5049      right type?  */
5050   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5051   return expr;
5052 }
5053
5054 /* Subroutine of coerce_template_template_parms, which returns 1 if
5055    PARM_PARM and ARG_PARM match using the rule for the template
5056    parameters of template template parameters. Both PARM and ARG are
5057    template parameters; the rest of the arguments are the same as for
5058    coerce_template_template_parms.
5059  */
5060 static int
5061 coerce_template_template_parm (tree parm,
5062                               tree arg,
5063                               tsubst_flags_t complain,
5064                               tree in_decl,
5065                               tree outer_args)
5066 {
5067   if (arg == NULL_TREE || arg == error_mark_node
5068       || parm == NULL_TREE || parm == error_mark_node)
5069     return 0;
5070   
5071   if (TREE_CODE (arg) != TREE_CODE (parm))
5072     return 0;
5073   
5074   switch (TREE_CODE (parm))
5075     {
5076     case TEMPLATE_DECL:
5077       /* We encounter instantiations of templates like
5078          template <template <template <class> class> class TT>
5079          class C;  */
5080       {
5081         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5082         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5083         
5084         if (!coerce_template_template_parms
5085             (parmparm, argparm, complain, in_decl, outer_args))
5086           return 0;
5087       }
5088       /* Fall through.  */
5089       
5090     case TYPE_DECL:
5091       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5092           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5093         /* Argument is a parameter pack but parameter is not.  */
5094         return 0;
5095       break;
5096       
5097     case PARM_DECL:
5098       /* The tsubst call is used to handle cases such as
5099          
5100            template <int> class C {};
5101            template <class T, template <T> class TT> class D {};
5102            D<int, C> d;
5103
5104          i.e. the parameter list of TT depends on earlier parameters.  */
5105       if (!uses_template_parms (TREE_TYPE (arg))
5106           && !same_type_p
5107                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5108                  TREE_TYPE (arg)))
5109         return 0;
5110       
5111       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5112           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5113         /* Argument is a parameter pack but parameter is not.  */
5114         return 0;
5115       
5116       break;
5117
5118     default:
5119       gcc_unreachable ();
5120     }
5121
5122   return 1;
5123 }
5124
5125
5126 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5127    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5128    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5129    or PARM_DECL.
5130
5131    Consider the example:
5132      template <class T> class A;
5133      template<template <class U> class TT> class B;
5134
5135    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5136    the parameters to A, and OUTER_ARGS contains A.  */
5137
5138 static int
5139 coerce_template_template_parms (tree parm_parms,
5140                                 tree arg_parms,
5141                                 tsubst_flags_t complain,
5142                                 tree in_decl,
5143                                 tree outer_args)
5144 {
5145   int nparms, nargs, i;
5146   tree parm, arg;
5147   int variadic_p = 0;
5148
5149   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5150   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5151
5152   nparms = TREE_VEC_LENGTH (parm_parms);
5153   nargs = TREE_VEC_LENGTH (arg_parms);
5154
5155   /* Determine whether we have a parameter pack at the end of the
5156      template template parameter's template parameter list.  */
5157   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5158     {
5159       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5160       
5161       if (parm == error_mark_node)
5162         return 0;
5163
5164       switch (TREE_CODE (parm))
5165         {
5166         case TEMPLATE_DECL:
5167         case TYPE_DECL:
5168           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5169             variadic_p = 1;
5170           break;
5171           
5172         case PARM_DECL:
5173           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5174             variadic_p = 1;
5175           break;
5176           
5177         default:
5178           gcc_unreachable ();
5179         }
5180     }
5181  
5182   if (nargs != nparms
5183       && !(variadic_p && nargs >= nparms - 1))
5184     return 0;
5185
5186   /* Check all of the template parameters except the parameter pack at
5187      the end (if any).  */
5188   for (i = 0; i < nparms - variadic_p; ++i)
5189     {
5190       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5191           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5192         continue;
5193
5194       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5195       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5196
5197       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5198                                           outer_args))
5199         return 0;
5200
5201     }
5202
5203   if (variadic_p)
5204     {
5205       /* Check each of the template parameters in the template
5206          argument against the template parameter pack at the end of
5207          the template template parameter.  */
5208       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5209         return 0;
5210
5211       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5212
5213       for (; i < nargs; ++i)
5214         {
5215           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5216             continue;
5217  
5218           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5219  
5220           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5221                                               outer_args))
5222             return 0;
5223         }
5224     }
5225
5226   return 1;
5227 }
5228
5229 /* Verifies that the deduced template arguments (in TARGS) for the
5230    template template parameters (in TPARMS) represent valid bindings,
5231    by comparing the template parameter list of each template argument
5232    to the template parameter list of its corresponding template
5233    template parameter, in accordance with DR150. This
5234    routine can only be called after all template arguments have been
5235    deduced. It will return TRUE if all of the template template
5236    parameter bindings are okay, FALSE otherwise.  */
5237 bool 
5238 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5239 {
5240   int i, ntparms = TREE_VEC_LENGTH (tparms);
5241   bool ret = true;
5242
5243   /* We're dealing with template parms in this process.  */
5244   ++processing_template_decl;
5245
5246   targs = INNERMOST_TEMPLATE_ARGS (targs);
5247
5248   for (i = 0; i < ntparms; ++i)
5249     {
5250       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5251       tree targ = TREE_VEC_ELT (targs, i);
5252
5253       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5254         {
5255           tree packed_args = NULL_TREE;
5256           int idx, len = 1;
5257
5258           if (ARGUMENT_PACK_P (targ))
5259             {
5260               /* Look inside the argument pack.  */
5261               packed_args = ARGUMENT_PACK_ARGS (targ);
5262               len = TREE_VEC_LENGTH (packed_args);
5263             }
5264
5265           for (idx = 0; idx < len; ++idx)
5266             {
5267               tree targ_parms = NULL_TREE;
5268
5269               if (packed_args)
5270                 /* Extract the next argument from the argument
5271                    pack.  */
5272                 targ = TREE_VEC_ELT (packed_args, idx);
5273
5274               if (PACK_EXPANSION_P (targ))
5275                 /* Look at the pattern of the pack expansion.  */
5276                 targ = PACK_EXPANSION_PATTERN (targ);
5277
5278               /* Extract the template parameters from the template
5279                  argument.  */
5280               if (TREE_CODE (targ) == TEMPLATE_DECL)
5281                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5282               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5283                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5284
5285               /* Verify that we can coerce the template template
5286                  parameters from the template argument to the template
5287                  parameter.  This requires an exact match.  */
5288               if (targ_parms
5289                   && !coerce_template_template_parms
5290                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5291                         targ_parms,
5292                         tf_none,
5293                         tparm,
5294                         targs))
5295                 {
5296                   ret = false;
5297                   goto out;
5298                 }
5299             }
5300         }
5301     }
5302
5303  out:
5304
5305   --processing_template_decl;
5306   return ret;
5307 }
5308
5309 /* Convert the indicated template ARG as necessary to match the
5310    indicated template PARM.  Returns the converted ARG, or
5311    error_mark_node if the conversion was unsuccessful.  Error and
5312    warning messages are issued under control of COMPLAIN.  This
5313    conversion is for the Ith parameter in the parameter list.  ARGS is
5314    the full set of template arguments deduced so far.  */
5315
5316 static tree
5317 convert_template_argument (tree parm,
5318                            tree arg,
5319                            tree args,
5320                            tsubst_flags_t complain,
5321                            int i,
5322                            tree in_decl)
5323 {
5324   tree orig_arg;
5325   tree val;
5326   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5327
5328   if (TREE_CODE (arg) == TREE_LIST
5329       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5330     {
5331       /* The template argument was the name of some
5332          member function.  That's usually
5333          invalid, but static members are OK.  In any
5334          case, grab the underlying fields/functions
5335          and issue an error later if required.  */
5336       orig_arg = TREE_VALUE (arg);
5337       TREE_TYPE (arg) = unknown_type_node;
5338     }
5339
5340   orig_arg = arg;
5341
5342   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5343   requires_type = (TREE_CODE (parm) == TYPE_DECL
5344                    || requires_tmpl_type);
5345
5346   /* When determining whether an argument pack expansion is a template,
5347      look at the pattern.  */
5348   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5349     arg = PACK_EXPANSION_PATTERN (arg);
5350
5351   is_tmpl_type = 
5352     ((TREE_CODE (arg) == TEMPLATE_DECL
5353       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5354      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5355      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5356
5357   if (is_tmpl_type
5358       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5359           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5360     arg = TYPE_STUB_DECL (arg);
5361
5362   is_type = TYPE_P (arg) || is_tmpl_type;
5363
5364   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5365       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5366     {
5367       permerror (input_location, "to refer to a type member of a template parameter, "
5368                  "use %<typename %E%>", orig_arg);
5369
5370       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5371                                      TREE_OPERAND (arg, 1),
5372                                      typename_type,
5373                                      complain & tf_error);
5374       arg = orig_arg;
5375       is_type = 1;
5376     }
5377   if (is_type != requires_type)
5378     {
5379       if (in_decl)
5380         {
5381           if (complain & tf_error)
5382             {
5383               error ("type/value mismatch at argument %d in template "
5384                      "parameter list for %qD",
5385                      i + 1, in_decl);
5386               if (is_type)
5387                 error ("  expected a constant of type %qT, got %qT",
5388                        TREE_TYPE (parm),
5389                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5390               else if (requires_tmpl_type)
5391                 error ("  expected a class template, got %qE", orig_arg);
5392               else
5393                 error ("  expected a type, got %qE", orig_arg);
5394             }
5395         }
5396       return error_mark_node;
5397     }
5398   if (is_tmpl_type ^ requires_tmpl_type)
5399     {
5400       if (in_decl && (complain & tf_error))
5401         {
5402           error ("type/value mismatch at argument %d in template "
5403                  "parameter list for %qD",
5404                  i + 1, in_decl);
5405           if (is_tmpl_type)
5406             error ("  expected a type, got %qT", DECL_NAME (arg));
5407           else
5408             error ("  expected a class template, got %qT", orig_arg);
5409         }
5410       return error_mark_node;
5411     }
5412
5413   if (is_type)
5414     {
5415       if (requires_tmpl_type)
5416         {
5417           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5418             /* The number of argument required is not known yet.
5419                Just accept it for now.  */
5420             val = TREE_TYPE (arg);
5421           else
5422             {
5423               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5424               tree argparm;
5425
5426               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5427
5428               if (coerce_template_template_parms (parmparm, argparm,
5429                                                   complain, in_decl,
5430                                                   args))
5431                 {
5432                   val = orig_arg;
5433
5434                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5435                      TEMPLATE_DECL.  */
5436                   if (val != error_mark_node)
5437                     {
5438                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5439                         val = TREE_TYPE (val);
5440                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
5441                                && DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
5442                         {
5443                           val = TREE_TYPE (arg);
5444                           val = make_pack_expansion (val);
5445                         }
5446                     }
5447                 }
5448               else
5449                 {
5450                   if (in_decl && (complain & tf_error))
5451                     {
5452                       error ("type/value mismatch at argument %d in "
5453                              "template parameter list for %qD",
5454                              i + 1, in_decl);
5455                       error ("  expected a template of type %qD, got %qD",
5456                              parm, orig_arg);
5457                     }
5458
5459                   val = error_mark_node;
5460                 }
5461             }
5462         }
5463       else
5464         val = orig_arg;
5465       /* We only form one instance of each template specialization.
5466          Therefore, if we use a non-canonical variant (i.e., a
5467          typedef), any future messages referring to the type will use
5468          the typedef, which is confusing if those future uses do not
5469          themselves also use the typedef.  */
5470       if (TYPE_P (val))
5471         val = strip_typedefs (val);
5472     }
5473   else
5474     {
5475       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5476
5477       if (invalid_nontype_parm_type_p (t, complain))
5478         return error_mark_node;
5479
5480       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5481         {
5482           if (same_type_p (t, TREE_TYPE (orig_arg)))
5483             val = orig_arg;
5484           else
5485             {
5486               /* Not sure if this is reachable, but it doesn't hurt
5487                  to be robust.  */
5488               error ("type mismatch in nontype parameter pack");
5489               val = error_mark_node;
5490             }
5491         }
5492       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5493         /* We used to call digest_init here.  However, digest_init
5494            will report errors, which we don't want when complain
5495            is zero.  More importantly, digest_init will try too
5496            hard to convert things: for example, `0' should not be
5497            converted to pointer type at this point according to
5498            the standard.  Accepting this is not merely an
5499            extension, since deciding whether or not these
5500            conversions can occur is part of determining which
5501            function template to call, or whether a given explicit
5502            argument specification is valid.  */
5503         val = convert_nontype_argument (t, orig_arg);
5504       else
5505         val = orig_arg;
5506
5507       if (val == NULL_TREE)
5508         val = error_mark_node;
5509       else if (val == error_mark_node && (complain & tf_error))
5510         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5511     }
5512
5513   return val;
5514 }
5515
5516 /* Coerces the remaining template arguments in INNER_ARGS (from
5517    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5518    Returns the coerced argument pack. PARM_IDX is the position of this
5519    parameter in the template parameter list. ARGS is the original
5520    template argument list.  */
5521 static tree
5522 coerce_template_parameter_pack (tree parms,
5523                                 int parm_idx,
5524                                 tree args,
5525                                 tree inner_args,
5526                                 int arg_idx,
5527                                 tree new_args,
5528                                 int* lost,
5529                                 tree in_decl,
5530                                 tsubst_flags_t complain)
5531 {
5532   tree parm = TREE_VEC_ELT (parms, parm_idx);
5533   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5534   tree packed_args;
5535   tree argument_pack;
5536   tree packed_types = NULL_TREE;
5537
5538   if (arg_idx > nargs)
5539     arg_idx = nargs;
5540
5541   packed_args = make_tree_vec (nargs - arg_idx);
5542
5543   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5544       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5545     {
5546       /* When the template parameter is a non-type template
5547          parameter pack whose type uses parameter packs, we need
5548          to look at each of the template arguments
5549          separately. Build a vector of the types for these
5550          non-type template parameters in PACKED_TYPES.  */
5551       tree expansion 
5552         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5553       packed_types = tsubst_pack_expansion (expansion, args,
5554                                             complain, in_decl);
5555
5556       if (packed_types == error_mark_node)
5557         return error_mark_node;
5558
5559       /* Check that we have the right number of arguments.  */
5560       if (arg_idx < nargs
5561           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5562           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5563         {
5564           int needed_parms 
5565             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5566           error ("wrong number of template arguments (%d, should be %d)",
5567                  nargs, needed_parms);
5568           return error_mark_node;
5569         }
5570
5571       /* If we aren't able to check the actual arguments now
5572          (because they haven't been expanded yet), we can at least
5573          verify that all of the types used for the non-type
5574          template parameter pack are, in fact, valid for non-type
5575          template parameters.  */
5576       if (arg_idx < nargs 
5577           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5578         {
5579           int j, len = TREE_VEC_LENGTH (packed_types);
5580           for (j = 0; j < len; ++j)
5581             {
5582               tree t = TREE_VEC_ELT (packed_types, j);
5583               if (invalid_nontype_parm_type_p (t, complain))
5584                 return error_mark_node;
5585             }
5586         }
5587     }
5588
5589   /* Convert the remaining arguments, which will be a part of the
5590      parameter pack "parm".  */
5591   for (; arg_idx < nargs; ++arg_idx)
5592     {
5593       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5594       tree actual_parm = TREE_VALUE (parm);
5595
5596       if (packed_types && !PACK_EXPANSION_P (arg))
5597         {
5598           /* When we have a vector of types (corresponding to the
5599              non-type template parameter pack that uses parameter
5600              packs in its type, as mention above), and the
5601              argument is not an expansion (which expands to a
5602              currently unknown number of arguments), clone the
5603              parm and give it the next type in PACKED_TYPES.  */
5604           actual_parm = copy_node (actual_parm);
5605           TREE_TYPE (actual_parm) = 
5606             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5607         }
5608
5609       if (arg != error_mark_node)
5610         arg = convert_template_argument (actual_parm, 
5611                                          arg, new_args, complain, parm_idx,
5612                                          in_decl);
5613       if (arg == error_mark_node)
5614         (*lost)++;
5615       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5616     }
5617
5618   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5619       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5620     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5621   else
5622     {
5623       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5624       TREE_TYPE (argument_pack) 
5625         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5626       TREE_CONSTANT (argument_pack) = 1;
5627     }
5628
5629   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5630   return argument_pack;
5631 }
5632
5633 /* Convert all template arguments to their appropriate types, and
5634    return a vector containing the innermost resulting template
5635    arguments.  If any error occurs, return error_mark_node. Error and
5636    warning messages are issued under control of COMPLAIN.
5637
5638    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5639    for arguments not specified in ARGS.  Otherwise, if
5640    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5641    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5642    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5643    ARGS.  */
5644
5645 static tree
5646 coerce_template_parms (tree parms,
5647                        tree args,
5648                        tree in_decl,
5649                        tsubst_flags_t complain,
5650                        bool require_all_args,
5651                        bool use_default_args)
5652 {
5653   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5654   tree inner_args;
5655   tree new_args;
5656   tree new_inner_args;
5657   int saved_unevaluated_operand;
5658   int saved_inhibit_evaluation_warnings;
5659
5660   /* When used as a boolean value, indicates whether this is a
5661      variadic template parameter list. Since it's an int, we can also
5662      subtract it from nparms to get the number of non-variadic
5663      parameters.  */
5664   int variadic_p = 0;
5665
5666   nparms = TREE_VEC_LENGTH (parms);
5667
5668   /* Determine if there are any parameter packs.  */
5669   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5670     {
5671       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5672       if (template_parameter_pack_p (tparm))
5673         ++variadic_p;
5674     }
5675
5676   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5677   /* If there are 0 or 1 parameter packs, we need to expand any argument
5678      packs so that we can deduce a parameter pack from some non-packed args
5679      followed by an argument pack, as in variadic85.C.  If there are more
5680      than that, we need to leave argument packs intact so the arguments are
5681      assigned to the right parameter packs.  This should only happen when
5682      dealing with a nested class inside a partial specialization of a class
5683      template, as in variadic92.C.  */
5684   if (variadic_p <= 1)
5685     inner_args = expand_template_argument_pack (inner_args);
5686
5687   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5688   if ((nargs > nparms && !variadic_p)
5689       || (nargs < nparms - variadic_p
5690           && require_all_args
5691           && (!use_default_args
5692               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5693                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5694     {
5695       if (complain & tf_error)
5696         {
5697           const char *or_more = "";
5698           if (variadic_p)
5699             {
5700               or_more = " or more";
5701               --nparms;
5702             }
5703
5704           error ("wrong number of template arguments (%d, should be %d%s)",
5705                  nargs, nparms, or_more);
5706
5707           if (in_decl)
5708             error ("provided for %q+D", in_decl);
5709         }
5710
5711       return error_mark_node;
5712     }
5713
5714   /* We need to evaluate the template arguments, even though this
5715      template-id may be nested within a "sizeof".  */
5716   saved_unevaluated_operand = cp_unevaluated_operand;
5717   cp_unevaluated_operand = 0;
5718   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5719   c_inhibit_evaluation_warnings = 0;
5720   new_inner_args = make_tree_vec (nparms);
5721   new_args = add_outermost_template_args (args, new_inner_args);
5722   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5723     {
5724       tree arg;
5725       tree parm;
5726
5727       /* Get the Ith template parameter.  */
5728       parm = TREE_VEC_ELT (parms, parm_idx);
5729  
5730       if (parm == error_mark_node)
5731       {
5732         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5733         continue;
5734       }
5735
5736       /* Calculate the next argument.  */
5737       if (arg_idx < nargs)
5738         arg = TREE_VEC_ELT (inner_args, arg_idx);
5739       else
5740         arg = NULL_TREE;
5741
5742       if (template_parameter_pack_p (TREE_VALUE (parm))
5743           && !(arg && ARGUMENT_PACK_P (arg)))
5744         {
5745           /* All remaining arguments will be placed in the
5746              template parameter pack PARM.  */
5747           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5748                                                 inner_args, arg_idx,
5749                                                 new_args, &lost,
5750                                                 in_decl, complain);
5751
5752           /* Store this argument.  */
5753           if (arg == error_mark_node)
5754             lost++;
5755           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5756
5757           /* We are done with all of the arguments.  */
5758           arg_idx = nargs;
5759           
5760           continue;
5761         }
5762       else if (arg)
5763         {
5764           if (PACK_EXPANSION_P (arg))
5765             {
5766               if (complain & tf_error)
5767                 {
5768                   /* FIXME this restriction was removed by N2555; see
5769                      bug 35722.  */
5770                   /* If ARG is a pack expansion, but PARM is not a
5771                      template parameter pack (if it were, we would have
5772                      handled it above), we're trying to expand into a
5773                      fixed-length argument list.  */
5774                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5775                     sorry ("cannot expand %<%E%> into a fixed-length "
5776                            "argument list", arg);
5777                   else
5778                     sorry ("cannot expand %<%T%> into a fixed-length "
5779                            "argument list", arg);
5780                 }
5781               return error_mark_node;
5782             }
5783         }
5784       else if (require_all_args)
5785         /* There must be a default arg in this case.  */
5786         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5787                                    complain, in_decl);
5788       else
5789         break;
5790
5791       if (arg == error_mark_node)
5792         {
5793           if (complain & tf_error)
5794             error ("template argument %d is invalid", arg_idx + 1);
5795         }
5796       else if (!arg)
5797         /* This only occurs if there was an error in the template
5798            parameter list itself (which we would already have
5799            reported) that we are trying to recover from, e.g., a class
5800            template with a parameter list such as
5801            template<typename..., typename>.  */
5802         return error_mark_node;
5803       else
5804         arg = convert_template_argument (TREE_VALUE (parm),
5805                                          arg, new_args, complain, 
5806                                          parm_idx, in_decl);
5807
5808       if (arg == error_mark_node)
5809         lost++;
5810       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5811     }
5812   cp_unevaluated_operand = saved_unevaluated_operand;
5813   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
5814
5815   if (lost)
5816     return error_mark_node;
5817
5818   return new_inner_args;
5819 }
5820
5821 /* Returns 1 if template args OT and NT are equivalent.  */
5822
5823 static int
5824 template_args_equal (tree ot, tree nt)
5825 {
5826   if (nt == ot)
5827     return 1;
5828
5829   if (TREE_CODE (nt) == TREE_VEC)
5830     /* For member templates */
5831     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5832   else if (PACK_EXPANSION_P (ot))
5833     return PACK_EXPANSION_P (nt) 
5834       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5835                               PACK_EXPANSION_PATTERN (nt));
5836   else if (ARGUMENT_PACK_P (ot))
5837     {
5838       int i, len;
5839       tree opack, npack;
5840
5841       if (!ARGUMENT_PACK_P (nt))
5842         return 0;
5843
5844       opack = ARGUMENT_PACK_ARGS (ot);
5845       npack = ARGUMENT_PACK_ARGS (nt);
5846       len = TREE_VEC_LENGTH (opack);
5847       if (TREE_VEC_LENGTH (npack) != len)
5848         return 0;
5849       for (i = 0; i < len; ++i)
5850         if (!template_args_equal (TREE_VEC_ELT (opack, i),
5851                                   TREE_VEC_ELT (npack, i)))
5852           return 0;
5853       return 1;
5854     }
5855   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
5856     {
5857       /* We get here probably because we are in the middle of substituting
5858          into the pattern of a pack expansion. In that case the
5859          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
5860          interested in. So we want to use the initial pack argument for
5861          the comparison.  */
5862       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
5863       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
5864         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
5865       return template_args_equal (ot, nt);
5866     }
5867   else if (TYPE_P (nt))
5868     return TYPE_P (ot) && same_type_p (ot, nt);
5869   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5870     return 0;
5871   else
5872     return cp_tree_equal (ot, nt);
5873 }
5874
5875 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5876    of template arguments.  Returns 0 otherwise.  */
5877
5878 int
5879 comp_template_args (tree oldargs, tree newargs)
5880 {
5881   int i;
5882
5883   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5884     return 0;
5885
5886   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5887     {
5888       tree nt = TREE_VEC_ELT (newargs, i);
5889       tree ot = TREE_VEC_ELT (oldargs, i);
5890
5891       if (! template_args_equal (ot, nt))
5892         return 0;
5893     }
5894   return 1;
5895 }
5896
5897 static void
5898 add_pending_template (tree d)
5899 {
5900   tree ti = (TYPE_P (d)
5901              ? CLASSTYPE_TEMPLATE_INFO (d)
5902              : DECL_TEMPLATE_INFO (d));
5903   struct pending_template *pt;
5904   int level;
5905
5906   if (TI_PENDING_TEMPLATE_FLAG (ti))
5907     return;
5908
5909   /* We are called both from instantiate_decl, where we've already had a
5910      tinst_level pushed, and instantiate_template, where we haven't.
5911      Compensate.  */
5912   level = !current_tinst_level || current_tinst_level->decl != d;
5913
5914   if (level)
5915     push_tinst_level (d);
5916
5917   pt = GGC_NEW (struct pending_template);
5918   pt->next = NULL;
5919   pt->tinst = current_tinst_level;
5920   if (last_pending_template)
5921     last_pending_template->next = pt;
5922   else
5923     pending_templates = pt;
5924
5925   last_pending_template = pt;
5926
5927   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5928
5929   if (level)
5930     pop_tinst_level ();
5931 }
5932
5933
5934 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5935    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5936    documentation for TEMPLATE_ID_EXPR.  */
5937
5938 tree
5939 lookup_template_function (tree fns, tree arglist)
5940 {
5941   tree type;
5942
5943   if (fns == error_mark_node || arglist == error_mark_node)
5944     return error_mark_node;
5945
5946   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5947   gcc_assert (fns && (is_overloaded_fn (fns)
5948                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5949
5950   if (BASELINK_P (fns))
5951     {
5952       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5953                                          unknown_type_node,
5954                                          BASELINK_FUNCTIONS (fns),
5955                                          arglist);
5956       return fns;
5957     }
5958
5959   type = TREE_TYPE (fns);
5960   if (TREE_CODE (fns) == OVERLOAD || !type)
5961     type = unknown_type_node;
5962
5963   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5964 }
5965
5966 /* Within the scope of a template class S<T>, the name S gets bound
5967    (in build_self_reference) to a TYPE_DECL for the class, not a
5968    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5969    or one of its enclosing classes, and that type is a template,
5970    return the associated TEMPLATE_DECL.  Otherwise, the original
5971    DECL is returned.  */
5972
5973 tree
5974 maybe_get_template_decl_from_type_decl (tree decl)
5975 {
5976   return (decl != NULL_TREE
5977           && TREE_CODE (decl) == TYPE_DECL
5978           && DECL_ARTIFICIAL (decl)
5979           && CLASS_TYPE_P (TREE_TYPE (decl))
5980           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5981     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5982 }
5983
5984 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5985    parameters, find the desired type.
5986
5987    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5988
5989    IN_DECL, if non-NULL, is the template declaration we are trying to
5990    instantiate.
5991
5992    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5993    the class we are looking up.
5994
5995    Issue error and warning messages under control of COMPLAIN.
5996
5997    If the template class is really a local class in a template
5998    function, then the FUNCTION_CONTEXT is the function in which it is
5999    being instantiated.
6000
6001    ??? Note that this function is currently called *twice* for each
6002    template-id: the first time from the parser, while creating the
6003    incomplete type (finish_template_type), and the second type during the
6004    real instantiation (instantiate_template_class). This is surely something
6005    that we want to avoid. It also causes some problems with argument
6006    coercion (see convert_nontype_argument for more information on this).  */
6007
6008 tree
6009 lookup_template_class (tree d1,
6010                        tree arglist,
6011                        tree in_decl,
6012                        tree context,
6013                        int entering_scope,
6014                        tsubst_flags_t complain)
6015 {
6016   tree templ = NULL_TREE, parmlist;
6017   tree t;
6018   spec_entry **slot;
6019   spec_entry *entry;
6020   spec_entry elt;
6021   hashval_t hash;
6022
6023   timevar_push (TV_NAME_LOOKUP);
6024
6025   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6026     {
6027       tree value = innermost_non_namespace_value (d1);
6028       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6029         templ = value;
6030       else
6031         {
6032           if (context)
6033             push_decl_namespace (context);
6034           templ = lookup_name (d1);
6035           templ = maybe_get_template_decl_from_type_decl (templ);
6036           if (context)
6037             pop_decl_namespace ();
6038         }
6039       if (templ)
6040         context = DECL_CONTEXT (templ);
6041     }
6042   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6043     {
6044       tree type = TREE_TYPE (d1);
6045
6046       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6047          an implicit typename for the second A.  Deal with it.  */
6048       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6049         type = TREE_TYPE (type);
6050
6051       if (CLASSTYPE_TEMPLATE_INFO (type))
6052         {
6053           templ = CLASSTYPE_TI_TEMPLATE (type);
6054           d1 = DECL_NAME (templ);
6055         }
6056     }
6057   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6058            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6059     {
6060       templ = TYPE_TI_TEMPLATE (d1);
6061       d1 = DECL_NAME (templ);
6062     }
6063   else if (TREE_CODE (d1) == TEMPLATE_DECL
6064            && DECL_TEMPLATE_RESULT (d1)
6065            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6066     {
6067       templ = d1;
6068       d1 = DECL_NAME (templ);
6069       context = DECL_CONTEXT (templ);
6070     }
6071
6072   /* Issue an error message if we didn't find a template.  */
6073   if (! templ)
6074     {
6075       if (complain & tf_error)
6076         error ("%qT is not a template", d1);
6077       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6078     }
6079
6080   if (TREE_CODE (templ) != TEMPLATE_DECL
6081          /* Make sure it's a user visible template, if it was named by
6082             the user.  */
6083       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6084           && !PRIMARY_TEMPLATE_P (templ)))
6085     {
6086       if (complain & tf_error)
6087         {
6088           error ("non-template type %qT used as a template", d1);
6089           if (in_decl)
6090             error ("for template declaration %q+D", in_decl);
6091         }
6092       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6093     }
6094
6095   complain &= ~tf_user;
6096
6097   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6098     {
6099       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6100          template arguments */
6101
6102       tree parm;
6103       tree arglist2;
6104       tree outer;
6105
6106       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6107
6108       /* Consider an example where a template template parameter declared as
6109
6110            template <class T, class U = std::allocator<T> > class TT
6111
6112          The template parameter level of T and U are one level larger than
6113          of TT.  To proper process the default argument of U, say when an
6114          instantiation `TT<int>' is seen, we need to build the full
6115          arguments containing {int} as the innermost level.  Outer levels,
6116          available when not appearing as default template argument, can be
6117          obtained from the arguments of the enclosing template.
6118
6119          Suppose that TT is later substituted with std::vector.  The above
6120          instantiation is `TT<int, std::allocator<T> >' with TT at
6121          level 1, and T at level 2, while the template arguments at level 1
6122          becomes {std::vector} and the inner level 2 is {int}.  */
6123
6124       outer = DECL_CONTEXT (templ);
6125       if (outer)
6126         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6127       else if (current_template_parms)
6128         /* This is an argument of the current template, so we haven't set
6129            DECL_CONTEXT yet.  */
6130         outer = current_template_args ();
6131
6132       if (outer)
6133         arglist = add_to_template_args (outer, arglist);
6134
6135       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6136                                         complain,
6137                                         /*require_all_args=*/true,
6138                                         /*use_default_args=*/true);
6139       if (arglist2 == error_mark_node
6140           || (!uses_template_parms (arglist2)
6141               && check_instantiated_args (templ, arglist2, complain)))
6142         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6143
6144       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6145       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6146     }
6147   else
6148     {
6149       tree template_type = TREE_TYPE (templ);
6150       tree gen_tmpl;
6151       tree type_decl;
6152       tree found = NULL_TREE;
6153       int arg_depth;
6154       int parm_depth;
6155       int is_partial_instantiation;
6156
6157       gen_tmpl = most_general_template (templ);
6158       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6159       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6160       arg_depth = TMPL_ARGS_DEPTH (arglist);
6161
6162       if (arg_depth == 1 && parm_depth > 1)
6163         {
6164           /* We've been given an incomplete set of template arguments.
6165              For example, given:
6166
6167                template <class T> struct S1 {
6168                  template <class U> struct S2 {};
6169                  template <class U> struct S2<U*> {};
6170                 };
6171
6172              we will be called with an ARGLIST of `U*', but the
6173              TEMPLATE will be `template <class T> template
6174              <class U> struct S1<T>::S2'.  We must fill in the missing
6175              arguments.  */
6176           arglist
6177             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6178                                            arglist);
6179           arg_depth = TMPL_ARGS_DEPTH (arglist);
6180         }
6181
6182       /* Now we should have enough arguments.  */
6183       gcc_assert (parm_depth == arg_depth);
6184
6185       /* From here on, we're only interested in the most general
6186          template.  */
6187
6188       /* Calculate the BOUND_ARGS.  These will be the args that are
6189          actually tsubst'd into the definition to create the
6190          instantiation.  */
6191       if (parm_depth > 1)
6192         {
6193           /* We have multiple levels of arguments to coerce, at once.  */
6194           int i;
6195           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6196
6197           tree bound_args = make_tree_vec (parm_depth);
6198
6199           for (i = saved_depth,
6200                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6201                i > 0 && t != NULL_TREE;
6202                --i, t = TREE_CHAIN (t))
6203             {
6204               tree a = coerce_template_parms (TREE_VALUE (t),
6205                                               arglist, gen_tmpl,
6206                                               complain,
6207                                               /*require_all_args=*/true,
6208                                               /*use_default_args=*/true);
6209
6210               /* Don't process further if one of the levels fails.  */
6211               if (a == error_mark_node)
6212                 {
6213                   /* Restore the ARGLIST to its full size.  */
6214                   TREE_VEC_LENGTH (arglist) = saved_depth;
6215                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6216                 }
6217
6218               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6219
6220               /* We temporarily reduce the length of the ARGLIST so
6221                  that coerce_template_parms will see only the arguments
6222                  corresponding to the template parameters it is
6223                  examining.  */
6224               TREE_VEC_LENGTH (arglist)--;
6225             }
6226
6227           /* Restore the ARGLIST to its full size.  */
6228           TREE_VEC_LENGTH (arglist) = saved_depth;
6229
6230           arglist = bound_args;
6231         }
6232       else
6233         arglist
6234           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6235                                    INNERMOST_TEMPLATE_ARGS (arglist),
6236                                    gen_tmpl,
6237                                    complain,
6238                                    /*require_all_args=*/true,
6239                                    /*use_default_args=*/true);
6240
6241       if (arglist == error_mark_node)
6242         /* We were unable to bind the arguments.  */
6243         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6244
6245       /* In the scope of a template class, explicit references to the
6246          template class refer to the type of the template, not any
6247          instantiation of it.  For example, in:
6248
6249            template <class T> class C { void f(C<T>); }
6250
6251          the `C<T>' is just the same as `C'.  Outside of the
6252          class, however, such a reference is an instantiation.  */
6253       if ((entering_scope
6254            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6255            || currently_open_class (template_type))
6256           /* comp_template_args is expensive, check it last.  */
6257           && comp_template_args (TYPE_TI_ARGS (template_type),
6258                                  arglist))
6259         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6260
6261       /* If we already have this specialization, return it.  */
6262       elt.tmpl = gen_tmpl;
6263       elt.args = arglist;
6264       hash = hash_specialization (&elt);
6265       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6266                                                   &elt, hash);
6267
6268       if (entry)
6269         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6270
6271       /* This type is a "partial instantiation" if any of the template
6272          arguments still involve template parameters.  Note that we set
6273          IS_PARTIAL_INSTANTIATION for partial specializations as
6274          well.  */
6275       is_partial_instantiation = uses_template_parms (arglist);
6276
6277       /* If the deduced arguments are invalid, then the binding
6278          failed.  */
6279       if (!is_partial_instantiation
6280           && check_instantiated_args (gen_tmpl,
6281                                       INNERMOST_TEMPLATE_ARGS (arglist),
6282                                       complain))
6283         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6284
6285       if (!is_partial_instantiation
6286           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6287           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6288           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6289         {
6290           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6291                                       DECL_NAME (gen_tmpl),
6292                                       /*tag_scope=*/ts_global);
6293           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6294         }
6295
6296       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6297                         complain, in_decl);
6298       if (!context)
6299         context = global_namespace;
6300
6301       /* Create the type.  */
6302       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6303         {
6304           if (!is_partial_instantiation)
6305             {
6306               set_current_access_from_decl (TYPE_NAME (template_type));
6307               t = start_enum (TYPE_IDENTIFIER (template_type),
6308                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6309                                       arglist, complain, in_decl),
6310                               SCOPED_ENUM_P (template_type));
6311             }
6312           else
6313             {
6314               /* We don't want to call start_enum for this type, since
6315                  the values for the enumeration constants may involve
6316                  template parameters.  And, no one should be interested
6317                  in the enumeration constants for such a type.  */
6318               t = cxx_make_type (ENUMERAL_TYPE);
6319               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6320             }
6321         }
6322       else
6323         {
6324           t = make_class_type (TREE_CODE (template_type));
6325           CLASSTYPE_DECLARED_CLASS (t)
6326             = CLASSTYPE_DECLARED_CLASS (template_type);
6327           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6328           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6329
6330           /* A local class.  Make sure the decl gets registered properly.  */
6331           if (context == current_function_decl)
6332             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6333
6334           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6335             /* This instantiation is another name for the primary
6336                template type. Set the TYPE_CANONICAL field
6337                appropriately. */
6338             TYPE_CANONICAL (t) = template_type;
6339           else if (any_template_arguments_need_structural_equality_p (arglist))
6340             /* Some of the template arguments require structural
6341                equality testing, so this template class requires
6342                structural equality testing. */
6343             SET_TYPE_STRUCTURAL_EQUALITY (t);
6344         }
6345
6346       /* If we called start_enum or pushtag above, this information
6347          will already be set up.  */
6348       if (!TYPE_NAME (t))
6349         {
6350           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6351
6352           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6353           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6354           TYPE_STUB_DECL (t) = type_decl;
6355           DECL_SOURCE_LOCATION (type_decl)
6356             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6357         }
6358       else
6359         type_decl = TYPE_NAME (t);
6360
6361       TREE_PRIVATE (type_decl)
6362         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6363       TREE_PROTECTED (type_decl)
6364         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6365       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6366         {
6367           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6368           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6369         }
6370
6371       /* Set up the template information.  We have to figure out which
6372          template is the immediate parent if this is a full
6373          instantiation.  */
6374       if (parm_depth == 1 || is_partial_instantiation
6375           || !PRIMARY_TEMPLATE_P (gen_tmpl))
6376         /* This case is easy; there are no member templates involved.  */
6377         found = gen_tmpl;
6378       else
6379         {
6380           /* This is a full instantiation of a member template.  Find
6381              the partial instantiation of which this is an instance.  */
6382
6383           /* Temporarily reduce by one the number of levels in the ARGLIST
6384              so as to avoid comparing the last set of arguments.  */
6385           TREE_VEC_LENGTH (arglist)--;
6386           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6387           TREE_VEC_LENGTH (arglist)++;
6388           found = CLASSTYPE_TI_TEMPLATE (found);
6389         }
6390
6391       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
6392
6393       elt.spec = t;
6394       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6395                                                        &elt, hash, INSERT);
6396       *slot = GGC_NEW (spec_entry);
6397       **slot = elt;
6398
6399       /* Note this use of the partial instantiation so we can check it
6400          later in maybe_process_partial_specialization.  */
6401       DECL_TEMPLATE_INSTANTIATIONS (templ)
6402         = tree_cons (arglist, t,
6403                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6404
6405       if (TREE_CODE (t) == ENUMERAL_TYPE
6406           && !is_partial_instantiation)
6407         /* Now that the type has been registered on the instantiations
6408            list, we set up the enumerators.  Because the enumeration
6409            constants may involve the enumeration type itself, we make
6410            sure to register the type first, and then create the
6411            constants.  That way, doing tsubst_expr for the enumeration
6412            constants won't result in recursive calls here; we'll find
6413            the instantiation and exit above.  */
6414         tsubst_enum (template_type, t, arglist);
6415
6416       if (is_partial_instantiation)
6417         /* If the type makes use of template parameters, the
6418            code that generates debugging information will crash.  */
6419         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6420
6421       /* Possibly limit visibility based on template args.  */
6422       TREE_PUBLIC (type_decl) = 1;
6423       determine_visibility (type_decl);
6424
6425       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6426     }
6427   timevar_pop (TV_NAME_LOOKUP);
6428 }
6429 \f
6430 struct pair_fn_data
6431 {
6432   tree_fn_t fn;
6433   void *data;
6434   /* True when we should also visit template parameters that occur in
6435      non-deduced contexts.  */
6436   bool include_nondeduced_p;
6437   struct pointer_set_t *visited;
6438 };
6439
6440 /* Called from for_each_template_parm via walk_tree.  */
6441
6442 static tree
6443 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6444 {
6445   tree t = *tp;
6446   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6447   tree_fn_t fn = pfd->fn;
6448   void *data = pfd->data;
6449
6450   if (TYPE_P (t)
6451       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6452       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6453                                  pfd->include_nondeduced_p))
6454     return error_mark_node;
6455
6456   switch (TREE_CODE (t))
6457     {
6458     case RECORD_TYPE:
6459       if (TYPE_PTRMEMFUNC_P (t))
6460         break;
6461       /* Fall through.  */
6462
6463     case UNION_TYPE:
6464     case ENUMERAL_TYPE:
6465       if (!TYPE_TEMPLATE_INFO (t))
6466         *walk_subtrees = 0;
6467       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
6468                                        fn, data, pfd->visited, 
6469                                        pfd->include_nondeduced_p))
6470         return error_mark_node;
6471       break;
6472
6473     case INTEGER_TYPE:
6474       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6475                                   fn, data, pfd->visited, 
6476                                   pfd->include_nondeduced_p)
6477           || for_each_template_parm (TYPE_MAX_VALUE (t),
6478                                      fn, data, pfd->visited,
6479                                      pfd->include_nondeduced_p))
6480         return error_mark_node;
6481       break;
6482
6483     case METHOD_TYPE:
6484       /* Since we're not going to walk subtrees, we have to do this
6485          explicitly here.  */
6486       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6487                                   pfd->visited, pfd->include_nondeduced_p))
6488         return error_mark_node;
6489       /* Fall through.  */
6490
6491     case FUNCTION_TYPE:
6492       /* Check the return type.  */
6493       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6494                                   pfd->include_nondeduced_p))
6495         return error_mark_node;
6496
6497       /* Check the parameter types.  Since default arguments are not
6498          instantiated until they are needed, the TYPE_ARG_TYPES may
6499          contain expressions that involve template parameters.  But,
6500          no-one should be looking at them yet.  And, once they're
6501          instantiated, they don't contain template parameters, so
6502          there's no point in looking at them then, either.  */
6503       {
6504         tree parm;
6505
6506         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6507           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6508                                       pfd->visited, pfd->include_nondeduced_p))
6509             return error_mark_node;
6510
6511         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6512            want walk_tree walking into them itself.  */
6513         *walk_subtrees = 0;
6514       }
6515       break;
6516
6517     case TYPEOF_TYPE:
6518       if (pfd->include_nondeduced_p
6519           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6520                                      pfd->visited, 
6521                                      pfd->include_nondeduced_p))
6522         return error_mark_node;
6523       break;
6524
6525     case FUNCTION_DECL:
6526     case VAR_DECL:
6527       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6528           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6529                                      pfd->visited, pfd->include_nondeduced_p))
6530         return error_mark_node;
6531       /* Fall through.  */
6532
6533     case PARM_DECL:
6534     case CONST_DECL:
6535       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6536           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6537                                      pfd->visited, pfd->include_nondeduced_p))
6538         return error_mark_node;
6539       if (DECL_CONTEXT (t)
6540           && pfd->include_nondeduced_p
6541           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6542                                      pfd->visited, pfd->include_nondeduced_p))
6543         return error_mark_node;
6544       break;
6545
6546     case BOUND_TEMPLATE_TEMPLATE_PARM:
6547       /* Record template parameters such as `T' inside `TT<T>'.  */
6548       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6549                                   pfd->include_nondeduced_p))
6550         return error_mark_node;
6551       /* Fall through.  */
6552
6553     case TEMPLATE_TEMPLATE_PARM:
6554     case TEMPLATE_TYPE_PARM:
6555     case TEMPLATE_PARM_INDEX:
6556       if (fn && (*fn)(t, data))
6557         return error_mark_node;
6558       else if (!fn)
6559         return error_mark_node;
6560       break;
6561
6562     case TEMPLATE_DECL:
6563       /* A template template parameter is encountered.  */
6564       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6565           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6566                                      pfd->include_nondeduced_p))
6567         return error_mark_node;
6568
6569       /* Already substituted template template parameter */
6570       *walk_subtrees = 0;
6571       break;
6572
6573     case TYPENAME_TYPE:
6574       if (!fn
6575           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6576                                      data, pfd->visited, 
6577                                      pfd->include_nondeduced_p))
6578         return error_mark_node;
6579       break;
6580
6581     case CONSTRUCTOR:
6582       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6583           && pfd->include_nondeduced_p
6584           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6585                                      (TREE_TYPE (t)), fn, data,
6586                                      pfd->visited, pfd->include_nondeduced_p))
6587         return error_mark_node;
6588       break;
6589
6590     case INDIRECT_REF:
6591     case COMPONENT_REF:
6592       /* If there's no type, then this thing must be some expression
6593          involving template parameters.  */
6594       if (!fn && !TREE_TYPE (t))
6595         return error_mark_node;
6596       break;
6597
6598     case MODOP_EXPR:
6599     case CAST_EXPR:
6600     case REINTERPRET_CAST_EXPR:
6601     case CONST_CAST_EXPR:
6602     case STATIC_CAST_EXPR:
6603     case DYNAMIC_CAST_EXPR:
6604     case ARROW_EXPR:
6605     case DOTSTAR_EXPR:
6606     case TYPEID_EXPR:
6607     case PSEUDO_DTOR_EXPR:
6608       if (!fn)
6609         return error_mark_node;
6610       break;
6611
6612     default:
6613       break;
6614     }
6615
6616   /* We didn't find any template parameters we liked.  */
6617   return NULL_TREE;
6618 }
6619
6620 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6621    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6622    call FN with the parameter and the DATA.
6623    If FN returns nonzero, the iteration is terminated, and
6624    for_each_template_parm returns 1.  Otherwise, the iteration
6625    continues.  If FN never returns a nonzero value, the value
6626    returned by for_each_template_parm is 0.  If FN is NULL, it is
6627    considered to be the function which always returns 1.
6628
6629    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6630    parameters that occur in non-deduced contexts.  When false, only
6631    visits those template parameters that can be deduced.  */
6632
6633 static int
6634 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6635                         struct pointer_set_t *visited,
6636                         bool include_nondeduced_p)
6637 {
6638   struct pair_fn_data pfd;
6639   int result;
6640
6641   /* Set up.  */
6642   pfd.fn = fn;
6643   pfd.data = data;
6644   pfd.include_nondeduced_p = include_nondeduced_p;
6645
6646   /* Walk the tree.  (Conceptually, we would like to walk without
6647      duplicates, but for_each_template_parm_r recursively calls
6648      for_each_template_parm, so we would need to reorganize a fair
6649      bit to use walk_tree_without_duplicates, so we keep our own
6650      visited list.)  */
6651   if (visited)
6652     pfd.visited = visited;
6653   else
6654     pfd.visited = pointer_set_create ();
6655   result = cp_walk_tree (&t,
6656                          for_each_template_parm_r,
6657                          &pfd,
6658                          pfd.visited) != NULL_TREE;
6659
6660   /* Clean up.  */
6661   if (!visited)
6662     {
6663       pointer_set_destroy (pfd.visited);
6664       pfd.visited = 0;
6665     }
6666
6667   return result;
6668 }
6669
6670 /* Returns true if T depends on any template parameter.  */
6671
6672 int
6673 uses_template_parms (tree t)
6674 {
6675   bool dependent_p;
6676   int saved_processing_template_decl;
6677
6678   saved_processing_template_decl = processing_template_decl;
6679   if (!saved_processing_template_decl)
6680     processing_template_decl = 1;
6681   if (TYPE_P (t))
6682     dependent_p = dependent_type_p (t);
6683   else if (TREE_CODE (t) == TREE_VEC)
6684     dependent_p = any_dependent_template_arguments_p (t);
6685   else if (TREE_CODE (t) == TREE_LIST)
6686     dependent_p = (uses_template_parms (TREE_VALUE (t))
6687                    || uses_template_parms (TREE_CHAIN (t)));
6688   else if (TREE_CODE (t) == TYPE_DECL)
6689     dependent_p = dependent_type_p (TREE_TYPE (t));
6690   else if (DECL_P (t)
6691            || EXPR_P (t)
6692            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6693            || TREE_CODE (t) == OVERLOAD
6694            || TREE_CODE (t) == BASELINK
6695            || TREE_CODE (t) == IDENTIFIER_NODE
6696            || TREE_CODE (t) == TRAIT_EXPR
6697            || TREE_CODE (t) == CONSTRUCTOR
6698            || CONSTANT_CLASS_P (t))
6699     dependent_p = (type_dependent_expression_p (t)
6700                    || value_dependent_expression_p (t));
6701   else
6702     {
6703       gcc_assert (t == error_mark_node);
6704       dependent_p = false;
6705     }
6706
6707   processing_template_decl = saved_processing_template_decl;
6708
6709   return dependent_p;
6710 }
6711
6712 /* Returns true if T depends on any template parameter with level LEVEL.  */
6713
6714 int
6715 uses_template_parms_level (tree t, int level)
6716 {
6717   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6718                                  /*include_nondeduced_p=*/true);
6719 }
6720
6721 static int tinst_depth;
6722 extern int max_tinst_depth;
6723 #ifdef GATHER_STATISTICS
6724 int depth_reached;
6725 #endif
6726 static int tinst_level_tick;
6727 static int last_template_error_tick;
6728
6729 /* We're starting to instantiate D; record the template instantiation context
6730    for diagnostics and to restore it later.  */
6731
6732 static int
6733 push_tinst_level (tree d)
6734 {
6735   struct tinst_level *new_level;
6736
6737   if (tinst_depth >= max_tinst_depth)
6738     {
6739       /* If the instantiation in question still has unbound template parms,
6740          we don't really care if we can't instantiate it, so just return.
6741          This happens with base instantiation for implicit `typename'.  */
6742       if (uses_template_parms (d))
6743         return 0;
6744
6745       last_template_error_tick = tinst_level_tick;
6746       error ("template instantiation depth exceeds maximum of %d (use "
6747              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6748              max_tinst_depth, d);
6749
6750       print_instantiation_context ();
6751
6752       return 0;
6753     }
6754
6755   new_level = GGC_NEW (struct tinst_level);
6756   new_level->decl = d;
6757   new_level->locus = input_location;
6758   new_level->in_system_header_p = in_system_header;
6759   new_level->next = current_tinst_level;
6760   current_tinst_level = new_level;
6761
6762   ++tinst_depth;
6763 #ifdef GATHER_STATISTICS
6764   if (tinst_depth > depth_reached)
6765     depth_reached = tinst_depth;
6766 #endif
6767
6768   ++tinst_level_tick;
6769   return 1;
6770 }
6771
6772 /* We're done instantiating this template; return to the instantiation
6773    context.  */
6774
6775 static void
6776 pop_tinst_level (void)
6777 {
6778   /* Restore the filename and line number stashed away when we started
6779      this instantiation.  */
6780   input_location = current_tinst_level->locus;
6781   current_tinst_level = current_tinst_level->next;
6782   --tinst_depth;
6783   ++tinst_level_tick;
6784 }
6785
6786 /* We're instantiating a deferred template; restore the template
6787    instantiation context in which the instantiation was requested, which
6788    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6789
6790 static tree
6791 reopen_tinst_level (struct tinst_level *level)
6792 {
6793   struct tinst_level *t;
6794
6795   tinst_depth = 0;
6796   for (t = level; t; t = t->next)
6797     ++tinst_depth;
6798
6799   current_tinst_level = level;
6800   pop_tinst_level ();
6801   return level->decl;
6802 }
6803
6804 /* Returns the TINST_LEVEL which gives the original instantiation
6805    context.  */
6806
6807 struct tinst_level *
6808 outermost_tinst_level (void)
6809 {
6810   struct tinst_level *level = current_tinst_level;
6811   if (level)
6812     while (level->next)
6813       level = level->next;
6814   return level;
6815 }
6816
6817 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
6818
6819 bool
6820 parameter_of_template_p (tree parm, tree templ)
6821 {
6822   tree parms;
6823   int i;
6824
6825   if (!parm || !templ)
6826     return false;
6827
6828   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
6829   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6830
6831   parms = DECL_TEMPLATE_PARMS (templ);
6832   parms = INNERMOST_TEMPLATE_PARMS (parms);
6833
6834   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
6835     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
6836       return true;
6837
6838   return false;
6839 }
6840
6841 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6842    vector of template arguments, as for tsubst.
6843
6844    Returns an appropriate tsubst'd friend declaration.  */
6845
6846 static tree
6847 tsubst_friend_function (tree decl, tree args)
6848 {
6849   tree new_friend;
6850
6851   if (TREE_CODE (decl) == FUNCTION_DECL
6852       && DECL_TEMPLATE_INSTANTIATION (decl)
6853       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6854     /* This was a friend declared with an explicit template
6855        argument list, e.g.:
6856
6857        friend void f<>(T);
6858
6859        to indicate that f was a template instantiation, not a new
6860        function declaration.  Now, we have to figure out what
6861        instantiation of what template.  */
6862     {
6863       tree template_id, arglist, fns;
6864       tree new_args;
6865       tree tmpl;
6866       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6867
6868       /* Friend functions are looked up in the containing namespace scope.
6869          We must enter that scope, to avoid finding member functions of the
6870          current class with same name.  */
6871       push_nested_namespace (ns);
6872       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6873                          tf_warning_or_error, NULL_TREE,
6874                          /*integral_constant_expression_p=*/false);
6875       pop_nested_namespace (ns);
6876       arglist = tsubst (DECL_TI_ARGS (decl), args,
6877                         tf_warning_or_error, NULL_TREE);
6878       template_id = lookup_template_function (fns, arglist);
6879
6880       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6881       tmpl = determine_specialization (template_id, new_friend,
6882                                        &new_args,
6883                                        /*need_member_template=*/0,
6884                                        TREE_VEC_LENGTH (args),
6885                                        tsk_none);
6886       return instantiate_template (tmpl, new_args, tf_error);
6887     }
6888
6889   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6890
6891   /* The NEW_FRIEND will look like an instantiation, to the
6892      compiler, but is not an instantiation from the point of view of
6893      the language.  For example, we might have had:
6894
6895      template <class T> struct S {
6896        template <class U> friend void f(T, U);
6897      };
6898
6899      Then, in S<int>, template <class U> void f(int, U) is not an
6900      instantiation of anything.  */
6901   if (new_friend == error_mark_node)
6902     return error_mark_node;
6903
6904   DECL_USE_TEMPLATE (new_friend) = 0;
6905   if (TREE_CODE (decl) == TEMPLATE_DECL)
6906     {
6907       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6908       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6909         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6910     }
6911
6912   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6913      is not a template instantiation and should not be mangled like
6914      one.  Therefore, we forget the mangling here; we'll recompute it
6915      later if we need it.  */
6916   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6917     {
6918       SET_DECL_RTL (new_friend, NULL_RTX);
6919       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6920     }
6921
6922   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6923     {
6924       tree old_decl;
6925       tree new_friend_template_info;
6926       tree new_friend_result_template_info;
6927       tree ns;
6928       int  new_friend_is_defn;
6929
6930       /* We must save some information from NEW_FRIEND before calling
6931          duplicate decls since that function will free NEW_FRIEND if
6932          possible.  */
6933       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6934       new_friend_is_defn =
6935             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6936                            (template_for_substitution (new_friend)))
6937              != NULL_TREE);
6938       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6939         {
6940           /* This declaration is a `primary' template.  */
6941           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6942
6943           new_friend_result_template_info
6944             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6945         }
6946       else
6947         new_friend_result_template_info = NULL_TREE;
6948
6949       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6950       if (new_friend_is_defn)
6951         DECL_INITIAL (new_friend) = error_mark_node;
6952
6953       /* Inside pushdecl_namespace_level, we will push into the
6954          current namespace. However, the friend function should go
6955          into the namespace of the template.  */
6956       ns = decl_namespace_context (new_friend);
6957       push_nested_namespace (ns);
6958       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6959       pop_nested_namespace (ns);
6960
6961       if (old_decl == error_mark_node)
6962         return error_mark_node;
6963
6964       if (old_decl != new_friend)
6965         {
6966           /* This new friend declaration matched an existing
6967              declaration.  For example, given:
6968
6969                template <class T> void f(T);
6970                template <class U> class C {
6971                  template <class T> friend void f(T) {}
6972                };
6973
6974              the friend declaration actually provides the definition
6975              of `f', once C has been instantiated for some type.  So,
6976              old_decl will be the out-of-class template declaration,
6977              while new_friend is the in-class definition.
6978
6979              But, if `f' was called before this point, the
6980              instantiation of `f' will have DECL_TI_ARGS corresponding
6981              to `T' but not to `U', references to which might appear
6982              in the definition of `f'.  Previously, the most general
6983              template for an instantiation of `f' was the out-of-class
6984              version; now it is the in-class version.  Therefore, we
6985              run through all specialization of `f', adding to their
6986              DECL_TI_ARGS appropriately.  In particular, they need a
6987              new set of outer arguments, corresponding to the
6988              arguments for this class instantiation.
6989
6990              The same situation can arise with something like this:
6991
6992                friend void f(int);
6993                template <class T> class C {
6994                  friend void f(T) {}
6995                };
6996
6997              when `C<int>' is instantiated.  Now, `f(int)' is defined
6998              in the class.  */
6999
7000           if (!new_friend_is_defn)
7001             /* On the other hand, if the in-class declaration does
7002                *not* provide a definition, then we don't want to alter
7003                existing definitions.  We can just leave everything
7004                alone.  */
7005             ;
7006           else
7007             {
7008               tree new_template = TI_TEMPLATE (new_friend_template_info);
7009               tree new_args = TI_ARGS (new_friend_template_info);
7010
7011               /* Overwrite whatever template info was there before, if
7012                  any, with the new template information pertaining to
7013                  the declaration.  */
7014               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7015
7016               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7017                 /* We should have called reregister_specialization in
7018                    duplicate_decls.  */
7019                 gcc_assert (retrieve_specialization (new_template,
7020                                                      new_args, 0)
7021                             == old_decl);
7022               else
7023                 {
7024                   tree t;
7025
7026                   /* Indicate that the old function template is a partial
7027                      instantiation.  */
7028                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7029                     = new_friend_result_template_info;
7030
7031                   gcc_assert (new_template
7032                               == most_general_template (new_template));
7033                   gcc_assert (new_template != old_decl);
7034
7035                   /* Reassign any specializations already in the hash table
7036                      to the new more general template, and add the
7037                      additional template args.  */
7038                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7039                        t != NULL_TREE;
7040                        t = TREE_CHAIN (t))
7041                     {
7042                       tree spec = TREE_VALUE (t);
7043                       spec_entry elt;
7044
7045                       elt.tmpl = old_decl;
7046                       elt.args = DECL_TI_ARGS (spec);
7047                       elt.spec = NULL_TREE;
7048
7049                       htab_remove_elt (decl_specializations, &elt);
7050
7051                       DECL_TI_ARGS (spec)
7052                         = add_outermost_template_args (new_args,
7053                                                        DECL_TI_ARGS (spec));
7054
7055                       register_specialization
7056                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7057
7058                     }
7059                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7060                 }
7061             }
7062
7063           /* The information from NEW_FRIEND has been merged into OLD_DECL
7064              by duplicate_decls.  */
7065           new_friend = old_decl;
7066         }
7067     }
7068   else
7069     {
7070       tree context = DECL_CONTEXT (new_friend);
7071       bool dependent_p;
7072
7073       /* In the code
7074            template <class T> class C {
7075              template <class U> friend void C1<U>::f (); // case 1
7076              friend void C2<T>::f ();                    // case 2
7077            };
7078          we only need to make sure CONTEXT is a complete type for
7079          case 2.  To distinguish between the two cases, we note that
7080          CONTEXT of case 1 remains dependent type after tsubst while
7081          this isn't true for case 2.  */
7082       ++processing_template_decl;
7083       dependent_p = dependent_type_p (context);
7084       --processing_template_decl;
7085
7086       if (!dependent_p
7087           && !complete_type_or_else (context, NULL_TREE))
7088         return error_mark_node;
7089
7090       if (COMPLETE_TYPE_P (context))
7091         {
7092           /* Check to see that the declaration is really present, and,
7093              possibly obtain an improved declaration.  */
7094           tree fn = check_classfn (context,
7095                                    new_friend, NULL_TREE);
7096
7097           if (fn)
7098             new_friend = fn;
7099         }
7100     }
7101
7102   return new_friend;
7103 }
7104
7105 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7106    template arguments, as for tsubst.
7107
7108    Returns an appropriate tsubst'd friend type or error_mark_node on
7109    failure.  */
7110
7111 static tree
7112 tsubst_friend_class (tree friend_tmpl, tree args)
7113 {
7114   tree friend_type;
7115   tree tmpl;
7116   tree context;
7117
7118   context = DECL_CONTEXT (friend_tmpl);
7119
7120   if (context)
7121     {
7122       if (TREE_CODE (context) == NAMESPACE_DECL)
7123         push_nested_namespace (context);
7124       else
7125         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7126     }
7127
7128   /* Look for a class template declaration.  We look for hidden names
7129      because two friend declarations of the same template are the
7130      same.  For example, in:
7131
7132        struct A { 
7133          template <typename> friend class F;
7134        };
7135        template <typename> struct B { 
7136          template <typename> friend class F;
7137        };
7138
7139      both F templates are the same.  */
7140   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7141                            /*block_p=*/true, 0, 
7142                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7143
7144   /* But, if we don't find one, it might be because we're in a
7145      situation like this:
7146
7147        template <class T>
7148        struct S {
7149          template <class U>
7150          friend struct S;
7151        };
7152
7153      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7154      for `S<int>', not the TEMPLATE_DECL.  */
7155   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7156     {
7157       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7158       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7159     }
7160
7161   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7162     {
7163       /* The friend template has already been declared.  Just
7164          check to see that the declarations match, and install any new
7165          default parameters.  We must tsubst the default parameters,
7166          of course.  We only need the innermost template parameters
7167          because that is all that redeclare_class_template will look
7168          at.  */
7169       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7170           > TMPL_ARGS_DEPTH (args))
7171         {
7172           tree parms;
7173           location_t saved_input_location;
7174           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7175                                          args, tf_warning_or_error);
7176
7177           saved_input_location = input_location;
7178           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7179           redeclare_class_template (TREE_TYPE (tmpl), parms);
7180           input_location = saved_input_location;
7181           
7182         }
7183
7184       friend_type = TREE_TYPE (tmpl);
7185     }
7186   else
7187     {
7188       /* The friend template has not already been declared.  In this
7189          case, the instantiation of the template class will cause the
7190          injection of this template into the global scope.  */
7191       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7192       if (tmpl == error_mark_node)
7193         return error_mark_node;
7194
7195       /* The new TMPL is not an instantiation of anything, so we
7196          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7197          the new type because that is supposed to be the corresponding
7198          template decl, i.e., TMPL.  */
7199       DECL_USE_TEMPLATE (tmpl) = 0;
7200       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7201       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7202       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7203         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7204
7205       /* Inject this template into the global scope.  */
7206       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7207     }
7208
7209   if (context)
7210     {
7211       if (TREE_CODE (context) == NAMESPACE_DECL)
7212         pop_nested_namespace (context);
7213       else
7214         pop_nested_class ();
7215     }
7216
7217   return friend_type;
7218 }
7219
7220 /* Returns zero if TYPE cannot be completed later due to circularity.
7221    Otherwise returns one.  */
7222
7223 static int
7224 can_complete_type_without_circularity (tree type)
7225 {
7226   if (type == NULL_TREE || type == error_mark_node)
7227     return 0;
7228   else if (COMPLETE_TYPE_P (type))
7229     return 1;
7230   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7231     return can_complete_type_without_circularity (TREE_TYPE (type));
7232   else if (CLASS_TYPE_P (type)
7233            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7234     return 0;
7235   else
7236     return 1;
7237 }
7238
7239 /* Apply any attributes which had to be deferred until instantiation
7240    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7241    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7242
7243 static void
7244 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7245                                 tree args, tsubst_flags_t complain, tree in_decl)
7246 {
7247   tree last_dep = NULL_TREE;
7248   tree t;
7249   tree *p;
7250
7251   for (t = attributes; t; t = TREE_CHAIN (t))
7252     if (ATTR_IS_DEPENDENT (t))
7253       {
7254         last_dep = t;
7255         attributes = copy_list (attributes);
7256         break;
7257       }
7258
7259   if (DECL_P (*decl_p))
7260     {
7261       if (TREE_TYPE (*decl_p) == error_mark_node)
7262         return;
7263       p = &DECL_ATTRIBUTES (*decl_p);
7264     }
7265   else
7266     p = &TYPE_ATTRIBUTES (*decl_p);
7267
7268   if (last_dep)
7269     {
7270       tree late_attrs = NULL_TREE;
7271       tree *q = &late_attrs;
7272
7273       for (*p = attributes; *p; )
7274         {
7275           t = *p;
7276           if (ATTR_IS_DEPENDENT (t))
7277             {
7278               *p = TREE_CHAIN (t);
7279               TREE_CHAIN (t) = NULL_TREE;
7280               /* If the first attribute argument is an identifier, don't
7281                  pass it through tsubst.  Attributes like mode, format,
7282                  cleanup and several target specific attributes expect it
7283                  unmodified.  */
7284               if (TREE_VALUE (t)
7285                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7286                   && TREE_VALUE (TREE_VALUE (t))
7287                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7288                       == IDENTIFIER_NODE))
7289                 {
7290                   tree chain
7291                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7292                                    in_decl,
7293                                    /*integral_constant_expression_p=*/false);
7294                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7295                     TREE_VALUE (t)
7296                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7297                                    chain);
7298                 }
7299               else
7300                 TREE_VALUE (t)
7301                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7302                                  /*integral_constant_expression_p=*/false);
7303               *q = t;
7304               q = &TREE_CHAIN (t);
7305             }
7306           else
7307             p = &TREE_CHAIN (t);
7308         }
7309
7310       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7311     }
7312 }
7313
7314 /* Perform (or defer) access check for typedefs that were referenced
7315    from within the template TMPL code.
7316    This is a subroutine of instantiate_template and instantiate_class_template.
7317    TMPL is the template to consider and TARGS is the list of arguments of
7318    that template.  */
7319
7320 static void
7321 perform_typedefs_access_check (tree tmpl, tree targs)
7322 {
7323   tree t;
7324
7325   if (!tmpl
7326       || (!CLASS_TYPE_P (tmpl)
7327           && TREE_CODE (tmpl) != FUNCTION_DECL))
7328     return;
7329
7330   for (t = get_types_needing_access_check (tmpl); t; t = TREE_CHAIN (t))
7331     {
7332       tree type_decl = TREE_PURPOSE (t);
7333       tree type_scope = TREE_VALUE (t);
7334
7335       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7336         continue;
7337
7338       if (uses_template_parms (type_decl))
7339         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7340       if (uses_template_parms (type_scope))
7341         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7342
7343       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7344                                      type_decl, type_decl);
7345     }
7346 }
7347
7348 tree
7349 instantiate_class_template (tree type)
7350 {
7351   tree templ, args, pattern, t, member;
7352   tree typedecl;
7353   tree pbinfo;
7354   tree base_list;
7355   unsigned int saved_maximum_field_alignment;
7356
7357   if (type == error_mark_node)
7358     return error_mark_node;
7359
7360   if (TYPE_BEING_DEFINED (type)
7361       || COMPLETE_TYPE_P (type)
7362       || uses_template_parms (type))
7363     return type;
7364
7365   /* Figure out which template is being instantiated.  */
7366   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7367   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7368
7369   /* Determine what specialization of the original template to
7370      instantiate.  */
7371   t = most_specialized_class (type, templ);
7372   if (t == error_mark_node)
7373     {
7374       TYPE_BEING_DEFINED (type) = 1;
7375       return error_mark_node;
7376     }
7377   else if (t)
7378     {
7379       /* This TYPE is actually an instantiation of a partial
7380          specialization.  We replace the innermost set of ARGS with
7381          the arguments appropriate for substitution.  For example,
7382          given:
7383
7384            template <class T> struct S {};
7385            template <class T> struct S<T*> {};
7386
7387          and supposing that we are instantiating S<int*>, ARGS will
7388          presently be {int*} -- but we need {int}.  */
7389       pattern = TREE_TYPE (t);
7390       args = TREE_PURPOSE (t);
7391     }
7392   else
7393     {
7394       pattern = TREE_TYPE (templ);
7395       args = CLASSTYPE_TI_ARGS (type);
7396     }
7397
7398   /* If the template we're instantiating is incomplete, then clearly
7399      there's nothing we can do.  */
7400   if (!COMPLETE_TYPE_P (pattern))
7401     return type;
7402
7403   /* If we've recursively instantiated too many templates, stop.  */
7404   if (! push_tinst_level (type))
7405     return type;
7406
7407   /* Now we're really doing the instantiation.  Mark the type as in
7408      the process of being defined.  */
7409   TYPE_BEING_DEFINED (type) = 1;
7410
7411   /* We may be in the middle of deferred access check.  Disable
7412      it now.  */
7413   push_deferring_access_checks (dk_no_deferred);
7414
7415   push_to_top_level ();
7416   /* Use #pragma pack from the template context.  */
7417   saved_maximum_field_alignment = maximum_field_alignment;
7418   maximum_field_alignment = TYPE_PRECISION (pattern);
7419
7420   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7421
7422   /* Set the input location to the most specialized template definition.
7423      This is needed if tsubsting causes an error.  */
7424   typedecl = TYPE_MAIN_DECL (pattern);
7425   input_location = DECL_SOURCE_LOCATION (typedecl);
7426
7427   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7428   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7429   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7430   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7431   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7432   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7433   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7434   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7435   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7436   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7437   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7438   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7439   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7440   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7441   if (ANON_AGGR_TYPE_P (pattern))
7442     SET_ANON_AGGR_TYPE_P (type);
7443   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7444     {
7445       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7446       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7447     }
7448
7449   pbinfo = TYPE_BINFO (pattern);
7450
7451   /* We should never instantiate a nested class before its enclosing
7452      class; we need to look up the nested class by name before we can
7453      instantiate it, and that lookup should instantiate the enclosing
7454      class.  */
7455   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7456               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7457               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7458
7459   base_list = NULL_TREE;
7460   if (BINFO_N_BASE_BINFOS (pbinfo))
7461     {
7462       tree pbase_binfo;
7463       tree context = TYPE_CONTEXT (type);
7464       tree pushed_scope;
7465       int i;
7466
7467       /* We must enter the scope containing the type, as that is where
7468          the accessibility of types named in dependent bases are
7469          looked up from.  */
7470       pushed_scope = push_scope (context ? context : global_namespace);
7471
7472       /* Substitute into each of the bases to determine the actual
7473          basetypes.  */
7474       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7475         {
7476           tree base;
7477           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7478           tree expanded_bases = NULL_TREE;
7479           int idx, len = 1;
7480
7481           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7482             {
7483               expanded_bases = 
7484                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7485                                        args, tf_error, NULL_TREE);
7486               if (expanded_bases == error_mark_node)
7487                 continue;
7488
7489               len = TREE_VEC_LENGTH (expanded_bases);
7490             }
7491
7492           for (idx = 0; idx < len; idx++)
7493             {
7494               if (expanded_bases)
7495                 /* Extract the already-expanded base class.  */
7496                 base = TREE_VEC_ELT (expanded_bases, idx);
7497               else
7498                 /* Substitute to figure out the base class.  */
7499                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7500                                NULL_TREE);
7501
7502               if (base == error_mark_node)
7503                 continue;
7504
7505               base_list = tree_cons (access, base, base_list);
7506               if (BINFO_VIRTUAL_P (pbase_binfo))
7507                 TREE_TYPE (base_list) = integer_type_node;
7508             }
7509         }
7510
7511       /* The list is now in reverse order; correct that.  */
7512       base_list = nreverse (base_list);
7513
7514       if (pushed_scope)
7515         pop_scope (pushed_scope);
7516     }
7517   /* Now call xref_basetypes to set up all the base-class
7518      information.  */
7519   xref_basetypes (type, base_list);
7520
7521   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7522                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7523                                   args, tf_error, NULL_TREE);
7524
7525   /* Now that our base classes are set up, enter the scope of the
7526      class, so that name lookups into base classes, etc. will work
7527      correctly.  This is precisely analogous to what we do in
7528      begin_class_definition when defining an ordinary non-template
7529      class, except we also need to push the enclosing classes.  */
7530   push_nested_class (type);
7531
7532   /* Now members are processed in the order of declaration.  */
7533   for (member = CLASSTYPE_DECL_LIST (pattern);
7534        member; member = TREE_CHAIN (member))
7535     {
7536       tree t = TREE_VALUE (member);
7537
7538       if (TREE_PURPOSE (member))
7539         {
7540           if (TYPE_P (t))
7541             {
7542               /* Build new CLASSTYPE_NESTED_UTDS.  */
7543
7544               tree newtag;
7545               bool class_template_p;
7546
7547               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7548                                   && TYPE_LANG_SPECIFIC (t)
7549                                   && CLASSTYPE_IS_TEMPLATE (t));
7550               /* If the member is a class template, then -- even after
7551                  substitution -- there may be dependent types in the
7552                  template argument list for the class.  We increment
7553                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7554                  that function will assume that no types are dependent
7555                  when outside of a template.  */
7556               if (class_template_p)
7557                 ++processing_template_decl;
7558               newtag = tsubst (t, args, tf_error, NULL_TREE);
7559               if (class_template_p)
7560                 --processing_template_decl;
7561               if (newtag == error_mark_node)
7562                 continue;
7563
7564               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7565                 {
7566                   tree name = TYPE_IDENTIFIER (t);
7567
7568                   if (class_template_p)
7569                     /* Unfortunately, lookup_template_class sets
7570                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7571                        instantiation (i.e., for the type of a member
7572                        template class nested within a template class.)
7573                        This behavior is required for
7574                        maybe_process_partial_specialization to work
7575                        correctly, but is not accurate in this case;
7576                        the TAG is not an instantiation of anything.
7577                        (The corresponding TEMPLATE_DECL is an
7578                        instantiation, but the TYPE is not.) */
7579                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7580
7581                   /* Now, we call pushtag to put this NEWTAG into the scope of
7582                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7583                      pushtag calling push_template_decl.  We don't have to do
7584                      this for enums because it will already have been done in
7585                      tsubst_enum.  */
7586                   if (name)
7587                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7588                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7589                 }
7590             }
7591           else if (TREE_CODE (t) == FUNCTION_DECL
7592                    || DECL_FUNCTION_TEMPLATE_P (t))
7593             {
7594               /* Build new TYPE_METHODS.  */
7595               tree r;
7596
7597               if (TREE_CODE (t) == TEMPLATE_DECL)
7598                 ++processing_template_decl;
7599               r = tsubst (t, args, tf_error, NULL_TREE);
7600               if (TREE_CODE (t) == TEMPLATE_DECL)
7601                 --processing_template_decl;
7602               set_current_access_from_decl (r);
7603               finish_member_declaration (r);
7604             }
7605           else
7606             {
7607               /* Build new TYPE_FIELDS.  */
7608               if (TREE_CODE (t) == STATIC_ASSERT)
7609                 {
7610                   tree condition = 
7611                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7612                                  tf_warning_or_error, NULL_TREE,
7613                                  /*integral_constant_expression_p=*/true);
7614                   finish_static_assert (condition,
7615                                         STATIC_ASSERT_MESSAGE (t), 
7616                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7617                                         /*member_p=*/true);
7618                 }
7619               else if (TREE_CODE (t) != CONST_DECL)
7620                 {
7621                   tree r;
7622
7623                   /* The file and line for this declaration, to
7624                      assist in error message reporting.  Since we
7625                      called push_tinst_level above, we don't need to
7626                      restore these.  */
7627                   input_location = DECL_SOURCE_LOCATION (t);
7628
7629                   if (TREE_CODE (t) == TEMPLATE_DECL)
7630                     ++processing_template_decl;
7631                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7632                   if (TREE_CODE (t) == TEMPLATE_DECL)
7633                     --processing_template_decl;
7634                   if (TREE_CODE (r) == VAR_DECL)
7635                     {
7636                       /* In [temp.inst]:
7637
7638                            [t]he initialization (and any associated
7639                            side-effects) of a static data member does
7640                            not occur unless the static data member is
7641                            itself used in a way that requires the
7642                            definition of the static data member to
7643                            exist.
7644
7645                          Therefore, we do not substitute into the
7646                          initialized for the static data member here.  */
7647                       finish_static_data_member_decl
7648                         (r,
7649                          /*init=*/NULL_TREE,
7650                          /*init_const_expr_p=*/false,
7651                          /*asmspec_tree=*/NULL_TREE,
7652                          /*flags=*/0);
7653                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7654                         check_static_variable_definition (r, TREE_TYPE (r));
7655                     }
7656                   else if (TREE_CODE (r) == FIELD_DECL)
7657                     {
7658                       /* Determine whether R has a valid type and can be
7659                          completed later.  If R is invalid, then it is
7660                          replaced by error_mark_node so that it will not be
7661                          added to TYPE_FIELDS.  */
7662                       tree rtype = TREE_TYPE (r);
7663                       if (can_complete_type_without_circularity (rtype))
7664                         complete_type (rtype);
7665
7666                       if (!COMPLETE_TYPE_P (rtype))
7667                         {
7668                           cxx_incomplete_type_error (r, rtype);
7669                           r = error_mark_node;
7670                         }
7671                     }
7672
7673                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7674                      such a thing will already have been added to the field
7675                      list by tsubst_enum in finish_member_declaration in the
7676                      CLASSTYPE_NESTED_UTDS case above.  */
7677                   if (!(TREE_CODE (r) == TYPE_DECL
7678                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7679                         && DECL_ARTIFICIAL (r)))
7680                     {
7681                       set_current_access_from_decl (r);
7682                       finish_member_declaration (r);
7683                     }
7684                 }
7685             }
7686         }
7687       else
7688         {
7689           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7690             {
7691               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7692
7693               tree friend_type = t;
7694               bool adjust_processing_template_decl = false;
7695
7696               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7697                 {
7698                   /* template <class T> friend class C;  */
7699                   friend_type = tsubst_friend_class (friend_type, args);
7700                   adjust_processing_template_decl = true;
7701                 }
7702               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7703                 {
7704                   /* template <class T> friend class C::D;  */
7705                   friend_type = tsubst (friend_type, args,
7706                                         tf_warning_or_error, NULL_TREE);
7707                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7708                     friend_type = TREE_TYPE (friend_type);
7709                   adjust_processing_template_decl = true;
7710                 }
7711               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7712                 {
7713                   /* This could be either
7714
7715                        friend class T::C;
7716
7717                      when dependent_type_p is false or
7718
7719                        template <class U> friend class T::C;
7720
7721                      otherwise.  */
7722                   friend_type = tsubst (friend_type, args,
7723                                         tf_warning_or_error, NULL_TREE);
7724                   /* Bump processing_template_decl for correct
7725                      dependent_type_p calculation.  */
7726                   ++processing_template_decl;
7727                   if (dependent_type_p (friend_type))
7728                     adjust_processing_template_decl = true;
7729                   --processing_template_decl;
7730                 }
7731               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7732                        && hidden_name_p (TYPE_NAME (friend_type)))
7733                 {
7734                   /* friend class C;
7735
7736                      where C hasn't been declared yet.  Let's lookup name
7737                      from namespace scope directly, bypassing any name that
7738                      come from dependent base class.  */
7739                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7740
7741                   /* The call to xref_tag_from_type does injection for friend
7742                      classes.  */
7743                   push_nested_namespace (ns);
7744                   friend_type =
7745                     xref_tag_from_type (friend_type, NULL_TREE,
7746                                         /*tag_scope=*/ts_current);
7747                   pop_nested_namespace (ns);
7748                 }
7749               else if (uses_template_parms (friend_type))
7750                 /* friend class C<T>;  */
7751                 friend_type = tsubst (friend_type, args,
7752                                       tf_warning_or_error, NULL_TREE);
7753               /* Otherwise it's
7754
7755                    friend class C;
7756
7757                  where C is already declared or
7758
7759                    friend class C<int>;
7760
7761                  We don't have to do anything in these cases.  */
7762
7763               if (adjust_processing_template_decl)
7764                 /* Trick make_friend_class into realizing that the friend
7765                    we're adding is a template, not an ordinary class.  It's
7766                    important that we use make_friend_class since it will
7767                    perform some error-checking and output cross-reference
7768                    information.  */
7769                 ++processing_template_decl;
7770
7771               if (friend_type != error_mark_node)
7772                 make_friend_class (type, friend_type, /*complain=*/false);
7773
7774               if (adjust_processing_template_decl)
7775                 --processing_template_decl;
7776             }
7777           else
7778             {
7779               /* Build new DECL_FRIENDLIST.  */
7780               tree r;
7781
7782               /* The file and line for this declaration, to
7783                  assist in error message reporting.  Since we
7784                  called push_tinst_level above, we don't need to
7785                  restore these.  */
7786               input_location = DECL_SOURCE_LOCATION (t);
7787
7788               if (TREE_CODE (t) == TEMPLATE_DECL)
7789                 {
7790                   ++processing_template_decl;
7791                   push_deferring_access_checks (dk_no_check);
7792                 }
7793
7794               r = tsubst_friend_function (t, args);
7795               add_friend (type, r, /*complain=*/false);
7796               if (TREE_CODE (t) == TEMPLATE_DECL)
7797                 {
7798                   pop_deferring_access_checks ();
7799                   --processing_template_decl;
7800                 }
7801             }
7802         }
7803     }
7804
7805   /* Set the file and line number information to whatever is given for
7806      the class itself.  This puts error messages involving generated
7807      implicit functions at a predictable point, and the same point
7808      that would be used for non-template classes.  */
7809   input_location = DECL_SOURCE_LOCATION (typedecl);
7810
7811   unreverse_member_declarations (type);
7812   finish_struct_1 (type);
7813   TYPE_BEING_DEFINED (type) = 0;
7814
7815   /* Now that the class is complete, instantiate default arguments for
7816      any member functions.  We don't do this earlier because the
7817      default arguments may reference members of the class.  */
7818   if (!PRIMARY_TEMPLATE_P (templ))
7819     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7820       if (TREE_CODE (t) == FUNCTION_DECL
7821           /* Implicitly generated member functions will not have template
7822              information; they are not instantiations, but instead are
7823              created "fresh" for each instantiation.  */
7824           && DECL_TEMPLATE_INFO (t))
7825         tsubst_default_arguments (t);
7826
7827   /* Some typedefs referenced from within the template code need to be access
7828      checked at template instantiation time, i.e now. These types were
7829      added to the template at parsing time. Let's get those and perform
7830      the access checks then.  */
7831   perform_typedefs_access_check (pattern, args);
7832   perform_deferred_access_checks ();
7833   pop_nested_class ();
7834   maximum_field_alignment = saved_maximum_field_alignment;
7835   pop_from_top_level ();
7836   pop_deferring_access_checks ();
7837   pop_tinst_level ();
7838
7839   /* The vtable for a template class can be emitted in any translation
7840      unit in which the class is instantiated.  When there is no key
7841      method, however, finish_struct_1 will already have added TYPE to
7842      the keyed_classes list.  */
7843   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7844     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7845
7846   return type;
7847 }
7848
7849 static tree
7850 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7851 {
7852   tree r;
7853
7854   if (!t)
7855     r = t;
7856   else if (TYPE_P (t))
7857     r = tsubst (t, args, complain, in_decl);
7858   else
7859     {
7860       r = tsubst_expr (t, args, complain, in_decl,
7861                        /*integral_constant_expression_p=*/true);
7862       r = fold_non_dependent_expr (r);
7863     }
7864   return r;
7865 }
7866
7867 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
7868    NONTYPE_ARGUMENT_PACK.  */
7869
7870 static tree
7871 make_fnparm_pack (tree spec_parm)
7872 {
7873   /* Collect all of the extra "packed" parameters into an
7874      argument pack.  */
7875   tree parmvec;
7876   tree parmtypevec;
7877   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
7878   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
7879   int i, len = list_length (spec_parm);
7880
7881   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
7882   parmvec = make_tree_vec (len);
7883   parmtypevec = make_tree_vec (len);
7884   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
7885     {
7886       TREE_VEC_ELT (parmvec, i) = spec_parm;
7887       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
7888     }
7889
7890   /* Build the argument packs.  */
7891   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
7892   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
7893   TREE_TYPE (argpack) = argtypepack;
7894
7895   return argpack;
7896 }        
7897
7898 /* Substitute ARGS into T, which is an pack expansion
7899    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7900    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7901    (if only a partial substitution could be performed) or
7902    ERROR_MARK_NODE if there was an error.  */
7903 tree
7904 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7905                        tree in_decl)
7906 {
7907   tree pattern;
7908   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7909   tree first_arg_pack; int i, len = -1;
7910   tree result;
7911   int incomplete = 0;
7912   bool very_local_specializations = false;
7913
7914   gcc_assert (PACK_EXPANSION_P (t));
7915   pattern = PACK_EXPANSION_PATTERN (t);
7916
7917   /* Determine the argument packs that will instantiate the parameter
7918      packs used in the expansion expression. While we're at it,
7919      compute the number of arguments to be expanded and make sure it
7920      is consistent.  */
7921   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7922        pack = TREE_CHAIN (pack))
7923     {
7924       tree parm_pack = TREE_VALUE (pack);
7925       tree arg_pack = NULL_TREE;
7926       tree orig_arg = NULL_TREE;
7927
7928       if (TREE_CODE (parm_pack) == PARM_DECL)
7929         {
7930           arg_pack = retrieve_local_specialization (parm_pack);
7931           if (arg_pack == NULL_TREE)
7932             {
7933               /* This can happen for a parameter name used later in a function
7934                  declaration (such as in a late-specified return type).  Just
7935                  make a dummy decl, since it's only used for its type.  */
7936               gcc_assert (cp_unevaluated_operand != 0);
7937               arg_pack = tsubst_decl (parm_pack, args, complain);
7938               arg_pack = make_fnparm_pack (arg_pack);
7939             }
7940         }
7941       else
7942         {
7943           int level, idx, levels;
7944           template_parm_level_and_index (parm_pack, &level, &idx);
7945
7946           levels = TMPL_ARGS_DEPTH (args);
7947           if (level <= levels)
7948             arg_pack = TMPL_ARG (args, level, idx);
7949         }
7950
7951       orig_arg = arg_pack;
7952       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7953         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7954       
7955       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7956         /* This can only happen if we forget to expand an argument
7957            pack somewhere else. Just return an error, silently.  */
7958         {
7959           result = make_tree_vec (1);
7960           TREE_VEC_ELT (result, 0) = error_mark_node;
7961           return result;
7962         }
7963
7964       if (arg_pack
7965           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
7966           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
7967         {
7968           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
7969           tree pattern = PACK_EXPANSION_PATTERN (expansion);
7970           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
7971               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
7972             /* The argument pack that the parameter maps to is just an
7973                expansion of the parameter itself, such as one would
7974                find in the implicit typedef of a class inside the
7975                class itself.  Consider this parameter "unsubstituted",
7976                so that we will maintain the outer pack expansion.  */
7977             arg_pack = NULL_TREE;
7978         }
7979           
7980       if (arg_pack)
7981         {
7982           int my_len = 
7983             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7984
7985           /* It's all-or-nothing with incomplete argument packs.  */
7986           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7987             return error_mark_node;
7988           
7989           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7990             incomplete = 1;
7991
7992           if (len < 0)
7993             {
7994               len = my_len;
7995               first_arg_pack = arg_pack;
7996             }
7997           else if (len != my_len)
7998             {
7999               if (incomplete)
8000                 /* We got explicit args for some packs but not others;
8001                    do nothing now and try again after deduction.  */
8002                 return t;
8003               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8004                 error ("mismatched argument pack lengths while expanding "
8005                        "%<%T%>",
8006                        pattern);
8007               else
8008                 error ("mismatched argument pack lengths while expanding "
8009                        "%<%E%>",
8010                        pattern);
8011               return error_mark_node;
8012             }
8013
8014           /* Keep track of the parameter packs and their corresponding
8015              argument packs.  */
8016           packs = tree_cons (parm_pack, arg_pack, packs);
8017           TREE_TYPE (packs) = orig_arg;
8018         }
8019       else
8020         /* We can't substitute for this parameter pack.  */
8021         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8022                                          TREE_VALUE (pack),
8023                                          unsubstituted_packs);
8024     }
8025
8026   /* We cannot expand this expansion expression, because we don't have
8027      all of the argument packs we need. Substitute into the pattern
8028      and return a PACK_EXPANSION_*. The caller will need to deal with
8029      that.  */
8030   if (unsubstituted_packs)
8031     {
8032       tree new_pat;
8033       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8034         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8035                                /*integral_constant_expression_p=*/false);
8036       else
8037         new_pat = tsubst (pattern, args, complain, in_decl);
8038       return make_pack_expansion (new_pat);
8039     }
8040
8041   /* We could not find any argument packs that work.  */
8042   if (len < 0)
8043     return error_mark_node;
8044
8045   if (!local_specializations)
8046     {
8047       /* We're in a late-specified return type, so we don't have a local
8048          specializations table.  Create one for doing this expansion.  */
8049       very_local_specializations = true;
8050       local_specializations = htab_create (37,
8051                                            hash_local_specialization,
8052                                            eq_local_specializations,
8053                                            NULL);
8054     }
8055
8056   /* For each argument in each argument pack, substitute into the
8057      pattern.  */
8058   result = make_tree_vec (len + incomplete);
8059   for (i = 0; i < len + incomplete; ++i)
8060     {
8061       /* For parameter pack, change the substitution of the parameter
8062          pack to the ith argument in its argument pack, then expand
8063          the pattern.  */
8064       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8065         {
8066           tree parm = TREE_PURPOSE (pack);
8067
8068           if (TREE_CODE (parm) == PARM_DECL)
8069             {
8070               /* Select the Ith argument from the pack.  */
8071               tree arg = make_node (ARGUMENT_PACK_SELECT);
8072               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8073               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8074               mark_used (parm);
8075               register_local_specialization (arg, parm);
8076             }
8077           else
8078             {
8079               tree value = parm;
8080               int idx, level;
8081               template_parm_level_and_index (parm, &level, &idx);
8082               
8083               if (i < len) 
8084                 {
8085                   /* Select the Ith argument from the pack. */
8086                   value = make_node (ARGUMENT_PACK_SELECT);
8087                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8088                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8089                 }
8090
8091               /* Update the corresponding argument.  */
8092               TMPL_ARG (args, level, idx) = value;
8093             }
8094         }
8095
8096       /* Substitute into the PATTERN with the altered arguments.  */
8097       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8098         TREE_VEC_ELT (result, i) = 
8099           tsubst_expr (pattern, args, complain, in_decl,
8100                        /*integral_constant_expression_p=*/false);
8101       else
8102         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8103
8104       if (i == len)
8105         /* When we have incomplete argument packs, the last "expanded"
8106            result is itself a pack expansion, which allows us
8107            to deduce more arguments.  */
8108         TREE_VEC_ELT (result, i) = 
8109           make_pack_expansion (TREE_VEC_ELT (result, i));
8110
8111       if (TREE_VEC_ELT (result, i) == error_mark_node)
8112         {
8113           result = error_mark_node;
8114           break;
8115         }
8116     }
8117
8118   /* Update ARGS to restore the substitution from parameter packs to
8119      their argument packs.  */
8120   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8121     {
8122       tree parm = TREE_PURPOSE (pack);
8123
8124       if (TREE_CODE (parm) == PARM_DECL)
8125         register_local_specialization (TREE_TYPE (pack), parm);
8126       else
8127         {
8128           int idx, level;
8129           template_parm_level_and_index (parm, &level, &idx);
8130           
8131           /* Update the corresponding argument.  */
8132           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8133             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8134               TREE_TYPE (pack);
8135           else
8136             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8137         }
8138     }
8139
8140   if (very_local_specializations)
8141     {
8142       htab_delete (local_specializations);
8143       local_specializations = NULL;
8144     }
8145   
8146   return result;
8147 }
8148
8149 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8150    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8151    parameter packs; all parms generated from a function parameter pack will
8152    have the same DECL_PARM_INDEX.  */
8153
8154 tree
8155 get_pattern_parm (tree parm, tree tmpl)
8156 {
8157   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8158   tree patparm;
8159
8160   if (DECL_ARTIFICIAL (parm))
8161     {
8162       for (patparm = DECL_ARGUMENTS (pattern);
8163            patparm; patparm = TREE_CHAIN (patparm))
8164         if (DECL_ARTIFICIAL (patparm)
8165             && DECL_NAME (parm) == DECL_NAME (patparm))
8166           break;
8167     }
8168   else
8169     {
8170       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8171       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8172       gcc_assert (DECL_PARM_INDEX (patparm)
8173                   == DECL_PARM_INDEX (parm));
8174     }
8175
8176   return patparm;
8177 }
8178
8179 /* Substitute ARGS into the vector or list of template arguments T.  */
8180
8181 static tree
8182 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8183 {
8184   tree orig_t = t;
8185   int len = TREE_VEC_LENGTH (t);
8186   int need_new = 0, i, expanded_len_adjust = 0, out;
8187   tree *elts = (tree *) alloca (len * sizeof (tree));
8188
8189   for (i = 0; i < len; i++)
8190     {
8191       tree orig_arg = TREE_VEC_ELT (t, i);
8192       tree new_arg;
8193
8194       if (TREE_CODE (orig_arg) == TREE_VEC)
8195         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8196       else if (PACK_EXPANSION_P (orig_arg))
8197         {
8198           /* Substitute into an expansion expression.  */
8199           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8200
8201           if (TREE_CODE (new_arg) == TREE_VEC)
8202             /* Add to the expanded length adjustment the number of
8203                expanded arguments. We subtract one from this
8204                measurement, because the argument pack expression
8205                itself is already counted as 1 in
8206                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8207                the argument pack is empty.  */
8208             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8209         }
8210       else if (ARGUMENT_PACK_P (orig_arg))
8211         {
8212           /* Substitute into each of the arguments.  */
8213           new_arg = TYPE_P (orig_arg)
8214             ? cxx_make_type (TREE_CODE (orig_arg))
8215             : make_node (TREE_CODE (orig_arg));
8216           
8217           SET_ARGUMENT_PACK_ARGS (
8218             new_arg,
8219             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8220                                   args, complain, in_decl));
8221
8222           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8223             new_arg = error_mark_node;
8224
8225           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8226             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8227                                           complain, in_decl);
8228             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8229
8230             if (TREE_TYPE (new_arg) == error_mark_node)
8231               new_arg = error_mark_node;
8232           }
8233         }
8234       else
8235         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8236
8237       if (new_arg == error_mark_node)
8238         return error_mark_node;
8239
8240       elts[i] = new_arg;
8241       if (new_arg != orig_arg)
8242         need_new = 1;
8243     }
8244
8245   if (!need_new)
8246     return t;
8247
8248   /* Make space for the expanded arguments coming from template
8249      argument packs.  */
8250   t = make_tree_vec (len + expanded_len_adjust);
8251   for (i = 0, out = 0; i < len; i++)
8252     {
8253       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8254            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8255           && TREE_CODE (elts[i]) == TREE_VEC)
8256         {
8257           int idx;
8258
8259           /* Now expand the template argument pack "in place".  */
8260           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8261             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8262         }
8263       else
8264         {
8265           TREE_VEC_ELT (t, out) = elts[i];
8266           out++;
8267         }
8268     }
8269
8270   return t;
8271 }
8272
8273 /* Return the result of substituting ARGS into the template parameters
8274    given by PARMS.  If there are m levels of ARGS and m + n levels of
8275    PARMS, then the result will contain n levels of PARMS.  For
8276    example, if PARMS is `template <class T> template <class U>
8277    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8278    result will be `template <int*, double, class V>'.  */
8279
8280 static tree
8281 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8282 {
8283   tree r = NULL_TREE;
8284   tree* new_parms;
8285
8286   /* When substituting into a template, we must set
8287      PROCESSING_TEMPLATE_DECL as the template parameters may be
8288      dependent if they are based on one-another, and the dependency
8289      predicates are short-circuit outside of templates.  */
8290   ++processing_template_decl;
8291
8292   for (new_parms = &r;
8293        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8294        new_parms = &(TREE_CHAIN (*new_parms)),
8295          parms = TREE_CHAIN (parms))
8296     {
8297       tree new_vec =
8298         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8299       int i;
8300
8301       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8302         {
8303           tree tuple;
8304           tree default_value;
8305           tree parm_decl;
8306
8307           if (parms == error_mark_node)
8308             continue;
8309
8310           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8311
8312           if (tuple == error_mark_node)
8313             continue;
8314
8315           default_value = TREE_PURPOSE (tuple);
8316           parm_decl = TREE_VALUE (tuple);
8317
8318           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8319           if (TREE_CODE (parm_decl) == PARM_DECL
8320               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8321             parm_decl = error_mark_node;
8322           default_value = tsubst_template_arg (default_value, args,
8323                                                complain, NULL_TREE);
8324
8325           tuple = build_tree_list (default_value, parm_decl);
8326           TREE_VEC_ELT (new_vec, i) = tuple;
8327         }
8328
8329       *new_parms =
8330         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8331                              - TMPL_ARGS_DEPTH (args)),
8332                    new_vec, NULL_TREE);
8333     }
8334
8335   --processing_template_decl;
8336
8337   return r;
8338 }
8339
8340 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8341    type T.  If T is not an aggregate or enumeration type, it is
8342    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8343    ENTERING_SCOPE is nonzero, T is the context for a template which
8344    we are presently tsubst'ing.  Return the substituted value.  */
8345
8346 static tree
8347 tsubst_aggr_type (tree t,
8348                   tree args,
8349                   tsubst_flags_t complain,
8350                   tree in_decl,
8351                   int entering_scope)
8352 {
8353   if (t == NULL_TREE)
8354     return NULL_TREE;
8355
8356   switch (TREE_CODE (t))
8357     {
8358     case RECORD_TYPE:
8359       if (TYPE_PTRMEMFUNC_P (t))
8360         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8361
8362       /* Else fall through.  */
8363     case ENUMERAL_TYPE:
8364     case UNION_TYPE:
8365       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8366         {
8367           tree argvec;
8368           tree context;
8369           tree r;
8370           int saved_unevaluated_operand;
8371           int saved_inhibit_evaluation_warnings;
8372
8373           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8374           saved_unevaluated_operand = cp_unevaluated_operand;
8375           cp_unevaluated_operand = 0;
8376           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8377           c_inhibit_evaluation_warnings = 0;
8378
8379           /* First, determine the context for the type we are looking
8380              up.  */
8381           context = TYPE_CONTEXT (t);
8382           if (context)
8383             {
8384               context = tsubst_aggr_type (context, args, complain,
8385                                           in_decl, /*entering_scope=*/1);
8386               /* If context is a nested class inside a class template,
8387                  it may still need to be instantiated (c++/33959).  */
8388               if (TYPE_P (context))
8389                 context = complete_type (context);
8390             }
8391
8392           /* Then, figure out what arguments are appropriate for the
8393              type we are trying to find.  For example, given:
8394
8395                template <class T> struct S;
8396                template <class T, class U> void f(T, U) { S<U> su; }
8397
8398              and supposing that we are instantiating f<int, double>,
8399              then our ARGS will be {int, double}, but, when looking up
8400              S we only want {double}.  */
8401           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8402                                          complain, in_decl);
8403           if (argvec == error_mark_node)
8404             r = error_mark_node;
8405           else
8406             {
8407               r = lookup_template_class (t, argvec, in_decl, context,
8408                                          entering_scope, complain);
8409               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8410             }
8411
8412           cp_unevaluated_operand = saved_unevaluated_operand;
8413           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8414
8415           return r;
8416         }
8417       else
8418         /* This is not a template type, so there's nothing to do.  */
8419         return t;
8420
8421     default:
8422       return tsubst (t, args, complain, in_decl);
8423     }
8424 }
8425
8426 /* Substitute into the default argument ARG (a default argument for
8427    FN), which has the indicated TYPE.  */
8428
8429 tree
8430 tsubst_default_argument (tree fn, tree type, tree arg)
8431 {
8432   tree saved_class_ptr = NULL_TREE;
8433   tree saved_class_ref = NULL_TREE;
8434
8435   /* This default argument came from a template.  Instantiate the
8436      default argument here, not in tsubst.  In the case of
8437      something like:
8438
8439        template <class T>
8440        struct S {
8441          static T t();
8442          void f(T = t());
8443        };
8444
8445      we must be careful to do name lookup in the scope of S<T>,
8446      rather than in the current class.  */
8447   push_access_scope (fn);
8448   /* The "this" pointer is not valid in a default argument.  */
8449   if (cfun)
8450     {
8451       saved_class_ptr = current_class_ptr;
8452       cp_function_chain->x_current_class_ptr = NULL_TREE;
8453       saved_class_ref = current_class_ref;
8454       cp_function_chain->x_current_class_ref = NULL_TREE;
8455     }
8456
8457   push_deferring_access_checks(dk_no_deferred);
8458   /* The default argument expression may cause implicitly defined
8459      member functions to be synthesized, which will result in garbage
8460      collection.  We must treat this situation as if we were within
8461      the body of function so as to avoid collecting live data on the
8462      stack.  */
8463   ++function_depth;
8464   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8465                      tf_warning_or_error, NULL_TREE,
8466                      /*integral_constant_expression_p=*/false);
8467   --function_depth;
8468   pop_deferring_access_checks();
8469
8470   /* Restore the "this" pointer.  */
8471   if (cfun)
8472     {
8473       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8474       cp_function_chain->x_current_class_ref = saved_class_ref;
8475     }
8476
8477   /* Make sure the default argument is reasonable.  */
8478   arg = check_default_argument (type, arg);
8479
8480   pop_access_scope (fn);
8481
8482   return arg;
8483 }
8484
8485 /* Substitute into all the default arguments for FN.  */
8486
8487 static void
8488 tsubst_default_arguments (tree fn)
8489 {
8490   tree arg;
8491   tree tmpl_args;
8492
8493   tmpl_args = DECL_TI_ARGS (fn);
8494
8495   /* If this function is not yet instantiated, we certainly don't need
8496      its default arguments.  */
8497   if (uses_template_parms (tmpl_args))
8498     return;
8499
8500   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8501        arg;
8502        arg = TREE_CHAIN (arg))
8503     if (TREE_PURPOSE (arg))
8504       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8505                                                     TREE_VALUE (arg),
8506                                                     TREE_PURPOSE (arg));
8507 }
8508
8509 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8510    result of the substitution.  Issue error and warning messages under
8511    control of COMPLAIN.  */
8512
8513 static tree
8514 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8515 {
8516 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8517   location_t saved_loc;
8518   tree r = NULL_TREE;
8519   tree in_decl = t;
8520   hashval_t hash = 0;
8521
8522   /* Set the filename and linenumber to improve error-reporting.  */
8523   saved_loc = input_location;
8524   input_location = DECL_SOURCE_LOCATION (t);
8525
8526   switch (TREE_CODE (t))
8527     {
8528     case TEMPLATE_DECL:
8529       {
8530         /* We can get here when processing a member function template,
8531            member class template, or template template parameter.  */
8532         tree decl = DECL_TEMPLATE_RESULT (t);
8533         tree spec;
8534         tree tmpl_args;
8535         tree full_args;
8536
8537         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8538           {
8539             /* Template template parameter is treated here.  */
8540             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8541             if (new_type == error_mark_node)
8542               RETURN (error_mark_node);
8543
8544             r = copy_decl (t);
8545             TREE_CHAIN (r) = NULL_TREE;
8546             TREE_TYPE (r) = new_type;
8547             DECL_TEMPLATE_RESULT (r)
8548               = build_decl (DECL_SOURCE_LOCATION (decl),
8549                             TYPE_DECL, DECL_NAME (decl), new_type);
8550             DECL_TEMPLATE_PARMS (r)
8551               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8552                                        complain);
8553             TYPE_NAME (new_type) = r;
8554             break;
8555           }
8556
8557         /* We might already have an instance of this template.
8558            The ARGS are for the surrounding class type, so the
8559            full args contain the tsubst'd args for the context,
8560            plus the innermost args from the template decl.  */
8561         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8562           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8563           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8564         /* Because this is a template, the arguments will still be
8565            dependent, even after substitution.  If
8566            PROCESSING_TEMPLATE_DECL is not set, the dependency
8567            predicates will short-circuit.  */
8568         ++processing_template_decl;
8569         full_args = tsubst_template_args (tmpl_args, args,
8570                                           complain, in_decl);
8571         --processing_template_decl;
8572         if (full_args == error_mark_node)
8573           RETURN (error_mark_node);
8574
8575         /* If this is a default template template argument,
8576            tsubst might not have changed anything.  */
8577         if (full_args == tmpl_args)
8578           RETURN (t);
8579
8580         hash = hash_tmpl_and_args (t, full_args);
8581         spec = retrieve_specialization (t, full_args, hash);
8582         if (spec != NULL_TREE)
8583           {
8584             r = spec;
8585             break;
8586           }
8587
8588         /* Make a new template decl.  It will be similar to the
8589            original, but will record the current template arguments.
8590            We also create a new function declaration, which is just
8591            like the old one, but points to this new template, rather
8592            than the old one.  */
8593         r = copy_decl (t);
8594         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8595         TREE_CHAIN (r) = NULL_TREE;
8596
8597         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
8598
8599         if (TREE_CODE (decl) == TYPE_DECL)
8600           {
8601             tree new_type;
8602             ++processing_template_decl;
8603             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8604             --processing_template_decl;
8605             if (new_type == error_mark_node)
8606               RETURN (error_mark_node);
8607
8608             TREE_TYPE (r) = new_type;
8609             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8610             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8611             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8612             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8613           }
8614         else
8615           {
8616             tree new_decl;
8617             ++processing_template_decl;
8618             new_decl = tsubst (decl, args, complain, in_decl);
8619             --processing_template_decl;
8620             if (new_decl == error_mark_node)
8621               RETURN (error_mark_node);
8622
8623             DECL_TEMPLATE_RESULT (r) = new_decl;
8624             DECL_TI_TEMPLATE (new_decl) = r;
8625             TREE_TYPE (r) = TREE_TYPE (new_decl);
8626             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8627             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8628           }
8629
8630         SET_DECL_IMPLICIT_INSTANTIATION (r);
8631         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8632         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8633
8634         /* The template parameters for this new template are all the
8635            template parameters for the old template, except the
8636            outermost level of parameters.  */
8637         DECL_TEMPLATE_PARMS (r)
8638           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8639                                    complain);
8640
8641         if (PRIMARY_TEMPLATE_P (t))
8642           DECL_PRIMARY_TEMPLATE (r) = r;
8643
8644         if (TREE_CODE (decl) != TYPE_DECL)
8645           /* Record this non-type partial instantiation.  */
8646           register_specialization (r, t,
8647                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8648                                    false, hash);
8649       }
8650       break;
8651
8652     case FUNCTION_DECL:
8653       {
8654         tree ctx;
8655         tree argvec = NULL_TREE;
8656         tree *friends;
8657         tree gen_tmpl;
8658         tree type;
8659         int member;
8660         int args_depth;
8661         int parms_depth;
8662
8663         /* Nobody should be tsubst'ing into non-template functions.  */
8664         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8665
8666         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8667           {
8668             tree spec;
8669             bool dependent_p;
8670
8671             /* If T is not dependent, just return it.  We have to
8672                increment PROCESSING_TEMPLATE_DECL because
8673                value_dependent_expression_p assumes that nothing is
8674                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8675             ++processing_template_decl;
8676             dependent_p = value_dependent_expression_p (t);
8677             --processing_template_decl;
8678             if (!dependent_p)
8679               RETURN (t);
8680
8681             /* Calculate the most general template of which R is a
8682                specialization, and the complete set of arguments used to
8683                specialize R.  */
8684             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8685             argvec = tsubst_template_args (DECL_TI_ARGS
8686                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8687                                            args, complain, in_decl);
8688
8689             /* Check to see if we already have this specialization.  */
8690             hash = hash_tmpl_and_args (gen_tmpl, argvec);
8691             spec = retrieve_specialization (gen_tmpl, argvec, hash);
8692
8693             if (spec)
8694               {
8695                 r = spec;
8696                 break;
8697               }
8698
8699             /* We can see more levels of arguments than parameters if
8700                there was a specialization of a member template, like
8701                this:
8702
8703                  template <class T> struct S { template <class U> void f(); }
8704                  template <> template <class U> void S<int>::f(U);
8705
8706                Here, we'll be substituting into the specialization,
8707                because that's where we can find the code we actually
8708                want to generate, but we'll have enough arguments for
8709                the most general template.
8710
8711                We also deal with the peculiar case:
8712
8713                  template <class T> struct S {
8714                    template <class U> friend void f();
8715                  };
8716                  template <class U> void f() {}
8717                  template S<int>;
8718                  template void f<double>();
8719
8720                Here, the ARGS for the instantiation of will be {int,
8721                double}.  But, we only need as many ARGS as there are
8722                levels of template parameters in CODE_PATTERN.  We are
8723                careful not to get fooled into reducing the ARGS in
8724                situations like:
8725
8726                  template <class T> struct S { template <class U> void f(U); }
8727                  template <class T> template <> void S<T>::f(int) {}
8728
8729                which we can spot because the pattern will be a
8730                specialization in this case.  */
8731             args_depth = TMPL_ARGS_DEPTH (args);
8732             parms_depth =
8733               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8734             if (args_depth > parms_depth
8735                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8736               args = get_innermost_template_args (args, parms_depth);
8737           }
8738         else
8739           {
8740             /* This special case arises when we have something like this:
8741
8742                  template <class T> struct S {
8743                    friend void f<int>(int, double);
8744                  };
8745
8746                Here, the DECL_TI_TEMPLATE for the friend declaration
8747                will be an IDENTIFIER_NODE.  We are being called from
8748                tsubst_friend_function, and we want only to create a
8749                new decl (R) with appropriate types so that we can call
8750                determine_specialization.  */
8751             gen_tmpl = NULL_TREE;
8752           }
8753
8754         if (DECL_CLASS_SCOPE_P (t))
8755           {
8756             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8757               member = 2;
8758             else
8759               member = 1;
8760             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8761                                     complain, t, /*entering_scope=*/1);
8762           }
8763         else
8764           {
8765             member = 0;
8766             ctx = DECL_CONTEXT (t);
8767           }
8768         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8769         if (type == error_mark_node)
8770           RETURN (error_mark_node);
8771
8772         /* We do NOT check for matching decls pushed separately at this
8773            point, as they may not represent instantiations of this
8774            template, and in any case are considered separate under the
8775            discrete model.  */
8776         r = copy_decl (t);
8777         DECL_USE_TEMPLATE (r) = 0;
8778         TREE_TYPE (r) = type;
8779         /* Clear out the mangled name and RTL for the instantiation.  */
8780         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8781         SET_DECL_RTL (r, NULL_RTX);
8782         /* Leave DECL_INITIAL set on deleted instantiations.  */
8783         if (!DECL_DELETED_FN (r))
8784           DECL_INITIAL (r) = NULL_TREE;
8785         DECL_CONTEXT (r) = ctx;
8786
8787         if (member && DECL_CONV_FN_P (r))
8788           /* Type-conversion operator.  Reconstruct the name, in
8789              case it's the name of one of the template's parameters.  */
8790           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8791
8792         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8793                                      complain, t);
8794         DECL_RESULT (r) = NULL_TREE;
8795
8796         TREE_STATIC (r) = 0;
8797         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8798         DECL_EXTERNAL (r) = 1;
8799         /* If this is an instantiation of a function with internal
8800            linkage, we already know what object file linkage will be
8801            assigned to the instantiation.  */
8802         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8803         DECL_DEFER_OUTPUT (r) = 0;
8804         TREE_CHAIN (r) = NULL_TREE;
8805         DECL_PENDING_INLINE_INFO (r) = 0;
8806         DECL_PENDING_INLINE_P (r) = 0;
8807         DECL_SAVED_TREE (r) = NULL_TREE;
8808         DECL_STRUCT_FUNCTION (r) = NULL;
8809         TREE_USED (r) = 0;
8810         /* We'll re-clone as appropriate in instantiate_template.  */
8811         DECL_CLONED_FUNCTION (r) = NULL_TREE;
8812
8813         /* If we aren't complaining now, return on error before we register
8814            the specialization so that we'll complain eventually.  */
8815         if ((complain & tf_error) == 0
8816             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
8817             && !grok_op_properties (r, /*complain=*/false))
8818           RETURN (error_mark_node);
8819
8820         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8821            this in the special friend case mentioned above where
8822            GEN_TMPL is NULL.  */
8823         if (gen_tmpl)
8824           {
8825             DECL_TEMPLATE_INFO (r)
8826               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8827             SET_DECL_IMPLICIT_INSTANTIATION (r);
8828             register_specialization (r, gen_tmpl, argvec, false, hash);
8829
8830             /* We're not supposed to instantiate default arguments
8831                until they are called, for a template.  But, for a
8832                declaration like:
8833
8834                  template <class T> void f ()
8835                  { extern void g(int i = T()); }
8836
8837                we should do the substitution when the template is
8838                instantiated.  We handle the member function case in
8839                instantiate_class_template since the default arguments
8840                might refer to other members of the class.  */
8841             if (!member
8842                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8843                 && !uses_template_parms (argvec))
8844               tsubst_default_arguments (r);
8845           }
8846         else
8847           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8848
8849         /* Copy the list of befriending classes.  */
8850         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8851              *friends;
8852              friends = &TREE_CHAIN (*friends))
8853           {
8854             *friends = copy_node (*friends);
8855             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8856                                             args, complain,
8857                                             in_decl);
8858           }
8859
8860         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8861           {
8862             maybe_retrofit_in_chrg (r);
8863             if (DECL_CONSTRUCTOR_P (r))
8864               grok_ctor_properties (ctx, r);
8865             /* If this is an instantiation of a member template, clone it.
8866                If it isn't, that'll be handled by
8867                clone_constructors_and_destructors.  */
8868             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8869               clone_function_decl (r, /*update_method_vec_p=*/0);
8870           }
8871         else if ((complain & tf_error) != 0
8872                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
8873                  && !grok_op_properties (r, /*complain=*/true))
8874           RETURN (error_mark_node);
8875
8876         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8877           SET_DECL_FRIEND_CONTEXT (r,
8878                                    tsubst (DECL_FRIEND_CONTEXT (t),
8879                                             args, complain, in_decl));
8880
8881         /* Possibly limit visibility based on template args.  */
8882         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8883         if (DECL_VISIBILITY_SPECIFIED (t))
8884           {
8885             DECL_VISIBILITY_SPECIFIED (r) = 0;
8886             DECL_ATTRIBUTES (r)
8887               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8888           }
8889         determine_visibility (r);
8890         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
8891             && !processing_template_decl)
8892           defaulted_late_check (r);
8893
8894         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8895                                         args, complain, in_decl);
8896       }
8897       break;
8898
8899     case PARM_DECL:
8900       {
8901         tree type = NULL_TREE;
8902         int i, len = 1;
8903         tree expanded_types = NULL_TREE;
8904         tree prev_r = NULL_TREE;
8905         tree first_r = NULL_TREE;
8906
8907         if (FUNCTION_PARAMETER_PACK_P (t))
8908           {
8909             /* If there is a local specialization that isn't a
8910                parameter pack, it means that we're doing a "simple"
8911                substitution from inside tsubst_pack_expansion. Just
8912                return the local specialization (which will be a single
8913                parm).  */
8914             tree spec = retrieve_local_specialization (t);
8915             if (spec 
8916                 && TREE_CODE (spec) == PARM_DECL
8917                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8918               RETURN (spec);
8919
8920             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8921                the parameters in this function parameter pack.  */
8922             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8923                                                     complain, in_decl);
8924             if (TREE_CODE (expanded_types) == TREE_VEC)
8925               {
8926                 len = TREE_VEC_LENGTH (expanded_types);
8927
8928                 /* Zero-length parameter packs are boring. Just substitute
8929                    into the chain.  */
8930                 if (len == 0)
8931                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
8932                                   TREE_CHAIN (t)));
8933               }
8934             else
8935               {
8936                 /* All we did was update the type. Make a note of that.  */
8937                 type = expanded_types;
8938                 expanded_types = NULL_TREE;
8939               }
8940           }
8941
8942         /* Loop through all of the parameter's we'll build. When T is
8943            a function parameter pack, LEN is the number of expanded
8944            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8945         r = NULL_TREE;
8946         for (i = 0; i < len; ++i)
8947           {
8948             prev_r = r;
8949             r = copy_node (t);
8950             if (DECL_TEMPLATE_PARM_P (t))
8951               SET_DECL_TEMPLATE_PARM_P (r);
8952
8953             /* An argument of a function parameter pack is not a parameter
8954                pack.  */
8955             FUNCTION_PARAMETER_PACK_P (r) = false;
8956
8957             if (expanded_types)
8958               /* We're on the Ith parameter of the function parameter
8959                  pack.  */
8960               {
8961                 /* Get the Ith type.  */
8962                 type = TREE_VEC_ELT (expanded_types, i);
8963
8964                 if (DECL_NAME (r))
8965                   /* Rename the parameter to include the index.  */
8966                   DECL_NAME (r) =
8967                     make_ith_pack_parameter_name (DECL_NAME (r), i);
8968               }
8969             else if (!type)
8970               /* We're dealing with a normal parameter.  */
8971               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8972
8973             type = type_decays_to (type);
8974             TREE_TYPE (r) = type;
8975             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8976
8977             if (DECL_INITIAL (r))
8978               {
8979                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
8980                   DECL_INITIAL (r) = TREE_TYPE (r);
8981                 else
8982                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
8983                                              complain, in_decl);
8984               }
8985
8986             DECL_CONTEXT (r) = NULL_TREE;
8987
8988             if (!DECL_TEMPLATE_PARM_P (r))
8989               DECL_ARG_TYPE (r) = type_passed_as (type);
8990
8991             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8992                                             args, complain, in_decl);
8993
8994             /* Keep track of the first new parameter we
8995                generate. That's what will be returned to the
8996                caller.  */
8997             if (!first_r)
8998               first_r = r;
8999
9000             /* Build a proper chain of parameters when substituting
9001                into a function parameter pack.  */
9002             if (prev_r)
9003               TREE_CHAIN (prev_r) = r;
9004           }
9005
9006         if (TREE_CHAIN (t))
9007           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
9008                                    complain, TREE_CHAIN (t));
9009
9010         /* FIRST_R contains the start of the chain we've built.  */
9011         r = first_r;
9012       }
9013       break;
9014
9015     case FIELD_DECL:
9016       {
9017         tree type;
9018
9019         r = copy_decl (t);
9020         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9021         if (type == error_mark_node)
9022           RETURN (error_mark_node);
9023         TREE_TYPE (r) = type;
9024         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9025
9026         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9027         DECL_INITIAL (r)
9028           = tsubst_expr (DECL_INITIAL (t), args,
9029                          complain, in_decl,
9030                          /*integral_constant_expression_p=*/true);
9031         /* We don't have to set DECL_CONTEXT here; it is set by
9032            finish_member_declaration.  */
9033         TREE_CHAIN (r) = NULL_TREE;
9034         if (VOID_TYPE_P (type))
9035           error ("instantiation of %q+D as type %qT", r, type);
9036
9037         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9038                                         args, complain, in_decl);
9039       }
9040       break;
9041
9042     case USING_DECL:
9043       /* We reach here only for member using decls.  */
9044       if (DECL_DEPENDENT_P (t))
9045         {
9046           r = do_class_using_decl
9047             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9048              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9049           if (!r)
9050             r = error_mark_node;
9051           else
9052             {
9053               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9054               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9055             }
9056         }
9057       else
9058         {
9059           r = copy_node (t);
9060           TREE_CHAIN (r) = NULL_TREE;
9061         }
9062       break;
9063
9064     case TYPE_DECL:
9065     case VAR_DECL:
9066       {
9067         tree argvec = NULL_TREE;
9068         tree gen_tmpl = NULL_TREE;
9069         tree spec;
9070         tree tmpl = NULL_TREE;
9071         tree ctx;
9072         tree type = NULL_TREE;
9073         bool local_p;
9074
9075         if (TREE_CODE (t) == TYPE_DECL
9076             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9077           {
9078             /* If this is the canonical decl, we don't have to
9079                mess with instantiations, and often we can't (for
9080                typename, template type parms and such).  Note that
9081                TYPE_NAME is not correct for the above test if
9082                we've copied the type for a typedef.  */
9083             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9084             if (type == error_mark_node)
9085               RETURN (error_mark_node);
9086             r = TYPE_NAME (type);
9087             break;
9088           }
9089
9090         /* Check to see if we already have the specialization we
9091            need.  */
9092         spec = NULL_TREE;
9093         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9094           {
9095             /* T is a static data member or namespace-scope entity.
9096                We have to substitute into namespace-scope variables
9097                (even though such entities are never templates) because
9098                of cases like:
9099                
9100                  template <class T> void f() { extern T t; }
9101
9102                where the entity referenced is not known until
9103                instantiation time.  */
9104             local_p = false;
9105             ctx = DECL_CONTEXT (t);
9106             if (DECL_CLASS_SCOPE_P (t))
9107               {
9108                 ctx = tsubst_aggr_type (ctx, args,
9109                                         complain,
9110                                         in_decl, /*entering_scope=*/1);
9111                 /* If CTX is unchanged, then T is in fact the
9112                    specialization we want.  That situation occurs when
9113                    referencing a static data member within in its own
9114                    class.  We can use pointer equality, rather than
9115                    same_type_p, because DECL_CONTEXT is always
9116                    canonical.  */
9117                 if (ctx == DECL_CONTEXT (t))
9118                   spec = t;
9119               }
9120
9121             if (!spec)
9122               {
9123                 tmpl = DECL_TI_TEMPLATE (t);
9124                 gen_tmpl = most_general_template (tmpl);
9125                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9126                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9127                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9128               }
9129           }
9130         else
9131           {
9132             /* A local variable.  */
9133             local_p = true;
9134             /* Subsequent calls to pushdecl will fill this in.  */
9135             ctx = NULL_TREE;
9136             spec = retrieve_local_specialization (t);
9137           }
9138         /* If we already have the specialization we need, there is
9139            nothing more to do.  */ 
9140         if (spec)
9141           {
9142             r = spec;
9143             break;
9144           }
9145
9146         /* Create a new node for the specialization we need.  */
9147         r = copy_decl (t);
9148         if (type == NULL_TREE)
9149           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9150         if (TREE_CODE (r) == VAR_DECL)
9151           {
9152             /* Even if the original location is out of scope, the
9153                newly substituted one is not.  */
9154             DECL_DEAD_FOR_LOCAL (r) = 0;
9155             DECL_INITIALIZED_P (r) = 0;
9156             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9157             if (type == error_mark_node)
9158               RETURN (error_mark_node);
9159             if (TREE_CODE (type) == FUNCTION_TYPE)
9160               {
9161                 /* It may seem that this case cannot occur, since:
9162
9163                      typedef void f();
9164                      void g() { f x; }
9165
9166                    declares a function, not a variable.  However:
9167       
9168                      typedef void f();
9169                      template <typename T> void g() { T t; }
9170                      template void g<f>();
9171
9172                    is an attempt to declare a variable with function
9173                    type.  */
9174                 error ("variable %qD has function type",
9175                        /* R is not yet sufficiently initialized, so we
9176                           just use its name.  */
9177                        DECL_NAME (r));
9178                 RETURN (error_mark_node);
9179               }
9180             type = complete_type (type);
9181             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9182               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9183             type = check_var_type (DECL_NAME (r), type);
9184
9185             if (DECL_HAS_VALUE_EXPR_P (t))
9186               {
9187                 tree ve = DECL_VALUE_EXPR (t);
9188                 ve = tsubst_expr (ve, args, complain, in_decl,
9189                                   /*constant_expression_p=*/false);
9190                 SET_DECL_VALUE_EXPR (r, ve);
9191               }
9192           }
9193         else if (DECL_SELF_REFERENCE_P (t))
9194           SET_DECL_SELF_REFERENCE_P (r);
9195         TREE_TYPE (r) = type;
9196         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9197         DECL_CONTEXT (r) = ctx;
9198         /* Clear out the mangled name and RTL for the instantiation.  */
9199         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9200         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9201           SET_DECL_RTL (r, NULL_RTX);
9202         /* The initializer must not be expanded until it is required;
9203            see [temp.inst].  */
9204         DECL_INITIAL (r) = NULL_TREE;
9205         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9206           SET_DECL_RTL (r, NULL_RTX);
9207         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9208         if (TREE_CODE (r) == VAR_DECL)
9209           {
9210             /* Possibly limit visibility based on template args.  */
9211             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9212             if (DECL_VISIBILITY_SPECIFIED (t))
9213               {
9214                 DECL_VISIBILITY_SPECIFIED (r) = 0;
9215                 DECL_ATTRIBUTES (r)
9216                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9217               }
9218             determine_visibility (r);
9219           }
9220         /* Preserve a typedef that names a type.  */
9221         else if (TREE_CODE (r) == TYPE_DECL
9222                  && DECL_ORIGINAL_TYPE (t)
9223                  && type != error_mark_node)
9224           {
9225             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
9226                                              args, complain, in_decl);
9227             TREE_TYPE (r) = type = build_variant_type_copy (type);
9228             TYPE_NAME (type) = r;
9229           }
9230
9231         if (!local_p)
9232           {
9233             /* A static data member declaration is always marked
9234                external when it is declared in-class, even if an
9235                initializer is present.  We mimic the non-template
9236                processing here.  */
9237             DECL_EXTERNAL (r) = 1;
9238
9239             register_specialization (r, gen_tmpl, argvec, false, hash);
9240             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
9241             SET_DECL_IMPLICIT_INSTANTIATION (r);
9242           }
9243         else if (cp_unevaluated_operand)
9244           {
9245             /* We're substituting this var in a decltype outside of its
9246                scope, such as for a lambda return type.  Don't add it to
9247                local_specializations, do perform auto deduction.  */
9248             tree auto_node = type_uses_auto (type);
9249             tree init
9250               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9251                              /*constant_expression_p=*/false);
9252
9253             if (auto_node && init && describable_type (init))
9254               {
9255                 type = do_auto_deduction (type, init, auto_node);
9256                 TREE_TYPE (r) = type;
9257               }
9258           }
9259         else
9260           register_local_specialization (r, t);
9261
9262         TREE_CHAIN (r) = NULL_TREE;
9263
9264         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9265                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
9266                                         args, complain, in_decl);
9267         layout_decl (r, 0);
9268       }
9269       break;
9270
9271     default:
9272       gcc_unreachable ();
9273     }
9274 #undef RETURN
9275
9276  out:
9277   /* Restore the file and line information.  */
9278   input_location = saved_loc;
9279
9280   return r;
9281 }
9282
9283 /* Substitute into the ARG_TYPES of a function type.  */
9284
9285 static tree
9286 tsubst_arg_types (tree arg_types,
9287                   tree args,
9288                   tsubst_flags_t complain,
9289                   tree in_decl)
9290 {
9291   tree remaining_arg_types;
9292   tree type = NULL_TREE;
9293   int i = 1;
9294   tree expanded_args = NULL_TREE;
9295   tree default_arg;
9296
9297   if (!arg_types || arg_types == void_list_node)
9298     return arg_types;
9299
9300   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9301                                           args, complain, in_decl);
9302   if (remaining_arg_types == error_mark_node)
9303     return error_mark_node;
9304
9305   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9306     {
9307       /* For a pack expansion, perform substitution on the
9308          entire expression. Later on, we'll handle the arguments
9309          one-by-one.  */
9310       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9311                                             args, complain, in_decl);
9312
9313       if (TREE_CODE (expanded_args) == TREE_VEC)
9314         /* So that we'll spin through the parameters, one by one.  */
9315         i = TREE_VEC_LENGTH (expanded_args);
9316       else
9317         {
9318           /* We only partially substituted into the parameter
9319              pack. Our type is TYPE_PACK_EXPANSION.  */
9320           type = expanded_args;
9321           expanded_args = NULL_TREE;
9322         }
9323     }
9324
9325   while (i > 0) {
9326     --i;
9327     
9328     if (expanded_args)
9329       type = TREE_VEC_ELT (expanded_args, i);
9330     else if (!type)
9331       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9332
9333     if (type == error_mark_node)
9334       return error_mark_node;
9335     if (VOID_TYPE_P (type))
9336       {
9337         if (complain & tf_error)
9338           {
9339             error ("invalid parameter type %qT", type);
9340             if (in_decl)
9341               error ("in declaration %q+D", in_decl);
9342           }
9343         return error_mark_node;
9344     }
9345     
9346     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9347        top-level qualifiers as required.  */
9348     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9349
9350     /* We do not substitute into default arguments here.  The standard
9351        mandates that they be instantiated only when needed, which is
9352        done in build_over_call.  */
9353     default_arg = TREE_PURPOSE (arg_types);
9354
9355     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9356       {
9357         /* We've instantiated a template before its default arguments
9358            have been parsed.  This can happen for a nested template
9359            class, and is not an error unless we require the default
9360            argument in a call of this function.  */
9361         remaining_arg_types = 
9362           tree_cons (default_arg, type, remaining_arg_types);
9363         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9364                        remaining_arg_types);
9365       }
9366     else
9367       remaining_arg_types = 
9368         hash_tree_cons (default_arg, type, remaining_arg_types);
9369   }
9370         
9371   return remaining_arg_types;
9372 }
9373
9374 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9375    *not* handle the exception-specification for FNTYPE, because the
9376    initial substitution of explicitly provided template parameters
9377    during argument deduction forbids substitution into the
9378    exception-specification:
9379
9380      [temp.deduct]
9381
9382      All references in the function type of the function template to  the
9383      corresponding template parameters are replaced by the specified tem-
9384      plate argument values.  If a substitution in a template parameter or
9385      in  the function type of the function template results in an invalid
9386      type, type deduction fails.  [Note: The equivalent  substitution  in
9387      exception specifications is done only when the function is instanti-
9388      ated, at which point a program is  ill-formed  if  the  substitution
9389      results in an invalid type.]  */
9390
9391 static tree
9392 tsubst_function_type (tree t,
9393                       tree args,
9394                       tsubst_flags_t complain,
9395                       tree in_decl)
9396 {
9397   tree return_type;
9398   tree arg_types;
9399   tree fntype;
9400
9401   /* The TYPE_CONTEXT is not used for function/method types.  */
9402   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9403
9404   /* Substitute the return type.  */
9405   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9406   if (return_type == error_mark_node)
9407     return error_mark_node;
9408   /* The standard does not presently indicate that creation of a
9409      function type with an invalid return type is a deduction failure.
9410      However, that is clearly analogous to creating an array of "void"
9411      or a reference to a reference.  This is core issue #486.  */
9412   if (TREE_CODE (return_type) == ARRAY_TYPE
9413       || TREE_CODE (return_type) == FUNCTION_TYPE)
9414     {
9415       if (complain & tf_error)
9416         {
9417           if (TREE_CODE (return_type) == ARRAY_TYPE)
9418             error ("function returning an array");
9419           else
9420             error ("function returning a function");
9421         }
9422       return error_mark_node;
9423     }
9424
9425   /* Substitute the argument types.  */
9426   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9427                                 complain, in_decl);
9428   if (arg_types == error_mark_node)
9429     return error_mark_node;
9430
9431   /* Construct a new type node and return it.  */
9432   if (TREE_CODE (t) == FUNCTION_TYPE)
9433     fntype = build_function_type (return_type, arg_types);
9434   else
9435     {
9436       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9437       if (! MAYBE_CLASS_TYPE_P (r))
9438         {
9439           /* [temp.deduct]
9440
9441              Type deduction may fail for any of the following
9442              reasons:
9443
9444              -- Attempting to create "pointer to member of T" when T
9445              is not a class type.  */
9446           if (complain & tf_error)
9447             error ("creating pointer to member function of non-class type %qT",
9448                       r);
9449           return error_mark_node;
9450         }
9451
9452       fntype = build_method_type_directly (r, return_type,
9453                                            TREE_CHAIN (arg_types));
9454     }
9455   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9456   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9457
9458   return fntype;
9459 }
9460
9461 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9462    ARGS into that specification, and return the substituted
9463    specification.  If there is no specification, return NULL_TREE.  */
9464
9465 static tree
9466 tsubst_exception_specification (tree fntype,
9467                                 tree args,
9468                                 tsubst_flags_t complain,
9469                                 tree in_decl)
9470 {
9471   tree specs;
9472   tree new_specs;
9473
9474   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9475   new_specs = NULL_TREE;
9476   if (specs)
9477     {
9478       if (! TREE_VALUE (specs))
9479         new_specs = specs;
9480       else
9481         while (specs)
9482           {
9483             tree spec;
9484             int i, len = 1;
9485             tree expanded_specs = NULL_TREE;
9486
9487             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9488               {
9489                 /* Expand the pack expansion type.  */
9490                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9491                                                        args, complain,
9492                                                        in_decl);
9493
9494                 if (expanded_specs == error_mark_node)
9495                   return error_mark_node;
9496                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9497                   len = TREE_VEC_LENGTH (expanded_specs);
9498                 else
9499                   {
9500                     /* We're substituting into a member template, so
9501                        we got a TYPE_PACK_EXPANSION back.  Add that
9502                        expansion and move on.  */
9503                     gcc_assert (TREE_CODE (expanded_specs) 
9504                                 == TYPE_PACK_EXPANSION);
9505                     new_specs = add_exception_specifier (new_specs,
9506                                                          expanded_specs,
9507                                                          complain);
9508                     specs = TREE_CHAIN (specs);
9509                     continue;
9510                   }
9511               }
9512
9513             for (i = 0; i < len; ++i)
9514               {
9515                 if (expanded_specs)
9516                   spec = TREE_VEC_ELT (expanded_specs, i);
9517                 else
9518                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9519                 if (spec == error_mark_node)
9520                   return spec;
9521                 new_specs = add_exception_specifier (new_specs, spec, 
9522                                                      complain);
9523               }
9524
9525             specs = TREE_CHAIN (specs);
9526           }
9527     }
9528   return new_specs;
9529 }
9530
9531 /* Take the tree structure T and replace template parameters used
9532    therein with the argument vector ARGS.  IN_DECL is an associated
9533    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9534    Issue error and warning messages under control of COMPLAIN.  Note
9535    that we must be relatively non-tolerant of extensions here, in
9536    order to preserve conformance; if we allow substitutions that
9537    should not be allowed, we may allow argument deductions that should
9538    not succeed, and therefore report ambiguous overload situations
9539    where there are none.  In theory, we could allow the substitution,
9540    but indicate that it should have failed, and allow our caller to
9541    make sure that the right thing happens, but we don't try to do this
9542    yet.
9543
9544    This function is used for dealing with types, decls and the like;
9545    for expressions, use tsubst_expr or tsubst_copy.  */
9546
9547 tree
9548 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9549 {
9550   tree type, r;
9551
9552   if (t == NULL_TREE || t == error_mark_node
9553       || t == integer_type_node
9554       || t == void_type_node
9555       || t == char_type_node
9556       || t == unknown_type_node
9557       || TREE_CODE (t) == NAMESPACE_DECL)
9558     return t;
9559
9560   if (DECL_P (t))
9561     return tsubst_decl (t, args, complain);
9562
9563   if (args == NULL_TREE)
9564     return t;
9565
9566   if (TREE_CODE (t) == IDENTIFIER_NODE)
9567     type = IDENTIFIER_TYPE_VALUE (t);
9568   else
9569     type = TREE_TYPE (t);
9570
9571   gcc_assert (type != unknown_type_node);
9572
9573   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9574      such as attribute aligned.  */
9575   if (TYPE_P (t)
9576       && TYPE_NAME (t)
9577       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9578     {
9579       tree decl = TYPE_NAME (t);
9580       
9581       if (DECL_CLASS_SCOPE_P (decl)
9582           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9583           && uses_template_parms (DECL_CONTEXT (decl)))
9584         {
9585           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9586           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9587           r = retrieve_specialization (tmpl, gen_args, 0);
9588         }
9589       else if (DECL_FUNCTION_SCOPE_P (decl)
9590                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9591                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9592         r = retrieve_local_specialization (decl);
9593       else
9594         /* The typedef is from a non-template context.  */
9595         return t;
9596
9597       if (r)
9598         {
9599           r = TREE_TYPE (r);
9600           r = cp_build_qualified_type_real
9601             (r, cp_type_quals (t) | cp_type_quals (r),
9602              complain | tf_ignore_bad_quals);
9603           return r;
9604         }
9605       /* Else we must be instantiating the typedef, so fall through.  */
9606     }
9607
9608   if (type
9609       && TREE_CODE (t) != TYPENAME_TYPE
9610       && TREE_CODE (t) != IDENTIFIER_NODE
9611       && TREE_CODE (t) != FUNCTION_TYPE
9612       && TREE_CODE (t) != METHOD_TYPE)
9613     type = tsubst (type, args, complain, in_decl);
9614   if (type == error_mark_node)
9615     return error_mark_node;
9616
9617   switch (TREE_CODE (t))
9618     {
9619     case RECORD_TYPE:
9620     case UNION_TYPE:
9621     case ENUMERAL_TYPE:
9622       return tsubst_aggr_type (t, args, complain, in_decl,
9623                                /*entering_scope=*/0);
9624
9625     case ERROR_MARK:
9626     case IDENTIFIER_NODE:
9627     case VOID_TYPE:
9628     case REAL_TYPE:
9629     case COMPLEX_TYPE:
9630     case VECTOR_TYPE:
9631     case BOOLEAN_TYPE:
9632     case INTEGER_CST:
9633     case REAL_CST:
9634     case STRING_CST:
9635       return t;
9636
9637     case INTEGER_TYPE:
9638       if (t == integer_type_node)
9639         return t;
9640
9641       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9642           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9643         return t;
9644
9645       {
9646         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9647
9648         max = tsubst_expr (omax, args, complain, in_decl,
9649                            /*integral_constant_expression_p=*/false);
9650
9651         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9652            needed.  */
9653         if (TREE_CODE (max) == NOP_EXPR
9654             && TREE_SIDE_EFFECTS (omax)
9655             && !TREE_TYPE (max))
9656           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9657
9658         max = fold_decl_constant_value (max);
9659
9660         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9661            with TREE_SIDE_EFFECTS that indicates this is not an integral
9662            constant expression.  */
9663         if (processing_template_decl
9664             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9665           {
9666             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9667             TREE_SIDE_EFFECTS (max) = 1;
9668           }
9669
9670         if (TREE_CODE (max) != INTEGER_CST
9671             && !at_function_scope_p ()
9672             && !TREE_SIDE_EFFECTS (max)
9673             && !value_dependent_expression_p (max))
9674           {
9675             if (complain & tf_error)
9676               error ("array bound is not an integer constant");
9677             return error_mark_node;
9678           }
9679
9680         /* [temp.deduct]
9681
9682            Type deduction may fail for any of the following
9683            reasons:
9684
9685              Attempting to create an array with a size that is
9686              zero or negative.  */
9687         if (integer_zerop (max) && !(complain & tf_error))
9688           /* We must fail if performing argument deduction (as
9689              indicated by the state of complain), so that
9690              another substitution can be found.  */
9691           return error_mark_node;
9692         else if (TREE_CODE (max) == INTEGER_CST
9693                  && INT_CST_LT (max, integer_zero_node))
9694           {
9695             if (complain & tf_error)
9696               error ("creating array with negative size (%qE)", max);
9697
9698             return error_mark_node;
9699           }
9700
9701         return compute_array_index_type (NULL_TREE, max);
9702       }
9703
9704     case TEMPLATE_TYPE_PARM:
9705     case TEMPLATE_TEMPLATE_PARM:
9706     case BOUND_TEMPLATE_TEMPLATE_PARM:
9707     case TEMPLATE_PARM_INDEX:
9708       {
9709         int idx;
9710         int level;
9711         int levels;
9712         tree arg = NULL_TREE;
9713
9714         r = NULL_TREE;
9715
9716         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9717         template_parm_level_and_index (t, &level, &idx); 
9718
9719         levels = TMPL_ARGS_DEPTH (args);
9720         if (level <= levels)
9721           {
9722             arg = TMPL_ARG (args, level, idx);
9723
9724             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9725               /* See through ARGUMENT_PACK_SELECT arguments. */
9726               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9727           }
9728
9729         if (arg == error_mark_node)
9730           return error_mark_node;
9731         else if (arg != NULL_TREE)
9732           {
9733             if (ARGUMENT_PACK_P (arg))
9734               /* If ARG is an argument pack, we don't actually want to
9735                  perform a substitution here, because substitutions
9736                  for argument packs are only done
9737                  element-by-element. We can get to this point when
9738                  substituting the type of a non-type template
9739                  parameter pack, when that type actually contains
9740                  template parameter packs from an outer template, e.g.,
9741
9742                  template<typename... Types> struct A {
9743                    template<Types... Values> struct B { };
9744                  };  */
9745               return t;
9746
9747             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9748               {
9749                 int quals;
9750                 gcc_assert (TYPE_P (arg));
9751
9752                 /* cv-quals from the template are discarded when
9753                    substituting in a function or reference type.  */
9754                 if (TREE_CODE (arg) == FUNCTION_TYPE
9755                     || TREE_CODE (arg) == METHOD_TYPE
9756                     || TREE_CODE (arg) == REFERENCE_TYPE)
9757                   quals = cp_type_quals (arg);
9758                 else
9759                   quals = cp_type_quals (arg) | cp_type_quals (t);
9760                   
9761                 return cp_build_qualified_type_real
9762                   (arg, quals, complain | tf_ignore_bad_quals);
9763               }
9764             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9765               {
9766                 /* We are processing a type constructed from a
9767                    template template parameter.  */
9768                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9769                                       args, complain, in_decl);
9770                 if (argvec == error_mark_node)
9771                   return error_mark_node;
9772
9773                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9774                    are resolving nested-types in the signature of a
9775                    member function templates.  Otherwise ARG is a
9776                    TEMPLATE_DECL and is the real template to be
9777                    instantiated.  */
9778                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9779                   arg = TYPE_NAME (arg);
9780
9781                 r = lookup_template_class (arg,
9782                                            argvec, in_decl,
9783                                            DECL_CONTEXT (arg),
9784                                             /*entering_scope=*/0,
9785                                            complain);
9786                 return cp_build_qualified_type_real
9787                   (r, TYPE_QUALS (t), complain);
9788               }
9789             else
9790               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9791               return arg;
9792           }
9793
9794         if (level == 1)
9795           /* This can happen during the attempted tsubst'ing in
9796              unify.  This means that we don't yet have any information
9797              about the template parameter in question.  */
9798           return t;
9799
9800         /* If we get here, we must have been looking at a parm for a
9801            more deeply nested template.  Make a new version of this
9802            template parameter, but with a lower level.  */
9803         switch (TREE_CODE (t))
9804           {
9805           case TEMPLATE_TYPE_PARM:
9806           case TEMPLATE_TEMPLATE_PARM:
9807           case BOUND_TEMPLATE_TEMPLATE_PARM:
9808             if (cp_type_quals (t))
9809               {
9810                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9811                 r = cp_build_qualified_type_real
9812                   (r, cp_type_quals (t),
9813                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9814                                ? tf_ignore_bad_quals : 0));
9815               }
9816             else
9817               {
9818                 r = copy_type (t);
9819                 TEMPLATE_TYPE_PARM_INDEX (r)
9820                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9821                                                 r, levels, args, complain);
9822                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9823                 TYPE_MAIN_VARIANT (r) = r;
9824                 TYPE_POINTER_TO (r) = NULL_TREE;
9825                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9826
9827                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9828                   /* We have reduced the level of the template
9829                      template parameter, but not the levels of its
9830                      template parameters, so canonical_type_parameter
9831                      will not be able to find the canonical template
9832                      template parameter for this level. Thus, we
9833                      require structural equality checking to compare
9834                      TEMPLATE_TEMPLATE_PARMs. */
9835                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9836                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9837                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9838                 else
9839                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9840
9841                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9842                   {
9843                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9844                                           complain, in_decl);
9845                     if (argvec == error_mark_node)
9846                       return error_mark_node;
9847
9848                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9849                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9850                   }
9851               }
9852             break;
9853
9854           case TEMPLATE_PARM_INDEX:
9855             r = reduce_template_parm_level (t, type, levels, args, complain);
9856             break;
9857
9858           default:
9859             gcc_unreachable ();
9860           }
9861
9862         return r;
9863       }
9864
9865     case TREE_LIST:
9866       {
9867         tree purpose, value, chain;
9868
9869         if (t == void_list_node)
9870           return t;
9871
9872         purpose = TREE_PURPOSE (t);
9873         if (purpose)
9874           {
9875             purpose = tsubst (purpose, args, complain, in_decl);
9876             if (purpose == error_mark_node)
9877               return error_mark_node;
9878           }
9879         value = TREE_VALUE (t);
9880         if (value)
9881           {
9882             value = tsubst (value, args, complain, in_decl);
9883             if (value == error_mark_node)
9884               return error_mark_node;
9885           }
9886         chain = TREE_CHAIN (t);
9887         if (chain && chain != void_type_node)
9888           {
9889             chain = tsubst (chain, args, complain, in_decl);
9890             if (chain == error_mark_node)
9891               return error_mark_node;
9892           }
9893         if (purpose == TREE_PURPOSE (t)
9894             && value == TREE_VALUE (t)
9895             && chain == TREE_CHAIN (t))
9896           return t;
9897         return hash_tree_cons (purpose, value, chain);
9898       }
9899
9900     case TREE_BINFO:
9901       /* We should never be tsubsting a binfo.  */
9902       gcc_unreachable ();
9903
9904     case TREE_VEC:
9905       /* A vector of template arguments.  */
9906       gcc_assert (!type);
9907       return tsubst_template_args (t, args, complain, in_decl);
9908
9909     case POINTER_TYPE:
9910     case REFERENCE_TYPE:
9911       {
9912         enum tree_code code;
9913
9914         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9915           return t;
9916
9917         code = TREE_CODE (t);
9918
9919
9920         /* [temp.deduct]
9921
9922            Type deduction may fail for any of the following
9923            reasons:
9924
9925            -- Attempting to create a pointer to reference type.
9926            -- Attempting to create a reference to a reference type or
9927               a reference to void.
9928
9929           Core issue 106 says that creating a reference to a reference
9930           during instantiation is no longer a cause for failure. We
9931           only enforce this check in strict C++98 mode.  */
9932         if ((TREE_CODE (type) == REFERENCE_TYPE
9933              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9934             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9935           {
9936             static location_t last_loc;
9937
9938             /* We keep track of the last time we issued this error
9939                message to avoid spewing a ton of messages during a
9940                single bad template instantiation.  */
9941             if (complain & tf_error
9942                 && last_loc != input_location)
9943               {
9944                 if (TREE_CODE (type) == VOID_TYPE)
9945                   error ("forming reference to void");
9946                 else
9947                   error ("forming %s to reference type %qT",
9948                          (code == POINTER_TYPE) ? "pointer" : "reference",
9949                          type);
9950                 last_loc = input_location;
9951               }
9952
9953             return error_mark_node;
9954           }
9955         else if (code == POINTER_TYPE)
9956           {
9957             r = build_pointer_type (type);
9958             if (TREE_CODE (type) == METHOD_TYPE)
9959               r = build_ptrmemfunc_type (r);
9960           }
9961         else if (TREE_CODE (type) == REFERENCE_TYPE)
9962           /* In C++0x, during template argument substitution, when there is an
9963              attempt to create a reference to a reference type, reference
9964              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9965
9966              "If a template-argument for a template-parameter T names a type
9967              that is a reference to a type A, an attempt to create the type
9968              'lvalue reference to cv T' creates the type 'lvalue reference to
9969              A,' while an attempt to create the type type rvalue reference to
9970              cv T' creates the type T"
9971           */
9972           r = cp_build_reference_type
9973               (TREE_TYPE (type),
9974                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9975         else
9976           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9977         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9978
9979         if (r != error_mark_node)
9980           /* Will this ever be needed for TYPE_..._TO values?  */
9981           layout_type (r);
9982
9983         return r;
9984       }
9985     case OFFSET_TYPE:
9986       {
9987         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9988         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
9989           {
9990             /* [temp.deduct]
9991
9992                Type deduction may fail for any of the following
9993                reasons:
9994
9995                -- Attempting to create "pointer to member of T" when T
9996                   is not a class type.  */
9997             if (complain & tf_error)
9998               error ("creating pointer to member of non-class type %qT", r);
9999             return error_mark_node;
10000           }
10001         if (TREE_CODE (type) == REFERENCE_TYPE)
10002           {
10003             if (complain & tf_error)
10004               error ("creating pointer to member reference type %qT", type);
10005             return error_mark_node;
10006           }
10007         if (TREE_CODE (type) == VOID_TYPE)
10008           {
10009             if (complain & tf_error)
10010               error ("creating pointer to member of type void");
10011             return error_mark_node;
10012           }
10013         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10014         if (TREE_CODE (type) == FUNCTION_TYPE)
10015           {
10016             /* The type of the implicit object parameter gets its
10017                cv-qualifiers from the FUNCTION_TYPE. */
10018             tree memptr;
10019             tree method_type = build_memfn_type (type, r, cp_type_quals (type));
10020             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10021             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10022                                                  complain);
10023           }
10024         else
10025           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10026                                                TYPE_QUALS (t),
10027                                                complain);
10028       }
10029     case FUNCTION_TYPE:
10030     case METHOD_TYPE:
10031       {
10032         tree fntype;
10033         tree specs;
10034         fntype = tsubst_function_type (t, args, complain, in_decl);
10035         if (fntype == error_mark_node)
10036           return error_mark_node;
10037
10038         /* Substitute the exception specification.  */
10039         specs = tsubst_exception_specification (t, args, complain,
10040                                                 in_decl);
10041         if (specs == error_mark_node)
10042           return error_mark_node;
10043         if (specs)
10044           fntype = build_exception_variant (fntype, specs);
10045         return fntype;
10046       }
10047     case ARRAY_TYPE:
10048       {
10049         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10050         if (domain == error_mark_node)
10051           return error_mark_node;
10052
10053         /* As an optimization, we avoid regenerating the array type if
10054            it will obviously be the same as T.  */
10055         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10056           return t;
10057
10058         /* These checks should match the ones in grokdeclarator.
10059
10060            [temp.deduct]
10061
10062            The deduction may fail for any of the following reasons:
10063
10064            -- Attempting to create an array with an element type that
10065               is void, a function type, or a reference type, or [DR337]
10066               an abstract class type.  */
10067         if (TREE_CODE (type) == VOID_TYPE
10068             || TREE_CODE (type) == FUNCTION_TYPE
10069             || TREE_CODE (type) == REFERENCE_TYPE)
10070           {
10071             if (complain & tf_error)
10072               error ("creating array of %qT", type);
10073             return error_mark_node;
10074           }
10075         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10076           {
10077             if (complain & tf_error)
10078               error ("creating array of %qT, which is an abstract class type",
10079                      type);
10080             return error_mark_node;
10081           }
10082
10083         r = build_cplus_array_type (type, domain);
10084
10085         if (TYPE_USER_ALIGN (t))
10086           {
10087             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10088             TYPE_USER_ALIGN (r) = 1;
10089           }
10090
10091         return r;
10092       }
10093
10094     case PLUS_EXPR:
10095     case MINUS_EXPR:
10096       {
10097         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10098         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10099
10100         if (e1 == error_mark_node || e2 == error_mark_node)
10101           return error_mark_node;
10102
10103         return fold_build2_loc (input_location,
10104                             TREE_CODE (t), TREE_TYPE (t), e1, e2);
10105       }
10106
10107     case NEGATE_EXPR:
10108     case NOP_EXPR:
10109       {
10110         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10111         if (e == error_mark_node)
10112           return error_mark_node;
10113
10114         return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
10115       }
10116
10117     case TYPENAME_TYPE:
10118       {
10119         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10120                                      in_decl, /*entering_scope=*/1);
10121         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10122                               complain, in_decl);
10123
10124         if (ctx == error_mark_node || f == error_mark_node)
10125           return error_mark_node;
10126
10127         if (!MAYBE_CLASS_TYPE_P (ctx))
10128           {
10129             if (complain & tf_error)
10130               error ("%qT is not a class, struct, or union type", ctx);
10131             return error_mark_node;
10132           }
10133         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10134           {
10135             /* Normally, make_typename_type does not require that the CTX
10136                have complete type in order to allow things like:
10137
10138                  template <class T> struct S { typename S<T>::X Y; };
10139
10140                But, such constructs have already been resolved by this
10141                point, so here CTX really should have complete type, unless
10142                it's a partial instantiation.  */
10143             if (!(complain & tf_no_class_instantiations))
10144               ctx = complete_type (ctx);
10145             if (!COMPLETE_TYPE_P (ctx))
10146               {
10147                 if (complain & tf_error)
10148                   cxx_incomplete_type_error (NULL_TREE, ctx);
10149                 return error_mark_node;
10150               }
10151           }
10152
10153         f = make_typename_type (ctx, f, typename_type,
10154                                 (complain & tf_error) | tf_keep_type_decl);
10155         if (f == error_mark_node)
10156           return f;
10157         if (TREE_CODE (f) == TYPE_DECL)
10158           {
10159             complain |= tf_ignore_bad_quals;
10160             f = TREE_TYPE (f);
10161           }
10162
10163         if (TREE_CODE (f) != TYPENAME_TYPE)
10164           {
10165             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10166               error ("%qT resolves to %qT, which is not an enumeration type",
10167                      t, f);
10168             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10169               error ("%qT resolves to %qT, which is is not a class type",
10170                      t, f);
10171           }
10172
10173         return cp_build_qualified_type_real
10174           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10175       }
10176
10177     case UNBOUND_CLASS_TEMPLATE:
10178       {
10179         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10180                                      in_decl, /*entering_scope=*/1);
10181         tree name = TYPE_IDENTIFIER (t);
10182         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10183
10184         if (ctx == error_mark_node || name == error_mark_node)
10185           return error_mark_node;
10186
10187         if (parm_list)
10188           parm_list = tsubst_template_parms (parm_list, args, complain);
10189         return make_unbound_class_template (ctx, name, parm_list, complain);
10190       }
10191
10192     case INDIRECT_REF:
10193     case ADDR_EXPR:
10194     case CALL_EXPR:
10195       gcc_unreachable ();
10196
10197     case ARRAY_REF:
10198       {
10199         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10200         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10201                                /*integral_constant_expression_p=*/false);
10202         if (e1 == error_mark_node || e2 == error_mark_node)
10203           return error_mark_node;
10204
10205         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10206       }
10207
10208     case SCOPE_REF:
10209       {
10210         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10211         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10212         if (e1 == error_mark_node || e2 == error_mark_node)
10213           return error_mark_node;
10214
10215         return build_qualified_name (/*type=*/NULL_TREE,
10216                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10217       }
10218
10219     case TYPEOF_TYPE:
10220       {
10221         tree type;
10222
10223         ++cp_unevaluated_operand;
10224         ++c_inhibit_evaluation_warnings;
10225
10226         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10227                             complain, in_decl,
10228                             /*integral_constant_expression_p=*/false);
10229
10230         --cp_unevaluated_operand;
10231         --c_inhibit_evaluation_warnings;
10232
10233         type = finish_typeof (type);
10234         return cp_build_qualified_type_real (type,
10235                                              cp_type_quals (t)
10236                                              | cp_type_quals (type),
10237                                              complain);
10238       }
10239
10240     case DECLTYPE_TYPE:
10241       {
10242         tree type;
10243
10244         ++cp_unevaluated_operand;
10245         ++c_inhibit_evaluation_warnings;
10246
10247         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10248                             complain, in_decl,
10249                             /*integral_constant_expression_p=*/false);
10250
10251         --cp_unevaluated_operand;
10252         --c_inhibit_evaluation_warnings;
10253
10254         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10255           type = lambda_capture_field_type (type);
10256         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10257           type = lambda_return_type (type);
10258         else
10259           type = finish_decltype_type
10260             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10261         return cp_build_qualified_type_real (type,
10262                                              cp_type_quals (t)
10263                                              | cp_type_quals (type),
10264                                              complain);
10265       }
10266
10267     case TYPE_ARGUMENT_PACK:
10268     case NONTYPE_ARGUMENT_PACK:
10269       {
10270         tree r = TYPE_P (t)
10271           ? cxx_make_type (TREE_CODE (t))
10272           : make_node (TREE_CODE (t));
10273         tree packed_out = 
10274           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10275                                 args,
10276                                 complain,
10277                                 in_decl);
10278         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10279
10280         /* For template nontype argument packs, also substitute into
10281            the type.  */
10282         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10283           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10284
10285         return r;
10286       }
10287       break;
10288
10289     default:
10290       sorry ("use of %qs in template",
10291              tree_code_name [(int) TREE_CODE (t)]);
10292       return error_mark_node;
10293     }
10294 }
10295
10296 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10297    type of the expression on the left-hand side of the "." or "->"
10298    operator.  */
10299
10300 static tree
10301 tsubst_baselink (tree baselink, tree object_type,
10302                  tree args, tsubst_flags_t complain, tree in_decl)
10303 {
10304     tree name;
10305     tree qualifying_scope;
10306     tree fns;
10307     tree optype;
10308     tree template_args = 0;
10309     bool template_id_p = false;
10310
10311     /* A baselink indicates a function from a base class.  Both the
10312        BASELINK_ACCESS_BINFO and the base class referenced may
10313        indicate bases of the template class, rather than the
10314        instantiated class.  In addition, lookups that were not
10315        ambiguous before may be ambiguous now.  Therefore, we perform
10316        the lookup again.  */
10317     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10318     qualifying_scope = tsubst (qualifying_scope, args,
10319                                complain, in_decl);
10320     fns = BASELINK_FUNCTIONS (baselink);
10321     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10322     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10323       {
10324         template_id_p = true;
10325         template_args = TREE_OPERAND (fns, 1);
10326         fns = TREE_OPERAND (fns, 0);
10327         if (template_args)
10328           template_args = tsubst_template_args (template_args, args,
10329                                                 complain, in_decl);
10330       }
10331     name = DECL_NAME (get_first_fn (fns));
10332     if (IDENTIFIER_TYPENAME_P (name))
10333       name = mangle_conv_op_name_for_type (optype);
10334     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10335
10336     /* If lookup found a single function, mark it as used at this
10337        point.  (If it lookup found multiple functions the one selected
10338        later by overload resolution will be marked as used at that
10339        point.)  */
10340     if (BASELINK_P (baselink))
10341       fns = BASELINK_FUNCTIONS (baselink);
10342     if (!template_id_p && !really_overloaded_fn (fns))
10343       mark_used (OVL_CURRENT (fns));
10344
10345     /* Add back the template arguments, if present.  */
10346     if (BASELINK_P (baselink) && template_id_p)
10347       BASELINK_FUNCTIONS (baselink)
10348         = build_nt (TEMPLATE_ID_EXPR,
10349                     BASELINK_FUNCTIONS (baselink),
10350                     template_args);
10351     /* Update the conversion operator type.  */
10352     BASELINK_OPTYPE (baselink) = optype;
10353
10354     if (!object_type)
10355       object_type = current_class_type;
10356     return adjust_result_of_qualified_name_lookup (baselink,
10357                                                    qualifying_scope,
10358                                                    object_type);
10359 }
10360
10361 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10362    true if the qualified-id will be a postfix-expression in-and-of
10363    itself; false if more of the postfix-expression follows the
10364    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10365    of "&".  */
10366
10367 static tree
10368 tsubst_qualified_id (tree qualified_id, tree args,
10369                      tsubst_flags_t complain, tree in_decl,
10370                      bool done, bool address_p)
10371 {
10372   tree expr;
10373   tree scope;
10374   tree name;
10375   bool is_template;
10376   tree template_args;
10377
10378   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10379
10380   /* Figure out what name to look up.  */
10381   name = TREE_OPERAND (qualified_id, 1);
10382   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10383     {
10384       is_template = true;
10385       template_args = TREE_OPERAND (name, 1);
10386       if (template_args)
10387         template_args = tsubst_template_args (template_args, args,
10388                                               complain, in_decl);
10389       name = TREE_OPERAND (name, 0);
10390     }
10391   else
10392     {
10393       is_template = false;
10394       template_args = NULL_TREE;
10395     }
10396
10397   /* Substitute into the qualifying scope.  When there are no ARGS, we
10398      are just trying to simplify a non-dependent expression.  In that
10399      case the qualifying scope may be dependent, and, in any case,
10400      substituting will not help.  */
10401   scope = TREE_OPERAND (qualified_id, 0);
10402   if (args)
10403     {
10404       scope = tsubst (scope, args, complain, in_decl);
10405       expr = tsubst_copy (name, args, complain, in_decl);
10406     }
10407   else
10408     expr = name;
10409
10410   if (dependent_type_p (scope))
10411     {
10412       tree type = NULL_TREE;
10413       if (DECL_P (expr) && !dependent_scope_p (scope))
10414         type = TREE_TYPE (expr);
10415       return build_qualified_name (type, scope, expr,
10416                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10417     }
10418
10419   if (!BASELINK_P (name) && !DECL_P (expr))
10420     {
10421       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10422         {
10423           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10424           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10425             {
10426               error ("qualifying type %qT does not match destructor name ~%qT",
10427                      scope, TREE_OPERAND (expr, 0));
10428               expr = error_mark_node;
10429             }
10430           else
10431             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10432                                           /*is_type_p=*/0, false);
10433         }
10434       else
10435         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10436       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10437                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10438         {
10439           if (complain & tf_error)
10440             {
10441               error ("dependent-name %qE is parsed as a non-type, but "
10442                      "instantiation yields a type", qualified_id);
10443               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10444             }
10445           return error_mark_node;
10446         }
10447     }
10448
10449   if (DECL_P (expr))
10450     {
10451       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10452                                            scope);
10453       /* Remember that there was a reference to this entity.  */
10454       mark_used (expr);
10455     }
10456
10457   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10458     {
10459       if (complain & tf_error)
10460         qualified_name_lookup_error (scope,
10461                                      TREE_OPERAND (qualified_id, 1),
10462                                      expr, input_location);
10463       return error_mark_node;
10464     }
10465
10466   if (is_template)
10467     expr = lookup_template_function (expr, template_args);
10468
10469   if (expr == error_mark_node && complain & tf_error)
10470     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10471                                  expr, input_location);
10472   else if (TYPE_P (scope))
10473     {
10474       expr = (adjust_result_of_qualified_name_lookup
10475               (expr, scope, current_class_type));
10476       expr = (finish_qualified_id_expr
10477               (scope, expr, done, address_p,
10478                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10479                /*template_arg_p=*/false));
10480     }
10481
10482   /* Expressions do not generally have reference type.  */
10483   if (TREE_CODE (expr) != SCOPE_REF
10484       /* However, if we're about to form a pointer-to-member, we just
10485          want the referenced member referenced.  */
10486       && TREE_CODE (expr) != OFFSET_REF)
10487     expr = convert_from_reference (expr);
10488
10489   return expr;
10490 }
10491
10492 /* Like tsubst, but deals with expressions.  This function just replaces
10493    template parms; to finish processing the resultant expression, use
10494    tsubst_expr.  */
10495
10496 static tree
10497 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10498 {
10499   enum tree_code code;
10500   tree r;
10501
10502   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10503     return t;
10504
10505   code = TREE_CODE (t);
10506
10507   switch (code)
10508     {
10509     case PARM_DECL:
10510       r = retrieve_local_specialization (t);
10511
10512       if (r == NULL)
10513         {
10514           tree c;
10515           /* This can happen for a parameter name used later in a function
10516              declaration (such as in a late-specified return type).  Just
10517              make a dummy decl, since it's only used for its type.  */
10518           gcc_assert (cp_unevaluated_operand != 0);
10519           /* We copy T because want to tsubst the PARM_DECL only,
10520              not the following PARM_DECLs that are chained to T.  */
10521           c = copy_node (t);
10522           r = tsubst_decl (c, args, complain);
10523           /* Give it the template pattern as its context; its true context
10524              hasn't been instantiated yet and this is good enough for
10525              mangling.  */
10526           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10527         }
10528       
10529       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10530         r = ARGUMENT_PACK_SELECT_ARG (r);
10531       mark_used (r);
10532       return r;
10533
10534     case CONST_DECL:
10535       {
10536         tree enum_type;
10537         tree v;
10538
10539         if (DECL_TEMPLATE_PARM_P (t))
10540           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10541         /* There is no need to substitute into namespace-scope
10542            enumerators.  */
10543         if (DECL_NAMESPACE_SCOPE_P (t))
10544           return t;
10545         /* If ARGS is NULL, then T is known to be non-dependent.  */
10546         if (args == NULL_TREE)
10547           return integral_constant_value (t);
10548
10549         /* Unfortunately, we cannot just call lookup_name here.
10550            Consider:
10551
10552              template <int I> int f() {
10553              enum E { a = I };
10554              struct S { void g() { E e = a; } };
10555              };
10556
10557            When we instantiate f<7>::S::g(), say, lookup_name is not
10558            clever enough to find f<7>::a.  */
10559         enum_type
10560           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10561                               /*entering_scope=*/0);
10562
10563         for (v = TYPE_VALUES (enum_type);
10564              v != NULL_TREE;
10565              v = TREE_CHAIN (v))
10566           if (TREE_PURPOSE (v) == DECL_NAME (t))
10567             return TREE_VALUE (v);
10568
10569           /* We didn't find the name.  That should never happen; if
10570              name-lookup found it during preliminary parsing, we
10571              should find it again here during instantiation.  */
10572         gcc_unreachable ();
10573       }
10574       return t;
10575
10576     case FIELD_DECL:
10577       if (DECL_CONTEXT (t))
10578         {
10579           tree ctx;
10580
10581           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10582                                   /*entering_scope=*/1);
10583           if (ctx != DECL_CONTEXT (t))
10584             {
10585               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10586               if (!r)
10587                 {
10588                   if (complain & tf_error)
10589                     error ("using invalid field %qD", t);
10590                   return error_mark_node;
10591                 }
10592               return r;
10593             }
10594         }
10595
10596       return t;
10597
10598     case VAR_DECL:
10599     case FUNCTION_DECL:
10600       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10601           || local_variable_p (t))
10602         t = tsubst (t, args, complain, in_decl);
10603       mark_used (t);
10604       return t;
10605
10606     case BASELINK:
10607       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10608
10609     case TEMPLATE_DECL:
10610       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10611         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10612                        args, complain, in_decl);
10613       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10614         return tsubst (t, args, complain, in_decl);
10615       else if (DECL_CLASS_SCOPE_P (t)
10616                && uses_template_parms (DECL_CONTEXT (t)))
10617         {
10618           /* Template template argument like the following example need
10619              special treatment:
10620
10621                template <template <class> class TT> struct C {};
10622                template <class T> struct D {
10623                  template <class U> struct E {};
10624                  C<E> c;                                // #1
10625                };
10626                D<int> d;                                // #2
10627
10628              We are processing the template argument `E' in #1 for
10629              the template instantiation #2.  Originally, `E' is a
10630              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10631              have to substitute this with one having context `D<int>'.  */
10632
10633           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10634           return lookup_field (context, DECL_NAME(t), 0, false);
10635         }
10636       else
10637         /* Ordinary template template argument.  */
10638         return t;
10639
10640     case CAST_EXPR:
10641     case REINTERPRET_CAST_EXPR:
10642     case CONST_CAST_EXPR:
10643     case STATIC_CAST_EXPR:
10644     case DYNAMIC_CAST_EXPR:
10645     case NOP_EXPR:
10646       return build1
10647         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10648          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10649
10650     case SIZEOF_EXPR:
10651       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10652         {
10653           /* We only want to compute the number of arguments.  */
10654           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10655                                                 complain, in_decl);
10656           int len = 0;
10657
10658           if (TREE_CODE (expanded) == TREE_VEC)
10659             len = TREE_VEC_LENGTH (expanded);
10660
10661           if (expanded == error_mark_node)
10662             return error_mark_node;
10663           else if (PACK_EXPANSION_P (expanded)
10664                    || (TREE_CODE (expanded) == TREE_VEC
10665                        && len > 0
10666                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10667             {
10668               if (TREE_CODE (expanded) == TREE_VEC)
10669                 expanded = TREE_VEC_ELT (expanded, len - 1);
10670
10671               if (TYPE_P (expanded))
10672                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10673                                                    complain & tf_error);
10674               else
10675                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10676                                                    complain & tf_error);
10677             }
10678           else
10679             return build_int_cst (size_type_node, len);
10680         }
10681       /* Fall through */
10682
10683     case INDIRECT_REF:
10684     case NEGATE_EXPR:
10685     case TRUTH_NOT_EXPR:
10686     case BIT_NOT_EXPR:
10687     case ADDR_EXPR:
10688     case UNARY_PLUS_EXPR:      /* Unary + */
10689     case ALIGNOF_EXPR:
10690     case ARROW_EXPR:
10691     case THROW_EXPR:
10692     case TYPEID_EXPR:
10693     case REALPART_EXPR:
10694     case IMAGPART_EXPR:
10695       return build1
10696         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10697          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10698
10699     case COMPONENT_REF:
10700       {
10701         tree object;
10702         tree name;
10703
10704         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10705         name = TREE_OPERAND (t, 1);
10706         if (TREE_CODE (name) == BIT_NOT_EXPR)
10707           {
10708             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10709                                 complain, in_decl);
10710             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10711           }
10712         else if (TREE_CODE (name) == SCOPE_REF
10713                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10714           {
10715             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10716                                      complain, in_decl);
10717             name = TREE_OPERAND (name, 1);
10718             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10719                                 complain, in_decl);
10720             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10721             name = build_qualified_name (/*type=*/NULL_TREE,
10722                                          base, name,
10723                                          /*template_p=*/false);
10724           }
10725         else if (TREE_CODE (name) == BASELINK)
10726           name = tsubst_baselink (name,
10727                                   non_reference (TREE_TYPE (object)),
10728                                   args, complain,
10729                                   in_decl);
10730         else
10731           name = tsubst_copy (name, args, complain, in_decl);
10732         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10733       }
10734
10735     case PLUS_EXPR:
10736     case MINUS_EXPR:
10737     case MULT_EXPR:
10738     case TRUNC_DIV_EXPR:
10739     case CEIL_DIV_EXPR:
10740     case FLOOR_DIV_EXPR:
10741     case ROUND_DIV_EXPR:
10742     case EXACT_DIV_EXPR:
10743     case BIT_AND_EXPR:
10744     case BIT_IOR_EXPR:
10745     case BIT_XOR_EXPR:
10746     case TRUNC_MOD_EXPR:
10747     case FLOOR_MOD_EXPR:
10748     case TRUTH_ANDIF_EXPR:
10749     case TRUTH_ORIF_EXPR:
10750     case TRUTH_AND_EXPR:
10751     case TRUTH_OR_EXPR:
10752     case RSHIFT_EXPR:
10753     case LSHIFT_EXPR:
10754     case RROTATE_EXPR:
10755     case LROTATE_EXPR:
10756     case EQ_EXPR:
10757     case NE_EXPR:
10758     case MAX_EXPR:
10759     case MIN_EXPR:
10760     case LE_EXPR:
10761     case GE_EXPR:
10762     case LT_EXPR:
10763     case GT_EXPR:
10764     case COMPOUND_EXPR:
10765     case DOTSTAR_EXPR:
10766     case MEMBER_REF:
10767     case PREDECREMENT_EXPR:
10768     case PREINCREMENT_EXPR:
10769     case POSTDECREMENT_EXPR:
10770     case POSTINCREMENT_EXPR:
10771       return build_nt
10772         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10773          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10774
10775     case SCOPE_REF:
10776       return build_qualified_name (/*type=*/NULL_TREE,
10777                                    tsubst_copy (TREE_OPERAND (t, 0),
10778                                                 args, complain, in_decl),
10779                                    tsubst_copy (TREE_OPERAND (t, 1),
10780                                                 args, complain, in_decl),
10781                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10782
10783     case ARRAY_REF:
10784       return build_nt
10785         (ARRAY_REF,
10786          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10787          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10788          NULL_TREE, NULL_TREE);
10789
10790     case CALL_EXPR:
10791       {
10792         int n = VL_EXP_OPERAND_LENGTH (t);
10793         tree result = build_vl_exp (CALL_EXPR, n);
10794         int i;
10795         for (i = 0; i < n; i++)
10796           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10797                                              complain, in_decl);
10798         return result;
10799       }
10800
10801     case COND_EXPR:
10802     case MODOP_EXPR:
10803     case PSEUDO_DTOR_EXPR:
10804       {
10805         r = build_nt
10806           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10807            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10808            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10809         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10810         return r;
10811       }
10812
10813     case NEW_EXPR:
10814       {
10815         r = build_nt
10816         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10817          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10818          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10819         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10820         return r;
10821       }
10822
10823     case DELETE_EXPR:
10824       {
10825         r = build_nt
10826         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10827          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10828         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10829         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10830         return r;
10831       }
10832
10833     case TEMPLATE_ID_EXPR:
10834       {
10835         /* Substituted template arguments */
10836         tree fn = TREE_OPERAND (t, 0);
10837         tree targs = TREE_OPERAND (t, 1);
10838
10839         fn = tsubst_copy (fn, args, complain, in_decl);
10840         if (targs)
10841           targs = tsubst_template_args (targs, args, complain, in_decl);
10842
10843         return lookup_template_function (fn, targs);
10844       }
10845
10846     case TREE_LIST:
10847       {
10848         tree purpose, value, chain;
10849
10850         if (t == void_list_node)
10851           return t;
10852
10853         purpose = TREE_PURPOSE (t);
10854         if (purpose)
10855           purpose = tsubst_copy (purpose, args, complain, in_decl);
10856         value = TREE_VALUE (t);
10857         if (value)
10858           value = tsubst_copy (value, args, complain, in_decl);
10859         chain = TREE_CHAIN (t);
10860         if (chain && chain != void_type_node)
10861           chain = tsubst_copy (chain, args, complain, in_decl);
10862         if (purpose == TREE_PURPOSE (t)
10863             && value == TREE_VALUE (t)
10864             && chain == TREE_CHAIN (t))
10865           return t;
10866         return tree_cons (purpose, value, chain);
10867       }
10868
10869     case RECORD_TYPE:
10870     case UNION_TYPE:
10871     case ENUMERAL_TYPE:
10872     case INTEGER_TYPE:
10873     case TEMPLATE_TYPE_PARM:
10874     case TEMPLATE_TEMPLATE_PARM:
10875     case BOUND_TEMPLATE_TEMPLATE_PARM:
10876     case TEMPLATE_PARM_INDEX:
10877     case POINTER_TYPE:
10878     case REFERENCE_TYPE:
10879     case OFFSET_TYPE:
10880     case FUNCTION_TYPE:
10881     case METHOD_TYPE:
10882     case ARRAY_TYPE:
10883     case TYPENAME_TYPE:
10884     case UNBOUND_CLASS_TEMPLATE:
10885     case TYPEOF_TYPE:
10886     case DECLTYPE_TYPE:
10887     case TYPE_DECL:
10888       return tsubst (t, args, complain, in_decl);
10889
10890     case IDENTIFIER_NODE:
10891       if (IDENTIFIER_TYPENAME_P (t))
10892         {
10893           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10894           return mangle_conv_op_name_for_type (new_type);
10895         }
10896       else
10897         return t;
10898
10899     case CONSTRUCTOR:
10900       /* This is handled by tsubst_copy_and_build.  */
10901       gcc_unreachable ();
10902
10903     case VA_ARG_EXPR:
10904       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10905                                           in_decl),
10906                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10907
10908     case CLEANUP_POINT_EXPR:
10909       /* We shouldn't have built any of these during initial template
10910          generation.  Instead, they should be built during instantiation
10911          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10912       gcc_unreachable ();
10913
10914     case OFFSET_REF:
10915       mark_used (TREE_OPERAND (t, 1));
10916       return t;
10917
10918     case EXPR_PACK_EXPANSION:
10919       error ("invalid use of pack expansion expression");
10920       return error_mark_node;
10921
10922     case NONTYPE_ARGUMENT_PACK:
10923       error ("use %<...%> to expand argument pack");
10924       return error_mark_node;
10925
10926     default:
10927       return t;
10928     }
10929 }
10930
10931 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10932
10933 static tree
10934 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10935                     tree in_decl)
10936 {
10937   tree new_clauses = NULL, nc, oc;
10938
10939   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10940     {
10941       nc = copy_node (oc);
10942       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10943       new_clauses = nc;
10944
10945       switch (OMP_CLAUSE_CODE (nc))
10946         {
10947         case OMP_CLAUSE_LASTPRIVATE:
10948           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
10949             {
10950               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
10951               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
10952                            in_decl, /*integral_constant_expression_p=*/false);
10953               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
10954                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
10955             }
10956           /* FALLTHRU */
10957         case OMP_CLAUSE_PRIVATE:
10958         case OMP_CLAUSE_SHARED:
10959         case OMP_CLAUSE_FIRSTPRIVATE:
10960         case OMP_CLAUSE_REDUCTION:
10961         case OMP_CLAUSE_COPYIN:
10962         case OMP_CLAUSE_COPYPRIVATE:
10963         case OMP_CLAUSE_IF:
10964         case OMP_CLAUSE_NUM_THREADS:
10965         case OMP_CLAUSE_SCHEDULE:
10966         case OMP_CLAUSE_COLLAPSE:
10967           OMP_CLAUSE_OPERAND (nc, 0)
10968             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10969                            in_decl, /*integral_constant_expression_p=*/false);
10970           break;
10971         case OMP_CLAUSE_NOWAIT:
10972         case OMP_CLAUSE_ORDERED:
10973         case OMP_CLAUSE_DEFAULT:
10974         case OMP_CLAUSE_UNTIED:
10975           break;
10976         default:
10977           gcc_unreachable ();
10978         }
10979     }
10980
10981   return finish_omp_clauses (nreverse (new_clauses));
10982 }
10983
10984 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10985
10986 static tree
10987 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10988                           tree in_decl)
10989 {
10990 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10991
10992   tree purpose, value, chain;
10993
10994   if (t == NULL)
10995     return t;
10996
10997   if (TREE_CODE (t) != TREE_LIST)
10998     return tsubst_copy_and_build (t, args, complain, in_decl,
10999                                   /*function_p=*/false,
11000                                   /*integral_constant_expression_p=*/false);
11001
11002   if (t == void_list_node)
11003     return t;
11004
11005   purpose = TREE_PURPOSE (t);
11006   if (purpose)
11007     purpose = RECUR (purpose);
11008   value = TREE_VALUE (t);
11009   if (value && TREE_CODE (value) != LABEL_DECL)
11010     value = RECUR (value);
11011   chain = TREE_CHAIN (t);
11012   if (chain && chain != void_type_node)
11013     chain = RECUR (chain);
11014   return tree_cons (purpose, value, chain);
11015 #undef RECUR
11016 }
11017
11018 /* Substitute one OMP_FOR iterator.  */
11019
11020 static void
11021 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11022                          tree condv, tree incrv, tree *clauses,
11023                          tree args, tsubst_flags_t complain, tree in_decl,
11024                          bool integral_constant_expression_p)
11025 {
11026 #define RECUR(NODE)                             \
11027   tsubst_expr ((NODE), args, complain, in_decl, \
11028                integral_constant_expression_p)
11029   tree decl, init, cond, incr, auto_node;
11030
11031   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11032   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11033   decl = RECUR (TREE_OPERAND (init, 0));
11034   init = TREE_OPERAND (init, 1);
11035   auto_node = type_uses_auto (TREE_TYPE (decl));
11036   if (auto_node && init)
11037     {
11038       tree init_expr = init;
11039       if (TREE_CODE (init_expr) == DECL_EXPR)
11040         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11041       init_expr = RECUR (init_expr);
11042       TREE_TYPE (decl)
11043         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11044     }
11045   gcc_assert (!type_dependent_expression_p (decl));
11046
11047   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11048     {
11049       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11050       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11051       if (TREE_CODE (incr) == MODIFY_EXPR)
11052         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11053                                     RECUR (TREE_OPERAND (incr, 1)),
11054                                     complain);
11055       else
11056         incr = RECUR (incr);
11057       TREE_VEC_ELT (declv, i) = decl;
11058       TREE_VEC_ELT (initv, i) = init;
11059       TREE_VEC_ELT (condv, i) = cond;
11060       TREE_VEC_ELT (incrv, i) = incr;
11061       return;
11062     }
11063
11064   if (init && TREE_CODE (init) != DECL_EXPR)
11065     {
11066       tree c;
11067       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11068         {
11069           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11070                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11071               && OMP_CLAUSE_DECL (c) == decl)
11072             break;
11073           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11074                    && OMP_CLAUSE_DECL (c) == decl)
11075             error ("iteration variable %qD should not be firstprivate", decl);
11076           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11077                    && OMP_CLAUSE_DECL (c) == decl)
11078             error ("iteration variable %qD should not be reduction", decl);
11079         }
11080       if (c == NULL)
11081         {
11082           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11083           OMP_CLAUSE_DECL (c) = decl;
11084           c = finish_omp_clauses (c);
11085           if (c)
11086             {
11087               OMP_CLAUSE_CHAIN (c) = *clauses;
11088               *clauses = c;
11089             }
11090         }
11091     }
11092   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11093   if (COMPARISON_CLASS_P (cond))
11094     cond = build2 (TREE_CODE (cond), boolean_type_node,
11095                    RECUR (TREE_OPERAND (cond, 0)),
11096                    RECUR (TREE_OPERAND (cond, 1)));
11097   else
11098     cond = RECUR (cond);
11099   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11100   switch (TREE_CODE (incr))
11101     {
11102     case PREINCREMENT_EXPR:
11103     case PREDECREMENT_EXPR:
11104     case POSTINCREMENT_EXPR:
11105     case POSTDECREMENT_EXPR:
11106       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11107                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11108       break;
11109     case MODIFY_EXPR:
11110       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11111           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11112         {
11113           tree rhs = TREE_OPERAND (incr, 1);
11114           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11115                          RECUR (TREE_OPERAND (incr, 0)),
11116                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11117                                  RECUR (TREE_OPERAND (rhs, 0)),
11118                                  RECUR (TREE_OPERAND (rhs, 1))));
11119         }
11120       else
11121         incr = RECUR (incr);
11122       break;
11123     case MODOP_EXPR:
11124       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11125           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11126         {
11127           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11128           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11129                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11130                                  TREE_TYPE (decl), lhs,
11131                                  RECUR (TREE_OPERAND (incr, 2))));
11132         }
11133       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11134                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11135                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11136         {
11137           tree rhs = TREE_OPERAND (incr, 2);
11138           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11139                          RECUR (TREE_OPERAND (incr, 0)),
11140                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11141                                  RECUR (TREE_OPERAND (rhs, 0)),
11142                                  RECUR (TREE_OPERAND (rhs, 1))));
11143         }
11144       else
11145         incr = RECUR (incr);
11146       break;
11147     default:
11148       incr = RECUR (incr);
11149       break;
11150     }
11151
11152   TREE_VEC_ELT (declv, i) = decl;
11153   TREE_VEC_ELT (initv, i) = init;
11154   TREE_VEC_ELT (condv, i) = cond;
11155   TREE_VEC_ELT (incrv, i) = incr;
11156 #undef RECUR
11157 }
11158
11159 /* Like tsubst_copy for expressions, etc. but also does semantic
11160    processing.  */
11161
11162 static tree
11163 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11164              bool integral_constant_expression_p)
11165 {
11166 #define RECUR(NODE)                             \
11167   tsubst_expr ((NODE), args, complain, in_decl, \
11168                integral_constant_expression_p)
11169
11170   tree stmt, tmp;
11171
11172   if (t == NULL_TREE || t == error_mark_node)
11173     return t;
11174
11175   if (EXPR_HAS_LOCATION (t))
11176     input_location = EXPR_LOCATION (t);
11177   if (STATEMENT_CODE_P (TREE_CODE (t)))
11178     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11179
11180   switch (TREE_CODE (t))
11181     {
11182     case STATEMENT_LIST:
11183       {
11184         tree_stmt_iterator i;
11185         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11186           RECUR (tsi_stmt (i));
11187         break;
11188       }
11189
11190     case CTOR_INITIALIZER:
11191       finish_mem_initializers (tsubst_initializer_list
11192                                (TREE_OPERAND (t, 0), args));
11193       break;
11194
11195     case RETURN_EXPR:
11196       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11197       break;
11198
11199     case EXPR_STMT:
11200       tmp = RECUR (EXPR_STMT_EXPR (t));
11201       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11202         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11203       else
11204         finish_expr_stmt (tmp);
11205       break;
11206
11207     case USING_STMT:
11208       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11209       break;
11210
11211     case DECL_EXPR:
11212       {
11213         tree decl;
11214         tree init;
11215
11216         decl = DECL_EXPR_DECL (t);
11217         if (TREE_CODE (decl) == LABEL_DECL)
11218           finish_label_decl (DECL_NAME (decl));
11219         else if (TREE_CODE (decl) == USING_DECL)
11220           {
11221             tree scope = USING_DECL_SCOPE (decl);
11222             tree name = DECL_NAME (decl);
11223             tree decl;
11224
11225             scope = RECUR (scope);
11226             decl = lookup_qualified_name (scope, name,
11227                                           /*is_type_p=*/false,
11228                                           /*complain=*/false);
11229             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11230               qualified_name_lookup_error (scope, name, decl, input_location);
11231             else
11232               do_local_using_decl (decl, scope, name);
11233           }
11234         else
11235           {
11236             init = DECL_INITIAL (decl);
11237             decl = tsubst (decl, args, complain, in_decl);
11238             if (decl != error_mark_node)
11239               {
11240                 /* By marking the declaration as instantiated, we avoid
11241                    trying to instantiate it.  Since instantiate_decl can't
11242                    handle local variables, and since we've already done
11243                    all that needs to be done, that's the right thing to
11244                    do.  */
11245                 if (TREE_CODE (decl) == VAR_DECL)
11246                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11247                 if (TREE_CODE (decl) == VAR_DECL
11248                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11249                   /* Anonymous aggregates are a special case.  */
11250                   finish_anon_union (decl);
11251                 else
11252                   {
11253                     maybe_push_decl (decl);
11254                     if (TREE_CODE (decl) == VAR_DECL
11255                         && DECL_PRETTY_FUNCTION_P (decl))
11256                       {
11257                         /* For __PRETTY_FUNCTION__ we have to adjust the
11258                            initializer.  */
11259                         const char *const name
11260                           = cxx_printable_name (current_function_decl, 2);
11261                         init = cp_fname_init (name, &TREE_TYPE (decl));
11262                       }
11263                     else
11264                       {
11265                         tree t = RECUR (init);
11266
11267                         if (init && !t)
11268                           /* If we had an initializer but it
11269                              instantiated to nothing,
11270                              value-initialize the object.  This will
11271                              only occur when the initializer was a
11272                              pack expansion where the parameter packs
11273                              used in that expansion were of length
11274                              zero.  */
11275                           init = build_value_init (TREE_TYPE (decl));
11276                         else
11277                           init = t;
11278                       }
11279
11280                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11281                   }
11282               }
11283           }
11284
11285         /* A DECL_EXPR can also be used as an expression, in the condition
11286            clause of an if/for/while construct.  */
11287         return decl;
11288       }
11289
11290     case FOR_STMT:
11291       stmt = begin_for_stmt ();
11292                           RECUR (FOR_INIT_STMT (t));
11293       finish_for_init_stmt (stmt);
11294       tmp = RECUR (FOR_COND (t));
11295       finish_for_cond (tmp, stmt);
11296       tmp = RECUR (FOR_EXPR (t));
11297       finish_for_expr (tmp, stmt);
11298       RECUR (FOR_BODY (t));
11299       finish_for_stmt (stmt);
11300       break;
11301
11302     case WHILE_STMT:
11303       stmt = begin_while_stmt ();
11304       tmp = RECUR (WHILE_COND (t));
11305       finish_while_stmt_cond (tmp, stmt);
11306       RECUR (WHILE_BODY (t));
11307       finish_while_stmt (stmt);
11308       break;
11309
11310     case DO_STMT:
11311       stmt = begin_do_stmt ();
11312       RECUR (DO_BODY (t));
11313       finish_do_body (stmt);
11314       tmp = RECUR (DO_COND (t));
11315       finish_do_stmt (tmp, stmt);
11316       break;
11317
11318     case IF_STMT:
11319       stmt = begin_if_stmt ();
11320       tmp = RECUR (IF_COND (t));
11321       finish_if_stmt_cond (tmp, stmt);
11322       RECUR (THEN_CLAUSE (t));
11323       finish_then_clause (stmt);
11324
11325       if (ELSE_CLAUSE (t))
11326         {
11327           begin_else_clause (stmt);
11328           RECUR (ELSE_CLAUSE (t));
11329           finish_else_clause (stmt);
11330         }
11331
11332       finish_if_stmt (stmt);
11333       break;
11334
11335     case BIND_EXPR:
11336       if (BIND_EXPR_BODY_BLOCK (t))
11337         stmt = begin_function_body ();
11338       else
11339         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11340                                     ? BCS_TRY_BLOCK : 0);
11341
11342       RECUR (BIND_EXPR_BODY (t));
11343
11344       if (BIND_EXPR_BODY_BLOCK (t))
11345         finish_function_body (stmt);
11346       else
11347         finish_compound_stmt (stmt);
11348       break;
11349
11350     case BREAK_STMT:
11351       finish_break_stmt ();
11352       break;
11353
11354     case CONTINUE_STMT:
11355       finish_continue_stmt ();
11356       break;
11357
11358     case SWITCH_STMT:
11359       stmt = begin_switch_stmt ();
11360       tmp = RECUR (SWITCH_STMT_COND (t));
11361       finish_switch_cond (tmp, stmt);
11362       RECUR (SWITCH_STMT_BODY (t));
11363       finish_switch_stmt (stmt);
11364       break;
11365
11366     case CASE_LABEL_EXPR:
11367       finish_case_label (EXPR_LOCATION (t),
11368                          RECUR (CASE_LOW (t)),
11369                          RECUR (CASE_HIGH (t)));
11370       break;
11371
11372     case LABEL_EXPR:
11373       {
11374         tree decl = LABEL_EXPR_LABEL (t);
11375         tree label;
11376
11377         label = finish_label_stmt (DECL_NAME (decl));
11378         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11379           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11380       }
11381       break;
11382
11383     case GOTO_EXPR:
11384       tmp = GOTO_DESTINATION (t);
11385       if (TREE_CODE (tmp) != LABEL_DECL)
11386         /* Computed goto's must be tsubst'd into.  On the other hand,
11387            non-computed gotos must not be; the identifier in question
11388            will have no binding.  */
11389         tmp = RECUR (tmp);
11390       else
11391         tmp = DECL_NAME (tmp);
11392       finish_goto_stmt (tmp);
11393       break;
11394
11395     case ASM_EXPR:
11396       tmp = finish_asm_stmt
11397         (ASM_VOLATILE_P (t),
11398          RECUR (ASM_STRING (t)),
11399          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11400          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11401          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11402          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11403       {
11404         tree asm_expr = tmp;
11405         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11406           asm_expr = TREE_OPERAND (asm_expr, 0);
11407         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11408       }
11409       break;
11410
11411     case TRY_BLOCK:
11412       if (CLEANUP_P (t))
11413         {
11414           stmt = begin_try_block ();
11415           RECUR (TRY_STMTS (t));
11416           finish_cleanup_try_block (stmt);
11417           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11418         }
11419       else
11420         {
11421           tree compound_stmt = NULL_TREE;
11422
11423           if (FN_TRY_BLOCK_P (t))
11424             stmt = begin_function_try_block (&compound_stmt);
11425           else
11426             stmt = begin_try_block ();
11427
11428           RECUR (TRY_STMTS (t));
11429
11430           if (FN_TRY_BLOCK_P (t))
11431             finish_function_try_block (stmt);
11432           else
11433             finish_try_block (stmt);
11434
11435           RECUR (TRY_HANDLERS (t));
11436           if (FN_TRY_BLOCK_P (t))
11437             finish_function_handler_sequence (stmt, compound_stmt);
11438           else
11439             finish_handler_sequence (stmt);
11440         }
11441       break;
11442
11443     case HANDLER:
11444       {
11445         tree decl = HANDLER_PARMS (t);
11446
11447         if (decl)
11448           {
11449             decl = tsubst (decl, args, complain, in_decl);
11450             /* Prevent instantiate_decl from trying to instantiate
11451                this variable.  We've already done all that needs to be
11452                done.  */
11453             if (decl != error_mark_node)
11454               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11455           }
11456         stmt = begin_handler ();
11457         finish_handler_parms (decl, stmt);
11458         RECUR (HANDLER_BODY (t));
11459         finish_handler (stmt);
11460       }
11461       break;
11462
11463     case TAG_DEFN:
11464       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11465       break;
11466
11467     case STATIC_ASSERT:
11468       {
11469         tree condition = 
11470           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11471                        args,
11472                        complain, in_decl,
11473                        /*integral_constant_expression_p=*/true);
11474         finish_static_assert (condition,
11475                               STATIC_ASSERT_MESSAGE (t),
11476                               STATIC_ASSERT_SOURCE_LOCATION (t),
11477                               /*member_p=*/false);
11478       }
11479       break;
11480
11481     case OMP_PARALLEL:
11482       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11483                                 args, complain, in_decl);
11484       stmt = begin_omp_parallel ();
11485       RECUR (OMP_PARALLEL_BODY (t));
11486       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11487         = OMP_PARALLEL_COMBINED (t);
11488       break;
11489
11490     case OMP_TASK:
11491       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11492                                 args, complain, in_decl);
11493       stmt = begin_omp_task ();
11494       RECUR (OMP_TASK_BODY (t));
11495       finish_omp_task (tmp, stmt);
11496       break;
11497
11498     case OMP_FOR:
11499       {
11500         tree clauses, body, pre_body;
11501         tree declv, initv, condv, incrv;
11502         int i;
11503
11504         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11505                                       args, complain, in_decl);
11506         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11507         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11508         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11509         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11510
11511         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11512           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11513                                    &clauses, args, complain, in_decl,
11514                                    integral_constant_expression_p);
11515
11516         stmt = begin_omp_structured_block ();
11517
11518         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11519           if (TREE_VEC_ELT (initv, i) == NULL
11520               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11521             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11522           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11523             {
11524               tree init = RECUR (TREE_VEC_ELT (initv, i));
11525               gcc_assert (init == TREE_VEC_ELT (declv, i));
11526               TREE_VEC_ELT (initv, i) = NULL_TREE;
11527             }
11528           else
11529             {
11530               tree decl_expr = TREE_VEC_ELT (initv, i);
11531               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11532               gcc_assert (init != NULL);
11533               TREE_VEC_ELT (initv, i) = RECUR (init);
11534               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11535               RECUR (decl_expr);
11536               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11537             }
11538
11539         pre_body = push_stmt_list ();
11540         RECUR (OMP_FOR_PRE_BODY (t));
11541         pre_body = pop_stmt_list (pre_body);
11542
11543         body = push_stmt_list ();
11544         RECUR (OMP_FOR_BODY (t));
11545         body = pop_stmt_list (body);
11546
11547         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11548                             body, pre_body, clauses);
11549
11550         add_stmt (finish_omp_structured_block (stmt));
11551       }
11552       break;
11553
11554     case OMP_SECTIONS:
11555     case OMP_SINGLE:
11556       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11557       stmt = push_stmt_list ();
11558       RECUR (OMP_BODY (t));
11559       stmt = pop_stmt_list (stmt);
11560
11561       t = copy_node (t);
11562       OMP_BODY (t) = stmt;
11563       OMP_CLAUSES (t) = tmp;
11564       add_stmt (t);
11565       break;
11566
11567     case OMP_SECTION:
11568     case OMP_CRITICAL:
11569     case OMP_MASTER:
11570     case OMP_ORDERED:
11571       stmt = push_stmt_list ();
11572       RECUR (OMP_BODY (t));
11573       stmt = pop_stmt_list (stmt);
11574
11575       t = copy_node (t);
11576       OMP_BODY (t) = stmt;
11577       add_stmt (t);
11578       break;
11579
11580     case OMP_ATOMIC:
11581       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11582       {
11583         tree op1 = TREE_OPERAND (t, 1);
11584         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11585         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11586         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11587       }
11588       break;
11589
11590     case EXPR_PACK_EXPANSION:
11591       error ("invalid use of pack expansion expression");
11592       return error_mark_node;
11593
11594     case NONTYPE_ARGUMENT_PACK:
11595       error ("use %<...%> to expand argument pack");
11596       return error_mark_node;
11597
11598     default:
11599       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11600
11601       return tsubst_copy_and_build (t, args, complain, in_decl,
11602                                     /*function_p=*/false,
11603                                     integral_constant_expression_p);
11604     }
11605
11606   return NULL_TREE;
11607 #undef RECUR
11608 }
11609
11610 /* T is a postfix-expression that is not being used in a function
11611    call.  Return the substituted version of T.  */
11612
11613 static tree
11614 tsubst_non_call_postfix_expression (tree t, tree args,
11615                                     tsubst_flags_t complain,
11616                                     tree in_decl)
11617 {
11618   if (TREE_CODE (t) == SCOPE_REF)
11619     t = tsubst_qualified_id (t, args, complain, in_decl,
11620                              /*done=*/false, /*address_p=*/false);
11621   else
11622     t = tsubst_copy_and_build (t, args, complain, in_decl,
11623                                /*function_p=*/false,
11624                                /*integral_constant_expression_p=*/false);
11625
11626   return t;
11627 }
11628
11629 /* Like tsubst but deals with expressions and performs semantic
11630    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11631
11632 tree
11633 tsubst_copy_and_build (tree t,
11634                        tree args,
11635                        tsubst_flags_t complain,
11636                        tree in_decl,
11637                        bool function_p,
11638                        bool integral_constant_expression_p)
11639 {
11640 #define RECUR(NODE)                                             \
11641   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11642                          /*function_p=*/false,                  \
11643                          integral_constant_expression_p)
11644
11645   tree op1;
11646
11647   if (t == NULL_TREE || t == error_mark_node)
11648     return t;
11649
11650   switch (TREE_CODE (t))
11651     {
11652     case USING_DECL:
11653       t = DECL_NAME (t);
11654       /* Fall through.  */
11655     case IDENTIFIER_NODE:
11656       {
11657         tree decl;
11658         cp_id_kind idk;
11659         bool non_integral_constant_expression_p;
11660         const char *error_msg;
11661
11662         if (IDENTIFIER_TYPENAME_P (t))
11663           {
11664             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11665             t = mangle_conv_op_name_for_type (new_type);
11666           }
11667
11668         /* Look up the name.  */
11669         decl = lookup_name (t);
11670
11671         /* By convention, expressions use ERROR_MARK_NODE to indicate
11672            failure, not NULL_TREE.  */
11673         if (decl == NULL_TREE)
11674           decl = error_mark_node;
11675
11676         decl = finish_id_expression (t, decl, NULL_TREE,
11677                                      &idk,
11678                                      integral_constant_expression_p,
11679                                      /*allow_non_integral_constant_expression_p=*/false,
11680                                      &non_integral_constant_expression_p,
11681                                      /*template_p=*/false,
11682                                      /*done=*/true,
11683                                      /*address_p=*/false,
11684                                      /*template_arg_p=*/false,
11685                                      &error_msg,
11686                                      input_location);
11687         if (error_msg)
11688           error (error_msg);
11689         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11690           decl = unqualified_name_lookup_error (decl);
11691         return decl;
11692       }
11693
11694     case TEMPLATE_ID_EXPR:
11695       {
11696         tree object;
11697         tree templ = RECUR (TREE_OPERAND (t, 0));
11698         tree targs = TREE_OPERAND (t, 1);
11699
11700         if (targs)
11701           targs = tsubst_template_args (targs, args, complain, in_decl);
11702
11703         if (TREE_CODE (templ) == COMPONENT_REF)
11704           {
11705             object = TREE_OPERAND (templ, 0);
11706             templ = TREE_OPERAND (templ, 1);
11707           }
11708         else
11709           object = NULL_TREE;
11710         templ = lookup_template_function (templ, targs);
11711
11712         if (object)
11713           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11714                          object, templ, NULL_TREE);
11715         else
11716           return baselink_for_fns (templ);
11717       }
11718
11719     case INDIRECT_REF:
11720       {
11721         tree r = RECUR (TREE_OPERAND (t, 0));
11722
11723         if (REFERENCE_REF_P (t))
11724           {
11725             /* A type conversion to reference type will be enclosed in
11726                such an indirect ref, but the substitution of the cast
11727                will have also added such an indirect ref.  */
11728             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11729               r = convert_from_reference (r);
11730           }
11731         else
11732           r = build_x_indirect_ref (r, "unary *", complain);
11733         return r;
11734       }
11735
11736     case NOP_EXPR:
11737       return build_nop
11738         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11739          RECUR (TREE_OPERAND (t, 0)));
11740
11741     case CAST_EXPR:
11742     case REINTERPRET_CAST_EXPR:
11743     case CONST_CAST_EXPR:
11744     case DYNAMIC_CAST_EXPR:
11745     case STATIC_CAST_EXPR:
11746       {
11747         tree type;
11748         tree op;
11749
11750         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11751         if (integral_constant_expression_p
11752             && !cast_valid_in_integral_constant_expression_p (type))
11753           {
11754             if (complain & tf_error)
11755               error ("a cast to a type other than an integral or "
11756                      "enumeration type cannot appear in a constant-expression");
11757             return error_mark_node; 
11758           }
11759
11760         op = RECUR (TREE_OPERAND (t, 0));
11761
11762         switch (TREE_CODE (t))
11763           {
11764           case CAST_EXPR:
11765             return build_functional_cast (type, op, complain);
11766           case REINTERPRET_CAST_EXPR:
11767             return build_reinterpret_cast (type, op, complain);
11768           case CONST_CAST_EXPR:
11769             return build_const_cast (type, op, complain);
11770           case DYNAMIC_CAST_EXPR:
11771             return build_dynamic_cast (type, op, complain);
11772           case STATIC_CAST_EXPR:
11773             return build_static_cast (type, op, complain);
11774           default:
11775             gcc_unreachable ();
11776           }
11777       }
11778
11779     case POSTDECREMENT_EXPR:
11780     case POSTINCREMENT_EXPR:
11781       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11782                                                 args, complain, in_decl);
11783       return build_x_unary_op (TREE_CODE (t), op1, complain);
11784
11785     case PREDECREMENT_EXPR:
11786     case PREINCREMENT_EXPR:
11787     case NEGATE_EXPR:
11788     case BIT_NOT_EXPR:
11789     case ABS_EXPR:
11790     case TRUTH_NOT_EXPR:
11791     case UNARY_PLUS_EXPR:  /* Unary + */
11792     case REALPART_EXPR:
11793     case IMAGPART_EXPR:
11794       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11795                                complain);
11796
11797     case ADDR_EXPR:
11798       op1 = TREE_OPERAND (t, 0);
11799       if (TREE_CODE (op1) == SCOPE_REF)
11800         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11801                                    /*done=*/true, /*address_p=*/true);
11802       else
11803         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11804                                                   in_decl);
11805       if (TREE_CODE (op1) == LABEL_DECL)
11806         return finish_label_address_expr (DECL_NAME (op1),
11807                                           EXPR_LOCATION (op1));
11808       return build_x_unary_op (ADDR_EXPR, op1, complain);
11809
11810     case PLUS_EXPR:
11811     case MINUS_EXPR:
11812     case MULT_EXPR:
11813     case TRUNC_DIV_EXPR:
11814     case CEIL_DIV_EXPR:
11815     case FLOOR_DIV_EXPR:
11816     case ROUND_DIV_EXPR:
11817     case EXACT_DIV_EXPR:
11818     case BIT_AND_EXPR:
11819     case BIT_IOR_EXPR:
11820     case BIT_XOR_EXPR:
11821     case TRUNC_MOD_EXPR:
11822     case FLOOR_MOD_EXPR:
11823     case TRUTH_ANDIF_EXPR:
11824     case TRUTH_ORIF_EXPR:
11825     case TRUTH_AND_EXPR:
11826     case TRUTH_OR_EXPR:
11827     case RSHIFT_EXPR:
11828     case LSHIFT_EXPR:
11829     case RROTATE_EXPR:
11830     case LROTATE_EXPR:
11831     case EQ_EXPR:
11832     case NE_EXPR:
11833     case MAX_EXPR:
11834     case MIN_EXPR:
11835     case LE_EXPR:
11836     case GE_EXPR:
11837     case LT_EXPR:
11838     case GT_EXPR:
11839     case MEMBER_REF:
11840     case DOTSTAR_EXPR:
11841       return build_x_binary_op
11842         (TREE_CODE (t),
11843          RECUR (TREE_OPERAND (t, 0)),
11844          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11845           ? ERROR_MARK
11846           : TREE_CODE (TREE_OPERAND (t, 0))),
11847          RECUR (TREE_OPERAND (t, 1)),
11848          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11849           ? ERROR_MARK
11850           : TREE_CODE (TREE_OPERAND (t, 1))),
11851          /*overloaded_p=*/NULL,
11852          complain);
11853
11854     case SCOPE_REF:
11855       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11856                                   /*address_p=*/false);
11857     case ARRAY_REF:
11858       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11859                                                 args, complain, in_decl);
11860       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11861
11862     case SIZEOF_EXPR:
11863       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11864         return tsubst_copy (t, args, complain, in_decl);
11865       /* Fall through */
11866       
11867     case ALIGNOF_EXPR:
11868       op1 = TREE_OPERAND (t, 0);
11869       if (!args)
11870         {
11871           /* When there are no ARGS, we are trying to evaluate a
11872              non-dependent expression from the parser.  Trying to do
11873              the substitutions may not work.  */
11874           if (!TYPE_P (op1))
11875             op1 = TREE_TYPE (op1);
11876         }
11877       else
11878         {
11879           ++cp_unevaluated_operand;
11880           ++c_inhibit_evaluation_warnings;
11881           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11882                                        /*function_p=*/false,
11883                                        /*integral_constant_expression_p=*/false);
11884           --cp_unevaluated_operand;
11885           --c_inhibit_evaluation_warnings;
11886         }
11887       if (TYPE_P (op1))
11888         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11889                                            complain & tf_error);
11890       else
11891         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11892                                            complain & tf_error);
11893
11894     case MODOP_EXPR:
11895       {
11896         tree r = build_x_modify_expr
11897           (RECUR (TREE_OPERAND (t, 0)),
11898            TREE_CODE (TREE_OPERAND (t, 1)),
11899            RECUR (TREE_OPERAND (t, 2)),
11900            complain);
11901         /* TREE_NO_WARNING must be set if either the expression was
11902            parenthesized or it uses an operator such as >>= rather
11903            than plain assignment.  In the former case, it was already
11904            set and must be copied.  In the latter case,
11905            build_x_modify_expr sets it and it must not be reset
11906            here.  */
11907         if (TREE_NO_WARNING (t))
11908           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11909         return r;
11910       }
11911
11912     case ARROW_EXPR:
11913       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11914                                                 args, complain, in_decl);
11915       /* Remember that there was a reference to this entity.  */
11916       if (DECL_P (op1))
11917         mark_used (op1);
11918       return build_x_arrow (op1);
11919
11920     case NEW_EXPR:
11921       {
11922         tree placement = RECUR (TREE_OPERAND (t, 0));
11923         tree init = RECUR (TREE_OPERAND (t, 3));
11924         VEC(tree,gc) *placement_vec;
11925         VEC(tree,gc) *init_vec;
11926         tree ret;
11927
11928         if (placement == NULL_TREE)
11929           placement_vec = NULL;
11930         else
11931           {
11932             placement_vec = make_tree_vector ();
11933             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
11934               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
11935           }
11936
11937         /* If there was an initializer in the original tree, but it
11938            instantiated to an empty list, then we should pass a
11939            non-NULL empty vector to tell build_new that it was an
11940            empty initializer() rather than no initializer.  This can
11941            only happen when the initializer is a pack expansion whose
11942            parameter packs are of length zero.  */
11943         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
11944           init_vec = NULL;
11945         else
11946           {
11947             init_vec = make_tree_vector ();
11948             if (init == void_zero_node)
11949               gcc_assert (init_vec != NULL);
11950             else
11951               {
11952                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
11953                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
11954               }
11955           }
11956
11957         ret = build_new (&placement_vec,
11958                          RECUR (TREE_OPERAND (t, 1)),
11959                          RECUR (TREE_OPERAND (t, 2)),
11960                          &init_vec,
11961                          NEW_EXPR_USE_GLOBAL (t),
11962                          complain);
11963
11964         if (placement_vec != NULL)
11965           release_tree_vector (placement_vec);
11966         if (init_vec != NULL)
11967           release_tree_vector (init_vec);
11968
11969         return ret;
11970       }
11971
11972     case DELETE_EXPR:
11973      return delete_sanity
11974        (RECUR (TREE_OPERAND (t, 0)),
11975         RECUR (TREE_OPERAND (t, 1)),
11976         DELETE_EXPR_USE_VEC (t),
11977         DELETE_EXPR_USE_GLOBAL (t));
11978
11979     case COMPOUND_EXPR:
11980       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
11981                                     RECUR (TREE_OPERAND (t, 1)),
11982                                     complain);
11983
11984     case CALL_EXPR:
11985       {
11986         tree function;
11987         VEC(tree,gc) *call_args;
11988         unsigned int nargs, i;
11989         bool qualified_p;
11990         bool koenig_p;
11991         tree ret;
11992
11993         function = CALL_EXPR_FN (t);
11994         /* When we parsed the expression,  we determined whether or
11995            not Koenig lookup should be performed.  */
11996         koenig_p = KOENIG_LOOKUP_P (t);
11997         if (TREE_CODE (function) == SCOPE_REF)
11998           {
11999             qualified_p = true;
12000             function = tsubst_qualified_id (function, args, complain, in_decl,
12001                                             /*done=*/false,
12002                                             /*address_p=*/false);
12003           }
12004         else
12005           {
12006             if (TREE_CODE (function) == COMPONENT_REF)
12007               {
12008                 tree op = TREE_OPERAND (function, 1);
12009
12010                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12011                                || (BASELINK_P (op)
12012                                    && BASELINK_QUALIFIED_P (op)));
12013               }
12014             else
12015               qualified_p = false;
12016
12017             function = tsubst_copy_and_build (function, args, complain,
12018                                               in_decl,
12019                                               !qualified_p,
12020                                               integral_constant_expression_p);
12021
12022             if (BASELINK_P (function))
12023               qualified_p = true;
12024           }
12025
12026         nargs = call_expr_nargs (t);
12027         call_args = make_tree_vector ();
12028         for (i = 0; i < nargs; ++i)
12029           {
12030             tree arg = CALL_EXPR_ARG (t, i);
12031
12032             if (!PACK_EXPANSION_P (arg))
12033               VEC_safe_push (tree, gc, call_args,
12034                              RECUR (CALL_EXPR_ARG (t, i)));
12035             else
12036               {
12037                 /* Expand the pack expansion and push each entry onto
12038                    CALL_ARGS.  */
12039                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12040                 if (TREE_CODE (arg) == TREE_VEC)
12041                   {
12042                     unsigned int len, j;
12043
12044                     len = TREE_VEC_LENGTH (arg);
12045                     for (j = 0; j < len; ++j)
12046                       {
12047                         tree value = TREE_VEC_ELT (arg, j);
12048                         if (value != NULL_TREE)
12049                           value = convert_from_reference (value);
12050                         VEC_safe_push (tree, gc, call_args, value);
12051                       }
12052                   }
12053                 else
12054                   {
12055                     /* A partial substitution.  Add one entry.  */
12056                     VEC_safe_push (tree, gc, call_args, arg);
12057                   }
12058               }
12059           }
12060
12061         /* We do not perform argument-dependent lookup if normal
12062            lookup finds a non-function, in accordance with the
12063            expected resolution of DR 218.  */
12064         if (koenig_p
12065             && ((is_overloaded_fn (function)
12066                  /* If lookup found a member function, the Koenig lookup is
12067                     not appropriate, even if an unqualified-name was used
12068                     to denote the function.  */
12069                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12070                 || TREE_CODE (function) == IDENTIFIER_NODE)
12071             /* Only do this when substitution turns a dependent call
12072                into a non-dependent call.  */
12073             && type_dependent_expression_p_push (t)
12074             && !any_type_dependent_arguments_p (call_args))
12075           function = perform_koenig_lookup (function, call_args);
12076
12077         if (TREE_CODE (function) == IDENTIFIER_NODE)
12078           {
12079             unqualified_name_lookup_error (function);
12080             release_tree_vector (call_args);
12081             return error_mark_node;
12082           }
12083
12084         /* Remember that there was a reference to this entity.  */
12085         if (DECL_P (function))
12086           mark_used (function);
12087
12088         if (TREE_CODE (function) == OFFSET_REF)
12089           ret = build_offset_ref_call_from_tree (function, &call_args);
12090         else if (TREE_CODE (function) == COMPONENT_REF)
12091           {
12092             if (!BASELINK_P (TREE_OPERAND (function, 1)))
12093               ret = finish_call_expr (function, &call_args,
12094                                        /*disallow_virtual=*/false,
12095                                        /*koenig_p=*/false,
12096                                        complain);
12097             else
12098               ret = (build_new_method_call
12099                       (TREE_OPERAND (function, 0),
12100                        TREE_OPERAND (function, 1),
12101                        &call_args, NULL_TREE,
12102                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12103                        /*fn_p=*/NULL,
12104                        complain));
12105           }
12106         else
12107           ret = finish_call_expr (function, &call_args,
12108                                   /*disallow_virtual=*/qualified_p,
12109                                   koenig_p,
12110                                   complain);
12111
12112         release_tree_vector (call_args);
12113
12114         return ret;
12115       }
12116
12117     case COND_EXPR:
12118       return build_x_conditional_expr
12119         (RECUR (TREE_OPERAND (t, 0)),
12120          RECUR (TREE_OPERAND (t, 1)),
12121          RECUR (TREE_OPERAND (t, 2)),
12122          complain);
12123
12124     case PSEUDO_DTOR_EXPR:
12125       return finish_pseudo_destructor_expr
12126         (RECUR (TREE_OPERAND (t, 0)),
12127          RECUR (TREE_OPERAND (t, 1)),
12128          RECUR (TREE_OPERAND (t, 2)));
12129
12130     case TREE_LIST:
12131       {
12132         tree purpose, value, chain;
12133
12134         if (t == void_list_node)
12135           return t;
12136
12137         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12138             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12139           {
12140             /* We have pack expansions, so expand those and
12141                create a new list out of it.  */
12142             tree purposevec = NULL_TREE;
12143             tree valuevec = NULL_TREE;
12144             tree chain;
12145             int i, len = -1;
12146
12147             /* Expand the argument expressions.  */
12148             if (TREE_PURPOSE (t))
12149               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12150                                                  complain, in_decl);
12151             if (TREE_VALUE (t))
12152               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12153                                                complain, in_decl);
12154
12155             /* Build the rest of the list.  */
12156             chain = TREE_CHAIN (t);
12157             if (chain && chain != void_type_node)
12158               chain = RECUR (chain);
12159
12160             /* Determine the number of arguments.  */
12161             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12162               {
12163                 len = TREE_VEC_LENGTH (purposevec);
12164                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12165               }
12166             else if (TREE_CODE (valuevec) == TREE_VEC)
12167               len = TREE_VEC_LENGTH (valuevec);
12168             else
12169               {
12170                 /* Since we only performed a partial substitution into
12171                    the argument pack, we only return a single list
12172                    node.  */
12173                 if (purposevec == TREE_PURPOSE (t)
12174                     && valuevec == TREE_VALUE (t)
12175                     && chain == TREE_CHAIN (t))
12176                   return t;
12177
12178                 return tree_cons (purposevec, valuevec, chain);
12179               }
12180             
12181             /* Convert the argument vectors into a TREE_LIST */
12182             i = len;
12183             while (i > 0)
12184               {
12185                 /* Grab the Ith values.  */
12186                 i--;
12187                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12188                                      : NULL_TREE;
12189                 value 
12190                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12191                              : NULL_TREE;
12192
12193                 /* Build the list (backwards).  */
12194                 chain = tree_cons (purpose, value, chain);
12195               }
12196
12197             return chain;
12198           }
12199
12200         purpose = TREE_PURPOSE (t);
12201         if (purpose)
12202           purpose = RECUR (purpose);
12203         value = TREE_VALUE (t);
12204         if (value)
12205           value = RECUR (value);
12206         chain = TREE_CHAIN (t);
12207         if (chain && chain != void_type_node)
12208           chain = RECUR (chain);
12209         if (purpose == TREE_PURPOSE (t)
12210             && value == TREE_VALUE (t)
12211             && chain == TREE_CHAIN (t))
12212           return t;
12213         return tree_cons (purpose, value, chain);
12214       }
12215
12216     case COMPONENT_REF:
12217       {
12218         tree object;
12219         tree object_type;
12220         tree member;
12221
12222         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12223                                                      args, complain, in_decl);
12224         /* Remember that there was a reference to this entity.  */
12225         if (DECL_P (object))
12226           mark_used (object);
12227         object_type = TREE_TYPE (object);
12228
12229         member = TREE_OPERAND (t, 1);
12230         if (BASELINK_P (member))
12231           member = tsubst_baselink (member,
12232                                     non_reference (TREE_TYPE (object)),
12233                                     args, complain, in_decl);
12234         else
12235           member = tsubst_copy (member, args, complain, in_decl);
12236         if (member == error_mark_node)
12237           return error_mark_node;
12238
12239         if (object_type && !CLASS_TYPE_P (object_type))
12240           {
12241             if (SCALAR_TYPE_P (object_type))
12242               {
12243                 tree s = NULL_TREE;
12244                 tree dtor = member;
12245
12246                 if (TREE_CODE (dtor) == SCOPE_REF)
12247                   {
12248                     s = TREE_OPERAND (dtor, 0);
12249                     dtor = TREE_OPERAND (dtor, 1);
12250                   }
12251                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12252                   {
12253                     dtor = TREE_OPERAND (dtor, 0);
12254                     if (TYPE_P (dtor))
12255                       return finish_pseudo_destructor_expr (object, s, dtor);
12256                   }
12257               }
12258           }
12259         else if (TREE_CODE (member) == SCOPE_REF
12260                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12261           {
12262             tree tmpl;
12263             tree args;
12264
12265             /* Lookup the template functions now that we know what the
12266                scope is.  */
12267             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12268             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12269             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12270                                             /*is_type_p=*/false,
12271                                             /*complain=*/false);
12272             if (BASELINK_P (member))
12273               {
12274                 BASELINK_FUNCTIONS (member)
12275                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12276                               args);
12277                 member = (adjust_result_of_qualified_name_lookup
12278                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12279                            object_type));
12280               }
12281             else
12282               {
12283                 qualified_name_lookup_error (object_type, tmpl, member,
12284                                              input_location);
12285                 return error_mark_node;
12286               }
12287           }
12288         else if (TREE_CODE (member) == SCOPE_REF
12289                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12290                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12291           {
12292             if (complain & tf_error)
12293               {
12294                 if (TYPE_P (TREE_OPERAND (member, 0)))
12295                   error ("%qT is not a class or namespace",
12296                          TREE_OPERAND (member, 0));
12297                 else
12298                   error ("%qD is not a class or namespace",
12299                          TREE_OPERAND (member, 0));
12300               }
12301             return error_mark_node;
12302           }
12303         else if (TREE_CODE (member) == FIELD_DECL)
12304           return finish_non_static_data_member (member, object, NULL_TREE);
12305
12306         return finish_class_member_access_expr (object, member,
12307                                                 /*template_p=*/false,
12308                                                 complain);
12309       }
12310
12311     case THROW_EXPR:
12312       return build_throw
12313         (RECUR (TREE_OPERAND (t, 0)));
12314
12315     case CONSTRUCTOR:
12316       {
12317         VEC(constructor_elt,gc) *n;
12318         constructor_elt *ce;
12319         unsigned HOST_WIDE_INT idx;
12320         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12321         bool process_index_p;
12322         int newlen;
12323         bool need_copy_p = false;
12324         tree r;
12325
12326         if (type == error_mark_node)
12327           return error_mark_node;
12328
12329         /* digest_init will do the wrong thing if we let it.  */
12330         if (type && TYPE_PTRMEMFUNC_P (type))
12331           return t;
12332
12333         /* We do not want to process the index of aggregate
12334            initializers as they are identifier nodes which will be
12335            looked up by digest_init.  */
12336         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12337
12338         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12339         newlen = VEC_length (constructor_elt, n);
12340         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12341           {
12342             if (ce->index && process_index_p)
12343               ce->index = RECUR (ce->index);
12344
12345             if (PACK_EXPANSION_P (ce->value))
12346               {
12347                 /* Substitute into the pack expansion.  */
12348                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12349                                                   in_decl);
12350
12351                 if (ce->value == error_mark_node)
12352                   ;
12353                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12354                   /* Just move the argument into place.  */
12355                   ce->value = TREE_VEC_ELT (ce->value, 0);
12356                 else
12357                   {
12358                     /* Update the length of the final CONSTRUCTOR
12359                        arguments vector, and note that we will need to
12360                        copy.*/
12361                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12362                     need_copy_p = true;
12363                   }
12364               }
12365             else
12366               ce->value = RECUR (ce->value);
12367           }
12368
12369         if (need_copy_p)
12370           {
12371             VEC(constructor_elt,gc) *old_n = n;
12372
12373             n = VEC_alloc (constructor_elt, gc, newlen);
12374             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
12375                  idx++)
12376               {
12377                 if (TREE_CODE (ce->value) == TREE_VEC)
12378                   {
12379                     int i, len = TREE_VEC_LENGTH (ce->value);
12380                     for (i = 0; i < len; ++i)
12381                       CONSTRUCTOR_APPEND_ELT (n, 0,
12382                                               TREE_VEC_ELT (ce->value, i));
12383                   }
12384                 else
12385                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12386               }
12387           }
12388
12389         r = build_constructor (init_list_type_node, n);
12390         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12391
12392         if (TREE_HAS_CONSTRUCTOR (t))
12393           return finish_compound_literal (type, r);
12394
12395         return r;
12396       }
12397
12398     case TYPEID_EXPR:
12399       {
12400         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12401         if (TYPE_P (operand_0))
12402           return get_typeid (operand_0);
12403         return build_typeid (operand_0);
12404       }
12405
12406     case VAR_DECL:
12407       if (!args)
12408         return t;
12409       /* Fall through */
12410
12411     case PARM_DECL:
12412       {
12413         tree r = tsubst_copy (t, args, complain, in_decl);
12414
12415         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12416           /* If the original type was a reference, we'll be wrapped in
12417              the appropriate INDIRECT_REF.  */
12418           r = convert_from_reference (r);
12419         return r;
12420       }
12421
12422     case VA_ARG_EXPR:
12423       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12424                              tsubst_copy (TREE_TYPE (t), args, complain,
12425                                           in_decl));
12426
12427     case OFFSETOF_EXPR:
12428       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12429
12430     case TRAIT_EXPR:
12431       {
12432         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12433                                   complain, in_decl);
12434
12435         tree type2 = TRAIT_EXPR_TYPE2 (t);
12436         if (type2)
12437           type2 = tsubst_copy (type2, args, complain, in_decl);
12438         
12439         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12440       }
12441
12442     case STMT_EXPR:
12443       {
12444         tree old_stmt_expr = cur_stmt_expr;
12445         tree stmt_expr = begin_stmt_expr ();
12446
12447         cur_stmt_expr = stmt_expr;
12448         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12449                      integral_constant_expression_p);
12450         stmt_expr = finish_stmt_expr (stmt_expr, false);
12451         cur_stmt_expr = old_stmt_expr;
12452
12453         return stmt_expr;
12454       }
12455
12456     case CONST_DECL:
12457       t = tsubst_copy (t, args, complain, in_decl);
12458       /* As in finish_id_expression, we resolve enumeration constants
12459          to their underlying values.  */
12460       if (TREE_CODE (t) == CONST_DECL)
12461         {
12462           used_types_insert (TREE_TYPE (t));
12463           return DECL_INITIAL (t);
12464         }
12465       return t;
12466
12467     case LAMBDA_EXPR:
12468       {
12469         tree r = build_lambda_expr ();
12470
12471         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12472         TREE_TYPE (r) = type;
12473         CLASSTYPE_LAMBDA_EXPR (type) = r;
12474
12475         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12476           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12477         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12478         LAMBDA_EXPR_DISCRIMINATOR (r)
12479           = (LAMBDA_EXPR_DISCRIMINATOR (t));
12480         LAMBDA_EXPR_CAPTURE_LIST (r)
12481           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12482         LAMBDA_EXPR_THIS_CAPTURE (r)
12483           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12484         LAMBDA_EXPR_EXTRA_SCOPE (r)
12485           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12486
12487         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12488         determine_visibility (TYPE_NAME (type));
12489         /* Now that we know visibility, instantiate the type so we have a
12490            declaration of the op() for later calls to lambda_function.  */
12491         complete_type (type);
12492
12493         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12494         if (type)
12495           apply_lambda_return_type (r, type);
12496
12497         return build_lambda_object (r);
12498       }
12499
12500     default:
12501       /* Handle Objective-C++ constructs, if appropriate.  */
12502       {
12503         tree subst
12504           = objcp_tsubst_copy_and_build (t, args, complain,
12505                                          in_decl, /*function_p=*/false);
12506         if (subst)
12507           return subst;
12508       }
12509       return tsubst_copy (t, args, complain, in_decl);
12510     }
12511
12512 #undef RECUR
12513 }
12514
12515 /* Verify that the instantiated ARGS are valid. For type arguments,
12516    make sure that the type's linkage is ok. For non-type arguments,
12517    make sure they are constants if they are integral or enumerations.
12518    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12519
12520 static bool
12521 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12522 {
12523   if (ARGUMENT_PACK_P (t))
12524     {
12525       tree vec = ARGUMENT_PACK_ARGS (t);
12526       int len = TREE_VEC_LENGTH (vec);
12527       bool result = false;
12528       int i;
12529
12530       for (i = 0; i < len; ++i)
12531         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12532           result = true;
12533       return result;
12534     }
12535   else if (TYPE_P (t))
12536     {
12537       /* [basic.link]: A name with no linkage (notably, the name
12538          of a class or enumeration declared in a local scope)
12539          shall not be used to declare an entity with linkage.
12540          This implies that names with no linkage cannot be used as
12541          template arguments
12542
12543          DR 757 relaxes this restriction for C++0x.  */
12544       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
12545                  : no_linkage_check (t, /*relaxed_p=*/false));
12546
12547       if (nt)
12548         {
12549           /* DR 488 makes use of a type with no linkage cause
12550              type deduction to fail.  */
12551           if (complain & tf_error)
12552             {
12553               if (TYPE_ANONYMOUS_P (nt))
12554                 error ("%qT is/uses anonymous type", t);
12555               else
12556                 error ("template argument for %qD uses local type %qT",
12557                        tmpl, t);
12558             }
12559           return true;
12560         }
12561       /* In order to avoid all sorts of complications, we do not
12562          allow variably-modified types as template arguments.  */
12563       else if (variably_modified_type_p (t, NULL_TREE))
12564         {
12565           if (complain & tf_error)
12566             error ("%qT is a variably modified type", t);
12567           return true;
12568         }
12569     }
12570   /* A non-type argument of integral or enumerated type must be a
12571      constant.  */
12572   else if (TREE_TYPE (t)
12573            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12574            && !TREE_CONSTANT (t))
12575     {
12576       if (complain & tf_error)
12577         error ("integral expression %qE is not constant", t);
12578       return true;
12579     }
12580   return false;
12581 }
12582
12583 static bool
12584 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12585 {
12586   int ix, len = DECL_NTPARMS (tmpl);
12587   bool result = false;
12588
12589   for (ix = 0; ix != len; ix++)
12590     {
12591       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12592         result = true;
12593     }
12594   if (result && (complain & tf_error))
12595     error ("  trying to instantiate %qD", tmpl);
12596   return result;
12597 }
12598
12599 /* Instantiate the indicated variable or function template TMPL with
12600    the template arguments in TARG_PTR.  */
12601
12602 tree
12603 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
12604 {
12605   tree targ_ptr = orig_args;
12606   tree fndecl;
12607   tree gen_tmpl;
12608   tree spec;
12609   HOST_WIDE_INT saved_processing_template_decl;
12610
12611   if (tmpl == error_mark_node)
12612     return error_mark_node;
12613
12614   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12615
12616   /* If this function is a clone, handle it specially.  */
12617   if (DECL_CLONED_FUNCTION_P (tmpl))
12618     {
12619       tree spec;
12620       tree clone;
12621
12622       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
12623          DECL_CLONED_FUNCTION.  */
12624       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
12625                                    targ_ptr, complain);
12626       if (spec == error_mark_node)
12627         return error_mark_node;
12628
12629       /* Look for the clone.  */
12630       FOR_EACH_CLONE (clone, spec)
12631         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12632           return clone;
12633       /* We should always have found the clone by now.  */
12634       gcc_unreachable ();
12635       return NULL_TREE;
12636     }
12637
12638   /* Check to see if we already have this specialization.  */
12639   gen_tmpl = most_general_template (tmpl);
12640   if (tmpl != gen_tmpl)
12641     /* The TMPL is a partial instantiation.  To get a full set of
12642        arguments we must add the arguments used to perform the
12643        partial instantiation.  */
12644     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12645                                             targ_ptr);
12646
12647   /* It would be nice to avoid hashing here and then again in tsubst_decl,
12648      but it doesn't seem to be on the hot path.  */
12649   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
12650
12651   gcc_assert (tmpl == gen_tmpl
12652               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
12653                   == spec)
12654               || fndecl == NULL_TREE);
12655
12656   if (spec != NULL_TREE)
12657     return spec;
12658
12659   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12660                                complain))
12661     return error_mark_node;
12662
12663   /* We are building a FUNCTION_DECL, during which the access of its
12664      parameters and return types have to be checked.  However this
12665      FUNCTION_DECL which is the desired context for access checking
12666      is not built yet.  We solve this chicken-and-egg problem by
12667      deferring all checks until we have the FUNCTION_DECL.  */
12668   push_deferring_access_checks (dk_deferred);
12669
12670   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12671      (because, for example, we have encountered a non-dependent
12672      function call in the body of a template function and must now
12673      determine which of several overloaded functions will be called),
12674      within the instantiation itself we are not processing a
12675      template.  */  
12676   saved_processing_template_decl = processing_template_decl;
12677   processing_template_decl = 0;
12678   /* Substitute template parameters to obtain the specialization.  */
12679   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12680                    targ_ptr, complain, gen_tmpl);
12681   processing_template_decl = saved_processing_template_decl;
12682   if (fndecl == error_mark_node)
12683     return error_mark_node;
12684
12685   /* Now we know the specialization, compute access previously
12686      deferred.  */
12687   push_access_scope (fndecl);
12688
12689   /* Some typedefs referenced from within the template code need to be access
12690      checked at template instantiation time, i.e now. These types were
12691      added to the template at parsing time. Let's get those and perfom
12692      the acces checks then.  */
12693   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
12694   perform_deferred_access_checks ();
12695   pop_access_scope (fndecl);
12696   pop_deferring_access_checks ();
12697
12698   /* The DECL_TI_TEMPLATE should always be the immediate parent
12699      template, not the most general template.  */
12700   DECL_TI_TEMPLATE (fndecl) = tmpl;
12701
12702   /* If we've just instantiated the main entry point for a function,
12703      instantiate all the alternate entry points as well.  We do this
12704      by cloning the instantiation of the main entry point, not by
12705      instantiating the template clones.  */
12706   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
12707     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
12708
12709   return fndecl;
12710 }
12711
12712 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
12713    NARGS elements of the arguments that are being used when calling
12714    it.  TARGS is a vector into which the deduced template arguments
12715    are placed.
12716
12717    Return zero for success, 2 for an incomplete match that doesn't resolve
12718    all the types, and 1 for complete failure.  An error message will be
12719    printed only for an incomplete match.
12720
12721    If FN is a conversion operator, or we are trying to produce a specific
12722    specialization, RETURN_TYPE is the return type desired.
12723
12724    The EXPLICIT_TARGS are explicit template arguments provided via a
12725    template-id.
12726
12727    The parameter STRICT is one of:
12728
12729    DEDUCE_CALL:
12730      We are deducing arguments for a function call, as in
12731      [temp.deduct.call].
12732
12733    DEDUCE_CONV:
12734      We are deducing arguments for a conversion function, as in
12735      [temp.deduct.conv].
12736
12737    DEDUCE_EXACT:
12738      We are deducing arguments when doing an explicit instantiation
12739      as in [temp.explicit], when determining an explicit specialization
12740      as in [temp.expl.spec], or when taking the address of a function
12741      template, as in [temp.deduct.funcaddr].  */
12742
12743 int
12744 fn_type_unification (tree fn,
12745                      tree explicit_targs,
12746                      tree targs,
12747                      const tree *args,
12748                      unsigned int nargs,
12749                      tree return_type,
12750                      unification_kind_t strict,
12751                      int flags)
12752 {
12753   tree parms;
12754   tree fntype;
12755   int result;
12756   bool incomplete_argument_packs_p = false;
12757
12758   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12759
12760   fntype = TREE_TYPE (fn);
12761   if (explicit_targs)
12762     {
12763       /* [temp.deduct]
12764
12765          The specified template arguments must match the template
12766          parameters in kind (i.e., type, nontype, template), and there
12767          must not be more arguments than there are parameters;
12768          otherwise type deduction fails.
12769
12770          Nontype arguments must match the types of the corresponding
12771          nontype template parameters, or must be convertible to the
12772          types of the corresponding nontype parameters as specified in
12773          _temp.arg.nontype_, otherwise type deduction fails.
12774
12775          All references in the function type of the function template
12776          to the corresponding template parameters are replaced by the
12777          specified template argument values.  If a substitution in a
12778          template parameter or in the function type of the function
12779          template results in an invalid type, type deduction fails.  */
12780       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12781       int i, len = TREE_VEC_LENGTH (tparms);
12782       tree converted_args;
12783       bool incomplete = false;
12784
12785       if (explicit_targs == error_mark_node)
12786         return 1;
12787
12788       converted_args
12789         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12790                                   /*require_all_args=*/false,
12791                                   /*use_default_args=*/false));
12792       if (converted_args == error_mark_node)
12793         return 1;
12794
12795       /* Substitute the explicit args into the function type.  This is
12796          necessary so that, for instance, explicitly declared function
12797          arguments can match null pointed constants.  If we were given
12798          an incomplete set of explicit args, we must not do semantic
12799          processing during substitution as we could create partial
12800          instantiations.  */
12801       for (i = 0; i < len; i++)
12802         {
12803           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12804           bool parameter_pack = false;
12805
12806           /* Dig out the actual parm.  */
12807           if (TREE_CODE (parm) == TYPE_DECL
12808               || TREE_CODE (parm) == TEMPLATE_DECL)
12809             {
12810               parm = TREE_TYPE (parm);
12811               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12812             }
12813           else if (TREE_CODE (parm) == PARM_DECL)
12814             {
12815               parm = DECL_INITIAL (parm);
12816               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12817             }
12818
12819           if (parameter_pack)
12820             {
12821               int level, idx;
12822               tree targ;
12823               template_parm_level_and_index (parm, &level, &idx);
12824
12825               /* Mark the argument pack as "incomplete". We could
12826                  still deduce more arguments during unification.  */
12827               targ = TMPL_ARG (converted_args, level, idx);
12828               if (targ)
12829                 {
12830                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12831                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12832                     = ARGUMENT_PACK_ARGS (targ);
12833                 }
12834
12835               /* We have some incomplete argument packs.  */
12836               incomplete_argument_packs_p = true;
12837             }
12838         }
12839
12840       if (incomplete_argument_packs_p)
12841         /* Any substitution is guaranteed to be incomplete if there
12842            are incomplete argument packs, because we can still deduce
12843            more arguments.  */
12844         incomplete = 1;
12845       else
12846         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12847
12848       processing_template_decl += incomplete;
12849       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12850       processing_template_decl -= incomplete;
12851
12852       if (fntype == error_mark_node)
12853         return 1;
12854
12855       /* Place the explicitly specified arguments in TARGS.  */
12856       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12857         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12858     }
12859
12860   /* Never do unification on the 'this' parameter.  */
12861   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12862
12863   if (return_type)
12864     {
12865       tree *new_args;
12866
12867       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12868       new_args = XALLOCAVEC (tree, nargs + 1);
12869       new_args[0] = return_type;
12870       memcpy (new_args + 1, args, nargs * sizeof (tree));
12871       args = new_args;
12872       ++nargs;
12873     }
12874
12875   /* We allow incomplete unification without an error message here
12876      because the standard doesn't seem to explicitly prohibit it.  Our
12877      callers must be ready to deal with unification failures in any
12878      event.  */
12879   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12880                                   targs, parms, args, nargs, /*subr=*/0,
12881                                   strict, flags);
12882
12883   if (result == 0 && incomplete_argument_packs_p)
12884     {
12885       int i, len = NUM_TMPL_ARGS (targs);
12886
12887       /* Clear the "incomplete" flags on all argument packs.  */
12888       for (i = 0; i < len; i++)
12889         {
12890           tree arg = TREE_VEC_ELT (targs, i);
12891           if (ARGUMENT_PACK_P (arg))
12892             {
12893               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12894               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12895             }
12896         }
12897     }
12898
12899   /* Now that we have bindings for all of the template arguments,
12900      ensure that the arguments deduced for the template template
12901      parameters have compatible template parameter lists.  We cannot
12902      check this property before we have deduced all template
12903      arguments, because the template parameter types of a template
12904      template parameter might depend on prior template parameters
12905      deduced after the template template parameter.  The following
12906      ill-formed example illustrates this issue:
12907
12908        template<typename T, template<T> class C> void f(C<5>, T);
12909
12910        template<int N> struct X {};
12911
12912        void g() {
12913          f(X<5>(), 5l); // error: template argument deduction fails
12914        }
12915
12916      The template parameter list of 'C' depends on the template type
12917      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
12918      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
12919      time that we deduce 'C'.  */
12920   if (result == 0
12921       && !template_template_parm_bindings_ok_p 
12922            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
12923     return 1;
12924
12925   if (result == 0)
12926     /* All is well so far.  Now, check:
12927
12928        [temp.deduct]
12929
12930        When all template arguments have been deduced, all uses of
12931        template parameters in nondeduced contexts are replaced with
12932        the corresponding deduced argument values.  If the
12933        substitution results in an invalid type, as described above,
12934        type deduction fails.  */
12935     {
12936       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
12937       if (substed == error_mark_node)
12938         return 1;
12939
12940       /* If we're looking for an exact match, check that what we got
12941          is indeed an exact match.  It might not be if some template
12942          parameters are used in non-deduced contexts.  */
12943       if (strict == DEDUCE_EXACT)
12944         {
12945           unsigned int i;
12946
12947           tree sarg
12948             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
12949           if (return_type)
12950             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
12951           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
12952             if (!same_type_p (args[i], TREE_VALUE (sarg)))
12953               return 1;
12954         }
12955     }
12956
12957   return result;
12958 }
12959
12960 /* Adjust types before performing type deduction, as described in
12961    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
12962    sections are symmetric.  PARM is the type of a function parameter
12963    or the return type of the conversion function.  ARG is the type of
12964    the argument passed to the call, or the type of the value
12965    initialized with the result of the conversion function.
12966    ARG_EXPR is the original argument expression, which may be null.  */
12967
12968 static int
12969 maybe_adjust_types_for_deduction (unification_kind_t strict,
12970                                   tree* parm,
12971                                   tree* arg,
12972                                   tree arg_expr)
12973 {
12974   int result = 0;
12975
12976   switch (strict)
12977     {
12978     case DEDUCE_CALL:
12979       break;
12980
12981     case DEDUCE_CONV:
12982       {
12983         /* Swap PARM and ARG throughout the remainder of this
12984            function; the handling is precisely symmetric since PARM
12985            will initialize ARG rather than vice versa.  */
12986         tree* temp = parm;
12987         parm = arg;
12988         arg = temp;
12989         break;
12990       }
12991
12992     case DEDUCE_EXACT:
12993       /* Core issue #873: Do the DR606 thing (see below) for these cases,
12994          too, but here handle it by stripping the reference from PARM
12995          rather than by adding it to ARG.  */
12996       if (TREE_CODE (*parm) == REFERENCE_TYPE
12997           && TYPE_REF_IS_RVALUE (*parm)
12998           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
12999           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13000           && TREE_CODE (*arg) == REFERENCE_TYPE
13001           && !TYPE_REF_IS_RVALUE (*arg))
13002         *parm = TREE_TYPE (*parm);
13003       /* Nothing else to do in this case.  */
13004       return 0;
13005
13006     default:
13007       gcc_unreachable ();
13008     }
13009
13010   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13011     {
13012       /* [temp.deduct.call]
13013
13014          If P is not a reference type:
13015
13016          --If A is an array type, the pointer type produced by the
13017          array-to-pointer standard conversion (_conv.array_) is
13018          used in place of A for type deduction; otherwise,
13019
13020          --If A is a function type, the pointer type produced by
13021          the function-to-pointer standard conversion
13022          (_conv.func_) is used in place of A for type deduction;
13023          otherwise,
13024
13025          --If A is a cv-qualified type, the top level
13026          cv-qualifiers of A's type are ignored for type
13027          deduction.  */
13028       if (TREE_CODE (*arg) == ARRAY_TYPE)
13029         *arg = build_pointer_type (TREE_TYPE (*arg));
13030       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13031         *arg = build_pointer_type (*arg);
13032       else
13033         *arg = TYPE_MAIN_VARIANT (*arg);
13034     }
13035
13036   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13037      of the form T&&, where T is a template parameter, and the argument
13038      is an lvalue, T is deduced as A& */
13039   if (TREE_CODE (*parm) == REFERENCE_TYPE
13040       && TYPE_REF_IS_RVALUE (*parm)
13041       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13042       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13043       && arg_expr && real_lvalue_p (arg_expr))
13044     *arg = build_reference_type (*arg);
13045
13046   /* [temp.deduct.call]
13047
13048      If P is a cv-qualified type, the top level cv-qualifiers
13049      of P's type are ignored for type deduction.  If P is a
13050      reference type, the type referred to by P is used for
13051      type deduction.  */
13052   *parm = TYPE_MAIN_VARIANT (*parm);
13053   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13054     {
13055       *parm = TREE_TYPE (*parm);
13056       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13057     }
13058
13059   /* DR 322. For conversion deduction, remove a reference type on parm
13060      too (which has been swapped into ARG).  */
13061   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13062     *arg = TREE_TYPE (*arg);
13063
13064   return result;
13065 }
13066
13067 /* Most parms like fn_type_unification.
13068
13069    If SUBR is 1, we're being called recursively (to unify the
13070    arguments of a function or method parameter of a function
13071    template). */
13072
13073 static int
13074 type_unification_real (tree tparms,
13075                        tree targs,
13076                        tree xparms,
13077                        const tree *xargs,
13078                        unsigned int xnargs,
13079                        int subr,
13080                        unification_kind_t strict,
13081                        int flags)
13082 {
13083   tree parm, arg, arg_expr;
13084   int i;
13085   int ntparms = TREE_VEC_LENGTH (tparms);
13086   int sub_strict;
13087   int saw_undeduced = 0;
13088   tree parms;
13089   const tree *args;
13090   unsigned int nargs;
13091   unsigned int ia;
13092
13093   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13094   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13095   gcc_assert (ntparms > 0);
13096
13097   switch (strict)
13098     {
13099     case DEDUCE_CALL:
13100       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13101                     | UNIFY_ALLOW_DERIVED);
13102       break;
13103
13104     case DEDUCE_CONV:
13105       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13106       break;
13107
13108     case DEDUCE_EXACT:
13109       sub_strict = UNIFY_ALLOW_NONE;
13110       break;
13111
13112     default:
13113       gcc_unreachable ();
13114     }
13115
13116  again:
13117   parms = xparms;
13118   args = xargs;
13119   nargs = xnargs;
13120
13121   ia = 0;
13122   while (parms && parms != void_list_node
13123          && ia < nargs)
13124     {
13125       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13126         break;
13127
13128       parm = TREE_VALUE (parms);
13129       parms = TREE_CHAIN (parms);
13130       arg = args[ia];
13131       ++ia;
13132       arg_expr = NULL;
13133
13134       if (arg == error_mark_node)
13135         return 1;
13136       if (arg == unknown_type_node)
13137         /* We can't deduce anything from this, but we might get all the
13138            template args from other function args.  */
13139         continue;
13140
13141       /* Conversions will be performed on a function argument that
13142          corresponds with a function parameter that contains only
13143          non-deducible template parameters and explicitly specified
13144          template parameters.  */
13145       if (!uses_template_parms (parm))
13146         {
13147           tree type;
13148
13149           if (!TYPE_P (arg))
13150             type = TREE_TYPE (arg);
13151           else
13152             type = arg;
13153
13154           if (same_type_p (parm, type))
13155             continue;
13156           if (strict != DEDUCE_EXACT
13157               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13158                                   flags))
13159             continue;
13160
13161           return 1;
13162         }
13163
13164       if (!TYPE_P (arg))
13165         {
13166           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13167           if (type_unknown_p (arg))
13168             {
13169               /* [temp.deduct.type] 
13170
13171                  A template-argument can be deduced from a pointer to
13172                  function or pointer to member function argument if
13173                  the set of overloaded functions does not contain
13174                  function templates and at most one of a set of
13175                  overloaded functions provides a unique match.  */
13176               if (resolve_overloaded_unification
13177                   (tparms, targs, parm, arg, strict, sub_strict))
13178                 continue;
13179
13180               return 1;
13181             }
13182           arg_expr = arg;
13183           arg = unlowered_expr_type (arg);
13184           if (arg == error_mark_node)
13185             return 1;
13186         }
13187
13188       {
13189         int arg_strict = sub_strict;
13190
13191         if (!subr)
13192           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13193                                                           arg_expr);
13194
13195         if (arg == init_list_type_node && arg_expr)
13196           arg = arg_expr;
13197         if (unify (tparms, targs, parm, arg, arg_strict))
13198           return 1;
13199       }
13200     }
13201
13202
13203   if (parms 
13204       && parms != void_list_node
13205       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13206     {
13207       /* Unify the remaining arguments with the pack expansion type.  */
13208       tree argvec;
13209       tree parmvec = make_tree_vec (1);
13210
13211       /* Allocate a TREE_VEC and copy in all of the arguments */ 
13212       argvec = make_tree_vec (nargs - ia);
13213       for (i = 0; ia < nargs; ++ia, ++i)
13214         TREE_VEC_ELT (argvec, i) = args[ia];
13215
13216       /* Copy the parameter into parmvec.  */
13217       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13218       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13219                                 /*call_args_p=*/true, /*subr=*/subr))
13220         return 1;
13221
13222       /* Advance to the end of the list of parameters.  */
13223       parms = TREE_CHAIN (parms);
13224     }
13225
13226   /* Fail if we've reached the end of the parm list, and more args
13227      are present, and the parm list isn't variadic.  */
13228   if (ia < nargs && parms == void_list_node)
13229     return 1;
13230   /* Fail if parms are left and they don't have default values.  */
13231   if (parms && parms != void_list_node
13232       && TREE_PURPOSE (parms) == NULL_TREE)
13233     return 1;
13234
13235   if (!subr)
13236     for (i = 0; i < ntparms; i++)
13237       if (!TREE_VEC_ELT (targs, i))
13238         {
13239           tree tparm;
13240
13241           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13242             continue;
13243
13244           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13245
13246           /* If this is an undeduced nontype parameter that depends on
13247              a type parameter, try another pass; its type may have been
13248              deduced from a later argument than the one from which
13249              this parameter can be deduced.  */
13250           if (TREE_CODE (tparm) == PARM_DECL
13251               && uses_template_parms (TREE_TYPE (tparm))
13252               && !saw_undeduced++)
13253             goto again;
13254
13255           /* Core issue #226 (C++0x) [temp.deduct]:
13256
13257                If a template argument has not been deduced, its
13258                default template argument, if any, is used. 
13259
13260              When we are in C++98 mode, TREE_PURPOSE will either
13261              be NULL_TREE or ERROR_MARK_NODE, so we do not need
13262              to explicitly check cxx_dialect here.  */
13263           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13264             {
13265               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13266               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13267               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13268               arg = convert_template_argument (parm, arg, targs, tf_none,
13269                                                i, NULL_TREE);
13270               if (arg == error_mark_node)
13271                 return 1;
13272               else
13273                 {
13274                   TREE_VEC_ELT (targs, i) = arg;
13275                   continue;
13276                 }
13277             }
13278
13279           /* If the type parameter is a parameter pack, then it will
13280              be deduced to an empty parameter pack.  */
13281           if (template_parameter_pack_p (tparm))
13282             {
13283               tree arg;
13284
13285               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13286                 {
13287                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13288                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13289                   TREE_CONSTANT (arg) = 1;
13290                 }
13291               else
13292                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13293
13294               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13295
13296               TREE_VEC_ELT (targs, i) = arg;
13297               continue;
13298             }
13299
13300           return 2;
13301         }
13302
13303   return 0;
13304 }
13305
13306 /* Subroutine of type_unification_real.  Args are like the variables
13307    at the call site.  ARG is an overloaded function (or template-id);
13308    we try deducing template args from each of the overloads, and if
13309    only one succeeds, we go with that.  Modifies TARGS and returns
13310    true on success.  */
13311
13312 static bool
13313 resolve_overloaded_unification (tree tparms,
13314                                 tree targs,
13315                                 tree parm,
13316                                 tree arg,
13317                                 unification_kind_t strict,
13318                                 int sub_strict)
13319 {
13320   tree tempargs = copy_node (targs);
13321   int good = 0;
13322   tree goodfn = NULL_TREE;
13323   bool addr_p;
13324
13325   if (TREE_CODE (arg) == ADDR_EXPR)
13326     {
13327       arg = TREE_OPERAND (arg, 0);
13328       addr_p = true;
13329     }
13330   else
13331     addr_p = false;
13332
13333   if (TREE_CODE (arg) == COMPONENT_REF)
13334     /* Handle `&x' where `x' is some static or non-static member
13335        function name.  */
13336     arg = TREE_OPERAND (arg, 1);
13337
13338   if (TREE_CODE (arg) == OFFSET_REF)
13339     arg = TREE_OPERAND (arg, 1);
13340
13341   /* Strip baselink information.  */
13342   if (BASELINK_P (arg))
13343     arg = BASELINK_FUNCTIONS (arg);
13344
13345   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13346     {
13347       /* If we got some explicit template args, we need to plug them into
13348          the affected templates before we try to unify, in case the
13349          explicit args will completely resolve the templates in question.  */
13350
13351       tree expl_subargs = TREE_OPERAND (arg, 1);
13352       arg = TREE_OPERAND (arg, 0);
13353
13354       for (; arg; arg = OVL_NEXT (arg))
13355         {
13356           tree fn = OVL_CURRENT (arg);
13357           tree subargs, elem;
13358
13359           if (TREE_CODE (fn) != TEMPLATE_DECL)
13360             continue;
13361
13362           ++processing_template_decl;
13363           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13364                                   expl_subargs, /*check_ret=*/false);
13365           if (subargs)
13366             {
13367               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13368               if (try_one_overload (tparms, targs, tempargs, parm,
13369                                     elem, strict, sub_strict, addr_p)
13370                   && (!goodfn || !decls_match (goodfn, elem)))
13371                 {
13372                   goodfn = elem;
13373                   ++good;
13374                 }
13375             }
13376           --processing_template_decl;
13377         }
13378     }
13379   else if (TREE_CODE (arg) != OVERLOAD
13380            && TREE_CODE (arg) != FUNCTION_DECL)
13381     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13382        -- but the deduction does not succeed because the expression is
13383        not just the function on its own.  */
13384     return false;
13385   else
13386     for (; arg; arg = OVL_NEXT (arg))
13387       if (try_one_overload (tparms, targs, tempargs, parm,
13388                             TREE_TYPE (OVL_CURRENT (arg)),
13389                             strict, sub_strict, addr_p)
13390           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13391         {
13392           goodfn = OVL_CURRENT (arg);
13393           ++good;
13394         }
13395
13396   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13397      to function or pointer to member function argument if the set of
13398      overloaded functions does not contain function templates and at most
13399      one of a set of overloaded functions provides a unique match.
13400
13401      So if we found multiple possibilities, we return success but don't
13402      deduce anything.  */
13403
13404   if (good == 1)
13405     {
13406       int i = TREE_VEC_LENGTH (targs);
13407       for (; i--; )
13408         if (TREE_VEC_ELT (tempargs, i))
13409           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13410     }
13411   if (good)
13412     return true;
13413
13414   return false;
13415 }
13416
13417 /* Core DR 115: In contexts where deduction is done and fails, or in
13418    contexts where deduction is not done, if a template argument list is
13419    specified and it, along with any default template arguments, identifies
13420    a single function template specialization, then the template-id is an
13421    lvalue for the function template specialization.  */
13422
13423 tree
13424 resolve_nondeduced_context (tree orig_expr)
13425 {
13426   tree expr, offset, baselink;
13427   bool addr;
13428
13429   if (!type_unknown_p (orig_expr))
13430     return orig_expr;
13431
13432   expr = orig_expr;
13433   addr = false;
13434   offset = NULL_TREE;
13435   baselink = NULL_TREE;
13436
13437   if (TREE_CODE (expr) == ADDR_EXPR)
13438     {
13439       expr = TREE_OPERAND (expr, 0);
13440       addr = true;
13441     }
13442   if (TREE_CODE (expr) == OFFSET_REF)
13443     {
13444       offset = expr;
13445       expr = TREE_OPERAND (expr, 1);
13446     }
13447   if (TREE_CODE (expr) == BASELINK)
13448     {
13449       baselink = expr;
13450       expr = BASELINK_FUNCTIONS (expr);
13451     }
13452
13453   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13454     {
13455       int good = 0;
13456       tree goodfn = NULL_TREE;
13457
13458       /* If we got some explicit template args, we need to plug them into
13459          the affected templates before we try to unify, in case the
13460          explicit args will completely resolve the templates in question.  */
13461
13462       tree expl_subargs = TREE_OPERAND (expr, 1);
13463       tree arg = TREE_OPERAND (expr, 0);
13464       tree badfn = NULL_TREE;
13465       tree badargs = NULL_TREE;
13466
13467       for (; arg; arg = OVL_NEXT (arg))
13468         {
13469           tree fn = OVL_CURRENT (arg);
13470           tree subargs, elem;
13471
13472           if (TREE_CODE (fn) != TEMPLATE_DECL)
13473             continue;
13474
13475           ++processing_template_decl;
13476           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13477                                   expl_subargs, /*check_ret=*/false);
13478           if (subargs && !any_dependent_template_arguments_p (subargs))
13479             {
13480               elem = instantiate_template (fn, subargs, tf_none);
13481               if (elem == error_mark_node)
13482                 {
13483                   badfn = fn;
13484                   badargs = subargs;
13485                 }
13486               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13487                 {
13488                   goodfn = elem;
13489                   ++good;
13490                 }
13491             }
13492           --processing_template_decl;
13493         }
13494       if (good == 1)
13495         {
13496           expr = goodfn;
13497           if (baselink)
13498             expr = build_baselink (BASELINK_BINFO (baselink),
13499                                    BASELINK_ACCESS_BINFO (baselink),
13500                                    expr, BASELINK_OPTYPE (baselink));
13501           if (offset)
13502             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13503                            TREE_OPERAND (offset, 0), expr);
13504           if (addr)
13505             expr = build_address (expr);
13506           return expr;
13507         }
13508       else if (good == 0 && badargs)
13509         /* There were no good options and at least one bad one, so let the
13510            user know what the problem is.  */
13511         instantiate_template (badfn, badargs, tf_warning_or_error);
13512     }
13513   return orig_expr;
13514 }
13515
13516 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13517    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13518    different overloads deduce different arguments for a given parm.
13519    ADDR_P is true if the expression for which deduction is being
13520    performed was of the form "& fn" rather than simply "fn".
13521
13522    Returns 1 on success.  */
13523
13524 static int
13525 try_one_overload (tree tparms,
13526                   tree orig_targs,
13527                   tree targs,
13528                   tree parm,
13529                   tree arg,
13530                   unification_kind_t strict,
13531                   int sub_strict,
13532                   bool addr_p)
13533 {
13534   int nargs;
13535   tree tempargs;
13536   int i;
13537
13538   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13539      to function or pointer to member function argument if the set of
13540      overloaded functions does not contain function templates and at most
13541      one of a set of overloaded functions provides a unique match.
13542
13543      So if this is a template, just return success.  */
13544
13545   if (uses_template_parms (arg))
13546     return 1;
13547
13548   if (TREE_CODE (arg) == METHOD_TYPE)
13549     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13550   else if (addr_p)
13551     arg = build_pointer_type (arg);
13552
13553   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13554
13555   /* We don't copy orig_targs for this because if we have already deduced
13556      some template args from previous args, unify would complain when we
13557      try to deduce a template parameter for the same argument, even though
13558      there isn't really a conflict.  */
13559   nargs = TREE_VEC_LENGTH (targs);
13560   tempargs = make_tree_vec (nargs);
13561
13562   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13563     return 0;
13564
13565   /* First make sure we didn't deduce anything that conflicts with
13566      explicitly specified args.  */
13567   for (i = nargs; i--; )
13568     {
13569       tree elt = TREE_VEC_ELT (tempargs, i);
13570       tree oldelt = TREE_VEC_ELT (orig_targs, i);
13571
13572       if (!elt)
13573         /*NOP*/;
13574       else if (uses_template_parms (elt))
13575         /* Since we're unifying against ourselves, we will fill in
13576            template args used in the function parm list with our own
13577            template parms.  Discard them.  */
13578         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13579       else if (oldelt && !template_args_equal (oldelt, elt))
13580         return 0;
13581     }
13582
13583   for (i = nargs; i--; )
13584     {
13585       tree elt = TREE_VEC_ELT (tempargs, i);
13586
13587       if (elt)
13588         TREE_VEC_ELT (targs, i) = elt;
13589     }
13590
13591   return 1;
13592 }
13593
13594 /* PARM is a template class (perhaps with unbound template
13595    parameters).  ARG is a fully instantiated type.  If ARG can be
13596    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
13597    TARGS are as for unify.  */
13598
13599 static tree
13600 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
13601 {
13602   tree copy_of_targs;
13603
13604   if (!CLASSTYPE_TEMPLATE_INFO (arg)
13605       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
13606           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
13607     return NULL_TREE;
13608
13609   /* We need to make a new template argument vector for the call to
13610      unify.  If we used TARGS, we'd clutter it up with the result of
13611      the attempted unification, even if this class didn't work out.
13612      We also don't want to commit ourselves to all the unifications
13613      we've already done, since unification is supposed to be done on
13614      an argument-by-argument basis.  In other words, consider the
13615      following pathological case:
13616
13617        template <int I, int J, int K>
13618        struct S {};
13619
13620        template <int I, int J>
13621        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
13622
13623        template <int I, int J, int K>
13624        void f(S<I, J, K>, S<I, I, I>);
13625
13626        void g() {
13627          S<0, 0, 0> s0;
13628          S<0, 1, 2> s2;
13629
13630          f(s0, s2);
13631        }
13632
13633      Now, by the time we consider the unification involving `s2', we
13634      already know that we must have `f<0, 0, 0>'.  But, even though
13635      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
13636      because there are two ways to unify base classes of S<0, 1, 2>
13637      with S<I, I, I>.  If we kept the already deduced knowledge, we
13638      would reject the possibility I=1.  */
13639   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
13640
13641   /* If unification failed, we're done.  */
13642   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
13643              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
13644     return NULL_TREE;
13645
13646   return arg;
13647 }
13648
13649 /* Given a template type PARM and a class type ARG, find the unique
13650    base type in ARG that is an instance of PARM.  We do not examine
13651    ARG itself; only its base-classes.  If there is not exactly one
13652    appropriate base class, return NULL_TREE.  PARM may be the type of
13653    a partial specialization, as well as a plain template type.  Used
13654    by unify.  */
13655
13656 static tree
13657 get_template_base (tree tparms, tree targs, tree parm, tree arg)
13658 {
13659   tree rval = NULL_TREE;
13660   tree binfo;
13661
13662   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
13663
13664   binfo = TYPE_BINFO (complete_type (arg));
13665   if (!binfo)
13666     /* The type could not be completed.  */
13667     return NULL_TREE;
13668
13669   /* Walk in inheritance graph order.  The search order is not
13670      important, and this avoids multiple walks of virtual bases.  */
13671   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
13672     {
13673       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
13674
13675       if (r)
13676         {
13677           /* If there is more than one satisfactory baseclass, then:
13678
13679                [temp.deduct.call]
13680
13681               If they yield more than one possible deduced A, the type
13682               deduction fails.
13683
13684              applies.  */
13685           if (rval && !same_type_p (r, rval))
13686             return NULL_TREE;
13687
13688           rval = r;
13689         }
13690     }
13691
13692   return rval;
13693 }
13694
13695 /* Returns the level of DECL, which declares a template parameter.  */
13696
13697 static int
13698 template_decl_level (tree decl)
13699 {
13700   switch (TREE_CODE (decl))
13701     {
13702     case TYPE_DECL:
13703     case TEMPLATE_DECL:
13704       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
13705
13706     case PARM_DECL:
13707       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
13708
13709     default:
13710       gcc_unreachable ();
13711     }
13712   return 0;
13713 }
13714
13715 /* Decide whether ARG can be unified with PARM, considering only the
13716    cv-qualifiers of each type, given STRICT as documented for unify.
13717    Returns nonzero iff the unification is OK on that basis.  */
13718
13719 static int
13720 check_cv_quals_for_unify (int strict, tree arg, tree parm)
13721 {
13722   int arg_quals = cp_type_quals (arg);
13723   int parm_quals = cp_type_quals (parm);
13724
13725   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13726       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13727     {
13728       /*  Although a CVR qualifier is ignored when being applied to a
13729           substituted template parameter ([8.3.2]/1 for example), that
13730           does not apply during deduction [14.8.2.4]/1, (even though
13731           that is not explicitly mentioned, [14.8.2.4]/9 indicates
13732           this).  Except when we're allowing additional CV qualifiers
13733           at the outer level [14.8.2.1]/3,1st bullet.  */
13734       if ((TREE_CODE (arg) == REFERENCE_TYPE
13735            || TREE_CODE (arg) == FUNCTION_TYPE
13736            || TREE_CODE (arg) == METHOD_TYPE)
13737           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
13738         return 0;
13739
13740       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
13741           && (parm_quals & TYPE_QUAL_RESTRICT))
13742         return 0;
13743     }
13744
13745   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13746       && (arg_quals & parm_quals) != parm_quals)
13747     return 0;
13748
13749   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
13750       && (parm_quals & arg_quals) != arg_quals)
13751     return 0;
13752
13753   return 1;
13754 }
13755
13756 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
13757 void 
13758 template_parm_level_and_index (tree parm, int* level, int* index)
13759 {
13760   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13761       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13762       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13763     {
13764       *index = TEMPLATE_TYPE_IDX (parm);
13765       *level = TEMPLATE_TYPE_LEVEL (parm);
13766     }
13767   else
13768     {
13769       *index = TEMPLATE_PARM_IDX (parm);
13770       *level = TEMPLATE_PARM_LEVEL (parm);
13771     }
13772 }
13773
13774 /* Unifies the remaining arguments in PACKED_ARGS with the pack
13775    expansion at the end of PACKED_PARMS. Returns 0 if the type
13776    deduction succeeds, 1 otherwise. STRICT is the same as in
13777    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
13778    call argument list. We'll need to adjust the arguments to make them
13779    types. SUBR tells us if this is from a recursive call to
13780    type_unification_real.  */
13781 int
13782 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
13783                       tree packed_args, int strict, bool call_args_p,
13784                       bool subr)
13785 {
13786   tree parm 
13787     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
13788   tree pattern = PACK_EXPANSION_PATTERN (parm);
13789   tree pack, packs = NULL_TREE;
13790   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
13791   int len = TREE_VEC_LENGTH (packed_args);
13792
13793   /* Determine the parameter packs we will be deducing from the
13794      pattern, and record their current deductions.  */
13795   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
13796        pack; pack = TREE_CHAIN (pack))
13797     {
13798       tree parm_pack = TREE_VALUE (pack);
13799       int idx, level;
13800
13801       /* Determine the index and level of this parameter pack.  */
13802       template_parm_level_and_index (parm_pack, &level, &idx);
13803
13804       /* Keep track of the parameter packs and their corresponding
13805          argument packs.  */
13806       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
13807       TREE_TYPE (packs) = make_tree_vec (len - start);
13808     }
13809   
13810   /* Loop through all of the arguments that have not yet been
13811      unified and unify each with the pattern.  */
13812   for (i = start; i < len; i++)
13813     {
13814       tree parm = pattern;
13815
13816       /* For each parameter pack, clear out the deduced value so that
13817          we can deduce it again.  */
13818       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13819         {
13820           int idx, level;
13821           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13822
13823           TMPL_ARG (targs, level, idx) = NULL_TREE;
13824         }
13825
13826       /* Unify the pattern with the current argument.  */
13827       {
13828         tree arg = TREE_VEC_ELT (packed_args, i);
13829         tree arg_expr = NULL_TREE;
13830         int arg_strict = strict;
13831         bool skip_arg_p = false;
13832
13833         if (call_args_p)
13834           {
13835             int sub_strict;
13836
13837             /* This mirrors what we do in type_unification_real.  */
13838             switch (strict)
13839               {
13840               case DEDUCE_CALL:
13841                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
13842                               | UNIFY_ALLOW_MORE_CV_QUAL
13843                               | UNIFY_ALLOW_DERIVED);
13844                 break;
13845                 
13846               case DEDUCE_CONV:
13847                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13848                 break;
13849                 
13850               case DEDUCE_EXACT:
13851                 sub_strict = UNIFY_ALLOW_NONE;
13852                 break;
13853                 
13854               default:
13855                 gcc_unreachable ();
13856               }
13857
13858             if (!TYPE_P (arg))
13859               {
13860                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13861                 if (type_unknown_p (arg))
13862                   {
13863                     /* [temp.deduct.type] A template-argument can be
13864                        deduced from a pointer to function or pointer
13865                        to member function argument if the set of
13866                        overloaded functions does not contain function
13867                        templates and at most one of a set of
13868                        overloaded functions provides a unique
13869                        match.  */
13870
13871                     if (resolve_overloaded_unification
13872                         (tparms, targs, parm, arg,
13873                          (unification_kind_t) strict,
13874                          sub_strict)
13875                         != 0)
13876                       return 1;
13877                     skip_arg_p = true;
13878                   }
13879
13880                 if (!skip_arg_p)
13881                   {
13882                     arg_expr = arg;
13883                     arg = unlowered_expr_type (arg);
13884                     if (arg == error_mark_node)
13885                       return 1;
13886                   }
13887               }
13888       
13889             arg_strict = sub_strict;
13890
13891             if (!subr)
13892               arg_strict |= 
13893                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
13894                                                   &parm, &arg, arg_expr);
13895           }
13896
13897         if (!skip_arg_p)
13898           {
13899             if (unify (tparms, targs, parm, arg, arg_strict))
13900               return 1;
13901           }
13902       }
13903
13904       /* For each parameter pack, collect the deduced value.  */
13905       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13906         {
13907           int idx, level;
13908           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13909
13910           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
13911             TMPL_ARG (targs, level, idx);
13912         }
13913     }
13914
13915   /* Verify that the results of unification with the parameter packs
13916      produce results consistent with what we've seen before, and make
13917      the deduced argument packs available.  */
13918   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13919     {
13920       tree old_pack = TREE_VALUE (pack);
13921       tree new_args = TREE_TYPE (pack);
13922       int i, len = TREE_VEC_LENGTH (new_args);
13923       bool nondeduced_p = false;
13924
13925       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
13926          actually deduce anything.  */
13927       for (i = 0; i < len && !nondeduced_p; ++i)
13928         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
13929           nondeduced_p = true;
13930       if (nondeduced_p)
13931         continue;
13932
13933       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
13934         {
13935           /* Prepend the explicit arguments onto NEW_ARGS.  */
13936           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13937           tree old_args = new_args;
13938           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
13939           int len = explicit_len + TREE_VEC_LENGTH (old_args);
13940
13941           /* Copy the explicit arguments.  */
13942           new_args = make_tree_vec (len);
13943           for (i = 0; i < explicit_len; i++)
13944             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
13945
13946           /* Copy the deduced arguments.  */
13947           for (; i < len; i++)
13948             TREE_VEC_ELT (new_args, i) =
13949               TREE_VEC_ELT (old_args, i - explicit_len);
13950         }
13951
13952       if (!old_pack)
13953         {
13954           tree result;
13955           int idx, level;
13956           
13957           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13958
13959           /* Build the deduced *_ARGUMENT_PACK.  */
13960           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
13961             {
13962               result = make_node (NONTYPE_ARGUMENT_PACK);
13963               TREE_TYPE (result) = 
13964                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
13965               TREE_CONSTANT (result) = 1;
13966             }
13967           else
13968             result = cxx_make_type (TYPE_ARGUMENT_PACK);
13969
13970           SET_ARGUMENT_PACK_ARGS (result, new_args);
13971
13972           /* Note the deduced argument packs for this parameter
13973              pack.  */
13974           TMPL_ARG (targs, level, idx) = result;
13975         }
13976       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
13977                && (ARGUMENT_PACK_ARGS (old_pack) 
13978                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
13979         {
13980           /* We only had the explicitly-provided arguments before, but
13981              now we have a complete set of arguments.  */
13982           int idx, level;
13983           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13984           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13985
13986           /* Keep the original deduced argument pack.  */
13987           TMPL_ARG (targs, level, idx) = old_pack;
13988
13989           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
13990           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
13991           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
13992         }
13993       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
13994                                     new_args))
13995         /* Inconsistent unification of this parameter pack.  */
13996         return 1;
13997       else
13998         {
13999           int idx, level;
14000           
14001           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14002
14003           /* Keep the original deduced argument pack.  */
14004           TMPL_ARG (targs, level, idx) = old_pack;
14005         }
14006     }
14007
14008   return 0;
14009 }
14010
14011 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14012    set of template parameters to a template.  TARGS is the bindings
14013    for those template parameters, as determined thus far; TARGS may
14014    include template arguments for outer levels of template parameters
14015    as well.  PARM is a parameter to a template function, or a
14016    subcomponent of that parameter; ARG is the corresponding argument.
14017    This function attempts to match PARM with ARG in a manner
14018    consistent with the existing assignments in TARGS.  If more values
14019    are deduced, then TARGS is updated.
14020
14021    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14022    parameter STRICT is a bitwise or of the following flags:
14023
14024      UNIFY_ALLOW_NONE:
14025        Require an exact match between PARM and ARG.
14026      UNIFY_ALLOW_MORE_CV_QUAL:
14027        Allow the deduced ARG to be more cv-qualified (by qualification
14028        conversion) than ARG.
14029      UNIFY_ALLOW_LESS_CV_QUAL:
14030        Allow the deduced ARG to be less cv-qualified than ARG.
14031      UNIFY_ALLOW_DERIVED:
14032        Allow the deduced ARG to be a template base class of ARG,
14033        or a pointer to a template base class of the type pointed to by
14034        ARG.
14035      UNIFY_ALLOW_INTEGER:
14036        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14037        case for more information.
14038      UNIFY_ALLOW_OUTER_LEVEL:
14039        This is the outermost level of a deduction. Used to determine validity
14040        of qualification conversions. A valid qualification conversion must
14041        have const qualified pointers leading up to the inner type which
14042        requires additional CV quals, except at the outer level, where const
14043        is not required [conv.qual]. It would be normal to set this flag in
14044        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14045      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14046        This is the outermost level of a deduction, and PARM can be more CV
14047        qualified at this point.
14048      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14049        This is the outermost level of a deduction, and PARM can be less CV
14050        qualified at this point.  */
14051
14052 static int
14053 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14054 {
14055   int idx;
14056   tree targ;
14057   tree tparm;
14058   int strict_in = strict;
14059
14060   /* I don't think this will do the right thing with respect to types.
14061      But the only case I've seen it in so far has been array bounds, where
14062      signedness is the only information lost, and I think that will be
14063      okay.  */
14064   while (TREE_CODE (parm) == NOP_EXPR)
14065     parm = TREE_OPERAND (parm, 0);
14066
14067   if (arg == error_mark_node)
14068     return 1;
14069   if (arg == unknown_type_node
14070       || arg == init_list_type_node)
14071     /* We can't deduce anything from this, but we might get all the
14072        template args from other function args.  */
14073     return 0;
14074
14075   /* If PARM uses template parameters, then we can't bail out here,
14076      even if ARG == PARM, since we won't record unifications for the
14077      template parameters.  We might need them if we're trying to
14078      figure out which of two things is more specialized.  */
14079   if (arg == parm && !uses_template_parms (parm))
14080     return 0;
14081
14082   /* Handle init lists early, so the rest of the function can assume
14083      we're dealing with a type. */
14084   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14085     {
14086       tree elt, elttype;
14087       unsigned i;
14088       tree orig_parm = parm;
14089
14090       /* Replace T with std::initializer_list<T> for deduction.  */
14091       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14092           && flag_deduce_init_list)
14093         parm = listify (parm);
14094
14095       if (!is_std_init_list (parm))
14096         /* We can only deduce from an initializer list argument if the
14097            parameter is std::initializer_list; otherwise this is a
14098            non-deduced context. */
14099         return 0;
14100
14101       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14102
14103       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14104         {
14105           int elt_strict = strict;
14106           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14107             {
14108               tree type = TREE_TYPE (elt);
14109               /* It should only be possible to get here for a call.  */
14110               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14111               elt_strict |= maybe_adjust_types_for_deduction
14112                 (DEDUCE_CALL, &elttype, &type, elt);
14113               elt = type;
14114             }
14115
14116           if (unify (tparms, targs, elttype, elt, elt_strict))
14117             return 1;
14118         }
14119
14120       /* If the std::initializer_list<T> deduction worked, replace the
14121          deduced A with std::initializer_list<A>.  */
14122       if (orig_parm != parm)
14123         {
14124           idx = TEMPLATE_TYPE_IDX (orig_parm);
14125           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14126           targ = listify (targ);
14127           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14128         }
14129       return 0;
14130     }
14131
14132   /* Immediately reject some pairs that won't unify because of
14133      cv-qualification mismatches.  */
14134   if (TREE_CODE (arg) == TREE_CODE (parm)
14135       && TYPE_P (arg)
14136       /* It is the elements of the array which hold the cv quals of an array
14137          type, and the elements might be template type parms. We'll check
14138          when we recurse.  */
14139       && TREE_CODE (arg) != ARRAY_TYPE
14140       /* We check the cv-qualifiers when unifying with template type
14141          parameters below.  We want to allow ARG `const T' to unify with
14142          PARM `T' for example, when computing which of two templates
14143          is more specialized, for example.  */
14144       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14145       && !check_cv_quals_for_unify (strict_in, arg, parm))
14146     return 1;
14147
14148   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14149       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14150     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14151   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14152   strict &= ~UNIFY_ALLOW_DERIVED;
14153   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14154   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14155
14156   switch (TREE_CODE (parm))
14157     {
14158     case TYPENAME_TYPE:
14159     case SCOPE_REF:
14160     case UNBOUND_CLASS_TEMPLATE:
14161       /* In a type which contains a nested-name-specifier, template
14162          argument values cannot be deduced for template parameters used
14163          within the nested-name-specifier.  */
14164       return 0;
14165
14166     case TEMPLATE_TYPE_PARM:
14167     case TEMPLATE_TEMPLATE_PARM:
14168     case BOUND_TEMPLATE_TEMPLATE_PARM:
14169       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14170       if (tparm == error_mark_node)
14171         return 1;
14172
14173       if (TEMPLATE_TYPE_LEVEL (parm)
14174           != template_decl_level (tparm))
14175         /* The PARM is not one we're trying to unify.  Just check
14176            to see if it matches ARG.  */
14177         return (TREE_CODE (arg) == TREE_CODE (parm)
14178                 && same_type_p (parm, arg)) ? 0 : 1;
14179       idx = TEMPLATE_TYPE_IDX (parm);
14180       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14181       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14182
14183       /* Check for mixed types and values.  */
14184       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14185            && TREE_CODE (tparm) != TYPE_DECL)
14186           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14187               && TREE_CODE (tparm) != TEMPLATE_DECL))
14188         return 1;
14189
14190       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14191         {
14192           /* ARG must be constructed from a template class or a template
14193              template parameter.  */
14194           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14195               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14196             return 1;
14197
14198           {
14199             tree parmvec = TYPE_TI_ARGS (parm);
14200             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14201             tree parm_parms 
14202               = DECL_INNERMOST_TEMPLATE_PARMS
14203                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14204             int i, len;
14205             int parm_variadic_p = 0;
14206
14207             /* The resolution to DR150 makes clear that default
14208                arguments for an N-argument may not be used to bind T
14209                to a template template parameter with fewer than N
14210                parameters.  It is not safe to permit the binding of
14211                default arguments as an extension, as that may change
14212                the meaning of a conforming program.  Consider:
14213
14214                   struct Dense { static const unsigned int dim = 1; };
14215
14216                   template <template <typename> class View,
14217                             typename Block>
14218                   void operator+(float, View<Block> const&);
14219
14220                   template <typename Block,
14221                             unsigned int Dim = Block::dim>
14222                   struct Lvalue_proxy { operator float() const; };
14223
14224                   void
14225                   test_1d (void) {
14226                     Lvalue_proxy<Dense> p;
14227                     float b;
14228                     b + p;
14229                   }
14230
14231               Here, if Lvalue_proxy is permitted to bind to View, then
14232               the global operator+ will be used; if they are not, the
14233               Lvalue_proxy will be converted to float.  */
14234             if (coerce_template_parms (parm_parms,
14235                                        argvec,
14236                                        TYPE_TI_TEMPLATE (parm),
14237                                        tf_none,
14238                                        /*require_all_args=*/true,
14239                                        /*use_default_args=*/false)
14240                 == error_mark_node)
14241               return 1;
14242
14243             /* Deduce arguments T, i from TT<T> or TT<i>.
14244                We check each element of PARMVEC and ARGVEC individually
14245                rather than the whole TREE_VEC since they can have
14246                different number of elements.  */
14247
14248             parmvec = expand_template_argument_pack (parmvec);
14249             argvec = expand_template_argument_pack (argvec);
14250
14251             len = TREE_VEC_LENGTH (parmvec);
14252
14253             /* Check if the parameters end in a pack, making them
14254                variadic.  */
14255             if (len > 0
14256                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14257               parm_variadic_p = 1;
14258             
14259             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14260               return 1;
14261
14262              for (i = 0; i < len - parm_variadic_p; ++i)
14263               {
14264                 if (unify (tparms, targs,
14265                            TREE_VEC_ELT (parmvec, i),
14266                            TREE_VEC_ELT (argvec, i),
14267                            UNIFY_ALLOW_NONE))
14268                   return 1;
14269               }
14270
14271             if (parm_variadic_p
14272                 && unify_pack_expansion (tparms, targs,
14273                                          parmvec, argvec,
14274                                          UNIFY_ALLOW_NONE,
14275                                          /*call_args_p=*/false,
14276                                          /*subr=*/false))
14277               return 1;
14278           }
14279           arg = TYPE_TI_TEMPLATE (arg);
14280
14281           /* Fall through to deduce template name.  */
14282         }
14283
14284       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14285           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14286         {
14287           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14288
14289           /* Simple cases: Value already set, does match or doesn't.  */
14290           if (targ != NULL_TREE && template_args_equal (targ, arg))
14291             return 0;
14292           else if (targ)
14293             return 1;
14294         }
14295       else
14296         {
14297           /* If PARM is `const T' and ARG is only `int', we don't have
14298              a match unless we are allowing additional qualification.
14299              If ARG is `const int' and PARM is just `T' that's OK;
14300              that binds `const int' to `T'.  */
14301           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14302                                          arg, parm))
14303             return 1;
14304
14305           /* Consider the case where ARG is `const volatile int' and
14306              PARM is `const T'.  Then, T should be `volatile int'.  */
14307           arg = cp_build_qualified_type_real
14308             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14309           if (arg == error_mark_node)
14310             return 1;
14311
14312           /* Simple cases: Value already set, does match or doesn't.  */
14313           if (targ != NULL_TREE && same_type_p (targ, arg))
14314             return 0;
14315           else if (targ)
14316             return 1;
14317
14318           /* Make sure that ARG is not a variable-sized array.  (Note
14319              that were talking about variable-sized arrays (like
14320              `int[n]'), rather than arrays of unknown size (like
14321              `int[]').)  We'll get very confused by such a type since
14322              the bound of the array will not be computable in an
14323              instantiation.  Besides, such types are not allowed in
14324              ISO C++, so we can do as we please here.  */
14325           if (variably_modified_type_p (arg, NULL_TREE))
14326             return 1;
14327
14328           /* Strip typedefs as in convert_template_argument.  */
14329           arg = strip_typedefs (arg);
14330         }
14331
14332       /* If ARG is a parameter pack or an expansion, we cannot unify
14333          against it unless PARM is also a parameter pack.  */
14334       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14335           && !template_parameter_pack_p (parm))
14336         return 1;
14337
14338       /* If the argument deduction results is a METHOD_TYPE,
14339          then there is a problem.
14340          METHOD_TYPE doesn't map to any real C++ type the result of
14341          the deduction can not be of that type.  */
14342       if (TREE_CODE (arg) == METHOD_TYPE)
14343         return 1;
14344
14345       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14346       return 0;
14347
14348     case TEMPLATE_PARM_INDEX:
14349       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14350       if (tparm == error_mark_node)
14351         return 1;
14352
14353       if (TEMPLATE_PARM_LEVEL (parm)
14354           != template_decl_level (tparm))
14355         /* The PARM is not one we're trying to unify.  Just check
14356            to see if it matches ARG.  */
14357         return !(TREE_CODE (arg) == TREE_CODE (parm)
14358                  && cp_tree_equal (parm, arg));
14359
14360       idx = TEMPLATE_PARM_IDX (parm);
14361       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14362
14363       if (targ)
14364         return !cp_tree_equal (targ, arg);
14365
14366       /* [temp.deduct.type] If, in the declaration of a function template
14367          with a non-type template-parameter, the non-type
14368          template-parameter is used in an expression in the function
14369          parameter-list and, if the corresponding template-argument is
14370          deduced, the template-argument type shall match the type of the
14371          template-parameter exactly, except that a template-argument
14372          deduced from an array bound may be of any integral type.
14373          The non-type parameter might use already deduced type parameters.  */
14374       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14375       if (!TREE_TYPE (arg))
14376         /* Template-parameter dependent expression.  Just accept it for now.
14377            It will later be processed in convert_template_argument.  */
14378         ;
14379       else if (same_type_p (TREE_TYPE (arg), tparm))
14380         /* OK */;
14381       else if ((strict & UNIFY_ALLOW_INTEGER)
14382                && (TREE_CODE (tparm) == INTEGER_TYPE
14383                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
14384         /* Convert the ARG to the type of PARM; the deduced non-type
14385            template argument must exactly match the types of the
14386            corresponding parameter.  */
14387         arg = fold (build_nop (tparm, arg));
14388       else if (uses_template_parms (tparm))
14389         /* We haven't deduced the type of this parameter yet.  Try again
14390            later.  */
14391         return 0;
14392       else
14393         return 1;
14394
14395       /* If ARG is a parameter pack or an expansion, we cannot unify
14396          against it unless PARM is also a parameter pack.  */
14397       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14398           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14399         return 1;
14400
14401       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14402       return 0;
14403
14404     case PTRMEM_CST:
14405      {
14406         /* A pointer-to-member constant can be unified only with
14407          another constant.  */
14408       if (TREE_CODE (arg) != PTRMEM_CST)
14409         return 1;
14410
14411       /* Just unify the class member. It would be useless (and possibly
14412          wrong, depending on the strict flags) to unify also
14413          PTRMEM_CST_CLASS, because we want to be sure that both parm and
14414          arg refer to the same variable, even if through different
14415          classes. For instance:
14416
14417          struct A { int x; };
14418          struct B : A { };
14419
14420          Unification of &A::x and &B::x must succeed.  */
14421       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14422                     PTRMEM_CST_MEMBER (arg), strict);
14423      }
14424
14425     case POINTER_TYPE:
14426       {
14427         if (TREE_CODE (arg) != POINTER_TYPE)
14428           return 1;
14429
14430         /* [temp.deduct.call]
14431
14432            A can be another pointer or pointer to member type that can
14433            be converted to the deduced A via a qualification
14434            conversion (_conv.qual_).
14435
14436            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14437            This will allow for additional cv-qualification of the
14438            pointed-to types if appropriate.  */
14439
14440         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14441           /* The derived-to-base conversion only persists through one
14442              level of pointers.  */
14443           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14444
14445         return unify (tparms, targs, TREE_TYPE (parm),
14446                       TREE_TYPE (arg), strict);
14447       }
14448
14449     case REFERENCE_TYPE:
14450       if (TREE_CODE (arg) != REFERENCE_TYPE)
14451         return 1;
14452       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14453                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14454
14455     case ARRAY_TYPE:
14456       if (TREE_CODE (arg) != ARRAY_TYPE)
14457         return 1;
14458       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14459           != (TYPE_DOMAIN (arg) == NULL_TREE))
14460         return 1;
14461       if (TYPE_DOMAIN (parm) != NULL_TREE)
14462         {
14463           tree parm_max;
14464           tree arg_max;
14465           bool parm_cst;
14466           bool arg_cst;
14467
14468           /* Our representation of array types uses "N - 1" as the
14469              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14470              not an integer constant.  We cannot unify arbitrarily
14471              complex expressions, so we eliminate the MINUS_EXPRs
14472              here.  */
14473           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14474           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14475           if (!parm_cst)
14476             {
14477               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14478               parm_max = TREE_OPERAND (parm_max, 0);
14479             }
14480           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14481           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14482           if (!arg_cst)
14483             {
14484               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14485                  trying to unify the type of a variable with the type
14486                  of a template parameter.  For example:
14487
14488                    template <unsigned int N>
14489                    void f (char (&) [N]);
14490                    int g(); 
14491                    void h(int i) {
14492                      char a[g(i)];
14493                      f(a); 
14494                    }
14495
14496                 Here, the type of the ARG will be "int [g(i)]", and
14497                 may be a SAVE_EXPR, etc.  */
14498               if (TREE_CODE (arg_max) != MINUS_EXPR)
14499                 return 1;
14500               arg_max = TREE_OPERAND (arg_max, 0);
14501             }
14502
14503           /* If only one of the bounds used a MINUS_EXPR, compensate
14504              by adding one to the other bound.  */
14505           if (parm_cst && !arg_cst)
14506             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14507                                     integer_type_node,
14508                                     parm_max,
14509                                     integer_one_node);
14510           else if (arg_cst && !parm_cst)
14511             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14512                                    integer_type_node,
14513                                    arg_max,
14514                                    integer_one_node);
14515
14516           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14517             return 1;
14518         }
14519       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14520                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14521
14522     case REAL_TYPE:
14523     case COMPLEX_TYPE:
14524     case VECTOR_TYPE:
14525     case INTEGER_TYPE:
14526     case BOOLEAN_TYPE:
14527     case ENUMERAL_TYPE:
14528     case VOID_TYPE:
14529       if (TREE_CODE (arg) != TREE_CODE (parm))
14530         return 1;
14531
14532       /* We have already checked cv-qualification at the top of the
14533          function.  */
14534       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14535         return 1;
14536
14537       /* As far as unification is concerned, this wins.  Later checks
14538          will invalidate it if necessary.  */
14539       return 0;
14540
14541       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14542       /* Type INTEGER_CST can come from ordinary constant template args.  */
14543     case INTEGER_CST:
14544       while (TREE_CODE (arg) == NOP_EXPR)
14545         arg = TREE_OPERAND (arg, 0);
14546
14547       if (TREE_CODE (arg) != INTEGER_CST)
14548         return 1;
14549       return !tree_int_cst_equal (parm, arg);
14550
14551     case TREE_VEC:
14552       {
14553         int i;
14554         if (TREE_CODE (arg) != TREE_VEC)
14555           return 1;
14556         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14557           return 1;
14558         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14559           if (unify (tparms, targs,
14560                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14561                      UNIFY_ALLOW_NONE))
14562             return 1;
14563         return 0;
14564       }
14565
14566     case RECORD_TYPE:
14567     case UNION_TYPE:
14568       if (TREE_CODE (arg) != TREE_CODE (parm))
14569         return 1;
14570
14571       if (TYPE_PTRMEMFUNC_P (parm))
14572         {
14573           if (!TYPE_PTRMEMFUNC_P (arg))
14574             return 1;
14575
14576           return unify (tparms, targs,
14577                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
14578                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
14579                         strict);
14580         }
14581
14582       if (CLASSTYPE_TEMPLATE_INFO (parm))
14583         {
14584           tree t = NULL_TREE;
14585
14586           if (strict_in & UNIFY_ALLOW_DERIVED)
14587             {
14588               /* First, we try to unify the PARM and ARG directly.  */
14589               t = try_class_unification (tparms, targs,
14590                                          parm, arg);
14591
14592               if (!t)
14593                 {
14594                   /* Fallback to the special case allowed in
14595                      [temp.deduct.call]:
14596
14597                        If P is a class, and P has the form
14598                        template-id, then A can be a derived class of
14599                        the deduced A.  Likewise, if P is a pointer to
14600                        a class of the form template-id, A can be a
14601                        pointer to a derived class pointed to by the
14602                        deduced A.  */
14603                   t = get_template_base (tparms, targs, parm, arg);
14604
14605                   if (!t)
14606                     return 1;
14607                 }
14608             }
14609           else if (CLASSTYPE_TEMPLATE_INFO (arg)
14610                    && (CLASSTYPE_TI_TEMPLATE (parm)
14611                        == CLASSTYPE_TI_TEMPLATE (arg)))
14612             /* Perhaps PARM is something like S<U> and ARG is S<int>.
14613                Then, we should unify `int' and `U'.  */
14614             t = arg;
14615           else
14616             /* There's no chance of unification succeeding.  */
14617             return 1;
14618
14619           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
14620                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
14621         }
14622       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
14623         return 1;
14624       return 0;
14625
14626     case METHOD_TYPE:
14627     case FUNCTION_TYPE:
14628       {
14629         unsigned int nargs;
14630         tree *args;
14631         tree a;
14632         unsigned int i;
14633
14634         if (TREE_CODE (arg) != TREE_CODE (parm))
14635           return 1;
14636
14637         /* CV qualifications for methods can never be deduced, they must
14638            match exactly.  We need to check them explicitly here,
14639            because type_unification_real treats them as any other
14640            cv-qualified parameter.  */
14641         if (TREE_CODE (parm) == METHOD_TYPE
14642             && (!check_cv_quals_for_unify
14643                 (UNIFY_ALLOW_NONE,
14644                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
14645                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
14646           return 1;
14647
14648         if (unify (tparms, targs, TREE_TYPE (parm),
14649                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
14650           return 1;
14651
14652         nargs = list_length (TYPE_ARG_TYPES (arg));
14653         args = XALLOCAVEC (tree, nargs);
14654         for (a = TYPE_ARG_TYPES (arg), i = 0;
14655              a != NULL_TREE && a != void_list_node;
14656              a = TREE_CHAIN (a), ++i)
14657           args[i] = TREE_VALUE (a);
14658         nargs = i;
14659
14660         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
14661                                       args, nargs, 1, DEDUCE_EXACT,
14662                                       LOOKUP_NORMAL);
14663       }
14664
14665     case OFFSET_TYPE:
14666       /* Unify a pointer to member with a pointer to member function, which
14667          deduces the type of the member as a function type. */
14668       if (TYPE_PTRMEMFUNC_P (arg))
14669         {
14670           tree method_type;
14671           tree fntype;
14672           cp_cv_quals cv_quals;
14673
14674           /* Check top-level cv qualifiers */
14675           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
14676             return 1;
14677
14678           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14679                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
14680             return 1;
14681
14682           /* Determine the type of the function we are unifying against. */
14683           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
14684           fntype =
14685             build_function_type (TREE_TYPE (method_type),
14686                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
14687
14688           /* Extract the cv-qualifiers of the member function from the
14689              implicit object parameter and place them on the function
14690              type to be restored later. */
14691           cv_quals =
14692             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
14693           fntype = build_qualified_type (fntype, cv_quals);
14694           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
14695         }
14696
14697       if (TREE_CODE (arg) != OFFSET_TYPE)
14698         return 1;
14699       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14700                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
14701         return 1;
14702       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14703                     strict);
14704
14705     case CONST_DECL:
14706       if (DECL_TEMPLATE_PARM_P (parm))
14707         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
14708       if (arg != integral_constant_value (parm))
14709         return 1;
14710       return 0;
14711
14712     case FIELD_DECL:
14713     case TEMPLATE_DECL:
14714       /* Matched cases are handled by the ARG == PARM test above.  */
14715       return 1;
14716
14717     case TYPE_ARGUMENT_PACK:
14718     case NONTYPE_ARGUMENT_PACK:
14719       {
14720         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
14721         tree packed_args = ARGUMENT_PACK_ARGS (arg);
14722         int i, len = TREE_VEC_LENGTH (packed_parms);
14723         int argslen = TREE_VEC_LENGTH (packed_args);
14724         int parm_variadic_p = 0;
14725
14726         for (i = 0; i < len; ++i)
14727           {
14728             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
14729               {
14730                 if (i == len - 1)
14731                   /* We can unify against something with a trailing
14732                      parameter pack.  */
14733                   parm_variadic_p = 1;
14734                 else
14735                   /* Since there is something following the pack
14736                      expansion, we cannot unify this template argument
14737                      list.  */
14738                   return 0;
14739               }
14740           }
14741           
14742
14743         /* If we don't have enough arguments to satisfy the parameters
14744            (not counting the pack expression at the end), or we have
14745            too many arguments for a parameter list that doesn't end in
14746            a pack expression, we can't unify.  */
14747         if (argslen < (len - parm_variadic_p)
14748             || (argslen > len && !parm_variadic_p))
14749           return 1;
14750
14751         /* Unify all of the parameters that precede the (optional)
14752            pack expression.  */
14753         for (i = 0; i < len - parm_variadic_p; ++i)
14754           {
14755             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
14756                        TREE_VEC_ELT (packed_args, i), strict))
14757               return 1;
14758           }
14759
14760         if (parm_variadic_p)
14761           return unify_pack_expansion (tparms, targs, 
14762                                        packed_parms, packed_args,
14763                                        strict, /*call_args_p=*/false,
14764                                        /*subr=*/false);
14765         return 0;
14766       }
14767
14768       break;
14769
14770     case TYPEOF_TYPE:
14771     case DECLTYPE_TYPE:
14772       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
14773          nodes.  */
14774       return 0;
14775
14776     case ERROR_MARK:
14777       /* Unification fails if we hit an error node.  */
14778       return 1;
14779
14780     default:
14781       gcc_assert (EXPR_P (parm));
14782
14783       /* We must be looking at an expression.  This can happen with
14784          something like:
14785
14786            template <int I>
14787            void foo(S<I>, S<I + 2>);
14788
14789          This is a "nondeduced context":
14790
14791            [deduct.type]
14792
14793            The nondeduced contexts are:
14794
14795            --A type that is a template-id in which one or more of
14796              the template-arguments is an expression that references
14797              a template-parameter.
14798
14799          In these cases, we assume deduction succeeded, but don't
14800          actually infer any unifications.  */
14801
14802       if (!uses_template_parms (parm)
14803           && !template_args_equal (parm, arg))
14804         return 1;
14805       else
14806         return 0;
14807     }
14808 }
14809 \f
14810 /* Note that DECL can be defined in this translation unit, if
14811    required.  */
14812
14813 static void
14814 mark_definable (tree decl)
14815 {
14816   tree clone;
14817   DECL_NOT_REALLY_EXTERN (decl) = 1;
14818   FOR_EACH_CLONE (clone, decl)
14819     DECL_NOT_REALLY_EXTERN (clone) = 1;
14820 }
14821
14822 /* Called if RESULT is explicitly instantiated, or is a member of an
14823    explicitly instantiated class.  */
14824
14825 void
14826 mark_decl_instantiated (tree result, int extern_p)
14827 {
14828   SET_DECL_EXPLICIT_INSTANTIATION (result);
14829
14830   /* If this entity has already been written out, it's too late to
14831      make any modifications.  */
14832   if (TREE_ASM_WRITTEN (result))
14833     return;
14834
14835   if (TREE_CODE (result) != FUNCTION_DECL)
14836     /* The TREE_PUBLIC flag for function declarations will have been
14837        set correctly by tsubst.  */
14838     TREE_PUBLIC (result) = 1;
14839
14840   /* This might have been set by an earlier implicit instantiation.  */
14841   DECL_COMDAT (result) = 0;
14842
14843   if (extern_p)
14844     DECL_NOT_REALLY_EXTERN (result) = 0;
14845   else
14846     {
14847       mark_definable (result);
14848       /* Always make artificials weak.  */
14849       if (DECL_ARTIFICIAL (result) && flag_weak)
14850         comdat_linkage (result);
14851       /* For WIN32 we also want to put explicit instantiations in
14852          linkonce sections.  */
14853       else if (TREE_PUBLIC (result))
14854         maybe_make_one_only (result);
14855     }
14856
14857   /* If EXTERN_P, then this function will not be emitted -- unless
14858      followed by an explicit instantiation, at which point its linkage
14859      will be adjusted.  If !EXTERN_P, then this function will be
14860      emitted here.  In neither circumstance do we want
14861      import_export_decl to adjust the linkage.  */
14862   DECL_INTERFACE_KNOWN (result) = 1;
14863 }
14864
14865 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
14866    important template arguments.  If any are missing, we check whether
14867    they're important by using error_mark_node for substituting into any
14868    args that were used for partial ordering (the ones between ARGS and END)
14869    and seeing if it bubbles up.  */
14870
14871 static bool
14872 check_undeduced_parms (tree targs, tree args, tree end)
14873 {
14874   bool found = false;
14875   int i;
14876   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
14877     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
14878       {
14879         found = true;
14880         TREE_VEC_ELT (targs, i) = error_mark_node;
14881       }
14882   if (found)
14883     {
14884       for (; args != end; args = TREE_CHAIN (args))
14885         {
14886           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
14887           if (substed == error_mark_node)
14888             return true;
14889         }
14890     }
14891   return false;
14892 }
14893
14894 /* Given two function templates PAT1 and PAT2, return:
14895
14896    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
14897    -1 if PAT2 is more specialized than PAT1.
14898    0 if neither is more specialized.
14899
14900    LEN indicates the number of parameters we should consider
14901    (defaulted parameters should not be considered).
14902
14903    The 1998 std underspecified function template partial ordering, and
14904    DR214 addresses the issue.  We take pairs of arguments, one from
14905    each of the templates, and deduce them against each other.  One of
14906    the templates will be more specialized if all the *other*
14907    template's arguments deduce against its arguments and at least one
14908    of its arguments *does* *not* deduce against the other template's
14909    corresponding argument.  Deduction is done as for class templates.
14910    The arguments used in deduction have reference and top level cv
14911    qualifiers removed.  Iff both arguments were originally reference
14912    types *and* deduction succeeds in both directions, the template
14913    with the more cv-qualified argument wins for that pairing (if
14914    neither is more cv-qualified, they both are equal).  Unlike regular
14915    deduction, after all the arguments have been deduced in this way,
14916    we do *not* verify the deduced template argument values can be
14917    substituted into non-deduced contexts.
14918
14919    The logic can be a bit confusing here, because we look at deduce1 and
14920    targs1 to see if pat2 is at least as specialized, and vice versa; if we
14921    can find template arguments for pat1 to make arg1 look like arg2, that
14922    means that arg2 is at least as specialized as arg1.  */
14923
14924 int
14925 more_specialized_fn (tree pat1, tree pat2, int len)
14926 {
14927   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
14928   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
14929   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
14930   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
14931   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
14932   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
14933   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
14934   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
14935   tree origs1, origs2;
14936   bool lose1 = false;
14937   bool lose2 = false;
14938
14939   /* Remove the this parameter from non-static member functions.  If
14940      one is a non-static member function and the other is not a static
14941      member function, remove the first parameter from that function
14942      also.  This situation occurs for operator functions where we
14943      locate both a member function (with this pointer) and non-member
14944      operator (with explicit first operand).  */
14945   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
14946     {
14947       len--; /* LEN is the number of significant arguments for DECL1 */
14948       args1 = TREE_CHAIN (args1);
14949       if (!DECL_STATIC_FUNCTION_P (decl2))
14950         args2 = TREE_CHAIN (args2);
14951     }
14952   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
14953     {
14954       args2 = TREE_CHAIN (args2);
14955       if (!DECL_STATIC_FUNCTION_P (decl1))
14956         {
14957           len--;
14958           args1 = TREE_CHAIN (args1);
14959         }
14960     }
14961
14962   /* If only one is a conversion operator, they are unordered.  */
14963   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
14964     return 0;
14965
14966   /* Consider the return type for a conversion function */
14967   if (DECL_CONV_FN_P (decl1))
14968     {
14969       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
14970       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
14971       len++;
14972     }
14973
14974   processing_template_decl++;
14975
14976   origs1 = args1;
14977   origs2 = args2;
14978
14979   while (len--
14980          /* Stop when an ellipsis is seen.  */
14981          && args1 != NULL_TREE && args2 != NULL_TREE)
14982     {
14983       tree arg1 = TREE_VALUE (args1);
14984       tree arg2 = TREE_VALUE (args2);
14985       int deduce1, deduce2;
14986       int quals1 = -1;
14987       int quals2 = -1;
14988
14989       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14990           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14991         {
14992           /* When both arguments are pack expansions, we need only
14993              unify the patterns themselves.  */
14994           arg1 = PACK_EXPANSION_PATTERN (arg1);
14995           arg2 = PACK_EXPANSION_PATTERN (arg2);
14996
14997           /* This is the last comparison we need to do.  */
14998           len = 0;
14999         }
15000
15001       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15002         {
15003           arg1 = TREE_TYPE (arg1);
15004           quals1 = cp_type_quals (arg1);
15005         }
15006
15007       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15008         {
15009           arg2 = TREE_TYPE (arg2);
15010           quals2 = cp_type_quals (arg2);
15011         }
15012
15013       if ((quals1 < 0) != (quals2 < 0))
15014         {
15015           /* Only of the args is a reference, see if we should apply
15016              array/function pointer decay to it.  This is not part of
15017              DR214, but is, IMHO, consistent with the deduction rules
15018              for the function call itself, and with our earlier
15019              implementation of the underspecified partial ordering
15020              rules.  (nathan).  */
15021           if (quals1 >= 0)
15022             {
15023               switch (TREE_CODE (arg1))
15024                 {
15025                 case ARRAY_TYPE:
15026                   arg1 = TREE_TYPE (arg1);
15027                   /* FALLTHROUGH. */
15028                 case FUNCTION_TYPE:
15029                   arg1 = build_pointer_type (arg1);
15030                   break;
15031
15032                 default:
15033                   break;
15034                 }
15035             }
15036           else
15037             {
15038               switch (TREE_CODE (arg2))
15039                 {
15040                 case ARRAY_TYPE:
15041                   arg2 = TREE_TYPE (arg2);
15042                   /* FALLTHROUGH. */
15043                 case FUNCTION_TYPE:
15044                   arg2 = build_pointer_type (arg2);
15045                   break;
15046
15047                 default:
15048                   break;
15049                 }
15050             }
15051         }
15052
15053       arg1 = TYPE_MAIN_VARIANT (arg1);
15054       arg2 = TYPE_MAIN_VARIANT (arg2);
15055
15056       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15057         {
15058           int i, len2 = list_length (args2);
15059           tree parmvec = make_tree_vec (1);
15060           tree argvec = make_tree_vec (len2);
15061           tree ta = args2;
15062
15063           /* Setup the parameter vector, which contains only ARG1.  */
15064           TREE_VEC_ELT (parmvec, 0) = arg1;
15065
15066           /* Setup the argument vector, which contains the remaining
15067              arguments.  */
15068           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15069             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15070
15071           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15072                                            argvec, UNIFY_ALLOW_NONE, 
15073                                            /*call_args_p=*/false, 
15074                                            /*subr=*/0);
15075
15076           /* We cannot deduce in the other direction, because ARG1 is
15077              a pack expansion but ARG2 is not.  */
15078           deduce2 = 0;
15079         }
15080       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15081         {
15082           int i, len1 = list_length (args1);
15083           tree parmvec = make_tree_vec (1);
15084           tree argvec = make_tree_vec (len1);
15085           tree ta = args1;
15086
15087           /* Setup the parameter vector, which contains only ARG1.  */
15088           TREE_VEC_ELT (parmvec, 0) = arg2;
15089
15090           /* Setup the argument vector, which contains the remaining
15091              arguments.  */
15092           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15093             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15094
15095           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15096                                            argvec, UNIFY_ALLOW_NONE, 
15097                                            /*call_args_p=*/false, 
15098                                            /*subr=*/0);
15099
15100           /* We cannot deduce in the other direction, because ARG2 is
15101              a pack expansion but ARG1 is not.*/
15102           deduce1 = 0;
15103         }
15104
15105       else
15106         {
15107           /* The normal case, where neither argument is a pack
15108              expansion.  */
15109           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15110           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15111         }
15112
15113       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15114          arg2, then arg2 is not as specialized as arg1.  */
15115       if (!deduce1)
15116         lose2 = true;
15117       if (!deduce2)
15118         lose1 = true;
15119
15120       /* "If, for a given type, deduction succeeds in both directions
15121          (i.e., the types are identical after the transformations above)
15122          and if the type from the argument template is more cv-qualified
15123          than the type from the parameter template (as described above)
15124          that type is considered to be more specialized than the other. If
15125          neither type is more cv-qualified than the other then neither type
15126          is more specialized than the other."
15127
15128          We check same_type_p explicitly because deduction can also succeed
15129          in both directions when there is a nondeduced context.  */
15130       if (deduce1 && deduce2
15131           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0
15132           && same_type_p (arg1, arg2))
15133         {
15134           if ((quals1 & quals2) == quals2)
15135             lose2 = true;
15136           if ((quals1 & quals2) == quals1)
15137             lose1 = true;
15138         }
15139
15140       if (lose1 && lose2)
15141         /* We've failed to deduce something in either direction.
15142            These must be unordered.  */
15143         break;
15144
15145       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15146           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15147         /* We have already processed all of the arguments in our
15148            handing of the pack expansion type.  */
15149         len = 0;
15150
15151       args1 = TREE_CHAIN (args1);
15152       args2 = TREE_CHAIN (args2);
15153     }
15154
15155   /* "In most cases, all template parameters must have values in order for
15156      deduction to succeed, but for partial ordering purposes a template
15157      parameter may remain without a value provided it is not used in the
15158      types being used for partial ordering."
15159
15160      Thus, if we are missing any of the targs1 we need to substitute into
15161      origs1, then pat2 is not as specialized as pat1.  This can happen when
15162      there is a nondeduced context.  */
15163   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15164     lose2 = true;
15165   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15166     lose1 = true;
15167
15168   processing_template_decl--;
15169
15170   /* All things being equal, if the next argument is a pack expansion
15171      for one function but not for the other, prefer the
15172      non-variadic function.  FIXME this is bogus; see c++/41958.  */
15173   if (lose1 == lose2
15174       && args1 && TREE_VALUE (args1)
15175       && args2 && TREE_VALUE (args2))
15176     {
15177       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15178       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15179     }
15180
15181   if (lose1 == lose2)
15182     return 0;
15183   else if (!lose1)
15184     return 1;
15185   else
15186     return -1;
15187 }
15188
15189 /* Determine which of two partial specializations is more specialized.
15190
15191    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15192    to the first partial specialization.  The TREE_VALUE is the
15193    innermost set of template parameters for the partial
15194    specialization.  PAT2 is similar, but for the second template.
15195
15196    Return 1 if the first partial specialization is more specialized;
15197    -1 if the second is more specialized; 0 if neither is more
15198    specialized.
15199
15200    See [temp.class.order] for information about determining which of
15201    two templates is more specialized.  */
15202
15203 static int
15204 more_specialized_class (tree pat1, tree pat2)
15205 {
15206   tree targs;
15207   tree tmpl1, tmpl2;
15208   int winner = 0;
15209   bool any_deductions = false;
15210
15211   tmpl1 = TREE_TYPE (pat1);
15212   tmpl2 = TREE_TYPE (pat2);
15213
15214   /* Just like what happens for functions, if we are ordering between
15215      different class template specializations, we may encounter dependent
15216      types in the arguments, and we need our dependency check functions
15217      to behave correctly.  */
15218   ++processing_template_decl;
15219   targs = get_class_bindings (TREE_VALUE (pat1),
15220                               CLASSTYPE_TI_ARGS (tmpl1),
15221                               CLASSTYPE_TI_ARGS (tmpl2));
15222   if (targs)
15223     {
15224       --winner;
15225       any_deductions = true;
15226     }
15227
15228   targs = get_class_bindings (TREE_VALUE (pat2),
15229                               CLASSTYPE_TI_ARGS (tmpl2),
15230                               CLASSTYPE_TI_ARGS (tmpl1));
15231   if (targs)
15232     {
15233       ++winner;
15234       any_deductions = true;
15235     }
15236   --processing_template_decl;
15237
15238   /* In the case of a tie where at least one of the class templates
15239      has a parameter pack at the end, the template with the most
15240      non-packed parameters wins.  */
15241   if (winner == 0
15242       && any_deductions
15243       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15244           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15245     {
15246       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15247       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15248       int len1 = TREE_VEC_LENGTH (args1);
15249       int len2 = TREE_VEC_LENGTH (args2);
15250
15251       /* We don't count the pack expansion at the end.  */
15252       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15253         --len1;
15254       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15255         --len2;
15256
15257       if (len1 > len2)
15258         return 1;
15259       else if (len1 < len2)
15260         return -1;
15261     }
15262
15263   return winner;
15264 }
15265
15266 /* Return the template arguments that will produce the function signature
15267    DECL from the function template FN, with the explicit template
15268    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15269    also match.  Return NULL_TREE if no satisfactory arguments could be
15270    found.  */
15271
15272 static tree
15273 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15274 {
15275   int ntparms = DECL_NTPARMS (fn);
15276   tree targs = make_tree_vec (ntparms);
15277   tree decl_type;
15278   tree decl_arg_types;
15279   tree *args;
15280   unsigned int nargs, ix;
15281   tree arg;
15282
15283   /* Substitute the explicit template arguments into the type of DECL.
15284      The call to fn_type_unification will handle substitution into the
15285      FN.  */
15286   decl_type = TREE_TYPE (decl);
15287   if (explicit_args && uses_template_parms (decl_type))
15288     {
15289       tree tmpl;
15290       tree converted_args;
15291
15292       if (DECL_TEMPLATE_INFO (decl))
15293         tmpl = DECL_TI_TEMPLATE (decl);
15294       else
15295         /* We can get here for some invalid specializations.  */
15296         return NULL_TREE;
15297
15298       converted_args
15299         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15300                                  explicit_args, NULL_TREE,
15301                                  tf_none,
15302                                  /*require_all_args=*/false,
15303                                  /*use_default_args=*/false);
15304       if (converted_args == error_mark_node)
15305         return NULL_TREE;
15306
15307       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15308       if (decl_type == error_mark_node)
15309         return NULL_TREE;
15310     }
15311
15312   /* Never do unification on the 'this' parameter.  */
15313   decl_arg_types = skip_artificial_parms_for (decl, 
15314                                               TYPE_ARG_TYPES (decl_type));
15315
15316   nargs = list_length (decl_arg_types);
15317   args = XALLOCAVEC (tree, nargs);
15318   for (arg = decl_arg_types, ix = 0;
15319        arg != NULL_TREE && arg != void_list_node;
15320        arg = TREE_CHAIN (arg), ++ix)
15321     args[ix] = TREE_VALUE (arg);
15322
15323   if (fn_type_unification (fn, explicit_args, targs,
15324                            args, ix,
15325                            (check_rettype || DECL_CONV_FN_P (fn)
15326                             ? TREE_TYPE (decl_type) : NULL_TREE),
15327                            DEDUCE_EXACT, LOOKUP_NORMAL))
15328     return NULL_TREE;
15329
15330   return targs;
15331 }
15332
15333 /* Return the innermost template arguments that, when applied to a
15334    template specialization whose innermost template parameters are
15335    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15336    ARGS.
15337
15338    For example, suppose we have:
15339
15340      template <class T, class U> struct S {};
15341      template <class T> struct S<T*, int> {};
15342
15343    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15344    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15345    int}.  The resulting vector will be {double}, indicating that `T'
15346    is bound to `double'.  */
15347
15348 static tree
15349 get_class_bindings (tree tparms, tree spec_args, tree args)
15350 {
15351   int i, ntparms = TREE_VEC_LENGTH (tparms);
15352   tree deduced_args;
15353   tree innermost_deduced_args;
15354
15355   innermost_deduced_args = make_tree_vec (ntparms);
15356   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15357     {
15358       deduced_args = copy_node (args);
15359       SET_TMPL_ARGS_LEVEL (deduced_args,
15360                            TMPL_ARGS_DEPTH (deduced_args),
15361                            innermost_deduced_args);
15362     }
15363   else
15364     deduced_args = innermost_deduced_args;
15365
15366   if (unify (tparms, deduced_args,
15367              INNERMOST_TEMPLATE_ARGS (spec_args),
15368              INNERMOST_TEMPLATE_ARGS (args),
15369              UNIFY_ALLOW_NONE))
15370     return NULL_TREE;
15371
15372   for (i =  0; i < ntparms; ++i)
15373     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15374       return NULL_TREE;
15375
15376   /* Verify that nondeduced template arguments agree with the type
15377      obtained from argument deduction.
15378
15379      For example:
15380
15381        struct A { typedef int X; };
15382        template <class T, class U> struct C {};
15383        template <class T> struct C<T, typename T::X> {};
15384
15385      Then with the instantiation `C<A, int>', we can deduce that
15386      `T' is `A' but unify () does not check whether `typename T::X'
15387      is `int'.  */
15388   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15389   if (spec_args == error_mark_node
15390       /* We only need to check the innermost arguments; the other
15391          arguments will always agree.  */
15392       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15393                               INNERMOST_TEMPLATE_ARGS (args)))
15394     return NULL_TREE;
15395
15396   /* Now that we have bindings for all of the template arguments,
15397      ensure that the arguments deduced for the template template
15398      parameters have compatible template parameter lists.  See the use
15399      of template_template_parm_bindings_ok_p in fn_type_unification
15400      for more information.  */
15401   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15402     return NULL_TREE;
15403
15404   return deduced_args;
15405 }
15406
15407 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15408    Return the TREE_LIST node with the most specialized template, if
15409    any.  If there is no most specialized template, the error_mark_node
15410    is returned.
15411
15412    Note that this function does not look at, or modify, the
15413    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15414    returned is one of the elements of INSTANTIATIONS, callers may
15415    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15416    and retrieve it from the value returned.  */
15417
15418 tree
15419 most_specialized_instantiation (tree templates)
15420 {
15421   tree fn, champ;
15422
15423   ++processing_template_decl;
15424
15425   champ = templates;
15426   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15427     {
15428       int fate = 0;
15429
15430       if (get_bindings (TREE_VALUE (champ),
15431                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15432                         NULL_TREE, /*check_ret=*/false))
15433         fate--;
15434
15435       if (get_bindings (TREE_VALUE (fn),
15436                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15437                         NULL_TREE, /*check_ret=*/false))
15438         fate++;
15439
15440       if (fate == -1)
15441         champ = fn;
15442       else if (!fate)
15443         {
15444           /* Equally specialized, move to next function.  If there
15445              is no next function, nothing's most specialized.  */
15446           fn = TREE_CHAIN (fn);
15447           champ = fn;
15448           if (!fn)
15449             break;
15450         }
15451     }
15452
15453   if (champ)
15454     /* Now verify that champ is better than everything earlier in the
15455        instantiation list.  */
15456     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15457       if (get_bindings (TREE_VALUE (champ),
15458                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15459                         NULL_TREE, /*check_ret=*/false)
15460           || !get_bindings (TREE_VALUE (fn),
15461                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15462                             NULL_TREE, /*check_ret=*/false))
15463         {
15464           champ = NULL_TREE;
15465           break;
15466         }
15467
15468   processing_template_decl--;
15469
15470   if (!champ)
15471     return error_mark_node;
15472
15473   return champ;
15474 }
15475
15476 /* If DECL is a specialization of some template, return the most
15477    general such template.  Otherwise, returns NULL_TREE.
15478
15479    For example, given:
15480
15481      template <class T> struct S { template <class U> void f(U); };
15482
15483    if TMPL is `template <class U> void S<int>::f(U)' this will return
15484    the full template.  This function will not trace past partial
15485    specializations, however.  For example, given in addition:
15486
15487      template <class T> struct S<T*> { template <class U> void f(U); };
15488
15489    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15490    `template <class T> template <class U> S<T*>::f(U)'.  */
15491
15492 tree
15493 most_general_template (tree decl)
15494 {
15495   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15496      an immediate specialization.  */
15497   if (TREE_CODE (decl) == FUNCTION_DECL)
15498     {
15499       if (DECL_TEMPLATE_INFO (decl)) {
15500         decl = DECL_TI_TEMPLATE (decl);
15501
15502         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15503            template friend.  */
15504         if (TREE_CODE (decl) != TEMPLATE_DECL)
15505           return NULL_TREE;
15506       } else
15507         return NULL_TREE;
15508     }
15509
15510   /* Look for more and more general templates.  */
15511   while (DECL_TEMPLATE_INFO (decl))
15512     {
15513       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15514          (See cp-tree.h for details.)  */
15515       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15516         break;
15517
15518       if (CLASS_TYPE_P (TREE_TYPE (decl))
15519           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15520         break;
15521
15522       /* Stop if we run into an explicitly specialized class template.  */
15523       if (!DECL_NAMESPACE_SCOPE_P (decl)
15524           && DECL_CONTEXT (decl)
15525           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15526         break;
15527
15528       decl = DECL_TI_TEMPLATE (decl);
15529     }
15530
15531   return decl;
15532 }
15533
15534 /* Return the most specialized of the class template partial
15535    specializations of TMPL which can produce TYPE, a specialization of
15536    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15537    a _TYPE node corresponding to the partial specialization, while the
15538    TREE_PURPOSE is the set of template arguments that must be
15539    substituted into the TREE_TYPE in order to generate TYPE.
15540
15541    If the choice of partial specialization is ambiguous, a diagnostic
15542    is issued, and the error_mark_node is returned.  If there are no
15543    partial specializations of TMPL matching TYPE, then NULL_TREE is
15544    returned.  */
15545
15546 static tree
15547 most_specialized_class (tree type, tree tmpl)
15548 {
15549   tree list = NULL_TREE;
15550   tree t;
15551   tree champ;
15552   int fate;
15553   bool ambiguous_p;
15554   tree args;
15555   tree outer_args = NULL_TREE;
15556
15557   tmpl = most_general_template (tmpl);
15558   args = CLASSTYPE_TI_ARGS (type);
15559
15560   /* For determining which partial specialization to use, only the
15561      innermost args are interesting.  */
15562   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15563     {
15564       outer_args = strip_innermost_template_args (args, 1);
15565       args = INNERMOST_TEMPLATE_ARGS (args);
15566     }
15567
15568   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15569     {
15570       tree partial_spec_args;
15571       tree spec_args;
15572       tree parms = TREE_VALUE (t);
15573
15574       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15575       if (outer_args)
15576         {
15577           int i;
15578
15579           ++processing_template_decl;
15580
15581           /* Discard the outer levels of args, and then substitute in the
15582              template args from the enclosing class.  */
15583           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
15584           partial_spec_args = tsubst_template_args
15585             (partial_spec_args, outer_args, tf_none, NULL_TREE);
15586
15587           /* PARMS already refers to just the innermost parms, but the
15588              template parms in partial_spec_args had their levels lowered
15589              by tsubst, so we need to do the same for the parm list.  We
15590              can't just tsubst the TREE_VEC itself, as tsubst wants to
15591              treat a TREE_VEC as an argument vector.  */
15592           parms = copy_node (parms);
15593           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
15594             TREE_VEC_ELT (parms, i) =
15595               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
15596
15597           --processing_template_decl;
15598         }
15599       spec_args = get_class_bindings (parms,
15600                                       partial_spec_args,
15601                                       args);
15602       if (spec_args)
15603         {
15604           if (outer_args)
15605             spec_args = add_to_template_args (outer_args, spec_args);
15606           list = tree_cons (spec_args, TREE_VALUE (t), list);
15607           TREE_TYPE (list) = TREE_TYPE (t);
15608         }
15609     }
15610
15611   if (! list)
15612     return NULL_TREE;
15613
15614   ambiguous_p = false;
15615   t = list;
15616   champ = t;
15617   t = TREE_CHAIN (t);
15618   for (; t; t = TREE_CHAIN (t))
15619     {
15620       fate = more_specialized_class (champ, t);
15621       if (fate == 1)
15622         ;
15623       else
15624         {
15625           if (fate == 0)
15626             {
15627               t = TREE_CHAIN (t);
15628               if (! t)
15629                 {
15630                   ambiguous_p = true;
15631                   break;
15632                 }
15633             }
15634           champ = t;
15635         }
15636     }
15637
15638   if (!ambiguous_p)
15639     for (t = list; t && t != champ; t = TREE_CHAIN (t))
15640       {
15641         fate = more_specialized_class (champ, t);
15642         if (fate != 1)
15643           {
15644             ambiguous_p = true;
15645             break;
15646           }
15647       }
15648
15649   if (ambiguous_p)
15650     {
15651       const char *str = "candidates are:";
15652       error ("ambiguous class template instantiation for %q#T", type);
15653       for (t = list; t; t = TREE_CHAIN (t))
15654         {
15655           error ("%s %+#T", str, TREE_TYPE (t));
15656           str = "               ";
15657         }
15658       return error_mark_node;
15659     }
15660
15661   return champ;
15662 }
15663
15664 /* Explicitly instantiate DECL.  */
15665
15666 void
15667 do_decl_instantiation (tree decl, tree storage)
15668 {
15669   tree result = NULL_TREE;
15670   int extern_p = 0;
15671
15672   if (!decl || decl == error_mark_node)
15673     /* An error occurred, for which grokdeclarator has already issued
15674        an appropriate message.  */
15675     return;
15676   else if (! DECL_LANG_SPECIFIC (decl))
15677     {
15678       error ("explicit instantiation of non-template %q#D", decl);
15679       return;
15680     }
15681   else if (TREE_CODE (decl) == VAR_DECL)
15682     {
15683       /* There is an asymmetry here in the way VAR_DECLs and
15684          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
15685          the latter, the DECL we get back will be marked as a
15686          template instantiation, and the appropriate
15687          DECL_TEMPLATE_INFO will be set up.  This does not happen for
15688          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
15689          should handle VAR_DECLs as it currently handles
15690          FUNCTION_DECLs.  */
15691       if (!DECL_CLASS_SCOPE_P (decl))
15692         {
15693           error ("%qD is not a static data member of a class template", decl);
15694           return;
15695         }
15696       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
15697       if (!result || TREE_CODE (result) != VAR_DECL)
15698         {
15699           error ("no matching template for %qD found", decl);
15700           return;
15701         }
15702       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
15703         {
15704           error ("type %qT for explicit instantiation %qD does not match "
15705                  "declared type %qT", TREE_TYPE (result), decl,
15706                  TREE_TYPE (decl));
15707           return;
15708         }
15709     }
15710   else if (TREE_CODE (decl) != FUNCTION_DECL)
15711     {
15712       error ("explicit instantiation of %q#D", decl);
15713       return;
15714     }
15715   else
15716     result = decl;
15717
15718   /* Check for various error cases.  Note that if the explicit
15719      instantiation is valid the RESULT will currently be marked as an
15720      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
15721      until we get here.  */
15722
15723   if (DECL_TEMPLATE_SPECIALIZATION (result))
15724     {
15725       /* DR 259 [temp.spec].
15726
15727          Both an explicit instantiation and a declaration of an explicit
15728          specialization shall not appear in a program unless the explicit
15729          instantiation follows a declaration of the explicit specialization.
15730
15731          For a given set of template parameters, if an explicit
15732          instantiation of a template appears after a declaration of an
15733          explicit specialization for that template, the explicit
15734          instantiation has no effect.  */
15735       return;
15736     }
15737   else if (DECL_EXPLICIT_INSTANTIATION (result))
15738     {
15739       /* [temp.spec]
15740
15741          No program shall explicitly instantiate any template more
15742          than once.
15743
15744          We check DECL_NOT_REALLY_EXTERN so as not to complain when
15745          the first instantiation was `extern' and the second is not,
15746          and EXTERN_P for the opposite case.  */
15747       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
15748         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
15749       /* If an "extern" explicit instantiation follows an ordinary
15750          explicit instantiation, the template is instantiated.  */
15751       if (extern_p)
15752         return;
15753     }
15754   else if (!DECL_IMPLICIT_INSTANTIATION (result))
15755     {
15756       error ("no matching template for %qD found", result);
15757       return;
15758     }
15759   else if (!DECL_TEMPLATE_INFO (result))
15760     {
15761       permerror (input_location, "explicit instantiation of non-template %q#D", result);
15762       return;
15763     }
15764
15765   if (storage == NULL_TREE)
15766     ;
15767   else if (storage == ridpointers[(int) RID_EXTERN])
15768     {
15769       if (!in_system_header && (cxx_dialect == cxx98))
15770         pedwarn (input_location, OPT_pedantic, 
15771                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
15772                  "instantiations");
15773       extern_p = 1;
15774     }
15775   else
15776     error ("storage class %qD applied to template instantiation", storage);
15777
15778   check_explicit_instantiation_namespace (result);
15779   mark_decl_instantiated (result, extern_p);
15780   if (! extern_p)
15781     instantiate_decl (result, /*defer_ok=*/1,
15782                       /*expl_inst_class_mem_p=*/false);
15783 }
15784
15785 static void
15786 mark_class_instantiated (tree t, int extern_p)
15787 {
15788   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
15789   SET_CLASSTYPE_INTERFACE_KNOWN (t);
15790   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
15791   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
15792   if (! extern_p)
15793     {
15794       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
15795       rest_of_type_compilation (t, 1);
15796     }
15797 }
15798
15799 /* Called from do_type_instantiation through binding_table_foreach to
15800    do recursive instantiation for the type bound in ENTRY.  */
15801 static void
15802 bt_instantiate_type_proc (binding_entry entry, void *data)
15803 {
15804   tree storage = *(tree *) data;
15805
15806   if (MAYBE_CLASS_TYPE_P (entry->type)
15807       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
15808     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
15809 }
15810
15811 /* Called from do_type_instantiation to instantiate a member
15812    (a member function or a static member variable) of an
15813    explicitly instantiated class template.  */
15814 static void
15815 instantiate_class_member (tree decl, int extern_p)
15816 {
15817   mark_decl_instantiated (decl, extern_p);
15818   if (! extern_p)
15819     instantiate_decl (decl, /*defer_ok=*/1,
15820                       /*expl_inst_class_mem_p=*/true);
15821 }
15822
15823 /* Perform an explicit instantiation of template class T.  STORAGE, if
15824    non-null, is the RID for extern, inline or static.  COMPLAIN is
15825    nonzero if this is called from the parser, zero if called recursively,
15826    since the standard is unclear (as detailed below).  */
15827
15828 void
15829 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
15830 {
15831   int extern_p = 0;
15832   int nomem_p = 0;
15833   int static_p = 0;
15834   int previous_instantiation_extern_p = 0;
15835
15836   if (TREE_CODE (t) == TYPE_DECL)
15837     t = TREE_TYPE (t);
15838
15839   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
15840     {
15841       error ("explicit instantiation of non-template type %qT", t);
15842       return;
15843     }
15844
15845   complete_type (t);
15846
15847   if (!COMPLETE_TYPE_P (t))
15848     {
15849       if (complain & tf_error)
15850         error ("explicit instantiation of %q#T before definition of template",
15851                t);
15852       return;
15853     }
15854
15855   if (storage != NULL_TREE)
15856     {
15857       if (!in_system_header)
15858         {
15859           if (storage == ridpointers[(int) RID_EXTERN])
15860             {
15861               if (cxx_dialect == cxx98)
15862                 pedwarn (input_location, OPT_pedantic, 
15863                          "ISO C++ 1998 forbids the use of %<extern%> on "
15864                          "explicit instantiations");
15865             }
15866           else
15867             pedwarn (input_location, OPT_pedantic, 
15868                      "ISO C++ forbids the use of %qE"
15869                      " on explicit instantiations", storage);
15870         }
15871
15872       if (storage == ridpointers[(int) RID_INLINE])
15873         nomem_p = 1;
15874       else if (storage == ridpointers[(int) RID_EXTERN])
15875         extern_p = 1;
15876       else if (storage == ridpointers[(int) RID_STATIC])
15877         static_p = 1;
15878       else
15879         {
15880           error ("storage class %qD applied to template instantiation",
15881                  storage);
15882           extern_p = 0;
15883         }
15884     }
15885
15886   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
15887     {
15888       /* DR 259 [temp.spec].
15889
15890          Both an explicit instantiation and a declaration of an explicit
15891          specialization shall not appear in a program unless the explicit
15892          instantiation follows a declaration of the explicit specialization.
15893
15894          For a given set of template parameters, if an explicit
15895          instantiation of a template appears after a declaration of an
15896          explicit specialization for that template, the explicit
15897          instantiation has no effect.  */
15898       return;
15899     }
15900   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
15901     {
15902       /* [temp.spec]
15903
15904          No program shall explicitly instantiate any template more
15905          than once.
15906
15907          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
15908          instantiation was `extern'.  If EXTERN_P then the second is.
15909          These cases are OK.  */
15910       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
15911
15912       if (!previous_instantiation_extern_p && !extern_p
15913           && (complain & tf_error))
15914         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
15915
15916       /* If we've already instantiated the template, just return now.  */
15917       if (!CLASSTYPE_INTERFACE_ONLY (t))
15918         return;
15919     }
15920
15921   check_explicit_instantiation_namespace (TYPE_NAME (t));
15922   mark_class_instantiated (t, extern_p);
15923
15924   if (nomem_p)
15925     return;
15926
15927   {
15928     tree tmp;
15929
15930     /* In contrast to implicit instantiation, where only the
15931        declarations, and not the definitions, of members are
15932        instantiated, we have here:
15933
15934          [temp.explicit]
15935
15936          The explicit instantiation of a class template specialization
15937          implies the instantiation of all of its members not
15938          previously explicitly specialized in the translation unit
15939          containing the explicit instantiation.
15940
15941        Of course, we can't instantiate member template classes, since
15942        we don't have any arguments for them.  Note that the standard
15943        is unclear on whether the instantiation of the members are
15944        *explicit* instantiations or not.  However, the most natural
15945        interpretation is that it should be an explicit instantiation.  */
15946
15947     if (! static_p)
15948       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
15949         if (TREE_CODE (tmp) == FUNCTION_DECL
15950             && DECL_TEMPLATE_INSTANTIATION (tmp))
15951           instantiate_class_member (tmp, extern_p);
15952
15953     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
15954       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
15955         instantiate_class_member (tmp, extern_p);
15956
15957     if (CLASSTYPE_NESTED_UTDS (t))
15958       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
15959                              bt_instantiate_type_proc, &storage);
15960   }
15961 }
15962
15963 /* Given a function DECL, which is a specialization of TMPL, modify
15964    DECL to be a re-instantiation of TMPL with the same template
15965    arguments.  TMPL should be the template into which tsubst'ing
15966    should occur for DECL, not the most general template.
15967
15968    One reason for doing this is a scenario like this:
15969
15970      template <class T>
15971      void f(const T&, int i);
15972
15973      void g() { f(3, 7); }
15974
15975      template <class T>
15976      void f(const T& t, const int i) { }
15977
15978    Note that when the template is first instantiated, with
15979    instantiate_template, the resulting DECL will have no name for the
15980    first parameter, and the wrong type for the second.  So, when we go
15981    to instantiate the DECL, we regenerate it.  */
15982
15983 static void
15984 regenerate_decl_from_template (tree decl, tree tmpl)
15985 {
15986   /* The arguments used to instantiate DECL, from the most general
15987      template.  */
15988   tree args;
15989   tree code_pattern;
15990
15991   args = DECL_TI_ARGS (decl);
15992   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
15993
15994   /* Make sure that we can see identifiers, and compute access
15995      correctly.  */
15996   push_access_scope (decl);
15997
15998   if (TREE_CODE (decl) == FUNCTION_DECL)
15999     {
16000       tree decl_parm;
16001       tree pattern_parm;
16002       tree specs;
16003       int args_depth;
16004       int parms_depth;
16005
16006       args_depth = TMPL_ARGS_DEPTH (args);
16007       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16008       if (args_depth > parms_depth)
16009         args = get_innermost_template_args (args, parms_depth);
16010
16011       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16012                                               args, tf_error, NULL_TREE);
16013       if (specs)
16014         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16015                                                     specs);
16016
16017       /* Merge parameter declarations.  */
16018       decl_parm = skip_artificial_parms_for (decl,
16019                                              DECL_ARGUMENTS (decl));
16020       pattern_parm
16021         = skip_artificial_parms_for (code_pattern,
16022                                      DECL_ARGUMENTS (code_pattern));
16023       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16024         {
16025           tree parm_type;
16026           tree attributes;
16027           
16028           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16029             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16030           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16031                               NULL_TREE);
16032           parm_type = type_decays_to (parm_type);
16033           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16034             TREE_TYPE (decl_parm) = parm_type;
16035           attributes = DECL_ATTRIBUTES (pattern_parm);
16036           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16037             {
16038               DECL_ATTRIBUTES (decl_parm) = attributes;
16039               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16040             }
16041           decl_parm = TREE_CHAIN (decl_parm);
16042           pattern_parm = TREE_CHAIN (pattern_parm);
16043         }
16044       /* Merge any parameters that match with the function parameter
16045          pack.  */
16046       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16047         {
16048           int i, len;
16049           tree expanded_types;
16050           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16051              the parameters in this function parameter pack.  */
16052           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16053                                                  args, tf_error, NULL_TREE);
16054           len = TREE_VEC_LENGTH (expanded_types);
16055           for (i = 0; i < len; i++)
16056             {
16057               tree parm_type;
16058               tree attributes;
16059           
16060               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16061                 /* Rename the parameter to include the index.  */
16062                 DECL_NAME (decl_parm) = 
16063                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16064               parm_type = TREE_VEC_ELT (expanded_types, i);
16065               parm_type = type_decays_to (parm_type);
16066               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16067                 TREE_TYPE (decl_parm) = parm_type;
16068               attributes = DECL_ATTRIBUTES (pattern_parm);
16069               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16070                 {
16071                   DECL_ATTRIBUTES (decl_parm) = attributes;
16072                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16073                 }
16074               decl_parm = TREE_CHAIN (decl_parm);
16075             }
16076         }
16077       /* Merge additional specifiers from the CODE_PATTERN.  */
16078       if (DECL_DECLARED_INLINE_P (code_pattern)
16079           && !DECL_DECLARED_INLINE_P (decl))
16080         DECL_DECLARED_INLINE_P (decl) = 1;
16081     }
16082   else if (TREE_CODE (decl) == VAR_DECL)
16083     DECL_INITIAL (decl) =
16084       tsubst_expr (DECL_INITIAL (code_pattern), args,
16085                    tf_error, DECL_TI_TEMPLATE (decl),
16086                    /*integral_constant_expression_p=*/false);
16087   else
16088     gcc_unreachable ();
16089
16090   pop_access_scope (decl);
16091 }
16092
16093 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16094    substituted to get DECL.  */
16095
16096 tree
16097 template_for_substitution (tree decl)
16098 {
16099   tree tmpl = DECL_TI_TEMPLATE (decl);
16100
16101   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16102      for the instantiation.  This is not always the most general
16103      template.  Consider, for example:
16104
16105         template <class T>
16106         struct S { template <class U> void f();
16107                    template <> void f<int>(); };
16108
16109      and an instantiation of S<double>::f<int>.  We want TD to be the
16110      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16111   while (/* An instantiation cannot have a definition, so we need a
16112             more general template.  */
16113          DECL_TEMPLATE_INSTANTIATION (tmpl)
16114            /* We must also deal with friend templates.  Given:
16115
16116                 template <class T> struct S {
16117                   template <class U> friend void f() {};
16118                 };
16119
16120               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16121               so far as the language is concerned, but that's still
16122               where we get the pattern for the instantiation from.  On
16123               other hand, if the definition comes outside the class, say:
16124
16125                 template <class T> struct S {
16126                   template <class U> friend void f();
16127                 };
16128                 template <class U> friend void f() {}
16129
16130               we don't need to look any further.  That's what the check for
16131               DECL_INITIAL is for.  */
16132           || (TREE_CODE (decl) == FUNCTION_DECL
16133               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16134               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16135     {
16136       /* The present template, TD, should not be a definition.  If it
16137          were a definition, we should be using it!  Note that we
16138          cannot restructure the loop to just keep going until we find
16139          a template with a definition, since that might go too far if
16140          a specialization was declared, but not defined.  */
16141       gcc_assert (TREE_CODE (decl) != VAR_DECL
16142                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16143
16144       /* Fetch the more general template.  */
16145       tmpl = DECL_TI_TEMPLATE (tmpl);
16146     }
16147
16148   return tmpl;
16149 }
16150
16151 /* Returns true if we need to instantiate this template instance even if we
16152    know we aren't going to emit it..  */
16153
16154 bool
16155 always_instantiate_p (tree decl)
16156 {
16157   /* We always instantiate inline functions so that we can inline them.  An
16158      explicit instantiation declaration prohibits implicit instantiation of
16159      non-inline functions.  With high levels of optimization, we would
16160      normally inline non-inline functions -- but we're not allowed to do
16161      that for "extern template" functions.  Therefore, we check
16162      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16163   return ((TREE_CODE (decl) == FUNCTION_DECL
16164            && DECL_DECLARED_INLINE_P (decl))
16165           /* And we need to instantiate static data members so that
16166              their initializers are available in integral constant
16167              expressions.  */
16168           || (TREE_CODE (decl) == VAR_DECL
16169               && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16170 }
16171
16172 /* Produce the definition of D, a _DECL generated from a template.  If
16173    DEFER_OK is nonzero, then we don't have to actually do the
16174    instantiation now; we just have to do it sometime.  Normally it is
16175    an error if this is an explicit instantiation but D is undefined.
16176    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16177    explicitly instantiated class template.  */
16178
16179 tree
16180 instantiate_decl (tree d, int defer_ok,
16181                   bool expl_inst_class_mem_p)
16182 {
16183   tree tmpl = DECL_TI_TEMPLATE (d);
16184   tree gen_args;
16185   tree args;
16186   tree td;
16187   tree code_pattern;
16188   tree spec;
16189   tree gen_tmpl;
16190   bool pattern_defined;
16191   int need_push;
16192   location_t saved_loc = input_location;
16193   bool external_p;
16194
16195   /* This function should only be used to instantiate templates for
16196      functions and static member variables.  */
16197   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16198               || TREE_CODE (d) == VAR_DECL);
16199
16200   /* Variables are never deferred; if instantiation is required, they
16201      are instantiated right away.  That allows for better code in the
16202      case that an expression refers to the value of the variable --
16203      if the variable has a constant value the referring expression can
16204      take advantage of that fact.  */
16205   if (TREE_CODE (d) == VAR_DECL)
16206     defer_ok = 0;
16207
16208   /* Don't instantiate cloned functions.  Instead, instantiate the
16209      functions they cloned.  */
16210   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16211     d = DECL_CLONED_FUNCTION (d);
16212
16213   if (DECL_TEMPLATE_INSTANTIATED (d)
16214       || DECL_TEMPLATE_SPECIALIZATION (d))
16215     /* D has already been instantiated or explicitly specialized, so
16216        there's nothing for us to do here.
16217
16218        It might seem reasonable to check whether or not D is an explicit
16219        instantiation, and, if so, stop here.  But when an explicit
16220        instantiation is deferred until the end of the compilation,
16221        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16222        the instantiation.  */
16223     return d;
16224
16225   /* Check to see whether we know that this template will be
16226      instantiated in some other file, as with "extern template"
16227      extension.  */
16228   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16229
16230   /* In general, we do not instantiate such templates.  */
16231   if (external_p && !always_instantiate_p (d))
16232     return d;
16233
16234   gen_tmpl = most_general_template (tmpl);
16235   gen_args = DECL_TI_ARGS (d);
16236
16237   if (tmpl != gen_tmpl)
16238     /* We should already have the extra args.  */
16239     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16240                 == TMPL_ARGS_DEPTH (gen_args));
16241   /* And what's in the hash table should match D.  */
16242   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16243               || spec == NULL_TREE);
16244
16245   /* This needs to happen before any tsubsting.  */
16246   if (! push_tinst_level (d))
16247     return d;
16248
16249   timevar_push (TV_PARSE);
16250
16251   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16252      for the instantiation.  */
16253   td = template_for_substitution (d);
16254   code_pattern = DECL_TEMPLATE_RESULT (td);
16255
16256   /* We should never be trying to instantiate a member of a class
16257      template or partial specialization.  */
16258   gcc_assert (d != code_pattern);
16259
16260   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16261       || DECL_TEMPLATE_SPECIALIZATION (td))
16262     /* In the case of a friend template whose definition is provided
16263        outside the class, we may have too many arguments.  Drop the
16264        ones we don't need.  The same is true for specializations.  */
16265     args = get_innermost_template_args
16266       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16267   else
16268     args = gen_args;
16269
16270   if (TREE_CODE (d) == FUNCTION_DECL)
16271     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16272   else
16273     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16274
16275   /* We may be in the middle of deferred access check.  Disable it now.  */
16276   push_deferring_access_checks (dk_no_deferred);
16277
16278   /* Unless an explicit instantiation directive has already determined
16279      the linkage of D, remember that a definition is available for
16280      this entity.  */
16281   if (pattern_defined
16282       && !DECL_INTERFACE_KNOWN (d)
16283       && !DECL_NOT_REALLY_EXTERN (d))
16284     mark_definable (d);
16285
16286   input_location = DECL_SOURCE_LOCATION (d);
16287
16288   /* If D is a member of an explicitly instantiated class template,
16289      and no definition is available, treat it like an implicit
16290      instantiation.  */
16291   if (!pattern_defined && expl_inst_class_mem_p
16292       && DECL_EXPLICIT_INSTANTIATION (d))
16293     {
16294       DECL_NOT_REALLY_EXTERN (d) = 0;
16295       DECL_INTERFACE_KNOWN (d) = 0;
16296       SET_DECL_IMPLICIT_INSTANTIATION (d);
16297     }
16298
16299   /* Recheck the substitutions to obtain any warning messages
16300      about ignoring cv qualifiers.  Don't do this for artificial decls,
16301      as it breaks the context-sensitive substitution for lambda op(). */
16302   if (!defer_ok && !DECL_ARTIFICIAL (d))
16303     {
16304       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16305       tree type = TREE_TYPE (gen);
16306
16307       /* Make sure that we can see identifiers, and compute access
16308          correctly.  D is already the target FUNCTION_DECL with the
16309          right context.  */
16310       push_access_scope (d);
16311
16312       if (TREE_CODE (gen) == FUNCTION_DECL)
16313         {
16314           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16315           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16316                                           d);
16317           /* Don't simply tsubst the function type, as that will give
16318              duplicate warnings about poor parameter qualifications.
16319              The function arguments are the same as the decl_arguments
16320              without the top level cv qualifiers.  */
16321           type = TREE_TYPE (type);
16322         }
16323       tsubst (type, gen_args, tf_warning_or_error, d);
16324
16325       pop_access_scope (d);
16326     }
16327
16328   /* Defer all other templates, unless we have been explicitly
16329      forbidden from doing so.  */
16330   if (/* If there is no definition, we cannot instantiate the
16331          template.  */
16332       ! pattern_defined
16333       /* If it's OK to postpone instantiation, do so.  */
16334       || defer_ok
16335       /* If this is a static data member that will be defined
16336          elsewhere, we don't want to instantiate the entire data
16337          member, but we do want to instantiate the initializer so that
16338          we can substitute that elsewhere.  */
16339       || (external_p && TREE_CODE (d) == VAR_DECL))
16340     {
16341       /* The definition of the static data member is now required so
16342          we must substitute the initializer.  */
16343       if (TREE_CODE (d) == VAR_DECL
16344           && !DECL_INITIAL (d)
16345           && DECL_INITIAL (code_pattern))
16346         {
16347           tree ns;
16348           tree init;
16349
16350           ns = decl_namespace_context (d);
16351           push_nested_namespace (ns);
16352           push_nested_class (DECL_CONTEXT (d));
16353           init = tsubst_expr (DECL_INITIAL (code_pattern),
16354                               args,
16355                               tf_warning_or_error, NULL_TREE,
16356                               /*integral_constant_expression_p=*/false);
16357           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16358                           /*asmspec_tree=*/NULL_TREE,
16359                           LOOKUP_ONLYCONVERTING);
16360           pop_nested_class ();
16361           pop_nested_namespace (ns);
16362         }
16363
16364       /* We restore the source position here because it's used by
16365          add_pending_template.  */
16366       input_location = saved_loc;
16367
16368       if (at_eof && !pattern_defined
16369           && DECL_EXPLICIT_INSTANTIATION (d)
16370           && DECL_NOT_REALLY_EXTERN (d))
16371         /* [temp.explicit]
16372
16373            The definition of a non-exported function template, a
16374            non-exported member function template, or a non-exported
16375            member function or static data member of a class template
16376            shall be present in every translation unit in which it is
16377            explicitly instantiated.  */
16378         permerror (input_location,  "explicit instantiation of %qD "
16379                    "but no definition available", d);
16380
16381       /* ??? Historically, we have instantiated inline functions, even
16382          when marked as "extern template".  */
16383       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16384         add_pending_template (d);
16385       goto out;
16386     }
16387   /* Tell the repository that D is available in this translation unit
16388      -- and see if it is supposed to be instantiated here.  */
16389   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16390     {
16391       /* In a PCH file, despite the fact that the repository hasn't
16392          requested instantiation in the PCH it is still possible that
16393          an instantiation will be required in a file that includes the
16394          PCH.  */
16395       if (pch_file)
16396         add_pending_template (d);
16397       /* Instantiate inline functions so that the inliner can do its
16398          job, even though we'll not be emitting a copy of this
16399          function.  */
16400       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16401         goto out;
16402     }
16403
16404   need_push = !cfun || !global_bindings_p ();
16405   if (need_push)
16406     push_to_top_level ();
16407
16408   /* Mark D as instantiated so that recursive calls to
16409      instantiate_decl do not try to instantiate it again.  */
16410   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16411
16412   /* Regenerate the declaration in case the template has been modified
16413      by a subsequent redeclaration.  */
16414   regenerate_decl_from_template (d, td);
16415
16416   /* We already set the file and line above.  Reset them now in case
16417      they changed as a result of calling regenerate_decl_from_template.  */
16418   input_location = DECL_SOURCE_LOCATION (d);
16419
16420   if (TREE_CODE (d) == VAR_DECL)
16421     {
16422       tree init;
16423
16424       /* Clear out DECL_RTL; whatever was there before may not be right
16425          since we've reset the type of the declaration.  */
16426       SET_DECL_RTL (d, NULL_RTX);
16427       DECL_IN_AGGR_P (d) = 0;
16428
16429       /* The initializer is placed in DECL_INITIAL by
16430          regenerate_decl_from_template.  Pull it out so that
16431          cp_finish_decl can process it.  */
16432       init = DECL_INITIAL (d);
16433       DECL_INITIAL (d) = NULL_TREE;
16434       DECL_INITIALIZED_P (d) = 0;
16435
16436       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16437          initializer.  That function will defer actual emission until
16438          we have a chance to determine linkage.  */
16439       DECL_EXTERNAL (d) = 0;
16440
16441       /* Enter the scope of D so that access-checking works correctly.  */
16442       push_nested_class (DECL_CONTEXT (d));
16443       cp_finish_decl (d, init, false, NULL_TREE, 0);
16444       pop_nested_class ();
16445     }
16446   else if (TREE_CODE (d) == FUNCTION_DECL)
16447     {
16448       htab_t saved_local_specializations;
16449       tree subst_decl;
16450       tree tmpl_parm;
16451       tree spec_parm;
16452
16453       /* Save away the current list, in case we are instantiating one
16454          template from within the body of another.  */
16455       saved_local_specializations = local_specializations;
16456
16457       /* Set up the list of local specializations.  */
16458       local_specializations = htab_create (37,
16459                                            hash_local_specialization,
16460                                            eq_local_specializations,
16461                                            NULL);
16462
16463       /* Set up context.  */
16464       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16465
16466       /* Create substitution entries for the parameters.  */
16467       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16468       tmpl_parm = DECL_ARGUMENTS (subst_decl);
16469       spec_parm = DECL_ARGUMENTS (d);
16470       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16471         {
16472           register_local_specialization (spec_parm, tmpl_parm);
16473           spec_parm = skip_artificial_parms_for (d, spec_parm);
16474           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16475         }
16476       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16477         {
16478           register_local_specialization (spec_parm, tmpl_parm);
16479           tmpl_parm = TREE_CHAIN (tmpl_parm);
16480           spec_parm = TREE_CHAIN (spec_parm);
16481         }
16482       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16483         {
16484           /* Register the (value) argument pack as a specialization of
16485              TMPL_PARM, then move on.  */
16486           tree argpack = make_fnparm_pack (spec_parm);
16487           register_local_specialization (argpack, tmpl_parm);
16488           tmpl_parm = TREE_CHAIN (tmpl_parm);
16489           spec_parm = NULL_TREE;
16490         }
16491       gcc_assert (!spec_parm);
16492
16493       /* Substitute into the body of the function.  */
16494       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16495                    tf_warning_or_error, tmpl,
16496                    /*integral_constant_expression_p=*/false);
16497
16498       /* Set the current input_location to the end of the function
16499          so that finish_function knows where we are.  */
16500       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16501
16502       /* We don't need the local specializations any more.  */
16503       htab_delete (local_specializations);
16504       local_specializations = saved_local_specializations;
16505
16506       /* Finish the function.  */
16507       d = finish_function (0);
16508       expand_or_defer_fn (d);
16509     }
16510
16511   /* We're not deferring instantiation any more.  */
16512   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16513
16514   if (need_push)
16515     pop_from_top_level ();
16516
16517 out:
16518   input_location = saved_loc;
16519   pop_deferring_access_checks ();
16520   pop_tinst_level ();
16521
16522   timevar_pop (TV_PARSE);
16523
16524   return d;
16525 }
16526
16527 /* Run through the list of templates that we wish we could
16528    instantiate, and instantiate any we can.  RETRIES is the
16529    number of times we retry pending template instantiation.  */
16530
16531 void
16532 instantiate_pending_templates (int retries)
16533 {
16534   int reconsider;
16535   location_t saved_loc = input_location;
16536
16537   /* Instantiating templates may trigger vtable generation.  This in turn
16538      may require further template instantiations.  We place a limit here
16539      to avoid infinite loop.  */
16540   if (pending_templates && retries >= max_tinst_depth)
16541     {
16542       tree decl = pending_templates->tinst->decl;
16543
16544       error ("template instantiation depth exceeds maximum of %d"
16545              " instantiating %q+D, possibly from virtual table generation"
16546              " (use -ftemplate-depth-NN to increase the maximum)",
16547              max_tinst_depth, decl);
16548       if (TREE_CODE (decl) == FUNCTION_DECL)
16549         /* Pretend that we defined it.  */
16550         DECL_INITIAL (decl) = error_mark_node;
16551       return;
16552     }
16553
16554   do
16555     {
16556       struct pending_template **t = &pending_templates;
16557       struct pending_template *last = NULL;
16558       reconsider = 0;
16559       while (*t)
16560         {
16561           tree instantiation = reopen_tinst_level ((*t)->tinst);
16562           bool complete = false;
16563
16564           if (TYPE_P (instantiation))
16565             {
16566               tree fn;
16567
16568               if (!COMPLETE_TYPE_P (instantiation))
16569                 {
16570                   instantiate_class_template (instantiation);
16571                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
16572                     for (fn = TYPE_METHODS (instantiation);
16573                          fn;
16574                          fn = TREE_CHAIN (fn))
16575                       if (! DECL_ARTIFICIAL (fn))
16576                         instantiate_decl (fn,
16577                                           /*defer_ok=*/0,
16578                                           /*expl_inst_class_mem_p=*/false);
16579                   if (COMPLETE_TYPE_P (instantiation))
16580                     reconsider = 1;
16581                 }
16582
16583               complete = COMPLETE_TYPE_P (instantiation);
16584             }
16585           else
16586             {
16587               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
16588                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
16589                 {
16590                   instantiation
16591                     = instantiate_decl (instantiation,
16592                                         /*defer_ok=*/0,
16593                                         /*expl_inst_class_mem_p=*/false);
16594                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
16595                     reconsider = 1;
16596                 }
16597
16598               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
16599                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
16600             }
16601
16602           if (complete)
16603             /* If INSTANTIATION has been instantiated, then we don't
16604                need to consider it again in the future.  */
16605             *t = (*t)->next;
16606           else
16607             {
16608               last = *t;
16609               t = &(*t)->next;
16610             }
16611           tinst_depth = 0;
16612           current_tinst_level = NULL;
16613         }
16614       last_pending_template = last;
16615     }
16616   while (reconsider);
16617
16618   input_location = saved_loc;
16619 }
16620
16621 /* Substitute ARGVEC into T, which is a list of initializers for
16622    either base class or a non-static data member.  The TREE_PURPOSEs
16623    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
16624    instantiate_decl.  */
16625
16626 static tree
16627 tsubst_initializer_list (tree t, tree argvec)
16628 {
16629   tree inits = NULL_TREE;
16630
16631   for (; t; t = TREE_CHAIN (t))
16632     {
16633       tree decl;
16634       tree init;
16635       tree expanded_bases = NULL_TREE;
16636       tree expanded_arguments = NULL_TREE;
16637       int i, len = 1;
16638
16639       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
16640         {
16641           tree expr;
16642           tree arg;
16643
16644           /* Expand the base class expansion type into separate base
16645              classes.  */
16646           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
16647                                                  tf_warning_or_error,
16648                                                  NULL_TREE);
16649           if (expanded_bases == error_mark_node)
16650             continue;
16651           
16652           /* We'll be building separate TREE_LISTs of arguments for
16653              each base.  */
16654           len = TREE_VEC_LENGTH (expanded_bases);
16655           expanded_arguments = make_tree_vec (len);
16656           for (i = 0; i < len; i++)
16657             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
16658
16659           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
16660              expand each argument in the TREE_VALUE of t.  */
16661           expr = make_node (EXPR_PACK_EXPANSION);
16662           PACK_EXPANSION_PARAMETER_PACKS (expr) =
16663             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
16664
16665           if (TREE_VALUE (t) == void_type_node)
16666             /* VOID_TYPE_NODE is used to indicate
16667                value-initialization.  */
16668             {
16669               for (i = 0; i < len; i++)
16670                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
16671             }
16672           else
16673             {
16674               /* Substitute parameter packs into each argument in the
16675                  TREE_LIST.  */
16676               in_base_initializer = 1;
16677               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
16678                 {
16679                   tree expanded_exprs;
16680
16681                   /* Expand the argument.  */
16682                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
16683                   expanded_exprs 
16684                     = tsubst_pack_expansion (expr, argvec,
16685                                              tf_warning_or_error,
16686                                              NULL_TREE);
16687                   if (expanded_exprs == error_mark_node)
16688                     continue;
16689
16690                   /* Prepend each of the expanded expressions to the
16691                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
16692                   for (i = 0; i < len; i++)
16693                     {
16694                       TREE_VEC_ELT (expanded_arguments, i) = 
16695                         tree_cons (NULL_TREE, 
16696                                    TREE_VEC_ELT (expanded_exprs, i),
16697                                    TREE_VEC_ELT (expanded_arguments, i));
16698                     }
16699                 }
16700               in_base_initializer = 0;
16701
16702               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
16703                  since we built them backwards.  */
16704               for (i = 0; i < len; i++)
16705                 {
16706                   TREE_VEC_ELT (expanded_arguments, i) = 
16707                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
16708                 }
16709             }
16710         }
16711
16712       for (i = 0; i < len; ++i)
16713         {
16714           if (expanded_bases)
16715             {
16716               decl = TREE_VEC_ELT (expanded_bases, i);
16717               decl = expand_member_init (decl);
16718               init = TREE_VEC_ELT (expanded_arguments, i);
16719             }
16720           else
16721             {
16722               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
16723                                   tf_warning_or_error, NULL_TREE);
16724
16725               decl = expand_member_init (decl);
16726               if (decl && !DECL_P (decl))
16727                 in_base_initializer = 1;
16728
16729               init = tsubst_expr (TREE_VALUE (t), argvec, 
16730                                   tf_warning_or_error, NULL_TREE,
16731                                   /*integral_constant_expression_p=*/false);
16732               in_base_initializer = 0;
16733             }
16734
16735           if (decl)
16736             {
16737               init = build_tree_list (decl, init);
16738               TREE_CHAIN (init) = inits;
16739               inits = init;
16740             }
16741         }
16742     }
16743   return inits;
16744 }
16745
16746 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
16747
16748 static void
16749 set_current_access_from_decl (tree decl)
16750 {
16751   if (TREE_PRIVATE (decl))
16752     current_access_specifier = access_private_node;
16753   else if (TREE_PROTECTED (decl))
16754     current_access_specifier = access_protected_node;
16755   else
16756     current_access_specifier = access_public_node;
16757 }
16758
16759 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
16760    is the instantiation (which should have been created with
16761    start_enum) and ARGS are the template arguments to use.  */
16762
16763 static void
16764 tsubst_enum (tree tag, tree newtag, tree args)
16765 {
16766   tree e;
16767
16768   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
16769     {
16770       tree value;
16771       tree decl;
16772
16773       decl = TREE_VALUE (e);
16774       /* Note that in a template enum, the TREE_VALUE is the
16775          CONST_DECL, not the corresponding INTEGER_CST.  */
16776       value = tsubst_expr (DECL_INITIAL (decl),
16777                            args, tf_warning_or_error, NULL_TREE,
16778                            /*integral_constant_expression_p=*/true);
16779
16780       /* Give this enumeration constant the correct access.  */
16781       set_current_access_from_decl (decl);
16782
16783       /* Actually build the enumerator itself.  */
16784       build_enumerator (DECL_NAME (decl), value, newtag);
16785     }
16786
16787   finish_enum (newtag);
16788   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
16789     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
16790 }
16791
16792 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
16793    its type -- but without substituting the innermost set of template
16794    arguments.  So, innermost set of template parameters will appear in
16795    the type.  */
16796
16797 tree
16798 get_mostly_instantiated_function_type (tree decl)
16799 {
16800   tree fn_type;
16801   tree tmpl;
16802   tree targs;
16803   tree tparms;
16804   int parm_depth;
16805
16806   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16807   targs = DECL_TI_ARGS (decl);
16808   tparms = DECL_TEMPLATE_PARMS (tmpl);
16809   parm_depth = TMPL_PARMS_DEPTH (tparms);
16810
16811   /* There should be as many levels of arguments as there are levels
16812      of parameters.  */
16813   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
16814
16815   fn_type = TREE_TYPE (tmpl);
16816
16817   if (parm_depth == 1)
16818     /* No substitution is necessary.  */
16819     ;
16820   else
16821     {
16822       int i, save_access_control;
16823       tree partial_args;
16824
16825       /* Replace the innermost level of the TARGS with NULL_TREEs to
16826          let tsubst know not to substitute for those parameters.  */
16827       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
16828       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
16829         SET_TMPL_ARGS_LEVEL (partial_args, i,
16830                              TMPL_ARGS_LEVEL (targs, i));
16831       SET_TMPL_ARGS_LEVEL (partial_args,
16832                            TMPL_ARGS_DEPTH (targs),
16833                            make_tree_vec (DECL_NTPARMS (tmpl)));
16834
16835       /* Disable access control as this function is used only during
16836          name-mangling.  */
16837       save_access_control = flag_access_control;
16838       flag_access_control = 0;
16839
16840       ++processing_template_decl;
16841       /* Now, do the (partial) substitution to figure out the
16842          appropriate function type.  */
16843       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
16844       --processing_template_decl;
16845
16846       /* Substitute into the template parameters to obtain the real
16847          innermost set of parameters.  This step is important if the
16848          innermost set of template parameters contains value
16849          parameters whose types depend on outer template parameters.  */
16850       TREE_VEC_LENGTH (partial_args)--;
16851       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
16852
16853       flag_access_control = save_access_control;
16854     }
16855
16856   return fn_type;
16857 }
16858
16859 /* Return truthvalue if we're processing a template different from
16860    the last one involved in diagnostics.  */
16861 int
16862 problematic_instantiation_changed (void)
16863 {
16864   return last_template_error_tick != tinst_level_tick;
16865 }
16866
16867 /* Remember current template involved in diagnostics.  */
16868 void
16869 record_last_problematic_instantiation (void)
16870 {
16871   last_template_error_tick = tinst_level_tick;
16872 }
16873
16874 struct tinst_level *
16875 current_instantiation (void)
16876 {
16877   return current_tinst_level;
16878 }
16879
16880 /* [temp.param] Check that template non-type parm TYPE is of an allowable
16881    type. Return zero for ok, nonzero for disallowed. Issue error and
16882    warning messages under control of COMPLAIN.  */
16883
16884 static int
16885 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
16886 {
16887   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
16888     return 0;
16889   else if (POINTER_TYPE_P (type))
16890     return 0;
16891   else if (TYPE_PTR_TO_MEMBER_P (type))
16892     return 0;
16893   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16894     return 0;
16895   else if (TREE_CODE (type) == TYPENAME_TYPE)
16896     return 0;
16897
16898   if (complain & tf_error)
16899     error ("%q#T is not a valid type for a template constant parameter", type);
16900   return 1;
16901 }
16902
16903 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
16904    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
16905
16906 static bool
16907 dependent_type_p_r (tree type)
16908 {
16909   tree scope;
16910
16911   /* [temp.dep.type]
16912
16913      A type is dependent if it is:
16914
16915      -- a template parameter. Template template parameters are types
16916         for us (since TYPE_P holds true for them) so we handle
16917         them here.  */
16918   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16919       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
16920     return true;
16921   /* -- a qualified-id with a nested-name-specifier which contains a
16922         class-name that names a dependent type or whose unqualified-id
16923         names a dependent type.  */
16924   if (TREE_CODE (type) == TYPENAME_TYPE)
16925     return true;
16926   /* -- a cv-qualified type where the cv-unqualified type is
16927         dependent.  */
16928   type = TYPE_MAIN_VARIANT (type);
16929   /* -- a compound type constructed from any dependent type.  */
16930   if (TYPE_PTR_TO_MEMBER_P (type))
16931     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
16932             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
16933                                            (type)));
16934   else if (TREE_CODE (type) == POINTER_TYPE
16935            || TREE_CODE (type) == REFERENCE_TYPE)
16936     return dependent_type_p (TREE_TYPE (type));
16937   else if (TREE_CODE (type) == FUNCTION_TYPE
16938            || TREE_CODE (type) == METHOD_TYPE)
16939     {
16940       tree arg_type;
16941
16942       if (dependent_type_p (TREE_TYPE (type)))
16943         return true;
16944       for (arg_type = TYPE_ARG_TYPES (type);
16945            arg_type;
16946            arg_type = TREE_CHAIN (arg_type))
16947         if (dependent_type_p (TREE_VALUE (arg_type)))
16948           return true;
16949       return false;
16950     }
16951   /* -- an array type constructed from any dependent type or whose
16952         size is specified by a constant expression that is
16953         value-dependent.  */
16954   if (TREE_CODE (type) == ARRAY_TYPE)
16955     {
16956       if (TYPE_DOMAIN (type)
16957           && dependent_type_p (TYPE_DOMAIN (type)))
16958         return true;
16959       return dependent_type_p (TREE_TYPE (type));
16960     }
16961   else if (TREE_CODE (type) == INTEGER_TYPE
16962            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
16963     {
16964       /* If this is the TYPE_DOMAIN of an array type, consider it
16965          dependent.  We already checked for value-dependence in
16966          compute_array_index_type.  */
16967       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
16968     }
16969
16970   /* -- a template-id in which either the template name is a template
16971      parameter ...  */
16972   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
16973     return true;
16974   /* ... or any of the template arguments is a dependent type or
16975         an expression that is type-dependent or value-dependent.  */
16976   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
16977            && (any_dependent_template_arguments_p
16978                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
16979     return true;
16980
16981   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
16982      argument of the `typeof' expression is not type-dependent, then
16983      it should already been have resolved.  */
16984   if (TREE_CODE (type) == TYPEOF_TYPE
16985       || TREE_CODE (type) == DECLTYPE_TYPE)
16986     return true;
16987
16988   /* A template argument pack is dependent if any of its packed
16989      arguments are.  */
16990   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
16991     {
16992       tree args = ARGUMENT_PACK_ARGS (type);
16993       int i, len = TREE_VEC_LENGTH (args);
16994       for (i = 0; i < len; ++i)
16995         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16996           return true;
16997     }
16998
16999   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17000      be template parameters.  */
17001   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17002     return true;
17003
17004   /* The standard does not specifically mention types that are local
17005      to template functions or local classes, but they should be
17006      considered dependent too.  For example:
17007
17008        template <int I> void f() {
17009          enum E { a = I };
17010          S<sizeof (E)> s;
17011        }
17012
17013      The size of `E' cannot be known until the value of `I' has been
17014      determined.  Therefore, `E' must be considered dependent.  */
17015   scope = TYPE_CONTEXT (type);
17016   if (scope && TYPE_P (scope))
17017     return dependent_type_p (scope);
17018   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17019     return type_dependent_expression_p (scope);
17020
17021   /* Other types are non-dependent.  */
17022   return false;
17023 }
17024
17025 /* Returns TRUE if TYPE is dependent, in the sense of
17026    [temp.dep.type].  */
17027
17028 bool
17029 dependent_type_p (tree type)
17030 {
17031   /* If there are no template parameters in scope, then there can't be
17032      any dependent types.  */
17033   if (!processing_template_decl)
17034     {
17035       /* If we are not processing a template, then nobody should be
17036          providing us with a dependent type.  */
17037       gcc_assert (type);
17038       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17039       return false;
17040     }
17041
17042   /* If the type is NULL, we have not computed a type for the entity
17043      in question; in that case, the type is dependent.  */
17044   if (!type)
17045     return true;
17046
17047   /* Erroneous types can be considered non-dependent.  */
17048   if (type == error_mark_node)
17049     return false;
17050
17051   /* If we have not already computed the appropriate value for TYPE,
17052      do so now.  */
17053   if (!TYPE_DEPENDENT_P_VALID (type))
17054     {
17055       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17056       TYPE_DEPENDENT_P_VALID (type) = 1;
17057     }
17058
17059   return TYPE_DEPENDENT_P (type);
17060 }
17061
17062 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17063    lookup.  In other words, a dependent type that is not the current
17064    instantiation.  */
17065
17066 bool
17067 dependent_scope_p (tree scope)
17068 {
17069   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17070           && !currently_open_class (scope));
17071 }
17072
17073 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
17074
17075 static bool
17076 dependent_scope_ref_p (tree expression, bool criterion (tree))
17077 {
17078   tree scope;
17079   tree name;
17080
17081   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
17082
17083   if (!TYPE_P (TREE_OPERAND (expression, 0)))
17084     return true;
17085
17086   scope = TREE_OPERAND (expression, 0);
17087   name = TREE_OPERAND (expression, 1);
17088
17089   /* [temp.dep.expr]
17090
17091      An id-expression is type-dependent if it contains a
17092      nested-name-specifier that contains a class-name that names a
17093      dependent type.  */
17094   /* The suggested resolution to Core Issue 224 implies that if the
17095      qualifying type is the current class, then we must peek
17096      inside it.  */
17097   if (DECL_P (name)
17098       && currently_open_class (scope)
17099       && !criterion (name))
17100     return false;
17101   if (dependent_type_p (scope))
17102     return true;
17103
17104   return false;
17105 }
17106
17107 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17108    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17109    expression.  */
17110
17111 bool
17112 value_dependent_expression_p (tree expression)
17113 {
17114   if (!processing_template_decl)
17115     return false;
17116
17117   /* A name declared with a dependent type.  */
17118   if (DECL_P (expression) && type_dependent_expression_p (expression))
17119     return true;
17120
17121   switch (TREE_CODE (expression))
17122     {
17123     case IDENTIFIER_NODE:
17124       /* A name that has not been looked up -- must be dependent.  */
17125       return true;
17126
17127     case TEMPLATE_PARM_INDEX:
17128       /* A non-type template parm.  */
17129       return true;
17130
17131     case CONST_DECL:
17132       /* A non-type template parm.  */
17133       if (DECL_TEMPLATE_PARM_P (expression))
17134         return true;
17135       return value_dependent_expression_p (DECL_INITIAL (expression));
17136
17137     case VAR_DECL:
17138        /* A constant with integral or enumeration type and is initialized
17139           with an expression that is value-dependent.  */
17140       if (DECL_INITIAL (expression)
17141           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17142           && value_dependent_expression_p (DECL_INITIAL (expression)))
17143         return true;
17144       return false;
17145
17146     case DYNAMIC_CAST_EXPR:
17147     case STATIC_CAST_EXPR:
17148     case CONST_CAST_EXPR:
17149     case REINTERPRET_CAST_EXPR:
17150     case CAST_EXPR:
17151       /* These expressions are value-dependent if the type to which
17152          the cast occurs is dependent or the expression being casted
17153          is value-dependent.  */
17154       {
17155         tree type = TREE_TYPE (expression);
17156
17157         if (dependent_type_p (type))
17158           return true;
17159
17160         /* A functional cast has a list of operands.  */
17161         expression = TREE_OPERAND (expression, 0);
17162         if (!expression)
17163           {
17164             /* If there are no operands, it must be an expression such
17165                as "int()". This should not happen for aggregate types
17166                because it would form non-constant expressions.  */
17167             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17168
17169             return false;
17170           }
17171
17172         if (TREE_CODE (expression) == TREE_LIST)
17173           return any_value_dependent_elements_p (expression);
17174
17175         return value_dependent_expression_p (expression);
17176       }
17177
17178     case SIZEOF_EXPR:
17179     case ALIGNOF_EXPR:
17180       /* A `sizeof' expression is value-dependent if the operand is
17181          type-dependent or is a pack expansion.  */
17182       expression = TREE_OPERAND (expression, 0);
17183       if (PACK_EXPANSION_P (expression))
17184         return true;
17185       else if (TYPE_P (expression))
17186         return dependent_type_p (expression);
17187       return type_dependent_expression_p (expression);
17188
17189     case SCOPE_REF:
17190       return dependent_scope_ref_p (expression, value_dependent_expression_p);
17191
17192     case COMPONENT_REF:
17193       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17194               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17195
17196     case CALL_EXPR:
17197       /* A CALL_EXPR may appear in a constant expression if it is a
17198          call to a builtin function, e.g., __builtin_constant_p.  All
17199          such calls are value-dependent.  */
17200       return true;
17201
17202     case NONTYPE_ARGUMENT_PACK:
17203       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17204          is value-dependent.  */
17205       {
17206         tree values = ARGUMENT_PACK_ARGS (expression);
17207         int i, len = TREE_VEC_LENGTH (values);
17208         
17209         for (i = 0; i < len; ++i)
17210           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17211             return true;
17212         
17213         return false;
17214       }
17215
17216     case TRAIT_EXPR:
17217       {
17218         tree type2 = TRAIT_EXPR_TYPE2 (expression);
17219         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17220                 || (type2 ? dependent_type_p (type2) : false));
17221       }
17222
17223     case MODOP_EXPR:
17224       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17225               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17226
17227     default:
17228       /* A constant expression is value-dependent if any subexpression is
17229          value-dependent.  */
17230       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17231         {
17232         case tcc_reference:
17233         case tcc_unary:
17234           return (value_dependent_expression_p
17235                   (TREE_OPERAND (expression, 0)));
17236
17237         case tcc_comparison:
17238         case tcc_binary:
17239           return ((value_dependent_expression_p
17240                    (TREE_OPERAND (expression, 0)))
17241                   || (value_dependent_expression_p
17242                       (TREE_OPERAND (expression, 1))));
17243
17244         case tcc_expression:
17245         case tcc_vl_exp:
17246           {
17247             int i;
17248             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17249               /* In some cases, some of the operands may be missing.
17250                  (For example, in the case of PREDECREMENT_EXPR, the
17251                  amount to increment by may be missing.)  That doesn't
17252                  make the expression dependent.  */
17253               if (TREE_OPERAND (expression, i)
17254                   && (value_dependent_expression_p
17255                       (TREE_OPERAND (expression, i))))
17256                 return true;
17257             return false;
17258           }
17259
17260         default:
17261           break;
17262         }
17263     }
17264
17265   /* The expression is not value-dependent.  */
17266   return false;
17267 }
17268
17269 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17270    [temp.dep.expr].  */
17271
17272 bool
17273 type_dependent_expression_p (tree expression)
17274 {
17275   if (!processing_template_decl)
17276     return false;
17277
17278   if (expression == error_mark_node)
17279     return false;
17280
17281   /* An unresolved name is always dependent.  */
17282   if (TREE_CODE (expression) == IDENTIFIER_NODE
17283       || TREE_CODE (expression) == USING_DECL)
17284     return true;
17285
17286   /* Some expression forms are never type-dependent.  */
17287   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17288       || TREE_CODE (expression) == SIZEOF_EXPR
17289       || TREE_CODE (expression) == ALIGNOF_EXPR
17290       || TREE_CODE (expression) == TRAIT_EXPR
17291       || TREE_CODE (expression) == TYPEID_EXPR
17292       || TREE_CODE (expression) == DELETE_EXPR
17293       || TREE_CODE (expression) == VEC_DELETE_EXPR
17294       || TREE_CODE (expression) == THROW_EXPR)
17295     return false;
17296
17297   /* The types of these expressions depends only on the type to which
17298      the cast occurs.  */
17299   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17300       || TREE_CODE (expression) == STATIC_CAST_EXPR
17301       || TREE_CODE (expression) == CONST_CAST_EXPR
17302       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17303       || TREE_CODE (expression) == CAST_EXPR)
17304     return dependent_type_p (TREE_TYPE (expression));
17305
17306   /* The types of these expressions depends only on the type created
17307      by the expression.  */
17308   if (TREE_CODE (expression) == NEW_EXPR
17309       || TREE_CODE (expression) == VEC_NEW_EXPR)
17310     {
17311       /* For NEW_EXPR tree nodes created inside a template, either
17312          the object type itself or a TREE_LIST may appear as the
17313          operand 1.  */
17314       tree type = TREE_OPERAND (expression, 1);
17315       if (TREE_CODE (type) == TREE_LIST)
17316         /* This is an array type.  We need to check array dimensions
17317            as well.  */
17318         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17319                || value_dependent_expression_p
17320                     (TREE_OPERAND (TREE_VALUE (type), 1));
17321       else
17322         return dependent_type_p (type);
17323     }
17324
17325   if (TREE_CODE (expression) == SCOPE_REF
17326       && dependent_scope_ref_p (expression,
17327                                 type_dependent_expression_p))
17328     return true;
17329
17330   if (TREE_CODE (expression) == FUNCTION_DECL
17331       && DECL_LANG_SPECIFIC (expression)
17332       && DECL_TEMPLATE_INFO (expression)
17333       && (any_dependent_template_arguments_p
17334           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17335     return true;
17336
17337   if (TREE_CODE (expression) == TEMPLATE_DECL
17338       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17339     return false;
17340
17341   if (TREE_CODE (expression) == STMT_EXPR)
17342     expression = stmt_expr_value_expr (expression);
17343
17344   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17345     {
17346       tree elt;
17347       unsigned i;
17348
17349       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17350         {
17351           if (type_dependent_expression_p (elt))
17352             return true;
17353         }
17354       return false;
17355     }
17356
17357   if (TREE_TYPE (expression) == unknown_type_node)
17358     {
17359       if (TREE_CODE (expression) == ADDR_EXPR)
17360         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17361       if (TREE_CODE (expression) == COMPONENT_REF
17362           || TREE_CODE (expression) == OFFSET_REF)
17363         {
17364           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17365             return true;
17366           expression = TREE_OPERAND (expression, 1);
17367           if (TREE_CODE (expression) == IDENTIFIER_NODE)
17368             return false;
17369         }
17370       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17371       if (TREE_CODE (expression) == SCOPE_REF)
17372         return false;
17373
17374       if (TREE_CODE (expression) == BASELINK)
17375         expression = BASELINK_FUNCTIONS (expression);
17376
17377       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17378         {
17379           if (any_dependent_template_arguments_p
17380               (TREE_OPERAND (expression, 1)))
17381             return true;
17382           expression = TREE_OPERAND (expression, 0);
17383         }
17384       gcc_assert (TREE_CODE (expression) == OVERLOAD
17385                   || TREE_CODE (expression) == FUNCTION_DECL);
17386
17387       while (expression)
17388         {
17389           if (type_dependent_expression_p (OVL_CURRENT (expression)))
17390             return true;
17391           expression = OVL_NEXT (expression);
17392         }
17393       return false;
17394     }
17395
17396   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17397
17398   return (dependent_type_p (TREE_TYPE (expression)));
17399 }
17400
17401 /* Like type_dependent_expression_p, but it also works while not processing
17402    a template definition, i.e. during substitution or mangling.  */
17403
17404 bool
17405 type_dependent_expression_p_push (tree expr)
17406 {
17407   bool b;
17408   ++processing_template_decl;
17409   b = type_dependent_expression_p (expr);
17410   --processing_template_decl;
17411   return b;
17412 }
17413
17414 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17415
17416 bool
17417 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17418 {
17419   unsigned int i;
17420   tree arg;
17421
17422   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
17423     {
17424       if (type_dependent_expression_p (arg))
17425         return true;
17426     }
17427   return false;
17428 }
17429
17430 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17431    expressions) contains any value-dependent expressions.  */
17432
17433 bool
17434 any_value_dependent_elements_p (const_tree list)
17435 {
17436   for (; list; list = TREE_CHAIN (list))
17437     if (value_dependent_expression_p (TREE_VALUE (list)))
17438       return true;
17439
17440   return false;
17441 }
17442
17443 /* Returns TRUE if the ARG (a template argument) is dependent.  */
17444
17445 bool
17446 dependent_template_arg_p (tree arg)
17447 {
17448   if (!processing_template_decl)
17449     return false;
17450
17451   if (TREE_CODE (arg) == TEMPLATE_DECL
17452       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17453     return dependent_template_p (arg);
17454   else if (ARGUMENT_PACK_P (arg))
17455     {
17456       tree args = ARGUMENT_PACK_ARGS (arg);
17457       int i, len = TREE_VEC_LENGTH (args);
17458       for (i = 0; i < len; ++i)
17459         {
17460           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17461             return true;
17462         }
17463
17464       return false;
17465     }
17466   else if (TYPE_P (arg))
17467     return dependent_type_p (arg);
17468   else
17469     return (type_dependent_expression_p (arg)
17470             || value_dependent_expression_p (arg));
17471 }
17472
17473 /* Returns true if ARGS (a collection of template arguments) contains
17474    any types that require structural equality testing.  */
17475
17476 bool
17477 any_template_arguments_need_structural_equality_p (tree args)
17478 {
17479   int i;
17480   int j;
17481
17482   if (!args)
17483     return false;
17484   if (args == error_mark_node)
17485     return true;
17486
17487   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17488     {
17489       tree level = TMPL_ARGS_LEVEL (args, i + 1);
17490       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17491         {
17492           tree arg = TREE_VEC_ELT (level, j);
17493           tree packed_args = NULL_TREE;
17494           int k, len = 1;
17495
17496           if (ARGUMENT_PACK_P (arg))
17497             {
17498               /* Look inside the argument pack.  */
17499               packed_args = ARGUMENT_PACK_ARGS (arg);
17500               len = TREE_VEC_LENGTH (packed_args);
17501             }
17502
17503           for (k = 0; k < len; ++k)
17504             {
17505               if (packed_args)
17506                 arg = TREE_VEC_ELT (packed_args, k);
17507
17508               if (error_operand_p (arg))
17509                 return true;
17510               else if (TREE_CODE (arg) == TEMPLATE_DECL
17511                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17512                 continue;
17513               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17514                 return true;
17515               else if (!TYPE_P (arg) && TREE_TYPE (arg)
17516                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17517                 return true;
17518             }
17519         }
17520     }
17521
17522   return false;
17523 }
17524
17525 /* Returns true if ARGS (a collection of template arguments) contains
17526    any dependent arguments.  */
17527
17528 bool
17529 any_dependent_template_arguments_p (const_tree args)
17530 {
17531   int i;
17532   int j;
17533
17534   if (!args)
17535     return false;
17536   if (args == error_mark_node)
17537     return true;
17538
17539   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17540     {
17541       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17542       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17543         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17544           return true;
17545     }
17546
17547   return false;
17548 }
17549
17550 /* Returns TRUE if the template TMPL is dependent.  */
17551
17552 bool
17553 dependent_template_p (tree tmpl)
17554 {
17555   if (TREE_CODE (tmpl) == OVERLOAD)
17556     {
17557       while (tmpl)
17558         {
17559           if (dependent_template_p (OVL_FUNCTION (tmpl)))
17560             return true;
17561           tmpl = OVL_CHAIN (tmpl);
17562         }
17563       return false;
17564     }
17565
17566   /* Template template parameters are dependent.  */
17567   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
17568       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
17569     return true;
17570   /* So are names that have not been looked up.  */
17571   if (TREE_CODE (tmpl) == SCOPE_REF
17572       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
17573     return true;
17574   /* So are member templates of dependent classes.  */
17575   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
17576     return dependent_type_p (DECL_CONTEXT (tmpl));
17577   return false;
17578 }
17579
17580 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
17581
17582 bool
17583 dependent_template_id_p (tree tmpl, tree args)
17584 {
17585   return (dependent_template_p (tmpl)
17586           || any_dependent_template_arguments_p (args));
17587 }
17588
17589 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
17590    is dependent.  */
17591
17592 bool
17593 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
17594 {
17595   int i;
17596
17597   if (!processing_template_decl)
17598     return false;
17599
17600   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
17601     {
17602       tree decl = TREE_VEC_ELT (declv, i);
17603       tree init = TREE_VEC_ELT (initv, i);
17604       tree cond = TREE_VEC_ELT (condv, i);
17605       tree incr = TREE_VEC_ELT (incrv, i);
17606
17607       if (type_dependent_expression_p (decl))
17608         return true;
17609
17610       if (init && type_dependent_expression_p (init))
17611         return true;
17612
17613       if (type_dependent_expression_p (cond))
17614         return true;
17615
17616       if (COMPARISON_CLASS_P (cond)
17617           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
17618               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
17619         return true;
17620
17621       if (TREE_CODE (incr) == MODOP_EXPR)
17622         {
17623           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
17624               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
17625             return true;
17626         }
17627       else if (type_dependent_expression_p (incr))
17628         return true;
17629       else if (TREE_CODE (incr) == MODIFY_EXPR)
17630         {
17631           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
17632             return true;
17633           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
17634             {
17635               tree t = TREE_OPERAND (incr, 1);
17636               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
17637                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
17638                 return true;
17639             }
17640         }
17641     }
17642
17643   return false;
17644 }
17645
17646 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
17647    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
17648    no such TYPE can be found.  Note that this function peers inside
17649    uninstantiated templates and therefore should be used only in
17650    extremely limited situations.  ONLY_CURRENT_P restricts this
17651    peering to the currently open classes hierarchy (which is required
17652    when comparing types).  */
17653
17654 tree
17655 resolve_typename_type (tree type, bool only_current_p)
17656 {
17657   tree scope;
17658   tree name;
17659   tree decl;
17660   int quals;
17661   tree pushed_scope;
17662   tree result;
17663
17664   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
17665
17666   scope = TYPE_CONTEXT (type);
17667   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
17668      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
17669      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
17670      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
17671      identifier  of the TYPENAME_TYPE anymore.
17672      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
17673      TYPENAME_TYPE instead, we avoid messing up with a possible
17674      typedef variant case.  */
17675   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
17676
17677   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
17678      it first before we can figure out what NAME refers to.  */
17679   if (TREE_CODE (scope) == TYPENAME_TYPE)
17680     scope = resolve_typename_type (scope, only_current_p);
17681   /* If we don't know what SCOPE refers to, then we cannot resolve the
17682      TYPENAME_TYPE.  */
17683   if (TREE_CODE (scope) == TYPENAME_TYPE)
17684     return type;
17685   /* If the SCOPE is a template type parameter, we have no way of
17686      resolving the name.  */
17687   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
17688     return type;
17689   /* If the SCOPE is not the current instantiation, there's no reason
17690      to look inside it.  */
17691   if (only_current_p && !currently_open_class (scope))
17692     return type;
17693   /* If SCOPE isn't the template itself, it will not have a valid
17694      TYPE_FIELDS list.  */
17695   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
17696     /* scope is either the template itself or a compatible instantiation
17697        like X<T>, so look up the name in the original template.  */
17698     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
17699   else
17700     /* scope is a partial instantiation, so we can't do the lookup or we
17701        will lose the template arguments.  */
17702     return type;
17703   /* Enter the SCOPE so that name lookup will be resolved as if we
17704      were in the class definition.  In particular, SCOPE will no
17705      longer be considered a dependent type.  */
17706   pushed_scope = push_scope (scope);
17707   /* Look up the declaration.  */
17708   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
17709
17710   result = NULL_TREE;
17711   
17712   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
17713      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
17714   if (!decl)
17715     /*nop*/;
17716   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
17717            && TREE_CODE (decl) == TYPE_DECL)
17718     {
17719       result = TREE_TYPE (decl);
17720       if (result == error_mark_node)
17721         result = NULL_TREE;
17722     }
17723   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
17724            && DECL_CLASS_TEMPLATE_P (decl))
17725     {
17726       tree tmpl;
17727       tree args;
17728       /* Obtain the template and the arguments.  */
17729       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
17730       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
17731       /* Instantiate the template.  */
17732       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
17733                                       /*entering_scope=*/0,
17734                                       tf_error | tf_user);
17735       if (result == error_mark_node)
17736         result = NULL_TREE;
17737     }
17738   
17739   /* Leave the SCOPE.  */
17740   if (pushed_scope)
17741     pop_scope (pushed_scope);
17742
17743   /* If we failed to resolve it, return the original typename.  */
17744   if (!result)
17745     return type;
17746   
17747   /* If lookup found a typename type, resolve that too.  */
17748   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
17749     {
17750       /* Ill-formed programs can cause infinite recursion here, so we
17751          must catch that.  */
17752       TYPENAME_IS_RESOLVING_P (type) = 1;
17753       result = resolve_typename_type (result, only_current_p);
17754       TYPENAME_IS_RESOLVING_P (type) = 0;
17755     }
17756   
17757   /* Qualify the resulting type.  */
17758   quals = cp_type_quals (type);
17759   if (quals)
17760     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
17761
17762   return result;
17763 }
17764
17765 /* EXPR is an expression which is not type-dependent.  Return a proxy
17766    for EXPR that can be used to compute the types of larger
17767    expressions containing EXPR.  */
17768
17769 tree
17770 build_non_dependent_expr (tree expr)
17771 {
17772   tree inner_expr;
17773
17774   /* Preserve null pointer constants so that the type of things like
17775      "p == 0" where "p" is a pointer can be determined.  */
17776   if (null_ptr_cst_p (expr))
17777     return expr;
17778   /* Preserve OVERLOADs; the functions must be available to resolve
17779      types.  */
17780   inner_expr = expr;
17781   if (TREE_CODE (inner_expr) == STMT_EXPR)
17782     inner_expr = stmt_expr_value_expr (inner_expr);
17783   if (TREE_CODE (inner_expr) == ADDR_EXPR)
17784     inner_expr = TREE_OPERAND (inner_expr, 0);
17785   if (TREE_CODE (inner_expr) == COMPONENT_REF)
17786     inner_expr = TREE_OPERAND (inner_expr, 1);
17787   if (is_overloaded_fn (inner_expr)
17788       || TREE_CODE (inner_expr) == OFFSET_REF)
17789     return expr;
17790   /* There is no need to return a proxy for a variable.  */
17791   if (TREE_CODE (expr) == VAR_DECL)
17792     return expr;
17793   /* Preserve string constants; conversions from string constants to
17794      "char *" are allowed, even though normally a "const char *"
17795      cannot be used to initialize a "char *".  */
17796   if (TREE_CODE (expr) == STRING_CST)
17797     return expr;
17798   /* Preserve arithmetic constants, as an optimization -- there is no
17799      reason to create a new node.  */
17800   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
17801     return expr;
17802   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
17803      There is at least one place where we want to know that a
17804      particular expression is a throw-expression: when checking a ?:
17805      expression, there are special rules if the second or third
17806      argument is a throw-expression.  */
17807   if (TREE_CODE (expr) == THROW_EXPR)
17808     return expr;
17809
17810   if (TREE_CODE (expr) == COND_EXPR)
17811     return build3 (COND_EXPR,
17812                    TREE_TYPE (expr),
17813                    TREE_OPERAND (expr, 0),
17814                    (TREE_OPERAND (expr, 1)
17815                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
17816                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
17817                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
17818   if (TREE_CODE (expr) == COMPOUND_EXPR
17819       && !COMPOUND_EXPR_OVERLOADED (expr))
17820     return build2 (COMPOUND_EXPR,
17821                    TREE_TYPE (expr),
17822                    TREE_OPERAND (expr, 0),
17823                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
17824
17825   /* If the type is unknown, it can't really be non-dependent */
17826   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
17827
17828   /* Otherwise, build a NON_DEPENDENT_EXPR.
17829
17830      REFERENCE_TYPEs are not stripped for expressions in templates
17831      because doing so would play havoc with mangling.  Consider, for
17832      example:
17833
17834        template <typename T> void f<T& g>() { g(); }
17835
17836      In the body of "f", the expression for "g" will have
17837      REFERENCE_TYPE, even though the standard says that it should
17838      not.  The reason is that we must preserve the syntactic form of
17839      the expression so that mangling (say) "f<g>" inside the body of
17840      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
17841      stripped here.  */
17842   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
17843 }
17844
17845 /* ARGS is a vector of expressions as arguments to a function call.
17846    Replace the arguments with equivalent non-dependent expressions.
17847    This modifies ARGS in place.  */
17848
17849 void
17850 make_args_non_dependent (VEC(tree,gc) *args)
17851 {
17852   unsigned int ix;
17853   tree arg;
17854
17855   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
17856     {
17857       tree newarg = build_non_dependent_expr (arg);
17858       if (newarg != arg)
17859         VEC_replace (tree, args, ix, newarg);
17860     }
17861 }
17862
17863 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
17864    with a level one deeper than the actual template parms.  */
17865
17866 tree
17867 make_auto (void)
17868 {
17869   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
17870   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
17871                                TYPE_DECL, get_identifier ("auto"), au);
17872   TYPE_STUB_DECL (au) = TYPE_NAME (au);
17873   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
17874     (0, processing_template_decl + 1, processing_template_decl + 1,
17875      TYPE_NAME (au), NULL_TREE);
17876   TYPE_CANONICAL (au) = canonical_type_parameter (au);
17877   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
17878   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
17879
17880   return au;
17881 }
17882
17883 /* Given type ARG, return std::initializer_list<ARG>.  */
17884
17885 static tree
17886 listify (tree arg)
17887 {
17888   tree std_init_list = namespace_binding
17889     (get_identifier ("initializer_list"), std_node);
17890   tree argvec;
17891   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
17892     {    
17893       error ("deducing from brace-enclosed initializer list requires "
17894              "#include <initializer_list>");
17895       return error_mark_node;
17896     }
17897   argvec = make_tree_vec (1);
17898   TREE_VEC_ELT (argvec, 0) = arg;
17899   return lookup_template_class (std_init_list, argvec, NULL_TREE,
17900                                 NULL_TREE, 0, tf_warning_or_error);
17901 }
17902
17903 /* Replace auto in TYPE with std::initializer_list<auto>.  */
17904
17905 static tree
17906 listify_autos (tree type, tree auto_node)
17907 {
17908   tree init_auto = listify (auto_node);
17909   tree argvec = make_tree_vec (1);
17910   TREE_VEC_ELT (argvec, 0) = init_auto;
17911   if (processing_template_decl)
17912     argvec = add_to_template_args (current_template_args (), argvec);
17913   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17914 }
17915
17916 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
17917    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
17918
17919 tree
17920 do_auto_deduction (tree type, tree init, tree auto_node)
17921 {
17922   tree parms, tparms, targs;
17923   tree args[1];
17924   int val;
17925
17926   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
17927      with either a new invented type template parameter U or, if the
17928      initializer is a braced-init-list (8.5.4), with
17929      std::initializer_list<U>.  */
17930   if (BRACE_ENCLOSED_INITIALIZER_P (init))
17931     type = listify_autos (type, auto_node);
17932
17933   parms = build_tree_list (NULL_TREE, type);
17934   args[0] = init;
17935   tparms = make_tree_vec (1);
17936   targs = make_tree_vec (1);
17937   TREE_VEC_ELT (tparms, 0)
17938     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
17939   val = type_unification_real (tparms, targs, parms, args, 1, 0,
17940                                DEDUCE_CALL, LOOKUP_NORMAL);
17941   if (val > 0)
17942     {
17943       error ("unable to deduce %qT from %qE", type, init);
17944       return error_mark_node;
17945     }
17946
17947   /* If the list of declarators contains more than one declarator, the type
17948      of each declared variable is determined as described above. If the
17949      type deduced for the template parameter U is not the same in each
17950      deduction, the program is ill-formed.  */
17951   if (TREE_TYPE (auto_node)
17952       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
17953     {
17954       error ("inconsistent deduction for %qT: %qT and then %qT",
17955              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
17956       return error_mark_node;
17957     }
17958   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
17959
17960   if (processing_template_decl)
17961     targs = add_to_template_args (current_template_args (), targs);
17962   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
17963 }
17964
17965 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
17966    result.  */
17967
17968 tree
17969 splice_late_return_type (tree type, tree late_return_type)
17970 {
17971   tree argvec;
17972
17973   if (late_return_type == NULL_TREE)
17974     return type;
17975   argvec = make_tree_vec (1);
17976   TREE_VEC_ELT (argvec, 0) = late_return_type;
17977   if (processing_template_decl)
17978     argvec = add_to_template_args (current_template_args (), argvec);
17979   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17980 }
17981
17982 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
17983
17984 bool
17985 is_auto (const_tree type)
17986 {
17987   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17988       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
17989     return true;
17990   else
17991     return false;
17992 }
17993
17994 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
17995    appear as a type-specifier for the declaration in question, we don't
17996    have to look through the whole type.  */
17997
17998 tree
17999 type_uses_auto (tree type)
18000 {
18001   enum tree_code code;
18002   if (is_auto (type))
18003     return type;
18004
18005   code = TREE_CODE (type);
18006
18007   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18008       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18009       || code == METHOD_TYPE || code == ARRAY_TYPE)
18010     return type_uses_auto (TREE_TYPE (type));
18011
18012   if (TYPE_PTRMEMFUNC_P (type))
18013     return type_uses_auto (TREE_TYPE (TREE_TYPE
18014                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18015
18016   return NULL_TREE;
18017 }
18018
18019 /* For a given template T, return the list of typedefs referenced
18020    in T for which access check is needed at T instantiation time.
18021    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18022    Those typedefs were added to T by the function
18023    append_type_to_template_for_access_check.  */
18024
18025 tree
18026 get_types_needing_access_check (tree t)
18027 {
18028   tree ti, result = NULL_TREE;
18029
18030   if (!t || t == error_mark_node)
18031     return t;
18032
18033   if (!(ti = get_template_info (t)))
18034     return NULL_TREE;
18035
18036   if (CLASS_TYPE_P (t)
18037       || TREE_CODE (t) == FUNCTION_DECL)
18038     {
18039       if (!TI_TEMPLATE (ti))
18040         return NULL_TREE;
18041
18042       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18043     }
18044
18045   return result;
18046 }
18047
18048 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
18049    tied to T. That list of typedefs will be access checked at
18050    T instantiation time.
18051    T is either a FUNCTION_DECL or a RECORD_TYPE.
18052    TYPE_DECL is a TYPE_DECL node representing a typedef.
18053    SCOPE is the scope through which TYPE_DECL is accessed.
18054
18055    This function is a subroutine of
18056    append_type_to_template_for_access_check.  */
18057
18058 static void
18059 append_type_to_template_for_access_check_1 (tree t,
18060                                             tree type_decl,
18061                                             tree scope)
18062 {
18063   tree ti;
18064
18065   if (!t || t == error_mark_node)
18066     return;
18067
18068   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18069                || CLASS_TYPE_P (t))
18070               && type_decl
18071               && TREE_CODE (type_decl) == TYPE_DECL
18072               && scope);
18073
18074   if (!(ti = get_template_info (t)))
18075     return;
18076
18077   gcc_assert (TI_TEMPLATE (ti));
18078
18079   TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti) =
18080     tree_cons (type_decl, scope, TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti));
18081 }
18082
18083 /* Append TYPE_DECL to the template TEMPL.
18084    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18085    At TEMPL instanciation time, TYPE_DECL will be checked to see
18086    if it can be accessed through SCOPE.
18087
18088    e.g. consider the following code snippet:
18089
18090      class C
18091      {
18092        typedef int myint;
18093      };
18094
18095      template<class U> struct S
18096      {
18097        C::myint mi;
18098      };
18099
18100      S<char> s;
18101
18102    At S<char> instantiation time, we need to check the access of C::myint
18103    In other words, we need to check the access of the myint typedef through
18104    the C scope. For that purpose, this function will add the myint typedef
18105    and the scope C through which its being accessed to a list of typedefs
18106    tied to the template S. That list will be walked at template instantiation
18107    time and access check performed on each typedefs it contains.
18108    Note that this particular code snippet should yield an error because
18109    myint is private to C.  */
18110
18111 void
18112 append_type_to_template_for_access_check (tree templ,
18113                                           tree type_decl,
18114                                           tree scope)
18115 {
18116   tree node;
18117
18118   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18119
18120   /* Make sure we don't append the type to the template twice.  */
18121   for (node = get_types_needing_access_check (templ);
18122        node;
18123        node = TREE_CHAIN (node))
18124     {
18125       tree decl = TREE_PURPOSE (node);
18126       tree type_scope = TREE_VALUE (node);
18127
18128       if (decl == type_decl && type_scope == scope)
18129         return;
18130     }
18131
18132   append_type_to_template_for_access_check_1 (templ, type_decl, scope);
18133 }
18134
18135 /* Set up the hash tables for template instantiations.  */
18136
18137 void
18138 init_template_processing (void)
18139 {
18140   decl_specializations = htab_create_ggc (37,
18141                                           hash_specialization,
18142                                           eq_specializations,
18143                                           ggc_free);
18144   type_specializations = htab_create_ggc (37,
18145                                           hash_specialization,
18146                                           eq_specializations,
18147                                           ggc_free);
18148 }
18149
18150 #include "gt-cp-pt.h"