OSDN Git Service

PR c++/11987
[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 tree listify (tree);
195 static tree listify_autos (tree, tree);
196
197 /* Make the current scope suitable for access checking when we are
198    processing T.  T can be FUNCTION_DECL for instantiated function
199    template, or VAR_DECL for static member variable (need by
200    instantiate_decl).  */
201
202 static void
203 push_access_scope (tree t)
204 {
205   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
206               || TREE_CODE (t) == VAR_DECL);
207
208   if (DECL_FRIEND_CONTEXT (t))
209     push_nested_class (DECL_FRIEND_CONTEXT (t));
210   else if (DECL_CLASS_SCOPE_P (t))
211     push_nested_class (DECL_CONTEXT (t));
212   else
213     push_to_top_level ();
214
215   if (TREE_CODE (t) == FUNCTION_DECL)
216     {
217       saved_access_scope = tree_cons
218         (NULL_TREE, current_function_decl, saved_access_scope);
219       current_function_decl = t;
220     }
221 }
222
223 /* Restore the scope set up by push_access_scope.  T is the node we
224    are processing.  */
225
226 static void
227 pop_access_scope (tree t)
228 {
229   if (TREE_CODE (t) == FUNCTION_DECL)
230     {
231       current_function_decl = TREE_VALUE (saved_access_scope);
232       saved_access_scope = TREE_CHAIN (saved_access_scope);
233     }
234
235   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
236     pop_nested_class ();
237   else
238     pop_from_top_level ();
239 }
240
241 /* Do any processing required when DECL (a member template
242    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
243    to DECL, unless it is a specialization, in which case the DECL
244    itself is returned.  */
245
246 tree
247 finish_member_template_decl (tree decl)
248 {
249   if (decl == error_mark_node)
250     return error_mark_node;
251
252   gcc_assert (DECL_P (decl));
253
254   if (TREE_CODE (decl) == TYPE_DECL)
255     {
256       tree type;
257
258       type = TREE_TYPE (decl);
259       if (type == error_mark_node)
260         return error_mark_node;
261       if (MAYBE_CLASS_TYPE_P (type)
262           && CLASSTYPE_TEMPLATE_INFO (type)
263           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
264         {
265           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
266           check_member_template (tmpl);
267           return tmpl;
268         }
269       return NULL_TREE;
270     }
271   else if (TREE_CODE (decl) == FIELD_DECL)
272     error ("data member %qD cannot be a member template", decl);
273   else if (DECL_TEMPLATE_INFO (decl))
274     {
275       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
276         {
277           check_member_template (DECL_TI_TEMPLATE (decl));
278           return DECL_TI_TEMPLATE (decl);
279         }
280       else
281         return decl;
282     }
283   else
284     error ("invalid member template declaration %qD", decl);
285
286   return error_mark_node;
287 }
288
289 /* Return the template info node corresponding to T, whatever T is.  */
290
291 tree
292 get_template_info (const_tree t)
293 {
294   tree tinfo = NULL_TREE;
295
296   if (!t || t == error_mark_node)
297     return NULL;
298
299   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
300     tinfo = DECL_TEMPLATE_INFO (t);
301
302   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
303     t = TREE_TYPE (t);
304
305   if (TAGGED_TYPE_P (t))
306     tinfo = TYPE_TEMPLATE_INFO (t);
307
308   return tinfo;
309 }
310
311 /* Returns the template nesting level of the indicated class TYPE.
312
313    For example, in:
314      template <class T>
315      struct A
316      {
317        template <class U>
318        struct B {};
319      };
320
321    A<T>::B<U> has depth two, while A<T> has depth one.
322    Both A<T>::B<int> and A<int>::B<U> have depth one, if
323    they are instantiations, not specializations.
324
325    This function is guaranteed to return 0 if passed NULL_TREE so
326    that, for example, `template_class_depth (current_class_type)' is
327    always safe.  */
328
329 int
330 template_class_depth (tree type)
331 {
332   int depth;
333
334   for (depth = 0;
335        type && TREE_CODE (type) != NAMESPACE_DECL;
336        type = (TREE_CODE (type) == FUNCTION_DECL)
337          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
338     {
339       tree tinfo = get_template_info (type);
340
341       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
342           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
343         ++depth;
344     }
345
346   return depth;
347 }
348
349 /* Subroutine of maybe_begin_member_template_processing.
350    Returns true if processing DECL needs us to push template parms.  */
351
352 static bool
353 inline_needs_template_parms (tree decl)
354 {
355   if (! DECL_TEMPLATE_INFO (decl))
356     return false;
357
358   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
359           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
360 }
361
362 /* Subroutine of maybe_begin_member_template_processing.
363    Push the template parms in PARMS, starting from LEVELS steps into the
364    chain, and ending at the beginning, since template parms are listed
365    innermost first.  */
366
367 static void
368 push_inline_template_parms_recursive (tree parmlist, int levels)
369 {
370   tree parms = TREE_VALUE (parmlist);
371   int i;
372
373   if (levels > 1)
374     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
375
376   ++processing_template_decl;
377   current_template_parms
378     = tree_cons (size_int (processing_template_decl),
379                  parms, current_template_parms);
380   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
381
382   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
383                NULL);
384   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
385     {
386       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
387
388       if (parm == error_mark_node)
389         continue;
390
391       gcc_assert (DECL_P (parm));
392
393       switch (TREE_CODE (parm))
394         {
395         case TYPE_DECL:
396         case TEMPLATE_DECL:
397           pushdecl (parm);
398           break;
399
400         case PARM_DECL:
401           {
402             /* Make a CONST_DECL as is done in process_template_parm.
403                It is ugly that we recreate this here; the original
404                version built in process_template_parm is no longer
405                available.  */
406             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
407                                     CONST_DECL, DECL_NAME (parm),
408                                     TREE_TYPE (parm));
409             DECL_ARTIFICIAL (decl) = 1;
410             TREE_CONSTANT (decl) = 1;
411             TREE_READONLY (decl) = 1;
412             DECL_INITIAL (decl) = DECL_INITIAL (parm);
413             SET_DECL_TEMPLATE_PARM_P (decl);
414             pushdecl (decl);
415           }
416           break;
417
418         default:
419           gcc_unreachable ();
420         }
421     }
422 }
423
424 /* Restore the template parameter context for a member template or
425    a friend template defined in a class definition.  */
426
427 void
428 maybe_begin_member_template_processing (tree decl)
429 {
430   tree parms;
431   int levels = 0;
432
433   if (inline_needs_template_parms (decl))
434     {
435       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
436       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
437
438       if (DECL_TEMPLATE_SPECIALIZATION (decl))
439         {
440           --levels;
441           parms = TREE_CHAIN (parms);
442         }
443
444       push_inline_template_parms_recursive (parms, levels);
445     }
446
447   /* Remember how many levels of template parameters we pushed so that
448      we can pop them later.  */
449   VEC_safe_push (int, heap, inline_parm_levels, levels);
450 }
451
452 /* Undo the effects of maybe_begin_member_template_processing.  */
453
454 void
455 maybe_end_member_template_processing (void)
456 {
457   int i;
458   int last;
459
460   if (VEC_length (int, inline_parm_levels) == 0)
461     return;
462
463   last = VEC_pop (int, inline_parm_levels);
464   for (i = 0; i < last; ++i)
465     {
466       --processing_template_decl;
467       current_template_parms = TREE_CHAIN (current_template_parms);
468       poplevel (0, 0, 0);
469     }
470 }
471
472 /* Return a new template argument vector which contains all of ARGS,
473    but has as its innermost set of arguments the EXTRA_ARGS.  */
474
475 static tree
476 add_to_template_args (tree args, tree extra_args)
477 {
478   tree new_args;
479   int extra_depth;
480   int i;
481   int j;
482
483   extra_depth = TMPL_ARGS_DEPTH (extra_args);
484   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
485
486   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
487     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
488
489   for (j = 1; j <= extra_depth; ++j, ++i)
490     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
491
492   return new_args;
493 }
494
495 /* Like add_to_template_args, but only the outermost ARGS are added to
496    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
497    (EXTRA_ARGS) levels are added.  This function is used to combine
498    the template arguments from a partial instantiation with the
499    template arguments used to attain the full instantiation from the
500    partial instantiation.  */
501
502 static tree
503 add_outermost_template_args (tree args, tree extra_args)
504 {
505   tree new_args;
506
507   /* If there are more levels of EXTRA_ARGS than there are ARGS,
508      something very fishy is going on.  */
509   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
510
511   /* If *all* the new arguments will be the EXTRA_ARGS, just return
512      them.  */
513   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
514     return extra_args;
515
516   /* For the moment, we make ARGS look like it contains fewer levels.  */
517   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
518
519   new_args = add_to_template_args (args, extra_args);
520
521   /* Now, we restore ARGS to its full dimensions.  */
522   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
523
524   return new_args;
525 }
526
527 /* Return the N levels of innermost template arguments from the ARGS.  */
528
529 tree
530 get_innermost_template_args (tree args, int n)
531 {
532   tree new_args;
533   int extra_levels;
534   int i;
535
536   gcc_assert (n >= 0);
537
538   /* If N is 1, just return the innermost set of template arguments.  */
539   if (n == 1)
540     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
541
542   /* If we're not removing anything, just return the arguments we were
543      given.  */
544   extra_levels = TMPL_ARGS_DEPTH (args) - n;
545   gcc_assert (extra_levels >= 0);
546   if (extra_levels == 0)
547     return args;
548
549   /* Make a new set of arguments, not containing the outer arguments.  */
550   new_args = make_tree_vec (n);
551   for (i = 1; i <= n; ++i)
552     SET_TMPL_ARGS_LEVEL (new_args, i,
553                          TMPL_ARGS_LEVEL (args, i + extra_levels));
554
555   return new_args;
556 }
557
558 /* The inverse of get_innermost_template_args: Return all but the innermost
559    EXTRA_LEVELS levels of template arguments from the ARGS.  */
560
561 static tree
562 strip_innermost_template_args (tree args, int extra_levels)
563 {
564   tree new_args;
565   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
566   int i;
567
568   gcc_assert (n >= 0);
569
570   /* If N is 1, just return the outermost set of template arguments.  */
571   if (n == 1)
572     return TMPL_ARGS_LEVEL (args, 1);
573
574   /* If we're not removing anything, just return the arguments we were
575      given.  */
576   gcc_assert (extra_levels >= 0);
577   if (extra_levels == 0)
578     return args;
579
580   /* Make a new set of arguments, not containing the inner arguments.  */
581   new_args = make_tree_vec (n);
582   for (i = 1; i <= n; ++i)
583     SET_TMPL_ARGS_LEVEL (new_args, i,
584                          TMPL_ARGS_LEVEL (args, i));
585
586   return new_args;
587 }
588
589 /* We've got a template header coming up; push to a new level for storing
590    the parms.  */
591
592 void
593 begin_template_parm_list (void)
594 {
595   /* We use a non-tag-transparent scope here, which causes pushtag to
596      put tags in this scope, rather than in the enclosing class or
597      namespace scope.  This is the right thing, since we want
598      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
599      global template class, push_template_decl handles putting the
600      TEMPLATE_DECL into top-level scope.  For a nested template class,
601      e.g.:
602
603        template <class T> struct S1 {
604          template <class T> struct S2 {};
605        };
606
607      pushtag contains special code to call pushdecl_with_scope on the
608      TEMPLATE_DECL for S2.  */
609   begin_scope (sk_template_parms, NULL);
610   ++processing_template_decl;
611   ++processing_template_parmlist;
612   note_template_header (0);
613 }
614
615 /* This routine is called when a specialization is declared.  If it is
616    invalid to declare a specialization here, an error is reported and
617    false is returned, otherwise this routine will return true.  */
618
619 static bool
620 check_specialization_scope (void)
621 {
622   tree scope = current_scope ();
623
624   /* [temp.expl.spec]
625
626      An explicit specialization shall be declared in the namespace of
627      which the template is a member, or, for member templates, in the
628      namespace of which the enclosing class or enclosing class
629      template is a member.  An explicit specialization of a member
630      function, member class or static data member of a class template
631      shall be declared in the namespace of which the class template
632      is a member.  */
633   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
634     {
635       error ("explicit specialization in non-namespace scope %qD", scope);
636       return false;
637     }
638
639   /* [temp.expl.spec]
640
641      In an explicit specialization declaration for a member of a class
642      template or a member template that appears in namespace scope,
643      the member template and some of its enclosing class templates may
644      remain unspecialized, except that the declaration shall not
645      explicitly specialize a class member template if its enclosing
646      class templates are not explicitly specialized as well.  */
647   if (current_template_parms)
648     {
649       error ("enclosing class templates are not explicitly specialized");
650       return false;
651     }
652
653   return true;
654 }
655
656 /* We've just seen template <>.  */
657
658 bool
659 begin_specialization (void)
660 {
661   begin_scope (sk_template_spec, NULL);
662   note_template_header (1);
663   return check_specialization_scope ();
664 }
665
666 /* Called at then end of processing a declaration preceded by
667    template<>.  */
668
669 void
670 end_specialization (void)
671 {
672   finish_scope ();
673   reset_specialization ();
674 }
675
676 /* Any template <>'s that we have seen thus far are not referring to a
677    function specialization.  */
678
679 void
680 reset_specialization (void)
681 {
682   processing_specialization = 0;
683   template_header_count = 0;
684 }
685
686 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
687    it was of the form template <>.  */
688
689 static void
690 note_template_header (int specialization)
691 {
692   processing_specialization = specialization;
693   template_header_count++;
694 }
695
696 /* We're beginning an explicit instantiation.  */
697
698 void
699 begin_explicit_instantiation (void)
700 {
701   gcc_assert (!processing_explicit_instantiation);
702   processing_explicit_instantiation = true;
703 }
704
705
706 void
707 end_explicit_instantiation (void)
708 {
709   gcc_assert (processing_explicit_instantiation);
710   processing_explicit_instantiation = false;
711 }
712
713 /* An explicit specialization or partial specialization TMPL is being
714    declared.  Check that the namespace in which the specialization is
715    occurring is permissible.  Returns false iff it is invalid to
716    specialize TMPL in the current namespace.  */
717
718 static bool
719 check_specialization_namespace (tree tmpl)
720 {
721   tree tpl_ns = decl_namespace_context (tmpl);
722
723   /* [tmpl.expl.spec]
724
725      An explicit specialization shall be declared in the namespace of
726      which the template is a member, or, for member templates, in the
727      namespace of which the enclosing class or enclosing class
728      template is a member.  An explicit specialization of a member
729      function, member class or static data member of a class template
730      shall be declared in the namespace of which the class template is
731      a member.  */
732   if (is_associated_namespace (current_namespace, tpl_ns))
733     /* Same or super-using namespace.  */
734     return true;
735   else
736     {
737       permerror (input_location, "specialization of %qD in different namespace", tmpl);
738       permerror (input_location, "  from definition of %q+#D", tmpl);
739       return false;
740     }
741 }
742
743 /* SPEC is an explicit instantiation.  Check that it is valid to
744    perform this explicit instantiation in the current namespace.  */
745
746 static void
747 check_explicit_instantiation_namespace (tree spec)
748 {
749   tree ns;
750
751   /* DR 275: An explicit instantiation shall appear in an enclosing
752      namespace of its template.  */
753   ns = decl_namespace_context (spec);
754   if (!is_ancestor (current_namespace, ns))
755     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
756                "(which does not enclose namespace %qD)",
757                spec, current_namespace, ns);
758 }
759
760 /* The TYPE is being declared.  If it is a template type, that means it
761    is a partial specialization.  Do appropriate error-checking.  */
762
763 tree
764 maybe_process_partial_specialization (tree type)
765 {
766   tree context;
767
768   if (type == error_mark_node)
769     return error_mark_node;
770
771   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
772     {
773       error ("name of class shadows template template parameter %qD",
774              TYPE_NAME (type));
775       return error_mark_node;
776     }
777
778   context = TYPE_CONTEXT (type);
779
780   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
781     {
782       /* This is for ordinary explicit specialization and partial
783          specialization of a template class such as:
784
785            template <> class C<int>;
786
787          or:
788
789            template <class T> class C<T*>;
790
791          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
792
793       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
794           && !COMPLETE_TYPE_P (type))
795         {
796           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
797           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
798           if (processing_template_decl)
799             {
800               if (push_template_decl (TYPE_MAIN_DECL (type))
801                   == error_mark_node)
802                 return error_mark_node;
803             }
804         }
805       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
806         error ("specialization of %qT after instantiation", type);
807     }
808   else if (CLASS_TYPE_P (type)
809            && !CLASSTYPE_USE_TEMPLATE (type)
810            && CLASSTYPE_TEMPLATE_INFO (type)
811            && context && CLASS_TYPE_P (context)
812            && CLASSTYPE_TEMPLATE_INFO (context))
813     {
814       /* This is for an explicit specialization of member class
815          template according to [temp.expl.spec/18]:
816
817            template <> template <class U> class C<int>::D;
818
819          The context `C<int>' must be an implicit instantiation.
820          Otherwise this is just a member class template declared
821          earlier like:
822
823            template <> class C<int> { template <class U> class D; };
824            template <> template <class U> class C<int>::D;
825
826          In the first case, `C<int>::D' is a specialization of `C<T>::D'
827          while in the second case, `C<int>::D' is a primary template
828          and `C<T>::D' may not exist.  */
829
830       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
831           && !COMPLETE_TYPE_P (type))
832         {
833           tree t;
834           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
835
836           if (current_namespace
837               != decl_namespace_context (tmpl))
838             {
839               permerror (input_location, "specializing %q#T in different namespace", type);
840               permerror (input_location, "  from definition of %q+#D", tmpl);
841             }
842
843           /* Check for invalid specialization after instantiation:
844
845                template <> template <> class C<int>::D<int>;
846                template <> template <class U> class C<int>::D;  */
847
848           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
849                t; t = TREE_CHAIN (t))
850             {
851               tree inst = TREE_VALUE (t);
852               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
853                 {
854                   /* We already have a full specialization of this partial
855                      instantiation.  Reassign it to the new member
856                      specialization template.  */
857                   spec_entry elt;
858                   spec_entry **slot;
859
860                   elt.tmpl = most_general_template (tmpl);
861                   elt.args = CLASSTYPE_TI_ARGS (inst);
862                   elt.spec = inst;
863
864                   htab_remove_elt (type_specializations, &elt);
865
866                   elt.tmpl = tmpl;
867                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
868
869                   slot = (spec_entry **)
870                     htab_find_slot (type_specializations, &elt, INSERT);
871                   *slot = GGC_NEW (spec_entry);
872                   **slot = elt;
873                 }
874               else if (COMPLETE_TYPE_P (inst) || TYPE_BEING_DEFINED (inst))
875                 /* But if we've had an implicit instantiation, that's a
876                    problem ([temp.expl.spec]/6).  */
877                 error ("specialization %qT after instantiation %qT",
878                        type, inst);
879             }
880
881           /* Mark TYPE as a specialization.  And as a result, we only
882              have one level of template argument for the innermost
883              class template.  */
884           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
885           CLASSTYPE_TI_ARGS (type)
886             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
887         }
888     }
889   else if (processing_specialization)
890     {
891       error ("explicit specialization of non-template %qT", type);
892       return error_mark_node;
893     }
894
895   return type;
896 }
897
898 /* Returns nonzero if we can optimize the retrieval of specializations
899    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
900    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
901
902 static inline bool
903 optimize_specialization_lookup_p (tree tmpl)
904 {
905   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
906           && DECL_CLASS_SCOPE_P (tmpl)
907           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
908              parameter.  */
909           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
910           /* The optimized lookup depends on the fact that the
911              template arguments for the member function template apply
912              purely to the containing class, which is not true if the
913              containing class is an explicit or partial
914              specialization.  */
915           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
916           && !DECL_MEMBER_TEMPLATE_P (tmpl)
917           && !DECL_CONV_FN_P (tmpl)
918           /* It is possible to have a template that is not a member
919              template and is not a member of a template class:
920
921              template <typename T>
922              struct S { friend A::f(); };
923
924              Here, the friend function is a template, but the context does
925              not have template information.  The optimized lookup relies
926              on having ARGS be the template arguments for both the class
927              and the function template.  */
928           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
929 }
930
931 /* Retrieve the specialization (in the sense of [temp.spec] - a
932    specialization is either an instantiation or an explicit
933    specialization) of TMPL for the given template ARGS.  If there is
934    no such specialization, return NULL_TREE.  The ARGS are a vector of
935    arguments, or a vector of vectors of arguments, in the case of
936    templates with more than one level of parameters.
937
938    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
939    then we search for a partial specialization matching ARGS.  This
940    parameter is ignored if TMPL is not a class template.  */
941
942 static tree
943 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
944 {
945   if (args == error_mark_node)
946     return NULL_TREE;
947
948   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
949
950   /* There should be as many levels of arguments as there are
951      levels of parameters.  */
952   gcc_assert (TMPL_ARGS_DEPTH (args)
953               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
954
955   if (optimize_specialization_lookup_p (tmpl))
956     {
957       tree class_template;
958       tree class_specialization;
959       VEC(tree,gc) *methods;
960       tree fns;
961       int idx;
962
963       /* The template arguments actually apply to the containing
964          class.  Find the class specialization with those
965          arguments.  */
966       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
967       class_specialization
968         = retrieve_specialization (class_template, args, 0);
969       if (!class_specialization)
970         return NULL_TREE;
971       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
972          for the specialization.  */
973       idx = class_method_index_for_fn (class_specialization, tmpl);
974       if (idx == -1)
975         return NULL_TREE;
976       /* Iterate through the methods with the indicated name, looking
977          for the one that has an instance of TMPL.  */
978       methods = CLASSTYPE_METHOD_VEC (class_specialization);
979       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
980         {
981           tree fn = OVL_CURRENT (fns);
982           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
983               /* using-declarations can add base methods to the method vec,
984                  and we don't want those here.  */
985               && DECL_CONTEXT (fn) == class_specialization)
986             return fn;
987         }
988       return NULL_TREE;
989     }
990   else
991     {
992       spec_entry *found;
993       spec_entry elt;
994       htab_t specializations;
995
996       elt.tmpl = tmpl;
997       elt.args = args;
998       elt.spec = NULL_TREE;
999
1000       if (DECL_CLASS_TEMPLATE_P (tmpl))
1001         specializations = type_specializations;
1002       else
1003         specializations = decl_specializations;
1004
1005       if (hash == 0)
1006         hash = hash_specialization (&elt);
1007       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1008       if (found)
1009         return found->spec;
1010     }
1011
1012   return NULL_TREE;
1013 }
1014
1015 /* Like retrieve_specialization, but for local declarations.  */
1016
1017 static tree
1018 retrieve_local_specialization (tree tmpl)
1019 {
1020   tree spec;
1021
1022   if (local_specializations == NULL)
1023     return NULL_TREE;
1024
1025   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1026                                      htab_hash_pointer (tmpl));
1027   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1028 }
1029
1030 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1031
1032 int
1033 is_specialization_of (tree decl, tree tmpl)
1034 {
1035   tree t;
1036
1037   if (TREE_CODE (decl) == FUNCTION_DECL)
1038     {
1039       for (t = decl;
1040            t != NULL_TREE;
1041            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1042         if (t == tmpl)
1043           return 1;
1044     }
1045   else
1046     {
1047       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1048
1049       for (t = TREE_TYPE (decl);
1050            t != NULL_TREE;
1051            t = CLASSTYPE_USE_TEMPLATE (t)
1052              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1053         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1054           return 1;
1055     }
1056
1057   return 0;
1058 }
1059
1060 /* Returns nonzero iff DECL is a specialization of friend declaration
1061    FRIEND_DECL according to [temp.friend].  */
1062
1063 bool
1064 is_specialization_of_friend (tree decl, tree friend_decl)
1065 {
1066   bool need_template = true;
1067   int template_depth;
1068
1069   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1070               || TREE_CODE (decl) == TYPE_DECL);
1071
1072   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1073      of a template class, we want to check if DECL is a specialization
1074      if this.  */
1075   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1076       && DECL_TEMPLATE_INFO (friend_decl)
1077       && !DECL_USE_TEMPLATE (friend_decl))
1078     {
1079       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1080       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1081       need_template = false;
1082     }
1083   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1084            && !PRIMARY_TEMPLATE_P (friend_decl))
1085     need_template = false;
1086
1087   /* There is nothing to do if this is not a template friend.  */
1088   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1089     return false;
1090
1091   if (is_specialization_of (decl, friend_decl))
1092     return true;
1093
1094   /* [temp.friend/6]
1095      A member of a class template may be declared to be a friend of a
1096      non-template class.  In this case, the corresponding member of
1097      every specialization of the class template is a friend of the
1098      class granting friendship.
1099
1100      For example, given a template friend declaration
1101
1102        template <class T> friend void A<T>::f();
1103
1104      the member function below is considered a friend
1105
1106        template <> struct A<int> {
1107          void f();
1108        };
1109
1110      For this type of template friend, TEMPLATE_DEPTH below will be
1111      nonzero.  To determine if DECL is a friend of FRIEND, we first
1112      check if the enclosing class is a specialization of another.  */
1113
1114   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1115   if (template_depth
1116       && DECL_CLASS_SCOPE_P (decl)
1117       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1118                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1119     {
1120       /* Next, we check the members themselves.  In order to handle
1121          a few tricky cases, such as when FRIEND_DECL's are
1122
1123            template <class T> friend void A<T>::g(T t);
1124            template <class T> template <T t> friend void A<T>::h();
1125
1126          and DECL's are
1127
1128            void A<int>::g(int);
1129            template <int> void A<int>::h();
1130
1131          we need to figure out ARGS, the template arguments from
1132          the context of DECL.  This is required for template substitution
1133          of `T' in the function parameter of `g' and template parameter
1134          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1135
1136       tree context = DECL_CONTEXT (decl);
1137       tree args = NULL_TREE;
1138       int current_depth = 0;
1139
1140       while (current_depth < template_depth)
1141         {
1142           if (CLASSTYPE_TEMPLATE_INFO (context))
1143             {
1144               if (current_depth == 0)
1145                 args = TYPE_TI_ARGS (context);
1146               else
1147                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1148               current_depth++;
1149             }
1150           context = TYPE_CONTEXT (context);
1151         }
1152
1153       if (TREE_CODE (decl) == FUNCTION_DECL)
1154         {
1155           bool is_template;
1156           tree friend_type;
1157           tree decl_type;
1158           tree friend_args_type;
1159           tree decl_args_type;
1160
1161           /* Make sure that both DECL and FRIEND_DECL are templates or
1162              non-templates.  */
1163           is_template = DECL_TEMPLATE_INFO (decl)
1164                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1165           if (need_template ^ is_template)
1166             return false;
1167           else if (is_template)
1168             {
1169               /* If both are templates, check template parameter list.  */
1170               tree friend_parms
1171                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1172                                          args, tf_none);
1173               if (!comp_template_parms
1174                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1175                       friend_parms))
1176                 return false;
1177
1178               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1179             }
1180           else
1181             decl_type = TREE_TYPE (decl);
1182
1183           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1184                                               tf_none, NULL_TREE);
1185           if (friend_type == error_mark_node)
1186             return false;
1187
1188           /* Check if return types match.  */
1189           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1190             return false;
1191
1192           /* Check if function parameter types match, ignoring the
1193              `this' parameter.  */
1194           friend_args_type = TYPE_ARG_TYPES (friend_type);
1195           decl_args_type = TYPE_ARG_TYPES (decl_type);
1196           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1197             friend_args_type = TREE_CHAIN (friend_args_type);
1198           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1199             decl_args_type = TREE_CHAIN (decl_args_type);
1200
1201           return compparms (decl_args_type, friend_args_type);
1202         }
1203       else
1204         {
1205           /* DECL is a TYPE_DECL */
1206           bool is_template;
1207           tree decl_type = TREE_TYPE (decl);
1208
1209           /* Make sure that both DECL and FRIEND_DECL are templates or
1210              non-templates.  */
1211           is_template
1212             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1213               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1214
1215           if (need_template ^ is_template)
1216             return false;
1217           else if (is_template)
1218             {
1219               tree friend_parms;
1220               /* If both are templates, check the name of the two
1221                  TEMPLATE_DECL's first because is_friend didn't.  */
1222               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1223                   != DECL_NAME (friend_decl))
1224                 return false;
1225
1226               /* Now check template parameter list.  */
1227               friend_parms
1228                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1229                                          args, tf_none);
1230               return comp_template_parms
1231                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1232                  friend_parms);
1233             }
1234           else
1235             return (DECL_NAME (decl)
1236                     == DECL_NAME (friend_decl));
1237         }
1238     }
1239   return false;
1240 }
1241
1242 /* Register the specialization SPEC as a specialization of TMPL with
1243    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1244    is actually just a friend declaration.  Returns SPEC, or an
1245    equivalent prior declaration, if available.  */
1246
1247 static tree
1248 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1249                          hashval_t hash)
1250 {
1251   tree fn;
1252   spec_entry **slot = NULL;
1253   spec_entry elt;
1254
1255   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1256
1257   if (TREE_CODE (spec) == FUNCTION_DECL
1258       && uses_template_parms (DECL_TI_ARGS (spec)))
1259     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1260        register it; we want the corresponding TEMPLATE_DECL instead.
1261        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1262        the more obvious `uses_template_parms (spec)' to avoid problems
1263        with default function arguments.  In particular, given
1264        something like this:
1265
1266           template <class T> void f(T t1, T t = T())
1267
1268        the default argument expression is not substituted for in an
1269        instantiation unless and until it is actually needed.  */
1270     return spec;
1271
1272   if (optimize_specialization_lookup_p (tmpl))
1273     /* We don't put these specializations in the hash table, but we might
1274        want to give an error about a mismatch.  */
1275     fn = retrieve_specialization (tmpl, args, 0);
1276   else
1277     {
1278       elt.tmpl = tmpl;
1279       elt.args = args;
1280       elt.spec = spec;
1281
1282       if (hash == 0)
1283         hash = hash_specialization (&elt);
1284
1285       slot = (spec_entry **)
1286         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1287       if (*slot)
1288         fn = (*slot)->spec;
1289       else
1290         fn = NULL_TREE;
1291     }
1292
1293   /* We can sometimes try to re-register a specialization that we've
1294      already got.  In particular, regenerate_decl_from_template calls
1295      duplicate_decls which will update the specialization list.  But,
1296      we'll still get called again here anyhow.  It's more convenient
1297      to simply allow this than to try to prevent it.  */
1298   if (fn == spec)
1299     return spec;
1300   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1301     {
1302       if (DECL_TEMPLATE_INSTANTIATION (fn))
1303         {
1304           if (DECL_ODR_USED (fn)
1305               || DECL_EXPLICIT_INSTANTIATION (fn))
1306             {
1307               error ("specialization of %qD after instantiation",
1308                      fn);
1309               return error_mark_node;
1310             }
1311           else
1312             {
1313               tree clone;
1314               /* This situation should occur only if the first
1315                  specialization is an implicit instantiation, the
1316                  second is an explicit specialization, and the
1317                  implicit instantiation has not yet been used.  That
1318                  situation can occur if we have implicitly
1319                  instantiated a member function and then specialized
1320                  it later.
1321
1322                  We can also wind up here if a friend declaration that
1323                  looked like an instantiation turns out to be a
1324                  specialization:
1325
1326                    template <class T> void foo(T);
1327                    class S { friend void foo<>(int) };
1328                    template <> void foo(int);
1329
1330                  We transform the existing DECL in place so that any
1331                  pointers to it become pointers to the updated
1332                  declaration.
1333
1334                  If there was a definition for the template, but not
1335                  for the specialization, we want this to look as if
1336                  there were no definition, and vice versa.  */
1337               DECL_INITIAL (fn) = NULL_TREE;
1338               duplicate_decls (spec, fn, is_friend);
1339               /* The call to duplicate_decls will have applied
1340                  [temp.expl.spec]:
1341
1342                    An explicit specialization of a function template
1343                    is inline only if it is explicitly declared to be,
1344                    and independently of whether its function template
1345                    is.
1346
1347                 to the primary function; now copy the inline bits to
1348                 the various clones.  */
1349               FOR_EACH_CLONE (clone, fn)
1350                 {
1351                   DECL_DECLARED_INLINE_P (clone)
1352                     = DECL_DECLARED_INLINE_P (fn);
1353                   DECL_SOURCE_LOCATION (clone)
1354                     = DECL_SOURCE_LOCATION (fn);
1355                 }
1356               check_specialization_namespace (fn);
1357
1358               return fn;
1359             }
1360         }
1361       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1362         {
1363           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1364             /* Dup decl failed, but this is a new definition. Set the
1365                line number so any errors match this new
1366                definition.  */
1367             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1368
1369           return fn;
1370         }
1371     }
1372   else if (fn)
1373     return duplicate_decls (spec, fn, is_friend);
1374
1375   /* A specialization must be declared in the same namespace as the
1376      template it is specializing.  */
1377   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1378       && !check_specialization_namespace (tmpl))
1379     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1380
1381   if (!optimize_specialization_lookup_p (tmpl))
1382     {
1383       gcc_assert (tmpl && args && spec);
1384       *slot = GGC_NEW (spec_entry);
1385       **slot = elt;
1386       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1387           && PRIMARY_TEMPLATE_P (tmpl)
1388           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1389         /* TMPL is a forward declaration of a template function; keep a list
1390            of all specializations in case we need to reassign them to a friend
1391            template later in tsubst_friend_function.  */
1392         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1393           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1394     }
1395
1396   return spec;
1397 }
1398
1399 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1400    TMPL and ARGS members, ignores SPEC.  */
1401
1402 static int
1403 eq_specializations (const void *p1, const void *p2)
1404 {
1405   const spec_entry *e1 = (const spec_entry *)p1;
1406   const spec_entry *e2 = (const spec_entry *)p2;
1407
1408   return (e1->tmpl == e2->tmpl
1409           && comp_template_args (e1->args, e2->args));
1410 }
1411
1412 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1413
1414 static hashval_t
1415 hash_tmpl_and_args (tree tmpl, tree args)
1416 {
1417   hashval_t val = DECL_UID (tmpl);
1418   return iterative_hash_template_arg (args, val);
1419 }
1420
1421 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1422    ignoring SPEC.  */
1423
1424 static hashval_t
1425 hash_specialization (const void *p)
1426 {
1427   const spec_entry *e = (const spec_entry *)p;
1428   return hash_tmpl_and_args (e->tmpl, e->args);
1429 }
1430
1431 /* Recursively calculate a hash value for a template argument ARG, for use
1432    in the hash tables of template specializations.  */
1433
1434 static hashval_t
1435 iterative_hash_template_arg (tree arg, hashval_t val)
1436 {
1437   unsigned HOST_WIDE_INT i;
1438   enum tree_code code;
1439   char tclass;
1440
1441   if (arg == NULL_TREE)
1442     return iterative_hash_object (arg, val);
1443
1444   if (!TYPE_P (arg))
1445     STRIP_NOPS (arg);
1446
1447   code = TREE_CODE (arg);
1448   tclass = TREE_CODE_CLASS (code);
1449
1450   val = iterative_hash_object (code, val);
1451
1452   switch (code)
1453     {
1454     case ERROR_MARK:
1455       return val;
1456
1457     case IDENTIFIER_NODE:
1458       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1459
1460     case TREE_VEC:
1461       {
1462         int i, len = TREE_VEC_LENGTH (arg);
1463         for (i = 0; i < len; ++i)
1464           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1465         return val;
1466       }
1467
1468     case TYPE_PACK_EXPANSION:
1469     case EXPR_PACK_EXPANSION:
1470       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1471
1472     case ARGUMENT_PACK_SELECT:
1473       /* We can get one of these when re-hashing a previous entry in the middle
1474          of substituting into a pack expansion.  Just look through it...  */
1475       arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1476       /* ...and fall through.  */
1477     case TYPE_ARGUMENT_PACK:
1478     case NONTYPE_ARGUMENT_PACK:
1479       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1480
1481     case TREE_LIST:
1482       for (; arg; arg = TREE_CHAIN (arg))
1483         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1484       return val;
1485
1486     case OVERLOAD:
1487       for (; arg; arg = OVL_CHAIN (arg))
1488         val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1489       return val;
1490
1491     case CONSTRUCTOR:
1492       {
1493         tree field, value;
1494         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1495           {
1496             val = iterative_hash_template_arg (field, val);
1497             val = iterative_hash_template_arg (value, val);
1498           }
1499         return val;
1500       }
1501
1502     case PARM_DECL:
1503       if (!DECL_ARTIFICIAL (arg))
1504         val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1505       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1506
1507     case TARGET_EXPR:
1508       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1509
1510     case PTRMEM_CST:
1511       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1512       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1513
1514     case TEMPLATE_PARM_INDEX:
1515       val = iterative_hash_template_arg
1516         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1517       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1518       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1519
1520     case TRAIT_EXPR:
1521       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1522       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1523       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1524
1525     case BASELINK:
1526       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1527                                          val);
1528       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1529                                           val);
1530
1531     case MODOP_EXPR:
1532       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1533       code = TREE_CODE (TREE_OPERAND (arg, 1));
1534       val = iterative_hash_object (code, val);
1535       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1536
1537     default:
1538       switch (tclass)
1539         {
1540         case tcc_type:
1541           if (TYPE_CANONICAL (arg))
1542             return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1543                                           val);
1544           else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1545             return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1546           /* Otherwise just compare the types during lookup.  */
1547           return val;
1548
1549         case tcc_declaration:
1550         case tcc_constant:
1551           return iterative_hash_expr (arg, val);
1552
1553         default:
1554           gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1555           {
1556             unsigned n = TREE_OPERAND_LENGTH (arg);
1557             for (i = 0; i < n; ++i)
1558               val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1559             return val;
1560           }
1561         }
1562     }
1563   gcc_unreachable ();
1564   return 0;
1565 }
1566
1567 /* Unregister the specialization SPEC as a specialization of TMPL.
1568    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1569    if the SPEC was listed as a specialization of TMPL.
1570
1571    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1572
1573 bool
1574 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1575 {
1576   spec_entry **slot;
1577   spec_entry elt;
1578
1579   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1580   elt.args = TI_ARGS (tinfo);
1581   elt.spec = NULL_TREE;
1582
1583   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1584   if (*slot)
1585     {
1586       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1587       gcc_assert (new_spec != NULL_TREE);
1588       (*slot)->spec = new_spec;
1589       return 1;
1590     }
1591
1592   return 0;
1593 }
1594
1595 /* Compare an entry in the local specializations hash table P1 (which
1596    is really a pointer to a TREE_LIST) with P2 (which is really a
1597    DECL).  */
1598
1599 static int
1600 eq_local_specializations (const void *p1, const void *p2)
1601 {
1602   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1603 }
1604
1605 /* Hash P1, an entry in the local specializations table.  */
1606
1607 static hashval_t
1608 hash_local_specialization (const void* p1)
1609 {
1610   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1611 }
1612
1613 /* Like register_specialization, but for local declarations.  We are
1614    registering SPEC, an instantiation of TMPL.  */
1615
1616 static void
1617 register_local_specialization (tree spec, tree tmpl)
1618 {
1619   void **slot;
1620
1621   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1622                                    htab_hash_pointer (tmpl), INSERT);
1623   *slot = build_tree_list (spec, tmpl);
1624 }
1625
1626 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1627    specialized class.  */
1628
1629 bool
1630 explicit_class_specialization_p (tree type)
1631 {
1632   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1633     return false;
1634   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1635 }
1636
1637 /* Print the list of candidate FNS in an error message.  */
1638
1639 void
1640 print_candidates (tree fns)
1641 {
1642   tree fn;
1643   tree f;
1644
1645   const char *str = "candidates are:";
1646
1647   if (is_overloaded_fn (fns))
1648     {
1649       for (f = fns; f; f = OVL_NEXT (f))
1650         {
1651           error ("%s %+#D", str, OVL_CURRENT (f));
1652           str = "               ";
1653         }
1654     }
1655   else for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1656     {
1657       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1658         error ("%s %+#D", str, OVL_CURRENT (f));
1659       str = "               ";
1660     }
1661 }
1662
1663 /* Returns the template (one of the functions given by TEMPLATE_ID)
1664    which can be specialized to match the indicated DECL with the
1665    explicit template args given in TEMPLATE_ID.  The DECL may be
1666    NULL_TREE if none is available.  In that case, the functions in
1667    TEMPLATE_ID are non-members.
1668
1669    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1670    specialization of a member template.
1671
1672    The TEMPLATE_COUNT is the number of references to qualifying
1673    template classes that appeared in the name of the function. See
1674    check_explicit_specialization for a more accurate description.
1675
1676    TSK indicates what kind of template declaration (if any) is being
1677    declared.  TSK_TEMPLATE indicates that the declaration given by
1678    DECL, though a FUNCTION_DECL, has template parameters, and is
1679    therefore a template function.
1680
1681    The template args (those explicitly specified and those deduced)
1682    are output in a newly created vector *TARGS_OUT.
1683
1684    If it is impossible to determine the result, an error message is
1685    issued.  The error_mark_node is returned to indicate failure.  */
1686
1687 static tree
1688 determine_specialization (tree template_id,
1689                           tree decl,
1690                           tree* targs_out,
1691                           int need_member_template,
1692                           int template_count,
1693                           tmpl_spec_kind tsk)
1694 {
1695   tree fns;
1696   tree targs;
1697   tree explicit_targs;
1698   tree candidates = NULL_TREE;
1699   /* A TREE_LIST of templates of which DECL may be a specialization.
1700      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1701      corresponding TREE_PURPOSE is the set of template arguments that,
1702      when used to instantiate the template, would produce a function
1703      with the signature of DECL.  */
1704   tree templates = NULL_TREE;
1705   int header_count;
1706   struct cp_binding_level *b;
1707
1708   *targs_out = NULL_TREE;
1709
1710   if (template_id == error_mark_node || decl == error_mark_node)
1711     return error_mark_node;
1712
1713   fns = TREE_OPERAND (template_id, 0);
1714   explicit_targs = TREE_OPERAND (template_id, 1);
1715
1716   if (fns == error_mark_node)
1717     return error_mark_node;
1718
1719   /* Check for baselinks.  */
1720   if (BASELINK_P (fns))
1721     fns = BASELINK_FUNCTIONS (fns);
1722
1723   if (!is_overloaded_fn (fns))
1724     {
1725       error ("%qD is not a function template", fns);
1726       return error_mark_node;
1727     }
1728
1729   /* Count the number of template headers specified for this
1730      specialization.  */
1731   header_count = 0;
1732   for (b = current_binding_level;
1733        b->kind == sk_template_parms;
1734        b = b->level_chain)
1735     ++header_count;
1736
1737   for (; fns; fns = OVL_NEXT (fns))
1738     {
1739       tree fn = OVL_CURRENT (fns);
1740
1741       if (TREE_CODE (fn) == TEMPLATE_DECL)
1742         {
1743           tree decl_arg_types;
1744           tree fn_arg_types;
1745
1746           /* In case of explicit specialization, we need to check if
1747              the number of template headers appearing in the specialization
1748              is correct. This is usually done in check_explicit_specialization,
1749              but the check done there cannot be exhaustive when specializing
1750              member functions. Consider the following code:
1751
1752              template <> void A<int>::f(int);
1753              template <> template <> void A<int>::f(int);
1754
1755              Assuming that A<int> is not itself an explicit specialization
1756              already, the first line specializes "f" which is a non-template
1757              member function, whilst the second line specializes "f" which
1758              is a template member function. So both lines are syntactically
1759              correct, and check_explicit_specialization does not reject
1760              them.
1761
1762              Here, we can do better, as we are matching the specialization
1763              against the declarations. We count the number of template
1764              headers, and we check if they match TEMPLATE_COUNT + 1
1765              (TEMPLATE_COUNT is the number of qualifying template classes,
1766              plus there must be another header for the member template
1767              itself).
1768
1769              Notice that if header_count is zero, this is not a
1770              specialization but rather a template instantiation, so there
1771              is no check we can perform here.  */
1772           if (header_count && header_count != template_count + 1)
1773             continue;
1774
1775           /* Check that the number of template arguments at the
1776              innermost level for DECL is the same as for FN.  */
1777           if (current_binding_level->kind == sk_template_parms
1778               && !current_binding_level->explicit_spec_p
1779               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1780                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1781                                       (current_template_parms))))
1782             continue;
1783
1784           /* DECL might be a specialization of FN.  */
1785           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1786           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1787
1788           /* For a non-static member function, we need to make sure
1789              that the const qualification is the same.  Since
1790              get_bindings does not try to merge the "this" parameter,
1791              we must do the comparison explicitly.  */
1792           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1793               && !same_type_p (TREE_VALUE (fn_arg_types),
1794                                TREE_VALUE (decl_arg_types)))
1795             continue;
1796
1797           /* Skip the "this" parameter and, for constructors of
1798              classes with virtual bases, the VTT parameter.  A
1799              full specialization of a constructor will have a VTT
1800              parameter, but a template never will.  */ 
1801           decl_arg_types 
1802             = skip_artificial_parms_for (decl, decl_arg_types);
1803           fn_arg_types 
1804             = skip_artificial_parms_for (fn, fn_arg_types);
1805
1806           /* Check that the number of function parameters matches.
1807              For example,
1808                template <class T> void f(int i = 0);
1809                template <> void f<int>();
1810              The specialization f<int> is invalid but is not caught
1811              by get_bindings below.  */
1812           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1813             continue;
1814
1815           /* Function templates cannot be specializations; there are
1816              no partial specializations of functions.  Therefore, if
1817              the type of DECL does not match FN, there is no
1818              match.  */
1819           if (tsk == tsk_template)
1820             {
1821               if (compparms (fn_arg_types, decl_arg_types))
1822                 candidates = tree_cons (NULL_TREE, fn, candidates);
1823               continue;
1824             }
1825
1826           /* See whether this function might be a specialization of this
1827              template.  */
1828           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1829
1830           if (!targs)
1831             /* We cannot deduce template arguments that when used to
1832                specialize TMPL will produce DECL.  */
1833             continue;
1834
1835           /* Save this template, and the arguments deduced.  */
1836           templates = tree_cons (targs, fn, templates);
1837         }
1838       else if (need_member_template)
1839         /* FN is an ordinary member function, and we need a
1840            specialization of a member template.  */
1841         ;
1842       else if (TREE_CODE (fn) != FUNCTION_DECL)
1843         /* We can get IDENTIFIER_NODEs here in certain erroneous
1844            cases.  */
1845         ;
1846       else if (!DECL_FUNCTION_MEMBER_P (fn))
1847         /* This is just an ordinary non-member function.  Nothing can
1848            be a specialization of that.  */
1849         ;
1850       else if (DECL_ARTIFICIAL (fn))
1851         /* Cannot specialize functions that are created implicitly.  */
1852         ;
1853       else
1854         {
1855           tree decl_arg_types;
1856
1857           /* This is an ordinary member function.  However, since
1858              we're here, we can assume it's enclosing class is a
1859              template class.  For example,
1860
1861                template <typename T> struct S { void f(); };
1862                template <> void S<int>::f() {}
1863
1864              Here, S<int>::f is a non-template, but S<int> is a
1865              template class.  If FN has the same type as DECL, we
1866              might be in business.  */
1867
1868           if (!DECL_TEMPLATE_INFO (fn))
1869             /* Its enclosing class is an explicit specialization
1870                of a template class.  This is not a candidate.  */
1871             continue;
1872
1873           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1874                             TREE_TYPE (TREE_TYPE (fn))))
1875             /* The return types differ.  */
1876             continue;
1877
1878           /* Adjust the type of DECL in case FN is a static member.  */
1879           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1880           if (DECL_STATIC_FUNCTION_P (fn)
1881               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1882             decl_arg_types = TREE_CHAIN (decl_arg_types);
1883
1884           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1885                          decl_arg_types))
1886             /* They match!  */
1887             candidates = tree_cons (NULL_TREE, fn, candidates);
1888         }
1889     }
1890
1891   if (templates && TREE_CHAIN (templates))
1892     {
1893       /* We have:
1894
1895            [temp.expl.spec]
1896
1897            It is possible for a specialization with a given function
1898            signature to be instantiated from more than one function
1899            template.  In such cases, explicit specification of the
1900            template arguments must be used to uniquely identify the
1901            function template specialization being specialized.
1902
1903          Note that here, there's no suggestion that we're supposed to
1904          determine which of the candidate templates is most
1905          specialized.  However, we, also have:
1906
1907            [temp.func.order]
1908
1909            Partial ordering of overloaded function template
1910            declarations is used in the following contexts to select
1911            the function template to which a function template
1912            specialization refers:
1913
1914            -- when an explicit specialization refers to a function
1915               template.
1916
1917          So, we do use the partial ordering rules, at least for now.
1918          This extension can only serve to make invalid programs valid,
1919          so it's safe.  And, there is strong anecdotal evidence that
1920          the committee intended the partial ordering rules to apply;
1921          the EDG front end has that behavior, and John Spicer claims
1922          that the committee simply forgot to delete the wording in
1923          [temp.expl.spec].  */
1924       tree tmpl = most_specialized_instantiation (templates);
1925       if (tmpl != error_mark_node)
1926         {
1927           templates = tmpl;
1928           TREE_CHAIN (templates) = NULL_TREE;
1929         }
1930     }
1931
1932   if (templates == NULL_TREE && candidates == NULL_TREE)
1933     {
1934       error ("template-id %qD for %q+D does not match any template "
1935              "declaration", template_id, decl);
1936       return error_mark_node;
1937     }
1938   else if ((templates && TREE_CHAIN (templates))
1939            || (candidates && TREE_CHAIN (candidates))
1940            || (templates && candidates))
1941     {
1942       error ("ambiguous template specialization %qD for %q+D",
1943              template_id, decl);
1944       chainon (candidates, templates);
1945       print_candidates (candidates);
1946       return error_mark_node;
1947     }
1948
1949   /* We have one, and exactly one, match.  */
1950   if (candidates)
1951     {
1952       tree fn = TREE_VALUE (candidates);
1953       *targs_out = copy_node (DECL_TI_ARGS (fn));
1954       /* DECL is a re-declaration or partial instantiation of a template
1955          function.  */
1956       if (TREE_CODE (fn) == TEMPLATE_DECL)
1957         return fn;
1958       /* It was a specialization of an ordinary member function in a
1959          template class.  */
1960       return DECL_TI_TEMPLATE (fn);
1961     }
1962
1963   /* It was a specialization of a template.  */
1964   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1965   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1966     {
1967       *targs_out = copy_node (targs);
1968       SET_TMPL_ARGS_LEVEL (*targs_out,
1969                            TMPL_ARGS_DEPTH (*targs_out),
1970                            TREE_PURPOSE (templates));
1971     }
1972   else
1973     *targs_out = TREE_PURPOSE (templates);
1974   return TREE_VALUE (templates);
1975 }
1976
1977 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1978    but with the default argument values filled in from those in the
1979    TMPL_TYPES.  */
1980
1981 static tree
1982 copy_default_args_to_explicit_spec_1 (tree spec_types,
1983                                       tree tmpl_types)
1984 {
1985   tree new_spec_types;
1986
1987   if (!spec_types)
1988     return NULL_TREE;
1989
1990   if (spec_types == void_list_node)
1991     return void_list_node;
1992
1993   /* Substitute into the rest of the list.  */
1994   new_spec_types =
1995     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1996                                           TREE_CHAIN (tmpl_types));
1997
1998   /* Add the default argument for this parameter.  */
1999   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2000                          TREE_VALUE (spec_types),
2001                          new_spec_types);
2002 }
2003
2004 /* DECL is an explicit specialization.  Replicate default arguments
2005    from the template it specializes.  (That way, code like:
2006
2007      template <class T> void f(T = 3);
2008      template <> void f(double);
2009      void g () { f (); }
2010
2011    works, as required.)  An alternative approach would be to look up
2012    the correct default arguments at the call-site, but this approach
2013    is consistent with how implicit instantiations are handled.  */
2014
2015 static void
2016 copy_default_args_to_explicit_spec (tree decl)
2017 {
2018   tree tmpl;
2019   tree spec_types;
2020   tree tmpl_types;
2021   tree new_spec_types;
2022   tree old_type;
2023   tree new_type;
2024   tree t;
2025   tree object_type = NULL_TREE;
2026   tree in_charge = NULL_TREE;
2027   tree vtt = NULL_TREE;
2028
2029   /* See if there's anything we need to do.  */
2030   tmpl = DECL_TI_TEMPLATE (decl);
2031   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2032   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2033     if (TREE_PURPOSE (t))
2034       break;
2035   if (!t)
2036     return;
2037
2038   old_type = TREE_TYPE (decl);
2039   spec_types = TYPE_ARG_TYPES (old_type);
2040
2041   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2042     {
2043       /* Remove the this pointer, but remember the object's type for
2044          CV quals.  */
2045       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2046       spec_types = TREE_CHAIN (spec_types);
2047       tmpl_types = TREE_CHAIN (tmpl_types);
2048
2049       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2050         {
2051           /* DECL may contain more parameters than TMPL due to the extra
2052              in-charge parameter in constructors and destructors.  */
2053           in_charge = spec_types;
2054           spec_types = TREE_CHAIN (spec_types);
2055         }
2056       if (DECL_HAS_VTT_PARM_P (decl))
2057         {
2058           vtt = spec_types;
2059           spec_types = TREE_CHAIN (spec_types);
2060         }
2061     }
2062
2063   /* Compute the merged default arguments.  */
2064   new_spec_types =
2065     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2066
2067   /* Compute the new FUNCTION_TYPE.  */
2068   if (object_type)
2069     {
2070       if (vtt)
2071         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2072                                          TREE_VALUE (vtt),
2073                                          new_spec_types);
2074
2075       if (in_charge)
2076         /* Put the in-charge parameter back.  */
2077         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2078                                          TREE_VALUE (in_charge),
2079                                          new_spec_types);
2080
2081       new_type = build_method_type_directly (object_type,
2082                                              TREE_TYPE (old_type),
2083                                              new_spec_types);
2084     }
2085   else
2086     new_type = build_function_type (TREE_TYPE (old_type),
2087                                     new_spec_types);
2088   new_type = cp_build_type_attribute_variant (new_type,
2089                                               TYPE_ATTRIBUTES (old_type));
2090   new_type = build_exception_variant (new_type,
2091                                       TYPE_RAISES_EXCEPTIONS (old_type));
2092   TREE_TYPE (decl) = new_type;
2093 }
2094
2095 /* Check to see if the function just declared, as indicated in
2096    DECLARATOR, and in DECL, is a specialization of a function
2097    template.  We may also discover that the declaration is an explicit
2098    instantiation at this point.
2099
2100    Returns DECL, or an equivalent declaration that should be used
2101    instead if all goes well.  Issues an error message if something is
2102    amiss.  Returns error_mark_node if the error is not easily
2103    recoverable.
2104
2105    FLAGS is a bitmask consisting of the following flags:
2106
2107    2: The function has a definition.
2108    4: The function is a friend.
2109
2110    The TEMPLATE_COUNT is the number of references to qualifying
2111    template classes that appeared in the name of the function.  For
2112    example, in
2113
2114      template <class T> struct S { void f(); };
2115      void S<int>::f();
2116
2117    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2118    classes are not counted in the TEMPLATE_COUNT, so that in
2119
2120      template <class T> struct S {};
2121      template <> struct S<int> { void f(); }
2122      template <> void S<int>::f();
2123
2124    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2125    invalid; there should be no template <>.)
2126
2127    If the function is a specialization, it is marked as such via
2128    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2129    is set up correctly, and it is added to the list of specializations
2130    for that template.  */
2131
2132 tree
2133 check_explicit_specialization (tree declarator,
2134                                tree decl,
2135                                int template_count,
2136                                int flags)
2137 {
2138   int have_def = flags & 2;
2139   int is_friend = flags & 4;
2140   int specialization = 0;
2141   int explicit_instantiation = 0;
2142   int member_specialization = 0;
2143   tree ctype = DECL_CLASS_CONTEXT (decl);
2144   tree dname = DECL_NAME (decl);
2145   tmpl_spec_kind tsk;
2146
2147   if (is_friend)
2148     {
2149       if (!processing_specialization)
2150         tsk = tsk_none;
2151       else
2152         tsk = tsk_excessive_parms;
2153     }
2154   else
2155     tsk = current_tmpl_spec_kind (template_count);
2156
2157   switch (tsk)
2158     {
2159     case tsk_none:
2160       if (processing_specialization)
2161         {
2162           specialization = 1;
2163           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2164         }
2165       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2166         {
2167           if (is_friend)
2168             /* This could be something like:
2169
2170                template <class T> void f(T);
2171                class S { friend void f<>(int); }  */
2172             specialization = 1;
2173           else
2174             {
2175               /* This case handles bogus declarations like template <>
2176                  template <class T> void f<int>(); */
2177
2178               error ("template-id %qD in declaration of primary template",
2179                      declarator);
2180               return decl;
2181             }
2182         }
2183       break;
2184
2185     case tsk_invalid_member_spec:
2186       /* The error has already been reported in
2187          check_specialization_scope.  */
2188       return error_mark_node;
2189
2190     case tsk_invalid_expl_inst:
2191       error ("template parameter list used in explicit instantiation");
2192
2193       /* Fall through.  */
2194
2195     case tsk_expl_inst:
2196       if (have_def)
2197         error ("definition provided for explicit instantiation");
2198
2199       explicit_instantiation = 1;
2200       break;
2201
2202     case tsk_excessive_parms:
2203     case tsk_insufficient_parms:
2204       if (tsk == tsk_excessive_parms)
2205         error ("too many template parameter lists in declaration of %qD",
2206                decl);
2207       else if (template_header_count)
2208         error("too few template parameter lists in declaration of %qD", decl);
2209       else
2210         error("explicit specialization of %qD must be introduced by "
2211               "%<template <>%>", decl);
2212
2213       /* Fall through.  */
2214     case tsk_expl_spec:
2215       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2216       if (ctype)
2217         member_specialization = 1;
2218       else
2219         specialization = 1;
2220       break;
2221
2222     case tsk_template:
2223       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2224         {
2225           /* This case handles bogus declarations like template <>
2226              template <class T> void f<int>(); */
2227
2228           if (uses_template_parms (declarator))
2229             error ("function template partial specialization %qD "
2230                    "is not allowed", declarator);
2231           else
2232             error ("template-id %qD in declaration of primary template",
2233                    declarator);
2234           return decl;
2235         }
2236
2237       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2238         /* This is a specialization of a member template, without
2239            specialization the containing class.  Something like:
2240
2241              template <class T> struct S {
2242                template <class U> void f (U);
2243              };
2244              template <> template <class U> void S<int>::f(U) {}
2245
2246            That's a specialization -- but of the entire template.  */
2247         specialization = 1;
2248       break;
2249
2250     default:
2251       gcc_unreachable ();
2252     }
2253
2254   if (specialization || member_specialization)
2255     {
2256       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2257       for (; t; t = TREE_CHAIN (t))
2258         if (TREE_PURPOSE (t))
2259           {
2260             permerror (input_location, 
2261                        "default argument specified in explicit specialization");
2262             break;
2263           }
2264     }
2265
2266   if (specialization || member_specialization || explicit_instantiation)
2267     {
2268       tree tmpl = NULL_TREE;
2269       tree targs = NULL_TREE;
2270
2271       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2272       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2273         {
2274           tree fns;
2275
2276           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2277           if (ctype)
2278             fns = dname;
2279           else
2280             {
2281               /* If there is no class context, the explicit instantiation
2282                  must be at namespace scope.  */
2283               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2284
2285               /* Find the namespace binding, using the declaration
2286                  context.  */
2287               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2288                                            false, true);
2289               if (fns == error_mark_node || !is_overloaded_fn (fns))
2290                 {
2291                   error ("%qD is not a template function", dname);
2292                   fns = error_mark_node;
2293                 }
2294               else
2295                 {
2296                   tree fn = OVL_CURRENT (fns);
2297                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2298                                                 CP_DECL_CONTEXT (fn)))
2299                     error ("%qD is not declared in %qD",
2300                            decl, current_namespace);
2301                 }
2302             }
2303
2304           declarator = lookup_template_function (fns, NULL_TREE);
2305         }
2306
2307       if (declarator == error_mark_node)
2308         return error_mark_node;
2309
2310       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2311         {
2312           if (!explicit_instantiation)
2313             /* A specialization in class scope.  This is invalid,
2314                but the error will already have been flagged by
2315                check_specialization_scope.  */
2316             return error_mark_node;
2317           else
2318             {
2319               /* It's not valid to write an explicit instantiation in
2320                  class scope, e.g.:
2321
2322                    class C { template void f(); }
2323
2324                    This case is caught by the parser.  However, on
2325                    something like:
2326
2327                    template class C { void f(); };
2328
2329                    (which is invalid) we can get here.  The error will be
2330                    issued later.  */
2331               ;
2332             }
2333
2334           return decl;
2335         }
2336       else if (ctype != NULL_TREE
2337                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2338                    IDENTIFIER_NODE))
2339         {
2340           /* Find the list of functions in ctype that have the same
2341              name as the declared function.  */
2342           tree name = TREE_OPERAND (declarator, 0);
2343           tree fns = NULL_TREE;
2344           int idx;
2345
2346           if (constructor_name_p (name, ctype))
2347             {
2348               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2349
2350               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2351                   : !CLASSTYPE_DESTRUCTORS (ctype))
2352                 {
2353                   /* From [temp.expl.spec]:
2354
2355                      If such an explicit specialization for the member
2356                      of a class template names an implicitly-declared
2357                      special member function (clause _special_), the
2358                      program is ill-formed.
2359
2360                      Similar language is found in [temp.explicit].  */
2361                   error ("specialization of implicitly-declared special member function");
2362                   return error_mark_node;
2363                 }
2364
2365               name = is_constructor ? ctor_identifier : dtor_identifier;
2366             }
2367
2368           if (!DECL_CONV_FN_P (decl))
2369             {
2370               idx = lookup_fnfields_1 (ctype, name);
2371               if (idx >= 0)
2372                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2373             }
2374           else
2375             {
2376               VEC(tree,gc) *methods;
2377               tree ovl;
2378
2379               /* For a type-conversion operator, we cannot do a
2380                  name-based lookup.  We might be looking for `operator
2381                  int' which will be a specialization of `operator T'.
2382                  So, we find *all* the conversion operators, and then
2383                  select from them.  */
2384               fns = NULL_TREE;
2385
2386               methods = CLASSTYPE_METHOD_VEC (ctype);
2387               if (methods)
2388                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2389                      VEC_iterate (tree, methods, idx, ovl);
2390                      ++idx)
2391                   {
2392                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2393                       /* There are no more conversion functions.  */
2394                       break;
2395
2396                     /* Glue all these conversion functions together
2397                        with those we already have.  */
2398                     for (; ovl; ovl = OVL_NEXT (ovl))
2399                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2400                   }
2401             }
2402
2403           if (fns == NULL_TREE)
2404             {
2405               error ("no member function %qD declared in %qT", name, ctype);
2406               return error_mark_node;
2407             }
2408           else
2409             TREE_OPERAND (declarator, 0) = fns;
2410         }
2411
2412       /* Figure out what exactly is being specialized at this point.
2413          Note that for an explicit instantiation, even one for a
2414          member function, we cannot tell apriori whether the
2415          instantiation is for a member template, or just a member
2416          function of a template class.  Even if a member template is
2417          being instantiated, the member template arguments may be
2418          elided if they can be deduced from the rest of the
2419          declaration.  */
2420       tmpl = determine_specialization (declarator, decl,
2421                                        &targs,
2422                                        member_specialization,
2423                                        template_count,
2424                                        tsk);
2425
2426       if (!tmpl || tmpl == error_mark_node)
2427         /* We couldn't figure out what this declaration was
2428            specializing.  */
2429         return error_mark_node;
2430       else
2431         {
2432           tree gen_tmpl = most_general_template (tmpl);
2433
2434           if (explicit_instantiation)
2435             {
2436               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2437                  is done by do_decl_instantiation later.  */
2438
2439               int arg_depth = TMPL_ARGS_DEPTH (targs);
2440               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2441
2442               if (arg_depth > parm_depth)
2443                 {
2444                   /* If TMPL is not the most general template (for
2445                      example, if TMPL is a friend template that is
2446                      injected into namespace scope), then there will
2447                      be too many levels of TARGS.  Remove some of them
2448                      here.  */
2449                   int i;
2450                   tree new_targs;
2451
2452                   new_targs = make_tree_vec (parm_depth);
2453                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2454                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2455                       = TREE_VEC_ELT (targs, i);
2456                   targs = new_targs;
2457                 }
2458
2459               return instantiate_template (tmpl, targs, tf_error);
2460             }
2461
2462           /* If we thought that the DECL was a member function, but it
2463              turns out to be specializing a static member function,
2464              make DECL a static member function as well.  */
2465           if (DECL_STATIC_FUNCTION_P (tmpl)
2466               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2467             revert_static_member_fn (decl);
2468
2469           /* If this is a specialization of a member template of a
2470              template class, we want to return the TEMPLATE_DECL, not
2471              the specialization of it.  */
2472           if (tsk == tsk_template)
2473             {
2474               tree result = DECL_TEMPLATE_RESULT (tmpl);
2475               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2476               DECL_INITIAL (result) = NULL_TREE;
2477               if (have_def)
2478                 {
2479                   tree parm;
2480                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2481                   DECL_SOURCE_LOCATION (result)
2482                     = DECL_SOURCE_LOCATION (decl);
2483                   /* We want to use the argument list specified in the
2484                      definition, not in the original declaration.  */
2485                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2486                   for (parm = DECL_ARGUMENTS (result); parm;
2487                        parm = TREE_CHAIN (parm))
2488                     DECL_CONTEXT (parm) = result;
2489                 }
2490               return register_specialization (tmpl, gen_tmpl, targs,
2491                                               is_friend, 0);
2492             }
2493
2494           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2495           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2496
2497           /* Inherit default function arguments from the template
2498              DECL is specializing.  */
2499           copy_default_args_to_explicit_spec (decl);
2500
2501           /* This specialization has the same protection as the
2502              template it specializes.  */
2503           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2504           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2505
2506           /* 7.1.1-1 [dcl.stc]
2507
2508              A storage-class-specifier shall not be specified in an
2509              explicit specialization...
2510
2511              The parser rejects these, so unless action is taken here,
2512              explicit function specializations will always appear with
2513              global linkage.
2514
2515              The action recommended by the C++ CWG in response to C++
2516              defect report 605 is to make the storage class and linkage
2517              of the explicit specialization match the templated function:
2518
2519              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2520            */
2521           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2522             {
2523               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2524               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2525
2526               /* This specialization has the same linkage and visibility as
2527                  the function template it specializes.  */
2528               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2529               if (! TREE_PUBLIC (decl))
2530                 {
2531                   DECL_INTERFACE_KNOWN (decl) = 1;
2532                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2533                 }
2534               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2535               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2536                 {
2537                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2538                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2539                 }
2540             }
2541
2542           /* If DECL is a friend declaration, declared using an
2543              unqualified name, the namespace associated with DECL may
2544              have been set incorrectly.  For example, in:
2545
2546                template <typename T> void f(T);
2547                namespace N {
2548                  struct S { friend void f<int>(int); }
2549                }
2550
2551              we will have set the DECL_CONTEXT for the friend
2552              declaration to N, rather than to the global namespace.  */
2553           if (DECL_NAMESPACE_SCOPE_P (decl))
2554             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2555
2556           if (is_friend && !have_def)
2557             /* This is not really a declaration of a specialization.
2558                It's just the name of an instantiation.  But, it's not
2559                a request for an instantiation, either.  */
2560             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2561           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2562             /* This is indeed a specialization.  In case of constructors
2563                and destructors, we need in-charge and not-in-charge
2564                versions in V3 ABI.  */
2565             clone_function_decl (decl, /*update_method_vec_p=*/0);
2566
2567           /* Register this specialization so that we can find it
2568              again.  */
2569           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2570         }
2571     }
2572
2573   return decl;
2574 }
2575
2576 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2577    parameters.  These are represented in the same format used for
2578    DECL_TEMPLATE_PARMS.  */
2579
2580 int
2581 comp_template_parms (const_tree parms1, const_tree parms2)
2582 {
2583   const_tree p1;
2584   const_tree p2;
2585
2586   if (parms1 == parms2)
2587     return 1;
2588
2589   for (p1 = parms1, p2 = parms2;
2590        p1 != NULL_TREE && p2 != NULL_TREE;
2591        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2592     {
2593       tree t1 = TREE_VALUE (p1);
2594       tree t2 = TREE_VALUE (p2);
2595       int i;
2596
2597       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2598       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2599
2600       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2601         return 0;
2602
2603       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2604         {
2605           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2606           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2607
2608           /* If either of the template parameters are invalid, assume
2609              they match for the sake of error recovery. */
2610           if (parm1 == error_mark_node || parm2 == error_mark_node)
2611             return 1;
2612
2613           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2614             return 0;
2615
2616           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2617               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2618                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2619             continue;
2620           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2621             return 0;
2622         }
2623     }
2624
2625   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2626     /* One set of parameters has more parameters lists than the
2627        other.  */
2628     return 0;
2629
2630   return 1;
2631 }
2632
2633 /* Determine whether PARM is a parameter pack.  */
2634
2635 bool 
2636 template_parameter_pack_p (const_tree parm)
2637 {
2638   /* Determine if we have a non-type template parameter pack.  */
2639   if (TREE_CODE (parm) == PARM_DECL)
2640     return (DECL_TEMPLATE_PARM_P (parm) 
2641             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2642
2643   /* If this is a list of template parameters, we could get a
2644      TYPE_DECL or a TEMPLATE_DECL.  */ 
2645   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2646     parm = TREE_TYPE (parm);
2647
2648   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2649            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2650           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2651 }
2652
2653 /* Determine if T is a function parameter pack.  */
2654
2655 bool
2656 function_parameter_pack_p (const_tree t)
2657 {
2658   if (t && TREE_CODE (t) == PARM_DECL)
2659     return FUNCTION_PARAMETER_PACK_P (t);
2660   return false;
2661 }
2662
2663 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2664    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2665
2666 tree
2667 get_function_template_decl (const_tree primary_func_tmpl_inst)
2668 {
2669   if (! primary_func_tmpl_inst
2670       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2671       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2672     return NULL;
2673
2674   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2675 }
2676
2677 /* Return true iff the function parameter PARAM_DECL was expanded
2678    from the function parameter pack PACK.  */
2679
2680 bool
2681 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2682 {
2683     if (DECL_ARTIFICIAL (param_decl)
2684         || !function_parameter_pack_p (pack))
2685       return false;
2686
2687     gcc_assert (DECL_NAME (param_decl) && DECL_NAME (pack));
2688
2689     /* The parameter pack and its pack arguments have the same
2690        DECL_PARM_INDEX.  */
2691     return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2692 }
2693
2694 /* Determine whether ARGS describes a variadic template args list,
2695    i.e., one that is terminated by a template argument pack.  */
2696
2697 static bool 
2698 template_args_variadic_p (tree args)
2699 {
2700   int nargs;
2701   tree last_parm;
2702
2703   if (args == NULL_TREE)
2704     return false;
2705
2706   args = INNERMOST_TEMPLATE_ARGS (args);
2707   nargs = TREE_VEC_LENGTH (args);
2708
2709   if (nargs == 0)
2710     return false;
2711
2712   last_parm = TREE_VEC_ELT (args, nargs - 1);
2713
2714   return ARGUMENT_PACK_P (last_parm);
2715 }
2716
2717 /* Generate a new name for the parameter pack name NAME (an
2718    IDENTIFIER_NODE) that incorporates its */
2719
2720 static tree
2721 make_ith_pack_parameter_name (tree name, int i)
2722 {
2723   /* Munge the name to include the parameter index.  */
2724 #define NUMBUF_LEN 128
2725   char numbuf[NUMBUF_LEN];
2726   char* newname;
2727   int newname_len;
2728
2729   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2730   newname_len = IDENTIFIER_LENGTH (name)
2731                 + strlen (numbuf) + 2;
2732   newname = (char*)alloca (newname_len);
2733   snprintf (newname, newname_len,
2734             "%s#%i", IDENTIFIER_POINTER (name), i);
2735   return get_identifier (newname);
2736 }
2737
2738 /* Return true if T is a primary function
2739    or class template instantiation.  */
2740
2741 bool
2742 primary_template_instantiation_p (const_tree t)
2743 {
2744   if (!t)
2745     return false;
2746
2747   if (TREE_CODE (t) == FUNCTION_DECL)
2748     return DECL_LANG_SPECIFIC (t)
2749            && DECL_TEMPLATE_INSTANTIATION (t)
2750            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2751   else if (CLASS_TYPE_P (t))
2752     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2753            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2754   return false;
2755 }
2756
2757 /* Return true if PARM is a template template parameter.  */
2758
2759 bool
2760 template_template_parameter_p (const_tree parm)
2761 {
2762   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2763 }
2764
2765 /* Return the template parameters of T if T is a
2766    primary template instantiation, NULL otherwise.  */
2767
2768 tree
2769 get_primary_template_innermost_parameters (const_tree t)
2770 {
2771   tree parms = NULL, template_info = NULL;
2772
2773   if ((template_info = get_template_info (t))
2774       && primary_template_instantiation_p (t))
2775     parms = INNERMOST_TEMPLATE_PARMS
2776         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2777
2778   return parms;
2779 }
2780
2781 /* Returns the template arguments of T if T is a template instantiation,
2782    NULL otherwise.  */
2783
2784 tree
2785 get_template_innermost_arguments (const_tree t)
2786 {
2787   tree args = NULL, template_info = NULL;
2788
2789   if ((template_info = get_template_info (t))
2790       && TI_ARGS (template_info))
2791     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2792
2793   return args;
2794 }
2795
2796 /* Return the argument pack elements of T if T is a template argument pack,
2797    NULL otherwise.  */
2798
2799 tree
2800 get_template_argument_pack_elems (const_tree t)
2801 {
2802   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2803       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2804     return NULL;
2805
2806   return ARGUMENT_PACK_ARGS (t);
2807 }
2808
2809 /* Structure used to track the progress of find_parameter_packs_r.  */
2810 struct find_parameter_pack_data 
2811 {
2812   /* TREE_LIST that will contain all of the parameter packs found by
2813      the traversal.  */
2814   tree* parameter_packs;
2815
2816   /* Set of AST nodes that have been visited by the traversal.  */
2817   struct pointer_set_t *visited;
2818 };
2819
2820 /* Identifies all of the argument packs that occur in a template
2821    argument and appends them to the TREE_LIST inside DATA, which is a
2822    find_parameter_pack_data structure. This is a subroutine of
2823    make_pack_expansion and uses_parameter_packs.  */
2824 static tree
2825 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2826 {
2827   tree t = *tp;
2828   struct find_parameter_pack_data* ppd = 
2829     (struct find_parameter_pack_data*)data;
2830   bool parameter_pack_p = false;
2831
2832   /* Identify whether this is a parameter pack or not.  */
2833   switch (TREE_CODE (t))
2834     {
2835     case TEMPLATE_PARM_INDEX:
2836       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2837         parameter_pack_p = true;
2838       break;
2839
2840     case TEMPLATE_TYPE_PARM:
2841     case TEMPLATE_TEMPLATE_PARM:
2842       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2843         parameter_pack_p = true;
2844       break;
2845
2846     case PARM_DECL:
2847       if (FUNCTION_PARAMETER_PACK_P (t))
2848         {
2849           /* We don't want to walk into the type of a PARM_DECL,
2850              because we don't want to see the type parameter pack.  */
2851           *walk_subtrees = 0;
2852           parameter_pack_p = true;
2853         }
2854       break;
2855
2856     default:
2857       /* Not a parameter pack.  */
2858       break;
2859     }
2860
2861   if (parameter_pack_p)
2862     {
2863       /* Add this parameter pack to the list.  */
2864       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2865     }
2866
2867   if (TYPE_P (t))
2868     cp_walk_tree (&TYPE_CONTEXT (t), 
2869                   &find_parameter_packs_r, ppd, ppd->visited);
2870
2871   /* This switch statement will return immediately if we don't find a
2872      parameter pack.  */
2873   switch (TREE_CODE (t)) 
2874     {
2875     case TEMPLATE_PARM_INDEX:
2876       return NULL_TREE;
2877
2878     case BOUND_TEMPLATE_TEMPLATE_PARM:
2879       /* Check the template itself.  */
2880       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2881                     &find_parameter_packs_r, ppd, ppd->visited);
2882       /* Check the template arguments.  */
2883       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2884                     ppd->visited);
2885       *walk_subtrees = 0;
2886       return NULL_TREE;
2887
2888     case TEMPLATE_TYPE_PARM:
2889     case TEMPLATE_TEMPLATE_PARM:
2890       return NULL_TREE;
2891
2892     case PARM_DECL:
2893       return NULL_TREE;
2894
2895     case RECORD_TYPE:
2896       if (TYPE_PTRMEMFUNC_P (t))
2897         return NULL_TREE;
2898       /* Fall through.  */
2899
2900     case UNION_TYPE:
2901     case ENUMERAL_TYPE:
2902       if (TYPE_TEMPLATE_INFO (t))
2903         cp_walk_tree (&TREE_VALUE (TYPE_TEMPLATE_INFO (t)), 
2904                       &find_parameter_packs_r, ppd, ppd->visited);
2905
2906       *walk_subtrees = 0;
2907       return NULL_TREE;
2908
2909     case TEMPLATE_DECL:
2910       cp_walk_tree (&TREE_TYPE (t),
2911                     &find_parameter_packs_r, ppd, ppd->visited);
2912       return NULL_TREE;
2913  
2914     case TYPENAME_TYPE:
2915       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2916                    ppd, ppd->visited);
2917       *walk_subtrees = 0;
2918       return NULL_TREE;
2919       
2920     case TYPE_PACK_EXPANSION:
2921     case EXPR_PACK_EXPANSION:
2922       *walk_subtrees = 0;
2923       return NULL_TREE;
2924
2925     case INTEGER_TYPE:
2926       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2927                     ppd, ppd->visited);
2928       *walk_subtrees = 0;
2929       return NULL_TREE;
2930
2931     case IDENTIFIER_NODE:
2932       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2933                     ppd->visited);
2934       *walk_subtrees = 0;
2935       return NULL_TREE;
2936
2937     default:
2938       return NULL_TREE;
2939     }
2940
2941   return NULL_TREE;
2942 }
2943
2944 /* Determines if the expression or type T uses any parameter packs.  */
2945 bool
2946 uses_parameter_packs (tree t)
2947 {
2948   tree parameter_packs = NULL_TREE;
2949   struct find_parameter_pack_data ppd;
2950   ppd.parameter_packs = &parameter_packs;
2951   ppd.visited = pointer_set_create ();
2952   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2953   pointer_set_destroy (ppd.visited);
2954   return parameter_packs != NULL_TREE;
2955 }
2956
2957 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2958    representation a base-class initializer into a parameter pack
2959    expansion. If all goes well, the resulting node will be an
2960    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2961    respectively.  */
2962 tree 
2963 make_pack_expansion (tree arg)
2964 {
2965   tree result;
2966   tree parameter_packs = NULL_TREE;
2967   bool for_types = false;
2968   struct find_parameter_pack_data ppd;
2969
2970   if (!arg || arg == error_mark_node)
2971     return arg;
2972
2973   if (TREE_CODE (arg) == TREE_LIST)
2974     {
2975       /* The only time we will see a TREE_LIST here is for a base
2976          class initializer.  In this case, the TREE_PURPOSE will be a
2977          _TYPE node (representing the base class expansion we're
2978          initializing) and the TREE_VALUE will be a TREE_LIST
2979          containing the initialization arguments. 
2980
2981          The resulting expansion looks somewhat different from most
2982          expansions. Rather than returning just one _EXPANSION, we
2983          return a TREE_LIST whose TREE_PURPOSE is a
2984          TYPE_PACK_EXPANSION containing the bases that will be
2985          initialized.  The TREE_VALUE will be identical to the
2986          original TREE_VALUE, which is a list of arguments that will
2987          be passed to each base.  We do not introduce any new pack
2988          expansion nodes into the TREE_VALUE (although it is possible
2989          that some already exist), because the TREE_PURPOSE and
2990          TREE_VALUE all need to be expanded together with the same
2991          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2992          resulting TREE_PURPOSE will mention the parameter packs in
2993          both the bases and the arguments to the bases.  */
2994       tree purpose;
2995       tree value;
2996       tree parameter_packs = NULL_TREE;
2997
2998       /* Determine which parameter packs will be used by the base
2999          class expansion.  */
3000       ppd.visited = pointer_set_create ();
3001       ppd.parameter_packs = &parameter_packs;
3002       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3003                     &ppd, ppd.visited);
3004
3005       if (parameter_packs == NULL_TREE)
3006         {
3007           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3008           pointer_set_destroy (ppd.visited);
3009           return error_mark_node;
3010         }
3011
3012       if (TREE_VALUE (arg) != void_type_node)
3013         {
3014           /* Collect the sets of parameter packs used in each of the
3015              initialization arguments.  */
3016           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3017             {
3018               /* Determine which parameter packs will be expanded in this
3019                  argument.  */
3020               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3021                             &ppd, ppd.visited);
3022             }
3023         }
3024
3025       pointer_set_destroy (ppd.visited);
3026
3027       /* Create the pack expansion type for the base type.  */
3028       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3029       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3030       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3031
3032       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3033          they will rarely be compared to anything.  */
3034       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3035
3036       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3037     }
3038
3039   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3040     for_types = true;
3041
3042   /* Build the PACK_EXPANSION_* node.  */
3043   result = for_types
3044      ? cxx_make_type (TYPE_PACK_EXPANSION)
3045      : make_node (EXPR_PACK_EXPANSION);
3046   SET_PACK_EXPANSION_PATTERN (result, arg);
3047   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3048     {
3049       /* Propagate type and const-expression information.  */
3050       TREE_TYPE (result) = TREE_TYPE (arg);
3051       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3052     }
3053   else
3054     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3055        they will rarely be compared to anything.  */
3056     SET_TYPE_STRUCTURAL_EQUALITY (result);
3057
3058   /* Determine which parameter packs will be expanded.  */
3059   ppd.parameter_packs = &parameter_packs;
3060   ppd.visited = pointer_set_create ();
3061   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3062   pointer_set_destroy (ppd.visited);
3063
3064   /* Make sure we found some parameter packs.  */
3065   if (parameter_packs == NULL_TREE)
3066     {
3067       if (TYPE_P (arg))
3068         error ("expansion pattern %<%T%> contains no argument packs", arg);
3069       else
3070         error ("expansion pattern %<%E%> contains no argument packs", arg);
3071       return error_mark_node;
3072     }
3073   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3074
3075   return result;
3076 }
3077
3078 /* Checks T for any "bare" parameter packs, which have not yet been
3079    expanded, and issues an error if any are found. This operation can
3080    only be done on full expressions or types (e.g., an expression
3081    statement, "if" condition, etc.), because we could have expressions like:
3082
3083      foo(f(g(h(args)))...)
3084
3085    where "args" is a parameter pack. check_for_bare_parameter_packs
3086    should not be called for the subexpressions args, h(args),
3087    g(h(args)), or f(g(h(args))), because we would produce erroneous
3088    error messages. 
3089
3090    Returns TRUE and emits an error if there were bare parameter packs,
3091    returns FALSE otherwise.  */
3092 bool 
3093 check_for_bare_parameter_packs (tree t)
3094 {
3095   tree parameter_packs = NULL_TREE;
3096   struct find_parameter_pack_data ppd;
3097
3098   if (!processing_template_decl || !t || t == error_mark_node)
3099     return false;
3100
3101   if (TREE_CODE (t) == TYPE_DECL)
3102     t = TREE_TYPE (t);
3103
3104   ppd.parameter_packs = &parameter_packs;
3105   ppd.visited = pointer_set_create ();
3106   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3107   pointer_set_destroy (ppd.visited);
3108
3109   if (parameter_packs) 
3110     {
3111       error ("parameter packs not expanded with %<...%>:");
3112       while (parameter_packs)
3113         {
3114           tree pack = TREE_VALUE (parameter_packs);
3115           tree name = NULL_TREE;
3116
3117           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3118               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3119             name = TYPE_NAME (pack);
3120           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3121             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3122           else
3123             name = DECL_NAME (pack);
3124
3125           if (name)
3126             inform (input_location, "        %qD", name);
3127           else
3128             inform (input_location, "        <anonymous>");
3129
3130           parameter_packs = TREE_CHAIN (parameter_packs);
3131         }
3132
3133       return true;
3134     }
3135
3136   return false;
3137 }
3138
3139 /* Expand any parameter packs that occur in the template arguments in
3140    ARGS.  */
3141 tree
3142 expand_template_argument_pack (tree args)
3143 {
3144   tree result_args = NULL_TREE;
3145   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3146   int num_result_args = -1;
3147
3148   /* First, determine if we need to expand anything, and the number of
3149      slots we'll need.  */
3150   for (in_arg = 0; in_arg < nargs; ++in_arg)
3151     {
3152       tree arg = TREE_VEC_ELT (args, in_arg);
3153       if (ARGUMENT_PACK_P (arg))
3154         {
3155           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3156           if (num_result_args < 0)
3157             num_result_args = in_arg + num_packed;
3158           else
3159             num_result_args += num_packed;
3160         }
3161       else
3162         {
3163           if (num_result_args >= 0)
3164             num_result_args++;
3165         }
3166     }
3167
3168   /* If no expansion is necessary, we're done.  */
3169   if (num_result_args < 0)
3170     return args;
3171
3172   /* Expand arguments.  */
3173   result_args = make_tree_vec (num_result_args);
3174   for (in_arg = 0; in_arg < nargs; ++in_arg)
3175     {
3176       tree arg = TREE_VEC_ELT (args, in_arg);
3177       if (ARGUMENT_PACK_P (arg))
3178         {
3179           tree packed = ARGUMENT_PACK_ARGS (arg);
3180           int i, num_packed = TREE_VEC_LENGTH (packed);
3181           for (i = 0; i < num_packed; ++i, ++out_arg)
3182             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3183         }
3184       else
3185         {
3186           TREE_VEC_ELT (result_args, out_arg) = arg;
3187           ++out_arg;
3188         }
3189     }
3190
3191   return result_args;
3192 }
3193
3194 /* Checks if DECL shadows a template parameter.
3195
3196    [temp.local]: A template-parameter shall not be redeclared within its
3197    scope (including nested scopes).
3198
3199    Emits an error and returns TRUE if the DECL shadows a parameter,
3200    returns FALSE otherwise.  */
3201
3202 bool
3203 check_template_shadow (tree decl)
3204 {
3205   tree olddecl;
3206
3207   /* If we're not in a template, we can't possibly shadow a template
3208      parameter.  */
3209   if (!current_template_parms)
3210     return true;
3211
3212   /* Figure out what we're shadowing.  */
3213   if (TREE_CODE (decl) == OVERLOAD)
3214     decl = OVL_CURRENT (decl);
3215   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3216
3217   /* If there's no previous binding for this name, we're not shadowing
3218      anything, let alone a template parameter.  */
3219   if (!olddecl)
3220     return true;
3221
3222   /* If we're not shadowing a template parameter, we're done.  Note
3223      that OLDDECL might be an OVERLOAD (or perhaps even an
3224      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3225      node.  */
3226   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3227     return true;
3228
3229   /* We check for decl != olddecl to avoid bogus errors for using a
3230      name inside a class.  We check TPFI to avoid duplicate errors for
3231      inline member templates.  */
3232   if (decl == olddecl
3233       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3234     return true;
3235
3236   error ("declaration of %q+#D", decl);
3237   error (" shadows template parm %q+#D", olddecl);
3238   return false;
3239 }
3240
3241 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3242    ORIG_LEVEL, DECL, and TYPE.  */
3243
3244 static tree
3245 build_template_parm_index (int index,
3246                            int level,
3247                            int orig_level,
3248                            tree decl,
3249                            tree type)
3250 {
3251   tree t = make_node (TEMPLATE_PARM_INDEX);
3252   TEMPLATE_PARM_IDX (t) = index;
3253   TEMPLATE_PARM_LEVEL (t) = level;
3254   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3255   TEMPLATE_PARM_DECL (t) = decl;
3256   TREE_TYPE (t) = type;
3257   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3258   TREE_READONLY (t) = TREE_READONLY (decl);
3259
3260   return t;
3261 }
3262
3263 /* Find the canonical type parameter for the given template type
3264    parameter.  Returns the canonical type parameter, which may be TYPE
3265    if no such parameter existed.  */
3266 static tree
3267 canonical_type_parameter (tree type)
3268 {
3269   tree list;
3270   int idx = TEMPLATE_TYPE_IDX (type);
3271   if (!canonical_template_parms)
3272     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3273
3274   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3275     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3276
3277   list = VEC_index (tree, canonical_template_parms, idx);
3278   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3279     list = TREE_CHAIN (list);
3280
3281   if (list)
3282     return TREE_VALUE (list);
3283   else
3284     {
3285       VEC_replace(tree, canonical_template_parms, idx,
3286                   tree_cons (NULL_TREE, type, 
3287                              VEC_index (tree, canonical_template_parms, idx)));
3288       return type;
3289     }
3290 }
3291
3292 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3293    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3294    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3295    new one is created.  */
3296
3297 static tree
3298 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3299                             tsubst_flags_t complain)
3300 {
3301   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3302       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3303           != TEMPLATE_PARM_LEVEL (index) - levels))
3304     {
3305       tree orig_decl = TEMPLATE_PARM_DECL (index);
3306       tree decl, t;
3307
3308       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3309                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3310       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3311       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3312       DECL_ARTIFICIAL (decl) = 1;
3313       SET_DECL_TEMPLATE_PARM_P (decl);
3314
3315       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3316                                      TEMPLATE_PARM_LEVEL (index) - levels,
3317                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3318                                      decl, type);
3319       TEMPLATE_PARM_DESCENDANTS (index) = t;
3320       TEMPLATE_PARM_PARAMETER_PACK (t) 
3321         = TEMPLATE_PARM_PARAMETER_PACK (index);
3322
3323         /* Template template parameters need this.  */
3324       if (TREE_CODE (decl) == TEMPLATE_DECL)
3325         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3326           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3327            args, complain);
3328     }
3329
3330   return TEMPLATE_PARM_DESCENDANTS (index);
3331 }
3332
3333 /* Process information from new template parameter PARM and append it to the
3334    LIST being built.  This new parameter is a non-type parameter iff
3335    IS_NON_TYPE is true. This new parameter is a parameter
3336    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3337    PARM_LOC.  */
3338
3339 tree
3340 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3341                        bool is_parameter_pack)
3342 {
3343   tree decl = 0;
3344   tree defval;
3345   tree err_parm_list;
3346   int idx = 0;
3347
3348   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3349   defval = TREE_PURPOSE (parm);
3350
3351   if (list)
3352     {
3353       tree p = tree_last (list);
3354
3355       if (p && TREE_VALUE (p) != error_mark_node)
3356         {
3357           p = TREE_VALUE (p);
3358           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3359             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3360           else
3361             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3362         }
3363
3364       ++idx;
3365     }
3366   else
3367     idx = 0;
3368
3369   if (is_non_type)
3370     {
3371       parm = TREE_VALUE (parm);
3372
3373       SET_DECL_TEMPLATE_PARM_P (parm);
3374
3375       if (TREE_TYPE (parm) == error_mark_node)
3376         {
3377           err_parm_list = build_tree_list (defval, parm);
3378           TREE_VALUE (err_parm_list) = error_mark_node;
3379            return chainon (list, err_parm_list);
3380         }
3381       else
3382       {
3383         /* [temp.param]
3384
3385            The top-level cv-qualifiers on the template-parameter are
3386            ignored when determining its type.  */
3387         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3388         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3389           {
3390             err_parm_list = build_tree_list (defval, parm);
3391             TREE_VALUE (err_parm_list) = error_mark_node;
3392              return chainon (list, err_parm_list);
3393           }
3394
3395         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3396           {
3397             /* This template parameter is not a parameter pack, but it
3398                should be. Complain about "bare" parameter packs.  */
3399             check_for_bare_parameter_packs (TREE_TYPE (parm));
3400             
3401             /* Recover by calling this a parameter pack.  */
3402             is_parameter_pack = true;
3403           }
3404       }
3405
3406       /* A template parameter is not modifiable.  */
3407       TREE_CONSTANT (parm) = 1;
3408       TREE_READONLY (parm) = 1;
3409       decl = build_decl (parm_loc,
3410                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3411       TREE_CONSTANT (decl) = 1;
3412       TREE_READONLY (decl) = 1;
3413       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3414         = build_template_parm_index (idx, processing_template_decl,
3415                                      processing_template_decl,
3416                                      decl, TREE_TYPE (parm));
3417
3418       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3419         = is_parameter_pack;
3420     }
3421   else
3422     {
3423       tree t;
3424       parm = TREE_VALUE (TREE_VALUE (parm));
3425
3426       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3427         {
3428           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3429           /* This is for distinguishing between real templates and template
3430              template parameters */
3431           TREE_TYPE (parm) = t;
3432           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3433           decl = parm;
3434         }
3435       else
3436         {
3437           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3438           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3439           decl = build_decl (parm_loc,
3440                              TYPE_DECL, parm, t);
3441         }
3442
3443       TYPE_NAME (t) = decl;
3444       TYPE_STUB_DECL (t) = decl;
3445       parm = decl;
3446       TEMPLATE_TYPE_PARM_INDEX (t)
3447         = build_template_parm_index (idx, processing_template_decl,
3448                                      processing_template_decl,
3449                                      decl, TREE_TYPE (parm));
3450       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3451       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3452     }
3453   DECL_ARTIFICIAL (decl) = 1;
3454   SET_DECL_TEMPLATE_PARM_P (decl);
3455   pushdecl (decl);
3456   parm = build_tree_list (defval, parm);
3457   return chainon (list, parm);
3458 }
3459
3460 /* The end of a template parameter list has been reached.  Process the
3461    tree list into a parameter vector, converting each parameter into a more
3462    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3463    as PARM_DECLs.  */
3464
3465 tree
3466 end_template_parm_list (tree parms)
3467 {
3468   int nparms;
3469   tree parm, next;
3470   tree saved_parmlist = make_tree_vec (list_length (parms));
3471
3472   current_template_parms
3473     = tree_cons (size_int (processing_template_decl),
3474                  saved_parmlist, current_template_parms);
3475
3476   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3477     {
3478       next = TREE_CHAIN (parm);
3479       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3480       TREE_CHAIN (parm) = NULL_TREE;
3481     }
3482
3483   --processing_template_parmlist;
3484
3485   return saved_parmlist;
3486 }
3487
3488 /* end_template_decl is called after a template declaration is seen.  */
3489
3490 void
3491 end_template_decl (void)
3492 {
3493   reset_specialization ();
3494
3495   if (! processing_template_decl)
3496     return;
3497
3498   /* This matches the pushlevel in begin_template_parm_list.  */
3499   finish_scope ();
3500
3501   --processing_template_decl;
3502   current_template_parms = TREE_CHAIN (current_template_parms);
3503 }
3504
3505 /* Within the declaration of a template, return all levels of template
3506    parameters that apply.  The template parameters are represented as
3507    a TREE_VEC, in the form documented in cp-tree.h for template
3508    arguments.  */
3509
3510 static tree
3511 current_template_args (void)
3512 {
3513   tree header;
3514   tree args = NULL_TREE;
3515   int length = TMPL_PARMS_DEPTH (current_template_parms);
3516   int l = length;
3517
3518   /* If there is only one level of template parameters, we do not
3519      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3520      TREE_VEC containing the arguments.  */
3521   if (length > 1)
3522     args = make_tree_vec (length);
3523
3524   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3525     {
3526       tree a = copy_node (TREE_VALUE (header));
3527       int i;
3528
3529       TREE_TYPE (a) = NULL_TREE;
3530       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3531         {
3532           tree t = TREE_VEC_ELT (a, i);
3533
3534           /* T will be a list if we are called from within a
3535              begin/end_template_parm_list pair, but a vector directly
3536              if within a begin/end_member_template_processing pair.  */
3537           if (TREE_CODE (t) == TREE_LIST)
3538             {
3539               t = TREE_VALUE (t);
3540
3541               if (!error_operand_p (t))
3542                 {
3543                   if (TREE_CODE (t) == TYPE_DECL
3544                       || TREE_CODE (t) == TEMPLATE_DECL)
3545                     {
3546                       t = TREE_TYPE (t);
3547                       
3548                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3549                         {
3550                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3551                              with a single element, which expands T.  */
3552                           tree vec = make_tree_vec (1);
3553                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3554                           
3555                           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3556                           SET_ARGUMENT_PACK_ARGS (t, vec);
3557                         }
3558                     }
3559                   else
3560                     {
3561                       t = DECL_INITIAL (t);
3562                       
3563                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3564                         {
3565                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3566                              with a single element, which expands T.  */
3567                           tree vec = make_tree_vec (1);
3568                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3569                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3570                           
3571                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3572                           SET_ARGUMENT_PACK_ARGS (t, vec);
3573                           TREE_TYPE (t) = type;
3574                         }
3575                     }
3576                   TREE_VEC_ELT (a, i) = t;
3577                 }
3578             }
3579         }
3580
3581       if (length > 1)
3582         TREE_VEC_ELT (args, --l) = a;
3583       else
3584         args = a;
3585     }
3586
3587   return args;
3588 }
3589
3590 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3591    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3592    a member template.  Used by push_template_decl below.  */
3593
3594 static tree
3595 build_template_decl (tree decl, tree parms, bool member_template_p)
3596 {
3597   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3598   DECL_TEMPLATE_PARMS (tmpl) = parms;
3599   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3600   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3601
3602   return tmpl;
3603 }
3604
3605 struct template_parm_data
3606 {
3607   /* The level of the template parameters we are currently
3608      processing.  */
3609   int level;
3610
3611   /* The index of the specialization argument we are currently
3612      processing.  */
3613   int current_arg;
3614
3615   /* An array whose size is the number of template parameters.  The
3616      elements are nonzero if the parameter has been used in any one
3617      of the arguments processed so far.  */
3618   int* parms;
3619
3620   /* An array whose size is the number of template arguments.  The
3621      elements are nonzero if the argument makes use of template
3622      parameters of this level.  */
3623   int* arg_uses_template_parms;
3624 };
3625
3626 /* Subroutine of push_template_decl used to see if each template
3627    parameter in a partial specialization is used in the explicit
3628    argument list.  If T is of the LEVEL given in DATA (which is
3629    treated as a template_parm_data*), then DATA->PARMS is marked
3630    appropriately.  */
3631
3632 static int
3633 mark_template_parm (tree t, void* data)
3634 {
3635   int level;
3636   int idx;
3637   struct template_parm_data* tpd = (struct template_parm_data*) data;
3638
3639   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3640     {
3641       level = TEMPLATE_PARM_LEVEL (t);
3642       idx = TEMPLATE_PARM_IDX (t);
3643     }
3644   else
3645     {
3646       level = TEMPLATE_TYPE_LEVEL (t);
3647       idx = TEMPLATE_TYPE_IDX (t);
3648     }
3649
3650   if (level == tpd->level)
3651     {
3652       tpd->parms[idx] = 1;
3653       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3654     }
3655
3656   /* Return zero so that for_each_template_parm will continue the
3657      traversal of the tree; we want to mark *every* template parm.  */
3658   return 0;
3659 }
3660
3661 /* Process the partial specialization DECL.  */
3662
3663 static tree
3664 process_partial_specialization (tree decl)
3665 {
3666   tree type = TREE_TYPE (decl);
3667   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3668   tree specargs = CLASSTYPE_TI_ARGS (type);
3669   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3670   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3671   tree inner_parms;
3672   int nargs = TREE_VEC_LENGTH (inner_args);
3673   int ntparms;
3674   int  i;
3675   int did_error_intro = 0;
3676   struct template_parm_data tpd;
3677   struct template_parm_data tpd2;
3678
3679   gcc_assert (current_template_parms);
3680
3681   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3682   ntparms = TREE_VEC_LENGTH (inner_parms);
3683
3684   /* We check that each of the template parameters given in the
3685      partial specialization is used in the argument list to the
3686      specialization.  For example:
3687
3688        template <class T> struct S;
3689        template <class T> struct S<T*>;
3690
3691      The second declaration is OK because `T*' uses the template
3692      parameter T, whereas
3693
3694        template <class T> struct S<int>;
3695
3696      is no good.  Even trickier is:
3697
3698        template <class T>
3699        struct S1
3700        {
3701           template <class U>
3702           struct S2;
3703           template <class U>
3704           struct S2<T>;
3705        };
3706
3707      The S2<T> declaration is actually invalid; it is a
3708      full-specialization.  Of course,
3709
3710           template <class U>
3711           struct S2<T (*)(U)>;
3712
3713      or some such would have been OK.  */
3714   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3715   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3716   memset (tpd.parms, 0, sizeof (int) * ntparms);
3717
3718   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3719   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3720   for (i = 0; i < nargs; ++i)
3721     {
3722       tpd.current_arg = i;
3723       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3724                               &mark_template_parm,
3725                               &tpd,
3726                               NULL,
3727                               /*include_nondeduced_p=*/false);
3728     }
3729   for (i = 0; i < ntparms; ++i)
3730     if (tpd.parms[i] == 0)
3731       {
3732         /* One of the template parms was not used in the
3733            specialization.  */
3734         if (!did_error_intro)
3735           {
3736             error ("template parameters not used in partial specialization:");
3737             did_error_intro = 1;
3738           }
3739
3740         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3741       }
3742
3743   /* [temp.class.spec]
3744
3745      The argument list of the specialization shall not be identical to
3746      the implicit argument list of the primary template.  */
3747   if (comp_template_args
3748       (inner_args,
3749        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3750                                                    (maintmpl)))))
3751     error ("partial specialization %qT does not specialize any template arguments", type);
3752
3753   /* [temp.class.spec]
3754
3755      A partially specialized non-type argument expression shall not
3756      involve template parameters of the partial specialization except
3757      when the argument expression is a simple identifier.
3758
3759      The type of a template parameter corresponding to a specialized
3760      non-type argument shall not be dependent on a parameter of the
3761      specialization. 
3762
3763      Also, we verify that pack expansions only occur at the
3764      end of the argument list.  */
3765   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3766   tpd2.parms = 0;
3767   for (i = 0; i < nargs; ++i)
3768     {
3769       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3770       tree arg = TREE_VEC_ELT (inner_args, i);
3771       tree packed_args = NULL_TREE;
3772       int j, len = 1;
3773
3774       if (ARGUMENT_PACK_P (arg))
3775         {
3776           /* Extract the arguments from the argument pack. We'll be
3777              iterating over these in the following loop.  */
3778           packed_args = ARGUMENT_PACK_ARGS (arg);
3779           len = TREE_VEC_LENGTH (packed_args);
3780         }
3781
3782       for (j = 0; j < len; j++)
3783         {
3784           if (packed_args)
3785             /* Get the Jth argument in the parameter pack.  */
3786             arg = TREE_VEC_ELT (packed_args, j);
3787
3788           if (PACK_EXPANSION_P (arg))
3789             {
3790               /* Pack expansions must come at the end of the
3791                  argument list.  */
3792               if ((packed_args && j < len - 1)
3793                   || (!packed_args && i < nargs - 1))
3794                 {
3795                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3796                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3797                   else
3798                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3799
3800                   if (packed_args)
3801                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3802                 }
3803             }
3804
3805           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3806             /* We only care about the pattern.  */
3807             arg = PACK_EXPANSION_PATTERN (arg);
3808
3809           if (/* These first two lines are the `non-type' bit.  */
3810               !TYPE_P (arg)
3811               && TREE_CODE (arg) != TEMPLATE_DECL
3812               /* This next line is the `argument expression is not just a
3813                  simple identifier' condition and also the `specialized
3814                  non-type argument' bit.  */
3815               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3816             {
3817               if ((!packed_args && tpd.arg_uses_template_parms[i])
3818                   || (packed_args && uses_template_parms (arg)))
3819                 error ("template argument %qE involves template parameter(s)",
3820                        arg);
3821               else 
3822                 {
3823                   /* Look at the corresponding template parameter,
3824                      marking which template parameters its type depends
3825                      upon.  */
3826                   tree type = TREE_TYPE (parm);
3827
3828                   if (!tpd2.parms)
3829                     {
3830                       /* We haven't yet initialized TPD2.  Do so now.  */
3831                       tpd2.arg_uses_template_parms 
3832                         = (int *) alloca (sizeof (int) * nargs);
3833                       /* The number of parameters here is the number in the
3834                          main template, which, as checked in the assertion
3835                          above, is NARGS.  */
3836                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3837                       tpd2.level = 
3838                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3839                     }
3840
3841                   /* Mark the template parameters.  But this time, we're
3842                      looking for the template parameters of the main
3843                      template, not in the specialization.  */
3844                   tpd2.current_arg = i;
3845                   tpd2.arg_uses_template_parms[i] = 0;
3846                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3847                   for_each_template_parm (type,
3848                                           &mark_template_parm,
3849                                           &tpd2,
3850                                           NULL,
3851                                           /*include_nondeduced_p=*/false);
3852
3853                   if (tpd2.arg_uses_template_parms [i])
3854                     {
3855                       /* The type depended on some template parameters.
3856                          If they are fully specialized in the
3857                          specialization, that's OK.  */
3858                       int j;
3859                       for (j = 0; j < nargs; ++j)
3860                         if (tpd2.parms[j] != 0
3861                             && tpd.arg_uses_template_parms [j])
3862                           {
3863                             error ("type %qT of template argument %qE depends "
3864                                    "on template parameter(s)", 
3865                                    type,
3866                                    arg);
3867                             break;
3868                           }
3869                     }
3870                 }
3871             }
3872         }
3873     }
3874
3875   /* We should only get here once.  */
3876   gcc_assert (!COMPLETE_TYPE_P (type));
3877
3878   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3879     = tree_cons (specargs, inner_parms,
3880                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3881   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3882   return decl;
3883 }
3884
3885 /* Check that a template declaration's use of default arguments and
3886    parameter packs is not invalid.  Here, PARMS are the template
3887    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3888    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3889    specialization.
3890    
3891
3892    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3893    declaration (but not a definition); 1 indicates a declaration, 2
3894    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3895    emitted for extraneous default arguments.
3896
3897    Returns TRUE if there were no errors found, FALSE otherwise. */
3898
3899 bool
3900 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3901                          int is_partial, int is_friend_decl)
3902 {
3903   const char *msg;
3904   int last_level_to_check;
3905   tree parm_level;
3906   bool no_errors = true;
3907
3908   /* [temp.param]
3909
3910      A default template-argument shall not be specified in a
3911      function template declaration or a function template definition, nor
3912      in the template-parameter-list of the definition of a member of a
3913      class template.  */
3914
3915   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3916     /* You can't have a function template declaration in a local
3917        scope, nor you can you define a member of a class template in a
3918        local scope.  */
3919     return true;
3920
3921   if (current_class_type
3922       && !TYPE_BEING_DEFINED (current_class_type)
3923       && DECL_LANG_SPECIFIC (decl)
3924       && DECL_DECLARES_FUNCTION_P (decl)
3925       /* If this is either a friend defined in the scope of the class
3926          or a member function.  */
3927       && (DECL_FUNCTION_MEMBER_P (decl)
3928           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3929           : DECL_FRIEND_CONTEXT (decl)
3930           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3931           : false)
3932       /* And, if it was a member function, it really was defined in
3933          the scope of the class.  */
3934       && (!DECL_FUNCTION_MEMBER_P (decl)
3935           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3936     /* We already checked these parameters when the template was
3937        declared, so there's no need to do it again now.  This function
3938        was defined in class scope, but we're processing it's body now
3939        that the class is complete.  */
3940     return true;
3941
3942   /* Core issue 226 (C++0x only): the following only applies to class
3943      templates.  */
3944   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3945     {
3946       /* [temp.param]
3947
3948          If a template-parameter has a default template-argument, all
3949          subsequent template-parameters shall have a default
3950          template-argument supplied.  */
3951       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3952         {
3953           tree inner_parms = TREE_VALUE (parm_level);
3954           int ntparms = TREE_VEC_LENGTH (inner_parms);
3955           int seen_def_arg_p = 0;
3956           int i;
3957
3958           for (i = 0; i < ntparms; ++i)
3959             {
3960               tree parm = TREE_VEC_ELT (inner_parms, i);
3961
3962               if (parm == error_mark_node)
3963                 continue;
3964
3965               if (TREE_PURPOSE (parm))
3966                 seen_def_arg_p = 1;
3967               else if (seen_def_arg_p
3968                        && !template_parameter_pack_p (TREE_VALUE (parm)))
3969                 {
3970                   error ("no default argument for %qD", TREE_VALUE (parm));
3971                   /* For better subsequent error-recovery, we indicate that
3972                      there should have been a default argument.  */
3973                   TREE_PURPOSE (parm) = error_mark_node;
3974                   no_errors = false;
3975                 }
3976               else if (is_primary
3977                        && !is_partial
3978                        && !is_friend_decl
3979                        /* Don't complain about an enclosing partial
3980                           specialization.  */
3981                        && parm_level == parms
3982                        && TREE_CODE (decl) == TYPE_DECL
3983                        && i < ntparms - 1
3984                        && template_parameter_pack_p (TREE_VALUE (parm)))
3985                 {
3986                   /* A primary class template can only have one
3987                      parameter pack, at the end of the template
3988                      parameter list.  */
3989
3990                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
3991                     error ("parameter pack %qE must be at the end of the"
3992                            " template parameter list", TREE_VALUE (parm));
3993                   else
3994                     error ("parameter pack %qT must be at the end of the"
3995                            " template parameter list", 
3996                            TREE_TYPE (TREE_VALUE (parm)));
3997
3998                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
3999                     = error_mark_node;
4000                   no_errors = false;
4001                 }
4002             }
4003         }
4004     }
4005
4006   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4007       || is_partial 
4008       || !is_primary
4009       || is_friend_decl)
4010     /* For an ordinary class template, default template arguments are
4011        allowed at the innermost level, e.g.:
4012          template <class T = int>
4013          struct S {};
4014        but, in a partial specialization, they're not allowed even
4015        there, as we have in [temp.class.spec]:
4016
4017          The template parameter list of a specialization shall not
4018          contain default template argument values.
4019
4020        So, for a partial specialization, or for a function template
4021        (in C++98/C++03), we look at all of them.  */
4022     ;
4023   else
4024     /* But, for a primary class template that is not a partial
4025        specialization we look at all template parameters except the
4026        innermost ones.  */
4027     parms = TREE_CHAIN (parms);
4028
4029   /* Figure out what error message to issue.  */
4030   if (is_friend_decl == 2)
4031     msg = "default template arguments may not be used in function template friend re-declaration";
4032   else if (is_friend_decl)
4033     msg = "default template arguments may not be used in function template friend declarations";
4034   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4035     msg = ("default template arguments may not be used in function templates "
4036            "without -std=c++0x or -std=gnu++0x");
4037   else if (is_partial)
4038     msg = "default template arguments may not be used in partial specializations";
4039   else
4040     msg = "default argument for template parameter for class enclosing %qD";
4041
4042   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4043     /* If we're inside a class definition, there's no need to
4044        examine the parameters to the class itself.  On the one
4045        hand, they will be checked when the class is defined, and,
4046        on the other, default arguments are valid in things like:
4047          template <class T = double>
4048          struct S { template <class U> void f(U); };
4049        Here the default argument for `S' has no bearing on the
4050        declaration of `f'.  */
4051     last_level_to_check = template_class_depth (current_class_type) + 1;
4052   else
4053     /* Check everything.  */
4054     last_level_to_check = 0;
4055
4056   for (parm_level = parms;
4057        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4058        parm_level = TREE_CHAIN (parm_level))
4059     {
4060       tree inner_parms = TREE_VALUE (parm_level);
4061       int i;
4062       int ntparms;
4063
4064       ntparms = TREE_VEC_LENGTH (inner_parms);
4065       for (i = 0; i < ntparms; ++i)
4066         {
4067           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4068             continue;
4069
4070           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4071             {
4072               if (msg)
4073                 {
4074                   no_errors = false;
4075                   if (is_friend_decl == 2)
4076                     return no_errors;
4077
4078                   error (msg, decl);
4079                   msg = 0;
4080                 }
4081
4082               /* Clear out the default argument so that we are not
4083                  confused later.  */
4084               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4085             }
4086         }
4087
4088       /* At this point, if we're still interested in issuing messages,
4089          they must apply to classes surrounding the object declared.  */
4090       if (msg)
4091         msg = "default argument for template parameter for class enclosing %qD";
4092     }
4093
4094   return no_errors;
4095 }
4096
4097 /* Worker for push_template_decl_real, called via
4098    for_each_template_parm.  DATA is really an int, indicating the
4099    level of the parameters we are interested in.  If T is a template
4100    parameter of that level, return nonzero.  */
4101
4102 static int
4103 template_parm_this_level_p (tree t, void* data)
4104 {
4105   int this_level = *(int *)data;
4106   int level;
4107
4108   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4109     level = TEMPLATE_PARM_LEVEL (t);
4110   else
4111     level = TEMPLATE_TYPE_LEVEL (t);
4112   return level == this_level;
4113 }
4114
4115 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4116    parameters given by current_template_args, or reuses a
4117    previously existing one, if appropriate.  Returns the DECL, or an
4118    equivalent one, if it is replaced via a call to duplicate_decls.
4119
4120    If IS_FRIEND is true, DECL is a friend declaration.  */
4121
4122 tree
4123 push_template_decl_real (tree decl, bool is_friend)
4124 {
4125   tree tmpl;
4126   tree args;
4127   tree info;
4128   tree ctx;
4129   int primary;
4130   int is_partial;
4131   int new_template_p = 0;
4132   /* True if the template is a member template, in the sense of
4133      [temp.mem].  */
4134   bool member_template_p = false;
4135
4136   if (decl == error_mark_node || !current_template_parms)
4137     return error_mark_node;
4138
4139   /* See if this is a partial specialization.  */
4140   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4141                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4142                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4143
4144   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4145     is_friend = true;
4146
4147   if (is_friend)
4148     /* For a friend, we want the context of the friend function, not
4149        the type of which it is a friend.  */
4150     ctx = DECL_CONTEXT (decl);
4151   else if (CP_DECL_CONTEXT (decl)
4152            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4153     /* In the case of a virtual function, we want the class in which
4154        it is defined.  */
4155     ctx = CP_DECL_CONTEXT (decl);
4156   else
4157     /* Otherwise, if we're currently defining some class, the DECL
4158        is assumed to be a member of the class.  */
4159     ctx = current_scope ();
4160
4161   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4162     ctx = NULL_TREE;
4163
4164   if (!DECL_CONTEXT (decl))
4165     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4166
4167   /* See if this is a primary template.  */
4168   if (is_friend && ctx)
4169     /* A friend template that specifies a class context, i.e.
4170          template <typename T> friend void A<T>::f();
4171        is not primary.  */
4172     primary = 0;
4173   else
4174     primary = template_parm_scope_p ();
4175
4176   if (primary)
4177     {
4178       if (DECL_CLASS_SCOPE_P (decl))
4179         member_template_p = true;
4180       if (TREE_CODE (decl) == TYPE_DECL
4181           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4182         {
4183           error ("template class without a name");
4184           return error_mark_node;
4185         }
4186       else if (TREE_CODE (decl) == FUNCTION_DECL)
4187         {
4188           if (DECL_DESTRUCTOR_P (decl))
4189             {
4190               /* [temp.mem]
4191
4192                  A destructor shall not be a member template.  */
4193               error ("destructor %qD declared as member template", decl);
4194               return error_mark_node;
4195             }
4196           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4197               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4198                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4199                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4200                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4201                       == void_list_node)))
4202             {
4203               /* [basic.stc.dynamic.allocation]
4204
4205                  An allocation function can be a function
4206                  template. ... Template allocation functions shall
4207                  have two or more parameters.  */
4208               error ("invalid template declaration of %qD", decl);
4209               return error_mark_node;
4210             }
4211         }
4212       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4213                && CLASS_TYPE_P (TREE_TYPE (decl)))
4214         /* OK */;
4215       else
4216         {
4217           error ("template declaration of %q#D", decl);
4218           return error_mark_node;
4219         }
4220     }
4221
4222   /* Check to see that the rules regarding the use of default
4223      arguments are not being violated.  */
4224   check_default_tmpl_args (decl, current_template_parms,
4225                            primary, is_partial, /*is_friend_decl=*/0);
4226
4227   /* Ensure that there are no parameter packs in the type of this
4228      declaration that have not been expanded.  */
4229   if (TREE_CODE (decl) == FUNCTION_DECL)
4230     {
4231       /* Check each of the arguments individually to see if there are
4232          any bare parameter packs.  */
4233       tree type = TREE_TYPE (decl);
4234       tree arg = DECL_ARGUMENTS (decl);
4235       tree argtype = TYPE_ARG_TYPES (type);
4236
4237       while (arg && argtype)
4238         {
4239           if (!FUNCTION_PARAMETER_PACK_P (arg)
4240               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4241             {
4242             /* This is a PARM_DECL that contains unexpanded parameter
4243                packs. We have already complained about this in the
4244                check_for_bare_parameter_packs call, so just replace
4245                these types with ERROR_MARK_NODE.  */
4246               TREE_TYPE (arg) = error_mark_node;
4247               TREE_VALUE (argtype) = error_mark_node;
4248             }
4249
4250           arg = TREE_CHAIN (arg);
4251           argtype = TREE_CHAIN (argtype);
4252         }
4253
4254       /* Check for bare parameter packs in the return type and the
4255          exception specifiers.  */
4256       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4257         /* Errors were already issued, set return type to int
4258            as the frontend doesn't expect error_mark_node as
4259            the return type.  */
4260         TREE_TYPE (type) = integer_type_node;
4261       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4262         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4263     }
4264   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4265     {
4266       TREE_TYPE (decl) = error_mark_node;
4267       return error_mark_node;
4268     }
4269
4270   if (is_partial)
4271     return process_partial_specialization (decl);
4272
4273   args = current_template_args ();
4274
4275   if (!ctx
4276       || TREE_CODE (ctx) == FUNCTION_DECL
4277       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4278       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4279     {
4280       if (DECL_LANG_SPECIFIC (decl)
4281           && DECL_TEMPLATE_INFO (decl)
4282           && DECL_TI_TEMPLATE (decl))
4283         tmpl = DECL_TI_TEMPLATE (decl);
4284       /* If DECL is a TYPE_DECL for a class-template, then there won't
4285          be DECL_LANG_SPECIFIC.  The information equivalent to
4286          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4287       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4288                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4289                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4290         {
4291           /* Since a template declaration already existed for this
4292              class-type, we must be redeclaring it here.  Make sure
4293              that the redeclaration is valid.  */
4294           redeclare_class_template (TREE_TYPE (decl),
4295                                     current_template_parms);
4296           /* We don't need to create a new TEMPLATE_DECL; just use the
4297              one we already had.  */
4298           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4299         }
4300       else
4301         {
4302           tmpl = build_template_decl (decl, current_template_parms,
4303                                       member_template_p);
4304           new_template_p = 1;
4305
4306           if (DECL_LANG_SPECIFIC (decl)
4307               && DECL_TEMPLATE_SPECIALIZATION (decl))
4308             {
4309               /* A specialization of a member template of a template
4310                  class.  */
4311               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4312               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4313               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4314             }
4315         }
4316     }
4317   else
4318     {
4319       tree a, t, current, parms;
4320       int i;
4321       tree tinfo = get_template_info (decl);
4322
4323       if (!tinfo)
4324         {
4325           error ("template definition of non-template %q#D", decl);
4326           return error_mark_node;
4327         }
4328
4329       tmpl = TI_TEMPLATE (tinfo);
4330
4331       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4332           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4333           && DECL_TEMPLATE_SPECIALIZATION (decl)
4334           && DECL_MEMBER_TEMPLATE_P (tmpl))
4335         {
4336           tree new_tmpl;
4337
4338           /* The declaration is a specialization of a member
4339              template, declared outside the class.  Therefore, the
4340              innermost template arguments will be NULL, so we
4341              replace them with the arguments determined by the
4342              earlier call to check_explicit_specialization.  */
4343           args = DECL_TI_ARGS (decl);
4344
4345           new_tmpl
4346             = build_template_decl (decl, current_template_parms,
4347                                    member_template_p);
4348           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4349           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4350           DECL_TI_TEMPLATE (decl) = new_tmpl;
4351           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4352           DECL_TEMPLATE_INFO (new_tmpl)
4353             = tree_cons (tmpl, args, NULL_TREE);
4354
4355           register_specialization (new_tmpl,
4356                                    most_general_template (tmpl),
4357                                    args,
4358                                    is_friend, 0);
4359           return decl;
4360         }
4361
4362       /* Make sure the template headers we got make sense.  */
4363
4364       parms = DECL_TEMPLATE_PARMS (tmpl);
4365       i = TMPL_PARMS_DEPTH (parms);
4366       if (TMPL_ARGS_DEPTH (args) != i)
4367         {
4368           error ("expected %d levels of template parms for %q#D, got %d",
4369                  i, decl, TMPL_ARGS_DEPTH (args));
4370         }
4371       else
4372         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4373           {
4374             a = TMPL_ARGS_LEVEL (args, i);
4375             t = INNERMOST_TEMPLATE_PARMS (parms);
4376
4377             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4378               {
4379                 if (current == decl)
4380                   error ("got %d template parameters for %q#D",
4381                          TREE_VEC_LENGTH (a), decl);
4382                 else
4383                   error ("got %d template parameters for %q#T",
4384                          TREE_VEC_LENGTH (a), current);
4385                 error ("  but %d required", TREE_VEC_LENGTH (t));
4386                 return error_mark_node;
4387               }
4388
4389             if (current == decl)
4390               current = ctx;
4391             else
4392               current = (TYPE_P (current)
4393                          ? TYPE_CONTEXT (current)
4394                          : DECL_CONTEXT (current));
4395           }
4396
4397       /* Check that the parms are used in the appropriate qualifying scopes
4398          in the declarator.  */
4399       if (!comp_template_args
4400           (TI_ARGS (tinfo),
4401            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4402         {
4403           error ("\
4404 template arguments to %qD do not match original template %qD",
4405                  decl, DECL_TEMPLATE_RESULT (tmpl));
4406           if (!uses_template_parms (TI_ARGS (tinfo)))
4407             inform (input_location, "use template<> for an explicit specialization");
4408           /* Avoid crash in import_export_decl.  */
4409           DECL_INTERFACE_KNOWN (decl) = 1;
4410           return error_mark_node;
4411         }
4412     }
4413
4414   DECL_TEMPLATE_RESULT (tmpl) = decl;
4415   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4416
4417   /* Push template declarations for global functions and types.  Note
4418      that we do not try to push a global template friend declared in a
4419      template class; such a thing may well depend on the template
4420      parameters of the class.  */
4421   if (new_template_p && !ctx
4422       && !(is_friend && template_class_depth (current_class_type) > 0))
4423     {
4424       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4425       if (tmpl == error_mark_node)
4426         return error_mark_node;
4427
4428       /* Hide template friend classes that haven't been declared yet.  */
4429       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4430         {
4431           DECL_ANTICIPATED (tmpl) = 1;
4432           DECL_FRIEND_P (tmpl) = 1;
4433         }
4434     }
4435
4436   if (primary)
4437     {
4438       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4439       int i;
4440
4441       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4442       if (DECL_CONV_FN_P (tmpl))
4443         {
4444           int depth = TMPL_PARMS_DEPTH (parms);
4445
4446           /* It is a conversion operator. See if the type converted to
4447              depends on innermost template operands.  */
4448
4449           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4450                                          depth))
4451             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4452         }
4453
4454       /* Give template template parms a DECL_CONTEXT of the template
4455          for which they are a parameter.  */
4456       parms = INNERMOST_TEMPLATE_PARMS (parms);
4457       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4458         {
4459           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4460           if (TREE_CODE (parm) == TEMPLATE_DECL)
4461             DECL_CONTEXT (parm) = tmpl;
4462         }
4463     }
4464
4465   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4466      back to its most general template.  If TMPL is a specialization,
4467      ARGS may only have the innermost set of arguments.  Add the missing
4468      argument levels if necessary.  */
4469   if (DECL_TEMPLATE_INFO (tmpl))
4470     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4471
4472   info = tree_cons (tmpl, args, NULL_TREE);
4473
4474   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4475     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4476   else if (DECL_LANG_SPECIFIC (decl))
4477     DECL_TEMPLATE_INFO (decl) = info;
4478
4479   return DECL_TEMPLATE_RESULT (tmpl);
4480 }
4481
4482 tree
4483 push_template_decl (tree decl)
4484 {
4485   return push_template_decl_real (decl, false);
4486 }
4487
4488 /* Called when a class template TYPE is redeclared with the indicated
4489    template PARMS, e.g.:
4490
4491      template <class T> struct S;
4492      template <class T> struct S {};  */
4493
4494 bool
4495 redeclare_class_template (tree type, tree parms)
4496 {
4497   tree tmpl;
4498   tree tmpl_parms;
4499   int i;
4500
4501   if (!TYPE_TEMPLATE_INFO (type))
4502     {
4503       error ("%qT is not a template type", type);
4504       return false;
4505     }
4506
4507   tmpl = TYPE_TI_TEMPLATE (type);
4508   if (!PRIMARY_TEMPLATE_P (tmpl))
4509     /* The type is nested in some template class.  Nothing to worry
4510        about here; there are no new template parameters for the nested
4511        type.  */
4512     return true;
4513
4514   if (!parms)
4515     {
4516       error ("template specifiers not specified in declaration of %qD",
4517              tmpl);
4518       return false;
4519     }
4520
4521   parms = INNERMOST_TEMPLATE_PARMS (parms);
4522   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4523
4524   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4525     {
4526       error ("redeclared with %d template parameter(s)", 
4527              TREE_VEC_LENGTH (parms));
4528       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4529              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4530       return false;
4531     }
4532
4533   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4534     {
4535       tree tmpl_parm;
4536       tree parm;
4537       tree tmpl_default;
4538       tree parm_default;
4539
4540       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4541           || TREE_VEC_ELT (parms, i) == error_mark_node)
4542         continue;
4543
4544       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4545       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4546       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4547       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4548
4549       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4550          TEMPLATE_DECL.  */
4551       if (tmpl_parm != error_mark_node
4552           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4553               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4554                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4555               || (TREE_CODE (tmpl_parm) != PARM_DECL
4556                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4557                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4558               || (TREE_CODE (tmpl_parm) == PARM_DECL
4559                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4560                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4561         {
4562           error ("template parameter %q+#D", tmpl_parm);
4563           error ("redeclared here as %q#D", parm);
4564           return false;
4565         }
4566
4567       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4568         {
4569           /* We have in [temp.param]:
4570
4571              A template-parameter may not be given default arguments
4572              by two different declarations in the same scope.  */
4573           error_at (input_location, "redefinition of default argument for %q#D", parm);
4574           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4575                   "original definition appeared here");
4576           return false;
4577         }
4578
4579       if (parm_default != NULL_TREE)
4580         /* Update the previous template parameters (which are the ones
4581            that will really count) with the new default value.  */
4582         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4583       else if (tmpl_default != NULL_TREE)
4584         /* Update the new parameters, too; they'll be used as the
4585            parameters for any members.  */
4586         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4587     }
4588
4589     return true;
4590 }
4591
4592 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4593    (possibly simplified) expression.  */
4594
4595 tree
4596 fold_non_dependent_expr (tree expr)
4597 {
4598   if (expr == NULL_TREE)
4599     return NULL_TREE;
4600
4601   /* If we're in a template, but EXPR isn't value dependent, simplify
4602      it.  We're supposed to treat:
4603
4604        template <typename T> void f(T[1 + 1]);
4605        template <typename T> void f(T[2]);
4606
4607      as two declarations of the same function, for example.  */
4608   if (processing_template_decl
4609       && !type_dependent_expression_p (expr)
4610       && !value_dependent_expression_p (expr))
4611     {
4612       HOST_WIDE_INT saved_processing_template_decl;
4613
4614       saved_processing_template_decl = processing_template_decl;
4615       processing_template_decl = 0;
4616       expr = tsubst_copy_and_build (expr,
4617                                     /*args=*/NULL_TREE,
4618                                     tf_error,
4619                                     /*in_decl=*/NULL_TREE,
4620                                     /*function_p=*/false,
4621                                     /*integral_constant_expression_p=*/true);
4622       processing_template_decl = saved_processing_template_decl;
4623     }
4624   return expr;
4625 }
4626
4627 /* EXPR is an expression which is used in a constant-expression context.
4628    For instance, it could be a VAR_DECL with a constant initializer.
4629    Extract the innermost constant expression.
4630
4631    This is basically a more powerful version of
4632    integral_constant_value, which can be used also in templates where
4633    initializers can maintain a syntactic rather than semantic form
4634    (even if they are non-dependent, for access-checking purposes).  */
4635
4636 static tree
4637 fold_decl_constant_value (tree expr)
4638 {
4639   tree const_expr = expr;
4640   do
4641     {
4642       expr = fold_non_dependent_expr (const_expr);
4643       const_expr = integral_constant_value (expr);
4644     }
4645   while (expr != const_expr);
4646
4647   return expr;
4648 }
4649
4650 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4651    must be a function or a pointer-to-function type, as specified
4652    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4653    and check that the resulting function has external linkage.  */
4654
4655 static tree
4656 convert_nontype_argument_function (tree type, tree expr)
4657 {
4658   tree fns = expr;
4659   tree fn, fn_no_ptr;
4660
4661   fn = instantiate_type (type, fns, tf_none);
4662   if (fn == error_mark_node)
4663     return error_mark_node;
4664
4665   fn_no_ptr = fn;
4666   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4667     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4668   if (TREE_CODE (fn_no_ptr) == BASELINK)
4669     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4670  
4671   /* [temp.arg.nontype]/1
4672
4673      A template-argument for a non-type, non-template template-parameter
4674      shall be one of:
4675      [...]
4676      -- the address of an object or function with external linkage.  */
4677   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4678     {
4679       error ("%qE is not a valid template argument for type %qT "
4680              "because function %qD has not external linkage",
4681              expr, type, fn_no_ptr);
4682       return NULL_TREE;
4683     }
4684
4685   return fn;
4686 }
4687
4688 /* Subroutine of convert_nontype_argument.
4689    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4690    Emit an error otherwise.  */
4691
4692 static bool
4693 check_valid_ptrmem_cst_expr (tree type, tree expr)
4694 {
4695   STRIP_NOPS (expr);
4696   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4697     return true;
4698   error ("%qE is not a valid template argument for type %qT",
4699          expr, type);
4700   error ("it must be a pointer-to-member of the form `&X::Y'");
4701   return false;
4702 }
4703
4704 /* Attempt to convert the non-type template parameter EXPR to the
4705    indicated TYPE.  If the conversion is successful, return the
4706    converted value.  If the conversion is unsuccessful, return
4707    NULL_TREE if we issued an error message, or error_mark_node if we
4708    did not.  We issue error messages for out-and-out bad template
4709    parameters, but not simply because the conversion failed, since we
4710    might be just trying to do argument deduction.  Both TYPE and EXPR
4711    must be non-dependent.
4712
4713    The conversion follows the special rules described in
4714    [temp.arg.nontype], and it is much more strict than an implicit
4715    conversion.
4716
4717    This function is called twice for each template argument (see
4718    lookup_template_class for a more accurate description of this
4719    problem). This means that we need to handle expressions which
4720    are not valid in a C++ source, but can be created from the
4721    first call (for instance, casts to perform conversions). These
4722    hacks can go away after we fix the double coercion problem.  */
4723
4724 static tree
4725 convert_nontype_argument (tree type, tree expr)
4726 {
4727   tree expr_type;
4728
4729   /* Detect immediately string literals as invalid non-type argument.
4730      This special-case is not needed for correctness (we would easily
4731      catch this later), but only to provide better diagnostic for this
4732      common user mistake. As suggested by DR 100, we do not mention
4733      linkage issues in the diagnostic as this is not the point.  */
4734   if (TREE_CODE (expr) == STRING_CST)
4735     {
4736       error ("%qE is not a valid template argument for type %qT "
4737              "because string literals can never be used in this context",
4738              expr, type);
4739       return NULL_TREE;
4740     }
4741
4742   /* If we are in a template, EXPR may be non-dependent, but still
4743      have a syntactic, rather than semantic, form.  For example, EXPR
4744      might be a SCOPE_REF, rather than the VAR_DECL to which the
4745      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4746      so that access checking can be performed when the template is
4747      instantiated -- but here we need the resolved form so that we can
4748      convert the argument.  */
4749   expr = fold_non_dependent_expr (expr);
4750   if (error_operand_p (expr))
4751     return error_mark_node;
4752   expr_type = TREE_TYPE (expr);
4753
4754   /* HACK: Due to double coercion, we can get a
4755      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4756      which is the tree that we built on the first call (see
4757      below when coercing to reference to object or to reference to
4758      function). We just strip everything and get to the arg.
4759      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4760      for examples.  */
4761   if (TREE_CODE (expr) == NOP_EXPR)
4762     {
4763       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4764         {
4765           /* ??? Maybe we could use convert_from_reference here, but we
4766              would need to relax its constraints because the NOP_EXPR
4767              could actually change the type to something more cv-qualified,
4768              and this is not folded by convert_from_reference.  */
4769           tree addr = TREE_OPERAND (expr, 0);
4770           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4771           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4772           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4773           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4774                       (TREE_TYPE (expr_type),
4775                        TREE_TYPE (TREE_TYPE (addr))));
4776
4777           expr = TREE_OPERAND (addr, 0);
4778           expr_type = TREE_TYPE (expr);
4779         }
4780
4781       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4782          parameter is a pointer to object, through decay and
4783          qualification conversion. Let's strip everything.  */
4784       else if (TYPE_PTROBV_P (type))
4785         {
4786           STRIP_NOPS (expr);
4787           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4788           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4789           /* Skip the ADDR_EXPR only if it is part of the decay for
4790              an array. Otherwise, it is part of the original argument
4791              in the source code.  */
4792           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4793             expr = TREE_OPERAND (expr, 0);
4794           expr_type = TREE_TYPE (expr);
4795         }
4796     }
4797
4798   /* [temp.arg.nontype]/5, bullet 1
4799
4800      For a non-type template-parameter of integral or enumeration type,
4801      integral promotions (_conv.prom_) and integral conversions
4802      (_conv.integral_) are applied.  */
4803   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4804     {
4805       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4806         return error_mark_node;
4807
4808       expr = fold_decl_constant_value (expr);
4809       /* Notice that there are constant expressions like '4 % 0' which
4810          do not fold into integer constants.  */
4811       if (TREE_CODE (expr) != INTEGER_CST)
4812         {
4813           error ("%qE is not a valid template argument for type %qT "
4814                  "because it is a non-constant expression", expr, type);
4815           return NULL_TREE;
4816         }
4817
4818       /* At this point, an implicit conversion does what we want,
4819          because we already know that the expression is of integral
4820          type.  */
4821       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4822       if (expr == error_mark_node)
4823         return error_mark_node;
4824
4825       /* Conversion was allowed: fold it to a bare integer constant.  */
4826       expr = fold (expr);
4827     }
4828   /* [temp.arg.nontype]/5, bullet 2
4829
4830      For a non-type template-parameter of type pointer to object,
4831      qualification conversions (_conv.qual_) and the array-to-pointer
4832      conversion (_conv.array_) are applied.  */
4833   else if (TYPE_PTROBV_P (type))
4834     {
4835       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4836
4837          A template-argument for a non-type, non-template template-parameter
4838          shall be one of: [...]
4839
4840          -- the name of a non-type template-parameter;
4841          -- the address of an object or function with external linkage, [...]
4842             expressed as "& id-expression" where the & is optional if the name
4843             refers to a function or array, or if the corresponding
4844             template-parameter is a reference.
4845
4846         Here, we do not care about functions, as they are invalid anyway
4847         for a parameter of type pointer-to-object.  */
4848
4849       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4850         /* Non-type template parameters are OK.  */
4851         ;
4852       else if (TREE_CODE (expr) != ADDR_EXPR
4853                && TREE_CODE (expr_type) != ARRAY_TYPE)
4854         {
4855           if (TREE_CODE (expr) == VAR_DECL)
4856             {
4857               error ("%qD is not a valid template argument "
4858                      "because %qD is a variable, not the address of "
4859                      "a variable",
4860                      expr, expr);
4861               return NULL_TREE;
4862             }
4863           /* Other values, like integer constants, might be valid
4864              non-type arguments of some other type.  */
4865           return error_mark_node;
4866         }
4867       else
4868         {
4869           tree decl;
4870
4871           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4872                   ? TREE_OPERAND (expr, 0) : expr);
4873           if (TREE_CODE (decl) != VAR_DECL)
4874             {
4875               error ("%qE is not a valid template argument of type %qT "
4876                      "because %qE is not a variable",
4877                      expr, type, decl);
4878               return NULL_TREE;
4879             }
4880           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4881             {
4882               error ("%qE is not a valid template argument of type %qT "
4883                      "because %qD does not have external linkage",
4884                      expr, type, decl);
4885               return NULL_TREE;
4886             }
4887         }
4888
4889       expr = decay_conversion (expr);
4890       if (expr == error_mark_node)
4891         return error_mark_node;
4892
4893       expr = perform_qualification_conversions (type, expr);
4894       if (expr == error_mark_node)
4895         return error_mark_node;
4896     }
4897   /* [temp.arg.nontype]/5, bullet 3
4898
4899      For a non-type template-parameter of type reference to object, no
4900      conversions apply. The type referred to by the reference may be more
4901      cv-qualified than the (otherwise identical) type of the
4902      template-argument. The template-parameter is bound directly to the
4903      template-argument, which must be an lvalue.  */
4904   else if (TYPE_REF_OBJ_P (type))
4905     {
4906       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4907                                                       expr_type))
4908         return error_mark_node;
4909
4910       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4911         {
4912           error ("%qE is not a valid template argument for type %qT "
4913                  "because of conflicts in cv-qualification", expr, type);
4914           return NULL_TREE;
4915         }
4916
4917       if (!real_lvalue_p (expr))
4918         {
4919           error ("%qE is not a valid template argument for type %qT "
4920                  "because it is not an lvalue", expr, type);
4921           return NULL_TREE;
4922         }
4923
4924       /* [temp.arg.nontype]/1
4925
4926          A template-argument for a non-type, non-template template-parameter
4927          shall be one of: [...]
4928
4929          -- the address of an object or function with external linkage.  */
4930       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4931         {
4932           error ("%qE is not a valid template argument for type %qT "
4933                  "because object %qD has not external linkage",
4934                  expr, type, expr);
4935           return NULL_TREE;
4936         }
4937
4938       expr = build_nop (type, build_address (expr));
4939     }
4940   /* [temp.arg.nontype]/5, bullet 4
4941
4942      For a non-type template-parameter of type pointer to function, only
4943      the function-to-pointer conversion (_conv.func_) is applied. If the
4944      template-argument represents a set of overloaded functions (or a
4945      pointer to such), the matching function is selected from the set
4946      (_over.over_).  */
4947   else if (TYPE_PTRFN_P (type))
4948     {
4949       /* If the argument is a template-id, we might not have enough
4950          context information to decay the pointer.  */
4951       if (!type_unknown_p (expr_type))
4952         {
4953           expr = decay_conversion (expr);
4954           if (expr == error_mark_node)
4955             return error_mark_node;
4956         }
4957
4958       expr = convert_nontype_argument_function (type, expr);
4959       if (!expr || expr == error_mark_node)
4960         return expr;
4961
4962       if (TREE_CODE (expr) != ADDR_EXPR)
4963         {
4964           error ("%qE is not a valid template argument for type %qT", expr, type);
4965           error ("it must be the address of a function with external linkage");
4966           return NULL_TREE;
4967         }
4968     }
4969   /* [temp.arg.nontype]/5, bullet 5
4970
4971      For a non-type template-parameter of type reference to function, no
4972      conversions apply. If the template-argument represents a set of
4973      overloaded functions, the matching function is selected from the set
4974      (_over.over_).  */
4975   else if (TYPE_REFFN_P (type))
4976     {
4977       if (TREE_CODE (expr) == ADDR_EXPR)
4978         {
4979           error ("%qE is not a valid template argument for type %qT "
4980                  "because it is a pointer", expr, type);
4981           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
4982           return NULL_TREE;
4983         }
4984
4985       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4986       if (!expr || expr == error_mark_node)
4987         return expr;
4988
4989       expr = build_nop (type, build_address (expr));
4990     }
4991   /* [temp.arg.nontype]/5, bullet 6
4992
4993      For a non-type template-parameter of type pointer to member function,
4994      no conversions apply. If the template-argument represents a set of
4995      overloaded member functions, the matching member function is selected
4996      from the set (_over.over_).  */
4997   else if (TYPE_PTRMEMFUNC_P (type))
4998     {
4999       expr = instantiate_type (type, expr, tf_none);
5000       if (expr == error_mark_node)
5001         return error_mark_node;
5002
5003       /* [temp.arg.nontype] bullet 1 says the pointer to member
5004          expression must be a pointer-to-member constant.  */
5005       if (!check_valid_ptrmem_cst_expr (type, expr))
5006         return error_mark_node;
5007
5008       /* There is no way to disable standard conversions in
5009          resolve_address_of_overloaded_function (called by
5010          instantiate_type). It is possible that the call succeeded by
5011          converting &B::I to &D::I (where B is a base of D), so we need
5012          to reject this conversion here.
5013
5014          Actually, even if there was a way to disable standard conversions,
5015          it would still be better to reject them here so that we can
5016          provide a superior diagnostic.  */
5017       if (!same_type_p (TREE_TYPE (expr), type))
5018         {
5019           /* Make sure we are just one standard conversion off.  */
5020           gcc_assert (can_convert (type, TREE_TYPE (expr)));
5021           error ("%qE is not a valid template argument for type %qT "
5022                  "because it is of type %qT", expr, type,
5023                  TREE_TYPE (expr));
5024           inform (input_location, "standard conversions are not allowed in this context");
5025           return NULL_TREE;
5026         }
5027     }
5028   /* [temp.arg.nontype]/5, bullet 7
5029
5030      For a non-type template-parameter of type pointer to data member,
5031      qualification conversions (_conv.qual_) are applied.  */
5032   else if (TYPE_PTRMEM_P (type))
5033     {
5034       /* [temp.arg.nontype] bullet 1 says the pointer to member
5035          expression must be a pointer-to-member constant.  */
5036       if (!check_valid_ptrmem_cst_expr (type, expr))
5037         return error_mark_node;
5038
5039       expr = perform_qualification_conversions (type, expr);
5040       if (expr == error_mark_node)
5041         return expr;
5042     }
5043   /* A template non-type parameter must be one of the above.  */
5044   else
5045     gcc_unreachable ();
5046
5047   /* Sanity check: did we actually convert the argument to the
5048      right type?  */
5049   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5050   return expr;
5051 }
5052
5053 /* Subroutine of coerce_template_template_parms, which returns 1 if
5054    PARM_PARM and ARG_PARM match using the rule for the template
5055    parameters of template template parameters. Both PARM and ARG are
5056    template parameters; the rest of the arguments are the same as for
5057    coerce_template_template_parms.
5058  */
5059 static int
5060 coerce_template_template_parm (tree parm,
5061                               tree arg,
5062                               tsubst_flags_t complain,
5063                               tree in_decl,
5064                               tree outer_args)
5065 {
5066   if (arg == NULL_TREE || arg == error_mark_node
5067       || parm == NULL_TREE || parm == error_mark_node)
5068     return 0;
5069   
5070   if (TREE_CODE (arg) != TREE_CODE (parm))
5071     return 0;
5072   
5073   switch (TREE_CODE (parm))
5074     {
5075     case TEMPLATE_DECL:
5076       /* We encounter instantiations of templates like
5077          template <template <template <class> class> class TT>
5078          class C;  */
5079       {
5080         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5081         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5082         
5083         if (!coerce_template_template_parms
5084             (parmparm, argparm, complain, in_decl, outer_args))
5085           return 0;
5086       }
5087       /* Fall through.  */
5088       
5089     case TYPE_DECL:
5090       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5091           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5092         /* Argument is a parameter pack but parameter is not.  */
5093         return 0;
5094       break;
5095       
5096     case PARM_DECL:
5097       /* The tsubst call is used to handle cases such as
5098          
5099            template <int> class C {};
5100            template <class T, template <T> class TT> class D {};
5101            D<int, C> d;
5102
5103          i.e. the parameter list of TT depends on earlier parameters.  */
5104       if (!uses_template_parms (TREE_TYPE (arg))
5105           && !same_type_p
5106                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5107                  TREE_TYPE (arg)))
5108         return 0;
5109       
5110       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5111           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5112         /* Argument is a parameter pack but parameter is not.  */
5113         return 0;
5114       
5115       break;
5116
5117     default:
5118       gcc_unreachable ();
5119     }
5120
5121   return 1;
5122 }
5123
5124
5125 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5126    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5127    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5128    or PARM_DECL.
5129
5130    Consider the example:
5131      template <class T> class A;
5132      template<template <class U> class TT> class B;
5133
5134    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5135    the parameters to A, and OUTER_ARGS contains A.  */
5136
5137 static int
5138 coerce_template_template_parms (tree parm_parms,
5139                                 tree arg_parms,
5140                                 tsubst_flags_t complain,
5141                                 tree in_decl,
5142                                 tree outer_args)
5143 {
5144   int nparms, nargs, i;
5145   tree parm, arg;
5146   int variadic_p = 0;
5147
5148   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5149   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5150
5151   nparms = TREE_VEC_LENGTH (parm_parms);
5152   nargs = TREE_VEC_LENGTH (arg_parms);
5153
5154   /* Determine whether we have a parameter pack at the end of the
5155      template template parameter's template parameter list.  */
5156   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5157     {
5158       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5159       
5160       if (parm == error_mark_node)
5161         return 0;
5162
5163       switch (TREE_CODE (parm))
5164         {
5165         case TEMPLATE_DECL:
5166         case TYPE_DECL:
5167           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5168             variadic_p = 1;
5169           break;
5170           
5171         case PARM_DECL:
5172           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5173             variadic_p = 1;
5174           break;
5175           
5176         default:
5177           gcc_unreachable ();
5178         }
5179     }
5180  
5181   if (nargs != nparms
5182       && !(variadic_p && nargs >= nparms - 1))
5183     return 0;
5184
5185   /* Check all of the template parameters except the parameter pack at
5186      the end (if any).  */
5187   for (i = 0; i < nparms - variadic_p; ++i)
5188     {
5189       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5190           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5191         continue;
5192
5193       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5194       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5195
5196       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5197                                           outer_args))
5198         return 0;
5199
5200     }
5201
5202   if (variadic_p)
5203     {
5204       /* Check each of the template parameters in the template
5205          argument against the template parameter pack at the end of
5206          the template template parameter.  */
5207       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5208         return 0;
5209
5210       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5211
5212       for (; i < nargs; ++i)
5213         {
5214           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5215             continue;
5216  
5217           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5218  
5219           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5220                                               outer_args))
5221             return 0;
5222         }
5223     }
5224
5225   return 1;
5226 }
5227
5228 /* Verifies that the deduced template arguments (in TARGS) for the
5229    template template parameters (in TPARMS) represent valid bindings,
5230    by comparing the template parameter list of each template argument
5231    to the template parameter list of its corresponding template
5232    template parameter, in accordance with DR150. This
5233    routine can only be called after all template arguments have been
5234    deduced. It will return TRUE if all of the template template
5235    parameter bindings are okay, FALSE otherwise.  */
5236 bool 
5237 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5238 {
5239   int i, ntparms = TREE_VEC_LENGTH (tparms);
5240   bool ret = true;
5241
5242   /* We're dealing with template parms in this process.  */
5243   ++processing_template_decl;
5244
5245   targs = INNERMOST_TEMPLATE_ARGS (targs);
5246
5247   for (i = 0; i < ntparms; ++i)
5248     {
5249       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5250       tree targ = TREE_VEC_ELT (targs, i);
5251
5252       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5253         {
5254           tree packed_args = NULL_TREE;
5255           int idx, len = 1;
5256
5257           if (ARGUMENT_PACK_P (targ))
5258             {
5259               /* Look inside the argument pack.  */
5260               packed_args = ARGUMENT_PACK_ARGS (targ);
5261               len = TREE_VEC_LENGTH (packed_args);
5262             }
5263
5264           for (idx = 0; idx < len; ++idx)
5265             {
5266               tree targ_parms = NULL_TREE;
5267
5268               if (packed_args)
5269                 /* Extract the next argument from the argument
5270                    pack.  */
5271                 targ = TREE_VEC_ELT (packed_args, idx);
5272
5273               if (PACK_EXPANSION_P (targ))
5274                 /* Look at the pattern of the pack expansion.  */
5275                 targ = PACK_EXPANSION_PATTERN (targ);
5276
5277               /* Extract the template parameters from the template
5278                  argument.  */
5279               if (TREE_CODE (targ) == TEMPLATE_DECL)
5280                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5281               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5282                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5283
5284               /* Verify that we can coerce the template template
5285                  parameters from the template argument to the template
5286                  parameter.  This requires an exact match.  */
5287               if (targ_parms
5288                   && !coerce_template_template_parms
5289                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5290                         targ_parms,
5291                         tf_none,
5292                         tparm,
5293                         targs))
5294                 {
5295                   ret = false;
5296                   goto out;
5297                 }
5298             }
5299         }
5300     }
5301
5302  out:
5303
5304   --processing_template_decl;
5305   return ret;
5306 }
5307
5308 /* Convert the indicated template ARG as necessary to match the
5309    indicated template PARM.  Returns the converted ARG, or
5310    error_mark_node if the conversion was unsuccessful.  Error and
5311    warning messages are issued under control of COMPLAIN.  This
5312    conversion is for the Ith parameter in the parameter list.  ARGS is
5313    the full set of template arguments deduced so far.  */
5314
5315 static tree
5316 convert_template_argument (tree parm,
5317                            tree arg,
5318                            tree args,
5319                            tsubst_flags_t complain,
5320                            int i,
5321                            tree in_decl)
5322 {
5323   tree orig_arg;
5324   tree val;
5325   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5326
5327   if (TREE_CODE (arg) == TREE_LIST
5328       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5329     {
5330       /* The template argument was the name of some
5331          member function.  That's usually
5332          invalid, but static members are OK.  In any
5333          case, grab the underlying fields/functions
5334          and issue an error later if required.  */
5335       orig_arg = TREE_VALUE (arg);
5336       TREE_TYPE (arg) = unknown_type_node;
5337     }
5338
5339   orig_arg = arg;
5340
5341   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5342   requires_type = (TREE_CODE (parm) == TYPE_DECL
5343                    || requires_tmpl_type);
5344
5345   /* When determining whether an argument pack expansion is a template,
5346      look at the pattern.  */
5347   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5348     arg = PACK_EXPANSION_PATTERN (arg);
5349
5350   is_tmpl_type = 
5351     ((TREE_CODE (arg) == TEMPLATE_DECL
5352       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5353      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5354      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5355
5356   if (is_tmpl_type
5357       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5358           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5359     arg = TYPE_STUB_DECL (arg);
5360
5361   is_type = TYPE_P (arg) || is_tmpl_type;
5362
5363   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5364       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5365     {
5366       permerror (input_location, "to refer to a type member of a template parameter, "
5367                  "use %<typename %E%>", orig_arg);
5368
5369       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5370                                      TREE_OPERAND (arg, 1),
5371                                      typename_type,
5372                                      complain & tf_error);
5373       arg = orig_arg;
5374       is_type = 1;
5375     }
5376   if (is_type != requires_type)
5377     {
5378       if (in_decl)
5379         {
5380           if (complain & tf_error)
5381             {
5382               error ("type/value mismatch at argument %d in template "
5383                      "parameter list for %qD",
5384                      i + 1, in_decl);
5385               if (is_type)
5386                 error ("  expected a constant of type %qT, got %qT",
5387                        TREE_TYPE (parm),
5388                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5389               else if (requires_tmpl_type)
5390                 error ("  expected a class template, got %qE", orig_arg);
5391               else
5392                 error ("  expected a type, got %qE", orig_arg);
5393             }
5394         }
5395       return error_mark_node;
5396     }
5397   if (is_tmpl_type ^ requires_tmpl_type)
5398     {
5399       if (in_decl && (complain & tf_error))
5400         {
5401           error ("type/value mismatch at argument %d in template "
5402                  "parameter list for %qD",
5403                  i + 1, in_decl);
5404           if (is_tmpl_type)
5405             error ("  expected a type, got %qT", DECL_NAME (arg));
5406           else
5407             error ("  expected a class template, got %qT", orig_arg);
5408         }
5409       return error_mark_node;
5410     }
5411
5412   if (is_type)
5413     {
5414       if (requires_tmpl_type)
5415         {
5416           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5417             /* The number of argument required is not known yet.
5418                Just accept it for now.  */
5419             val = TREE_TYPE (arg);
5420           else
5421             {
5422               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5423               tree argparm;
5424
5425               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5426
5427               if (coerce_template_template_parms (parmparm, argparm,
5428                                                   complain, in_decl,
5429                                                   args))
5430                 {
5431                   val = orig_arg;
5432
5433                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5434                      TEMPLATE_DECL.  */
5435                   if (val != error_mark_node)
5436                     {
5437                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5438                         val = TREE_TYPE (val);
5439                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
5440                                && DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
5441                         {
5442                           val = TREE_TYPE (arg);
5443                           val = make_pack_expansion (val);
5444                         }
5445                     }
5446                 }
5447               else
5448                 {
5449                   if (in_decl && (complain & tf_error))
5450                     {
5451                       error ("type/value mismatch at argument %d in "
5452                              "template parameter list for %qD",
5453                              i + 1, in_decl);
5454                       error ("  expected a template of type %qD, got %qD",
5455                              parm, orig_arg);
5456                     }
5457
5458                   val = error_mark_node;
5459                 }
5460             }
5461         }
5462       else
5463         val = orig_arg;
5464       /* We only form one instance of each template specialization.
5465          Therefore, if we use a non-canonical variant (i.e., a
5466          typedef), any future messages referring to the type will use
5467          the typedef, which is confusing if those future uses do not
5468          themselves also use the typedef.  */
5469       if (TYPE_P (val))
5470         val = strip_typedefs (val);
5471     }
5472   else
5473     {
5474       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5475
5476       if (invalid_nontype_parm_type_p (t, complain))
5477         return error_mark_node;
5478
5479       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5480         {
5481           if (same_type_p (t, TREE_TYPE (orig_arg)))
5482             val = orig_arg;
5483           else
5484             {
5485               /* Not sure if this is reachable, but it doesn't hurt
5486                  to be robust.  */
5487               error ("type mismatch in nontype parameter pack");
5488               val = error_mark_node;
5489             }
5490         }
5491       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5492         /* We used to call digest_init here.  However, digest_init
5493            will report errors, which we don't want when complain
5494            is zero.  More importantly, digest_init will try too
5495            hard to convert things: for example, `0' should not be
5496            converted to pointer type at this point according to
5497            the standard.  Accepting this is not merely an
5498            extension, since deciding whether or not these
5499            conversions can occur is part of determining which
5500            function template to call, or whether a given explicit
5501            argument specification is valid.  */
5502         val = convert_nontype_argument (t, orig_arg);
5503       else
5504         val = orig_arg;
5505
5506       if (val == NULL_TREE)
5507         val = error_mark_node;
5508       else if (val == error_mark_node && (complain & tf_error))
5509         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5510     }
5511
5512   return val;
5513 }
5514
5515 /* Coerces the remaining template arguments in INNER_ARGS (from
5516    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5517    Returns the coerced argument pack. PARM_IDX is the position of this
5518    parameter in the template parameter list. ARGS is the original
5519    template argument list.  */
5520 static tree
5521 coerce_template_parameter_pack (tree parms,
5522                                 int parm_idx,
5523                                 tree args,
5524                                 tree inner_args,
5525                                 int arg_idx,
5526                                 tree new_args,
5527                                 int* lost,
5528                                 tree in_decl,
5529                                 tsubst_flags_t complain)
5530 {
5531   tree parm = TREE_VEC_ELT (parms, parm_idx);
5532   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5533   tree packed_args;
5534   tree argument_pack;
5535   tree packed_types = NULL_TREE;
5536
5537   if (arg_idx > nargs)
5538     arg_idx = nargs;
5539
5540   packed_args = make_tree_vec (nargs - arg_idx);
5541
5542   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5543       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5544     {
5545       /* When the template parameter is a non-type template
5546          parameter pack whose type uses parameter packs, we need
5547          to look at each of the template arguments
5548          separately. Build a vector of the types for these
5549          non-type template parameters in PACKED_TYPES.  */
5550       tree expansion 
5551         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5552       packed_types = tsubst_pack_expansion (expansion, args,
5553                                             complain, in_decl);
5554
5555       if (packed_types == error_mark_node)
5556         return error_mark_node;
5557
5558       /* Check that we have the right number of arguments.  */
5559       if (arg_idx < nargs
5560           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5561           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5562         {
5563           int needed_parms 
5564             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5565           error ("wrong number of template arguments (%d, should be %d)",
5566                  nargs, needed_parms);
5567           return error_mark_node;
5568         }
5569
5570       /* If we aren't able to check the actual arguments now
5571          (because they haven't been expanded yet), we can at least
5572          verify that all of the types used for the non-type
5573          template parameter pack are, in fact, valid for non-type
5574          template parameters.  */
5575       if (arg_idx < nargs 
5576           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5577         {
5578           int j, len = TREE_VEC_LENGTH (packed_types);
5579           for (j = 0; j < len; ++j)
5580             {
5581               tree t = TREE_VEC_ELT (packed_types, j);
5582               if (invalid_nontype_parm_type_p (t, complain))
5583                 return error_mark_node;
5584             }
5585         }
5586     }
5587
5588   /* Convert the remaining arguments, which will be a part of the
5589      parameter pack "parm".  */
5590   for (; arg_idx < nargs; ++arg_idx)
5591     {
5592       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5593       tree actual_parm = TREE_VALUE (parm);
5594
5595       if (packed_types && !PACK_EXPANSION_P (arg))
5596         {
5597           /* When we have a vector of types (corresponding to the
5598              non-type template parameter pack that uses parameter
5599              packs in its type, as mention above), and the
5600              argument is not an expansion (which expands to a
5601              currently unknown number of arguments), clone the
5602              parm and give it the next type in PACKED_TYPES.  */
5603           actual_parm = copy_node (actual_parm);
5604           TREE_TYPE (actual_parm) = 
5605             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5606         }
5607
5608       if (arg != error_mark_node)
5609         arg = convert_template_argument (actual_parm, 
5610                                          arg, new_args, complain, parm_idx,
5611                                          in_decl);
5612       if (arg == error_mark_node)
5613         (*lost)++;
5614       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5615     }
5616
5617   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5618       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5619     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5620   else
5621     {
5622       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5623       TREE_TYPE (argument_pack) 
5624         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5625       TREE_CONSTANT (argument_pack) = 1;
5626     }
5627
5628   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5629   return argument_pack;
5630 }
5631
5632 /* Convert all template arguments to their appropriate types, and
5633    return a vector containing the innermost resulting template
5634    arguments.  If any error occurs, return error_mark_node. Error and
5635    warning messages are issued under control of COMPLAIN.
5636
5637    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5638    for arguments not specified in ARGS.  Otherwise, if
5639    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5640    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5641    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5642    ARGS.  */
5643
5644 static tree
5645 coerce_template_parms (tree parms,
5646                        tree args,
5647                        tree in_decl,
5648                        tsubst_flags_t complain,
5649                        bool require_all_args,
5650                        bool use_default_args)
5651 {
5652   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5653   tree inner_args;
5654   tree new_args;
5655   tree new_inner_args;
5656   int saved_unevaluated_operand;
5657   int saved_inhibit_evaluation_warnings;
5658
5659   /* When used as a boolean value, indicates whether this is a
5660      variadic template parameter list. Since it's an int, we can also
5661      subtract it from nparms to get the number of non-variadic
5662      parameters.  */
5663   int variadic_p = 0;
5664
5665   nparms = TREE_VEC_LENGTH (parms);
5666
5667   /* Determine if there are any parameter packs.  */
5668   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5669     {
5670       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5671       if (template_parameter_pack_p (tparm))
5672         ++variadic_p;
5673     }
5674
5675   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5676   /* If there are 0 or 1 parameter packs, we need to expand any argument
5677      packs so that we can deduce a parameter pack from some non-packed args
5678      followed by an argument pack, as in variadic85.C.  If there are more
5679      than that, we need to leave argument packs intact so the arguments are
5680      assigned to the right parameter packs.  This should only happen when
5681      dealing with a nested class inside a partial specialization of a class
5682      template, as in variadic92.C.  */
5683   if (variadic_p <= 1)
5684     inner_args = expand_template_argument_pack (inner_args);
5685
5686   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5687   if ((nargs > nparms && !variadic_p)
5688       || (nargs < nparms - variadic_p
5689           && require_all_args
5690           && (!use_default_args
5691               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5692                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5693     {
5694       if (complain & tf_error)
5695         {
5696           const char *or_more = "";
5697           if (variadic_p)
5698             {
5699               or_more = " or more";
5700               --nparms;
5701             }
5702
5703           error ("wrong number of template arguments (%d, should be %d%s)",
5704                  nargs, nparms, or_more);
5705
5706           if (in_decl)
5707             error ("provided for %q+D", in_decl);
5708         }
5709
5710       return error_mark_node;
5711     }
5712
5713   /* We need to evaluate the template arguments, even though this
5714      template-id may be nested within a "sizeof".  */
5715   saved_unevaluated_operand = cp_unevaluated_operand;
5716   cp_unevaluated_operand = 0;
5717   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5718   c_inhibit_evaluation_warnings = 0;
5719   new_inner_args = make_tree_vec (nparms);
5720   new_args = add_outermost_template_args (args, new_inner_args);
5721   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5722     {
5723       tree arg;
5724       tree parm;
5725
5726       /* Get the Ith template parameter.  */
5727       parm = TREE_VEC_ELT (parms, parm_idx);
5728  
5729       if (parm == error_mark_node)
5730       {
5731         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5732         continue;
5733       }
5734
5735       /* Calculate the next argument.  */
5736       if (arg_idx < nargs)
5737         arg = TREE_VEC_ELT (inner_args, arg_idx);
5738       else
5739         arg = NULL_TREE;
5740
5741       if (template_parameter_pack_p (TREE_VALUE (parm))
5742           && !(arg && ARGUMENT_PACK_P (arg)))
5743         {
5744           /* All remaining arguments will be placed in the
5745              template parameter pack PARM.  */
5746           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5747                                                 inner_args, arg_idx,
5748                                                 new_args, &lost,
5749                                                 in_decl, complain);
5750
5751           /* Store this argument.  */
5752           if (arg == error_mark_node)
5753             lost++;
5754           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5755
5756           /* We are done with all of the arguments.  */
5757           arg_idx = nargs;
5758           
5759           continue;
5760         }
5761       else if (arg)
5762         {
5763           if (PACK_EXPANSION_P (arg))
5764             {
5765               if (complain & tf_error)
5766                 {
5767                   /* FIXME this restriction was removed by N2555; see
5768                      bug 35722.  */
5769                   /* If ARG is a pack expansion, but PARM is not a
5770                      template parameter pack (if it were, we would have
5771                      handled it above), we're trying to expand into a
5772                      fixed-length argument list.  */
5773                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5774                     sorry ("cannot expand %<%E%> into a fixed-length "
5775                            "argument list", arg);
5776                   else
5777                     sorry ("cannot expand %<%T%> into a fixed-length "
5778                            "argument list", arg);
5779                 }
5780               return error_mark_node;
5781             }
5782         }
5783       else if (require_all_args)
5784         /* There must be a default arg in this case.  */
5785         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5786                                    complain, in_decl);
5787       else
5788         break;
5789
5790       if (arg == error_mark_node)
5791         {
5792           if (complain & tf_error)
5793             error ("template argument %d is invalid", arg_idx + 1);
5794         }
5795       else if (!arg)
5796         /* This only occurs if there was an error in the template
5797            parameter list itself (which we would already have
5798            reported) that we are trying to recover from, e.g., a class
5799            template with a parameter list such as
5800            template<typename..., typename>.  */
5801         return error_mark_node;
5802       else
5803         arg = convert_template_argument (TREE_VALUE (parm),
5804                                          arg, new_args, complain, 
5805                                          parm_idx, in_decl);
5806
5807       if (arg == error_mark_node)
5808         lost++;
5809       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5810     }
5811   cp_unevaluated_operand = saved_unevaluated_operand;
5812   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
5813
5814   if (lost)
5815     return error_mark_node;
5816
5817   return new_inner_args;
5818 }
5819
5820 /* Returns 1 if template args OT and NT are equivalent.  */
5821
5822 static int
5823 template_args_equal (tree ot, tree nt)
5824 {
5825   if (nt == ot)
5826     return 1;
5827
5828   if (TREE_CODE (nt) == TREE_VEC)
5829     /* For member templates */
5830     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5831   else if (PACK_EXPANSION_P (ot))
5832     return PACK_EXPANSION_P (nt) 
5833       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5834                               PACK_EXPANSION_PATTERN (nt));
5835   else if (ARGUMENT_PACK_P (ot))
5836     {
5837       int i, len;
5838       tree opack, npack;
5839
5840       if (!ARGUMENT_PACK_P (nt))
5841         return 0;
5842
5843       opack = ARGUMENT_PACK_ARGS (ot);
5844       npack = ARGUMENT_PACK_ARGS (nt);
5845       len = TREE_VEC_LENGTH (opack);
5846       if (TREE_VEC_LENGTH (npack) != len)
5847         return 0;
5848       for (i = 0; i < len; ++i)
5849         if (!template_args_equal (TREE_VEC_ELT (opack, i),
5850                                   TREE_VEC_ELT (npack, i)))
5851           return 0;
5852       return 1;
5853     }
5854   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
5855     {
5856       /* We get here probably because we are in the middle of substituting
5857          into the pattern of a pack expansion. In that case the
5858          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
5859          interested in. So we want to use the initial pack argument for
5860          the comparison.  */
5861       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
5862       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
5863         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
5864       return template_args_equal (ot, nt);
5865     }
5866   else if (TYPE_P (nt))
5867     return TYPE_P (ot) && same_type_p (ot, nt);
5868   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5869     return 0;
5870   else
5871     return cp_tree_equal (ot, nt);
5872 }
5873
5874 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5875    of template arguments.  Returns 0 otherwise.  */
5876
5877 int
5878 comp_template_args (tree oldargs, tree newargs)
5879 {
5880   int i;
5881
5882   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5883     return 0;
5884
5885   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5886     {
5887       tree nt = TREE_VEC_ELT (newargs, i);
5888       tree ot = TREE_VEC_ELT (oldargs, i);
5889
5890       if (! template_args_equal (ot, nt))
5891         return 0;
5892     }
5893   return 1;
5894 }
5895
5896 static void
5897 add_pending_template (tree d)
5898 {
5899   tree ti = (TYPE_P (d)
5900              ? CLASSTYPE_TEMPLATE_INFO (d)
5901              : DECL_TEMPLATE_INFO (d));
5902   struct pending_template *pt;
5903   int level;
5904
5905   if (TI_PENDING_TEMPLATE_FLAG (ti))
5906     return;
5907
5908   /* We are called both from instantiate_decl, where we've already had a
5909      tinst_level pushed, and instantiate_template, where we haven't.
5910      Compensate.  */
5911   level = !current_tinst_level || current_tinst_level->decl != d;
5912
5913   if (level)
5914     push_tinst_level (d);
5915
5916   pt = GGC_NEW (struct pending_template);
5917   pt->next = NULL;
5918   pt->tinst = current_tinst_level;
5919   if (last_pending_template)
5920     last_pending_template->next = pt;
5921   else
5922     pending_templates = pt;
5923
5924   last_pending_template = pt;
5925
5926   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5927
5928   if (level)
5929     pop_tinst_level ();
5930 }
5931
5932
5933 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5934    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5935    documentation for TEMPLATE_ID_EXPR.  */
5936
5937 tree
5938 lookup_template_function (tree fns, tree arglist)
5939 {
5940   tree type;
5941
5942   if (fns == error_mark_node || arglist == error_mark_node)
5943     return error_mark_node;
5944
5945   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5946   gcc_assert (fns && (is_overloaded_fn (fns)
5947                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5948
5949   if (BASELINK_P (fns))
5950     {
5951       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5952                                          unknown_type_node,
5953                                          BASELINK_FUNCTIONS (fns),
5954                                          arglist);
5955       return fns;
5956     }
5957
5958   type = TREE_TYPE (fns);
5959   if (TREE_CODE (fns) == OVERLOAD || !type)
5960     type = unknown_type_node;
5961
5962   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5963 }
5964
5965 /* Within the scope of a template class S<T>, the name S gets bound
5966    (in build_self_reference) to a TYPE_DECL for the class, not a
5967    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5968    or one of its enclosing classes, and that type is a template,
5969    return the associated TEMPLATE_DECL.  Otherwise, the original
5970    DECL is returned.  */
5971
5972 tree
5973 maybe_get_template_decl_from_type_decl (tree decl)
5974 {
5975   return (decl != NULL_TREE
5976           && TREE_CODE (decl) == TYPE_DECL
5977           && DECL_ARTIFICIAL (decl)
5978           && CLASS_TYPE_P (TREE_TYPE (decl))
5979           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5980     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5981 }
5982
5983 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5984    parameters, find the desired type.
5985
5986    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5987
5988    IN_DECL, if non-NULL, is the template declaration we are trying to
5989    instantiate.
5990
5991    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5992    the class we are looking up.
5993
5994    Issue error and warning messages under control of COMPLAIN.
5995
5996    If the template class is really a local class in a template
5997    function, then the FUNCTION_CONTEXT is the function in which it is
5998    being instantiated.
5999
6000    ??? Note that this function is currently called *twice* for each
6001    template-id: the first time from the parser, while creating the
6002    incomplete type (finish_template_type), and the second type during the
6003    real instantiation (instantiate_template_class). This is surely something
6004    that we want to avoid. It also causes some problems with argument
6005    coercion (see convert_nontype_argument for more information on this).  */
6006
6007 tree
6008 lookup_template_class (tree d1,
6009                        tree arglist,
6010                        tree in_decl,
6011                        tree context,
6012                        int entering_scope,
6013                        tsubst_flags_t complain)
6014 {
6015   tree templ = NULL_TREE, parmlist;
6016   tree t;
6017   spec_entry **slot;
6018   spec_entry *entry;
6019   spec_entry elt;
6020   hashval_t hash;
6021
6022   timevar_push (TV_NAME_LOOKUP);
6023
6024   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6025     {
6026       tree value = innermost_non_namespace_value (d1);
6027       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6028         templ = value;
6029       else
6030         {
6031           if (context)
6032             push_decl_namespace (context);
6033           templ = lookup_name (d1);
6034           templ = maybe_get_template_decl_from_type_decl (templ);
6035           if (context)
6036             pop_decl_namespace ();
6037         }
6038       if (templ)
6039         context = DECL_CONTEXT (templ);
6040     }
6041   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6042     {
6043       tree type = TREE_TYPE (d1);
6044
6045       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6046          an implicit typename for the second A.  Deal with it.  */
6047       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6048         type = TREE_TYPE (type);
6049
6050       if (CLASSTYPE_TEMPLATE_INFO (type))
6051         {
6052           templ = CLASSTYPE_TI_TEMPLATE (type);
6053           d1 = DECL_NAME (templ);
6054         }
6055     }
6056   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6057            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6058     {
6059       templ = TYPE_TI_TEMPLATE (d1);
6060       d1 = DECL_NAME (templ);
6061     }
6062   else if (TREE_CODE (d1) == TEMPLATE_DECL
6063            && DECL_TEMPLATE_RESULT (d1)
6064            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6065     {
6066       templ = d1;
6067       d1 = DECL_NAME (templ);
6068       context = DECL_CONTEXT (templ);
6069     }
6070
6071   /* Issue an error message if we didn't find a template.  */
6072   if (! templ)
6073     {
6074       if (complain & tf_error)
6075         error ("%qT is not a template", d1);
6076       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6077     }
6078
6079   if (TREE_CODE (templ) != TEMPLATE_DECL
6080          /* Make sure it's a user visible template, if it was named by
6081             the user.  */
6082       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6083           && !PRIMARY_TEMPLATE_P (templ)))
6084     {
6085       if (complain & tf_error)
6086         {
6087           error ("non-template type %qT used as a template", d1);
6088           if (in_decl)
6089             error ("for template declaration %q+D", in_decl);
6090         }
6091       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6092     }
6093
6094   complain &= ~tf_user;
6095
6096   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6097     {
6098       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6099          template arguments */
6100
6101       tree parm;
6102       tree arglist2;
6103       tree outer;
6104
6105       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6106
6107       /* Consider an example where a template template parameter declared as
6108
6109            template <class T, class U = std::allocator<T> > class TT
6110
6111          The template parameter level of T and U are one level larger than
6112          of TT.  To proper process the default argument of U, say when an
6113          instantiation `TT<int>' is seen, we need to build the full
6114          arguments containing {int} as the innermost level.  Outer levels,
6115          available when not appearing as default template argument, can be
6116          obtained from the arguments of the enclosing template.
6117
6118          Suppose that TT is later substituted with std::vector.  The above
6119          instantiation is `TT<int, std::allocator<T> >' with TT at
6120          level 1, and T at level 2, while the template arguments at level 1
6121          becomes {std::vector} and the inner level 2 is {int}.  */
6122
6123       outer = DECL_CONTEXT (templ);
6124       if (outer)
6125         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6126       else if (current_template_parms)
6127         /* This is an argument of the current template, so we haven't set
6128            DECL_CONTEXT yet.  */
6129         outer = current_template_args ();
6130
6131       if (outer)
6132         arglist = add_to_template_args (outer, arglist);
6133
6134       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6135                                         complain,
6136                                         /*require_all_args=*/true,
6137                                         /*use_default_args=*/true);
6138       if (arglist2 == error_mark_node
6139           || (!uses_template_parms (arglist2)
6140               && check_instantiated_args (templ, arglist2, complain)))
6141         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6142
6143       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6144       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6145     }
6146   else
6147     {
6148       tree template_type = TREE_TYPE (templ);
6149       tree gen_tmpl;
6150       tree type_decl;
6151       tree found = NULL_TREE;
6152       int arg_depth;
6153       int parm_depth;
6154       int is_partial_instantiation;
6155
6156       gen_tmpl = most_general_template (templ);
6157       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6158       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6159       arg_depth = TMPL_ARGS_DEPTH (arglist);
6160
6161       if (arg_depth == 1 && parm_depth > 1)
6162         {
6163           /* We've been given an incomplete set of template arguments.
6164              For example, given:
6165
6166                template <class T> struct S1 {
6167                  template <class U> struct S2 {};
6168                  template <class U> struct S2<U*> {};
6169                 };
6170
6171              we will be called with an ARGLIST of `U*', but the
6172              TEMPLATE will be `template <class T> template
6173              <class U> struct S1<T>::S2'.  We must fill in the missing
6174              arguments.  */
6175           arglist
6176             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6177                                            arglist);
6178           arg_depth = TMPL_ARGS_DEPTH (arglist);
6179         }
6180
6181       /* Now we should have enough arguments.  */
6182       gcc_assert (parm_depth == arg_depth);
6183
6184       /* From here on, we're only interested in the most general
6185          template.  */
6186
6187       /* Calculate the BOUND_ARGS.  These will be the args that are
6188          actually tsubst'd into the definition to create the
6189          instantiation.  */
6190       if (parm_depth > 1)
6191         {
6192           /* We have multiple levels of arguments to coerce, at once.  */
6193           int i;
6194           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6195
6196           tree bound_args = make_tree_vec (parm_depth);
6197
6198           for (i = saved_depth,
6199                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6200                i > 0 && t != NULL_TREE;
6201                --i, t = TREE_CHAIN (t))
6202             {
6203               tree a = coerce_template_parms (TREE_VALUE (t),
6204                                               arglist, gen_tmpl,
6205                                               complain,
6206                                               /*require_all_args=*/true,
6207                                               /*use_default_args=*/true);
6208
6209               /* Don't process further if one of the levels fails.  */
6210               if (a == error_mark_node)
6211                 {
6212                   /* Restore the ARGLIST to its full size.  */
6213                   TREE_VEC_LENGTH (arglist) = saved_depth;
6214                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6215                 }
6216
6217               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6218
6219               /* We temporarily reduce the length of the ARGLIST so
6220                  that coerce_template_parms will see only the arguments
6221                  corresponding to the template parameters it is
6222                  examining.  */
6223               TREE_VEC_LENGTH (arglist)--;
6224             }
6225
6226           /* Restore the ARGLIST to its full size.  */
6227           TREE_VEC_LENGTH (arglist) = saved_depth;
6228
6229           arglist = bound_args;
6230         }
6231       else
6232         arglist
6233           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6234                                    INNERMOST_TEMPLATE_ARGS (arglist),
6235                                    gen_tmpl,
6236                                    complain,
6237                                    /*require_all_args=*/true,
6238                                    /*use_default_args=*/true);
6239
6240       if (arglist == error_mark_node)
6241         /* We were unable to bind the arguments.  */
6242         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6243
6244       /* In the scope of a template class, explicit references to the
6245          template class refer to the type of the template, not any
6246          instantiation of it.  For example, in:
6247
6248            template <class T> class C { void f(C<T>); }
6249
6250          the `C<T>' is just the same as `C'.  Outside of the
6251          class, however, such a reference is an instantiation.  */
6252       if ((entering_scope
6253            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6254            || currently_open_class (template_type))
6255           /* comp_template_args is expensive, check it last.  */
6256           && comp_template_args (TYPE_TI_ARGS (template_type),
6257                                  arglist))
6258         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6259
6260       /* If we already have this specialization, return it.  */
6261       elt.tmpl = gen_tmpl;
6262       elt.args = arglist;
6263       hash = hash_specialization (&elt);
6264       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6265                                                   &elt, hash);
6266
6267       if (entry)
6268         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6269
6270       /* This type is a "partial instantiation" if any of the template
6271          arguments still involve template parameters.  Note that we set
6272          IS_PARTIAL_INSTANTIATION for partial specializations as
6273          well.  */
6274       is_partial_instantiation = uses_template_parms (arglist);
6275
6276       /* If the deduced arguments are invalid, then the binding
6277          failed.  */
6278       if (!is_partial_instantiation
6279           && check_instantiated_args (gen_tmpl,
6280                                       INNERMOST_TEMPLATE_ARGS (arglist),
6281                                       complain))
6282         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6283
6284       if (!is_partial_instantiation
6285           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6286           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6287           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6288         {
6289           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6290                                       DECL_NAME (gen_tmpl),
6291                                       /*tag_scope=*/ts_global);
6292           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6293         }
6294
6295       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6296                         complain, in_decl);
6297       if (!context)
6298         context = global_namespace;
6299
6300       /* Create the type.  */
6301       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6302         {
6303           if (!is_partial_instantiation)
6304             {
6305               set_current_access_from_decl (TYPE_NAME (template_type));
6306               t = start_enum (TYPE_IDENTIFIER (template_type),
6307                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6308                                       arglist, complain, in_decl),
6309                               SCOPED_ENUM_P (template_type));
6310             }
6311           else
6312             {
6313               /* We don't want to call start_enum for this type, since
6314                  the values for the enumeration constants may involve
6315                  template parameters.  And, no one should be interested
6316                  in the enumeration constants for such a type.  */
6317               t = cxx_make_type (ENUMERAL_TYPE);
6318               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6319             }
6320         }
6321       else
6322         {
6323           t = make_class_type (TREE_CODE (template_type));
6324           CLASSTYPE_DECLARED_CLASS (t)
6325             = CLASSTYPE_DECLARED_CLASS (template_type);
6326           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6327           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6328
6329           /* A local class.  Make sure the decl gets registered properly.  */
6330           if (context == current_function_decl)
6331             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6332
6333           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6334             /* This instantiation is another name for the primary
6335                template type. Set the TYPE_CANONICAL field
6336                appropriately. */
6337             TYPE_CANONICAL (t) = template_type;
6338           else if (any_template_arguments_need_structural_equality_p (arglist))
6339             /* Some of the template arguments require structural
6340                equality testing, so this template class requires
6341                structural equality testing. */
6342             SET_TYPE_STRUCTURAL_EQUALITY (t);
6343         }
6344
6345       /* If we called start_enum or pushtag above, this information
6346          will already be set up.  */
6347       if (!TYPE_NAME (t))
6348         {
6349           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6350
6351           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6352           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6353           TYPE_STUB_DECL (t) = type_decl;
6354           DECL_SOURCE_LOCATION (type_decl)
6355             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6356         }
6357       else
6358         type_decl = TYPE_NAME (t);
6359
6360       TREE_PRIVATE (type_decl)
6361         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6362       TREE_PROTECTED (type_decl)
6363         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6364       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6365         {
6366           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6367           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6368         }
6369
6370       /* Set up the template information.  We have to figure out which
6371          template is the immediate parent if this is a full
6372          instantiation.  */
6373       if (parm_depth == 1 || is_partial_instantiation
6374           || !PRIMARY_TEMPLATE_P (gen_tmpl))
6375         /* This case is easy; there are no member templates involved.  */
6376         found = gen_tmpl;
6377       else
6378         {
6379           /* This is a full instantiation of a member template.  Find
6380              the partial instantiation of which this is an instance.  */
6381
6382           /* Temporarily reduce by one the number of levels in the ARGLIST
6383              so as to avoid comparing the last set of arguments.  */
6384           TREE_VEC_LENGTH (arglist)--;
6385           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6386           TREE_VEC_LENGTH (arglist)++;
6387           found = CLASSTYPE_TI_TEMPLATE (found);
6388         }
6389
6390       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
6391
6392       elt.spec = t;
6393       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6394                                                        &elt, hash, INSERT);
6395       *slot = GGC_NEW (spec_entry);
6396       **slot = elt;
6397
6398       /* Note this use of the partial instantiation so we can check it
6399          later in maybe_process_partial_specialization.  */
6400       DECL_TEMPLATE_INSTANTIATIONS (templ)
6401         = tree_cons (arglist, t,
6402                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6403
6404       if (TREE_CODE (t) == ENUMERAL_TYPE
6405           && !is_partial_instantiation)
6406         /* Now that the type has been registered on the instantiations
6407            list, we set up the enumerators.  Because the enumeration
6408            constants may involve the enumeration type itself, we make
6409            sure to register the type first, and then create the
6410            constants.  That way, doing tsubst_expr for the enumeration
6411            constants won't result in recursive calls here; we'll find
6412            the instantiation and exit above.  */
6413         tsubst_enum (template_type, t, arglist);
6414
6415       if (is_partial_instantiation)
6416         /* If the type makes use of template parameters, the
6417            code that generates debugging information will crash.  */
6418         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6419
6420       /* Possibly limit visibility based on template args.  */
6421       TREE_PUBLIC (type_decl) = 1;
6422       determine_visibility (type_decl);
6423
6424       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6425     }
6426   timevar_pop (TV_NAME_LOOKUP);
6427 }
6428 \f
6429 struct pair_fn_data
6430 {
6431   tree_fn_t fn;
6432   void *data;
6433   /* True when we should also visit template parameters that occur in
6434      non-deduced contexts.  */
6435   bool include_nondeduced_p;
6436   struct pointer_set_t *visited;
6437 };
6438
6439 /* Called from for_each_template_parm via walk_tree.  */
6440
6441 static tree
6442 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6443 {
6444   tree t = *tp;
6445   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6446   tree_fn_t fn = pfd->fn;
6447   void *data = pfd->data;
6448
6449   if (TYPE_P (t)
6450       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6451       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6452                                  pfd->include_nondeduced_p))
6453     return error_mark_node;
6454
6455   switch (TREE_CODE (t))
6456     {
6457     case RECORD_TYPE:
6458       if (TYPE_PTRMEMFUNC_P (t))
6459         break;
6460       /* Fall through.  */
6461
6462     case UNION_TYPE:
6463     case ENUMERAL_TYPE:
6464       if (!TYPE_TEMPLATE_INFO (t))
6465         *walk_subtrees = 0;
6466       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
6467                                        fn, data, pfd->visited, 
6468                                        pfd->include_nondeduced_p))
6469         return error_mark_node;
6470       break;
6471
6472     case INTEGER_TYPE:
6473       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6474                                   fn, data, pfd->visited, 
6475                                   pfd->include_nondeduced_p)
6476           || for_each_template_parm (TYPE_MAX_VALUE (t),
6477                                      fn, data, pfd->visited,
6478                                      pfd->include_nondeduced_p))
6479         return error_mark_node;
6480       break;
6481
6482     case METHOD_TYPE:
6483       /* Since we're not going to walk subtrees, we have to do this
6484          explicitly here.  */
6485       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6486                                   pfd->visited, pfd->include_nondeduced_p))
6487         return error_mark_node;
6488       /* Fall through.  */
6489
6490     case FUNCTION_TYPE:
6491       /* Check the return type.  */
6492       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6493                                   pfd->include_nondeduced_p))
6494         return error_mark_node;
6495
6496       /* Check the parameter types.  Since default arguments are not
6497          instantiated until they are needed, the TYPE_ARG_TYPES may
6498          contain expressions that involve template parameters.  But,
6499          no-one should be looking at them yet.  And, once they're
6500          instantiated, they don't contain template parameters, so
6501          there's no point in looking at them then, either.  */
6502       {
6503         tree parm;
6504
6505         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6506           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6507                                       pfd->visited, pfd->include_nondeduced_p))
6508             return error_mark_node;
6509
6510         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6511            want walk_tree walking into them itself.  */
6512         *walk_subtrees = 0;
6513       }
6514       break;
6515
6516     case TYPEOF_TYPE:
6517       if (pfd->include_nondeduced_p
6518           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6519                                      pfd->visited, 
6520                                      pfd->include_nondeduced_p))
6521         return error_mark_node;
6522       break;
6523
6524     case FUNCTION_DECL:
6525     case VAR_DECL:
6526       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6527           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6528                                      pfd->visited, pfd->include_nondeduced_p))
6529         return error_mark_node;
6530       /* Fall through.  */
6531
6532     case PARM_DECL:
6533     case CONST_DECL:
6534       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6535           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6536                                      pfd->visited, pfd->include_nondeduced_p))
6537         return error_mark_node;
6538       if (DECL_CONTEXT (t)
6539           && pfd->include_nondeduced_p
6540           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6541                                      pfd->visited, pfd->include_nondeduced_p))
6542         return error_mark_node;
6543       break;
6544
6545     case BOUND_TEMPLATE_TEMPLATE_PARM:
6546       /* Record template parameters such as `T' inside `TT<T>'.  */
6547       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6548                                   pfd->include_nondeduced_p))
6549         return error_mark_node;
6550       /* Fall through.  */
6551
6552     case TEMPLATE_TEMPLATE_PARM:
6553     case TEMPLATE_TYPE_PARM:
6554     case TEMPLATE_PARM_INDEX:
6555       if (fn && (*fn)(t, data))
6556         return error_mark_node;
6557       else if (!fn)
6558         return error_mark_node;
6559       break;
6560
6561     case TEMPLATE_DECL:
6562       /* A template template parameter is encountered.  */
6563       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6564           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6565                                      pfd->include_nondeduced_p))
6566         return error_mark_node;
6567
6568       /* Already substituted template template parameter */
6569       *walk_subtrees = 0;
6570       break;
6571
6572     case TYPENAME_TYPE:
6573       if (!fn
6574           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6575                                      data, pfd->visited, 
6576                                      pfd->include_nondeduced_p))
6577         return error_mark_node;
6578       break;
6579
6580     case CONSTRUCTOR:
6581       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6582           && pfd->include_nondeduced_p
6583           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6584                                      (TREE_TYPE (t)), fn, data,
6585                                      pfd->visited, pfd->include_nondeduced_p))
6586         return error_mark_node;
6587       break;
6588
6589     case INDIRECT_REF:
6590     case COMPONENT_REF:
6591       /* If there's no type, then this thing must be some expression
6592          involving template parameters.  */
6593       if (!fn && !TREE_TYPE (t))
6594         return error_mark_node;
6595       break;
6596
6597     case MODOP_EXPR:
6598     case CAST_EXPR:
6599     case REINTERPRET_CAST_EXPR:
6600     case CONST_CAST_EXPR:
6601     case STATIC_CAST_EXPR:
6602     case DYNAMIC_CAST_EXPR:
6603     case ARROW_EXPR:
6604     case DOTSTAR_EXPR:
6605     case TYPEID_EXPR:
6606     case PSEUDO_DTOR_EXPR:
6607       if (!fn)
6608         return error_mark_node;
6609       break;
6610
6611     default:
6612       break;
6613     }
6614
6615   /* We didn't find any template parameters we liked.  */
6616   return NULL_TREE;
6617 }
6618
6619 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6620    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6621    call FN with the parameter and the DATA.
6622    If FN returns nonzero, the iteration is terminated, and
6623    for_each_template_parm returns 1.  Otherwise, the iteration
6624    continues.  If FN never returns a nonzero value, the value
6625    returned by for_each_template_parm is 0.  If FN is NULL, it is
6626    considered to be the function which always returns 1.
6627
6628    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6629    parameters that occur in non-deduced contexts.  When false, only
6630    visits those template parameters that can be deduced.  */
6631
6632 static int
6633 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6634                         struct pointer_set_t *visited,
6635                         bool include_nondeduced_p)
6636 {
6637   struct pair_fn_data pfd;
6638   int result;
6639
6640   /* Set up.  */
6641   pfd.fn = fn;
6642   pfd.data = data;
6643   pfd.include_nondeduced_p = include_nondeduced_p;
6644
6645   /* Walk the tree.  (Conceptually, we would like to walk without
6646      duplicates, but for_each_template_parm_r recursively calls
6647      for_each_template_parm, so we would need to reorganize a fair
6648      bit to use walk_tree_without_duplicates, so we keep our own
6649      visited list.)  */
6650   if (visited)
6651     pfd.visited = visited;
6652   else
6653     pfd.visited = pointer_set_create ();
6654   result = cp_walk_tree (&t,
6655                          for_each_template_parm_r,
6656                          &pfd,
6657                          pfd.visited) != NULL_TREE;
6658
6659   /* Clean up.  */
6660   if (!visited)
6661     {
6662       pointer_set_destroy (pfd.visited);
6663       pfd.visited = 0;
6664     }
6665
6666   return result;
6667 }
6668
6669 /* Returns true if T depends on any template parameter.  */
6670
6671 int
6672 uses_template_parms (tree t)
6673 {
6674   bool dependent_p;
6675   int saved_processing_template_decl;
6676
6677   saved_processing_template_decl = processing_template_decl;
6678   if (!saved_processing_template_decl)
6679     processing_template_decl = 1;
6680   if (TYPE_P (t))
6681     dependent_p = dependent_type_p (t);
6682   else if (TREE_CODE (t) == TREE_VEC)
6683     dependent_p = any_dependent_template_arguments_p (t);
6684   else if (TREE_CODE (t) == TREE_LIST)
6685     dependent_p = (uses_template_parms (TREE_VALUE (t))
6686                    || uses_template_parms (TREE_CHAIN (t)));
6687   else if (TREE_CODE (t) == TYPE_DECL)
6688     dependent_p = dependent_type_p (TREE_TYPE (t));
6689   else if (DECL_P (t)
6690            || EXPR_P (t)
6691            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6692            || TREE_CODE (t) == OVERLOAD
6693            || TREE_CODE (t) == BASELINK
6694            || TREE_CODE (t) == IDENTIFIER_NODE
6695            || TREE_CODE (t) == TRAIT_EXPR
6696            || TREE_CODE (t) == CONSTRUCTOR
6697            || CONSTANT_CLASS_P (t))
6698     dependent_p = (type_dependent_expression_p (t)
6699                    || value_dependent_expression_p (t));
6700   else
6701     {
6702       gcc_assert (t == error_mark_node);
6703       dependent_p = false;
6704     }
6705
6706   processing_template_decl = saved_processing_template_decl;
6707
6708   return dependent_p;
6709 }
6710
6711 /* Returns true if T depends on any template parameter with level LEVEL.  */
6712
6713 int
6714 uses_template_parms_level (tree t, int level)
6715 {
6716   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6717                                  /*include_nondeduced_p=*/true);
6718 }
6719
6720 static int tinst_depth;
6721 extern int max_tinst_depth;
6722 #ifdef GATHER_STATISTICS
6723 int depth_reached;
6724 #endif
6725 static int tinst_level_tick;
6726 static int last_template_error_tick;
6727
6728 /* We're starting to instantiate D; record the template instantiation context
6729    for diagnostics and to restore it later.  */
6730
6731 static int
6732 push_tinst_level (tree d)
6733 {
6734   struct tinst_level *new_level;
6735
6736   if (tinst_depth >= max_tinst_depth)
6737     {
6738       /* If the instantiation in question still has unbound template parms,
6739          we don't really care if we can't instantiate it, so just return.
6740          This happens with base instantiation for implicit `typename'.  */
6741       if (uses_template_parms (d))
6742         return 0;
6743
6744       last_template_error_tick = tinst_level_tick;
6745       error ("template instantiation depth exceeds maximum of %d (use "
6746              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6747              max_tinst_depth, d);
6748
6749       print_instantiation_context ();
6750
6751       return 0;
6752     }
6753
6754   new_level = GGC_NEW (struct tinst_level);
6755   new_level->decl = d;
6756   new_level->locus = input_location;
6757   new_level->in_system_header_p = in_system_header;
6758   new_level->next = current_tinst_level;
6759   current_tinst_level = new_level;
6760
6761   ++tinst_depth;
6762 #ifdef GATHER_STATISTICS
6763   if (tinst_depth > depth_reached)
6764     depth_reached = tinst_depth;
6765 #endif
6766
6767   ++tinst_level_tick;
6768   return 1;
6769 }
6770
6771 /* We're done instantiating this template; return to the instantiation
6772    context.  */
6773
6774 static void
6775 pop_tinst_level (void)
6776 {
6777   /* Restore the filename and line number stashed away when we started
6778      this instantiation.  */
6779   input_location = current_tinst_level->locus;
6780   current_tinst_level = current_tinst_level->next;
6781   --tinst_depth;
6782   ++tinst_level_tick;
6783 }
6784
6785 /* We're instantiating a deferred template; restore the template
6786    instantiation context in which the instantiation was requested, which
6787    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6788
6789 static tree
6790 reopen_tinst_level (struct tinst_level *level)
6791 {
6792   struct tinst_level *t;
6793
6794   tinst_depth = 0;
6795   for (t = level; t; t = t->next)
6796     ++tinst_depth;
6797
6798   current_tinst_level = level;
6799   pop_tinst_level ();
6800   return level->decl;
6801 }
6802
6803 /* Returns the TINST_LEVEL which gives the original instantiation
6804    context.  */
6805
6806 struct tinst_level *
6807 outermost_tinst_level (void)
6808 {
6809   struct tinst_level *level = current_tinst_level;
6810   if (level)
6811     while (level->next)
6812       level = level->next;
6813   return level;
6814 }
6815
6816 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
6817
6818 bool
6819 parameter_of_template_p (tree parm, tree templ)
6820 {
6821   tree parms;
6822   int i;
6823
6824   if (!parm || !templ)
6825     return false;
6826
6827   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
6828   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6829
6830   parms = DECL_TEMPLATE_PARMS (templ);
6831   parms = INNERMOST_TEMPLATE_PARMS (parms);
6832
6833   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
6834     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
6835       return true;
6836
6837   return false;
6838 }
6839
6840 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6841    vector of template arguments, as for tsubst.
6842
6843    Returns an appropriate tsubst'd friend declaration.  */
6844
6845 static tree
6846 tsubst_friend_function (tree decl, tree args)
6847 {
6848   tree new_friend;
6849
6850   if (TREE_CODE (decl) == FUNCTION_DECL
6851       && DECL_TEMPLATE_INSTANTIATION (decl)
6852       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6853     /* This was a friend declared with an explicit template
6854        argument list, e.g.:
6855
6856        friend void f<>(T);
6857
6858        to indicate that f was a template instantiation, not a new
6859        function declaration.  Now, we have to figure out what
6860        instantiation of what template.  */
6861     {
6862       tree template_id, arglist, fns;
6863       tree new_args;
6864       tree tmpl;
6865       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6866
6867       /* Friend functions are looked up in the containing namespace scope.
6868          We must enter that scope, to avoid finding member functions of the
6869          current class with same name.  */
6870       push_nested_namespace (ns);
6871       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6872                          tf_warning_or_error, NULL_TREE,
6873                          /*integral_constant_expression_p=*/false);
6874       pop_nested_namespace (ns);
6875       arglist = tsubst (DECL_TI_ARGS (decl), args,
6876                         tf_warning_or_error, NULL_TREE);
6877       template_id = lookup_template_function (fns, arglist);
6878
6879       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6880       tmpl = determine_specialization (template_id, new_friend,
6881                                        &new_args,
6882                                        /*need_member_template=*/0,
6883                                        TREE_VEC_LENGTH (args),
6884                                        tsk_none);
6885       return instantiate_template (tmpl, new_args, tf_error);
6886     }
6887
6888   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6889
6890   /* The NEW_FRIEND will look like an instantiation, to the
6891      compiler, but is not an instantiation from the point of view of
6892      the language.  For example, we might have had:
6893
6894      template <class T> struct S {
6895        template <class U> friend void f(T, U);
6896      };
6897
6898      Then, in S<int>, template <class U> void f(int, U) is not an
6899      instantiation of anything.  */
6900   if (new_friend == error_mark_node)
6901     return error_mark_node;
6902
6903   DECL_USE_TEMPLATE (new_friend) = 0;
6904   if (TREE_CODE (decl) == TEMPLATE_DECL)
6905     {
6906       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6907       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6908         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6909     }
6910
6911   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6912      is not a template instantiation and should not be mangled like
6913      one.  Therefore, we forget the mangling here; we'll recompute it
6914      later if we need it.  */
6915   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6916     {
6917       SET_DECL_RTL (new_friend, NULL_RTX);
6918       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6919     }
6920
6921   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6922     {
6923       tree old_decl;
6924       tree new_friend_template_info;
6925       tree new_friend_result_template_info;
6926       tree ns;
6927       int  new_friend_is_defn;
6928
6929       /* We must save some information from NEW_FRIEND before calling
6930          duplicate decls since that function will free NEW_FRIEND if
6931          possible.  */
6932       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6933       new_friend_is_defn =
6934             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6935                            (template_for_substitution (new_friend)))
6936              != NULL_TREE);
6937       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6938         {
6939           /* This declaration is a `primary' template.  */
6940           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6941
6942           new_friend_result_template_info
6943             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6944         }
6945       else
6946         new_friend_result_template_info = NULL_TREE;
6947
6948       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6949       if (new_friend_is_defn)
6950         DECL_INITIAL (new_friend) = error_mark_node;
6951
6952       /* Inside pushdecl_namespace_level, we will push into the
6953          current namespace. However, the friend function should go
6954          into the namespace of the template.  */
6955       ns = decl_namespace_context (new_friend);
6956       push_nested_namespace (ns);
6957       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6958       pop_nested_namespace (ns);
6959
6960       if (old_decl == error_mark_node)
6961         return error_mark_node;
6962
6963       if (old_decl != new_friend)
6964         {
6965           /* This new friend declaration matched an existing
6966              declaration.  For example, given:
6967
6968                template <class T> void f(T);
6969                template <class U> class C {
6970                  template <class T> friend void f(T) {}
6971                };
6972
6973              the friend declaration actually provides the definition
6974              of `f', once C has been instantiated for some type.  So,
6975              old_decl will be the out-of-class template declaration,
6976              while new_friend is the in-class definition.
6977
6978              But, if `f' was called before this point, the
6979              instantiation of `f' will have DECL_TI_ARGS corresponding
6980              to `T' but not to `U', references to which might appear
6981              in the definition of `f'.  Previously, the most general
6982              template for an instantiation of `f' was the out-of-class
6983              version; now it is the in-class version.  Therefore, we
6984              run through all specialization of `f', adding to their
6985              DECL_TI_ARGS appropriately.  In particular, they need a
6986              new set of outer arguments, corresponding to the
6987              arguments for this class instantiation.
6988
6989              The same situation can arise with something like this:
6990
6991                friend void f(int);
6992                template <class T> class C {
6993                  friend void f(T) {}
6994                };
6995
6996              when `C<int>' is instantiated.  Now, `f(int)' is defined
6997              in the class.  */
6998
6999           if (!new_friend_is_defn)
7000             /* On the other hand, if the in-class declaration does
7001                *not* provide a definition, then we don't want to alter
7002                existing definitions.  We can just leave everything
7003                alone.  */
7004             ;
7005           else
7006             {
7007               tree new_template = TI_TEMPLATE (new_friend_template_info);
7008               tree new_args = TI_ARGS (new_friend_template_info);
7009
7010               /* Overwrite whatever template info was there before, if
7011                  any, with the new template information pertaining to
7012                  the declaration.  */
7013               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7014
7015               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7016                 /* We should have called reregister_specialization in
7017                    duplicate_decls.  */
7018                 gcc_assert (retrieve_specialization (new_template,
7019                                                      new_args, 0)
7020                             == old_decl);
7021               else
7022                 {
7023                   tree t;
7024
7025                   /* Indicate that the old function template is a partial
7026                      instantiation.  */
7027                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7028                     = new_friend_result_template_info;
7029
7030                   gcc_assert (new_template
7031                               == most_general_template (new_template));
7032                   gcc_assert (new_template != old_decl);
7033
7034                   /* Reassign any specializations already in the hash table
7035                      to the new more general template, and add the
7036                      additional template args.  */
7037                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7038                        t != NULL_TREE;
7039                        t = TREE_CHAIN (t))
7040                     {
7041                       tree spec = TREE_VALUE (t);
7042                       spec_entry elt;
7043
7044                       elt.tmpl = old_decl;
7045                       elt.args = DECL_TI_ARGS (spec);
7046                       elt.spec = NULL_TREE;
7047
7048                       htab_remove_elt (decl_specializations, &elt);
7049
7050                       DECL_TI_ARGS (spec)
7051                         = add_outermost_template_args (new_args,
7052                                                        DECL_TI_ARGS (spec));
7053
7054                       register_specialization
7055                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7056
7057                     }
7058                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7059                 }
7060             }
7061
7062           /* The information from NEW_FRIEND has been merged into OLD_DECL
7063              by duplicate_decls.  */
7064           new_friend = old_decl;
7065         }
7066     }
7067   else
7068     {
7069       tree context = DECL_CONTEXT (new_friend);
7070       bool dependent_p;
7071
7072       /* In the code
7073            template <class T> class C {
7074              template <class U> friend void C1<U>::f (); // case 1
7075              friend void C2<T>::f ();                    // case 2
7076            };
7077          we only need to make sure CONTEXT is a complete type for
7078          case 2.  To distinguish between the two cases, we note that
7079          CONTEXT of case 1 remains dependent type after tsubst while
7080          this isn't true for case 2.  */
7081       ++processing_template_decl;
7082       dependent_p = dependent_type_p (context);
7083       --processing_template_decl;
7084
7085       if (!dependent_p
7086           && !complete_type_or_else (context, NULL_TREE))
7087         return error_mark_node;
7088
7089       if (COMPLETE_TYPE_P (context))
7090         {
7091           /* Check to see that the declaration is really present, and,
7092              possibly obtain an improved declaration.  */
7093           tree fn = check_classfn (context,
7094                                    new_friend, NULL_TREE);
7095
7096           if (fn)
7097             new_friend = fn;
7098         }
7099     }
7100
7101   return new_friend;
7102 }
7103
7104 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7105    template arguments, as for tsubst.
7106
7107    Returns an appropriate tsubst'd friend type or error_mark_node on
7108    failure.  */
7109
7110 static tree
7111 tsubst_friend_class (tree friend_tmpl, tree args)
7112 {
7113   tree friend_type;
7114   tree tmpl;
7115   tree context;
7116
7117   context = DECL_CONTEXT (friend_tmpl);
7118
7119   if (context)
7120     {
7121       if (TREE_CODE (context) == NAMESPACE_DECL)
7122         push_nested_namespace (context);
7123       else
7124         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7125     }
7126
7127   /* Look for a class template declaration.  We look for hidden names
7128      because two friend declarations of the same template are the
7129      same.  For example, in:
7130
7131        struct A { 
7132          template <typename> friend class F;
7133        };
7134        template <typename> struct B { 
7135          template <typename> friend class F;
7136        };
7137
7138      both F templates are the same.  */
7139   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7140                            /*block_p=*/true, 0, 
7141                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7142
7143   /* But, if we don't find one, it might be because we're in a
7144      situation like this:
7145
7146        template <class T>
7147        struct S {
7148          template <class U>
7149          friend struct S;
7150        };
7151
7152      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7153      for `S<int>', not the TEMPLATE_DECL.  */
7154   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7155     {
7156       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7157       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7158     }
7159
7160   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7161     {
7162       /* The friend template has already been declared.  Just
7163          check to see that the declarations match, and install any new
7164          default parameters.  We must tsubst the default parameters,
7165          of course.  We only need the innermost template parameters
7166          because that is all that redeclare_class_template will look
7167          at.  */
7168       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7169           > TMPL_ARGS_DEPTH (args))
7170         {
7171           tree parms;
7172           location_t saved_input_location;
7173           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7174                                          args, tf_warning_or_error);
7175
7176           saved_input_location = input_location;
7177           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7178           redeclare_class_template (TREE_TYPE (tmpl), parms);
7179           input_location = saved_input_location;
7180           
7181         }
7182
7183       friend_type = TREE_TYPE (tmpl);
7184     }
7185   else
7186     {
7187       /* The friend template has not already been declared.  In this
7188          case, the instantiation of the template class will cause the
7189          injection of this template into the global scope.  */
7190       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7191       if (tmpl == error_mark_node)
7192         return error_mark_node;
7193
7194       /* The new TMPL is not an instantiation of anything, so we
7195          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7196          the new type because that is supposed to be the corresponding
7197          template decl, i.e., TMPL.  */
7198       DECL_USE_TEMPLATE (tmpl) = 0;
7199       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7200       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7201       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7202         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7203
7204       /* Inject this template into the global scope.  */
7205       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7206     }
7207
7208   if (context)
7209     {
7210       if (TREE_CODE (context) == NAMESPACE_DECL)
7211         pop_nested_namespace (context);
7212       else
7213         pop_nested_class ();
7214     }
7215
7216   return friend_type;
7217 }
7218
7219 /* Returns zero if TYPE cannot be completed later due to circularity.
7220    Otherwise returns one.  */
7221
7222 static int
7223 can_complete_type_without_circularity (tree type)
7224 {
7225   if (type == NULL_TREE || type == error_mark_node)
7226     return 0;
7227   else if (COMPLETE_TYPE_P (type))
7228     return 1;
7229   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7230     return can_complete_type_without_circularity (TREE_TYPE (type));
7231   else if (CLASS_TYPE_P (type)
7232            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7233     return 0;
7234   else
7235     return 1;
7236 }
7237
7238 /* Apply any attributes which had to be deferred until instantiation
7239    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7240    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7241
7242 static void
7243 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7244                                 tree args, tsubst_flags_t complain, tree in_decl)
7245 {
7246   tree last_dep = NULL_TREE;
7247   tree t;
7248   tree *p;
7249
7250   for (t = attributes; t; t = TREE_CHAIN (t))
7251     if (ATTR_IS_DEPENDENT (t))
7252       {
7253         last_dep = t;
7254         attributes = copy_list (attributes);
7255         break;
7256       }
7257
7258   if (DECL_P (*decl_p))
7259     {
7260       if (TREE_TYPE (*decl_p) == error_mark_node)
7261         return;
7262       p = &DECL_ATTRIBUTES (*decl_p);
7263     }
7264   else
7265     p = &TYPE_ATTRIBUTES (*decl_p);
7266
7267   if (last_dep)
7268     {
7269       tree late_attrs = NULL_TREE;
7270       tree *q = &late_attrs;
7271
7272       for (*p = attributes; *p; )
7273         {
7274           t = *p;
7275           if (ATTR_IS_DEPENDENT (t))
7276             {
7277               *p = TREE_CHAIN (t);
7278               TREE_CHAIN (t) = NULL_TREE;
7279               /* If the first attribute argument is an identifier, don't
7280                  pass it through tsubst.  Attributes like mode, format,
7281                  cleanup and several target specific attributes expect it
7282                  unmodified.  */
7283               if (TREE_VALUE (t)
7284                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7285                   && TREE_VALUE (TREE_VALUE (t))
7286                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7287                       == IDENTIFIER_NODE))
7288                 {
7289                   tree chain
7290                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7291                                    in_decl,
7292                                    /*integral_constant_expression_p=*/false);
7293                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7294                     TREE_VALUE (t)
7295                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7296                                    chain);
7297                 }
7298               else
7299                 TREE_VALUE (t)
7300                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7301                                  /*integral_constant_expression_p=*/false);
7302               *q = t;
7303               q = &TREE_CHAIN (t);
7304             }
7305           else
7306             p = &TREE_CHAIN (t);
7307         }
7308
7309       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7310     }
7311 }
7312
7313 /* Perform (or defer) access check for typedefs that were referenced
7314    from within the template TMPL code.
7315    This is a subroutine of instantiate_template and instantiate_class_template.
7316    TMPL is the template to consider and TARGS is the list of arguments of
7317    that template.  */
7318
7319 static void
7320 perform_typedefs_access_check (tree tmpl, tree targs)
7321 {
7322   tree t;
7323
7324   if (!tmpl
7325       || (!CLASS_TYPE_P (tmpl)
7326           && TREE_CODE (tmpl) != FUNCTION_DECL))
7327     return;
7328
7329   for (t = get_types_needing_access_check (tmpl); t; t = TREE_CHAIN (t))
7330     {
7331       tree type_decl = TREE_PURPOSE (t);
7332       tree type_scope = TREE_VALUE (t);
7333
7334       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7335         continue;
7336
7337       if (uses_template_parms (type_decl))
7338         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7339       if (uses_template_parms (type_scope))
7340         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7341
7342       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7343                                      type_decl, type_decl);
7344     }
7345 }
7346
7347 tree
7348 instantiate_class_template (tree type)
7349 {
7350   tree templ, args, pattern, t, member;
7351   tree typedecl;
7352   tree pbinfo;
7353   tree base_list;
7354   unsigned int saved_maximum_field_alignment;
7355
7356   if (type == error_mark_node)
7357     return error_mark_node;
7358
7359   if (TYPE_BEING_DEFINED (type)
7360       || COMPLETE_TYPE_P (type)
7361       || uses_template_parms (type))
7362     return type;
7363
7364   /* Figure out which template is being instantiated.  */
7365   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7366   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7367
7368   /* Determine what specialization of the original template to
7369      instantiate.  */
7370   t = most_specialized_class (type, templ);
7371   if (t == error_mark_node)
7372     {
7373       TYPE_BEING_DEFINED (type) = 1;
7374       return error_mark_node;
7375     }
7376   else if (t)
7377     {
7378       /* This TYPE is actually an instantiation of a partial
7379          specialization.  We replace the innermost set of ARGS with
7380          the arguments appropriate for substitution.  For example,
7381          given:
7382
7383            template <class T> struct S {};
7384            template <class T> struct S<T*> {};
7385
7386          and supposing that we are instantiating S<int*>, ARGS will
7387          presently be {int*} -- but we need {int}.  */
7388       pattern = TREE_TYPE (t);
7389       args = TREE_PURPOSE (t);
7390     }
7391   else
7392     {
7393       pattern = TREE_TYPE (templ);
7394       args = CLASSTYPE_TI_ARGS (type);
7395     }
7396
7397   /* If the template we're instantiating is incomplete, then clearly
7398      there's nothing we can do.  */
7399   if (!COMPLETE_TYPE_P (pattern))
7400     return type;
7401
7402   /* If we've recursively instantiated too many templates, stop.  */
7403   if (! push_tinst_level (type))
7404     return type;
7405
7406   /* Now we're really doing the instantiation.  Mark the type as in
7407      the process of being defined.  */
7408   TYPE_BEING_DEFINED (type) = 1;
7409
7410   /* We may be in the middle of deferred access check.  Disable
7411      it now.  */
7412   push_deferring_access_checks (dk_no_deferred);
7413
7414   push_to_top_level ();
7415   /* Use #pragma pack from the template context.  */
7416   saved_maximum_field_alignment = maximum_field_alignment;
7417   maximum_field_alignment = TYPE_PRECISION (pattern);
7418
7419   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7420
7421   /* Set the input location to the most specialized template definition.
7422      This is needed if tsubsting causes an error.  */
7423   typedecl = TYPE_MAIN_DECL (pattern);
7424   input_location = DECL_SOURCE_LOCATION (typedecl);
7425
7426   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7427   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7428   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7429   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7430   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7431   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7432   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7433   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7434   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7435   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7436   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7437   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7438   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7439   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7440   if (ANON_AGGR_TYPE_P (pattern))
7441     SET_ANON_AGGR_TYPE_P (type);
7442   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7443     {
7444       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7445       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7446     }
7447
7448   pbinfo = TYPE_BINFO (pattern);
7449
7450   /* We should never instantiate a nested class before its enclosing
7451      class; we need to look up the nested class by name before we can
7452      instantiate it, and that lookup should instantiate the enclosing
7453      class.  */
7454   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7455               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7456               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7457
7458   base_list = NULL_TREE;
7459   if (BINFO_N_BASE_BINFOS (pbinfo))
7460     {
7461       tree pbase_binfo;
7462       tree context = TYPE_CONTEXT (type);
7463       tree pushed_scope;
7464       int i;
7465
7466       /* We must enter the scope containing the type, as that is where
7467          the accessibility of types named in dependent bases are
7468          looked up from.  */
7469       pushed_scope = push_scope (context ? context : global_namespace);
7470
7471       /* Substitute into each of the bases to determine the actual
7472          basetypes.  */
7473       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7474         {
7475           tree base;
7476           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7477           tree expanded_bases = NULL_TREE;
7478           int idx, len = 1;
7479
7480           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7481             {
7482               expanded_bases = 
7483                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7484                                        args, tf_error, NULL_TREE);
7485               if (expanded_bases == error_mark_node)
7486                 continue;
7487
7488               len = TREE_VEC_LENGTH (expanded_bases);
7489             }
7490
7491           for (idx = 0; idx < len; idx++)
7492             {
7493               if (expanded_bases)
7494                 /* Extract the already-expanded base class.  */
7495                 base = TREE_VEC_ELT (expanded_bases, idx);
7496               else
7497                 /* Substitute to figure out the base class.  */
7498                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7499                                NULL_TREE);
7500
7501               if (base == error_mark_node)
7502                 continue;
7503
7504               base_list = tree_cons (access, base, base_list);
7505               if (BINFO_VIRTUAL_P (pbase_binfo))
7506                 TREE_TYPE (base_list) = integer_type_node;
7507             }
7508         }
7509
7510       /* The list is now in reverse order; correct that.  */
7511       base_list = nreverse (base_list);
7512
7513       if (pushed_scope)
7514         pop_scope (pushed_scope);
7515     }
7516   /* Now call xref_basetypes to set up all the base-class
7517      information.  */
7518   xref_basetypes (type, base_list);
7519
7520   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7521                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7522                                   args, tf_error, NULL_TREE);
7523
7524   /* Now that our base classes are set up, enter the scope of the
7525      class, so that name lookups into base classes, etc. will work
7526      correctly.  This is precisely analogous to what we do in
7527      begin_class_definition when defining an ordinary non-template
7528      class, except we also need to push the enclosing classes.  */
7529   push_nested_class (type);
7530
7531   /* Now members are processed in the order of declaration.  */
7532   for (member = CLASSTYPE_DECL_LIST (pattern);
7533        member; member = TREE_CHAIN (member))
7534     {
7535       tree t = TREE_VALUE (member);
7536
7537       if (TREE_PURPOSE (member))
7538         {
7539           if (TYPE_P (t))
7540             {
7541               /* Build new CLASSTYPE_NESTED_UTDS.  */
7542
7543               tree newtag;
7544               bool class_template_p;
7545
7546               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7547                                   && TYPE_LANG_SPECIFIC (t)
7548                                   && CLASSTYPE_IS_TEMPLATE (t));
7549               /* If the member is a class template, then -- even after
7550                  substitution -- there may be dependent types in the
7551                  template argument list for the class.  We increment
7552                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7553                  that function will assume that no types are dependent
7554                  when outside of a template.  */
7555               if (class_template_p)
7556                 ++processing_template_decl;
7557               newtag = tsubst (t, args, tf_error, NULL_TREE);
7558               if (class_template_p)
7559                 --processing_template_decl;
7560               if (newtag == error_mark_node)
7561                 continue;
7562
7563               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7564                 {
7565                   tree name = TYPE_IDENTIFIER (t);
7566
7567                   if (class_template_p)
7568                     /* Unfortunately, lookup_template_class sets
7569                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7570                        instantiation (i.e., for the type of a member
7571                        template class nested within a template class.)
7572                        This behavior is required for
7573                        maybe_process_partial_specialization to work
7574                        correctly, but is not accurate in this case;
7575                        the TAG is not an instantiation of anything.
7576                        (The corresponding TEMPLATE_DECL is an
7577                        instantiation, but the TYPE is not.) */
7578                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7579
7580                   /* Now, we call pushtag to put this NEWTAG into the scope of
7581                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7582                      pushtag calling push_template_decl.  We don't have to do
7583                      this for enums because it will already have been done in
7584                      tsubst_enum.  */
7585                   if (name)
7586                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7587                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7588                 }
7589             }
7590           else if (TREE_CODE (t) == FUNCTION_DECL
7591                    || DECL_FUNCTION_TEMPLATE_P (t))
7592             {
7593               /* Build new TYPE_METHODS.  */
7594               tree r;
7595
7596               if (TREE_CODE (t) == TEMPLATE_DECL)
7597                 ++processing_template_decl;
7598               r = tsubst (t, args, tf_error, NULL_TREE);
7599               if (TREE_CODE (t) == TEMPLATE_DECL)
7600                 --processing_template_decl;
7601               set_current_access_from_decl (r);
7602               finish_member_declaration (r);
7603             }
7604           else
7605             {
7606               /* Build new TYPE_FIELDS.  */
7607               if (TREE_CODE (t) == STATIC_ASSERT)
7608                 {
7609                   tree condition = 
7610                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7611                                  tf_warning_or_error, NULL_TREE,
7612                                  /*integral_constant_expression_p=*/true);
7613                   finish_static_assert (condition,
7614                                         STATIC_ASSERT_MESSAGE (t), 
7615                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7616                                         /*member_p=*/true);
7617                 }
7618               else if (TREE_CODE (t) != CONST_DECL)
7619                 {
7620                   tree r;
7621
7622                   /* The file and line for this declaration, to
7623                      assist in error message reporting.  Since we
7624                      called push_tinst_level above, we don't need to
7625                      restore these.  */
7626                   input_location = DECL_SOURCE_LOCATION (t);
7627
7628                   if (TREE_CODE (t) == TEMPLATE_DECL)
7629                     ++processing_template_decl;
7630                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7631                   if (TREE_CODE (t) == TEMPLATE_DECL)
7632                     --processing_template_decl;
7633                   if (TREE_CODE (r) == VAR_DECL)
7634                     {
7635                       /* In [temp.inst]:
7636
7637                            [t]he initialization (and any associated
7638                            side-effects) of a static data member does
7639                            not occur unless the static data member is
7640                            itself used in a way that requires the
7641                            definition of the static data member to
7642                            exist.
7643
7644                          Therefore, we do not substitute into the
7645                          initialized for the static data member here.  */
7646                       finish_static_data_member_decl
7647                         (r,
7648                          /*init=*/NULL_TREE,
7649                          /*init_const_expr_p=*/false,
7650                          /*asmspec_tree=*/NULL_TREE,
7651                          /*flags=*/0);
7652                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7653                         check_static_variable_definition (r, TREE_TYPE (r));
7654                     }
7655                   else if (TREE_CODE (r) == FIELD_DECL)
7656                     {
7657                       /* Determine whether R has a valid type and can be
7658                          completed later.  If R is invalid, then it is
7659                          replaced by error_mark_node so that it will not be
7660                          added to TYPE_FIELDS.  */
7661                       tree rtype = TREE_TYPE (r);
7662                       if (can_complete_type_without_circularity (rtype))
7663                         complete_type (rtype);
7664
7665                       if (!COMPLETE_TYPE_P (rtype))
7666                         {
7667                           cxx_incomplete_type_error (r, rtype);
7668                           r = error_mark_node;
7669                         }
7670                     }
7671
7672                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7673                      such a thing will already have been added to the field
7674                      list by tsubst_enum in finish_member_declaration in the
7675                      CLASSTYPE_NESTED_UTDS case above.  */
7676                   if (!(TREE_CODE (r) == TYPE_DECL
7677                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7678                         && DECL_ARTIFICIAL (r)))
7679                     {
7680                       set_current_access_from_decl (r);
7681                       finish_member_declaration (r);
7682                     }
7683                 }
7684             }
7685         }
7686       else
7687         {
7688           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7689             {
7690               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7691
7692               tree friend_type = t;
7693               bool adjust_processing_template_decl = false;
7694
7695               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7696                 {
7697                   /* template <class T> friend class C;  */
7698                   friend_type = tsubst_friend_class (friend_type, args);
7699                   adjust_processing_template_decl = true;
7700                 }
7701               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7702                 {
7703                   /* template <class T> friend class C::D;  */
7704                   friend_type = tsubst (friend_type, args,
7705                                         tf_warning_or_error, NULL_TREE);
7706                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7707                     friend_type = TREE_TYPE (friend_type);
7708                   adjust_processing_template_decl = true;
7709                 }
7710               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7711                 {
7712                   /* This could be either
7713
7714                        friend class T::C;
7715
7716                      when dependent_type_p is false or
7717
7718                        template <class U> friend class T::C;
7719
7720                      otherwise.  */
7721                   friend_type = tsubst (friend_type, args,
7722                                         tf_warning_or_error, NULL_TREE);
7723                   /* Bump processing_template_decl for correct
7724                      dependent_type_p calculation.  */
7725                   ++processing_template_decl;
7726                   if (dependent_type_p (friend_type))
7727                     adjust_processing_template_decl = true;
7728                   --processing_template_decl;
7729                 }
7730               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7731                        && hidden_name_p (TYPE_NAME (friend_type)))
7732                 {
7733                   /* friend class C;
7734
7735                      where C hasn't been declared yet.  Let's lookup name
7736                      from namespace scope directly, bypassing any name that
7737                      come from dependent base class.  */
7738                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7739
7740                   /* The call to xref_tag_from_type does injection for friend
7741                      classes.  */
7742                   push_nested_namespace (ns);
7743                   friend_type =
7744                     xref_tag_from_type (friend_type, NULL_TREE,
7745                                         /*tag_scope=*/ts_current);
7746                   pop_nested_namespace (ns);
7747                 }
7748               else if (uses_template_parms (friend_type))
7749                 /* friend class C<T>;  */
7750                 friend_type = tsubst (friend_type, args,
7751                                       tf_warning_or_error, NULL_TREE);
7752               /* Otherwise it's
7753
7754                    friend class C;
7755
7756                  where C is already declared or
7757
7758                    friend class C<int>;
7759
7760                  We don't have to do anything in these cases.  */
7761
7762               if (adjust_processing_template_decl)
7763                 /* Trick make_friend_class into realizing that the friend
7764                    we're adding is a template, not an ordinary class.  It's
7765                    important that we use make_friend_class since it will
7766                    perform some error-checking and output cross-reference
7767                    information.  */
7768                 ++processing_template_decl;
7769
7770               if (friend_type != error_mark_node)
7771                 make_friend_class (type, friend_type, /*complain=*/false);
7772
7773               if (adjust_processing_template_decl)
7774                 --processing_template_decl;
7775             }
7776           else
7777             {
7778               /* Build new DECL_FRIENDLIST.  */
7779               tree r;
7780
7781               /* The file and line for this declaration, to
7782                  assist in error message reporting.  Since we
7783                  called push_tinst_level above, we don't need to
7784                  restore these.  */
7785               input_location = DECL_SOURCE_LOCATION (t);
7786
7787               if (TREE_CODE (t) == TEMPLATE_DECL)
7788                 {
7789                   ++processing_template_decl;
7790                   push_deferring_access_checks (dk_no_check);
7791                 }
7792
7793               r = tsubst_friend_function (t, args);
7794               add_friend (type, r, /*complain=*/false);
7795               if (TREE_CODE (t) == TEMPLATE_DECL)
7796                 {
7797                   pop_deferring_access_checks ();
7798                   --processing_template_decl;
7799                 }
7800             }
7801         }
7802     }
7803
7804   /* Set the file and line number information to whatever is given for
7805      the class itself.  This puts error messages involving generated
7806      implicit functions at a predictable point, and the same point
7807      that would be used for non-template classes.  */
7808   input_location = DECL_SOURCE_LOCATION (typedecl);
7809
7810   unreverse_member_declarations (type);
7811   finish_struct_1 (type);
7812   TYPE_BEING_DEFINED (type) = 0;
7813
7814   /* Now that the class is complete, instantiate default arguments for
7815      any member functions.  We don't do this earlier because the
7816      default arguments may reference members of the class.  */
7817   if (!PRIMARY_TEMPLATE_P (templ))
7818     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7819       if (TREE_CODE (t) == FUNCTION_DECL
7820           /* Implicitly generated member functions will not have template
7821              information; they are not instantiations, but instead are
7822              created "fresh" for each instantiation.  */
7823           && DECL_TEMPLATE_INFO (t))
7824         tsubst_default_arguments (t);
7825
7826   /* Some typedefs referenced from within the template code need to be access
7827      checked at template instantiation time, i.e now. These types were
7828      added to the template at parsing time. Let's get those and perform
7829      the access checks then.  */
7830   perform_typedefs_access_check (pattern, args);
7831   perform_deferred_access_checks ();
7832   pop_nested_class ();
7833   maximum_field_alignment = saved_maximum_field_alignment;
7834   pop_from_top_level ();
7835   pop_deferring_access_checks ();
7836   pop_tinst_level ();
7837
7838   /* The vtable for a template class can be emitted in any translation
7839      unit in which the class is instantiated.  When there is no key
7840      method, however, finish_struct_1 will already have added TYPE to
7841      the keyed_classes list.  */
7842   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7843     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7844
7845   return type;
7846 }
7847
7848 static tree
7849 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7850 {
7851   tree r;
7852
7853   if (!t)
7854     r = t;
7855   else if (TYPE_P (t))
7856     r = tsubst (t, args, complain, in_decl);
7857   else
7858     {
7859       r = tsubst_expr (t, args, complain, in_decl,
7860                        /*integral_constant_expression_p=*/true);
7861       r = fold_non_dependent_expr (r);
7862     }
7863   return r;
7864 }
7865
7866 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
7867    NONTYPE_ARGUMENT_PACK.  */
7868
7869 static tree
7870 make_fnparm_pack (tree spec_parm)
7871 {
7872   /* Collect all of the extra "packed" parameters into an
7873      argument pack.  */
7874   tree parmvec;
7875   tree parmtypevec;
7876   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
7877   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
7878   int i, len = list_length (spec_parm);
7879
7880   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
7881   parmvec = make_tree_vec (len);
7882   parmtypevec = make_tree_vec (len);
7883   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
7884     {
7885       TREE_VEC_ELT (parmvec, i) = spec_parm;
7886       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
7887     }
7888
7889   /* Build the argument packs.  */
7890   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
7891   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
7892   TREE_TYPE (argpack) = argtypepack;
7893
7894   return argpack;
7895 }        
7896
7897 /* Substitute ARGS into T, which is an pack expansion
7898    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7899    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7900    (if only a partial substitution could be performed) or
7901    ERROR_MARK_NODE if there was an error.  */
7902 tree
7903 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7904                        tree in_decl)
7905 {
7906   tree pattern;
7907   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7908   tree first_arg_pack; int i, len = -1;
7909   tree result;
7910   int incomplete = 0;
7911   bool very_local_specializations = false;
7912
7913   gcc_assert (PACK_EXPANSION_P (t));
7914   pattern = PACK_EXPANSION_PATTERN (t);
7915
7916   /* Determine the argument packs that will instantiate the parameter
7917      packs used in the expansion expression. While we're at it,
7918      compute the number of arguments to be expanded and make sure it
7919      is consistent.  */
7920   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7921        pack = TREE_CHAIN (pack))
7922     {
7923       tree parm_pack = TREE_VALUE (pack);
7924       tree arg_pack = NULL_TREE;
7925       tree orig_arg = NULL_TREE;
7926
7927       if (TREE_CODE (parm_pack) == PARM_DECL)
7928         {
7929           arg_pack = retrieve_local_specialization (parm_pack);
7930           if (arg_pack == NULL_TREE)
7931             {
7932               /* This can happen for a parameter name used later in a function
7933                  declaration (such as in a late-specified return type).  Just
7934                  make a dummy decl, since it's only used for its type.  */
7935               gcc_assert (cp_unevaluated_operand != 0);
7936               arg_pack = tsubst_decl (parm_pack, args, complain);
7937               arg_pack = make_fnparm_pack (arg_pack);
7938             }
7939         }
7940       else
7941         {
7942           int level, idx, levels;
7943           template_parm_level_and_index (parm_pack, &level, &idx);
7944
7945           levels = TMPL_ARGS_DEPTH (args);
7946           if (level <= levels)
7947             arg_pack = TMPL_ARG (args, level, idx);
7948         }
7949
7950       orig_arg = arg_pack;
7951       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7952         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7953       
7954       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7955         /* This can only happen if we forget to expand an argument
7956            pack somewhere else. Just return an error, silently.  */
7957         {
7958           result = make_tree_vec (1);
7959           TREE_VEC_ELT (result, 0) = error_mark_node;
7960           return result;
7961         }
7962
7963       if (arg_pack
7964           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
7965           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
7966         {
7967           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
7968           tree pattern = PACK_EXPANSION_PATTERN (expansion);
7969           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
7970               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
7971             /* The argument pack that the parameter maps to is just an
7972                expansion of the parameter itself, such as one would
7973                find in the implicit typedef of a class inside the
7974                class itself.  Consider this parameter "unsubstituted",
7975                so that we will maintain the outer pack expansion.  */
7976             arg_pack = NULL_TREE;
7977         }
7978           
7979       if (arg_pack)
7980         {
7981           int my_len = 
7982             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7983
7984           /* It's all-or-nothing with incomplete argument packs.  */
7985           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7986             return error_mark_node;
7987           
7988           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7989             incomplete = 1;
7990
7991           if (len < 0)
7992             {
7993               len = my_len;
7994               first_arg_pack = arg_pack;
7995             }
7996           else if (len != my_len)
7997             {
7998               if (incomplete)
7999                 /* We got explicit args for some packs but not others;
8000                    do nothing now and try again after deduction.  */
8001                 return t;
8002               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8003                 error ("mismatched argument pack lengths while expanding "
8004                        "%<%T%>",
8005                        pattern);
8006               else
8007                 error ("mismatched argument pack lengths while expanding "
8008                        "%<%E%>",
8009                        pattern);
8010               return error_mark_node;
8011             }
8012
8013           /* Keep track of the parameter packs and their corresponding
8014              argument packs.  */
8015           packs = tree_cons (parm_pack, arg_pack, packs);
8016           TREE_TYPE (packs) = orig_arg;
8017         }
8018       else
8019         /* We can't substitute for this parameter pack.  */
8020         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8021                                          TREE_VALUE (pack),
8022                                          unsubstituted_packs);
8023     }
8024
8025   /* We cannot expand this expansion expression, because we don't have
8026      all of the argument packs we need. Substitute into the pattern
8027      and return a PACK_EXPANSION_*. The caller will need to deal with
8028      that.  */
8029   if (unsubstituted_packs)
8030     {
8031       tree new_pat;
8032       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8033         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8034                                /*integral_constant_expression_p=*/false);
8035       else
8036         new_pat = tsubst (pattern, args, complain, in_decl);
8037       return make_pack_expansion (new_pat);
8038     }
8039
8040   /* We could not find any argument packs that work.  */
8041   if (len < 0)
8042     return error_mark_node;
8043
8044   if (!local_specializations)
8045     {
8046       /* We're in a late-specified return type, so we don't have a local
8047          specializations table.  Create one for doing this expansion.  */
8048       very_local_specializations = true;
8049       local_specializations = htab_create (37,
8050                                            hash_local_specialization,
8051                                            eq_local_specializations,
8052                                            NULL);
8053     }
8054
8055   /* For each argument in each argument pack, substitute into the
8056      pattern.  */
8057   result = make_tree_vec (len + incomplete);
8058   for (i = 0; i < len + incomplete; ++i)
8059     {
8060       /* For parameter pack, change the substitution of the parameter
8061          pack to the ith argument in its argument pack, then expand
8062          the pattern.  */
8063       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8064         {
8065           tree parm = TREE_PURPOSE (pack);
8066
8067           if (TREE_CODE (parm) == PARM_DECL)
8068             {
8069               /* Select the Ith argument from the pack.  */
8070               tree arg = make_node (ARGUMENT_PACK_SELECT);
8071               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8072               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8073               mark_used (parm);
8074               register_local_specialization (arg, parm);
8075             }
8076           else
8077             {
8078               tree value = parm;
8079               int idx, level;
8080               template_parm_level_and_index (parm, &level, &idx);
8081               
8082               if (i < len) 
8083                 {
8084                   /* Select the Ith argument from the pack. */
8085                   value = make_node (ARGUMENT_PACK_SELECT);
8086                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8087                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8088                 }
8089
8090               /* Update the corresponding argument.  */
8091               TMPL_ARG (args, level, idx) = value;
8092             }
8093         }
8094
8095       /* Substitute into the PATTERN with the altered arguments.  */
8096       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8097         TREE_VEC_ELT (result, i) = 
8098           tsubst_expr (pattern, args, complain, in_decl,
8099                        /*integral_constant_expression_p=*/false);
8100       else
8101         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8102
8103       if (i == len)
8104         /* When we have incomplete argument packs, the last "expanded"
8105            result is itself a pack expansion, which allows us
8106            to deduce more arguments.  */
8107         TREE_VEC_ELT (result, i) = 
8108           make_pack_expansion (TREE_VEC_ELT (result, i));
8109
8110       if (TREE_VEC_ELT (result, i) == error_mark_node)
8111         {
8112           result = error_mark_node;
8113           break;
8114         }
8115     }
8116
8117   /* Update ARGS to restore the substitution from parameter packs to
8118      their argument packs.  */
8119   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8120     {
8121       tree parm = TREE_PURPOSE (pack);
8122
8123       if (TREE_CODE (parm) == PARM_DECL)
8124         register_local_specialization (TREE_TYPE (pack), parm);
8125       else
8126         {
8127           int idx, level;
8128           template_parm_level_and_index (parm, &level, &idx);
8129           
8130           /* Update the corresponding argument.  */
8131           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8132             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8133               TREE_TYPE (pack);
8134           else
8135             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8136         }
8137     }
8138
8139   if (very_local_specializations)
8140     {
8141       htab_delete (local_specializations);
8142       local_specializations = NULL;
8143     }
8144   
8145   return result;
8146 }
8147
8148 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8149    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8150    parameter packs; all parms generated from a function parameter pack will
8151    have the same DECL_PARM_INDEX.  */
8152
8153 tree
8154 get_pattern_parm (tree parm, tree tmpl)
8155 {
8156   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8157   tree patparm;
8158
8159   if (DECL_ARTIFICIAL (parm))
8160     {
8161       for (patparm = DECL_ARGUMENTS (pattern);
8162            patparm; patparm = TREE_CHAIN (patparm))
8163         if (DECL_ARTIFICIAL (patparm)
8164             && DECL_NAME (parm) == DECL_NAME (patparm))
8165           break;
8166     }
8167   else
8168     {
8169       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8170       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8171       gcc_assert (DECL_PARM_INDEX (patparm)
8172                   == DECL_PARM_INDEX (parm));
8173     }
8174
8175   return patparm;
8176 }
8177
8178 /* Substitute ARGS into the vector or list of template arguments T.  */
8179
8180 static tree
8181 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8182 {
8183   tree orig_t = t;
8184   int len = TREE_VEC_LENGTH (t);
8185   int need_new = 0, i, expanded_len_adjust = 0, out;
8186   tree *elts = (tree *) alloca (len * sizeof (tree));
8187
8188   for (i = 0; i < len; i++)
8189     {
8190       tree orig_arg = TREE_VEC_ELT (t, i);
8191       tree new_arg;
8192
8193       if (TREE_CODE (orig_arg) == TREE_VEC)
8194         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8195       else if (PACK_EXPANSION_P (orig_arg))
8196         {
8197           /* Substitute into an expansion expression.  */
8198           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8199
8200           if (TREE_CODE (new_arg) == TREE_VEC)
8201             /* Add to the expanded length adjustment the number of
8202                expanded arguments. We subtract one from this
8203                measurement, because the argument pack expression
8204                itself is already counted as 1 in
8205                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8206                the argument pack is empty.  */
8207             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8208         }
8209       else if (ARGUMENT_PACK_P (orig_arg))
8210         {
8211           /* Substitute into each of the arguments.  */
8212           new_arg = TYPE_P (orig_arg)
8213             ? cxx_make_type (TREE_CODE (orig_arg))
8214             : make_node (TREE_CODE (orig_arg));
8215           
8216           SET_ARGUMENT_PACK_ARGS (
8217             new_arg,
8218             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8219                                   args, complain, in_decl));
8220
8221           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8222             new_arg = error_mark_node;
8223
8224           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8225             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8226                                           complain, in_decl);
8227             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8228
8229             if (TREE_TYPE (new_arg) == error_mark_node)
8230               new_arg = error_mark_node;
8231           }
8232         }
8233       else
8234         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8235
8236       if (new_arg == error_mark_node)
8237         return error_mark_node;
8238
8239       elts[i] = new_arg;
8240       if (new_arg != orig_arg)
8241         need_new = 1;
8242     }
8243
8244   if (!need_new)
8245     return t;
8246
8247   /* Make space for the expanded arguments coming from template
8248      argument packs.  */
8249   t = make_tree_vec (len + expanded_len_adjust);
8250   for (i = 0, out = 0; i < len; i++)
8251     {
8252       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8253            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8254           && TREE_CODE (elts[i]) == TREE_VEC)
8255         {
8256           int idx;
8257
8258           /* Now expand the template argument pack "in place".  */
8259           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8260             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8261         }
8262       else
8263         {
8264           TREE_VEC_ELT (t, out) = elts[i];
8265           out++;
8266         }
8267     }
8268
8269   return t;
8270 }
8271
8272 /* Return the result of substituting ARGS into the template parameters
8273    given by PARMS.  If there are m levels of ARGS and m + n levels of
8274    PARMS, then the result will contain n levels of PARMS.  For
8275    example, if PARMS is `template <class T> template <class U>
8276    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8277    result will be `template <int*, double, class V>'.  */
8278
8279 static tree
8280 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8281 {
8282   tree r = NULL_TREE;
8283   tree* new_parms;
8284
8285   /* When substituting into a template, we must set
8286      PROCESSING_TEMPLATE_DECL as the template parameters may be
8287      dependent if they are based on one-another, and the dependency
8288      predicates are short-circuit outside of templates.  */
8289   ++processing_template_decl;
8290
8291   for (new_parms = &r;
8292        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8293        new_parms = &(TREE_CHAIN (*new_parms)),
8294          parms = TREE_CHAIN (parms))
8295     {
8296       tree new_vec =
8297         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8298       int i;
8299
8300       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8301         {
8302           tree tuple;
8303           tree default_value;
8304           tree parm_decl;
8305
8306           if (parms == error_mark_node)
8307             continue;
8308
8309           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8310
8311           if (tuple == error_mark_node)
8312             continue;
8313
8314           default_value = TREE_PURPOSE (tuple);
8315           parm_decl = TREE_VALUE (tuple);
8316
8317           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8318           if (TREE_CODE (parm_decl) == PARM_DECL
8319               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8320             parm_decl = error_mark_node;
8321           default_value = tsubst_template_arg (default_value, args,
8322                                                complain, NULL_TREE);
8323
8324           tuple = build_tree_list (default_value, parm_decl);
8325           TREE_VEC_ELT (new_vec, i) = tuple;
8326         }
8327
8328       *new_parms =
8329         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8330                              - TMPL_ARGS_DEPTH (args)),
8331                    new_vec, NULL_TREE);
8332     }
8333
8334   --processing_template_decl;
8335
8336   return r;
8337 }
8338
8339 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8340    type T.  If T is not an aggregate or enumeration type, it is
8341    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8342    ENTERING_SCOPE is nonzero, T is the context for a template which
8343    we are presently tsubst'ing.  Return the substituted value.  */
8344
8345 static tree
8346 tsubst_aggr_type (tree t,
8347                   tree args,
8348                   tsubst_flags_t complain,
8349                   tree in_decl,
8350                   int entering_scope)
8351 {
8352   if (t == NULL_TREE)
8353     return NULL_TREE;
8354
8355   switch (TREE_CODE (t))
8356     {
8357     case RECORD_TYPE:
8358       if (TYPE_PTRMEMFUNC_P (t))
8359         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8360
8361       /* Else fall through.  */
8362     case ENUMERAL_TYPE:
8363     case UNION_TYPE:
8364       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8365         {
8366           tree argvec;
8367           tree context;
8368           tree r;
8369           int saved_unevaluated_operand;
8370           int saved_inhibit_evaluation_warnings;
8371
8372           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8373           saved_unevaluated_operand = cp_unevaluated_operand;
8374           cp_unevaluated_operand = 0;
8375           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8376           c_inhibit_evaluation_warnings = 0;
8377
8378           /* First, determine the context for the type we are looking
8379              up.  */
8380           context = TYPE_CONTEXT (t);
8381           if (context)
8382             {
8383               context = tsubst_aggr_type (context, args, complain,
8384                                           in_decl, /*entering_scope=*/1);
8385               /* If context is a nested class inside a class template,
8386                  it may still need to be instantiated (c++/33959).  */
8387               if (TYPE_P (context))
8388                 context = complete_type (context);
8389             }
8390
8391           /* Then, figure out what arguments are appropriate for the
8392              type we are trying to find.  For example, given:
8393
8394                template <class T> struct S;
8395                template <class T, class U> void f(T, U) { S<U> su; }
8396
8397              and supposing that we are instantiating f<int, double>,
8398              then our ARGS will be {int, double}, but, when looking up
8399              S we only want {double}.  */
8400           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8401                                          complain, in_decl);
8402           if (argvec == error_mark_node)
8403             r = error_mark_node;
8404           else
8405             {
8406               r = lookup_template_class (t, argvec, in_decl, context,
8407                                          entering_scope, complain);
8408               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8409             }
8410
8411           cp_unevaluated_operand = saved_unevaluated_operand;
8412           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8413
8414           return r;
8415         }
8416       else
8417         /* This is not a template type, so there's nothing to do.  */
8418         return t;
8419
8420     default:
8421       return tsubst (t, args, complain, in_decl);
8422     }
8423 }
8424
8425 /* Substitute into the default argument ARG (a default argument for
8426    FN), which has the indicated TYPE.  */
8427
8428 tree
8429 tsubst_default_argument (tree fn, tree type, tree arg)
8430 {
8431   tree saved_class_ptr = NULL_TREE;
8432   tree saved_class_ref = NULL_TREE;
8433
8434   /* This default argument came from a template.  Instantiate the
8435      default argument here, not in tsubst.  In the case of
8436      something like:
8437
8438        template <class T>
8439        struct S {
8440          static T t();
8441          void f(T = t());
8442        };
8443
8444      we must be careful to do name lookup in the scope of S<T>,
8445      rather than in the current class.  */
8446   push_access_scope (fn);
8447   /* The "this" pointer is not valid in a default argument.  */
8448   if (cfun)
8449     {
8450       saved_class_ptr = current_class_ptr;
8451       cp_function_chain->x_current_class_ptr = NULL_TREE;
8452       saved_class_ref = current_class_ref;
8453       cp_function_chain->x_current_class_ref = NULL_TREE;
8454     }
8455
8456   push_deferring_access_checks(dk_no_deferred);
8457   /* The default argument expression may cause implicitly defined
8458      member functions to be synthesized, which will result in garbage
8459      collection.  We must treat this situation as if we were within
8460      the body of function so as to avoid collecting live data on the
8461      stack.  */
8462   ++function_depth;
8463   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8464                      tf_warning_or_error, NULL_TREE,
8465                      /*integral_constant_expression_p=*/false);
8466   --function_depth;
8467   pop_deferring_access_checks();
8468
8469   /* Restore the "this" pointer.  */
8470   if (cfun)
8471     {
8472       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8473       cp_function_chain->x_current_class_ref = saved_class_ref;
8474     }
8475
8476   /* Make sure the default argument is reasonable.  */
8477   arg = check_default_argument (type, arg);
8478
8479   pop_access_scope (fn);
8480
8481   return arg;
8482 }
8483
8484 /* Substitute into all the default arguments for FN.  */
8485
8486 static void
8487 tsubst_default_arguments (tree fn)
8488 {
8489   tree arg;
8490   tree tmpl_args;
8491
8492   tmpl_args = DECL_TI_ARGS (fn);
8493
8494   /* If this function is not yet instantiated, we certainly don't need
8495      its default arguments.  */
8496   if (uses_template_parms (tmpl_args))
8497     return;
8498
8499   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8500        arg;
8501        arg = TREE_CHAIN (arg))
8502     if (TREE_PURPOSE (arg))
8503       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8504                                                     TREE_VALUE (arg),
8505                                                     TREE_PURPOSE (arg));
8506 }
8507
8508 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8509    result of the substitution.  Issue error and warning messages under
8510    control of COMPLAIN.  */
8511
8512 static tree
8513 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8514 {
8515 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8516   location_t saved_loc;
8517   tree r = NULL_TREE;
8518   tree in_decl = t;
8519   hashval_t hash = 0;
8520
8521   /* Set the filename and linenumber to improve error-reporting.  */
8522   saved_loc = input_location;
8523   input_location = DECL_SOURCE_LOCATION (t);
8524
8525   switch (TREE_CODE (t))
8526     {
8527     case TEMPLATE_DECL:
8528       {
8529         /* We can get here when processing a member function template,
8530            member class template, or template template parameter.  */
8531         tree decl = DECL_TEMPLATE_RESULT (t);
8532         tree spec;
8533         tree tmpl_args;
8534         tree full_args;
8535
8536         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8537           {
8538             /* Template template parameter is treated here.  */
8539             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8540             if (new_type == error_mark_node)
8541               RETURN (error_mark_node);
8542
8543             r = copy_decl (t);
8544             TREE_CHAIN (r) = NULL_TREE;
8545             TREE_TYPE (r) = new_type;
8546             DECL_TEMPLATE_RESULT (r)
8547               = build_decl (DECL_SOURCE_LOCATION (decl),
8548                             TYPE_DECL, DECL_NAME (decl), new_type);
8549             DECL_TEMPLATE_PARMS (r)
8550               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8551                                        complain);
8552             TYPE_NAME (new_type) = r;
8553             break;
8554           }
8555
8556         /* We might already have an instance of this template.
8557            The ARGS are for the surrounding class type, so the
8558            full args contain the tsubst'd args for the context,
8559            plus the innermost args from the template decl.  */
8560         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8561           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8562           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8563         /* Because this is a template, the arguments will still be
8564            dependent, even after substitution.  If
8565            PROCESSING_TEMPLATE_DECL is not set, the dependency
8566            predicates will short-circuit.  */
8567         ++processing_template_decl;
8568         full_args = tsubst_template_args (tmpl_args, args,
8569                                           complain, in_decl);
8570         --processing_template_decl;
8571         if (full_args == error_mark_node)
8572           RETURN (error_mark_node);
8573
8574         /* If this is a default template template argument,
8575            tsubst might not have changed anything.  */
8576         if (full_args == tmpl_args)
8577           RETURN (t);
8578
8579         hash = hash_tmpl_and_args (t, full_args);
8580         spec = retrieve_specialization (t, full_args, hash);
8581         if (spec != NULL_TREE)
8582           {
8583             r = spec;
8584             break;
8585           }
8586
8587         /* Make a new template decl.  It will be similar to the
8588            original, but will record the current template arguments.
8589            We also create a new function declaration, which is just
8590            like the old one, but points to this new template, rather
8591            than the old one.  */
8592         r = copy_decl (t);
8593         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8594         TREE_CHAIN (r) = NULL_TREE;
8595
8596         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
8597
8598         if (TREE_CODE (decl) == TYPE_DECL)
8599           {
8600             tree new_type;
8601             ++processing_template_decl;
8602             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8603             --processing_template_decl;
8604             if (new_type == error_mark_node)
8605               RETURN (error_mark_node);
8606
8607             TREE_TYPE (r) = new_type;
8608             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8609             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8610             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8611             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8612           }
8613         else
8614           {
8615             tree new_decl;
8616             ++processing_template_decl;
8617             new_decl = tsubst (decl, args, complain, in_decl);
8618             --processing_template_decl;
8619             if (new_decl == error_mark_node)
8620               RETURN (error_mark_node);
8621
8622             DECL_TEMPLATE_RESULT (r) = new_decl;
8623             DECL_TI_TEMPLATE (new_decl) = r;
8624             TREE_TYPE (r) = TREE_TYPE (new_decl);
8625             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8626             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8627           }
8628
8629         SET_DECL_IMPLICIT_INSTANTIATION (r);
8630         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8631         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8632
8633         /* The template parameters for this new template are all the
8634            template parameters for the old template, except the
8635            outermost level of parameters.  */
8636         DECL_TEMPLATE_PARMS (r)
8637           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8638                                    complain);
8639
8640         if (PRIMARY_TEMPLATE_P (t))
8641           DECL_PRIMARY_TEMPLATE (r) = r;
8642
8643         if (TREE_CODE (decl) != TYPE_DECL)
8644           /* Record this non-type partial instantiation.  */
8645           register_specialization (r, t,
8646                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8647                                    false, hash);
8648       }
8649       break;
8650
8651     case FUNCTION_DECL:
8652       {
8653         tree ctx;
8654         tree argvec = NULL_TREE;
8655         tree *friends;
8656         tree gen_tmpl;
8657         tree type;
8658         int member;
8659         int args_depth;
8660         int parms_depth;
8661
8662         /* Nobody should be tsubst'ing into non-template functions.  */
8663         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8664
8665         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8666           {
8667             tree spec;
8668             bool dependent_p;
8669
8670             /* If T is not dependent, just return it.  We have to
8671                increment PROCESSING_TEMPLATE_DECL because
8672                value_dependent_expression_p assumes that nothing is
8673                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8674             ++processing_template_decl;
8675             dependent_p = value_dependent_expression_p (t);
8676             --processing_template_decl;
8677             if (!dependent_p)
8678               RETURN (t);
8679
8680             /* Calculate the most general template of which R is a
8681                specialization, and the complete set of arguments used to
8682                specialize R.  */
8683             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8684             argvec = tsubst_template_args (DECL_TI_ARGS
8685                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8686                                            args, complain, in_decl);
8687
8688             /* Check to see if we already have this specialization.  */
8689             hash = hash_tmpl_and_args (gen_tmpl, argvec);
8690             spec = retrieve_specialization (gen_tmpl, argvec, hash);
8691
8692             if (spec)
8693               {
8694                 r = spec;
8695                 break;
8696               }
8697
8698             /* We can see more levels of arguments than parameters if
8699                there was a specialization of a member template, like
8700                this:
8701
8702                  template <class T> struct S { template <class U> void f(); }
8703                  template <> template <class U> void S<int>::f(U);
8704
8705                Here, we'll be substituting into the specialization,
8706                because that's where we can find the code we actually
8707                want to generate, but we'll have enough arguments for
8708                the most general template.
8709
8710                We also deal with the peculiar case:
8711
8712                  template <class T> struct S {
8713                    template <class U> friend void f();
8714                  };
8715                  template <class U> void f() {}
8716                  template S<int>;
8717                  template void f<double>();
8718
8719                Here, the ARGS for the instantiation of will be {int,
8720                double}.  But, we only need as many ARGS as there are
8721                levels of template parameters in CODE_PATTERN.  We are
8722                careful not to get fooled into reducing the ARGS in
8723                situations like:
8724
8725                  template <class T> struct S { template <class U> void f(U); }
8726                  template <class T> template <> void S<T>::f(int) {}
8727
8728                which we can spot because the pattern will be a
8729                specialization in this case.  */
8730             args_depth = TMPL_ARGS_DEPTH (args);
8731             parms_depth =
8732               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8733             if (args_depth > parms_depth
8734                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8735               args = get_innermost_template_args (args, parms_depth);
8736           }
8737         else
8738           {
8739             /* This special case arises when we have something like this:
8740
8741                  template <class T> struct S {
8742                    friend void f<int>(int, double);
8743                  };
8744
8745                Here, the DECL_TI_TEMPLATE for the friend declaration
8746                will be an IDENTIFIER_NODE.  We are being called from
8747                tsubst_friend_function, and we want only to create a
8748                new decl (R) with appropriate types so that we can call
8749                determine_specialization.  */
8750             gen_tmpl = NULL_TREE;
8751           }
8752
8753         if (DECL_CLASS_SCOPE_P (t))
8754           {
8755             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8756               member = 2;
8757             else
8758               member = 1;
8759             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8760                                     complain, t, /*entering_scope=*/1);
8761           }
8762         else
8763           {
8764             member = 0;
8765             ctx = DECL_CONTEXT (t);
8766           }
8767         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8768         if (type == error_mark_node)
8769           RETURN (error_mark_node);
8770
8771         /* We do NOT check for matching decls pushed separately at this
8772            point, as they may not represent instantiations of this
8773            template, and in any case are considered separate under the
8774            discrete model.  */
8775         r = copy_decl (t);
8776         DECL_USE_TEMPLATE (r) = 0;
8777         TREE_TYPE (r) = type;
8778         /* Clear out the mangled name and RTL for the instantiation.  */
8779         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8780         SET_DECL_RTL (r, NULL_RTX);
8781         /* Leave DECL_INITIAL set on deleted instantiations.  */
8782         if (!DECL_DELETED_FN (r))
8783           DECL_INITIAL (r) = NULL_TREE;
8784         DECL_CONTEXT (r) = ctx;
8785
8786         if (member && DECL_CONV_FN_P (r))
8787           /* Type-conversion operator.  Reconstruct the name, in
8788              case it's the name of one of the template's parameters.  */
8789           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8790
8791         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8792                                      complain, t);
8793         DECL_RESULT (r) = NULL_TREE;
8794
8795         TREE_STATIC (r) = 0;
8796         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8797         DECL_EXTERNAL (r) = 1;
8798         /* If this is an instantiation of a function with internal
8799            linkage, we already know what object file linkage will be
8800            assigned to the instantiation.  */
8801         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8802         DECL_DEFER_OUTPUT (r) = 0;
8803         TREE_CHAIN (r) = NULL_TREE;
8804         DECL_PENDING_INLINE_INFO (r) = 0;
8805         DECL_PENDING_INLINE_P (r) = 0;
8806         DECL_SAVED_TREE (r) = NULL_TREE;
8807         DECL_STRUCT_FUNCTION (r) = NULL;
8808         TREE_USED (r) = 0;
8809         /* We'll re-clone as appropriate in instantiate_template.  */
8810         DECL_CLONED_FUNCTION (r) = NULL_TREE;
8811
8812         /* If we aren't complaining now, return on error before we register
8813            the specialization so that we'll complain eventually.  */
8814         if ((complain & tf_error) == 0
8815             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
8816             && !grok_op_properties (r, /*complain=*/false))
8817           RETURN (error_mark_node);
8818
8819         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8820            this in the special friend case mentioned above where
8821            GEN_TMPL is NULL.  */
8822         if (gen_tmpl)
8823           {
8824             DECL_TEMPLATE_INFO (r)
8825               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8826             SET_DECL_IMPLICIT_INSTANTIATION (r);
8827             register_specialization (r, gen_tmpl, argvec, false, hash);
8828
8829             /* We're not supposed to instantiate default arguments
8830                until they are called, for a template.  But, for a
8831                declaration like:
8832
8833                  template <class T> void f ()
8834                  { extern void g(int i = T()); }
8835
8836                we should do the substitution when the template is
8837                instantiated.  We handle the member function case in
8838                instantiate_class_template since the default arguments
8839                might refer to other members of the class.  */
8840             if (!member
8841                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8842                 && !uses_template_parms (argvec))
8843               tsubst_default_arguments (r);
8844           }
8845         else
8846           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8847
8848         /* Copy the list of befriending classes.  */
8849         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8850              *friends;
8851              friends = &TREE_CHAIN (*friends))
8852           {
8853             *friends = copy_node (*friends);
8854             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8855                                             args, complain,
8856                                             in_decl);
8857           }
8858
8859         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8860           {
8861             maybe_retrofit_in_chrg (r);
8862             if (DECL_CONSTRUCTOR_P (r))
8863               grok_ctor_properties (ctx, r);
8864             /* If this is an instantiation of a member template, clone it.
8865                If it isn't, that'll be handled by
8866                clone_constructors_and_destructors.  */
8867             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8868               clone_function_decl (r, /*update_method_vec_p=*/0);
8869           }
8870         else if ((complain & tf_error) != 0
8871                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
8872                  && !grok_op_properties (r, /*complain=*/true))
8873           RETURN (error_mark_node);
8874
8875         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8876           SET_DECL_FRIEND_CONTEXT (r,
8877                                    tsubst (DECL_FRIEND_CONTEXT (t),
8878                                             args, complain, in_decl));
8879
8880         /* Possibly limit visibility based on template args.  */
8881         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8882         if (DECL_VISIBILITY_SPECIFIED (t))
8883           {
8884             DECL_VISIBILITY_SPECIFIED (r) = 0;
8885             DECL_ATTRIBUTES (r)
8886               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8887           }
8888         determine_visibility (r);
8889         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
8890             && !processing_template_decl)
8891           defaulted_late_check (r);
8892
8893         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8894                                         args, complain, in_decl);
8895       }
8896       break;
8897
8898     case PARM_DECL:
8899       {
8900         tree type = NULL_TREE;
8901         int i, len = 1;
8902         tree expanded_types = NULL_TREE;
8903         tree prev_r = NULL_TREE;
8904         tree first_r = NULL_TREE;
8905
8906         if (FUNCTION_PARAMETER_PACK_P (t))
8907           {
8908             /* If there is a local specialization that isn't a
8909                parameter pack, it means that we're doing a "simple"
8910                substitution from inside tsubst_pack_expansion. Just
8911                return the local specialization (which will be a single
8912                parm).  */
8913             tree spec = retrieve_local_specialization (t);
8914             if (spec 
8915                 && TREE_CODE (spec) == PARM_DECL
8916                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8917               RETURN (spec);
8918
8919             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8920                the parameters in this function parameter pack.  */
8921             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8922                                                     complain, in_decl);
8923             if (TREE_CODE (expanded_types) == TREE_VEC)
8924               {
8925                 len = TREE_VEC_LENGTH (expanded_types);
8926
8927                 /* Zero-length parameter packs are boring. Just substitute
8928                    into the chain.  */
8929                 if (len == 0)
8930                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
8931                                   TREE_CHAIN (t)));
8932               }
8933             else
8934               {
8935                 /* All we did was update the type. Make a note of that.  */
8936                 type = expanded_types;
8937                 expanded_types = NULL_TREE;
8938               }
8939           }
8940
8941         /* Loop through all of the parameter's we'll build. When T is
8942            a function parameter pack, LEN is the number of expanded
8943            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8944         r = NULL_TREE;
8945         for (i = 0; i < len; ++i)
8946           {
8947             prev_r = r;
8948             r = copy_node (t);
8949             if (DECL_TEMPLATE_PARM_P (t))
8950               SET_DECL_TEMPLATE_PARM_P (r);
8951
8952             /* An argument of a function parameter pack is not a parameter
8953                pack.  */
8954             FUNCTION_PARAMETER_PACK_P (r) = false;
8955
8956             if (expanded_types)
8957               /* We're on the Ith parameter of the function parameter
8958                  pack.  */
8959               {
8960                 /* Get the Ith type.  */
8961                 type = TREE_VEC_ELT (expanded_types, i);
8962
8963                 if (DECL_NAME (r))
8964                   /* Rename the parameter to include the index.  */
8965                   DECL_NAME (r) =
8966                     make_ith_pack_parameter_name (DECL_NAME (r), i);
8967               }
8968             else if (!type)
8969               /* We're dealing with a normal parameter.  */
8970               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8971
8972             type = type_decays_to (type);
8973             TREE_TYPE (r) = type;
8974             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8975
8976             if (DECL_INITIAL (r))
8977               {
8978                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
8979                   DECL_INITIAL (r) = TREE_TYPE (r);
8980                 else
8981                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
8982                                              complain, in_decl);
8983               }
8984
8985             DECL_CONTEXT (r) = NULL_TREE;
8986
8987             if (!DECL_TEMPLATE_PARM_P (r))
8988               DECL_ARG_TYPE (r) = type_passed_as (type);
8989
8990             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8991                                             args, complain, in_decl);
8992
8993             /* Keep track of the first new parameter we
8994                generate. That's what will be returned to the
8995                caller.  */
8996             if (!first_r)
8997               first_r = r;
8998
8999             /* Build a proper chain of parameters when substituting
9000                into a function parameter pack.  */
9001             if (prev_r)
9002               TREE_CHAIN (prev_r) = r;
9003           }
9004
9005         if (TREE_CHAIN (t))
9006           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
9007                                    complain, TREE_CHAIN (t));
9008
9009         /* FIRST_R contains the start of the chain we've built.  */
9010         r = first_r;
9011       }
9012       break;
9013
9014     case FIELD_DECL:
9015       {
9016         tree type;
9017
9018         r = copy_decl (t);
9019         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9020         if (type == error_mark_node)
9021           RETURN (error_mark_node);
9022         TREE_TYPE (r) = type;
9023         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9024
9025         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9026         DECL_INITIAL (r)
9027           = tsubst_expr (DECL_INITIAL (t), args,
9028                          complain, in_decl,
9029                          /*integral_constant_expression_p=*/true);
9030         /* We don't have to set DECL_CONTEXT here; it is set by
9031            finish_member_declaration.  */
9032         TREE_CHAIN (r) = NULL_TREE;
9033         if (VOID_TYPE_P (type))
9034           error ("instantiation of %q+D as type %qT", r, type);
9035
9036         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9037                                         args, complain, in_decl);
9038       }
9039       break;
9040
9041     case USING_DECL:
9042       /* We reach here only for member using decls.  */
9043       if (DECL_DEPENDENT_P (t))
9044         {
9045           r = do_class_using_decl
9046             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9047              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9048           if (!r)
9049             r = error_mark_node;
9050           else
9051             {
9052               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9053               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9054             }
9055         }
9056       else
9057         {
9058           r = copy_node (t);
9059           TREE_CHAIN (r) = NULL_TREE;
9060         }
9061       break;
9062
9063     case TYPE_DECL:
9064     case VAR_DECL:
9065       {
9066         tree argvec = NULL_TREE;
9067         tree gen_tmpl = NULL_TREE;
9068         tree spec;
9069         tree tmpl = NULL_TREE;
9070         tree ctx;
9071         tree type = NULL_TREE;
9072         bool local_p;
9073
9074         if (TREE_CODE (t) == TYPE_DECL
9075             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9076           {
9077             /* If this is the canonical decl, we don't have to
9078                mess with instantiations, and often we can't (for
9079                typename, template type parms and such).  Note that
9080                TYPE_NAME is not correct for the above test if
9081                we've copied the type for a typedef.  */
9082             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9083             if (type == error_mark_node)
9084               RETURN (error_mark_node);
9085             r = TYPE_NAME (type);
9086             break;
9087           }
9088
9089         /* Check to see if we already have the specialization we
9090            need.  */
9091         spec = NULL_TREE;
9092         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9093           {
9094             /* T is a static data member or namespace-scope entity.
9095                We have to substitute into namespace-scope variables
9096                (even though such entities are never templates) because
9097                of cases like:
9098                
9099                  template <class T> void f() { extern T t; }
9100
9101                where the entity referenced is not known until
9102                instantiation time.  */
9103             local_p = false;
9104             ctx = DECL_CONTEXT (t);
9105             if (DECL_CLASS_SCOPE_P (t))
9106               {
9107                 ctx = tsubst_aggr_type (ctx, args,
9108                                         complain,
9109                                         in_decl, /*entering_scope=*/1);
9110                 /* If CTX is unchanged, then T is in fact the
9111                    specialization we want.  That situation occurs when
9112                    referencing a static data member within in its own
9113                    class.  We can use pointer equality, rather than
9114                    same_type_p, because DECL_CONTEXT is always
9115                    canonical.  */
9116                 if (ctx == DECL_CONTEXT (t))
9117                   spec = t;
9118               }
9119
9120             if (!spec)
9121               {
9122                 tmpl = DECL_TI_TEMPLATE (t);
9123                 gen_tmpl = most_general_template (tmpl);
9124                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9125                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9126                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9127               }
9128           }
9129         else
9130           {
9131             /* A local variable.  */
9132             local_p = true;
9133             /* Subsequent calls to pushdecl will fill this in.  */
9134             ctx = NULL_TREE;
9135             spec = retrieve_local_specialization (t);
9136           }
9137         /* If we already have the specialization we need, there is
9138            nothing more to do.  */ 
9139         if (spec)
9140           {
9141             r = spec;
9142             break;
9143           }
9144
9145         /* Create a new node for the specialization we need.  */
9146         r = copy_decl (t);
9147         if (type == NULL_TREE)
9148           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9149         if (TREE_CODE (r) == VAR_DECL)
9150           {
9151             /* Even if the original location is out of scope, the
9152                newly substituted one is not.  */
9153             DECL_DEAD_FOR_LOCAL (r) = 0;
9154             DECL_INITIALIZED_P (r) = 0;
9155             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9156             if (type == error_mark_node)
9157               RETURN (error_mark_node);
9158             if (TREE_CODE (type) == FUNCTION_TYPE)
9159               {
9160                 /* It may seem that this case cannot occur, since:
9161
9162                      typedef void f();
9163                      void g() { f x; }
9164
9165                    declares a function, not a variable.  However:
9166       
9167                      typedef void f();
9168                      template <typename T> void g() { T t; }
9169                      template void g<f>();
9170
9171                    is an attempt to declare a variable with function
9172                    type.  */
9173                 error ("variable %qD has function type",
9174                        /* R is not yet sufficiently initialized, so we
9175                           just use its name.  */
9176                        DECL_NAME (r));
9177                 RETURN (error_mark_node);
9178               }
9179             type = complete_type (type);
9180             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9181               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9182             type = check_var_type (DECL_NAME (r), type);
9183
9184             if (DECL_HAS_VALUE_EXPR_P (t))
9185               {
9186                 tree ve = DECL_VALUE_EXPR (t);
9187                 ve = tsubst_expr (ve, args, complain, in_decl,
9188                                   /*constant_expression_p=*/false);
9189                 SET_DECL_VALUE_EXPR (r, ve);
9190               }
9191           }
9192         else if (DECL_SELF_REFERENCE_P (t))
9193           SET_DECL_SELF_REFERENCE_P (r);
9194         TREE_TYPE (r) = type;
9195         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9196         DECL_CONTEXT (r) = ctx;
9197         /* Clear out the mangled name and RTL for the instantiation.  */
9198         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9199         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9200           SET_DECL_RTL (r, NULL_RTX);
9201         /* The initializer must not be expanded until it is required;
9202            see [temp.inst].  */
9203         DECL_INITIAL (r) = NULL_TREE;
9204         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9205           SET_DECL_RTL (r, NULL_RTX);
9206         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9207         if (TREE_CODE (r) == VAR_DECL)
9208           {
9209             /* Possibly limit visibility based on template args.  */
9210             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9211             if (DECL_VISIBILITY_SPECIFIED (t))
9212               {
9213                 DECL_VISIBILITY_SPECIFIED (r) = 0;
9214                 DECL_ATTRIBUTES (r)
9215                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9216               }
9217             determine_visibility (r);
9218           }
9219         /* Preserve a typedef that names a type.  */
9220         else if (TREE_CODE (r) == TYPE_DECL
9221                  && DECL_ORIGINAL_TYPE (t)
9222                  && type != error_mark_node)
9223           {
9224             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
9225                                              args, complain, in_decl);
9226             TREE_TYPE (r) = type = build_variant_type_copy (type);
9227             TYPE_NAME (type) = r;
9228           }
9229
9230         if (!local_p)
9231           {
9232             /* A static data member declaration is always marked
9233                external when it is declared in-class, even if an
9234                initializer is present.  We mimic the non-template
9235                processing here.  */
9236             DECL_EXTERNAL (r) = 1;
9237
9238             register_specialization (r, gen_tmpl, argvec, false, hash);
9239             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
9240             SET_DECL_IMPLICIT_INSTANTIATION (r);
9241           }
9242         else if (cp_unevaluated_operand)
9243           {
9244             /* We're substituting this var in a decltype outside of its
9245                scope, such as for a lambda return type.  Don't add it to
9246                local_specializations, do perform auto deduction.  */
9247             tree auto_node = type_uses_auto (type);
9248             tree init
9249               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9250                              /*constant_expression_p=*/false);
9251
9252             if (auto_node && init && describable_type (init))
9253               {
9254                 type = do_auto_deduction (type, init, auto_node);
9255                 TREE_TYPE (r) = type;
9256               }
9257           }
9258         else
9259           register_local_specialization (r, t);
9260
9261         TREE_CHAIN (r) = NULL_TREE;
9262
9263         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9264                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
9265                                         args, complain, in_decl);
9266         layout_decl (r, 0);
9267       }
9268       break;
9269
9270     default:
9271       gcc_unreachable ();
9272     }
9273 #undef RETURN
9274
9275  out:
9276   /* Restore the file and line information.  */
9277   input_location = saved_loc;
9278
9279   return r;
9280 }
9281
9282 /* Substitute into the ARG_TYPES of a function type.  */
9283
9284 static tree
9285 tsubst_arg_types (tree arg_types,
9286                   tree args,
9287                   tsubst_flags_t complain,
9288                   tree in_decl)
9289 {
9290   tree remaining_arg_types;
9291   tree type = NULL_TREE;
9292   int i = 1;
9293   tree expanded_args = NULL_TREE;
9294   tree default_arg;
9295
9296   if (!arg_types || arg_types == void_list_node)
9297     return arg_types;
9298
9299   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9300                                           args, complain, in_decl);
9301   if (remaining_arg_types == error_mark_node)
9302     return error_mark_node;
9303
9304   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9305     {
9306       /* For a pack expansion, perform substitution on the
9307          entire expression. Later on, we'll handle the arguments
9308          one-by-one.  */
9309       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9310                                             args, complain, in_decl);
9311
9312       if (TREE_CODE (expanded_args) == TREE_VEC)
9313         /* So that we'll spin through the parameters, one by one.  */
9314         i = TREE_VEC_LENGTH (expanded_args);
9315       else
9316         {
9317           /* We only partially substituted into the parameter
9318              pack. Our type is TYPE_PACK_EXPANSION.  */
9319           type = expanded_args;
9320           expanded_args = NULL_TREE;
9321         }
9322     }
9323
9324   while (i > 0) {
9325     --i;
9326     
9327     if (expanded_args)
9328       type = TREE_VEC_ELT (expanded_args, i);
9329     else if (!type)
9330       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9331
9332     if (type == error_mark_node)
9333       return error_mark_node;
9334     if (VOID_TYPE_P (type))
9335       {
9336         if (complain & tf_error)
9337           {
9338             error ("invalid parameter type %qT", type);
9339             if (in_decl)
9340               error ("in declaration %q+D", in_decl);
9341           }
9342         return error_mark_node;
9343     }
9344     
9345     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9346        top-level qualifiers as required.  */
9347     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9348
9349     /* We do not substitute into default arguments here.  The standard
9350        mandates that they be instantiated only when needed, which is
9351        done in build_over_call.  */
9352     default_arg = TREE_PURPOSE (arg_types);
9353
9354     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9355       {
9356         /* We've instantiated a template before its default arguments
9357            have been parsed.  This can happen for a nested template
9358            class, and is not an error unless we require the default
9359            argument in a call of this function.  */
9360         remaining_arg_types = 
9361           tree_cons (default_arg, type, remaining_arg_types);
9362         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9363                        remaining_arg_types);
9364       }
9365     else
9366       remaining_arg_types = 
9367         hash_tree_cons (default_arg, type, remaining_arg_types);
9368   }
9369         
9370   return remaining_arg_types;
9371 }
9372
9373 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9374    *not* handle the exception-specification for FNTYPE, because the
9375    initial substitution of explicitly provided template parameters
9376    during argument deduction forbids substitution into the
9377    exception-specification:
9378
9379      [temp.deduct]
9380
9381      All references in the function type of the function template to  the
9382      corresponding template parameters are replaced by the specified tem-
9383      plate argument values.  If a substitution in a template parameter or
9384      in  the function type of the function template results in an invalid
9385      type, type deduction fails.  [Note: The equivalent  substitution  in
9386      exception specifications is done only when the function is instanti-
9387      ated, at which point a program is  ill-formed  if  the  substitution
9388      results in an invalid type.]  */
9389
9390 static tree
9391 tsubst_function_type (tree t,
9392                       tree args,
9393                       tsubst_flags_t complain,
9394                       tree in_decl)
9395 {
9396   tree return_type;
9397   tree arg_types;
9398   tree fntype;
9399
9400   /* The TYPE_CONTEXT is not used for function/method types.  */
9401   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9402
9403   /* Substitute the return type.  */
9404   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9405   if (return_type == error_mark_node)
9406     return error_mark_node;
9407   /* The standard does not presently indicate that creation of a
9408      function type with an invalid return type is a deduction failure.
9409      However, that is clearly analogous to creating an array of "void"
9410      or a reference to a reference.  This is core issue #486.  */
9411   if (TREE_CODE (return_type) == ARRAY_TYPE
9412       || TREE_CODE (return_type) == FUNCTION_TYPE)
9413     {
9414       if (complain & tf_error)
9415         {
9416           if (TREE_CODE (return_type) == ARRAY_TYPE)
9417             error ("function returning an array");
9418           else
9419             error ("function returning a function");
9420         }
9421       return error_mark_node;
9422     }
9423
9424   /* Substitute the argument types.  */
9425   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9426                                 complain, in_decl);
9427   if (arg_types == error_mark_node)
9428     return error_mark_node;
9429
9430   /* Construct a new type node and return it.  */
9431   if (TREE_CODE (t) == FUNCTION_TYPE)
9432     fntype = build_function_type (return_type, arg_types);
9433   else
9434     {
9435       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9436       if (! MAYBE_CLASS_TYPE_P (r))
9437         {
9438           /* [temp.deduct]
9439
9440              Type deduction may fail for any of the following
9441              reasons:
9442
9443              -- Attempting to create "pointer to member of T" when T
9444              is not a class type.  */
9445           if (complain & tf_error)
9446             error ("creating pointer to member function of non-class type %qT",
9447                       r);
9448           return error_mark_node;
9449         }
9450
9451       fntype = build_method_type_directly (r, return_type,
9452                                            TREE_CHAIN (arg_types));
9453     }
9454   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9455   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9456
9457   return fntype;
9458 }
9459
9460 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9461    ARGS into that specification, and return the substituted
9462    specification.  If there is no specification, return NULL_TREE.  */
9463
9464 static tree
9465 tsubst_exception_specification (tree fntype,
9466                                 tree args,
9467                                 tsubst_flags_t complain,
9468                                 tree in_decl)
9469 {
9470   tree specs;
9471   tree new_specs;
9472
9473   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9474   new_specs = NULL_TREE;
9475   if (specs)
9476     {
9477       if (! TREE_VALUE (specs))
9478         new_specs = specs;
9479       else
9480         while (specs)
9481           {
9482             tree spec;
9483             int i, len = 1;
9484             tree expanded_specs = NULL_TREE;
9485
9486             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9487               {
9488                 /* Expand the pack expansion type.  */
9489                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9490                                                        args, complain,
9491                                                        in_decl);
9492
9493                 if (expanded_specs == error_mark_node)
9494                   return error_mark_node;
9495                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9496                   len = TREE_VEC_LENGTH (expanded_specs);
9497                 else
9498                   {
9499                     /* We're substituting into a member template, so
9500                        we got a TYPE_PACK_EXPANSION back.  Add that
9501                        expansion and move on.  */
9502                     gcc_assert (TREE_CODE (expanded_specs) 
9503                                 == TYPE_PACK_EXPANSION);
9504                     new_specs = add_exception_specifier (new_specs,
9505                                                          expanded_specs,
9506                                                          complain);
9507                     specs = TREE_CHAIN (specs);
9508                     continue;
9509                   }
9510               }
9511
9512             for (i = 0; i < len; ++i)
9513               {
9514                 if (expanded_specs)
9515                   spec = TREE_VEC_ELT (expanded_specs, i);
9516                 else
9517                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9518                 if (spec == error_mark_node)
9519                   return spec;
9520                 new_specs = add_exception_specifier (new_specs, spec, 
9521                                                      complain);
9522               }
9523
9524             specs = TREE_CHAIN (specs);
9525           }
9526     }
9527   return new_specs;
9528 }
9529
9530 /* Take the tree structure T and replace template parameters used
9531    therein with the argument vector ARGS.  IN_DECL is an associated
9532    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9533    Issue error and warning messages under control of COMPLAIN.  Note
9534    that we must be relatively non-tolerant of extensions here, in
9535    order to preserve conformance; if we allow substitutions that
9536    should not be allowed, we may allow argument deductions that should
9537    not succeed, and therefore report ambiguous overload situations
9538    where there are none.  In theory, we could allow the substitution,
9539    but indicate that it should have failed, and allow our caller to
9540    make sure that the right thing happens, but we don't try to do this
9541    yet.
9542
9543    This function is used for dealing with types, decls and the like;
9544    for expressions, use tsubst_expr or tsubst_copy.  */
9545
9546 tree
9547 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9548 {
9549   tree type, r;
9550
9551   if (t == NULL_TREE || t == error_mark_node
9552       || t == integer_type_node
9553       || t == void_type_node
9554       || t == char_type_node
9555       || t == unknown_type_node
9556       || TREE_CODE (t) == NAMESPACE_DECL)
9557     return t;
9558
9559   if (DECL_P (t))
9560     return tsubst_decl (t, args, complain);
9561
9562   if (args == NULL_TREE)
9563     return t;
9564
9565   if (TREE_CODE (t) == IDENTIFIER_NODE)
9566     type = IDENTIFIER_TYPE_VALUE (t);
9567   else
9568     type = TREE_TYPE (t);
9569
9570   gcc_assert (type != unknown_type_node);
9571
9572   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9573      such as attribute aligned.  */
9574   if (TYPE_P (t)
9575       && TYPE_NAME (t)
9576       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9577     {
9578       tree decl = TYPE_NAME (t);
9579       
9580       if (DECL_CLASS_SCOPE_P (decl)
9581           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9582           && uses_template_parms (DECL_CONTEXT (decl)))
9583         {
9584           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9585           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9586           r = retrieve_specialization (tmpl, gen_args, 0);
9587         }
9588       else if (DECL_FUNCTION_SCOPE_P (decl)
9589                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9590                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9591         r = retrieve_local_specialization (decl);
9592       else
9593         /* The typedef is from a non-template context.  */
9594         return t;
9595
9596       if (r)
9597         {
9598           r = TREE_TYPE (r);
9599           r = cp_build_qualified_type_real
9600             (r, cp_type_quals (t) | cp_type_quals (r),
9601              complain | tf_ignore_bad_quals);
9602           return r;
9603         }
9604       /* Else we must be instantiating the typedef, so fall through.  */
9605     }
9606
9607   if (type
9608       && TREE_CODE (t) != TYPENAME_TYPE
9609       && TREE_CODE (t) != IDENTIFIER_NODE
9610       && TREE_CODE (t) != FUNCTION_TYPE
9611       && TREE_CODE (t) != METHOD_TYPE)
9612     type = tsubst (type, args, complain, in_decl);
9613   if (type == error_mark_node)
9614     return error_mark_node;
9615
9616   switch (TREE_CODE (t))
9617     {
9618     case RECORD_TYPE:
9619     case UNION_TYPE:
9620     case ENUMERAL_TYPE:
9621       return tsubst_aggr_type (t, args, complain, in_decl,
9622                                /*entering_scope=*/0);
9623
9624     case ERROR_MARK:
9625     case IDENTIFIER_NODE:
9626     case VOID_TYPE:
9627     case REAL_TYPE:
9628     case COMPLEX_TYPE:
9629     case VECTOR_TYPE:
9630     case BOOLEAN_TYPE:
9631     case INTEGER_CST:
9632     case REAL_CST:
9633     case STRING_CST:
9634       return t;
9635
9636     case INTEGER_TYPE:
9637       if (t == integer_type_node)
9638         return t;
9639
9640       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9641           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9642         return t;
9643
9644       {
9645         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9646
9647         max = tsubst_expr (omax, args, complain, in_decl,
9648                            /*integral_constant_expression_p=*/false);
9649
9650         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9651            needed.  */
9652         if (TREE_CODE (max) == NOP_EXPR
9653             && TREE_SIDE_EFFECTS (omax)
9654             && !TREE_TYPE (max))
9655           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9656
9657         max = fold_decl_constant_value (max);
9658
9659         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9660            with TREE_SIDE_EFFECTS that indicates this is not an integral
9661            constant expression.  */
9662         if (processing_template_decl
9663             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9664           {
9665             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9666             TREE_SIDE_EFFECTS (max) = 1;
9667           }
9668
9669         if (TREE_CODE (max) != INTEGER_CST
9670             && !at_function_scope_p ()
9671             && !TREE_SIDE_EFFECTS (max)
9672             && !value_dependent_expression_p (max))
9673           {
9674             if (complain & tf_error)
9675               error ("array bound is not an integer constant");
9676             return error_mark_node;
9677           }
9678
9679         /* [temp.deduct]
9680
9681            Type deduction may fail for any of the following
9682            reasons:
9683
9684              Attempting to create an array with a size that is
9685              zero or negative.  */
9686         if (integer_zerop (max) && !(complain & tf_error))
9687           /* We must fail if performing argument deduction (as
9688              indicated by the state of complain), so that
9689              another substitution can be found.  */
9690           return error_mark_node;
9691         else if (TREE_CODE (max) == INTEGER_CST
9692                  && INT_CST_LT (max, integer_zero_node))
9693           {
9694             if (complain & tf_error)
9695               error ("creating array with negative size (%qE)", max);
9696
9697             return error_mark_node;
9698           }
9699
9700         return compute_array_index_type (NULL_TREE, max);
9701       }
9702
9703     case TEMPLATE_TYPE_PARM:
9704     case TEMPLATE_TEMPLATE_PARM:
9705     case BOUND_TEMPLATE_TEMPLATE_PARM:
9706     case TEMPLATE_PARM_INDEX:
9707       {
9708         int idx;
9709         int level;
9710         int levels;
9711         tree arg = NULL_TREE;
9712
9713         r = NULL_TREE;
9714
9715         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9716         template_parm_level_and_index (t, &level, &idx); 
9717
9718         levels = TMPL_ARGS_DEPTH (args);
9719         if (level <= levels)
9720           {
9721             arg = TMPL_ARG (args, level, idx);
9722
9723             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9724               /* See through ARGUMENT_PACK_SELECT arguments. */
9725               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9726           }
9727
9728         if (arg == error_mark_node)
9729           return error_mark_node;
9730         else if (arg != NULL_TREE)
9731           {
9732             if (ARGUMENT_PACK_P (arg))
9733               /* If ARG is an argument pack, we don't actually want to
9734                  perform a substitution here, because substitutions
9735                  for argument packs are only done
9736                  element-by-element. We can get to this point when
9737                  substituting the type of a non-type template
9738                  parameter pack, when that type actually contains
9739                  template parameter packs from an outer template, e.g.,
9740
9741                  template<typename... Types> struct A {
9742                    template<Types... Values> struct B { };
9743                  };  */
9744               return t;
9745
9746             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9747               {
9748                 int quals;
9749                 gcc_assert (TYPE_P (arg));
9750
9751                 /* cv-quals from the template are discarded when
9752                    substituting in a function or reference type.  */
9753                 if (TREE_CODE (arg) == FUNCTION_TYPE
9754                     || TREE_CODE (arg) == METHOD_TYPE
9755                     || TREE_CODE (arg) == REFERENCE_TYPE)
9756                   quals = cp_type_quals (arg);
9757                 else
9758                   quals = cp_type_quals (arg) | cp_type_quals (t);
9759                   
9760                 return cp_build_qualified_type_real
9761                   (arg, quals, complain | tf_ignore_bad_quals);
9762               }
9763             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9764               {
9765                 /* We are processing a type constructed from a
9766                    template template parameter.  */
9767                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9768                                       args, complain, in_decl);
9769                 if (argvec == error_mark_node)
9770                   return error_mark_node;
9771
9772                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9773                    are resolving nested-types in the signature of a
9774                    member function templates.  Otherwise ARG is a
9775                    TEMPLATE_DECL and is the real template to be
9776                    instantiated.  */
9777                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9778                   arg = TYPE_NAME (arg);
9779
9780                 r = lookup_template_class (arg,
9781                                            argvec, in_decl,
9782                                            DECL_CONTEXT (arg),
9783                                             /*entering_scope=*/0,
9784                                            complain);
9785                 return cp_build_qualified_type_real
9786                   (r, TYPE_QUALS (t), complain);
9787               }
9788             else
9789               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9790               return arg;
9791           }
9792
9793         if (level == 1)
9794           /* This can happen during the attempted tsubst'ing in
9795              unify.  This means that we don't yet have any information
9796              about the template parameter in question.  */
9797           return t;
9798
9799         /* If we get here, we must have been looking at a parm for a
9800            more deeply nested template.  Make a new version of this
9801            template parameter, but with a lower level.  */
9802         switch (TREE_CODE (t))
9803           {
9804           case TEMPLATE_TYPE_PARM:
9805           case TEMPLATE_TEMPLATE_PARM:
9806           case BOUND_TEMPLATE_TEMPLATE_PARM:
9807             if (cp_type_quals (t))
9808               {
9809                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9810                 r = cp_build_qualified_type_real
9811                   (r, cp_type_quals (t),
9812                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9813                                ? tf_ignore_bad_quals : 0));
9814               }
9815             else
9816               {
9817                 r = copy_type (t);
9818                 TEMPLATE_TYPE_PARM_INDEX (r)
9819                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9820                                                 r, levels, args, complain);
9821                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9822                 TYPE_MAIN_VARIANT (r) = r;
9823                 TYPE_POINTER_TO (r) = NULL_TREE;
9824                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9825
9826                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9827                   /* We have reduced the level of the template
9828                      template parameter, but not the levels of its
9829                      template parameters, so canonical_type_parameter
9830                      will not be able to find the canonical template
9831                      template parameter for this level. Thus, we
9832                      require structural equality checking to compare
9833                      TEMPLATE_TEMPLATE_PARMs. */
9834                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9835                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9836                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9837                 else
9838                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9839
9840                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9841                   {
9842                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9843                                           complain, in_decl);
9844                     if (argvec == error_mark_node)
9845                       return error_mark_node;
9846
9847                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9848                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9849                   }
9850               }
9851             break;
9852
9853           case TEMPLATE_PARM_INDEX:
9854             r = reduce_template_parm_level (t, type, levels, args, complain);
9855             break;
9856
9857           default:
9858             gcc_unreachable ();
9859           }
9860
9861         return r;
9862       }
9863
9864     case TREE_LIST:
9865       {
9866         tree purpose, value, chain;
9867
9868         if (t == void_list_node)
9869           return t;
9870
9871         purpose = TREE_PURPOSE (t);
9872         if (purpose)
9873           {
9874             purpose = tsubst (purpose, args, complain, in_decl);
9875             if (purpose == error_mark_node)
9876               return error_mark_node;
9877           }
9878         value = TREE_VALUE (t);
9879         if (value)
9880           {
9881             value = tsubst (value, args, complain, in_decl);
9882             if (value == error_mark_node)
9883               return error_mark_node;
9884           }
9885         chain = TREE_CHAIN (t);
9886         if (chain && chain != void_type_node)
9887           {
9888             chain = tsubst (chain, args, complain, in_decl);
9889             if (chain == error_mark_node)
9890               return error_mark_node;
9891           }
9892         if (purpose == TREE_PURPOSE (t)
9893             && value == TREE_VALUE (t)
9894             && chain == TREE_CHAIN (t))
9895           return t;
9896         return hash_tree_cons (purpose, value, chain);
9897       }
9898
9899     case TREE_BINFO:
9900       /* We should never be tsubsting a binfo.  */
9901       gcc_unreachable ();
9902
9903     case TREE_VEC:
9904       /* A vector of template arguments.  */
9905       gcc_assert (!type);
9906       return tsubst_template_args (t, args, complain, in_decl);
9907
9908     case POINTER_TYPE:
9909     case REFERENCE_TYPE:
9910       {
9911         enum tree_code code;
9912
9913         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9914           return t;
9915
9916         code = TREE_CODE (t);
9917
9918
9919         /* [temp.deduct]
9920
9921            Type deduction may fail for any of the following
9922            reasons:
9923
9924            -- Attempting to create a pointer to reference type.
9925            -- Attempting to create a reference to a reference type or
9926               a reference to void.
9927
9928           Core issue 106 says that creating a reference to a reference
9929           during instantiation is no longer a cause for failure. We
9930           only enforce this check in strict C++98 mode.  */
9931         if ((TREE_CODE (type) == REFERENCE_TYPE
9932              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9933             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9934           {
9935             static location_t last_loc;
9936
9937             /* We keep track of the last time we issued this error
9938                message to avoid spewing a ton of messages during a
9939                single bad template instantiation.  */
9940             if (complain & tf_error
9941                 && last_loc != input_location)
9942               {
9943                 if (TREE_CODE (type) == VOID_TYPE)
9944                   error ("forming reference to void");
9945                 else
9946                   error ("forming %s to reference type %qT",
9947                          (code == POINTER_TYPE) ? "pointer" : "reference",
9948                          type);
9949                 last_loc = input_location;
9950               }
9951
9952             return error_mark_node;
9953           }
9954         else if (code == POINTER_TYPE)
9955           {
9956             r = build_pointer_type (type);
9957             if (TREE_CODE (type) == METHOD_TYPE)
9958               r = build_ptrmemfunc_type (r);
9959           }
9960         else if (TREE_CODE (type) == REFERENCE_TYPE)
9961           /* In C++0x, during template argument substitution, when there is an
9962              attempt to create a reference to a reference type, reference
9963              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9964
9965              "If a template-argument for a template-parameter T names a type
9966              that is a reference to a type A, an attempt to create the type
9967              'lvalue reference to cv T' creates the type 'lvalue reference to
9968              A,' while an attempt to create the type type rvalue reference to
9969              cv T' creates the type T"
9970           */
9971           r = cp_build_reference_type
9972               (TREE_TYPE (type),
9973                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9974         else
9975           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9976         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9977
9978         if (r != error_mark_node)
9979           /* Will this ever be needed for TYPE_..._TO values?  */
9980           layout_type (r);
9981
9982         return r;
9983       }
9984     case OFFSET_TYPE:
9985       {
9986         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9987         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
9988           {
9989             /* [temp.deduct]
9990
9991                Type deduction may fail for any of the following
9992                reasons:
9993
9994                -- Attempting to create "pointer to member of T" when T
9995                   is not a class type.  */
9996             if (complain & tf_error)
9997               error ("creating pointer to member of non-class type %qT", r);
9998             return error_mark_node;
9999           }
10000         if (TREE_CODE (type) == REFERENCE_TYPE)
10001           {
10002             if (complain & tf_error)
10003               error ("creating pointer to member reference type %qT", type);
10004             return error_mark_node;
10005           }
10006         if (TREE_CODE (type) == VOID_TYPE)
10007           {
10008             if (complain & tf_error)
10009               error ("creating pointer to member of type void");
10010             return error_mark_node;
10011           }
10012         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10013         if (TREE_CODE (type) == FUNCTION_TYPE)
10014           {
10015             /* The type of the implicit object parameter gets its
10016                cv-qualifiers from the FUNCTION_TYPE. */
10017             tree memptr;
10018             tree method_type = build_memfn_type (type, r, cp_type_quals (type));
10019             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10020             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10021                                                  complain);
10022           }
10023         else
10024           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10025                                                TYPE_QUALS (t),
10026                                                complain);
10027       }
10028     case FUNCTION_TYPE:
10029     case METHOD_TYPE:
10030       {
10031         tree fntype;
10032         tree specs;
10033         fntype = tsubst_function_type (t, args, complain, in_decl);
10034         if (fntype == error_mark_node)
10035           return error_mark_node;
10036
10037         /* Substitute the exception specification.  */
10038         specs = tsubst_exception_specification (t, args, complain,
10039                                                 in_decl);
10040         if (specs == error_mark_node)
10041           return error_mark_node;
10042         if (specs)
10043           fntype = build_exception_variant (fntype, specs);
10044         return fntype;
10045       }
10046     case ARRAY_TYPE:
10047       {
10048         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10049         if (domain == error_mark_node)
10050           return error_mark_node;
10051
10052         /* As an optimization, we avoid regenerating the array type if
10053            it will obviously be the same as T.  */
10054         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10055           return t;
10056
10057         /* These checks should match the ones in grokdeclarator.
10058
10059            [temp.deduct]
10060
10061            The deduction may fail for any of the following reasons:
10062
10063            -- Attempting to create an array with an element type that
10064               is void, a function type, or a reference type, or [DR337]
10065               an abstract class type.  */
10066         if (TREE_CODE (type) == VOID_TYPE
10067             || TREE_CODE (type) == FUNCTION_TYPE
10068             || TREE_CODE (type) == REFERENCE_TYPE)
10069           {
10070             if (complain & tf_error)
10071               error ("creating array of %qT", type);
10072             return error_mark_node;
10073           }
10074         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10075           {
10076             if (complain & tf_error)
10077               error ("creating array of %qT, which is an abstract class type",
10078                      type);
10079             return error_mark_node;
10080           }
10081
10082         r = build_cplus_array_type (type, domain);
10083
10084         if (TYPE_USER_ALIGN (t))
10085           {
10086             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10087             TYPE_USER_ALIGN (r) = 1;
10088           }
10089
10090         return r;
10091       }
10092
10093     case PLUS_EXPR:
10094     case MINUS_EXPR:
10095       {
10096         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10097         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10098
10099         if (e1 == error_mark_node || e2 == error_mark_node)
10100           return error_mark_node;
10101
10102         return fold_build2_loc (input_location,
10103                             TREE_CODE (t), TREE_TYPE (t), e1, e2);
10104       }
10105
10106     case NEGATE_EXPR:
10107     case NOP_EXPR:
10108       {
10109         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10110         if (e == error_mark_node)
10111           return error_mark_node;
10112
10113         return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
10114       }
10115
10116     case TYPENAME_TYPE:
10117       {
10118         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10119                                      in_decl, /*entering_scope=*/1);
10120         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10121                               complain, in_decl);
10122
10123         if (ctx == error_mark_node || f == error_mark_node)
10124           return error_mark_node;
10125
10126         if (!MAYBE_CLASS_TYPE_P (ctx))
10127           {
10128             if (complain & tf_error)
10129               error ("%qT is not a class, struct, or union type", ctx);
10130             return error_mark_node;
10131           }
10132         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10133           {
10134             /* Normally, make_typename_type does not require that the CTX
10135                have complete type in order to allow things like:
10136
10137                  template <class T> struct S { typename S<T>::X Y; };
10138
10139                But, such constructs have already been resolved by this
10140                point, so here CTX really should have complete type, unless
10141                it's a partial instantiation.  */
10142             if (!(complain & tf_no_class_instantiations))
10143               ctx = complete_type (ctx);
10144             if (!COMPLETE_TYPE_P (ctx))
10145               {
10146                 if (complain & tf_error)
10147                   cxx_incomplete_type_error (NULL_TREE, ctx);
10148                 return error_mark_node;
10149               }
10150           }
10151
10152         f = make_typename_type (ctx, f, typename_type,
10153                                 (complain & tf_error) | tf_keep_type_decl);
10154         if (f == error_mark_node)
10155           return f;
10156         if (TREE_CODE (f) == TYPE_DECL)
10157           {
10158             complain |= tf_ignore_bad_quals;
10159             f = TREE_TYPE (f);
10160           }
10161
10162         if (TREE_CODE (f) != TYPENAME_TYPE)
10163           {
10164             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10165               error ("%qT resolves to %qT, which is not an enumeration type",
10166                      t, f);
10167             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10168               error ("%qT resolves to %qT, which is is not a class type",
10169                      t, f);
10170           }
10171
10172         return cp_build_qualified_type_real
10173           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10174       }
10175
10176     case UNBOUND_CLASS_TEMPLATE:
10177       {
10178         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10179                                      in_decl, /*entering_scope=*/1);
10180         tree name = TYPE_IDENTIFIER (t);
10181         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10182
10183         if (ctx == error_mark_node || name == error_mark_node)
10184           return error_mark_node;
10185
10186         if (parm_list)
10187           parm_list = tsubst_template_parms (parm_list, args, complain);
10188         return make_unbound_class_template (ctx, name, parm_list, complain);
10189       }
10190
10191     case INDIRECT_REF:
10192     case ADDR_EXPR:
10193     case CALL_EXPR:
10194       gcc_unreachable ();
10195
10196     case ARRAY_REF:
10197       {
10198         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10199         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10200                                /*integral_constant_expression_p=*/false);
10201         if (e1 == error_mark_node || e2 == error_mark_node)
10202           return error_mark_node;
10203
10204         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10205       }
10206
10207     case SCOPE_REF:
10208       {
10209         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10210         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10211         if (e1 == error_mark_node || e2 == error_mark_node)
10212           return error_mark_node;
10213
10214         return build_qualified_name (/*type=*/NULL_TREE,
10215                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10216       }
10217
10218     case TYPEOF_TYPE:
10219       {
10220         tree type;
10221
10222         ++cp_unevaluated_operand;
10223         ++c_inhibit_evaluation_warnings;
10224
10225         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10226                             complain, in_decl,
10227                             /*integral_constant_expression_p=*/false);
10228
10229         --cp_unevaluated_operand;
10230         --c_inhibit_evaluation_warnings;
10231
10232         type = finish_typeof (type);
10233         return cp_build_qualified_type_real (type,
10234                                              cp_type_quals (t)
10235                                              | cp_type_quals (type),
10236                                              complain);
10237       }
10238
10239     case DECLTYPE_TYPE:
10240       {
10241         tree type;
10242
10243         ++cp_unevaluated_operand;
10244         ++c_inhibit_evaluation_warnings;
10245
10246         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10247                             complain, in_decl,
10248                             /*integral_constant_expression_p=*/false);
10249
10250         --cp_unevaluated_operand;
10251         --c_inhibit_evaluation_warnings;
10252
10253         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10254           type = lambda_capture_field_type (type);
10255         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10256           type = lambda_return_type (type);
10257         else
10258           type = finish_decltype_type
10259             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10260         return cp_build_qualified_type_real (type,
10261                                              cp_type_quals (t)
10262                                              | cp_type_quals (type),
10263                                              complain);
10264       }
10265
10266     case TYPE_ARGUMENT_PACK:
10267     case NONTYPE_ARGUMENT_PACK:
10268       {
10269         tree r = TYPE_P (t)
10270           ? cxx_make_type (TREE_CODE (t))
10271           : make_node (TREE_CODE (t));
10272         tree packed_out = 
10273           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10274                                 args,
10275                                 complain,
10276                                 in_decl);
10277         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10278
10279         /* For template nontype argument packs, also substitute into
10280            the type.  */
10281         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10282           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10283
10284         return r;
10285       }
10286       break;
10287
10288     default:
10289       sorry ("use of %qs in template",
10290              tree_code_name [(int) TREE_CODE (t)]);
10291       return error_mark_node;
10292     }
10293 }
10294
10295 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10296    type of the expression on the left-hand side of the "." or "->"
10297    operator.  */
10298
10299 static tree
10300 tsubst_baselink (tree baselink, tree object_type,
10301                  tree args, tsubst_flags_t complain, tree in_decl)
10302 {
10303     tree name;
10304     tree qualifying_scope;
10305     tree fns;
10306     tree optype;
10307     tree template_args = 0;
10308     bool template_id_p = false;
10309
10310     /* A baselink indicates a function from a base class.  Both the
10311        BASELINK_ACCESS_BINFO and the base class referenced may
10312        indicate bases of the template class, rather than the
10313        instantiated class.  In addition, lookups that were not
10314        ambiguous before may be ambiguous now.  Therefore, we perform
10315        the lookup again.  */
10316     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10317     qualifying_scope = tsubst (qualifying_scope, args,
10318                                complain, in_decl);
10319     fns = BASELINK_FUNCTIONS (baselink);
10320     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10321     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10322       {
10323         template_id_p = true;
10324         template_args = TREE_OPERAND (fns, 1);
10325         fns = TREE_OPERAND (fns, 0);
10326         if (template_args)
10327           template_args = tsubst_template_args (template_args, args,
10328                                                 complain, in_decl);
10329       }
10330     name = DECL_NAME (get_first_fn (fns));
10331     if (IDENTIFIER_TYPENAME_P (name))
10332       name = mangle_conv_op_name_for_type (optype);
10333     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10334
10335     /* If lookup found a single function, mark it as used at this
10336        point.  (If it lookup found multiple functions the one selected
10337        later by overload resolution will be marked as used at that
10338        point.)  */
10339     if (BASELINK_P (baselink))
10340       fns = BASELINK_FUNCTIONS (baselink);
10341     if (!template_id_p && !really_overloaded_fn (fns))
10342       mark_used (OVL_CURRENT (fns));
10343
10344     /* Add back the template arguments, if present.  */
10345     if (BASELINK_P (baselink) && template_id_p)
10346       BASELINK_FUNCTIONS (baselink)
10347         = build_nt (TEMPLATE_ID_EXPR,
10348                     BASELINK_FUNCTIONS (baselink),
10349                     template_args);
10350     /* Update the conversion operator type.  */
10351     BASELINK_OPTYPE (baselink) = optype;
10352
10353     if (!object_type)
10354       object_type = current_class_type;
10355     return adjust_result_of_qualified_name_lookup (baselink,
10356                                                    qualifying_scope,
10357                                                    object_type);
10358 }
10359
10360 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10361    true if the qualified-id will be a postfix-expression in-and-of
10362    itself; false if more of the postfix-expression follows the
10363    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10364    of "&".  */
10365
10366 static tree
10367 tsubst_qualified_id (tree qualified_id, tree args,
10368                      tsubst_flags_t complain, tree in_decl,
10369                      bool done, bool address_p)
10370 {
10371   tree expr;
10372   tree scope;
10373   tree name;
10374   bool is_template;
10375   tree template_args;
10376
10377   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10378
10379   /* Figure out what name to look up.  */
10380   name = TREE_OPERAND (qualified_id, 1);
10381   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10382     {
10383       is_template = true;
10384       template_args = TREE_OPERAND (name, 1);
10385       if (template_args)
10386         template_args = tsubst_template_args (template_args, args,
10387                                               complain, in_decl);
10388       name = TREE_OPERAND (name, 0);
10389     }
10390   else
10391     {
10392       is_template = false;
10393       template_args = NULL_TREE;
10394     }
10395
10396   /* Substitute into the qualifying scope.  When there are no ARGS, we
10397      are just trying to simplify a non-dependent expression.  In that
10398      case the qualifying scope may be dependent, and, in any case,
10399      substituting will not help.  */
10400   scope = TREE_OPERAND (qualified_id, 0);
10401   if (args)
10402     {
10403       scope = tsubst (scope, args, complain, in_decl);
10404       expr = tsubst_copy (name, args, complain, in_decl);
10405     }
10406   else
10407     expr = name;
10408
10409   if (dependent_type_p (scope))
10410     {
10411       tree type = NULL_TREE;
10412       if (DECL_P (expr) && !dependent_scope_p (scope))
10413         type = TREE_TYPE (expr);
10414       return build_qualified_name (type, scope, expr,
10415                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10416     }
10417
10418   if (!BASELINK_P (name) && !DECL_P (expr))
10419     {
10420       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10421         {
10422           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10423           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10424             {
10425               error ("qualifying type %qT does not match destructor name ~%qT",
10426                      scope, TREE_OPERAND (expr, 0));
10427               expr = error_mark_node;
10428             }
10429           else
10430             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10431                                           /*is_type_p=*/0, false);
10432         }
10433       else
10434         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10435       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10436                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10437         {
10438           if (complain & tf_error)
10439             {
10440               error ("dependent-name %qE is parsed as a non-type, but "
10441                      "instantiation yields a type", qualified_id);
10442               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10443             }
10444           return error_mark_node;
10445         }
10446     }
10447
10448   if (DECL_P (expr))
10449     {
10450       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10451                                            scope);
10452       /* Remember that there was a reference to this entity.  */
10453       mark_used (expr);
10454     }
10455
10456   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10457     {
10458       if (complain & tf_error)
10459         qualified_name_lookup_error (scope,
10460                                      TREE_OPERAND (qualified_id, 1),
10461                                      expr, input_location);
10462       return error_mark_node;
10463     }
10464
10465   if (is_template)
10466     expr = lookup_template_function (expr, template_args);
10467
10468   if (expr == error_mark_node && complain & tf_error)
10469     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10470                                  expr, input_location);
10471   else if (TYPE_P (scope))
10472     {
10473       expr = (adjust_result_of_qualified_name_lookup
10474               (expr, scope, current_class_type));
10475       expr = (finish_qualified_id_expr
10476               (scope, expr, done, address_p,
10477                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10478                /*template_arg_p=*/false));
10479     }
10480
10481   /* Expressions do not generally have reference type.  */
10482   if (TREE_CODE (expr) != SCOPE_REF
10483       /* However, if we're about to form a pointer-to-member, we just
10484          want the referenced member referenced.  */
10485       && TREE_CODE (expr) != OFFSET_REF)
10486     expr = convert_from_reference (expr);
10487
10488   return expr;
10489 }
10490
10491 /* Like tsubst, but deals with expressions.  This function just replaces
10492    template parms; to finish processing the resultant expression, use
10493    tsubst_expr.  */
10494
10495 static tree
10496 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10497 {
10498   enum tree_code code;
10499   tree r;
10500
10501   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10502     return t;
10503
10504   code = TREE_CODE (t);
10505
10506   switch (code)
10507     {
10508     case PARM_DECL:
10509       r = retrieve_local_specialization (t);
10510
10511       if (r == NULL)
10512         {
10513           tree c;
10514           /* This can happen for a parameter name used later in a function
10515              declaration (such as in a late-specified return type).  Just
10516              make a dummy decl, since it's only used for its type.  */
10517           gcc_assert (cp_unevaluated_operand != 0);
10518           /* We copy T because want to tsubst the PARM_DECL only,
10519              not the following PARM_DECLs that are chained to T.  */
10520           c = copy_node (t);
10521           r = tsubst_decl (c, args, complain);
10522           /* Give it the template pattern as its context; its true context
10523              hasn't been instantiated yet and this is good enough for
10524              mangling.  */
10525           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10526         }
10527       
10528       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10529         r = ARGUMENT_PACK_SELECT_ARG (r);
10530       mark_used (r);
10531       return r;
10532
10533     case CONST_DECL:
10534       {
10535         tree enum_type;
10536         tree v;
10537
10538         if (DECL_TEMPLATE_PARM_P (t))
10539           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10540         /* There is no need to substitute into namespace-scope
10541            enumerators.  */
10542         if (DECL_NAMESPACE_SCOPE_P (t))
10543           return t;
10544         /* If ARGS is NULL, then T is known to be non-dependent.  */
10545         if (args == NULL_TREE)
10546           return integral_constant_value (t);
10547
10548         /* Unfortunately, we cannot just call lookup_name here.
10549            Consider:
10550
10551              template <int I> int f() {
10552              enum E { a = I };
10553              struct S { void g() { E e = a; } };
10554              };
10555
10556            When we instantiate f<7>::S::g(), say, lookup_name is not
10557            clever enough to find f<7>::a.  */
10558         enum_type
10559           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10560                               /*entering_scope=*/0);
10561
10562         for (v = TYPE_VALUES (enum_type);
10563              v != NULL_TREE;
10564              v = TREE_CHAIN (v))
10565           if (TREE_PURPOSE (v) == DECL_NAME (t))
10566             return TREE_VALUE (v);
10567
10568           /* We didn't find the name.  That should never happen; if
10569              name-lookup found it during preliminary parsing, we
10570              should find it again here during instantiation.  */
10571         gcc_unreachable ();
10572       }
10573       return t;
10574
10575     case FIELD_DECL:
10576       if (DECL_CONTEXT (t))
10577         {
10578           tree ctx;
10579
10580           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10581                                   /*entering_scope=*/1);
10582           if (ctx != DECL_CONTEXT (t))
10583             {
10584               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10585               if (!r)
10586                 {
10587                   if (complain & tf_error)
10588                     error ("using invalid field %qD", t);
10589                   return error_mark_node;
10590                 }
10591               return r;
10592             }
10593         }
10594
10595       return t;
10596
10597     case VAR_DECL:
10598     case FUNCTION_DECL:
10599       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10600           || local_variable_p (t))
10601         t = tsubst (t, args, complain, in_decl);
10602       mark_used (t);
10603       return t;
10604
10605     case BASELINK:
10606       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10607
10608     case TEMPLATE_DECL:
10609       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10610         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10611                        args, complain, in_decl);
10612       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10613         return tsubst (t, args, complain, in_decl);
10614       else if (DECL_CLASS_SCOPE_P (t)
10615                && uses_template_parms (DECL_CONTEXT (t)))
10616         {
10617           /* Template template argument like the following example need
10618              special treatment:
10619
10620                template <template <class> class TT> struct C {};
10621                template <class T> struct D {
10622                  template <class U> struct E {};
10623                  C<E> c;                                // #1
10624                };
10625                D<int> d;                                // #2
10626
10627              We are processing the template argument `E' in #1 for
10628              the template instantiation #2.  Originally, `E' is a
10629              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10630              have to substitute this with one having context `D<int>'.  */
10631
10632           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10633           return lookup_field (context, DECL_NAME(t), 0, false);
10634         }
10635       else
10636         /* Ordinary template template argument.  */
10637         return t;
10638
10639     case CAST_EXPR:
10640     case REINTERPRET_CAST_EXPR:
10641     case CONST_CAST_EXPR:
10642     case STATIC_CAST_EXPR:
10643     case DYNAMIC_CAST_EXPR:
10644     case NOP_EXPR:
10645       return build1
10646         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10647          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10648
10649     case SIZEOF_EXPR:
10650       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10651         {
10652           /* We only want to compute the number of arguments.  */
10653           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10654                                                 complain, in_decl);
10655           int len = 0;
10656
10657           if (TREE_CODE (expanded) == TREE_VEC)
10658             len = TREE_VEC_LENGTH (expanded);
10659
10660           if (expanded == error_mark_node)
10661             return error_mark_node;
10662           else if (PACK_EXPANSION_P (expanded)
10663                    || (TREE_CODE (expanded) == TREE_VEC
10664                        && len > 0
10665                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10666             {
10667               if (TREE_CODE (expanded) == TREE_VEC)
10668                 expanded = TREE_VEC_ELT (expanded, len - 1);
10669
10670               if (TYPE_P (expanded))
10671                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10672                                                    complain & tf_error);
10673               else
10674                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10675                                                    complain & tf_error);
10676             }
10677           else
10678             return build_int_cst (size_type_node, len);
10679         }
10680       /* Fall through */
10681
10682     case INDIRECT_REF:
10683     case NEGATE_EXPR:
10684     case TRUTH_NOT_EXPR:
10685     case BIT_NOT_EXPR:
10686     case ADDR_EXPR:
10687     case UNARY_PLUS_EXPR:      /* Unary + */
10688     case ALIGNOF_EXPR:
10689     case ARROW_EXPR:
10690     case THROW_EXPR:
10691     case TYPEID_EXPR:
10692     case REALPART_EXPR:
10693     case IMAGPART_EXPR:
10694       return build1
10695         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10696          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10697
10698     case COMPONENT_REF:
10699       {
10700         tree object;
10701         tree name;
10702
10703         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10704         name = TREE_OPERAND (t, 1);
10705         if (TREE_CODE (name) == BIT_NOT_EXPR)
10706           {
10707             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10708                                 complain, in_decl);
10709             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10710           }
10711         else if (TREE_CODE (name) == SCOPE_REF
10712                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10713           {
10714             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10715                                      complain, in_decl);
10716             name = TREE_OPERAND (name, 1);
10717             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10718                                 complain, in_decl);
10719             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10720             name = build_qualified_name (/*type=*/NULL_TREE,
10721                                          base, name,
10722                                          /*template_p=*/false);
10723           }
10724         else if (TREE_CODE (name) == BASELINK)
10725           name = tsubst_baselink (name,
10726                                   non_reference (TREE_TYPE (object)),
10727                                   args, complain,
10728                                   in_decl);
10729         else
10730           name = tsubst_copy (name, args, complain, in_decl);
10731         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10732       }
10733
10734     case PLUS_EXPR:
10735     case MINUS_EXPR:
10736     case MULT_EXPR:
10737     case TRUNC_DIV_EXPR:
10738     case CEIL_DIV_EXPR:
10739     case FLOOR_DIV_EXPR:
10740     case ROUND_DIV_EXPR:
10741     case EXACT_DIV_EXPR:
10742     case BIT_AND_EXPR:
10743     case BIT_IOR_EXPR:
10744     case BIT_XOR_EXPR:
10745     case TRUNC_MOD_EXPR:
10746     case FLOOR_MOD_EXPR:
10747     case TRUTH_ANDIF_EXPR:
10748     case TRUTH_ORIF_EXPR:
10749     case TRUTH_AND_EXPR:
10750     case TRUTH_OR_EXPR:
10751     case RSHIFT_EXPR:
10752     case LSHIFT_EXPR:
10753     case RROTATE_EXPR:
10754     case LROTATE_EXPR:
10755     case EQ_EXPR:
10756     case NE_EXPR:
10757     case MAX_EXPR:
10758     case MIN_EXPR:
10759     case LE_EXPR:
10760     case GE_EXPR:
10761     case LT_EXPR:
10762     case GT_EXPR:
10763     case COMPOUND_EXPR:
10764     case DOTSTAR_EXPR:
10765     case MEMBER_REF:
10766     case PREDECREMENT_EXPR:
10767     case PREINCREMENT_EXPR:
10768     case POSTDECREMENT_EXPR:
10769     case POSTINCREMENT_EXPR:
10770       return build_nt
10771         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10772          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10773
10774     case SCOPE_REF:
10775       return build_qualified_name (/*type=*/NULL_TREE,
10776                                    tsubst_copy (TREE_OPERAND (t, 0),
10777                                                 args, complain, in_decl),
10778                                    tsubst_copy (TREE_OPERAND (t, 1),
10779                                                 args, complain, in_decl),
10780                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10781
10782     case ARRAY_REF:
10783       return build_nt
10784         (ARRAY_REF,
10785          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10786          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10787          NULL_TREE, NULL_TREE);
10788
10789     case CALL_EXPR:
10790       {
10791         int n = VL_EXP_OPERAND_LENGTH (t);
10792         tree result = build_vl_exp (CALL_EXPR, n);
10793         int i;
10794         for (i = 0; i < n; i++)
10795           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10796                                              complain, in_decl);
10797         return result;
10798       }
10799
10800     case COND_EXPR:
10801     case MODOP_EXPR:
10802     case PSEUDO_DTOR_EXPR:
10803       {
10804         r = build_nt
10805           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10806            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10807            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10808         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10809         return r;
10810       }
10811
10812     case NEW_EXPR:
10813       {
10814         r = build_nt
10815         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10816          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10817          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10818         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10819         return r;
10820       }
10821
10822     case DELETE_EXPR:
10823       {
10824         r = build_nt
10825         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10826          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10827         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10828         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10829         return r;
10830       }
10831
10832     case TEMPLATE_ID_EXPR:
10833       {
10834         /* Substituted template arguments */
10835         tree fn = TREE_OPERAND (t, 0);
10836         tree targs = TREE_OPERAND (t, 1);
10837
10838         fn = tsubst_copy (fn, args, complain, in_decl);
10839         if (targs)
10840           targs = tsubst_template_args (targs, args, complain, in_decl);
10841
10842         return lookup_template_function (fn, targs);
10843       }
10844
10845     case TREE_LIST:
10846       {
10847         tree purpose, value, chain;
10848
10849         if (t == void_list_node)
10850           return t;
10851
10852         purpose = TREE_PURPOSE (t);
10853         if (purpose)
10854           purpose = tsubst_copy (purpose, args, complain, in_decl);
10855         value = TREE_VALUE (t);
10856         if (value)
10857           value = tsubst_copy (value, args, complain, in_decl);
10858         chain = TREE_CHAIN (t);
10859         if (chain && chain != void_type_node)
10860           chain = tsubst_copy (chain, args, complain, in_decl);
10861         if (purpose == TREE_PURPOSE (t)
10862             && value == TREE_VALUE (t)
10863             && chain == TREE_CHAIN (t))
10864           return t;
10865         return tree_cons (purpose, value, chain);
10866       }
10867
10868     case RECORD_TYPE:
10869     case UNION_TYPE:
10870     case ENUMERAL_TYPE:
10871     case INTEGER_TYPE:
10872     case TEMPLATE_TYPE_PARM:
10873     case TEMPLATE_TEMPLATE_PARM:
10874     case BOUND_TEMPLATE_TEMPLATE_PARM:
10875     case TEMPLATE_PARM_INDEX:
10876     case POINTER_TYPE:
10877     case REFERENCE_TYPE:
10878     case OFFSET_TYPE:
10879     case FUNCTION_TYPE:
10880     case METHOD_TYPE:
10881     case ARRAY_TYPE:
10882     case TYPENAME_TYPE:
10883     case UNBOUND_CLASS_TEMPLATE:
10884     case TYPEOF_TYPE:
10885     case DECLTYPE_TYPE:
10886     case TYPE_DECL:
10887       return tsubst (t, args, complain, in_decl);
10888
10889     case IDENTIFIER_NODE:
10890       if (IDENTIFIER_TYPENAME_P (t))
10891         {
10892           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10893           return mangle_conv_op_name_for_type (new_type);
10894         }
10895       else
10896         return t;
10897
10898     case CONSTRUCTOR:
10899       /* This is handled by tsubst_copy_and_build.  */
10900       gcc_unreachable ();
10901
10902     case VA_ARG_EXPR:
10903       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10904                                           in_decl),
10905                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10906
10907     case CLEANUP_POINT_EXPR:
10908       /* We shouldn't have built any of these during initial template
10909          generation.  Instead, they should be built during instantiation
10910          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10911       gcc_unreachable ();
10912
10913     case OFFSET_REF:
10914       mark_used (TREE_OPERAND (t, 1));
10915       return t;
10916
10917     case EXPR_PACK_EXPANSION:
10918       error ("invalid use of pack expansion expression");
10919       return error_mark_node;
10920
10921     case NONTYPE_ARGUMENT_PACK:
10922       error ("use %<...%> to expand argument pack");
10923       return error_mark_node;
10924
10925     default:
10926       return t;
10927     }
10928 }
10929
10930 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10931
10932 static tree
10933 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10934                     tree in_decl)
10935 {
10936   tree new_clauses = NULL, nc, oc;
10937
10938   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10939     {
10940       nc = copy_node (oc);
10941       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10942       new_clauses = nc;
10943
10944       switch (OMP_CLAUSE_CODE (nc))
10945         {
10946         case OMP_CLAUSE_LASTPRIVATE:
10947           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
10948             {
10949               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
10950               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
10951                            in_decl, /*integral_constant_expression_p=*/false);
10952               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
10953                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
10954             }
10955           /* FALLTHRU */
10956         case OMP_CLAUSE_PRIVATE:
10957         case OMP_CLAUSE_SHARED:
10958         case OMP_CLAUSE_FIRSTPRIVATE:
10959         case OMP_CLAUSE_REDUCTION:
10960         case OMP_CLAUSE_COPYIN:
10961         case OMP_CLAUSE_COPYPRIVATE:
10962         case OMP_CLAUSE_IF:
10963         case OMP_CLAUSE_NUM_THREADS:
10964         case OMP_CLAUSE_SCHEDULE:
10965         case OMP_CLAUSE_COLLAPSE:
10966           OMP_CLAUSE_OPERAND (nc, 0)
10967             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10968                            in_decl, /*integral_constant_expression_p=*/false);
10969           break;
10970         case OMP_CLAUSE_NOWAIT:
10971         case OMP_CLAUSE_ORDERED:
10972         case OMP_CLAUSE_DEFAULT:
10973         case OMP_CLAUSE_UNTIED:
10974           break;
10975         default:
10976           gcc_unreachable ();
10977         }
10978     }
10979
10980   return finish_omp_clauses (nreverse (new_clauses));
10981 }
10982
10983 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10984
10985 static tree
10986 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10987                           tree in_decl)
10988 {
10989 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10990
10991   tree purpose, value, chain;
10992
10993   if (t == NULL)
10994     return t;
10995
10996   if (TREE_CODE (t) != TREE_LIST)
10997     return tsubst_copy_and_build (t, args, complain, in_decl,
10998                                   /*function_p=*/false,
10999                                   /*integral_constant_expression_p=*/false);
11000
11001   if (t == void_list_node)
11002     return t;
11003
11004   purpose = TREE_PURPOSE (t);
11005   if (purpose)
11006     purpose = RECUR (purpose);
11007   value = TREE_VALUE (t);
11008   if (value && TREE_CODE (value) != LABEL_DECL)
11009     value = RECUR (value);
11010   chain = TREE_CHAIN (t);
11011   if (chain && chain != void_type_node)
11012     chain = RECUR (chain);
11013   return tree_cons (purpose, value, chain);
11014 #undef RECUR
11015 }
11016
11017 /* Substitute one OMP_FOR iterator.  */
11018
11019 static void
11020 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11021                          tree condv, tree incrv, tree *clauses,
11022                          tree args, tsubst_flags_t complain, tree in_decl,
11023                          bool integral_constant_expression_p)
11024 {
11025 #define RECUR(NODE)                             \
11026   tsubst_expr ((NODE), args, complain, in_decl, \
11027                integral_constant_expression_p)
11028   tree decl, init, cond, incr, auto_node;
11029
11030   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11031   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11032   decl = RECUR (TREE_OPERAND (init, 0));
11033   init = TREE_OPERAND (init, 1);
11034   auto_node = type_uses_auto (TREE_TYPE (decl));
11035   if (auto_node && init)
11036     {
11037       tree init_expr = init;
11038       if (TREE_CODE (init_expr) == DECL_EXPR)
11039         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11040       init_expr = RECUR (init_expr);
11041       TREE_TYPE (decl)
11042         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11043     }
11044   gcc_assert (!type_dependent_expression_p (decl));
11045
11046   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11047     {
11048       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11049       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11050       if (TREE_CODE (incr) == MODIFY_EXPR)
11051         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11052                                     RECUR (TREE_OPERAND (incr, 1)),
11053                                     complain);
11054       else
11055         incr = RECUR (incr);
11056       TREE_VEC_ELT (declv, i) = decl;
11057       TREE_VEC_ELT (initv, i) = init;
11058       TREE_VEC_ELT (condv, i) = cond;
11059       TREE_VEC_ELT (incrv, i) = incr;
11060       return;
11061     }
11062
11063   if (init && TREE_CODE (init) != DECL_EXPR)
11064     {
11065       tree c;
11066       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11067         {
11068           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11069                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11070               && OMP_CLAUSE_DECL (c) == decl)
11071             break;
11072           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11073                    && OMP_CLAUSE_DECL (c) == decl)
11074             error ("iteration variable %qD should not be firstprivate", decl);
11075           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11076                    && OMP_CLAUSE_DECL (c) == decl)
11077             error ("iteration variable %qD should not be reduction", decl);
11078         }
11079       if (c == NULL)
11080         {
11081           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11082           OMP_CLAUSE_DECL (c) = decl;
11083           c = finish_omp_clauses (c);
11084           if (c)
11085             {
11086               OMP_CLAUSE_CHAIN (c) = *clauses;
11087               *clauses = c;
11088             }
11089         }
11090     }
11091   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11092   if (COMPARISON_CLASS_P (cond))
11093     cond = build2 (TREE_CODE (cond), boolean_type_node,
11094                    RECUR (TREE_OPERAND (cond, 0)),
11095                    RECUR (TREE_OPERAND (cond, 1)));
11096   else
11097     cond = RECUR (cond);
11098   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11099   switch (TREE_CODE (incr))
11100     {
11101     case PREINCREMENT_EXPR:
11102     case PREDECREMENT_EXPR:
11103     case POSTINCREMENT_EXPR:
11104     case POSTDECREMENT_EXPR:
11105       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11106                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11107       break;
11108     case MODIFY_EXPR:
11109       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11110           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11111         {
11112           tree rhs = TREE_OPERAND (incr, 1);
11113           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11114                          RECUR (TREE_OPERAND (incr, 0)),
11115                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11116                                  RECUR (TREE_OPERAND (rhs, 0)),
11117                                  RECUR (TREE_OPERAND (rhs, 1))));
11118         }
11119       else
11120         incr = RECUR (incr);
11121       break;
11122     case MODOP_EXPR:
11123       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11124           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11125         {
11126           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11127           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11128                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11129                                  TREE_TYPE (decl), lhs,
11130                                  RECUR (TREE_OPERAND (incr, 2))));
11131         }
11132       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11133                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11134                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11135         {
11136           tree rhs = TREE_OPERAND (incr, 2);
11137           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11138                          RECUR (TREE_OPERAND (incr, 0)),
11139                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11140                                  RECUR (TREE_OPERAND (rhs, 0)),
11141                                  RECUR (TREE_OPERAND (rhs, 1))));
11142         }
11143       else
11144         incr = RECUR (incr);
11145       break;
11146     default:
11147       incr = RECUR (incr);
11148       break;
11149     }
11150
11151   TREE_VEC_ELT (declv, i) = decl;
11152   TREE_VEC_ELT (initv, i) = init;
11153   TREE_VEC_ELT (condv, i) = cond;
11154   TREE_VEC_ELT (incrv, i) = incr;
11155 #undef RECUR
11156 }
11157
11158 /* Like tsubst_copy for expressions, etc. but also does semantic
11159    processing.  */
11160
11161 static tree
11162 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11163              bool integral_constant_expression_p)
11164 {
11165 #define RECUR(NODE)                             \
11166   tsubst_expr ((NODE), args, complain, in_decl, \
11167                integral_constant_expression_p)
11168
11169   tree stmt, tmp;
11170
11171   if (t == NULL_TREE || t == error_mark_node)
11172     return t;
11173
11174   if (EXPR_HAS_LOCATION (t))
11175     input_location = EXPR_LOCATION (t);
11176   if (STATEMENT_CODE_P (TREE_CODE (t)))
11177     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11178
11179   switch (TREE_CODE (t))
11180     {
11181     case STATEMENT_LIST:
11182       {
11183         tree_stmt_iterator i;
11184         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11185           RECUR (tsi_stmt (i));
11186         break;
11187       }
11188
11189     case CTOR_INITIALIZER:
11190       finish_mem_initializers (tsubst_initializer_list
11191                                (TREE_OPERAND (t, 0), args));
11192       break;
11193
11194     case RETURN_EXPR:
11195       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11196       break;
11197
11198     case EXPR_STMT:
11199       tmp = RECUR (EXPR_STMT_EXPR (t));
11200       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11201         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11202       else
11203         finish_expr_stmt (tmp);
11204       break;
11205
11206     case USING_STMT:
11207       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11208       break;
11209
11210     case DECL_EXPR:
11211       {
11212         tree decl;
11213         tree init;
11214
11215         decl = DECL_EXPR_DECL (t);
11216         if (TREE_CODE (decl) == LABEL_DECL)
11217           finish_label_decl (DECL_NAME (decl));
11218         else if (TREE_CODE (decl) == USING_DECL)
11219           {
11220             tree scope = USING_DECL_SCOPE (decl);
11221             tree name = DECL_NAME (decl);
11222             tree decl;
11223
11224             scope = RECUR (scope);
11225             decl = lookup_qualified_name (scope, name,
11226                                           /*is_type_p=*/false,
11227                                           /*complain=*/false);
11228             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11229               qualified_name_lookup_error (scope, name, decl, input_location);
11230             else
11231               do_local_using_decl (decl, scope, name);
11232           }
11233         else
11234           {
11235             init = DECL_INITIAL (decl);
11236             decl = tsubst (decl, args, complain, in_decl);
11237             if (decl != error_mark_node)
11238               {
11239                 /* By marking the declaration as instantiated, we avoid
11240                    trying to instantiate it.  Since instantiate_decl can't
11241                    handle local variables, and since we've already done
11242                    all that needs to be done, that's the right thing to
11243                    do.  */
11244                 if (TREE_CODE (decl) == VAR_DECL)
11245                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11246                 if (TREE_CODE (decl) == VAR_DECL
11247                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11248                   /* Anonymous aggregates are a special case.  */
11249                   finish_anon_union (decl);
11250                 else
11251                   {
11252                     maybe_push_decl (decl);
11253                     if (TREE_CODE (decl) == VAR_DECL
11254                         && DECL_PRETTY_FUNCTION_P (decl))
11255                       {
11256                         /* For __PRETTY_FUNCTION__ we have to adjust the
11257                            initializer.  */
11258                         const char *const name
11259                           = cxx_printable_name (current_function_decl, 2);
11260                         init = cp_fname_init (name, &TREE_TYPE (decl));
11261                       }
11262                     else
11263                       {
11264                         tree t = RECUR (init);
11265
11266                         if (init && !t)
11267                           /* If we had an initializer but it
11268                              instantiated to nothing,
11269                              value-initialize the object.  This will
11270                              only occur when the initializer was a
11271                              pack expansion where the parameter packs
11272                              used in that expansion were of length
11273                              zero.  */
11274                           init = build_value_init (TREE_TYPE (decl));
11275                         else
11276                           init = t;
11277                       }
11278
11279                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11280                   }
11281               }
11282           }
11283
11284         /* A DECL_EXPR can also be used as an expression, in the condition
11285            clause of an if/for/while construct.  */
11286         return decl;
11287       }
11288
11289     case FOR_STMT:
11290       stmt = begin_for_stmt ();
11291                           RECUR (FOR_INIT_STMT (t));
11292       finish_for_init_stmt (stmt);
11293       tmp = RECUR (FOR_COND (t));
11294       finish_for_cond (tmp, stmt);
11295       tmp = RECUR (FOR_EXPR (t));
11296       finish_for_expr (tmp, stmt);
11297       RECUR (FOR_BODY (t));
11298       finish_for_stmt (stmt);
11299       break;
11300
11301     case WHILE_STMT:
11302       stmt = begin_while_stmt ();
11303       tmp = RECUR (WHILE_COND (t));
11304       finish_while_stmt_cond (tmp, stmt);
11305       RECUR (WHILE_BODY (t));
11306       finish_while_stmt (stmt);
11307       break;
11308
11309     case DO_STMT:
11310       stmt = begin_do_stmt ();
11311       RECUR (DO_BODY (t));
11312       finish_do_body (stmt);
11313       tmp = RECUR (DO_COND (t));
11314       finish_do_stmt (tmp, stmt);
11315       break;
11316
11317     case IF_STMT:
11318       stmt = begin_if_stmt ();
11319       tmp = RECUR (IF_COND (t));
11320       finish_if_stmt_cond (tmp, stmt);
11321       RECUR (THEN_CLAUSE (t));
11322       finish_then_clause (stmt);
11323
11324       if (ELSE_CLAUSE (t))
11325         {
11326           begin_else_clause (stmt);
11327           RECUR (ELSE_CLAUSE (t));
11328           finish_else_clause (stmt);
11329         }
11330
11331       finish_if_stmt (stmt);
11332       break;
11333
11334     case BIND_EXPR:
11335       if (BIND_EXPR_BODY_BLOCK (t))
11336         stmt = begin_function_body ();
11337       else
11338         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11339                                     ? BCS_TRY_BLOCK : 0);
11340
11341       RECUR (BIND_EXPR_BODY (t));
11342
11343       if (BIND_EXPR_BODY_BLOCK (t))
11344         finish_function_body (stmt);
11345       else
11346         finish_compound_stmt (stmt);
11347       break;
11348
11349     case BREAK_STMT:
11350       finish_break_stmt ();
11351       break;
11352
11353     case CONTINUE_STMT:
11354       finish_continue_stmt ();
11355       break;
11356
11357     case SWITCH_STMT:
11358       stmt = begin_switch_stmt ();
11359       tmp = RECUR (SWITCH_STMT_COND (t));
11360       finish_switch_cond (tmp, stmt);
11361       RECUR (SWITCH_STMT_BODY (t));
11362       finish_switch_stmt (stmt);
11363       break;
11364
11365     case CASE_LABEL_EXPR:
11366       finish_case_label (EXPR_LOCATION (t),
11367                          RECUR (CASE_LOW (t)),
11368                          RECUR (CASE_HIGH (t)));
11369       break;
11370
11371     case LABEL_EXPR:
11372       {
11373         tree decl = LABEL_EXPR_LABEL (t);
11374         tree label;
11375
11376         label = finish_label_stmt (DECL_NAME (decl));
11377         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11378           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11379       }
11380       break;
11381
11382     case GOTO_EXPR:
11383       tmp = GOTO_DESTINATION (t);
11384       if (TREE_CODE (tmp) != LABEL_DECL)
11385         /* Computed goto's must be tsubst'd into.  On the other hand,
11386            non-computed gotos must not be; the identifier in question
11387            will have no binding.  */
11388         tmp = RECUR (tmp);
11389       else
11390         tmp = DECL_NAME (tmp);
11391       finish_goto_stmt (tmp);
11392       break;
11393
11394     case ASM_EXPR:
11395       tmp = finish_asm_stmt
11396         (ASM_VOLATILE_P (t),
11397          RECUR (ASM_STRING (t)),
11398          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11399          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11400          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11401          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11402       {
11403         tree asm_expr = tmp;
11404         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11405           asm_expr = TREE_OPERAND (asm_expr, 0);
11406         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11407       }
11408       break;
11409
11410     case TRY_BLOCK:
11411       if (CLEANUP_P (t))
11412         {
11413           stmt = begin_try_block ();
11414           RECUR (TRY_STMTS (t));
11415           finish_cleanup_try_block (stmt);
11416           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11417         }
11418       else
11419         {
11420           tree compound_stmt = NULL_TREE;
11421
11422           if (FN_TRY_BLOCK_P (t))
11423             stmt = begin_function_try_block (&compound_stmt);
11424           else
11425             stmt = begin_try_block ();
11426
11427           RECUR (TRY_STMTS (t));
11428
11429           if (FN_TRY_BLOCK_P (t))
11430             finish_function_try_block (stmt);
11431           else
11432             finish_try_block (stmt);
11433
11434           RECUR (TRY_HANDLERS (t));
11435           if (FN_TRY_BLOCK_P (t))
11436             finish_function_handler_sequence (stmt, compound_stmt);
11437           else
11438             finish_handler_sequence (stmt);
11439         }
11440       break;
11441
11442     case HANDLER:
11443       {
11444         tree decl = HANDLER_PARMS (t);
11445
11446         if (decl)
11447           {
11448             decl = tsubst (decl, args, complain, in_decl);
11449             /* Prevent instantiate_decl from trying to instantiate
11450                this variable.  We've already done all that needs to be
11451                done.  */
11452             if (decl != error_mark_node)
11453               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11454           }
11455         stmt = begin_handler ();
11456         finish_handler_parms (decl, stmt);
11457         RECUR (HANDLER_BODY (t));
11458         finish_handler (stmt);
11459       }
11460       break;
11461
11462     case TAG_DEFN:
11463       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11464       break;
11465
11466     case STATIC_ASSERT:
11467       {
11468         tree condition = 
11469           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11470                        args,
11471                        complain, in_decl,
11472                        /*integral_constant_expression_p=*/true);
11473         finish_static_assert (condition,
11474                               STATIC_ASSERT_MESSAGE (t),
11475                               STATIC_ASSERT_SOURCE_LOCATION (t),
11476                               /*member_p=*/false);
11477       }
11478       break;
11479
11480     case OMP_PARALLEL:
11481       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11482                                 args, complain, in_decl);
11483       stmt = begin_omp_parallel ();
11484       RECUR (OMP_PARALLEL_BODY (t));
11485       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11486         = OMP_PARALLEL_COMBINED (t);
11487       break;
11488
11489     case OMP_TASK:
11490       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11491                                 args, complain, in_decl);
11492       stmt = begin_omp_task ();
11493       RECUR (OMP_TASK_BODY (t));
11494       finish_omp_task (tmp, stmt);
11495       break;
11496
11497     case OMP_FOR:
11498       {
11499         tree clauses, body, pre_body;
11500         tree declv, initv, condv, incrv;
11501         int i;
11502
11503         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11504                                       args, complain, in_decl);
11505         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11506         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11507         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11508         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11509
11510         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11511           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11512                                    &clauses, args, complain, in_decl,
11513                                    integral_constant_expression_p);
11514
11515         stmt = begin_omp_structured_block ();
11516
11517         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11518           if (TREE_VEC_ELT (initv, i) == NULL
11519               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11520             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11521           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11522             {
11523               tree init = RECUR (TREE_VEC_ELT (initv, i));
11524               gcc_assert (init == TREE_VEC_ELT (declv, i));
11525               TREE_VEC_ELT (initv, i) = NULL_TREE;
11526             }
11527           else
11528             {
11529               tree decl_expr = TREE_VEC_ELT (initv, i);
11530               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11531               gcc_assert (init != NULL);
11532               TREE_VEC_ELT (initv, i) = RECUR (init);
11533               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11534               RECUR (decl_expr);
11535               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11536             }
11537
11538         pre_body = push_stmt_list ();
11539         RECUR (OMP_FOR_PRE_BODY (t));
11540         pre_body = pop_stmt_list (pre_body);
11541
11542         body = push_stmt_list ();
11543         RECUR (OMP_FOR_BODY (t));
11544         body = pop_stmt_list (body);
11545
11546         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11547                             body, pre_body, clauses);
11548
11549         add_stmt (finish_omp_structured_block (stmt));
11550       }
11551       break;
11552
11553     case OMP_SECTIONS:
11554     case OMP_SINGLE:
11555       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11556       stmt = push_stmt_list ();
11557       RECUR (OMP_BODY (t));
11558       stmt = pop_stmt_list (stmt);
11559
11560       t = copy_node (t);
11561       OMP_BODY (t) = stmt;
11562       OMP_CLAUSES (t) = tmp;
11563       add_stmt (t);
11564       break;
11565
11566     case OMP_SECTION:
11567     case OMP_CRITICAL:
11568     case OMP_MASTER:
11569     case OMP_ORDERED:
11570       stmt = push_stmt_list ();
11571       RECUR (OMP_BODY (t));
11572       stmt = pop_stmt_list (stmt);
11573
11574       t = copy_node (t);
11575       OMP_BODY (t) = stmt;
11576       add_stmt (t);
11577       break;
11578
11579     case OMP_ATOMIC:
11580       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11581       {
11582         tree op1 = TREE_OPERAND (t, 1);
11583         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11584         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11585         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11586       }
11587       break;
11588
11589     case EXPR_PACK_EXPANSION:
11590       error ("invalid use of pack expansion expression");
11591       return error_mark_node;
11592
11593     case NONTYPE_ARGUMENT_PACK:
11594       error ("use %<...%> to expand argument pack");
11595       return error_mark_node;
11596
11597     default:
11598       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11599
11600       return tsubst_copy_and_build (t, args, complain, in_decl,
11601                                     /*function_p=*/false,
11602                                     integral_constant_expression_p);
11603     }
11604
11605   return NULL_TREE;
11606 #undef RECUR
11607 }
11608
11609 /* T is a postfix-expression that is not being used in a function
11610    call.  Return the substituted version of T.  */
11611
11612 static tree
11613 tsubst_non_call_postfix_expression (tree t, tree args,
11614                                     tsubst_flags_t complain,
11615                                     tree in_decl)
11616 {
11617   if (TREE_CODE (t) == SCOPE_REF)
11618     t = tsubst_qualified_id (t, args, complain, in_decl,
11619                              /*done=*/false, /*address_p=*/false);
11620   else
11621     t = tsubst_copy_and_build (t, args, complain, in_decl,
11622                                /*function_p=*/false,
11623                                /*integral_constant_expression_p=*/false);
11624
11625   return t;
11626 }
11627
11628 /* Like tsubst but deals with expressions and performs semantic
11629    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11630
11631 tree
11632 tsubst_copy_and_build (tree t,
11633                        tree args,
11634                        tsubst_flags_t complain,
11635                        tree in_decl,
11636                        bool function_p,
11637                        bool integral_constant_expression_p)
11638 {
11639 #define RECUR(NODE)                                             \
11640   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11641                          /*function_p=*/false,                  \
11642                          integral_constant_expression_p)
11643
11644   tree op1;
11645
11646   if (t == NULL_TREE || t == error_mark_node)
11647     return t;
11648
11649   switch (TREE_CODE (t))
11650     {
11651     case USING_DECL:
11652       t = DECL_NAME (t);
11653       /* Fall through.  */
11654     case IDENTIFIER_NODE:
11655       {
11656         tree decl;
11657         cp_id_kind idk;
11658         bool non_integral_constant_expression_p;
11659         const char *error_msg;
11660
11661         if (IDENTIFIER_TYPENAME_P (t))
11662           {
11663             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11664             t = mangle_conv_op_name_for_type (new_type);
11665           }
11666
11667         /* Look up the name.  */
11668         decl = lookup_name (t);
11669
11670         /* By convention, expressions use ERROR_MARK_NODE to indicate
11671            failure, not NULL_TREE.  */
11672         if (decl == NULL_TREE)
11673           decl = error_mark_node;
11674
11675         decl = finish_id_expression (t, decl, NULL_TREE,
11676                                      &idk,
11677                                      integral_constant_expression_p,
11678                                      /*allow_non_integral_constant_expression_p=*/false,
11679                                      &non_integral_constant_expression_p,
11680                                      /*template_p=*/false,
11681                                      /*done=*/true,
11682                                      /*address_p=*/false,
11683                                      /*template_arg_p=*/false,
11684                                      &error_msg,
11685                                      input_location);
11686         if (error_msg)
11687           error (error_msg);
11688         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11689           decl = unqualified_name_lookup_error (decl);
11690         return decl;
11691       }
11692
11693     case TEMPLATE_ID_EXPR:
11694       {
11695         tree object;
11696         tree templ = RECUR (TREE_OPERAND (t, 0));
11697         tree targs = TREE_OPERAND (t, 1);
11698
11699         if (targs)
11700           targs = tsubst_template_args (targs, args, complain, in_decl);
11701
11702         if (TREE_CODE (templ) == COMPONENT_REF)
11703           {
11704             object = TREE_OPERAND (templ, 0);
11705             templ = TREE_OPERAND (templ, 1);
11706           }
11707         else
11708           object = NULL_TREE;
11709         templ = lookup_template_function (templ, targs);
11710
11711         if (object)
11712           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11713                          object, templ, NULL_TREE);
11714         else
11715           return baselink_for_fns (templ);
11716       }
11717
11718     case INDIRECT_REF:
11719       {
11720         tree r = RECUR (TREE_OPERAND (t, 0));
11721
11722         if (REFERENCE_REF_P (t))
11723           {
11724             /* A type conversion to reference type will be enclosed in
11725                such an indirect ref, but the substitution of the cast
11726                will have also added such an indirect ref.  */
11727             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11728               r = convert_from_reference (r);
11729           }
11730         else
11731           r = build_x_indirect_ref (r, "unary *", complain);
11732         return r;
11733       }
11734
11735     case NOP_EXPR:
11736       return build_nop
11737         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11738          RECUR (TREE_OPERAND (t, 0)));
11739
11740     case CAST_EXPR:
11741     case REINTERPRET_CAST_EXPR:
11742     case CONST_CAST_EXPR:
11743     case DYNAMIC_CAST_EXPR:
11744     case STATIC_CAST_EXPR:
11745       {
11746         tree type;
11747         tree op;
11748
11749         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11750         if (integral_constant_expression_p
11751             && !cast_valid_in_integral_constant_expression_p (type))
11752           {
11753             if (complain & tf_error)
11754               error ("a cast to a type other than an integral or "
11755                      "enumeration type cannot appear in a constant-expression");
11756             return error_mark_node; 
11757           }
11758
11759         op = RECUR (TREE_OPERAND (t, 0));
11760
11761         switch (TREE_CODE (t))
11762           {
11763           case CAST_EXPR:
11764             return build_functional_cast (type, op, complain);
11765           case REINTERPRET_CAST_EXPR:
11766             return build_reinterpret_cast (type, op, complain);
11767           case CONST_CAST_EXPR:
11768             return build_const_cast (type, op, complain);
11769           case DYNAMIC_CAST_EXPR:
11770             return build_dynamic_cast (type, op, complain);
11771           case STATIC_CAST_EXPR:
11772             return build_static_cast (type, op, complain);
11773           default:
11774             gcc_unreachable ();
11775           }
11776       }
11777
11778     case POSTDECREMENT_EXPR:
11779     case POSTINCREMENT_EXPR:
11780       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11781                                                 args, complain, in_decl);
11782       return build_x_unary_op (TREE_CODE (t), op1, complain);
11783
11784     case PREDECREMENT_EXPR:
11785     case PREINCREMENT_EXPR:
11786     case NEGATE_EXPR:
11787     case BIT_NOT_EXPR:
11788     case ABS_EXPR:
11789     case TRUTH_NOT_EXPR:
11790     case UNARY_PLUS_EXPR:  /* Unary + */
11791     case REALPART_EXPR:
11792     case IMAGPART_EXPR:
11793       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11794                                complain);
11795
11796     case ADDR_EXPR:
11797       op1 = TREE_OPERAND (t, 0);
11798       if (TREE_CODE (op1) == SCOPE_REF)
11799         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11800                                    /*done=*/true, /*address_p=*/true);
11801       else
11802         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11803                                                   in_decl);
11804       if (TREE_CODE (op1) == LABEL_DECL)
11805         return finish_label_address_expr (DECL_NAME (op1),
11806                                           EXPR_LOCATION (op1));
11807       return build_x_unary_op (ADDR_EXPR, op1, complain);
11808
11809     case PLUS_EXPR:
11810     case MINUS_EXPR:
11811     case MULT_EXPR:
11812     case TRUNC_DIV_EXPR:
11813     case CEIL_DIV_EXPR:
11814     case FLOOR_DIV_EXPR:
11815     case ROUND_DIV_EXPR:
11816     case EXACT_DIV_EXPR:
11817     case BIT_AND_EXPR:
11818     case BIT_IOR_EXPR:
11819     case BIT_XOR_EXPR:
11820     case TRUNC_MOD_EXPR:
11821     case FLOOR_MOD_EXPR:
11822     case TRUTH_ANDIF_EXPR:
11823     case TRUTH_ORIF_EXPR:
11824     case TRUTH_AND_EXPR:
11825     case TRUTH_OR_EXPR:
11826     case RSHIFT_EXPR:
11827     case LSHIFT_EXPR:
11828     case RROTATE_EXPR:
11829     case LROTATE_EXPR:
11830     case EQ_EXPR:
11831     case NE_EXPR:
11832     case MAX_EXPR:
11833     case MIN_EXPR:
11834     case LE_EXPR:
11835     case GE_EXPR:
11836     case LT_EXPR:
11837     case GT_EXPR:
11838     case MEMBER_REF:
11839     case DOTSTAR_EXPR:
11840       return build_x_binary_op
11841         (TREE_CODE (t),
11842          RECUR (TREE_OPERAND (t, 0)),
11843          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11844           ? ERROR_MARK
11845           : TREE_CODE (TREE_OPERAND (t, 0))),
11846          RECUR (TREE_OPERAND (t, 1)),
11847          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11848           ? ERROR_MARK
11849           : TREE_CODE (TREE_OPERAND (t, 1))),
11850          /*overloaded_p=*/NULL,
11851          complain);
11852
11853     case SCOPE_REF:
11854       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11855                                   /*address_p=*/false);
11856     case ARRAY_REF:
11857       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11858                                                 args, complain, in_decl);
11859       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11860
11861     case SIZEOF_EXPR:
11862       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11863         return tsubst_copy (t, args, complain, in_decl);
11864       /* Fall through */
11865       
11866     case ALIGNOF_EXPR:
11867       op1 = TREE_OPERAND (t, 0);
11868       if (!args)
11869         {
11870           /* When there are no ARGS, we are trying to evaluate a
11871              non-dependent expression from the parser.  Trying to do
11872              the substitutions may not work.  */
11873           if (!TYPE_P (op1))
11874             op1 = TREE_TYPE (op1);
11875         }
11876       else
11877         {
11878           ++cp_unevaluated_operand;
11879           ++c_inhibit_evaluation_warnings;
11880           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11881                                        /*function_p=*/false,
11882                                        /*integral_constant_expression_p=*/false);
11883           --cp_unevaluated_operand;
11884           --c_inhibit_evaluation_warnings;
11885         }
11886       if (TYPE_P (op1))
11887         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11888                                            complain & tf_error);
11889       else
11890         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11891                                            complain & tf_error);
11892
11893     case MODOP_EXPR:
11894       {
11895         tree r = build_x_modify_expr
11896           (RECUR (TREE_OPERAND (t, 0)),
11897            TREE_CODE (TREE_OPERAND (t, 1)),
11898            RECUR (TREE_OPERAND (t, 2)),
11899            complain);
11900         /* TREE_NO_WARNING must be set if either the expression was
11901            parenthesized or it uses an operator such as >>= rather
11902            than plain assignment.  In the former case, it was already
11903            set and must be copied.  In the latter case,
11904            build_x_modify_expr sets it and it must not be reset
11905            here.  */
11906         if (TREE_NO_WARNING (t))
11907           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11908         return r;
11909       }
11910
11911     case ARROW_EXPR:
11912       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11913                                                 args, complain, in_decl);
11914       /* Remember that there was a reference to this entity.  */
11915       if (DECL_P (op1))
11916         mark_used (op1);
11917       return build_x_arrow (op1);
11918
11919     case NEW_EXPR:
11920       {
11921         tree placement = RECUR (TREE_OPERAND (t, 0));
11922         tree init = RECUR (TREE_OPERAND (t, 3));
11923         VEC(tree,gc) *placement_vec;
11924         VEC(tree,gc) *init_vec;
11925         tree ret;
11926
11927         if (placement == NULL_TREE)
11928           placement_vec = NULL;
11929         else
11930           {
11931             placement_vec = make_tree_vector ();
11932             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
11933               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
11934           }
11935
11936         /* If there was an initializer in the original tree, but it
11937            instantiated to an empty list, then we should pass a
11938            non-NULL empty vector to tell build_new that it was an
11939            empty initializer() rather than no initializer.  This can
11940            only happen when the initializer is a pack expansion whose
11941            parameter packs are of length zero.  */
11942         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
11943           init_vec = NULL;
11944         else
11945           {
11946             init_vec = make_tree_vector ();
11947             if (init == void_zero_node)
11948               gcc_assert (init_vec != NULL);
11949             else
11950               {
11951                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
11952                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
11953               }
11954           }
11955
11956         ret = build_new (&placement_vec,
11957                          RECUR (TREE_OPERAND (t, 1)),
11958                          RECUR (TREE_OPERAND (t, 2)),
11959                          &init_vec,
11960                          NEW_EXPR_USE_GLOBAL (t),
11961                          complain);
11962
11963         if (placement_vec != NULL)
11964           release_tree_vector (placement_vec);
11965         if (init_vec != NULL)
11966           release_tree_vector (init_vec);
11967
11968         return ret;
11969       }
11970
11971     case DELETE_EXPR:
11972      return delete_sanity
11973        (RECUR (TREE_OPERAND (t, 0)),
11974         RECUR (TREE_OPERAND (t, 1)),
11975         DELETE_EXPR_USE_VEC (t),
11976         DELETE_EXPR_USE_GLOBAL (t));
11977
11978     case COMPOUND_EXPR:
11979       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
11980                                     RECUR (TREE_OPERAND (t, 1)),
11981                                     complain);
11982
11983     case CALL_EXPR:
11984       {
11985         tree function;
11986         VEC(tree,gc) *call_args;
11987         unsigned int nargs, i;
11988         bool qualified_p;
11989         bool koenig_p;
11990         tree ret;
11991
11992         function = CALL_EXPR_FN (t);
11993         /* When we parsed the expression,  we determined whether or
11994            not Koenig lookup should be performed.  */
11995         koenig_p = KOENIG_LOOKUP_P (t);
11996         if (TREE_CODE (function) == SCOPE_REF)
11997           {
11998             qualified_p = true;
11999             function = tsubst_qualified_id (function, args, complain, in_decl,
12000                                             /*done=*/false,
12001                                             /*address_p=*/false);
12002           }
12003         else
12004           {
12005             if (TREE_CODE (function) == COMPONENT_REF)
12006               {
12007                 tree op = TREE_OPERAND (function, 1);
12008
12009                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12010                                || (BASELINK_P (op)
12011                                    && BASELINK_QUALIFIED_P (op)));
12012               }
12013             else
12014               qualified_p = false;
12015
12016             function = tsubst_copy_and_build (function, args, complain,
12017                                               in_decl,
12018                                               !qualified_p,
12019                                               integral_constant_expression_p);
12020
12021             if (BASELINK_P (function))
12022               qualified_p = true;
12023           }
12024
12025         nargs = call_expr_nargs (t);
12026         call_args = make_tree_vector ();
12027         for (i = 0; i < nargs; ++i)
12028           {
12029             tree arg = CALL_EXPR_ARG (t, i);
12030
12031             if (!PACK_EXPANSION_P (arg))
12032               VEC_safe_push (tree, gc, call_args,
12033                              RECUR (CALL_EXPR_ARG (t, i)));
12034             else
12035               {
12036                 /* Expand the pack expansion and push each entry onto
12037                    CALL_ARGS.  */
12038                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12039                 if (TREE_CODE (arg) == TREE_VEC)
12040                   {
12041                     unsigned int len, j;
12042
12043                     len = TREE_VEC_LENGTH (arg);
12044                     for (j = 0; j < len; ++j)
12045                       {
12046                         tree value = TREE_VEC_ELT (arg, j);
12047                         if (value != NULL_TREE)
12048                           value = convert_from_reference (value);
12049                         VEC_safe_push (tree, gc, call_args, value);
12050                       }
12051                   }
12052                 else
12053                   {
12054                     /* A partial substitution.  Add one entry.  */
12055                     VEC_safe_push (tree, gc, call_args, arg);
12056                   }
12057               }
12058           }
12059
12060         /* We do not perform argument-dependent lookup if normal
12061            lookup finds a non-function, in accordance with the
12062            expected resolution of DR 218.  */
12063         if (koenig_p
12064             && ((is_overloaded_fn (function)
12065                  /* If lookup found a member function, the Koenig lookup is
12066                     not appropriate, even if an unqualified-name was used
12067                     to denote the function.  */
12068                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12069                 || TREE_CODE (function) == IDENTIFIER_NODE)
12070             /* Only do this when substitution turns a dependent call
12071                into a non-dependent call.  */
12072             && type_dependent_expression_p_push (t)
12073             && !any_type_dependent_arguments_p (call_args))
12074           function = perform_koenig_lookup (function, call_args);
12075
12076         if (TREE_CODE (function) == IDENTIFIER_NODE)
12077           {
12078             unqualified_name_lookup_error (function);
12079             release_tree_vector (call_args);
12080             return error_mark_node;
12081           }
12082
12083         /* Remember that there was a reference to this entity.  */
12084         if (DECL_P (function))
12085           mark_used (function);
12086
12087         if (TREE_CODE (function) == OFFSET_REF)
12088           ret = build_offset_ref_call_from_tree (function, &call_args);
12089         else if (TREE_CODE (function) == COMPONENT_REF)
12090           {
12091             if (!BASELINK_P (TREE_OPERAND (function, 1)))
12092               ret = finish_call_expr (function, &call_args,
12093                                        /*disallow_virtual=*/false,
12094                                        /*koenig_p=*/false,
12095                                        complain);
12096             else
12097               ret = (build_new_method_call
12098                       (TREE_OPERAND (function, 0),
12099                        TREE_OPERAND (function, 1),
12100                        &call_args, NULL_TREE,
12101                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12102                        /*fn_p=*/NULL,
12103                        complain));
12104           }
12105         else
12106           ret = finish_call_expr (function, &call_args,
12107                                   /*disallow_virtual=*/qualified_p,
12108                                   koenig_p,
12109                                   complain);
12110
12111         release_tree_vector (call_args);
12112
12113         return ret;
12114       }
12115
12116     case COND_EXPR:
12117       return build_x_conditional_expr
12118         (RECUR (TREE_OPERAND (t, 0)),
12119          RECUR (TREE_OPERAND (t, 1)),
12120          RECUR (TREE_OPERAND (t, 2)),
12121          complain);
12122
12123     case PSEUDO_DTOR_EXPR:
12124       return finish_pseudo_destructor_expr
12125         (RECUR (TREE_OPERAND (t, 0)),
12126          RECUR (TREE_OPERAND (t, 1)),
12127          RECUR (TREE_OPERAND (t, 2)));
12128
12129     case TREE_LIST:
12130       {
12131         tree purpose, value, chain;
12132
12133         if (t == void_list_node)
12134           return t;
12135
12136         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12137             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12138           {
12139             /* We have pack expansions, so expand those and
12140                create a new list out of it.  */
12141             tree purposevec = NULL_TREE;
12142             tree valuevec = NULL_TREE;
12143             tree chain;
12144             int i, len = -1;
12145
12146             /* Expand the argument expressions.  */
12147             if (TREE_PURPOSE (t))
12148               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12149                                                  complain, in_decl);
12150             if (TREE_VALUE (t))
12151               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12152                                                complain, in_decl);
12153
12154             /* Build the rest of the list.  */
12155             chain = TREE_CHAIN (t);
12156             if (chain && chain != void_type_node)
12157               chain = RECUR (chain);
12158
12159             /* Determine the number of arguments.  */
12160             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12161               {
12162                 len = TREE_VEC_LENGTH (purposevec);
12163                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12164               }
12165             else if (TREE_CODE (valuevec) == TREE_VEC)
12166               len = TREE_VEC_LENGTH (valuevec);
12167             else
12168               {
12169                 /* Since we only performed a partial substitution into
12170                    the argument pack, we only return a single list
12171                    node.  */
12172                 if (purposevec == TREE_PURPOSE (t)
12173                     && valuevec == TREE_VALUE (t)
12174                     && chain == TREE_CHAIN (t))
12175                   return t;
12176
12177                 return tree_cons (purposevec, valuevec, chain);
12178               }
12179             
12180             /* Convert the argument vectors into a TREE_LIST */
12181             i = len;
12182             while (i > 0)
12183               {
12184                 /* Grab the Ith values.  */
12185                 i--;
12186                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12187                                      : NULL_TREE;
12188                 value 
12189                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12190                              : NULL_TREE;
12191
12192                 /* Build the list (backwards).  */
12193                 chain = tree_cons (purpose, value, chain);
12194               }
12195
12196             return chain;
12197           }
12198
12199         purpose = TREE_PURPOSE (t);
12200         if (purpose)
12201           purpose = RECUR (purpose);
12202         value = TREE_VALUE (t);
12203         if (value)
12204           value = RECUR (value);
12205         chain = TREE_CHAIN (t);
12206         if (chain && chain != void_type_node)
12207           chain = RECUR (chain);
12208         if (purpose == TREE_PURPOSE (t)
12209             && value == TREE_VALUE (t)
12210             && chain == TREE_CHAIN (t))
12211           return t;
12212         return tree_cons (purpose, value, chain);
12213       }
12214
12215     case COMPONENT_REF:
12216       {
12217         tree object;
12218         tree object_type;
12219         tree member;
12220
12221         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12222                                                      args, complain, in_decl);
12223         /* Remember that there was a reference to this entity.  */
12224         if (DECL_P (object))
12225           mark_used (object);
12226         object_type = TREE_TYPE (object);
12227
12228         member = TREE_OPERAND (t, 1);
12229         if (BASELINK_P (member))
12230           member = tsubst_baselink (member,
12231                                     non_reference (TREE_TYPE (object)),
12232                                     args, complain, in_decl);
12233         else
12234           member = tsubst_copy (member, args, complain, in_decl);
12235         if (member == error_mark_node)
12236           return error_mark_node;
12237
12238         if (object_type && !CLASS_TYPE_P (object_type))
12239           {
12240             if (SCALAR_TYPE_P (object_type))
12241               {
12242                 tree s = NULL_TREE;
12243                 tree dtor = member;
12244
12245                 if (TREE_CODE (dtor) == SCOPE_REF)
12246                   {
12247                     s = TREE_OPERAND (dtor, 0);
12248                     dtor = TREE_OPERAND (dtor, 1);
12249                   }
12250                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12251                   {
12252                     dtor = TREE_OPERAND (dtor, 0);
12253                     if (TYPE_P (dtor))
12254                       return finish_pseudo_destructor_expr (object, s, dtor);
12255                   }
12256               }
12257           }
12258         else if (TREE_CODE (member) == SCOPE_REF
12259                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12260           {
12261             tree tmpl;
12262             tree args;
12263
12264             /* Lookup the template functions now that we know what the
12265                scope is.  */
12266             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12267             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12268             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12269                                             /*is_type_p=*/false,
12270                                             /*complain=*/false);
12271             if (BASELINK_P (member))
12272               {
12273                 BASELINK_FUNCTIONS (member)
12274                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12275                               args);
12276                 member = (adjust_result_of_qualified_name_lookup
12277                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12278                            object_type));
12279               }
12280             else
12281               {
12282                 qualified_name_lookup_error (object_type, tmpl, member,
12283                                              input_location);
12284                 return error_mark_node;
12285               }
12286           }
12287         else if (TREE_CODE (member) == SCOPE_REF
12288                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12289                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12290           {
12291             if (complain & tf_error)
12292               {
12293                 if (TYPE_P (TREE_OPERAND (member, 0)))
12294                   error ("%qT is not a class or namespace",
12295                          TREE_OPERAND (member, 0));
12296                 else
12297                   error ("%qD is not a class or namespace",
12298                          TREE_OPERAND (member, 0));
12299               }
12300             return error_mark_node;
12301           }
12302         else if (TREE_CODE (member) == FIELD_DECL)
12303           return finish_non_static_data_member (member, object, NULL_TREE);
12304
12305         return finish_class_member_access_expr (object, member,
12306                                                 /*template_p=*/false,
12307                                                 complain);
12308       }
12309
12310     case THROW_EXPR:
12311       return build_throw
12312         (RECUR (TREE_OPERAND (t, 0)));
12313
12314     case CONSTRUCTOR:
12315       {
12316         VEC(constructor_elt,gc) *n;
12317         constructor_elt *ce;
12318         unsigned HOST_WIDE_INT idx;
12319         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12320         bool process_index_p;
12321         int newlen;
12322         bool need_copy_p = false;
12323         tree r;
12324
12325         if (type == error_mark_node)
12326           return error_mark_node;
12327
12328         /* digest_init will do the wrong thing if we let it.  */
12329         if (type && TYPE_PTRMEMFUNC_P (type))
12330           return t;
12331
12332         /* We do not want to process the index of aggregate
12333            initializers as they are identifier nodes which will be
12334            looked up by digest_init.  */
12335         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12336
12337         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12338         newlen = VEC_length (constructor_elt, n);
12339         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12340           {
12341             if (ce->index && process_index_p)
12342               ce->index = RECUR (ce->index);
12343
12344             if (PACK_EXPANSION_P (ce->value))
12345               {
12346                 /* Substitute into the pack expansion.  */
12347                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12348                                                   in_decl);
12349
12350                 if (ce->value == error_mark_node)
12351                   ;
12352                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12353                   /* Just move the argument into place.  */
12354                   ce->value = TREE_VEC_ELT (ce->value, 0);
12355                 else
12356                   {
12357                     /* Update the length of the final CONSTRUCTOR
12358                        arguments vector, and note that we will need to
12359                        copy.*/
12360                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12361                     need_copy_p = true;
12362                   }
12363               }
12364             else
12365               ce->value = RECUR (ce->value);
12366           }
12367
12368         if (need_copy_p)
12369           {
12370             VEC(constructor_elt,gc) *old_n = n;
12371
12372             n = VEC_alloc (constructor_elt, gc, newlen);
12373             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
12374                  idx++)
12375               {
12376                 if (TREE_CODE (ce->value) == TREE_VEC)
12377                   {
12378                     int i, len = TREE_VEC_LENGTH (ce->value);
12379                     for (i = 0; i < len; ++i)
12380                       CONSTRUCTOR_APPEND_ELT (n, 0,
12381                                               TREE_VEC_ELT (ce->value, i));
12382                   }
12383                 else
12384                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12385               }
12386           }
12387
12388         r = build_constructor (init_list_type_node, n);
12389         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12390
12391         if (TREE_HAS_CONSTRUCTOR (t))
12392           return finish_compound_literal (type, r);
12393
12394         return r;
12395       }
12396
12397     case TYPEID_EXPR:
12398       {
12399         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12400         if (TYPE_P (operand_0))
12401           return get_typeid (operand_0);
12402         return build_typeid (operand_0);
12403       }
12404
12405     case VAR_DECL:
12406       if (!args)
12407         return t;
12408       /* Fall through */
12409
12410     case PARM_DECL:
12411       {
12412         tree r = tsubst_copy (t, args, complain, in_decl);
12413
12414         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12415           /* If the original type was a reference, we'll be wrapped in
12416              the appropriate INDIRECT_REF.  */
12417           r = convert_from_reference (r);
12418         return r;
12419       }
12420
12421     case VA_ARG_EXPR:
12422       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12423                              tsubst_copy (TREE_TYPE (t), args, complain,
12424                                           in_decl));
12425
12426     case OFFSETOF_EXPR:
12427       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12428
12429     case TRAIT_EXPR:
12430       {
12431         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12432                                   complain, in_decl);
12433
12434         tree type2 = TRAIT_EXPR_TYPE2 (t);
12435         if (type2)
12436           type2 = tsubst_copy (type2, args, complain, in_decl);
12437         
12438         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12439       }
12440
12441     case STMT_EXPR:
12442       {
12443         tree old_stmt_expr = cur_stmt_expr;
12444         tree stmt_expr = begin_stmt_expr ();
12445
12446         cur_stmt_expr = stmt_expr;
12447         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12448                      integral_constant_expression_p);
12449         stmt_expr = finish_stmt_expr (stmt_expr, false);
12450         cur_stmt_expr = old_stmt_expr;
12451
12452         return stmt_expr;
12453       }
12454
12455     case CONST_DECL:
12456       t = tsubst_copy (t, args, complain, in_decl);
12457       /* As in finish_id_expression, we resolve enumeration constants
12458          to their underlying values.  */
12459       if (TREE_CODE (t) == CONST_DECL)
12460         {
12461           used_types_insert (TREE_TYPE (t));
12462           return DECL_INITIAL (t);
12463         }
12464       return t;
12465
12466     case LAMBDA_EXPR:
12467       {
12468         tree r = build_lambda_expr ();
12469
12470         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12471         TREE_TYPE (r) = type;
12472         CLASSTYPE_LAMBDA_EXPR (type) = r;
12473
12474         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12475           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12476         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12477         LAMBDA_EXPR_DISCRIMINATOR (r)
12478           = (LAMBDA_EXPR_DISCRIMINATOR (t));
12479         LAMBDA_EXPR_CAPTURE_LIST (r)
12480           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12481         LAMBDA_EXPR_THIS_CAPTURE (r)
12482           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12483         LAMBDA_EXPR_EXTRA_SCOPE (r)
12484           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12485
12486         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12487         determine_visibility (TYPE_NAME (type));
12488         /* Now that we know visibility, instantiate the type so we have a
12489            declaration of the op() for later calls to lambda_function.  */
12490         complete_type (type);
12491
12492         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12493         if (type)
12494           apply_lambda_return_type (r, type);
12495
12496         return build_lambda_object (r);
12497       }
12498
12499     default:
12500       /* Handle Objective-C++ constructs, if appropriate.  */
12501       {
12502         tree subst
12503           = objcp_tsubst_copy_and_build (t, args, complain,
12504                                          in_decl, /*function_p=*/false);
12505         if (subst)
12506           return subst;
12507       }
12508       return tsubst_copy (t, args, complain, in_decl);
12509     }
12510
12511 #undef RECUR
12512 }
12513
12514 /* Verify that the instantiated ARGS are valid. For type arguments,
12515    make sure that the type's linkage is ok. For non-type arguments,
12516    make sure they are constants if they are integral or enumerations.
12517    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12518
12519 static bool
12520 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12521 {
12522   if (ARGUMENT_PACK_P (t))
12523     {
12524       tree vec = ARGUMENT_PACK_ARGS (t);
12525       int len = TREE_VEC_LENGTH (vec);
12526       bool result = false;
12527       int i;
12528
12529       for (i = 0; i < len; ++i)
12530         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12531           result = true;
12532       return result;
12533     }
12534   else if (TYPE_P (t))
12535     {
12536       /* [basic.link]: A name with no linkage (notably, the name
12537          of a class or enumeration declared in a local scope)
12538          shall not be used to declare an entity with linkage.
12539          This implies that names with no linkage cannot be used as
12540          template arguments
12541
12542          DR 757 relaxes this restriction for C++0x.  */
12543       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
12544                  : no_linkage_check (t, /*relaxed_p=*/false));
12545
12546       if (nt)
12547         {
12548           /* DR 488 makes use of a type with no linkage cause
12549              type deduction to fail.  */
12550           if (complain & tf_error)
12551             {
12552               if (TYPE_ANONYMOUS_P (nt))
12553                 error ("%qT is/uses anonymous type", t);
12554               else
12555                 error ("template argument for %qD uses local type %qT",
12556                        tmpl, t);
12557             }
12558           return true;
12559         }
12560       /* In order to avoid all sorts of complications, we do not
12561          allow variably-modified types as template arguments.  */
12562       else if (variably_modified_type_p (t, NULL_TREE))
12563         {
12564           if (complain & tf_error)
12565             error ("%qT is a variably modified type", t);
12566           return true;
12567         }
12568     }
12569   /* A non-type argument of integral or enumerated type must be a
12570      constant.  */
12571   else if (TREE_TYPE (t)
12572            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12573            && !TREE_CONSTANT (t))
12574     {
12575       if (complain & tf_error)
12576         error ("integral expression %qE is not constant", t);
12577       return true;
12578     }
12579   return false;
12580 }
12581
12582 static bool
12583 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12584 {
12585   int ix, len = DECL_NTPARMS (tmpl);
12586   bool result = false;
12587
12588   for (ix = 0; ix != len; ix++)
12589     {
12590       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12591         result = true;
12592     }
12593   if (result && (complain & tf_error))
12594     error ("  trying to instantiate %qD", tmpl);
12595   return result;
12596 }
12597
12598 /* Instantiate the indicated variable or function template TMPL with
12599    the template arguments in TARG_PTR.  */
12600
12601 tree
12602 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
12603 {
12604   tree targ_ptr = orig_args;
12605   tree fndecl;
12606   tree gen_tmpl;
12607   tree spec;
12608   HOST_WIDE_INT saved_processing_template_decl;
12609
12610   if (tmpl == error_mark_node)
12611     return error_mark_node;
12612
12613   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12614
12615   /* If this function is a clone, handle it specially.  */
12616   if (DECL_CLONED_FUNCTION_P (tmpl))
12617     {
12618       tree spec;
12619       tree clone;
12620
12621       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
12622          DECL_CLONED_FUNCTION.  */
12623       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
12624                                    targ_ptr, complain);
12625       if (spec == error_mark_node)
12626         return error_mark_node;
12627
12628       /* Look for the clone.  */
12629       FOR_EACH_CLONE (clone, spec)
12630         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12631           return clone;
12632       /* We should always have found the clone by now.  */
12633       gcc_unreachable ();
12634       return NULL_TREE;
12635     }
12636
12637   /* Check to see if we already have this specialization.  */
12638   gen_tmpl = most_general_template (tmpl);
12639   if (tmpl != gen_tmpl)
12640     /* The TMPL is a partial instantiation.  To get a full set of
12641        arguments we must add the arguments used to perform the
12642        partial instantiation.  */
12643     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12644                                             targ_ptr);
12645
12646   /* It would be nice to avoid hashing here and then again in tsubst_decl,
12647      but it doesn't seem to be on the hot path.  */
12648   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
12649
12650   gcc_assert (tmpl == gen_tmpl
12651               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
12652                   == spec)
12653               || fndecl == NULL_TREE);
12654
12655   if (spec != NULL_TREE)
12656     return spec;
12657
12658   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12659                                complain))
12660     return error_mark_node;
12661
12662   /* We are building a FUNCTION_DECL, during which the access of its
12663      parameters and return types have to be checked.  However this
12664      FUNCTION_DECL which is the desired context for access checking
12665      is not built yet.  We solve this chicken-and-egg problem by
12666      deferring all checks until we have the FUNCTION_DECL.  */
12667   push_deferring_access_checks (dk_deferred);
12668
12669   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12670      (because, for example, we have encountered a non-dependent
12671      function call in the body of a template function and must now
12672      determine which of several overloaded functions will be called),
12673      within the instantiation itself we are not processing a
12674      template.  */  
12675   saved_processing_template_decl = processing_template_decl;
12676   processing_template_decl = 0;
12677   /* Substitute template parameters to obtain the specialization.  */
12678   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12679                    targ_ptr, complain, gen_tmpl);
12680   processing_template_decl = saved_processing_template_decl;
12681   if (fndecl == error_mark_node)
12682     return error_mark_node;
12683
12684   /* Now we know the specialization, compute access previously
12685      deferred.  */
12686   push_access_scope (fndecl);
12687
12688   /* Some typedefs referenced from within the template code need to be access
12689      checked at template instantiation time, i.e now. These types were
12690      added to the template at parsing time. Let's get those and perfom
12691      the acces checks then.  */
12692   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
12693   perform_deferred_access_checks ();
12694   pop_access_scope (fndecl);
12695   pop_deferring_access_checks ();
12696
12697   /* The DECL_TI_TEMPLATE should always be the immediate parent
12698      template, not the most general template.  */
12699   DECL_TI_TEMPLATE (fndecl) = tmpl;
12700
12701   /* If we've just instantiated the main entry point for a function,
12702      instantiate all the alternate entry points as well.  We do this
12703      by cloning the instantiation of the main entry point, not by
12704      instantiating the template clones.  */
12705   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
12706     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
12707
12708   return fndecl;
12709 }
12710
12711 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
12712    NARGS elements of the arguments that are being used when calling
12713    it.  TARGS is a vector into which the deduced template arguments
12714    are placed.
12715
12716    Return zero for success, 2 for an incomplete match that doesn't resolve
12717    all the types, and 1 for complete failure.  An error message will be
12718    printed only for an incomplete match.
12719
12720    If FN is a conversion operator, or we are trying to produce a specific
12721    specialization, RETURN_TYPE is the return type desired.
12722
12723    The EXPLICIT_TARGS are explicit template arguments provided via a
12724    template-id.
12725
12726    The parameter STRICT is one of:
12727
12728    DEDUCE_CALL:
12729      We are deducing arguments for a function call, as in
12730      [temp.deduct.call].
12731
12732    DEDUCE_CONV:
12733      We are deducing arguments for a conversion function, as in
12734      [temp.deduct.conv].
12735
12736    DEDUCE_EXACT:
12737      We are deducing arguments when doing an explicit instantiation
12738      as in [temp.explicit], when determining an explicit specialization
12739      as in [temp.expl.spec], or when taking the address of a function
12740      template, as in [temp.deduct.funcaddr].  */
12741
12742 int
12743 fn_type_unification (tree fn,
12744                      tree explicit_targs,
12745                      tree targs,
12746                      const tree *args,
12747                      unsigned int nargs,
12748                      tree return_type,
12749                      unification_kind_t strict,
12750                      int flags)
12751 {
12752   tree parms;
12753   tree fntype;
12754   int result;
12755   bool incomplete_argument_packs_p = false;
12756
12757   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12758
12759   fntype = TREE_TYPE (fn);
12760   if (explicit_targs)
12761     {
12762       /* [temp.deduct]
12763
12764          The specified template arguments must match the template
12765          parameters in kind (i.e., type, nontype, template), and there
12766          must not be more arguments than there are parameters;
12767          otherwise type deduction fails.
12768
12769          Nontype arguments must match the types of the corresponding
12770          nontype template parameters, or must be convertible to the
12771          types of the corresponding nontype parameters as specified in
12772          _temp.arg.nontype_, otherwise type deduction fails.
12773
12774          All references in the function type of the function template
12775          to the corresponding template parameters are replaced by the
12776          specified template argument values.  If a substitution in a
12777          template parameter or in the function type of the function
12778          template results in an invalid type, type deduction fails.  */
12779       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12780       int i, len = TREE_VEC_LENGTH (tparms);
12781       tree converted_args;
12782       bool incomplete = false;
12783
12784       if (explicit_targs == error_mark_node)
12785         return 1;
12786
12787       converted_args
12788         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12789                                   /*require_all_args=*/false,
12790                                   /*use_default_args=*/false));
12791       if (converted_args == error_mark_node)
12792         return 1;
12793
12794       /* Substitute the explicit args into the function type.  This is
12795          necessary so that, for instance, explicitly declared function
12796          arguments can match null pointed constants.  If we were given
12797          an incomplete set of explicit args, we must not do semantic
12798          processing during substitution as we could create partial
12799          instantiations.  */
12800       for (i = 0; i < len; i++)
12801         {
12802           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12803           bool parameter_pack = false;
12804
12805           /* Dig out the actual parm.  */
12806           if (TREE_CODE (parm) == TYPE_DECL
12807               || TREE_CODE (parm) == TEMPLATE_DECL)
12808             {
12809               parm = TREE_TYPE (parm);
12810               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12811             }
12812           else if (TREE_CODE (parm) == PARM_DECL)
12813             {
12814               parm = DECL_INITIAL (parm);
12815               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12816             }
12817
12818           if (parameter_pack)
12819             {
12820               int level, idx;
12821               tree targ;
12822               template_parm_level_and_index (parm, &level, &idx);
12823
12824               /* Mark the argument pack as "incomplete". We could
12825                  still deduce more arguments during unification.  */
12826               targ = TMPL_ARG (converted_args, level, idx);
12827               if (targ)
12828                 {
12829                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12830                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12831                     = ARGUMENT_PACK_ARGS (targ);
12832                 }
12833
12834               /* We have some incomplete argument packs.  */
12835               incomplete_argument_packs_p = true;
12836             }
12837         }
12838
12839       if (incomplete_argument_packs_p)
12840         /* Any substitution is guaranteed to be incomplete if there
12841            are incomplete argument packs, because we can still deduce
12842            more arguments.  */
12843         incomplete = 1;
12844       else
12845         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12846
12847       processing_template_decl += incomplete;
12848       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12849       processing_template_decl -= incomplete;
12850
12851       if (fntype == error_mark_node)
12852         return 1;
12853
12854       /* Place the explicitly specified arguments in TARGS.  */
12855       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12856         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12857     }
12858
12859   /* Never do unification on the 'this' parameter.  */
12860   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12861
12862   if (return_type)
12863     {
12864       tree *new_args;
12865
12866       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12867       new_args = XALLOCAVEC (tree, nargs + 1);
12868       new_args[0] = return_type;
12869       memcpy (new_args + 1, args, nargs * sizeof (tree));
12870       args = new_args;
12871       ++nargs;
12872     }
12873
12874   /* We allow incomplete unification without an error message here
12875      because the standard doesn't seem to explicitly prohibit it.  Our
12876      callers must be ready to deal with unification failures in any
12877      event.  */
12878   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12879                                   targs, parms, args, nargs, /*subr=*/0,
12880                                   strict, flags);
12881
12882   if (result == 0 && incomplete_argument_packs_p)
12883     {
12884       int i, len = NUM_TMPL_ARGS (targs);
12885
12886       /* Clear the "incomplete" flags on all argument packs.  */
12887       for (i = 0; i < len; i++)
12888         {
12889           tree arg = TREE_VEC_ELT (targs, i);
12890           if (ARGUMENT_PACK_P (arg))
12891             {
12892               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12893               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12894             }
12895         }
12896     }
12897
12898   /* Now that we have bindings for all of the template arguments,
12899      ensure that the arguments deduced for the template template
12900      parameters have compatible template parameter lists.  We cannot
12901      check this property before we have deduced all template
12902      arguments, because the template parameter types of a template
12903      template parameter might depend on prior template parameters
12904      deduced after the template template parameter.  The following
12905      ill-formed example illustrates this issue:
12906
12907        template<typename T, template<T> class C> void f(C<5>, T);
12908
12909        template<int N> struct X {};
12910
12911        void g() {
12912          f(X<5>(), 5l); // error: template argument deduction fails
12913        }
12914
12915      The template parameter list of 'C' depends on the template type
12916      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
12917      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
12918      time that we deduce 'C'.  */
12919   if (result == 0
12920       && !template_template_parm_bindings_ok_p 
12921            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
12922     return 1;
12923
12924   if (result == 0)
12925     /* All is well so far.  Now, check:
12926
12927        [temp.deduct]
12928
12929        When all template arguments have been deduced, all uses of
12930        template parameters in nondeduced contexts are replaced with
12931        the corresponding deduced argument values.  If the
12932        substitution results in an invalid type, as described above,
12933        type deduction fails.  */
12934     {
12935       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
12936       if (substed == error_mark_node)
12937         return 1;
12938
12939       /* If we're looking for an exact match, check that what we got
12940          is indeed an exact match.  It might not be if some template
12941          parameters are used in non-deduced contexts.  */
12942       if (strict == DEDUCE_EXACT)
12943         {
12944           unsigned int i;
12945
12946           tree sarg
12947             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
12948           if (return_type)
12949             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
12950           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
12951             if (!same_type_p (args[i], TREE_VALUE (sarg)))
12952               return 1;
12953         }
12954     }
12955
12956   return result;
12957 }
12958
12959 /* Adjust types before performing type deduction, as described in
12960    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
12961    sections are symmetric.  PARM is the type of a function parameter
12962    or the return type of the conversion function.  ARG is the type of
12963    the argument passed to the call, or the type of the value
12964    initialized with the result of the conversion function.
12965    ARG_EXPR is the original argument expression, which may be null.  */
12966
12967 static int
12968 maybe_adjust_types_for_deduction (unification_kind_t strict,
12969                                   tree* parm,
12970                                   tree* arg,
12971                                   tree arg_expr)
12972 {
12973   int result = 0;
12974
12975   switch (strict)
12976     {
12977     case DEDUCE_CALL:
12978       break;
12979
12980     case DEDUCE_CONV:
12981       {
12982         /* Swap PARM and ARG throughout the remainder of this
12983            function; the handling is precisely symmetric since PARM
12984            will initialize ARG rather than vice versa.  */
12985         tree* temp = parm;
12986         parm = arg;
12987         arg = temp;
12988         break;
12989       }
12990
12991     case DEDUCE_EXACT:
12992       /* Core issue #873: Do the DR606 thing (see below) for these cases,
12993          too, but here handle it by stripping the reference from PARM
12994          rather than by adding it to ARG.  */
12995       if (TREE_CODE (*parm) == REFERENCE_TYPE
12996           && TYPE_REF_IS_RVALUE (*parm)
12997           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
12998           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
12999           && TREE_CODE (*arg) == REFERENCE_TYPE
13000           && !TYPE_REF_IS_RVALUE (*arg))
13001         *parm = TREE_TYPE (*parm);
13002       /* Nothing else to do in this case.  */
13003       return 0;
13004
13005     default:
13006       gcc_unreachable ();
13007     }
13008
13009   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13010     {
13011       /* [temp.deduct.call]
13012
13013          If P is not a reference type:
13014
13015          --If A is an array type, the pointer type produced by the
13016          array-to-pointer standard conversion (_conv.array_) is
13017          used in place of A for type deduction; otherwise,
13018
13019          --If A is a function type, the pointer type produced by
13020          the function-to-pointer standard conversion
13021          (_conv.func_) is used in place of A for type deduction;
13022          otherwise,
13023
13024          --If A is a cv-qualified type, the top level
13025          cv-qualifiers of A's type are ignored for type
13026          deduction.  */
13027       if (TREE_CODE (*arg) == ARRAY_TYPE)
13028         *arg = build_pointer_type (TREE_TYPE (*arg));
13029       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13030         *arg = build_pointer_type (*arg);
13031       else
13032         *arg = TYPE_MAIN_VARIANT (*arg);
13033     }
13034
13035   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13036      of the form T&&, where T is a template parameter, and the argument
13037      is an lvalue, T is deduced as A& */
13038   if (TREE_CODE (*parm) == REFERENCE_TYPE
13039       && TYPE_REF_IS_RVALUE (*parm)
13040       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13041       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13042       && arg_expr && real_lvalue_p (arg_expr))
13043     *arg = build_reference_type (*arg);
13044
13045   /* [temp.deduct.call]
13046
13047      If P is a cv-qualified type, the top level cv-qualifiers
13048      of P's type are ignored for type deduction.  If P is a
13049      reference type, the type referred to by P is used for
13050      type deduction.  */
13051   *parm = TYPE_MAIN_VARIANT (*parm);
13052   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13053     {
13054       *parm = TREE_TYPE (*parm);
13055       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13056     }
13057
13058   /* DR 322. For conversion deduction, remove a reference type on parm
13059      too (which has been swapped into ARG).  */
13060   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13061     *arg = TREE_TYPE (*arg);
13062
13063   return result;
13064 }
13065
13066 /* Most parms like fn_type_unification.
13067
13068    If SUBR is 1, we're being called recursively (to unify the
13069    arguments of a function or method parameter of a function
13070    template). */
13071
13072 static int
13073 type_unification_real (tree tparms,
13074                        tree targs,
13075                        tree xparms,
13076                        const tree *xargs,
13077                        unsigned int xnargs,
13078                        int subr,
13079                        unification_kind_t strict,
13080                        int flags)
13081 {
13082   tree parm, arg, arg_expr;
13083   int i;
13084   int ntparms = TREE_VEC_LENGTH (tparms);
13085   int sub_strict;
13086   int saw_undeduced = 0;
13087   tree parms;
13088   const tree *args;
13089   unsigned int nargs;
13090   unsigned int ia;
13091
13092   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13093   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13094   gcc_assert (ntparms > 0);
13095
13096   switch (strict)
13097     {
13098     case DEDUCE_CALL:
13099       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13100                     | UNIFY_ALLOW_DERIVED);
13101       break;
13102
13103     case DEDUCE_CONV:
13104       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13105       break;
13106
13107     case DEDUCE_EXACT:
13108       sub_strict = UNIFY_ALLOW_NONE;
13109       break;
13110
13111     default:
13112       gcc_unreachable ();
13113     }
13114
13115  again:
13116   parms = xparms;
13117   args = xargs;
13118   nargs = xnargs;
13119
13120   ia = 0;
13121   while (parms && parms != void_list_node
13122          && ia < nargs)
13123     {
13124       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13125         break;
13126
13127       parm = TREE_VALUE (parms);
13128       parms = TREE_CHAIN (parms);
13129       arg = args[ia];
13130       ++ia;
13131       arg_expr = NULL;
13132
13133       if (arg == error_mark_node)
13134         return 1;
13135       if (arg == unknown_type_node)
13136         /* We can't deduce anything from this, but we might get all the
13137            template args from other function args.  */
13138         continue;
13139
13140       /* Conversions will be performed on a function argument that
13141          corresponds with a function parameter that contains only
13142          non-deducible template parameters and explicitly specified
13143          template parameters.  */
13144       if (!uses_template_parms (parm))
13145         {
13146           tree type;
13147
13148           if (!TYPE_P (arg))
13149             type = TREE_TYPE (arg);
13150           else
13151             type = arg;
13152
13153           if (same_type_p (parm, type))
13154             continue;
13155           if (strict != DEDUCE_EXACT
13156               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13157                                   flags))
13158             continue;
13159
13160           return 1;
13161         }
13162
13163       if (!TYPE_P (arg))
13164         {
13165           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13166           if (type_unknown_p (arg))
13167             {
13168               /* [temp.deduct.type] 
13169
13170                  A template-argument can be deduced from a pointer to
13171                  function or pointer to member function argument if
13172                  the set of overloaded functions does not contain
13173                  function templates and at most one of a set of
13174                  overloaded functions provides a unique match.  */
13175               if (resolve_overloaded_unification
13176                   (tparms, targs, parm, arg, strict, sub_strict))
13177                 continue;
13178
13179               return 1;
13180             }
13181           arg_expr = arg;
13182           arg = unlowered_expr_type (arg);
13183           if (arg == error_mark_node)
13184             return 1;
13185         }
13186
13187       {
13188         int arg_strict = sub_strict;
13189
13190         if (!subr)
13191           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13192                                                           arg_expr);
13193
13194         if (arg == init_list_type_node && arg_expr)
13195           arg = arg_expr;
13196         if (unify (tparms, targs, parm, arg, arg_strict))
13197           return 1;
13198       }
13199     }
13200
13201
13202   if (parms 
13203       && parms != void_list_node
13204       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13205     {
13206       /* Unify the remaining arguments with the pack expansion type.  */
13207       tree argvec;
13208       tree parmvec = make_tree_vec (1);
13209
13210       /* Allocate a TREE_VEC and copy in all of the arguments */ 
13211       argvec = make_tree_vec (nargs - ia);
13212       for (i = 0; ia < nargs; ++ia, ++i)
13213         TREE_VEC_ELT (argvec, i) = args[ia];
13214
13215       /* Copy the parameter into parmvec.  */
13216       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13217       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13218                                 /*call_args_p=*/true, /*subr=*/subr))
13219         return 1;
13220
13221       /* Advance to the end of the list of parameters.  */
13222       parms = TREE_CHAIN (parms);
13223     }
13224
13225   /* Fail if we've reached the end of the parm list, and more args
13226      are present, and the parm list isn't variadic.  */
13227   if (ia < nargs && parms == void_list_node)
13228     return 1;
13229   /* Fail if parms are left and they don't have default values.  */
13230   if (parms && parms != void_list_node
13231       && TREE_PURPOSE (parms) == NULL_TREE)
13232     return 1;
13233
13234   if (!subr)
13235     for (i = 0; i < ntparms; i++)
13236       if (!TREE_VEC_ELT (targs, i))
13237         {
13238           tree tparm;
13239
13240           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13241             continue;
13242
13243           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13244
13245           /* If this is an undeduced nontype parameter that depends on
13246              a type parameter, try another pass; its type may have been
13247              deduced from a later argument than the one from which
13248              this parameter can be deduced.  */
13249           if (TREE_CODE (tparm) == PARM_DECL
13250               && uses_template_parms (TREE_TYPE (tparm))
13251               && !saw_undeduced++)
13252             goto again;
13253
13254           /* Core issue #226 (C++0x) [temp.deduct]:
13255
13256                If a template argument has not been deduced, its
13257                default template argument, if any, is used. 
13258
13259              When we are in C++98 mode, TREE_PURPOSE will either
13260              be NULL_TREE or ERROR_MARK_NODE, so we do not need
13261              to explicitly check cxx_dialect here.  */
13262           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13263             {
13264               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13265               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13266               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13267               arg = convert_template_argument (parm, arg, targs, tf_none,
13268                                                i, NULL_TREE);
13269               if (arg == error_mark_node)
13270                 return 1;
13271               else
13272                 {
13273                   TREE_VEC_ELT (targs, i) = arg;
13274                   continue;
13275                 }
13276             }
13277
13278           /* If the type parameter is a parameter pack, then it will
13279              be deduced to an empty parameter pack.  */
13280           if (template_parameter_pack_p (tparm))
13281             {
13282               tree arg;
13283
13284               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13285                 {
13286                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13287                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13288                   TREE_CONSTANT (arg) = 1;
13289                 }
13290               else
13291                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13292
13293               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13294
13295               TREE_VEC_ELT (targs, i) = arg;
13296               continue;
13297             }
13298
13299           return 2;
13300         }
13301
13302   return 0;
13303 }
13304
13305 /* Subroutine of type_unification_real.  Args are like the variables
13306    at the call site.  ARG is an overloaded function (or template-id);
13307    we try deducing template args from each of the overloads, and if
13308    only one succeeds, we go with that.  Modifies TARGS and returns
13309    true on success.  */
13310
13311 static bool
13312 resolve_overloaded_unification (tree tparms,
13313                                 tree targs,
13314                                 tree parm,
13315                                 tree arg,
13316                                 unification_kind_t strict,
13317                                 int sub_strict)
13318 {
13319   tree tempargs = copy_node (targs);
13320   int good = 0;
13321   tree goodfn = NULL_TREE;
13322   bool addr_p;
13323
13324   if (TREE_CODE (arg) == ADDR_EXPR)
13325     {
13326       arg = TREE_OPERAND (arg, 0);
13327       addr_p = true;
13328     }
13329   else
13330     addr_p = false;
13331
13332   if (TREE_CODE (arg) == COMPONENT_REF)
13333     /* Handle `&x' where `x' is some static or non-static member
13334        function name.  */
13335     arg = TREE_OPERAND (arg, 1);
13336
13337   if (TREE_CODE (arg) == OFFSET_REF)
13338     arg = TREE_OPERAND (arg, 1);
13339
13340   /* Strip baselink information.  */
13341   if (BASELINK_P (arg))
13342     arg = BASELINK_FUNCTIONS (arg);
13343
13344   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13345     {
13346       /* If we got some explicit template args, we need to plug them into
13347          the affected templates before we try to unify, in case the
13348          explicit args will completely resolve the templates in question.  */
13349
13350       tree expl_subargs = TREE_OPERAND (arg, 1);
13351       arg = TREE_OPERAND (arg, 0);
13352
13353       for (; arg; arg = OVL_NEXT (arg))
13354         {
13355           tree fn = OVL_CURRENT (arg);
13356           tree subargs, elem;
13357
13358           if (TREE_CODE (fn) != TEMPLATE_DECL)
13359             continue;
13360
13361           ++processing_template_decl;
13362           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13363                                   expl_subargs, /*check_ret=*/false);
13364           if (subargs)
13365             {
13366               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13367               if (try_one_overload (tparms, targs, tempargs, parm,
13368                                     elem, strict, sub_strict, addr_p)
13369                   && (!goodfn || !decls_match (goodfn, elem)))
13370                 {
13371                   goodfn = elem;
13372                   ++good;
13373                 }
13374             }
13375           --processing_template_decl;
13376         }
13377     }
13378   else if (TREE_CODE (arg) != OVERLOAD
13379            && TREE_CODE (arg) != FUNCTION_DECL)
13380     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13381        -- but the deduction does not succeed because the expression is
13382        not just the function on its own.  */
13383     return false;
13384   else
13385     for (; arg; arg = OVL_NEXT (arg))
13386       if (try_one_overload (tparms, targs, tempargs, parm,
13387                             TREE_TYPE (OVL_CURRENT (arg)),
13388                             strict, sub_strict, addr_p)
13389           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13390         {
13391           goodfn = OVL_CURRENT (arg);
13392           ++good;
13393         }
13394
13395   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13396      to function or pointer to member function argument if the set of
13397      overloaded functions does not contain function templates and at most
13398      one of a set of overloaded functions provides a unique match.
13399
13400      So if we found multiple possibilities, we return success but don't
13401      deduce anything.  */
13402
13403   if (good == 1)
13404     {
13405       int i = TREE_VEC_LENGTH (targs);
13406       for (; i--; )
13407         if (TREE_VEC_ELT (tempargs, i))
13408           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13409     }
13410   if (good)
13411     return true;
13412
13413   return false;
13414 }
13415
13416 /* Core DR 115: In contexts where deduction is done and fails, or in
13417    contexts where deduction is not done, if a template argument list is
13418    specified and it, along with any default template arguments, identifies
13419    a single function template specialization, then the template-id is an
13420    lvalue for the function template specialization.  */
13421
13422 tree
13423 resolve_nondeduced_context (tree orig_expr)
13424 {
13425   tree expr, offset, baselink;
13426   bool addr;
13427
13428   if (!type_unknown_p (orig_expr))
13429     return orig_expr;
13430
13431   expr = orig_expr;
13432   addr = false;
13433   offset = NULL_TREE;
13434   baselink = NULL_TREE;
13435
13436   if (TREE_CODE (expr) == ADDR_EXPR)
13437     {
13438       expr = TREE_OPERAND (expr, 0);
13439       addr = true;
13440     }
13441   if (TREE_CODE (expr) == OFFSET_REF)
13442     {
13443       offset = expr;
13444       expr = TREE_OPERAND (expr, 1);
13445     }
13446   if (TREE_CODE (expr) == BASELINK)
13447     {
13448       baselink = expr;
13449       expr = BASELINK_FUNCTIONS (expr);
13450     }
13451
13452   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13453     {
13454       int good = 0;
13455       tree goodfn = NULL_TREE;
13456
13457       /* If we got some explicit template args, we need to plug them into
13458          the affected templates before we try to unify, in case the
13459          explicit args will completely resolve the templates in question.  */
13460
13461       tree expl_subargs = TREE_OPERAND (expr, 1);
13462       tree arg = TREE_OPERAND (expr, 0);
13463       tree badfn = NULL_TREE;
13464       tree badargs = NULL_TREE;
13465
13466       for (; arg; arg = OVL_NEXT (arg))
13467         {
13468           tree fn = OVL_CURRENT (arg);
13469           tree subargs, elem;
13470
13471           if (TREE_CODE (fn) != TEMPLATE_DECL)
13472             continue;
13473
13474           ++processing_template_decl;
13475           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13476                                   expl_subargs, /*check_ret=*/false);
13477           if (subargs && !any_dependent_template_arguments_p (subargs))
13478             {
13479               elem = instantiate_template (fn, subargs, tf_none);
13480               if (elem == error_mark_node)
13481                 {
13482                   badfn = fn;
13483                   badargs = subargs;
13484                 }
13485               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13486                 {
13487                   goodfn = elem;
13488                   ++good;
13489                 }
13490             }
13491           --processing_template_decl;
13492         }
13493       if (good == 1)
13494         {
13495           expr = goodfn;
13496           if (baselink)
13497             expr = build_baselink (BASELINK_BINFO (baselink),
13498                                    BASELINK_ACCESS_BINFO (baselink),
13499                                    expr, BASELINK_OPTYPE (baselink));
13500           if (offset)
13501             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13502                            TREE_OPERAND (offset, 0), expr);
13503           if (addr)
13504             expr = build_address (expr);
13505           return expr;
13506         }
13507       else if (good == 0 && badargs)
13508         /* There were no good options and at least one bad one, so let the
13509            user know what the problem is.  */
13510         instantiate_template (badfn, badargs, tf_warning_or_error);
13511     }
13512   return orig_expr;
13513 }
13514
13515 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13516    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13517    different overloads deduce different arguments for a given parm.
13518    ADDR_P is true if the expression for which deduction is being
13519    performed was of the form "& fn" rather than simply "fn".
13520
13521    Returns 1 on success.  */
13522
13523 static int
13524 try_one_overload (tree tparms,
13525                   tree orig_targs,
13526                   tree targs,
13527                   tree parm,
13528                   tree arg,
13529                   unification_kind_t strict,
13530                   int sub_strict,
13531                   bool addr_p)
13532 {
13533   int nargs;
13534   tree tempargs;
13535   int i;
13536
13537   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13538      to function or pointer to member function argument if the set of
13539      overloaded functions does not contain function templates and at most
13540      one of a set of overloaded functions provides a unique match.
13541
13542      So if this is a template, just return success.  */
13543
13544   if (uses_template_parms (arg))
13545     return 1;
13546
13547   if (TREE_CODE (arg) == METHOD_TYPE)
13548     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13549   else if (addr_p)
13550     arg = build_pointer_type (arg);
13551
13552   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13553
13554   /* We don't copy orig_targs for this because if we have already deduced
13555      some template args from previous args, unify would complain when we
13556      try to deduce a template parameter for the same argument, even though
13557      there isn't really a conflict.  */
13558   nargs = TREE_VEC_LENGTH (targs);
13559   tempargs = make_tree_vec (nargs);
13560
13561   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13562     return 0;
13563
13564   /* First make sure we didn't deduce anything that conflicts with
13565      explicitly specified args.  */
13566   for (i = nargs; i--; )
13567     {
13568       tree elt = TREE_VEC_ELT (tempargs, i);
13569       tree oldelt = TREE_VEC_ELT (orig_targs, i);
13570
13571       if (!elt)
13572         /*NOP*/;
13573       else if (uses_template_parms (elt))
13574         /* Since we're unifying against ourselves, we will fill in
13575            template args used in the function parm list with our own
13576            template parms.  Discard them.  */
13577         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13578       else if (oldelt && !template_args_equal (oldelt, elt))
13579         return 0;
13580     }
13581
13582   for (i = nargs; i--; )
13583     {
13584       tree elt = TREE_VEC_ELT (tempargs, i);
13585
13586       if (elt)
13587         TREE_VEC_ELT (targs, i) = elt;
13588     }
13589
13590   return 1;
13591 }
13592
13593 /* PARM is a template class (perhaps with unbound template
13594    parameters).  ARG is a fully instantiated type.  If ARG can be
13595    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
13596    TARGS are as for unify.  */
13597
13598 static tree
13599 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
13600 {
13601   tree copy_of_targs;
13602
13603   if (!CLASSTYPE_TEMPLATE_INFO (arg)
13604       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
13605           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
13606     return NULL_TREE;
13607
13608   /* We need to make a new template argument vector for the call to
13609      unify.  If we used TARGS, we'd clutter it up with the result of
13610      the attempted unification, even if this class didn't work out.
13611      We also don't want to commit ourselves to all the unifications
13612      we've already done, since unification is supposed to be done on
13613      an argument-by-argument basis.  In other words, consider the
13614      following pathological case:
13615
13616        template <int I, int J, int K>
13617        struct S {};
13618
13619        template <int I, int J>
13620        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
13621
13622        template <int I, int J, int K>
13623        void f(S<I, J, K>, S<I, I, I>);
13624
13625        void g() {
13626          S<0, 0, 0> s0;
13627          S<0, 1, 2> s2;
13628
13629          f(s0, s2);
13630        }
13631
13632      Now, by the time we consider the unification involving `s2', we
13633      already know that we must have `f<0, 0, 0>'.  But, even though
13634      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
13635      because there are two ways to unify base classes of S<0, 1, 2>
13636      with S<I, I, I>.  If we kept the already deduced knowledge, we
13637      would reject the possibility I=1.  */
13638   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
13639
13640   /* If unification failed, we're done.  */
13641   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
13642              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
13643     return NULL_TREE;
13644
13645   return arg;
13646 }
13647
13648 /* Given a template type PARM and a class type ARG, find the unique
13649    base type in ARG that is an instance of PARM.  We do not examine
13650    ARG itself; only its base-classes.  If there is not exactly one
13651    appropriate base class, return NULL_TREE.  PARM may be the type of
13652    a partial specialization, as well as a plain template type.  Used
13653    by unify.  */
13654
13655 static tree
13656 get_template_base (tree tparms, tree targs, tree parm, tree arg)
13657 {
13658   tree rval = NULL_TREE;
13659   tree binfo;
13660
13661   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
13662
13663   binfo = TYPE_BINFO (complete_type (arg));
13664   if (!binfo)
13665     /* The type could not be completed.  */
13666     return NULL_TREE;
13667
13668   /* Walk in inheritance graph order.  The search order is not
13669      important, and this avoids multiple walks of virtual bases.  */
13670   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
13671     {
13672       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
13673
13674       if (r)
13675         {
13676           /* If there is more than one satisfactory baseclass, then:
13677
13678                [temp.deduct.call]
13679
13680               If they yield more than one possible deduced A, the type
13681               deduction fails.
13682
13683              applies.  */
13684           if (rval && !same_type_p (r, rval))
13685             return NULL_TREE;
13686
13687           rval = r;
13688         }
13689     }
13690
13691   return rval;
13692 }
13693
13694 /* Returns the level of DECL, which declares a template parameter.  */
13695
13696 static int
13697 template_decl_level (tree decl)
13698 {
13699   switch (TREE_CODE (decl))
13700     {
13701     case TYPE_DECL:
13702     case TEMPLATE_DECL:
13703       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
13704
13705     case PARM_DECL:
13706       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
13707
13708     default:
13709       gcc_unreachable ();
13710     }
13711   return 0;
13712 }
13713
13714 /* Decide whether ARG can be unified with PARM, considering only the
13715    cv-qualifiers of each type, given STRICT as documented for unify.
13716    Returns nonzero iff the unification is OK on that basis.  */
13717
13718 static int
13719 check_cv_quals_for_unify (int strict, tree arg, tree parm)
13720 {
13721   int arg_quals = cp_type_quals (arg);
13722   int parm_quals = cp_type_quals (parm);
13723
13724   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13725       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13726     {
13727       /*  Although a CVR qualifier is ignored when being applied to a
13728           substituted template parameter ([8.3.2]/1 for example), that
13729           does not apply during deduction [14.8.2.4]/1, (even though
13730           that is not explicitly mentioned, [14.8.2.4]/9 indicates
13731           this).  Except when we're allowing additional CV qualifiers
13732           at the outer level [14.8.2.1]/3,1st bullet.  */
13733       if ((TREE_CODE (arg) == REFERENCE_TYPE
13734            || TREE_CODE (arg) == FUNCTION_TYPE
13735            || TREE_CODE (arg) == METHOD_TYPE)
13736           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
13737         return 0;
13738
13739       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
13740           && (parm_quals & TYPE_QUAL_RESTRICT))
13741         return 0;
13742     }
13743
13744   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13745       && (arg_quals & parm_quals) != parm_quals)
13746     return 0;
13747
13748   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
13749       && (parm_quals & arg_quals) != arg_quals)
13750     return 0;
13751
13752   return 1;
13753 }
13754
13755 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
13756 void 
13757 template_parm_level_and_index (tree parm, int* level, int* index)
13758 {
13759   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13760       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13761       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13762     {
13763       *index = TEMPLATE_TYPE_IDX (parm);
13764       *level = TEMPLATE_TYPE_LEVEL (parm);
13765     }
13766   else
13767     {
13768       *index = TEMPLATE_PARM_IDX (parm);
13769       *level = TEMPLATE_PARM_LEVEL (parm);
13770     }
13771 }
13772
13773 /* Unifies the remaining arguments in PACKED_ARGS with the pack
13774    expansion at the end of PACKED_PARMS. Returns 0 if the type
13775    deduction succeeds, 1 otherwise. STRICT is the same as in
13776    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
13777    call argument list. We'll need to adjust the arguments to make them
13778    types. SUBR tells us if this is from a recursive call to
13779    type_unification_real.  */
13780 int
13781 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
13782                       tree packed_args, int strict, bool call_args_p,
13783                       bool subr)
13784 {
13785   tree parm 
13786     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
13787   tree pattern = PACK_EXPANSION_PATTERN (parm);
13788   tree pack, packs = NULL_TREE;
13789   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
13790   int len = TREE_VEC_LENGTH (packed_args);
13791
13792   /* Determine the parameter packs we will be deducing from the
13793      pattern, and record their current deductions.  */
13794   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
13795        pack; pack = TREE_CHAIN (pack))
13796     {
13797       tree parm_pack = TREE_VALUE (pack);
13798       int idx, level;
13799
13800       /* Determine the index and level of this parameter pack.  */
13801       template_parm_level_and_index (parm_pack, &level, &idx);
13802
13803       /* Keep track of the parameter packs and their corresponding
13804          argument packs.  */
13805       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
13806       TREE_TYPE (packs) = make_tree_vec (len - start);
13807     }
13808   
13809   /* Loop through all of the arguments that have not yet been
13810      unified and unify each with the pattern.  */
13811   for (i = start; i < len; i++)
13812     {
13813       tree parm = pattern;
13814
13815       /* For each parameter pack, clear out the deduced value so that
13816          we can deduce it again.  */
13817       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13818         {
13819           int idx, level;
13820           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13821
13822           TMPL_ARG (targs, level, idx) = NULL_TREE;
13823         }
13824
13825       /* Unify the pattern with the current argument.  */
13826       {
13827         tree arg = TREE_VEC_ELT (packed_args, i);
13828         tree arg_expr = NULL_TREE;
13829         int arg_strict = strict;
13830         bool skip_arg_p = false;
13831
13832         if (call_args_p)
13833           {
13834             int sub_strict;
13835
13836             /* This mirrors what we do in type_unification_real.  */
13837             switch (strict)
13838               {
13839               case DEDUCE_CALL:
13840                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
13841                               | UNIFY_ALLOW_MORE_CV_QUAL
13842                               | UNIFY_ALLOW_DERIVED);
13843                 break;
13844                 
13845               case DEDUCE_CONV:
13846                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13847                 break;
13848                 
13849               case DEDUCE_EXACT:
13850                 sub_strict = UNIFY_ALLOW_NONE;
13851                 break;
13852                 
13853               default:
13854                 gcc_unreachable ();
13855               }
13856
13857             if (!TYPE_P (arg))
13858               {
13859                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13860                 if (type_unknown_p (arg))
13861                   {
13862                     /* [temp.deduct.type] A template-argument can be
13863                        deduced from a pointer to function or pointer
13864                        to member function argument if the set of
13865                        overloaded functions does not contain function
13866                        templates and at most one of a set of
13867                        overloaded functions provides a unique
13868                        match.  */
13869
13870                     if (resolve_overloaded_unification
13871                         (tparms, targs, parm, arg,
13872                          (unification_kind_t) strict,
13873                          sub_strict)
13874                         != 0)
13875                       return 1;
13876                     skip_arg_p = true;
13877                   }
13878
13879                 if (!skip_arg_p)
13880                   {
13881                     arg_expr = arg;
13882                     arg = unlowered_expr_type (arg);
13883                     if (arg == error_mark_node)
13884                       return 1;
13885                   }
13886               }
13887       
13888             arg_strict = sub_strict;
13889
13890             if (!subr)
13891               arg_strict |= 
13892                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
13893                                                   &parm, &arg, arg_expr);
13894           }
13895
13896         if (!skip_arg_p)
13897           {
13898             if (unify (tparms, targs, parm, arg, arg_strict))
13899               return 1;
13900           }
13901       }
13902
13903       /* For each parameter pack, collect the deduced value.  */
13904       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13905         {
13906           int idx, level;
13907           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13908
13909           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
13910             TMPL_ARG (targs, level, idx);
13911         }
13912     }
13913
13914   /* Verify that the results of unification with the parameter packs
13915      produce results consistent with what we've seen before, and make
13916      the deduced argument packs available.  */
13917   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13918     {
13919       tree old_pack = TREE_VALUE (pack);
13920       tree new_args = TREE_TYPE (pack);
13921       int i, len = TREE_VEC_LENGTH (new_args);
13922       bool nondeduced_p = false;
13923
13924       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
13925          actually deduce anything.  */
13926       for (i = 0; i < len && !nondeduced_p; ++i)
13927         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
13928           nondeduced_p = true;
13929       if (nondeduced_p)
13930         continue;
13931
13932       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
13933         {
13934           /* Prepend the explicit arguments onto NEW_ARGS.  */
13935           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13936           tree old_args = new_args;
13937           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
13938           int len = explicit_len + TREE_VEC_LENGTH (old_args);
13939
13940           /* Copy the explicit arguments.  */
13941           new_args = make_tree_vec (len);
13942           for (i = 0; i < explicit_len; i++)
13943             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
13944
13945           /* Copy the deduced arguments.  */
13946           for (; i < len; i++)
13947             TREE_VEC_ELT (new_args, i) =
13948               TREE_VEC_ELT (old_args, i - explicit_len);
13949         }
13950
13951       if (!old_pack)
13952         {
13953           tree result;
13954           int idx, level;
13955           
13956           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13957
13958           /* Build the deduced *_ARGUMENT_PACK.  */
13959           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
13960             {
13961               result = make_node (NONTYPE_ARGUMENT_PACK);
13962               TREE_TYPE (result) = 
13963                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
13964               TREE_CONSTANT (result) = 1;
13965             }
13966           else
13967             result = cxx_make_type (TYPE_ARGUMENT_PACK);
13968
13969           SET_ARGUMENT_PACK_ARGS (result, new_args);
13970
13971           /* Note the deduced argument packs for this parameter
13972              pack.  */
13973           TMPL_ARG (targs, level, idx) = result;
13974         }
13975       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
13976                && (ARGUMENT_PACK_ARGS (old_pack) 
13977                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
13978         {
13979           /* We only had the explicitly-provided arguments before, but
13980              now we have a complete set of arguments.  */
13981           int idx, level;
13982           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13983           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13984
13985           /* Keep the original deduced argument pack.  */
13986           TMPL_ARG (targs, level, idx) = old_pack;
13987
13988           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
13989           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
13990           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
13991         }
13992       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
13993                                     new_args))
13994         /* Inconsistent unification of this parameter pack.  */
13995         return 1;
13996       else
13997         {
13998           int idx, level;
13999           
14000           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14001
14002           /* Keep the original deduced argument pack.  */
14003           TMPL_ARG (targs, level, idx) = old_pack;
14004         }
14005     }
14006
14007   return 0;
14008 }
14009
14010 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14011    set of template parameters to a template.  TARGS is the bindings
14012    for those template parameters, as determined thus far; TARGS may
14013    include template arguments for outer levels of template parameters
14014    as well.  PARM is a parameter to a template function, or a
14015    subcomponent of that parameter; ARG is the corresponding argument.
14016    This function attempts to match PARM with ARG in a manner
14017    consistent with the existing assignments in TARGS.  If more values
14018    are deduced, then TARGS is updated.
14019
14020    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14021    parameter STRICT is a bitwise or of the following flags:
14022
14023      UNIFY_ALLOW_NONE:
14024        Require an exact match between PARM and ARG.
14025      UNIFY_ALLOW_MORE_CV_QUAL:
14026        Allow the deduced ARG to be more cv-qualified (by qualification
14027        conversion) than ARG.
14028      UNIFY_ALLOW_LESS_CV_QUAL:
14029        Allow the deduced ARG to be less cv-qualified than ARG.
14030      UNIFY_ALLOW_DERIVED:
14031        Allow the deduced ARG to be a template base class of ARG,
14032        or a pointer to a template base class of the type pointed to by
14033        ARG.
14034      UNIFY_ALLOW_INTEGER:
14035        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14036        case for more information.
14037      UNIFY_ALLOW_OUTER_LEVEL:
14038        This is the outermost level of a deduction. Used to determine validity
14039        of qualification conversions. A valid qualification conversion must
14040        have const qualified pointers leading up to the inner type which
14041        requires additional CV quals, except at the outer level, where const
14042        is not required [conv.qual]. It would be normal to set this flag in
14043        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14044      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14045        This is the outermost level of a deduction, and PARM can be more CV
14046        qualified at this point.
14047      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14048        This is the outermost level of a deduction, and PARM can be less CV
14049        qualified at this point.  */
14050
14051 static int
14052 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14053 {
14054   int idx;
14055   tree targ;
14056   tree tparm;
14057   int strict_in = strict;
14058
14059   /* I don't think this will do the right thing with respect to types.
14060      But the only case I've seen it in so far has been array bounds, where
14061      signedness is the only information lost, and I think that will be
14062      okay.  */
14063   while (TREE_CODE (parm) == NOP_EXPR)
14064     parm = TREE_OPERAND (parm, 0);
14065
14066   if (arg == error_mark_node)
14067     return 1;
14068   if (arg == unknown_type_node
14069       || arg == init_list_type_node)
14070     /* We can't deduce anything from this, but we might get all the
14071        template args from other function args.  */
14072     return 0;
14073
14074   /* If PARM uses template parameters, then we can't bail out here,
14075      even if ARG == PARM, since we won't record unifications for the
14076      template parameters.  We might need them if we're trying to
14077      figure out which of two things is more specialized.  */
14078   if (arg == parm && !uses_template_parms (parm))
14079     return 0;
14080
14081   /* Handle init lists early, so the rest of the function can assume
14082      we're dealing with a type. */
14083   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14084     {
14085       tree elt, elttype;
14086       unsigned i;
14087       tree orig_parm = parm;
14088
14089       /* Replace T with std::initializer_list<T> for deduction.  */
14090       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14091           && flag_deduce_init_list)
14092         parm = listify (parm);
14093
14094       if (!is_std_init_list (parm))
14095         /* We can only deduce from an initializer list argument if the
14096            parameter is std::initializer_list; otherwise this is a
14097            non-deduced context. */
14098         return 0;
14099
14100       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14101
14102       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14103         {
14104           int elt_strict = strict;
14105           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14106             {
14107               tree type = TREE_TYPE (elt);
14108               /* It should only be possible to get here for a call.  */
14109               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14110               elt_strict |= maybe_adjust_types_for_deduction
14111                 (DEDUCE_CALL, &elttype, &type, elt);
14112               elt = type;
14113             }
14114
14115           if (unify (tparms, targs, elttype, elt, elt_strict))
14116             return 1;
14117         }
14118
14119       /* If the std::initializer_list<T> deduction worked, replace the
14120          deduced A with std::initializer_list<A>.  */
14121       if (orig_parm != parm)
14122         {
14123           idx = TEMPLATE_TYPE_IDX (orig_parm);
14124           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14125           targ = listify (targ);
14126           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14127         }
14128       return 0;
14129     }
14130
14131   /* Immediately reject some pairs that won't unify because of
14132      cv-qualification mismatches.  */
14133   if (TREE_CODE (arg) == TREE_CODE (parm)
14134       && TYPE_P (arg)
14135       /* It is the elements of the array which hold the cv quals of an array
14136          type, and the elements might be template type parms. We'll check
14137          when we recurse.  */
14138       && TREE_CODE (arg) != ARRAY_TYPE
14139       /* We check the cv-qualifiers when unifying with template type
14140          parameters below.  We want to allow ARG `const T' to unify with
14141          PARM `T' for example, when computing which of two templates
14142          is more specialized, for example.  */
14143       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14144       && !check_cv_quals_for_unify (strict_in, arg, parm))
14145     return 1;
14146
14147   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14148       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14149     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14150   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14151   strict &= ~UNIFY_ALLOW_DERIVED;
14152   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14153   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14154
14155   switch (TREE_CODE (parm))
14156     {
14157     case TYPENAME_TYPE:
14158     case SCOPE_REF:
14159     case UNBOUND_CLASS_TEMPLATE:
14160       /* In a type which contains a nested-name-specifier, template
14161          argument values cannot be deduced for template parameters used
14162          within the nested-name-specifier.  */
14163       return 0;
14164
14165     case TEMPLATE_TYPE_PARM:
14166     case TEMPLATE_TEMPLATE_PARM:
14167     case BOUND_TEMPLATE_TEMPLATE_PARM:
14168       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14169       if (tparm == error_mark_node)
14170         return 1;
14171
14172       if (TEMPLATE_TYPE_LEVEL (parm)
14173           != template_decl_level (tparm))
14174         /* The PARM is not one we're trying to unify.  Just check
14175            to see if it matches ARG.  */
14176         return (TREE_CODE (arg) == TREE_CODE (parm)
14177                 && same_type_p (parm, arg)) ? 0 : 1;
14178       idx = TEMPLATE_TYPE_IDX (parm);
14179       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14180       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14181
14182       /* Check for mixed types and values.  */
14183       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14184            && TREE_CODE (tparm) != TYPE_DECL)
14185           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14186               && TREE_CODE (tparm) != TEMPLATE_DECL))
14187         return 1;
14188
14189       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14190         {
14191           /* ARG must be constructed from a template class or a template
14192              template parameter.  */
14193           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14194               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14195             return 1;
14196
14197           {
14198             tree parmvec = TYPE_TI_ARGS (parm);
14199             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14200             tree parm_parms 
14201               = DECL_INNERMOST_TEMPLATE_PARMS
14202                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14203             int i, len;
14204             int parm_variadic_p = 0;
14205
14206             /* The resolution to DR150 makes clear that default
14207                arguments for an N-argument may not be used to bind T
14208                to a template template parameter with fewer than N
14209                parameters.  It is not safe to permit the binding of
14210                default arguments as an extension, as that may change
14211                the meaning of a conforming program.  Consider:
14212
14213                   struct Dense { static const unsigned int dim = 1; };
14214
14215                   template <template <typename> class View,
14216                             typename Block>
14217                   void operator+(float, View<Block> const&);
14218
14219                   template <typename Block,
14220                             unsigned int Dim = Block::dim>
14221                   struct Lvalue_proxy { operator float() const; };
14222
14223                   void
14224                   test_1d (void) {
14225                     Lvalue_proxy<Dense> p;
14226                     float b;
14227                     b + p;
14228                   }
14229
14230               Here, if Lvalue_proxy is permitted to bind to View, then
14231               the global operator+ will be used; if they are not, the
14232               Lvalue_proxy will be converted to float.  */
14233             if (coerce_template_parms (parm_parms,
14234                                        argvec,
14235                                        TYPE_TI_TEMPLATE (parm),
14236                                        tf_none,
14237                                        /*require_all_args=*/true,
14238                                        /*use_default_args=*/false)
14239                 == error_mark_node)
14240               return 1;
14241
14242             /* Deduce arguments T, i from TT<T> or TT<i>.
14243                We check each element of PARMVEC and ARGVEC individually
14244                rather than the whole TREE_VEC since they can have
14245                different number of elements.  */
14246
14247             parmvec = expand_template_argument_pack (parmvec);
14248             argvec = expand_template_argument_pack (argvec);
14249
14250             len = TREE_VEC_LENGTH (parmvec);
14251
14252             /* Check if the parameters end in a pack, making them
14253                variadic.  */
14254             if (len > 0
14255                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14256               parm_variadic_p = 1;
14257             
14258             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14259               return 1;
14260
14261              for (i = 0; i < len - parm_variadic_p; ++i)
14262               {
14263                 if (unify (tparms, targs,
14264                            TREE_VEC_ELT (parmvec, i),
14265                            TREE_VEC_ELT (argvec, i),
14266                            UNIFY_ALLOW_NONE))
14267                   return 1;
14268               }
14269
14270             if (parm_variadic_p
14271                 && unify_pack_expansion (tparms, targs,
14272                                          parmvec, argvec,
14273                                          UNIFY_ALLOW_NONE,
14274                                          /*call_args_p=*/false,
14275                                          /*subr=*/false))
14276               return 1;
14277           }
14278           arg = TYPE_TI_TEMPLATE (arg);
14279
14280           /* Fall through to deduce template name.  */
14281         }
14282
14283       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14284           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14285         {
14286           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14287
14288           /* Simple cases: Value already set, does match or doesn't.  */
14289           if (targ != NULL_TREE && template_args_equal (targ, arg))
14290             return 0;
14291           else if (targ)
14292             return 1;
14293         }
14294       else
14295         {
14296           /* If PARM is `const T' and ARG is only `int', we don't have
14297              a match unless we are allowing additional qualification.
14298              If ARG is `const int' and PARM is just `T' that's OK;
14299              that binds `const int' to `T'.  */
14300           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14301                                          arg, parm))
14302             return 1;
14303
14304           /* Consider the case where ARG is `const volatile int' and
14305              PARM is `const T'.  Then, T should be `volatile int'.  */
14306           arg = cp_build_qualified_type_real
14307             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14308           if (arg == error_mark_node)
14309             return 1;
14310
14311           /* Simple cases: Value already set, does match or doesn't.  */
14312           if (targ != NULL_TREE && same_type_p (targ, arg))
14313             return 0;
14314           else if (targ)
14315             return 1;
14316
14317           /* Make sure that ARG is not a variable-sized array.  (Note
14318              that were talking about variable-sized arrays (like
14319              `int[n]'), rather than arrays of unknown size (like
14320              `int[]').)  We'll get very confused by such a type since
14321              the bound of the array will not be computable in an
14322              instantiation.  Besides, such types are not allowed in
14323              ISO C++, so we can do as we please here.  */
14324           if (variably_modified_type_p (arg, NULL_TREE))
14325             return 1;
14326
14327           /* Strip typedefs as in convert_template_argument.  */
14328           arg = strip_typedefs (arg);
14329         }
14330
14331       /* If ARG is a parameter pack or an expansion, we cannot unify
14332          against it unless PARM is also a parameter pack.  */
14333       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14334           && !template_parameter_pack_p (parm))
14335         return 1;
14336
14337       /* If the argument deduction results is a METHOD_TYPE,
14338          then there is a problem.
14339          METHOD_TYPE doesn't map to any real C++ type the result of
14340          the deduction can not be of that type.  */
14341       if (TREE_CODE (arg) == METHOD_TYPE)
14342         return 1;
14343
14344       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14345       return 0;
14346
14347     case TEMPLATE_PARM_INDEX:
14348       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14349       if (tparm == error_mark_node)
14350         return 1;
14351
14352       if (TEMPLATE_PARM_LEVEL (parm)
14353           != template_decl_level (tparm))
14354         /* The PARM is not one we're trying to unify.  Just check
14355            to see if it matches ARG.  */
14356         return !(TREE_CODE (arg) == TREE_CODE (parm)
14357                  && cp_tree_equal (parm, arg));
14358
14359       idx = TEMPLATE_PARM_IDX (parm);
14360       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14361
14362       if (targ)
14363         return !cp_tree_equal (targ, arg);
14364
14365       /* [temp.deduct.type] If, in the declaration of a function template
14366          with a non-type template-parameter, the non-type
14367          template-parameter is used in an expression in the function
14368          parameter-list and, if the corresponding template-argument is
14369          deduced, the template-argument type shall match the type of the
14370          template-parameter exactly, except that a template-argument
14371          deduced from an array bound may be of any integral type.
14372          The non-type parameter might use already deduced type parameters.  */
14373       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14374       if (!TREE_TYPE (arg))
14375         /* Template-parameter dependent expression.  Just accept it for now.
14376            It will later be processed in convert_template_argument.  */
14377         ;
14378       else if (same_type_p (TREE_TYPE (arg), tparm))
14379         /* OK */;
14380       else if ((strict & UNIFY_ALLOW_INTEGER)
14381                && (TREE_CODE (tparm) == INTEGER_TYPE
14382                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
14383         /* Convert the ARG to the type of PARM; the deduced non-type
14384            template argument must exactly match the types of the
14385            corresponding parameter.  */
14386         arg = fold (build_nop (tparm, arg));
14387       else if (uses_template_parms (tparm))
14388         /* We haven't deduced the type of this parameter yet.  Try again
14389            later.  */
14390         return 0;
14391       else
14392         return 1;
14393
14394       /* If ARG is a parameter pack or an expansion, we cannot unify
14395          against it unless PARM is also a parameter pack.  */
14396       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14397           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14398         return 1;
14399
14400       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14401       return 0;
14402
14403     case PTRMEM_CST:
14404      {
14405         /* A pointer-to-member constant can be unified only with
14406          another constant.  */
14407       if (TREE_CODE (arg) != PTRMEM_CST)
14408         return 1;
14409
14410       /* Just unify the class member. It would be useless (and possibly
14411          wrong, depending on the strict flags) to unify also
14412          PTRMEM_CST_CLASS, because we want to be sure that both parm and
14413          arg refer to the same variable, even if through different
14414          classes. For instance:
14415
14416          struct A { int x; };
14417          struct B : A { };
14418
14419          Unification of &A::x and &B::x must succeed.  */
14420       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14421                     PTRMEM_CST_MEMBER (arg), strict);
14422      }
14423
14424     case POINTER_TYPE:
14425       {
14426         if (TREE_CODE (arg) != POINTER_TYPE)
14427           return 1;
14428
14429         /* [temp.deduct.call]
14430
14431            A can be another pointer or pointer to member type that can
14432            be converted to the deduced A via a qualification
14433            conversion (_conv.qual_).
14434
14435            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14436            This will allow for additional cv-qualification of the
14437            pointed-to types if appropriate.  */
14438
14439         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14440           /* The derived-to-base conversion only persists through one
14441              level of pointers.  */
14442           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14443
14444         return unify (tparms, targs, TREE_TYPE (parm),
14445                       TREE_TYPE (arg), strict);
14446       }
14447
14448     case REFERENCE_TYPE:
14449       if (TREE_CODE (arg) != REFERENCE_TYPE)
14450         return 1;
14451       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14452                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14453
14454     case ARRAY_TYPE:
14455       if (TREE_CODE (arg) != ARRAY_TYPE)
14456         return 1;
14457       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14458           != (TYPE_DOMAIN (arg) == NULL_TREE))
14459         return 1;
14460       if (TYPE_DOMAIN (parm) != NULL_TREE)
14461         {
14462           tree parm_max;
14463           tree arg_max;
14464           bool parm_cst;
14465           bool arg_cst;
14466
14467           /* Our representation of array types uses "N - 1" as the
14468              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14469              not an integer constant.  We cannot unify arbitrarily
14470              complex expressions, so we eliminate the MINUS_EXPRs
14471              here.  */
14472           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14473           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14474           if (!parm_cst)
14475             {
14476               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14477               parm_max = TREE_OPERAND (parm_max, 0);
14478             }
14479           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14480           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14481           if (!arg_cst)
14482             {
14483               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14484                  trying to unify the type of a variable with the type
14485                  of a template parameter.  For example:
14486
14487                    template <unsigned int N>
14488                    void f (char (&) [N]);
14489                    int g(); 
14490                    void h(int i) {
14491                      char a[g(i)];
14492                      f(a); 
14493                    }
14494
14495                 Here, the type of the ARG will be "int [g(i)]", and
14496                 may be a SAVE_EXPR, etc.  */
14497               if (TREE_CODE (arg_max) != MINUS_EXPR)
14498                 return 1;
14499               arg_max = TREE_OPERAND (arg_max, 0);
14500             }
14501
14502           /* If only one of the bounds used a MINUS_EXPR, compensate
14503              by adding one to the other bound.  */
14504           if (parm_cst && !arg_cst)
14505             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14506                                     integer_type_node,
14507                                     parm_max,
14508                                     integer_one_node);
14509           else if (arg_cst && !parm_cst)
14510             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14511                                    integer_type_node,
14512                                    arg_max,
14513                                    integer_one_node);
14514
14515           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14516             return 1;
14517         }
14518       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14519                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14520
14521     case REAL_TYPE:
14522     case COMPLEX_TYPE:
14523     case VECTOR_TYPE:
14524     case INTEGER_TYPE:
14525     case BOOLEAN_TYPE:
14526     case ENUMERAL_TYPE:
14527     case VOID_TYPE:
14528       if (TREE_CODE (arg) != TREE_CODE (parm))
14529         return 1;
14530
14531       /* We have already checked cv-qualification at the top of the
14532          function.  */
14533       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14534         return 1;
14535
14536       /* As far as unification is concerned, this wins.  Later checks
14537          will invalidate it if necessary.  */
14538       return 0;
14539
14540       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14541       /* Type INTEGER_CST can come from ordinary constant template args.  */
14542     case INTEGER_CST:
14543       while (TREE_CODE (arg) == NOP_EXPR)
14544         arg = TREE_OPERAND (arg, 0);
14545
14546       if (TREE_CODE (arg) != INTEGER_CST)
14547         return 1;
14548       return !tree_int_cst_equal (parm, arg);
14549
14550     case TREE_VEC:
14551       {
14552         int i;
14553         if (TREE_CODE (arg) != TREE_VEC)
14554           return 1;
14555         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14556           return 1;
14557         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14558           if (unify (tparms, targs,
14559                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14560                      UNIFY_ALLOW_NONE))
14561             return 1;
14562         return 0;
14563       }
14564
14565     case RECORD_TYPE:
14566     case UNION_TYPE:
14567       if (TREE_CODE (arg) != TREE_CODE (parm))
14568         return 1;
14569
14570       if (TYPE_PTRMEMFUNC_P (parm))
14571         {
14572           if (!TYPE_PTRMEMFUNC_P (arg))
14573             return 1;
14574
14575           return unify (tparms, targs,
14576                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
14577                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
14578                         strict);
14579         }
14580
14581       if (CLASSTYPE_TEMPLATE_INFO (parm))
14582         {
14583           tree t = NULL_TREE;
14584
14585           if (strict_in & UNIFY_ALLOW_DERIVED)
14586             {
14587               /* First, we try to unify the PARM and ARG directly.  */
14588               t = try_class_unification (tparms, targs,
14589                                          parm, arg);
14590
14591               if (!t)
14592                 {
14593                   /* Fallback to the special case allowed in
14594                      [temp.deduct.call]:
14595
14596                        If P is a class, and P has the form
14597                        template-id, then A can be a derived class of
14598                        the deduced A.  Likewise, if P is a pointer to
14599                        a class of the form template-id, A can be a
14600                        pointer to a derived class pointed to by the
14601                        deduced A.  */
14602                   t = get_template_base (tparms, targs, parm, arg);
14603
14604                   if (!t)
14605                     return 1;
14606                 }
14607             }
14608           else if (CLASSTYPE_TEMPLATE_INFO (arg)
14609                    && (CLASSTYPE_TI_TEMPLATE (parm)
14610                        == CLASSTYPE_TI_TEMPLATE (arg)))
14611             /* Perhaps PARM is something like S<U> and ARG is S<int>.
14612                Then, we should unify `int' and `U'.  */
14613             t = arg;
14614           else
14615             /* There's no chance of unification succeeding.  */
14616             return 1;
14617
14618           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
14619                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
14620         }
14621       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
14622         return 1;
14623       return 0;
14624
14625     case METHOD_TYPE:
14626     case FUNCTION_TYPE:
14627       {
14628         unsigned int nargs;
14629         tree *args;
14630         tree a;
14631         unsigned int i;
14632
14633         if (TREE_CODE (arg) != TREE_CODE (parm))
14634           return 1;
14635
14636         /* CV qualifications for methods can never be deduced, they must
14637            match exactly.  We need to check them explicitly here,
14638            because type_unification_real treats them as any other
14639            cv-qualified parameter.  */
14640         if (TREE_CODE (parm) == METHOD_TYPE
14641             && (!check_cv_quals_for_unify
14642                 (UNIFY_ALLOW_NONE,
14643                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
14644                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
14645           return 1;
14646
14647         if (unify (tparms, targs, TREE_TYPE (parm),
14648                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
14649           return 1;
14650
14651         nargs = list_length (TYPE_ARG_TYPES (arg));
14652         args = XALLOCAVEC (tree, nargs);
14653         for (a = TYPE_ARG_TYPES (arg), i = 0;
14654              a != NULL_TREE && a != void_list_node;
14655              a = TREE_CHAIN (a), ++i)
14656           args[i] = TREE_VALUE (a);
14657         nargs = i;
14658
14659         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
14660                                       args, nargs, 1, DEDUCE_EXACT,
14661                                       LOOKUP_NORMAL);
14662       }
14663
14664     case OFFSET_TYPE:
14665       /* Unify a pointer to member with a pointer to member function, which
14666          deduces the type of the member as a function type. */
14667       if (TYPE_PTRMEMFUNC_P (arg))
14668         {
14669           tree method_type;
14670           tree fntype;
14671           cp_cv_quals cv_quals;
14672
14673           /* Check top-level cv qualifiers */
14674           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
14675             return 1;
14676
14677           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14678                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
14679             return 1;
14680
14681           /* Determine the type of the function we are unifying against. */
14682           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
14683           fntype =
14684             build_function_type (TREE_TYPE (method_type),
14685                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
14686
14687           /* Extract the cv-qualifiers of the member function from the
14688              implicit object parameter and place them on the function
14689              type to be restored later. */
14690           cv_quals =
14691             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
14692           fntype = build_qualified_type (fntype, cv_quals);
14693           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
14694         }
14695
14696       if (TREE_CODE (arg) != OFFSET_TYPE)
14697         return 1;
14698       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14699                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
14700         return 1;
14701       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14702                     strict);
14703
14704     case CONST_DECL:
14705       if (DECL_TEMPLATE_PARM_P (parm))
14706         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
14707       if (arg != integral_constant_value (parm))
14708         return 1;
14709       return 0;
14710
14711     case FIELD_DECL:
14712     case TEMPLATE_DECL:
14713       /* Matched cases are handled by the ARG == PARM test above.  */
14714       return 1;
14715
14716     case TYPE_ARGUMENT_PACK:
14717     case NONTYPE_ARGUMENT_PACK:
14718       {
14719         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
14720         tree packed_args = ARGUMENT_PACK_ARGS (arg);
14721         int i, len = TREE_VEC_LENGTH (packed_parms);
14722         int argslen = TREE_VEC_LENGTH (packed_args);
14723         int parm_variadic_p = 0;
14724
14725         for (i = 0; i < len; ++i)
14726           {
14727             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
14728               {
14729                 if (i == len - 1)
14730                   /* We can unify against something with a trailing
14731                      parameter pack.  */
14732                   parm_variadic_p = 1;
14733                 else
14734                   /* Since there is something following the pack
14735                      expansion, we cannot unify this template argument
14736                      list.  */
14737                   return 0;
14738               }
14739           }
14740           
14741
14742         /* If we don't have enough arguments to satisfy the parameters
14743            (not counting the pack expression at the end), or we have
14744            too many arguments for a parameter list that doesn't end in
14745            a pack expression, we can't unify.  */
14746         if (argslen < (len - parm_variadic_p)
14747             || (argslen > len && !parm_variadic_p))
14748           return 1;
14749
14750         /* Unify all of the parameters that precede the (optional)
14751            pack expression.  */
14752         for (i = 0; i < len - parm_variadic_p; ++i)
14753           {
14754             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
14755                        TREE_VEC_ELT (packed_args, i), strict))
14756               return 1;
14757           }
14758
14759         if (parm_variadic_p)
14760           return unify_pack_expansion (tparms, targs, 
14761                                        packed_parms, packed_args,
14762                                        strict, /*call_args_p=*/false,
14763                                        /*subr=*/false);
14764         return 0;
14765       }
14766
14767       break;
14768
14769     case TYPEOF_TYPE:
14770     case DECLTYPE_TYPE:
14771       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
14772          nodes.  */
14773       return 0;
14774
14775     case ERROR_MARK:
14776       /* Unification fails if we hit an error node.  */
14777       return 1;
14778
14779     default:
14780       gcc_assert (EXPR_P (parm));
14781
14782       /* We must be looking at an expression.  This can happen with
14783          something like:
14784
14785            template <int I>
14786            void foo(S<I>, S<I + 2>);
14787
14788          This is a "nondeduced context":
14789
14790            [deduct.type]
14791
14792            The nondeduced contexts are:
14793
14794            --A type that is a template-id in which one or more of
14795              the template-arguments is an expression that references
14796              a template-parameter.
14797
14798          In these cases, we assume deduction succeeded, but don't
14799          actually infer any unifications.  */
14800
14801       if (!uses_template_parms (parm)
14802           && !template_args_equal (parm, arg))
14803         return 1;
14804       else
14805         return 0;
14806     }
14807 }
14808 \f
14809 /* Note that DECL can be defined in this translation unit, if
14810    required.  */
14811
14812 static void
14813 mark_definable (tree decl)
14814 {
14815   tree clone;
14816   DECL_NOT_REALLY_EXTERN (decl) = 1;
14817   FOR_EACH_CLONE (clone, decl)
14818     DECL_NOT_REALLY_EXTERN (clone) = 1;
14819 }
14820
14821 /* Called if RESULT is explicitly instantiated, or is a member of an
14822    explicitly instantiated class.  */
14823
14824 void
14825 mark_decl_instantiated (tree result, int extern_p)
14826 {
14827   SET_DECL_EXPLICIT_INSTANTIATION (result);
14828
14829   /* If this entity has already been written out, it's too late to
14830      make any modifications.  */
14831   if (TREE_ASM_WRITTEN (result))
14832     return;
14833
14834   if (TREE_CODE (result) != FUNCTION_DECL)
14835     /* The TREE_PUBLIC flag for function declarations will have been
14836        set correctly by tsubst.  */
14837     TREE_PUBLIC (result) = 1;
14838
14839   /* This might have been set by an earlier implicit instantiation.  */
14840   DECL_COMDAT (result) = 0;
14841
14842   if (extern_p)
14843     DECL_NOT_REALLY_EXTERN (result) = 0;
14844   else
14845     {
14846       mark_definable (result);
14847       /* Always make artificials weak.  */
14848       if (DECL_ARTIFICIAL (result) && flag_weak)
14849         comdat_linkage (result);
14850       /* For WIN32 we also want to put explicit instantiations in
14851          linkonce sections.  */
14852       else if (TREE_PUBLIC (result))
14853         maybe_make_one_only (result);
14854     }
14855
14856   /* If EXTERN_P, then this function will not be emitted -- unless
14857      followed by an explicit instantiation, at which point its linkage
14858      will be adjusted.  If !EXTERN_P, then this function will be
14859      emitted here.  In neither circumstance do we want
14860      import_export_decl to adjust the linkage.  */
14861   DECL_INTERFACE_KNOWN (result) = 1;
14862 }
14863
14864 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
14865    important template arguments.  If any are missing, we check whether
14866    they're important by using error_mark_node for substituting into any
14867    args that were used for partial ordering (the ones between ARGS and END)
14868    and seeing if it bubbles up.  */
14869
14870 static bool
14871 check_undeduced_parms (tree targs, tree args, tree end)
14872 {
14873   bool found = false;
14874   int i;
14875   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
14876     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
14877       {
14878         found = true;
14879         TREE_VEC_ELT (targs, i) = error_mark_node;
14880       }
14881   if (found)
14882     {
14883       for (; args != end; args = TREE_CHAIN (args))
14884         {
14885           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
14886           if (substed == error_mark_node)
14887             return true;
14888         }
14889     }
14890   return false;
14891 }
14892
14893 /* Given two function templates PAT1 and PAT2, return:
14894
14895    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
14896    -1 if PAT2 is more specialized than PAT1.
14897    0 if neither is more specialized.
14898
14899    LEN indicates the number of parameters we should consider
14900    (defaulted parameters should not be considered).
14901
14902    The 1998 std underspecified function template partial ordering, and
14903    DR214 addresses the issue.  We take pairs of arguments, one from
14904    each of the templates, and deduce them against each other.  One of
14905    the templates will be more specialized if all the *other*
14906    template's arguments deduce against its arguments and at least one
14907    of its arguments *does* *not* deduce against the other template's
14908    corresponding argument.  Deduction is done as for class templates.
14909    The arguments used in deduction have reference and top level cv
14910    qualifiers removed.  Iff both arguments were originally reference
14911    types *and* deduction succeeds in both directions, the template
14912    with the more cv-qualified argument wins for that pairing (if
14913    neither is more cv-qualified, they both are equal).  Unlike regular
14914    deduction, after all the arguments have been deduced in this way,
14915    we do *not* verify the deduced template argument values can be
14916    substituted into non-deduced contexts.
14917
14918    The logic can be a bit confusing here, because we look at deduce1 and
14919    targs1 to see if pat2 is at least as specialized, and vice versa; if we
14920    can find template arguments for pat1 to make arg1 look like arg2, that
14921    means that arg2 is at least as specialized as arg1.  */
14922
14923 int
14924 more_specialized_fn (tree pat1, tree pat2, int len)
14925 {
14926   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
14927   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
14928   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
14929   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
14930   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
14931   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
14932   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
14933   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
14934   tree origs1, origs2;
14935   bool lose1 = false;
14936   bool lose2 = false;
14937
14938   /* Remove the this parameter from non-static member functions.  If
14939      one is a non-static member function and the other is not a static
14940      member function, remove the first parameter from that function
14941      also.  This situation occurs for operator functions where we
14942      locate both a member function (with this pointer) and non-member
14943      operator (with explicit first operand).  */
14944   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
14945     {
14946       len--; /* LEN is the number of significant arguments for DECL1 */
14947       args1 = TREE_CHAIN (args1);
14948       if (!DECL_STATIC_FUNCTION_P (decl2))
14949         args2 = TREE_CHAIN (args2);
14950     }
14951   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
14952     {
14953       args2 = TREE_CHAIN (args2);
14954       if (!DECL_STATIC_FUNCTION_P (decl1))
14955         {
14956           len--;
14957           args1 = TREE_CHAIN (args1);
14958         }
14959     }
14960
14961   /* If only one is a conversion operator, they are unordered.  */
14962   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
14963     return 0;
14964
14965   /* Consider the return type for a conversion function */
14966   if (DECL_CONV_FN_P (decl1))
14967     {
14968       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
14969       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
14970       len++;
14971     }
14972
14973   processing_template_decl++;
14974
14975   origs1 = args1;
14976   origs2 = args2;
14977
14978   while (len--
14979          /* Stop when an ellipsis is seen.  */
14980          && args1 != NULL_TREE && args2 != NULL_TREE)
14981     {
14982       tree arg1 = TREE_VALUE (args1);
14983       tree arg2 = TREE_VALUE (args2);
14984       int deduce1, deduce2;
14985       int quals1 = -1;
14986       int quals2 = -1;
14987
14988       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14989           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14990         {
14991           /* When both arguments are pack expansions, we need only
14992              unify the patterns themselves.  */
14993           arg1 = PACK_EXPANSION_PATTERN (arg1);
14994           arg2 = PACK_EXPANSION_PATTERN (arg2);
14995
14996           /* This is the last comparison we need to do.  */
14997           len = 0;
14998         }
14999
15000       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15001         {
15002           arg1 = TREE_TYPE (arg1);
15003           quals1 = cp_type_quals (arg1);
15004         }
15005
15006       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15007         {
15008           arg2 = TREE_TYPE (arg2);
15009           quals2 = cp_type_quals (arg2);
15010         }
15011
15012       if ((quals1 < 0) != (quals2 < 0))
15013         {
15014           /* Only of the args is a reference, see if we should apply
15015              array/function pointer decay to it.  This is not part of
15016              DR214, but is, IMHO, consistent with the deduction rules
15017              for the function call itself, and with our earlier
15018              implementation of the underspecified partial ordering
15019              rules.  (nathan).  */
15020           if (quals1 >= 0)
15021             {
15022               switch (TREE_CODE (arg1))
15023                 {
15024                 case ARRAY_TYPE:
15025                   arg1 = TREE_TYPE (arg1);
15026                   /* FALLTHROUGH. */
15027                 case FUNCTION_TYPE:
15028                   arg1 = build_pointer_type (arg1);
15029                   break;
15030
15031                 default:
15032                   break;
15033                 }
15034             }
15035           else
15036             {
15037               switch (TREE_CODE (arg2))
15038                 {
15039                 case ARRAY_TYPE:
15040                   arg2 = TREE_TYPE (arg2);
15041                   /* FALLTHROUGH. */
15042                 case FUNCTION_TYPE:
15043                   arg2 = build_pointer_type (arg2);
15044                   break;
15045
15046                 default:
15047                   break;
15048                 }
15049             }
15050         }
15051
15052       arg1 = TYPE_MAIN_VARIANT (arg1);
15053       arg2 = TYPE_MAIN_VARIANT (arg2);
15054
15055       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15056         {
15057           int i, len2 = list_length (args2);
15058           tree parmvec = make_tree_vec (1);
15059           tree argvec = make_tree_vec (len2);
15060           tree ta = args2;
15061
15062           /* Setup the parameter vector, which contains only ARG1.  */
15063           TREE_VEC_ELT (parmvec, 0) = arg1;
15064
15065           /* Setup the argument vector, which contains the remaining
15066              arguments.  */
15067           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15068             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15069
15070           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15071                                            argvec, UNIFY_ALLOW_NONE, 
15072                                            /*call_args_p=*/false, 
15073                                            /*subr=*/0);
15074
15075           /* We cannot deduce in the other direction, because ARG1 is
15076              a pack expansion but ARG2 is not.  */
15077           deduce2 = 0;
15078         }
15079       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15080         {
15081           int i, len1 = list_length (args1);
15082           tree parmvec = make_tree_vec (1);
15083           tree argvec = make_tree_vec (len1);
15084           tree ta = args1;
15085
15086           /* Setup the parameter vector, which contains only ARG1.  */
15087           TREE_VEC_ELT (parmvec, 0) = arg2;
15088
15089           /* Setup the argument vector, which contains the remaining
15090              arguments.  */
15091           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15092             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15093
15094           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15095                                            argvec, UNIFY_ALLOW_NONE, 
15096                                            /*call_args_p=*/false, 
15097                                            /*subr=*/0);
15098
15099           /* We cannot deduce in the other direction, because ARG2 is
15100              a pack expansion but ARG1 is not.*/
15101           deduce1 = 0;
15102         }
15103
15104       else
15105         {
15106           /* The normal case, where neither argument is a pack
15107              expansion.  */
15108           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15109           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15110         }
15111
15112       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15113          arg2, then arg2 is not as specialized as arg1.  */
15114       if (!deduce1)
15115         lose2 = true;
15116       if (!deduce2)
15117         lose1 = true;
15118
15119       /* "If, for a given type, deduction succeeds in both directions
15120          (i.e., the types are identical after the transformations above)
15121          and if the type from the argument template is more cv-qualified
15122          than the type from the parameter template (as described above)
15123          that type is considered to be more specialized than the other. If
15124          neither type is more cv-qualified than the other then neither type
15125          is more specialized than the other."
15126
15127          We check same_type_p explicitly because deduction can also succeed
15128          in both directions when there is a nondeduced context.  */
15129       if (deduce1 && deduce2
15130           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0
15131           && same_type_p (arg1, arg2))
15132         {
15133           if ((quals1 & quals2) == quals2)
15134             lose2 = true;
15135           if ((quals1 & quals2) == quals1)
15136             lose1 = true;
15137         }
15138
15139       if (lose1 && lose2)
15140         /* We've failed to deduce something in either direction.
15141            These must be unordered.  */
15142         break;
15143
15144       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15145           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15146         /* We have already processed all of the arguments in our
15147            handing of the pack expansion type.  */
15148         len = 0;
15149
15150       args1 = TREE_CHAIN (args1);
15151       args2 = TREE_CHAIN (args2);
15152     }
15153
15154   /* "In most cases, all template parameters must have values in order for
15155      deduction to succeed, but for partial ordering purposes a template
15156      parameter may remain without a value provided it is not used in the
15157      types being used for partial ordering."
15158
15159      Thus, if we are missing any of the targs1 we need to substitute into
15160      origs1, then pat2 is not as specialized as pat1.  This can happen when
15161      there is a nondeduced context.  */
15162   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15163     lose2 = true;
15164   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15165     lose1 = true;
15166
15167   processing_template_decl--;
15168
15169   /* All things being equal, if the next argument is a pack expansion
15170      for one function but not for the other, prefer the
15171      non-variadic function.  FIXME this is bogus; see c++/41958.  */
15172   if (lose1 == lose2
15173       && args1 && TREE_VALUE (args1)
15174       && args2 && TREE_VALUE (args2))
15175     {
15176       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15177       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15178     }
15179
15180   if (lose1 == lose2)
15181     return 0;
15182   else if (!lose1)
15183     return 1;
15184   else
15185     return -1;
15186 }
15187
15188 /* Determine which of two partial specializations is more specialized.
15189
15190    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15191    to the first partial specialization.  The TREE_VALUE is the
15192    innermost set of template parameters for the partial
15193    specialization.  PAT2 is similar, but for the second template.
15194
15195    Return 1 if the first partial specialization is more specialized;
15196    -1 if the second is more specialized; 0 if neither is more
15197    specialized.
15198
15199    See [temp.class.order] for information about determining which of
15200    two templates is more specialized.  */
15201
15202 static int
15203 more_specialized_class (tree pat1, tree pat2)
15204 {
15205   tree targs;
15206   tree tmpl1, tmpl2;
15207   int winner = 0;
15208   bool any_deductions = false;
15209
15210   tmpl1 = TREE_TYPE (pat1);
15211   tmpl2 = TREE_TYPE (pat2);
15212
15213   /* Just like what happens for functions, if we are ordering between
15214      different class template specializations, we may encounter dependent
15215      types in the arguments, and we need our dependency check functions
15216      to behave correctly.  */
15217   ++processing_template_decl;
15218   targs = get_class_bindings (TREE_VALUE (pat1),
15219                               CLASSTYPE_TI_ARGS (tmpl1),
15220                               CLASSTYPE_TI_ARGS (tmpl2));
15221   if (targs)
15222     {
15223       --winner;
15224       any_deductions = true;
15225     }
15226
15227   targs = get_class_bindings (TREE_VALUE (pat2),
15228                               CLASSTYPE_TI_ARGS (tmpl2),
15229                               CLASSTYPE_TI_ARGS (tmpl1));
15230   if (targs)
15231     {
15232       ++winner;
15233       any_deductions = true;
15234     }
15235   --processing_template_decl;
15236
15237   /* In the case of a tie where at least one of the class templates
15238      has a parameter pack at the end, the template with the most
15239      non-packed parameters wins.  */
15240   if (winner == 0
15241       && any_deductions
15242       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15243           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15244     {
15245       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15246       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15247       int len1 = TREE_VEC_LENGTH (args1);
15248       int len2 = TREE_VEC_LENGTH (args2);
15249
15250       /* We don't count the pack expansion at the end.  */
15251       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15252         --len1;
15253       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15254         --len2;
15255
15256       if (len1 > len2)
15257         return 1;
15258       else if (len1 < len2)
15259         return -1;
15260     }
15261
15262   return winner;
15263 }
15264
15265 /* Return the template arguments that will produce the function signature
15266    DECL from the function template FN, with the explicit template
15267    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15268    also match.  Return NULL_TREE if no satisfactory arguments could be
15269    found.  */
15270
15271 static tree
15272 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15273 {
15274   int ntparms = DECL_NTPARMS (fn);
15275   tree targs = make_tree_vec (ntparms);
15276   tree decl_type;
15277   tree decl_arg_types;
15278   tree *args;
15279   unsigned int nargs, ix;
15280   tree arg;
15281
15282   /* Substitute the explicit template arguments into the type of DECL.
15283      The call to fn_type_unification will handle substitution into the
15284      FN.  */
15285   decl_type = TREE_TYPE (decl);
15286   if (explicit_args && uses_template_parms (decl_type))
15287     {
15288       tree tmpl;
15289       tree converted_args;
15290
15291       if (DECL_TEMPLATE_INFO (decl))
15292         tmpl = DECL_TI_TEMPLATE (decl);
15293       else
15294         /* We can get here for some invalid specializations.  */
15295         return NULL_TREE;
15296
15297       converted_args
15298         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15299                                  explicit_args, NULL_TREE,
15300                                  tf_none,
15301                                  /*require_all_args=*/false,
15302                                  /*use_default_args=*/false);
15303       if (converted_args == error_mark_node)
15304         return NULL_TREE;
15305
15306       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15307       if (decl_type == error_mark_node)
15308         return NULL_TREE;
15309     }
15310
15311   /* Never do unification on the 'this' parameter.  */
15312   decl_arg_types = skip_artificial_parms_for (decl, 
15313                                               TYPE_ARG_TYPES (decl_type));
15314
15315   nargs = list_length (decl_arg_types);
15316   args = XALLOCAVEC (tree, nargs);
15317   for (arg = decl_arg_types, ix = 0;
15318        arg != NULL_TREE && arg != void_list_node;
15319        arg = TREE_CHAIN (arg), ++ix)
15320     args[ix] = TREE_VALUE (arg);
15321
15322   if (fn_type_unification (fn, explicit_args, targs,
15323                            args, ix,
15324                            (check_rettype || DECL_CONV_FN_P (fn)
15325                             ? TREE_TYPE (decl_type) : NULL_TREE),
15326                            DEDUCE_EXACT, LOOKUP_NORMAL))
15327     return NULL_TREE;
15328
15329   return targs;
15330 }
15331
15332 /* Return the innermost template arguments that, when applied to a
15333    template specialization whose innermost template parameters are
15334    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15335    ARGS.
15336
15337    For example, suppose we have:
15338
15339      template <class T, class U> struct S {};
15340      template <class T> struct S<T*, int> {};
15341
15342    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15343    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15344    int}.  The resulting vector will be {double}, indicating that `T'
15345    is bound to `double'.  */
15346
15347 static tree
15348 get_class_bindings (tree tparms, tree spec_args, tree args)
15349 {
15350   int i, ntparms = TREE_VEC_LENGTH (tparms);
15351   tree deduced_args;
15352   tree innermost_deduced_args;
15353
15354   innermost_deduced_args = make_tree_vec (ntparms);
15355   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15356     {
15357       deduced_args = copy_node (args);
15358       SET_TMPL_ARGS_LEVEL (deduced_args,
15359                            TMPL_ARGS_DEPTH (deduced_args),
15360                            innermost_deduced_args);
15361     }
15362   else
15363     deduced_args = innermost_deduced_args;
15364
15365   if (unify (tparms, deduced_args,
15366              INNERMOST_TEMPLATE_ARGS (spec_args),
15367              INNERMOST_TEMPLATE_ARGS (args),
15368              UNIFY_ALLOW_NONE))
15369     return NULL_TREE;
15370
15371   for (i =  0; i < ntparms; ++i)
15372     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15373       return NULL_TREE;
15374
15375   /* Verify that nondeduced template arguments agree with the type
15376      obtained from argument deduction.
15377
15378      For example:
15379
15380        struct A { typedef int X; };
15381        template <class T, class U> struct C {};
15382        template <class T> struct C<T, typename T::X> {};
15383
15384      Then with the instantiation `C<A, int>', we can deduce that
15385      `T' is `A' but unify () does not check whether `typename T::X'
15386      is `int'.  */
15387   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15388   if (spec_args == error_mark_node
15389       /* We only need to check the innermost arguments; the other
15390          arguments will always agree.  */
15391       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15392                               INNERMOST_TEMPLATE_ARGS (args)))
15393     return NULL_TREE;
15394
15395   /* Now that we have bindings for all of the template arguments,
15396      ensure that the arguments deduced for the template template
15397      parameters have compatible template parameter lists.  See the use
15398      of template_template_parm_bindings_ok_p in fn_type_unification
15399      for more information.  */
15400   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15401     return NULL_TREE;
15402
15403   return deduced_args;
15404 }
15405
15406 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15407    Return the TREE_LIST node with the most specialized template, if
15408    any.  If there is no most specialized template, the error_mark_node
15409    is returned.
15410
15411    Note that this function does not look at, or modify, the
15412    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15413    returned is one of the elements of INSTANTIATIONS, callers may
15414    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15415    and retrieve it from the value returned.  */
15416
15417 tree
15418 most_specialized_instantiation (tree templates)
15419 {
15420   tree fn, champ;
15421
15422   ++processing_template_decl;
15423
15424   champ = templates;
15425   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15426     {
15427       int fate = 0;
15428
15429       if (get_bindings (TREE_VALUE (champ),
15430                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15431                         NULL_TREE, /*check_ret=*/false))
15432         fate--;
15433
15434       if (get_bindings (TREE_VALUE (fn),
15435                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15436                         NULL_TREE, /*check_ret=*/false))
15437         fate++;
15438
15439       if (fate == -1)
15440         champ = fn;
15441       else if (!fate)
15442         {
15443           /* Equally specialized, move to next function.  If there
15444              is no next function, nothing's most specialized.  */
15445           fn = TREE_CHAIN (fn);
15446           champ = fn;
15447           if (!fn)
15448             break;
15449         }
15450     }
15451
15452   if (champ)
15453     /* Now verify that champ is better than everything earlier in the
15454        instantiation list.  */
15455     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15456       if (get_bindings (TREE_VALUE (champ),
15457                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15458                         NULL_TREE, /*check_ret=*/false)
15459           || !get_bindings (TREE_VALUE (fn),
15460                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15461                             NULL_TREE, /*check_ret=*/false))
15462         {
15463           champ = NULL_TREE;
15464           break;
15465         }
15466
15467   processing_template_decl--;
15468
15469   if (!champ)
15470     return error_mark_node;
15471
15472   return champ;
15473 }
15474
15475 /* If DECL is a specialization of some template, return the most
15476    general such template.  Otherwise, returns NULL_TREE.
15477
15478    For example, given:
15479
15480      template <class T> struct S { template <class U> void f(U); };
15481
15482    if TMPL is `template <class U> void S<int>::f(U)' this will return
15483    the full template.  This function will not trace past partial
15484    specializations, however.  For example, given in addition:
15485
15486      template <class T> struct S<T*> { template <class U> void f(U); };
15487
15488    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15489    `template <class T> template <class U> S<T*>::f(U)'.  */
15490
15491 tree
15492 most_general_template (tree decl)
15493 {
15494   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15495      an immediate specialization.  */
15496   if (TREE_CODE (decl) == FUNCTION_DECL)
15497     {
15498       if (DECL_TEMPLATE_INFO (decl)) {
15499         decl = DECL_TI_TEMPLATE (decl);
15500
15501         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15502            template friend.  */
15503         if (TREE_CODE (decl) != TEMPLATE_DECL)
15504           return NULL_TREE;
15505       } else
15506         return NULL_TREE;
15507     }
15508
15509   /* Look for more and more general templates.  */
15510   while (DECL_TEMPLATE_INFO (decl))
15511     {
15512       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15513          (See cp-tree.h for details.)  */
15514       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15515         break;
15516
15517       if (CLASS_TYPE_P (TREE_TYPE (decl))
15518           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15519         break;
15520
15521       /* Stop if we run into an explicitly specialized class template.  */
15522       if (!DECL_NAMESPACE_SCOPE_P (decl)
15523           && DECL_CONTEXT (decl)
15524           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15525         break;
15526
15527       decl = DECL_TI_TEMPLATE (decl);
15528     }
15529
15530   return decl;
15531 }
15532
15533 /* Return the most specialized of the class template partial
15534    specializations of TMPL which can produce TYPE, a specialization of
15535    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15536    a _TYPE node corresponding to the partial specialization, while the
15537    TREE_PURPOSE is the set of template arguments that must be
15538    substituted into the TREE_TYPE in order to generate TYPE.
15539
15540    If the choice of partial specialization is ambiguous, a diagnostic
15541    is issued, and the error_mark_node is returned.  If there are no
15542    partial specializations of TMPL matching TYPE, then NULL_TREE is
15543    returned.  */
15544
15545 static tree
15546 most_specialized_class (tree type, tree tmpl)
15547 {
15548   tree list = NULL_TREE;
15549   tree t;
15550   tree champ;
15551   int fate;
15552   bool ambiguous_p;
15553   tree args;
15554   tree outer_args = NULL_TREE;
15555
15556   tmpl = most_general_template (tmpl);
15557   args = CLASSTYPE_TI_ARGS (type);
15558
15559   /* For determining which partial specialization to use, only the
15560      innermost args are interesting.  */
15561   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15562     {
15563       outer_args = strip_innermost_template_args (args, 1);
15564       args = INNERMOST_TEMPLATE_ARGS (args);
15565     }
15566
15567   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15568     {
15569       tree partial_spec_args;
15570       tree spec_args;
15571       tree parms = TREE_VALUE (t);
15572
15573       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15574       if (outer_args)
15575         {
15576           int i;
15577
15578           ++processing_template_decl;
15579
15580           /* Discard the outer levels of args, and then substitute in the
15581              template args from the enclosing class.  */
15582           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
15583           partial_spec_args = tsubst_template_args
15584             (partial_spec_args, outer_args, tf_none, NULL_TREE);
15585
15586           /* PARMS already refers to just the innermost parms, but the
15587              template parms in partial_spec_args had their levels lowered
15588              by tsubst, so we need to do the same for the parm list.  We
15589              can't just tsubst the TREE_VEC itself, as tsubst wants to
15590              treat a TREE_VEC as an argument vector.  */
15591           parms = copy_node (parms);
15592           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
15593             TREE_VEC_ELT (parms, i) =
15594               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
15595
15596           --processing_template_decl;
15597         }
15598       spec_args = get_class_bindings (parms,
15599                                       partial_spec_args,
15600                                       args);
15601       if (spec_args)
15602         {
15603           if (outer_args)
15604             spec_args = add_to_template_args (outer_args, spec_args);
15605           list = tree_cons (spec_args, TREE_VALUE (t), list);
15606           TREE_TYPE (list) = TREE_TYPE (t);
15607         }
15608     }
15609
15610   if (! list)
15611     return NULL_TREE;
15612
15613   ambiguous_p = false;
15614   t = list;
15615   champ = t;
15616   t = TREE_CHAIN (t);
15617   for (; t; t = TREE_CHAIN (t))
15618     {
15619       fate = more_specialized_class (champ, t);
15620       if (fate == 1)
15621         ;
15622       else
15623         {
15624           if (fate == 0)
15625             {
15626               t = TREE_CHAIN (t);
15627               if (! t)
15628                 {
15629                   ambiguous_p = true;
15630                   break;
15631                 }
15632             }
15633           champ = t;
15634         }
15635     }
15636
15637   if (!ambiguous_p)
15638     for (t = list; t && t != champ; t = TREE_CHAIN (t))
15639       {
15640         fate = more_specialized_class (champ, t);
15641         if (fate != 1)
15642           {
15643             ambiguous_p = true;
15644             break;
15645           }
15646       }
15647
15648   if (ambiguous_p)
15649     {
15650       const char *str = "candidates are:";
15651       error ("ambiguous class template instantiation for %q#T", type);
15652       for (t = list; t; t = TREE_CHAIN (t))
15653         {
15654           error ("%s %+#T", str, TREE_TYPE (t));
15655           str = "               ";
15656         }
15657       return error_mark_node;
15658     }
15659
15660   return champ;
15661 }
15662
15663 /* Explicitly instantiate DECL.  */
15664
15665 void
15666 do_decl_instantiation (tree decl, tree storage)
15667 {
15668   tree result = NULL_TREE;
15669   int extern_p = 0;
15670
15671   if (!decl || decl == error_mark_node)
15672     /* An error occurred, for which grokdeclarator has already issued
15673        an appropriate message.  */
15674     return;
15675   else if (! DECL_LANG_SPECIFIC (decl))
15676     {
15677       error ("explicit instantiation of non-template %q#D", decl);
15678       return;
15679     }
15680   else if (TREE_CODE (decl) == VAR_DECL)
15681     {
15682       /* There is an asymmetry here in the way VAR_DECLs and
15683          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
15684          the latter, the DECL we get back will be marked as a
15685          template instantiation, and the appropriate
15686          DECL_TEMPLATE_INFO will be set up.  This does not happen for
15687          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
15688          should handle VAR_DECLs as it currently handles
15689          FUNCTION_DECLs.  */
15690       if (!DECL_CLASS_SCOPE_P (decl))
15691         {
15692           error ("%qD is not a static data member of a class template", decl);
15693           return;
15694         }
15695       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
15696       if (!result || TREE_CODE (result) != VAR_DECL)
15697         {
15698           error ("no matching template for %qD found", decl);
15699           return;
15700         }
15701       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
15702         {
15703           error ("type %qT for explicit instantiation %qD does not match "
15704                  "declared type %qT", TREE_TYPE (result), decl,
15705                  TREE_TYPE (decl));
15706           return;
15707         }
15708     }
15709   else if (TREE_CODE (decl) != FUNCTION_DECL)
15710     {
15711       error ("explicit instantiation of %q#D", decl);
15712       return;
15713     }
15714   else
15715     result = decl;
15716
15717   /* Check for various error cases.  Note that if the explicit
15718      instantiation is valid the RESULT will currently be marked as an
15719      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
15720      until we get here.  */
15721
15722   if (DECL_TEMPLATE_SPECIALIZATION (result))
15723     {
15724       /* DR 259 [temp.spec].
15725
15726          Both an explicit instantiation and a declaration of an explicit
15727          specialization shall not appear in a program unless the explicit
15728          instantiation follows a declaration of the explicit specialization.
15729
15730          For a given set of template parameters, if an explicit
15731          instantiation of a template appears after a declaration of an
15732          explicit specialization for that template, the explicit
15733          instantiation has no effect.  */
15734       return;
15735     }
15736   else if (DECL_EXPLICIT_INSTANTIATION (result))
15737     {
15738       /* [temp.spec]
15739
15740          No program shall explicitly instantiate any template more
15741          than once.
15742
15743          We check DECL_NOT_REALLY_EXTERN so as not to complain when
15744          the first instantiation was `extern' and the second is not,
15745          and EXTERN_P for the opposite case.  */
15746       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
15747         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
15748       /* If an "extern" explicit instantiation follows an ordinary
15749          explicit instantiation, the template is instantiated.  */
15750       if (extern_p)
15751         return;
15752     }
15753   else if (!DECL_IMPLICIT_INSTANTIATION (result))
15754     {
15755       error ("no matching template for %qD found", result);
15756       return;
15757     }
15758   else if (!DECL_TEMPLATE_INFO (result))
15759     {
15760       permerror (input_location, "explicit instantiation of non-template %q#D", result);
15761       return;
15762     }
15763
15764   if (storage == NULL_TREE)
15765     ;
15766   else if (storage == ridpointers[(int) RID_EXTERN])
15767     {
15768       if (!in_system_header && (cxx_dialect == cxx98))
15769         pedwarn (input_location, OPT_pedantic, 
15770                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
15771                  "instantiations");
15772       extern_p = 1;
15773     }
15774   else
15775     error ("storage class %qD applied to template instantiation", storage);
15776
15777   check_explicit_instantiation_namespace (result);
15778   mark_decl_instantiated (result, extern_p);
15779   if (! extern_p)
15780     instantiate_decl (result, /*defer_ok=*/1,
15781                       /*expl_inst_class_mem_p=*/false);
15782 }
15783
15784 static void
15785 mark_class_instantiated (tree t, int extern_p)
15786 {
15787   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
15788   SET_CLASSTYPE_INTERFACE_KNOWN (t);
15789   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
15790   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
15791   if (! extern_p)
15792     {
15793       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
15794       rest_of_type_compilation (t, 1);
15795     }
15796 }
15797
15798 /* Called from do_type_instantiation through binding_table_foreach to
15799    do recursive instantiation for the type bound in ENTRY.  */
15800 static void
15801 bt_instantiate_type_proc (binding_entry entry, void *data)
15802 {
15803   tree storage = *(tree *) data;
15804
15805   if (MAYBE_CLASS_TYPE_P (entry->type)
15806       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
15807     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
15808 }
15809
15810 /* Called from do_type_instantiation to instantiate a member
15811    (a member function or a static member variable) of an
15812    explicitly instantiated class template.  */
15813 static void
15814 instantiate_class_member (tree decl, int extern_p)
15815 {
15816   mark_decl_instantiated (decl, extern_p);
15817   if (! extern_p)
15818     instantiate_decl (decl, /*defer_ok=*/1,
15819                       /*expl_inst_class_mem_p=*/true);
15820 }
15821
15822 /* Perform an explicit instantiation of template class T.  STORAGE, if
15823    non-null, is the RID for extern, inline or static.  COMPLAIN is
15824    nonzero if this is called from the parser, zero if called recursively,
15825    since the standard is unclear (as detailed below).  */
15826
15827 void
15828 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
15829 {
15830   int extern_p = 0;
15831   int nomem_p = 0;
15832   int static_p = 0;
15833   int previous_instantiation_extern_p = 0;
15834
15835   if (TREE_CODE (t) == TYPE_DECL)
15836     t = TREE_TYPE (t);
15837
15838   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
15839     {
15840       error ("explicit instantiation of non-template type %qT", t);
15841       return;
15842     }
15843
15844   complete_type (t);
15845
15846   if (!COMPLETE_TYPE_P (t))
15847     {
15848       if (complain & tf_error)
15849         error ("explicit instantiation of %q#T before definition of template",
15850                t);
15851       return;
15852     }
15853
15854   if (storage != NULL_TREE)
15855     {
15856       if (!in_system_header)
15857         {
15858           if (storage == ridpointers[(int) RID_EXTERN])
15859             {
15860               if (cxx_dialect == cxx98)
15861                 pedwarn (input_location, OPT_pedantic, 
15862                          "ISO C++ 1998 forbids the use of %<extern%> on "
15863                          "explicit instantiations");
15864             }
15865           else
15866             pedwarn (input_location, OPT_pedantic, 
15867                      "ISO C++ forbids the use of %qE"
15868                      " on explicit instantiations", storage);
15869         }
15870
15871       if (storage == ridpointers[(int) RID_INLINE])
15872         nomem_p = 1;
15873       else if (storage == ridpointers[(int) RID_EXTERN])
15874         extern_p = 1;
15875       else if (storage == ridpointers[(int) RID_STATIC])
15876         static_p = 1;
15877       else
15878         {
15879           error ("storage class %qD applied to template instantiation",
15880                  storage);
15881           extern_p = 0;
15882         }
15883     }
15884
15885   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
15886     {
15887       /* DR 259 [temp.spec].
15888
15889          Both an explicit instantiation and a declaration of an explicit
15890          specialization shall not appear in a program unless the explicit
15891          instantiation follows a declaration of the explicit specialization.
15892
15893          For a given set of template parameters, if an explicit
15894          instantiation of a template appears after a declaration of an
15895          explicit specialization for that template, the explicit
15896          instantiation has no effect.  */
15897       return;
15898     }
15899   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
15900     {
15901       /* [temp.spec]
15902
15903          No program shall explicitly instantiate any template more
15904          than once.
15905
15906          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
15907          instantiation was `extern'.  If EXTERN_P then the second is.
15908          These cases are OK.  */
15909       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
15910
15911       if (!previous_instantiation_extern_p && !extern_p
15912           && (complain & tf_error))
15913         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
15914
15915       /* If we've already instantiated the template, just return now.  */
15916       if (!CLASSTYPE_INTERFACE_ONLY (t))
15917         return;
15918     }
15919
15920   check_explicit_instantiation_namespace (TYPE_NAME (t));
15921   mark_class_instantiated (t, extern_p);
15922
15923   if (nomem_p)
15924     return;
15925
15926   {
15927     tree tmp;
15928
15929     /* In contrast to implicit instantiation, where only the
15930        declarations, and not the definitions, of members are
15931        instantiated, we have here:
15932
15933          [temp.explicit]
15934
15935          The explicit instantiation of a class template specialization
15936          implies the instantiation of all of its members not
15937          previously explicitly specialized in the translation unit
15938          containing the explicit instantiation.
15939
15940        Of course, we can't instantiate member template classes, since
15941        we don't have any arguments for them.  Note that the standard
15942        is unclear on whether the instantiation of the members are
15943        *explicit* instantiations or not.  However, the most natural
15944        interpretation is that it should be an explicit instantiation.  */
15945
15946     if (! static_p)
15947       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
15948         if (TREE_CODE (tmp) == FUNCTION_DECL
15949             && DECL_TEMPLATE_INSTANTIATION (tmp))
15950           instantiate_class_member (tmp, extern_p);
15951
15952     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
15953       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
15954         instantiate_class_member (tmp, extern_p);
15955
15956     if (CLASSTYPE_NESTED_UTDS (t))
15957       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
15958                              bt_instantiate_type_proc, &storage);
15959   }
15960 }
15961
15962 /* Given a function DECL, which is a specialization of TMPL, modify
15963    DECL to be a re-instantiation of TMPL with the same template
15964    arguments.  TMPL should be the template into which tsubst'ing
15965    should occur for DECL, not the most general template.
15966
15967    One reason for doing this is a scenario like this:
15968
15969      template <class T>
15970      void f(const T&, int i);
15971
15972      void g() { f(3, 7); }
15973
15974      template <class T>
15975      void f(const T& t, const int i) { }
15976
15977    Note that when the template is first instantiated, with
15978    instantiate_template, the resulting DECL will have no name for the
15979    first parameter, and the wrong type for the second.  So, when we go
15980    to instantiate the DECL, we regenerate it.  */
15981
15982 static void
15983 regenerate_decl_from_template (tree decl, tree tmpl)
15984 {
15985   /* The arguments used to instantiate DECL, from the most general
15986      template.  */
15987   tree args;
15988   tree code_pattern;
15989
15990   args = DECL_TI_ARGS (decl);
15991   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
15992
15993   /* Make sure that we can see identifiers, and compute access
15994      correctly.  */
15995   push_access_scope (decl);
15996
15997   if (TREE_CODE (decl) == FUNCTION_DECL)
15998     {
15999       tree decl_parm;
16000       tree pattern_parm;
16001       tree specs;
16002       int args_depth;
16003       int parms_depth;
16004
16005       args_depth = TMPL_ARGS_DEPTH (args);
16006       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16007       if (args_depth > parms_depth)
16008         args = get_innermost_template_args (args, parms_depth);
16009
16010       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16011                                               args, tf_error, NULL_TREE);
16012       if (specs)
16013         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16014                                                     specs);
16015
16016       /* Merge parameter declarations.  */
16017       decl_parm = skip_artificial_parms_for (decl,
16018                                              DECL_ARGUMENTS (decl));
16019       pattern_parm
16020         = skip_artificial_parms_for (code_pattern,
16021                                      DECL_ARGUMENTS (code_pattern));
16022       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16023         {
16024           tree parm_type;
16025           tree attributes;
16026           
16027           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16028             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16029           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16030                               NULL_TREE);
16031           parm_type = type_decays_to (parm_type);
16032           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16033             TREE_TYPE (decl_parm) = parm_type;
16034           attributes = DECL_ATTRIBUTES (pattern_parm);
16035           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16036             {
16037               DECL_ATTRIBUTES (decl_parm) = attributes;
16038               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16039             }
16040           decl_parm = TREE_CHAIN (decl_parm);
16041           pattern_parm = TREE_CHAIN (pattern_parm);
16042         }
16043       /* Merge any parameters that match with the function parameter
16044          pack.  */
16045       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16046         {
16047           int i, len;
16048           tree expanded_types;
16049           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16050              the parameters in this function parameter pack.  */
16051           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16052                                                  args, tf_error, NULL_TREE);
16053           len = TREE_VEC_LENGTH (expanded_types);
16054           for (i = 0; i < len; i++)
16055             {
16056               tree parm_type;
16057               tree attributes;
16058           
16059               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16060                 /* Rename the parameter to include the index.  */
16061                 DECL_NAME (decl_parm) = 
16062                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16063               parm_type = TREE_VEC_ELT (expanded_types, i);
16064               parm_type = type_decays_to (parm_type);
16065               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16066                 TREE_TYPE (decl_parm) = parm_type;
16067               attributes = DECL_ATTRIBUTES (pattern_parm);
16068               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16069                 {
16070                   DECL_ATTRIBUTES (decl_parm) = attributes;
16071                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16072                 }
16073               decl_parm = TREE_CHAIN (decl_parm);
16074             }
16075         }
16076       /* Merge additional specifiers from the CODE_PATTERN.  */
16077       if (DECL_DECLARED_INLINE_P (code_pattern)
16078           && !DECL_DECLARED_INLINE_P (decl))
16079         DECL_DECLARED_INLINE_P (decl) = 1;
16080     }
16081   else if (TREE_CODE (decl) == VAR_DECL)
16082     DECL_INITIAL (decl) =
16083       tsubst_expr (DECL_INITIAL (code_pattern), args,
16084                    tf_error, DECL_TI_TEMPLATE (decl),
16085                    /*integral_constant_expression_p=*/false);
16086   else
16087     gcc_unreachable ();
16088
16089   pop_access_scope (decl);
16090 }
16091
16092 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16093    substituted to get DECL.  */
16094
16095 tree
16096 template_for_substitution (tree decl)
16097 {
16098   tree tmpl = DECL_TI_TEMPLATE (decl);
16099
16100   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16101      for the instantiation.  This is not always the most general
16102      template.  Consider, for example:
16103
16104         template <class T>
16105         struct S { template <class U> void f();
16106                    template <> void f<int>(); };
16107
16108      and an instantiation of S<double>::f<int>.  We want TD to be the
16109      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16110   while (/* An instantiation cannot have a definition, so we need a
16111             more general template.  */
16112          DECL_TEMPLATE_INSTANTIATION (tmpl)
16113            /* We must also deal with friend templates.  Given:
16114
16115                 template <class T> struct S {
16116                   template <class U> friend void f() {};
16117                 };
16118
16119               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16120               so far as the language is concerned, but that's still
16121               where we get the pattern for the instantiation from.  On
16122               other hand, if the definition comes outside the class, say:
16123
16124                 template <class T> struct S {
16125                   template <class U> friend void f();
16126                 };
16127                 template <class U> friend void f() {}
16128
16129               we don't need to look any further.  That's what the check for
16130               DECL_INITIAL is for.  */
16131           || (TREE_CODE (decl) == FUNCTION_DECL
16132               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16133               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16134     {
16135       /* The present template, TD, should not be a definition.  If it
16136          were a definition, we should be using it!  Note that we
16137          cannot restructure the loop to just keep going until we find
16138          a template with a definition, since that might go too far if
16139          a specialization was declared, but not defined.  */
16140       gcc_assert (TREE_CODE (decl) != VAR_DECL
16141                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16142
16143       /* Fetch the more general template.  */
16144       tmpl = DECL_TI_TEMPLATE (tmpl);
16145     }
16146
16147   return tmpl;
16148 }
16149
16150 /* Returns true if we need to instantiate this template instance even if we
16151    know we aren't going to emit it..  */
16152
16153 bool
16154 always_instantiate_p (tree decl)
16155 {
16156   /* We always instantiate inline functions so that we can inline them.  An
16157      explicit instantiation declaration prohibits implicit instantiation of
16158      non-inline functions.  With high levels of optimization, we would
16159      normally inline non-inline functions -- but we're not allowed to do
16160      that for "extern template" functions.  Therefore, we check
16161      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16162   return ((TREE_CODE (decl) == FUNCTION_DECL
16163            && DECL_DECLARED_INLINE_P (decl))
16164           /* And we need to instantiate static data members so that
16165              their initializers are available in integral constant
16166              expressions.  */
16167           || (TREE_CODE (decl) == VAR_DECL
16168               && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16169 }
16170
16171 /* Produce the definition of D, a _DECL generated from a template.  If
16172    DEFER_OK is nonzero, then we don't have to actually do the
16173    instantiation now; we just have to do it sometime.  Normally it is
16174    an error if this is an explicit instantiation but D is undefined.
16175    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16176    explicitly instantiated class template.  */
16177
16178 tree
16179 instantiate_decl (tree d, int defer_ok,
16180                   bool expl_inst_class_mem_p)
16181 {
16182   tree tmpl = DECL_TI_TEMPLATE (d);
16183   tree gen_args;
16184   tree args;
16185   tree td;
16186   tree code_pattern;
16187   tree spec;
16188   tree gen_tmpl;
16189   bool pattern_defined;
16190   int need_push;
16191   location_t saved_loc = input_location;
16192   bool external_p;
16193
16194   /* This function should only be used to instantiate templates for
16195      functions and static member variables.  */
16196   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16197               || TREE_CODE (d) == VAR_DECL);
16198
16199   /* Variables are never deferred; if instantiation is required, they
16200      are instantiated right away.  That allows for better code in the
16201      case that an expression refers to the value of the variable --
16202      if the variable has a constant value the referring expression can
16203      take advantage of that fact.  */
16204   if (TREE_CODE (d) == VAR_DECL)
16205     defer_ok = 0;
16206
16207   /* Don't instantiate cloned functions.  Instead, instantiate the
16208      functions they cloned.  */
16209   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16210     d = DECL_CLONED_FUNCTION (d);
16211
16212   if (DECL_TEMPLATE_INSTANTIATED (d)
16213       || DECL_TEMPLATE_SPECIALIZATION (d))
16214     /* D has already been instantiated or explicitly specialized, so
16215        there's nothing for us to do here.
16216
16217        It might seem reasonable to check whether or not D is an explicit
16218        instantiation, and, if so, stop here.  But when an explicit
16219        instantiation is deferred until the end of the compilation,
16220        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16221        the instantiation.  */
16222     return d;
16223
16224   /* Check to see whether we know that this template will be
16225      instantiated in some other file, as with "extern template"
16226      extension.  */
16227   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16228
16229   /* In general, we do not instantiate such templates.  */
16230   if (external_p && !always_instantiate_p (d))
16231     return d;
16232
16233   gen_tmpl = most_general_template (tmpl);
16234   gen_args = DECL_TI_ARGS (d);
16235
16236   if (tmpl != gen_tmpl)
16237     /* We should already have the extra args.  */
16238     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16239                 == TMPL_ARGS_DEPTH (gen_args));
16240   /* And what's in the hash table should match D.  */
16241   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16242               || spec == NULL_TREE);
16243
16244   /* This needs to happen before any tsubsting.  */
16245   if (! push_tinst_level (d))
16246     return d;
16247
16248   timevar_push (TV_PARSE);
16249
16250   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16251      for the instantiation.  */
16252   td = template_for_substitution (d);
16253   code_pattern = DECL_TEMPLATE_RESULT (td);
16254
16255   /* We should never be trying to instantiate a member of a class
16256      template or partial specialization.  */
16257   gcc_assert (d != code_pattern);
16258
16259   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16260       || DECL_TEMPLATE_SPECIALIZATION (td))
16261     /* In the case of a friend template whose definition is provided
16262        outside the class, we may have too many arguments.  Drop the
16263        ones we don't need.  The same is true for specializations.  */
16264     args = get_innermost_template_args
16265       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16266   else
16267     args = gen_args;
16268
16269   if (TREE_CODE (d) == FUNCTION_DECL)
16270     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16271   else
16272     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16273
16274   /* We may be in the middle of deferred access check.  Disable it now.  */
16275   push_deferring_access_checks (dk_no_deferred);
16276
16277   /* Unless an explicit instantiation directive has already determined
16278      the linkage of D, remember that a definition is available for
16279      this entity.  */
16280   if (pattern_defined
16281       && !DECL_INTERFACE_KNOWN (d)
16282       && !DECL_NOT_REALLY_EXTERN (d))
16283     mark_definable (d);
16284
16285   input_location = DECL_SOURCE_LOCATION (d);
16286
16287   /* If D is a member of an explicitly instantiated class template,
16288      and no definition is available, treat it like an implicit
16289      instantiation.  */
16290   if (!pattern_defined && expl_inst_class_mem_p
16291       && DECL_EXPLICIT_INSTANTIATION (d))
16292     {
16293       DECL_NOT_REALLY_EXTERN (d) = 0;
16294       DECL_INTERFACE_KNOWN (d) = 0;
16295       SET_DECL_IMPLICIT_INSTANTIATION (d);
16296     }
16297
16298   /* Recheck the substitutions to obtain any warning messages
16299      about ignoring cv qualifiers.  Don't do this for artificial decls,
16300      as it breaks the context-sensitive substitution for lambda op(). */
16301   if (!defer_ok && !DECL_ARTIFICIAL (d))
16302     {
16303       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16304       tree type = TREE_TYPE (gen);
16305
16306       /* Make sure that we can see identifiers, and compute access
16307          correctly.  D is already the target FUNCTION_DECL with the
16308          right context.  */
16309       push_access_scope (d);
16310
16311       if (TREE_CODE (gen) == FUNCTION_DECL)
16312         {
16313           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16314           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16315                                           d);
16316           /* Don't simply tsubst the function type, as that will give
16317              duplicate warnings about poor parameter qualifications.
16318              The function arguments are the same as the decl_arguments
16319              without the top level cv qualifiers.  */
16320           type = TREE_TYPE (type);
16321         }
16322       tsubst (type, gen_args, tf_warning_or_error, d);
16323
16324       pop_access_scope (d);
16325     }
16326
16327   /* Defer all other templates, unless we have been explicitly
16328      forbidden from doing so.  */
16329   if (/* If there is no definition, we cannot instantiate the
16330          template.  */
16331       ! pattern_defined
16332       /* If it's OK to postpone instantiation, do so.  */
16333       || defer_ok
16334       /* If this is a static data member that will be defined
16335          elsewhere, we don't want to instantiate the entire data
16336          member, but we do want to instantiate the initializer so that
16337          we can substitute that elsewhere.  */
16338       || (external_p && TREE_CODE (d) == VAR_DECL))
16339     {
16340       /* The definition of the static data member is now required so
16341          we must substitute the initializer.  */
16342       if (TREE_CODE (d) == VAR_DECL
16343           && !DECL_INITIAL (d)
16344           && DECL_INITIAL (code_pattern))
16345         {
16346           tree ns;
16347           tree init;
16348
16349           ns = decl_namespace_context (d);
16350           push_nested_namespace (ns);
16351           push_nested_class (DECL_CONTEXT (d));
16352           init = tsubst_expr (DECL_INITIAL (code_pattern),
16353                               args,
16354                               tf_warning_or_error, NULL_TREE,
16355                               /*integral_constant_expression_p=*/false);
16356           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16357                           /*asmspec_tree=*/NULL_TREE,
16358                           LOOKUP_ONLYCONVERTING);
16359           pop_nested_class ();
16360           pop_nested_namespace (ns);
16361         }
16362
16363       /* We restore the source position here because it's used by
16364          add_pending_template.  */
16365       input_location = saved_loc;
16366
16367       if (at_eof && !pattern_defined
16368           && DECL_EXPLICIT_INSTANTIATION (d)
16369           && DECL_NOT_REALLY_EXTERN (d))
16370         /* [temp.explicit]
16371
16372            The definition of a non-exported function template, a
16373            non-exported member function template, or a non-exported
16374            member function or static data member of a class template
16375            shall be present in every translation unit in which it is
16376            explicitly instantiated.  */
16377         permerror (input_location,  "explicit instantiation of %qD "
16378                    "but no definition available", d);
16379
16380       /* ??? Historically, we have instantiated inline functions, even
16381          when marked as "extern template".  */
16382       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16383         add_pending_template (d);
16384       goto out;
16385     }
16386   /* Tell the repository that D is available in this translation unit
16387      -- and see if it is supposed to be instantiated here.  */
16388   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16389     {
16390       /* In a PCH file, despite the fact that the repository hasn't
16391          requested instantiation in the PCH it is still possible that
16392          an instantiation will be required in a file that includes the
16393          PCH.  */
16394       if (pch_file)
16395         add_pending_template (d);
16396       /* Instantiate inline functions so that the inliner can do its
16397          job, even though we'll not be emitting a copy of this
16398          function.  */
16399       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16400         goto out;
16401     }
16402
16403   need_push = !cfun || !global_bindings_p ();
16404   if (need_push)
16405     push_to_top_level ();
16406
16407   /* Mark D as instantiated so that recursive calls to
16408      instantiate_decl do not try to instantiate it again.  */
16409   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16410
16411   /* Regenerate the declaration in case the template has been modified
16412      by a subsequent redeclaration.  */
16413   regenerate_decl_from_template (d, td);
16414
16415   /* We already set the file and line above.  Reset them now in case
16416      they changed as a result of calling regenerate_decl_from_template.  */
16417   input_location = DECL_SOURCE_LOCATION (d);
16418
16419   if (TREE_CODE (d) == VAR_DECL)
16420     {
16421       tree init;
16422
16423       /* Clear out DECL_RTL; whatever was there before may not be right
16424          since we've reset the type of the declaration.  */
16425       SET_DECL_RTL (d, NULL_RTX);
16426       DECL_IN_AGGR_P (d) = 0;
16427
16428       /* The initializer is placed in DECL_INITIAL by
16429          regenerate_decl_from_template.  Pull it out so that
16430          cp_finish_decl can process it.  */
16431       init = DECL_INITIAL (d);
16432       DECL_INITIAL (d) = NULL_TREE;
16433       DECL_INITIALIZED_P (d) = 0;
16434
16435       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16436          initializer.  That function will defer actual emission until
16437          we have a chance to determine linkage.  */
16438       DECL_EXTERNAL (d) = 0;
16439
16440       /* Enter the scope of D so that access-checking works correctly.  */
16441       push_nested_class (DECL_CONTEXT (d));
16442       cp_finish_decl (d, init, false, NULL_TREE, 0);
16443       pop_nested_class ();
16444     }
16445   else if (TREE_CODE (d) == FUNCTION_DECL)
16446     {
16447       htab_t saved_local_specializations;
16448       tree subst_decl;
16449       tree tmpl_parm;
16450       tree spec_parm;
16451
16452       /* Save away the current list, in case we are instantiating one
16453          template from within the body of another.  */
16454       saved_local_specializations = local_specializations;
16455
16456       /* Set up the list of local specializations.  */
16457       local_specializations = htab_create (37,
16458                                            hash_local_specialization,
16459                                            eq_local_specializations,
16460                                            NULL);
16461
16462       /* Set up context.  */
16463       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16464
16465       /* Create substitution entries for the parameters.  */
16466       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16467       tmpl_parm = DECL_ARGUMENTS (subst_decl);
16468       spec_parm = DECL_ARGUMENTS (d);
16469       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16470         {
16471           register_local_specialization (spec_parm, tmpl_parm);
16472           spec_parm = skip_artificial_parms_for (d, spec_parm);
16473           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16474         }
16475       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16476         {
16477           register_local_specialization (spec_parm, tmpl_parm);
16478           tmpl_parm = TREE_CHAIN (tmpl_parm);
16479           spec_parm = TREE_CHAIN (spec_parm);
16480         }
16481       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16482         {
16483           /* Register the (value) argument pack as a specialization of
16484              TMPL_PARM, then move on.  */
16485           tree argpack = make_fnparm_pack (spec_parm);
16486           register_local_specialization (argpack, tmpl_parm);
16487           tmpl_parm = TREE_CHAIN (tmpl_parm);
16488           spec_parm = NULL_TREE;
16489         }
16490       gcc_assert (!spec_parm);
16491
16492       /* Substitute into the body of the function.  */
16493       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16494                    tf_warning_or_error, tmpl,
16495                    /*integral_constant_expression_p=*/false);
16496
16497       /* Set the current input_location to the end of the function
16498          so that finish_function knows where we are.  */
16499       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16500
16501       /* We don't need the local specializations any more.  */
16502       htab_delete (local_specializations);
16503       local_specializations = saved_local_specializations;
16504
16505       /* Finish the function.  */
16506       d = finish_function (0);
16507       expand_or_defer_fn (d);
16508     }
16509
16510   /* We're not deferring instantiation any more.  */
16511   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16512
16513   if (need_push)
16514     pop_from_top_level ();
16515
16516 out:
16517   input_location = saved_loc;
16518   pop_deferring_access_checks ();
16519   pop_tinst_level ();
16520
16521   timevar_pop (TV_PARSE);
16522
16523   return d;
16524 }
16525
16526 /* Run through the list of templates that we wish we could
16527    instantiate, and instantiate any we can.  RETRIES is the
16528    number of times we retry pending template instantiation.  */
16529
16530 void
16531 instantiate_pending_templates (int retries)
16532 {
16533   int reconsider;
16534   location_t saved_loc = input_location;
16535
16536   /* Instantiating templates may trigger vtable generation.  This in turn
16537      may require further template instantiations.  We place a limit here
16538      to avoid infinite loop.  */
16539   if (pending_templates && retries >= max_tinst_depth)
16540     {
16541       tree decl = pending_templates->tinst->decl;
16542
16543       error ("template instantiation depth exceeds maximum of %d"
16544              " instantiating %q+D, possibly from virtual table generation"
16545              " (use -ftemplate-depth-NN to increase the maximum)",
16546              max_tinst_depth, decl);
16547       if (TREE_CODE (decl) == FUNCTION_DECL)
16548         /* Pretend that we defined it.  */
16549         DECL_INITIAL (decl) = error_mark_node;
16550       return;
16551     }
16552
16553   do
16554     {
16555       struct pending_template **t = &pending_templates;
16556       struct pending_template *last = NULL;
16557       reconsider = 0;
16558       while (*t)
16559         {
16560           tree instantiation = reopen_tinst_level ((*t)->tinst);
16561           bool complete = false;
16562
16563           if (TYPE_P (instantiation))
16564             {
16565               tree fn;
16566
16567               if (!COMPLETE_TYPE_P (instantiation))
16568                 {
16569                   instantiate_class_template (instantiation);
16570                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
16571                     for (fn = TYPE_METHODS (instantiation);
16572                          fn;
16573                          fn = TREE_CHAIN (fn))
16574                       if (! DECL_ARTIFICIAL (fn))
16575                         instantiate_decl (fn,
16576                                           /*defer_ok=*/0,
16577                                           /*expl_inst_class_mem_p=*/false);
16578                   if (COMPLETE_TYPE_P (instantiation))
16579                     reconsider = 1;
16580                 }
16581
16582               complete = COMPLETE_TYPE_P (instantiation);
16583             }
16584           else
16585             {
16586               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
16587                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
16588                 {
16589                   instantiation
16590                     = instantiate_decl (instantiation,
16591                                         /*defer_ok=*/0,
16592                                         /*expl_inst_class_mem_p=*/false);
16593                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
16594                     reconsider = 1;
16595                 }
16596
16597               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
16598                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
16599             }
16600
16601           if (complete)
16602             /* If INSTANTIATION has been instantiated, then we don't
16603                need to consider it again in the future.  */
16604             *t = (*t)->next;
16605           else
16606             {
16607               last = *t;
16608               t = &(*t)->next;
16609             }
16610           tinst_depth = 0;
16611           current_tinst_level = NULL;
16612         }
16613       last_pending_template = last;
16614     }
16615   while (reconsider);
16616
16617   input_location = saved_loc;
16618 }
16619
16620 /* Substitute ARGVEC into T, which is a list of initializers for
16621    either base class or a non-static data member.  The TREE_PURPOSEs
16622    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
16623    instantiate_decl.  */
16624
16625 static tree
16626 tsubst_initializer_list (tree t, tree argvec)
16627 {
16628   tree inits = NULL_TREE;
16629
16630   for (; t; t = TREE_CHAIN (t))
16631     {
16632       tree decl;
16633       tree init;
16634       tree expanded_bases = NULL_TREE;
16635       tree expanded_arguments = NULL_TREE;
16636       int i, len = 1;
16637
16638       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
16639         {
16640           tree expr;
16641           tree arg;
16642
16643           /* Expand the base class expansion type into separate base
16644              classes.  */
16645           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
16646                                                  tf_warning_or_error,
16647                                                  NULL_TREE);
16648           if (expanded_bases == error_mark_node)
16649             continue;
16650           
16651           /* We'll be building separate TREE_LISTs of arguments for
16652              each base.  */
16653           len = TREE_VEC_LENGTH (expanded_bases);
16654           expanded_arguments = make_tree_vec (len);
16655           for (i = 0; i < len; i++)
16656             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
16657
16658           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
16659              expand each argument in the TREE_VALUE of t.  */
16660           expr = make_node (EXPR_PACK_EXPANSION);
16661           PACK_EXPANSION_PARAMETER_PACKS (expr) =
16662             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
16663
16664           if (TREE_VALUE (t) == void_type_node)
16665             /* VOID_TYPE_NODE is used to indicate
16666                value-initialization.  */
16667             {
16668               for (i = 0; i < len; i++)
16669                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
16670             }
16671           else
16672             {
16673               /* Substitute parameter packs into each argument in the
16674                  TREE_LIST.  */
16675               in_base_initializer = 1;
16676               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
16677                 {
16678                   tree expanded_exprs;
16679
16680                   /* Expand the argument.  */
16681                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
16682                   expanded_exprs 
16683                     = tsubst_pack_expansion (expr, argvec,
16684                                              tf_warning_or_error,
16685                                              NULL_TREE);
16686                   if (expanded_exprs == error_mark_node)
16687                     continue;
16688
16689                   /* Prepend each of the expanded expressions to the
16690                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
16691                   for (i = 0; i < len; i++)
16692                     {
16693                       TREE_VEC_ELT (expanded_arguments, i) = 
16694                         tree_cons (NULL_TREE, 
16695                                    TREE_VEC_ELT (expanded_exprs, i),
16696                                    TREE_VEC_ELT (expanded_arguments, i));
16697                     }
16698                 }
16699               in_base_initializer = 0;
16700
16701               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
16702                  since we built them backwards.  */
16703               for (i = 0; i < len; i++)
16704                 {
16705                   TREE_VEC_ELT (expanded_arguments, i) = 
16706                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
16707                 }
16708             }
16709         }
16710
16711       for (i = 0; i < len; ++i)
16712         {
16713           if (expanded_bases)
16714             {
16715               decl = TREE_VEC_ELT (expanded_bases, i);
16716               decl = expand_member_init (decl);
16717               init = TREE_VEC_ELT (expanded_arguments, i);
16718             }
16719           else
16720             {
16721               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
16722                                   tf_warning_or_error, NULL_TREE);
16723
16724               decl = expand_member_init (decl);
16725               if (decl && !DECL_P (decl))
16726                 in_base_initializer = 1;
16727
16728               init = tsubst_expr (TREE_VALUE (t), argvec, 
16729                                   tf_warning_or_error, NULL_TREE,
16730                                   /*integral_constant_expression_p=*/false);
16731               in_base_initializer = 0;
16732             }
16733
16734           if (decl)
16735             {
16736               init = build_tree_list (decl, init);
16737               TREE_CHAIN (init) = inits;
16738               inits = init;
16739             }
16740         }
16741     }
16742   return inits;
16743 }
16744
16745 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
16746
16747 static void
16748 set_current_access_from_decl (tree decl)
16749 {
16750   if (TREE_PRIVATE (decl))
16751     current_access_specifier = access_private_node;
16752   else if (TREE_PROTECTED (decl))
16753     current_access_specifier = access_protected_node;
16754   else
16755     current_access_specifier = access_public_node;
16756 }
16757
16758 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
16759    is the instantiation (which should have been created with
16760    start_enum) and ARGS are the template arguments to use.  */
16761
16762 static void
16763 tsubst_enum (tree tag, tree newtag, tree args)
16764 {
16765   tree e;
16766
16767   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
16768     {
16769       tree value;
16770       tree decl;
16771
16772       decl = TREE_VALUE (e);
16773       /* Note that in a template enum, the TREE_VALUE is the
16774          CONST_DECL, not the corresponding INTEGER_CST.  */
16775       value = tsubst_expr (DECL_INITIAL (decl),
16776                            args, tf_warning_or_error, NULL_TREE,
16777                            /*integral_constant_expression_p=*/true);
16778
16779       /* Give this enumeration constant the correct access.  */
16780       set_current_access_from_decl (decl);
16781
16782       /* Actually build the enumerator itself.  */
16783       build_enumerator (DECL_NAME (decl), value, newtag);
16784     }
16785
16786   finish_enum (newtag);
16787   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
16788     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
16789 }
16790
16791 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
16792    its type -- but without substituting the innermost set of template
16793    arguments.  So, innermost set of template parameters will appear in
16794    the type.  */
16795
16796 tree
16797 get_mostly_instantiated_function_type (tree decl)
16798 {
16799   tree fn_type;
16800   tree tmpl;
16801   tree targs;
16802   tree tparms;
16803   int parm_depth;
16804
16805   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16806   targs = DECL_TI_ARGS (decl);
16807   tparms = DECL_TEMPLATE_PARMS (tmpl);
16808   parm_depth = TMPL_PARMS_DEPTH (tparms);
16809
16810   /* There should be as many levels of arguments as there are levels
16811      of parameters.  */
16812   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
16813
16814   fn_type = TREE_TYPE (tmpl);
16815
16816   if (parm_depth == 1)
16817     /* No substitution is necessary.  */
16818     ;
16819   else
16820     {
16821       int i, save_access_control;
16822       tree partial_args;
16823
16824       /* Replace the innermost level of the TARGS with NULL_TREEs to
16825          let tsubst know not to substitute for those parameters.  */
16826       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
16827       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
16828         SET_TMPL_ARGS_LEVEL (partial_args, i,
16829                              TMPL_ARGS_LEVEL (targs, i));
16830       SET_TMPL_ARGS_LEVEL (partial_args,
16831                            TMPL_ARGS_DEPTH (targs),
16832                            make_tree_vec (DECL_NTPARMS (tmpl)));
16833
16834       /* Disable access control as this function is used only during
16835          name-mangling.  */
16836       save_access_control = flag_access_control;
16837       flag_access_control = 0;
16838
16839       ++processing_template_decl;
16840       /* Now, do the (partial) substitution to figure out the
16841          appropriate function type.  */
16842       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
16843       --processing_template_decl;
16844
16845       /* Substitute into the template parameters to obtain the real
16846          innermost set of parameters.  This step is important if the
16847          innermost set of template parameters contains value
16848          parameters whose types depend on outer template parameters.  */
16849       TREE_VEC_LENGTH (partial_args)--;
16850       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
16851
16852       flag_access_control = save_access_control;
16853     }
16854
16855   return fn_type;
16856 }
16857
16858 /* Return truthvalue if we're processing a template different from
16859    the last one involved in diagnostics.  */
16860 int
16861 problematic_instantiation_changed (void)
16862 {
16863   return last_template_error_tick != tinst_level_tick;
16864 }
16865
16866 /* Remember current template involved in diagnostics.  */
16867 void
16868 record_last_problematic_instantiation (void)
16869 {
16870   last_template_error_tick = tinst_level_tick;
16871 }
16872
16873 struct tinst_level *
16874 current_instantiation (void)
16875 {
16876   return current_tinst_level;
16877 }
16878
16879 /* [temp.param] Check that template non-type parm TYPE is of an allowable
16880    type. Return zero for ok, nonzero for disallowed. Issue error and
16881    warning messages under control of COMPLAIN.  */
16882
16883 static int
16884 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
16885 {
16886   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
16887     return 0;
16888   else if (POINTER_TYPE_P (type))
16889     return 0;
16890   else if (TYPE_PTR_TO_MEMBER_P (type))
16891     return 0;
16892   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16893     return 0;
16894   else if (TREE_CODE (type) == TYPENAME_TYPE)
16895     return 0;
16896
16897   if (complain & tf_error)
16898     error ("%q#T is not a valid type for a template constant parameter", type);
16899   return 1;
16900 }
16901
16902 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
16903    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
16904
16905 static bool
16906 dependent_type_p_r (tree type)
16907 {
16908   tree scope;
16909
16910   /* [temp.dep.type]
16911
16912      A type is dependent if it is:
16913
16914      -- a template parameter. Template template parameters are types
16915         for us (since TYPE_P holds true for them) so we handle
16916         them here.  */
16917   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16918       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
16919     return true;
16920   /* -- a qualified-id with a nested-name-specifier which contains a
16921         class-name that names a dependent type or whose unqualified-id
16922         names a dependent type.  */
16923   if (TREE_CODE (type) == TYPENAME_TYPE)
16924     return true;
16925   /* -- a cv-qualified type where the cv-unqualified type is
16926         dependent.  */
16927   type = TYPE_MAIN_VARIANT (type);
16928   /* -- a compound type constructed from any dependent type.  */
16929   if (TYPE_PTR_TO_MEMBER_P (type))
16930     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
16931             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
16932                                            (type)));
16933   else if (TREE_CODE (type) == POINTER_TYPE
16934            || TREE_CODE (type) == REFERENCE_TYPE)
16935     return dependent_type_p (TREE_TYPE (type));
16936   else if (TREE_CODE (type) == FUNCTION_TYPE
16937            || TREE_CODE (type) == METHOD_TYPE)
16938     {
16939       tree arg_type;
16940
16941       if (dependent_type_p (TREE_TYPE (type)))
16942         return true;
16943       for (arg_type = TYPE_ARG_TYPES (type);
16944            arg_type;
16945            arg_type = TREE_CHAIN (arg_type))
16946         if (dependent_type_p (TREE_VALUE (arg_type)))
16947           return true;
16948       return false;
16949     }
16950   /* -- an array type constructed from any dependent type or whose
16951         size is specified by a constant expression that is
16952         value-dependent.  */
16953   if (TREE_CODE (type) == ARRAY_TYPE)
16954     {
16955       if (TYPE_DOMAIN (type)
16956           && dependent_type_p (TYPE_DOMAIN (type)))
16957         return true;
16958       return dependent_type_p (TREE_TYPE (type));
16959     }
16960   else if (TREE_CODE (type) == INTEGER_TYPE
16961            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
16962     {
16963       /* If this is the TYPE_DOMAIN of an array type, consider it
16964          dependent.  We already checked for value-dependence in
16965          compute_array_index_type.  */
16966       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
16967     }
16968
16969   /* -- a template-id in which either the template name is a template
16970      parameter ...  */
16971   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
16972     return true;
16973   /* ... or any of the template arguments is a dependent type or
16974         an expression that is type-dependent or value-dependent.  */
16975   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
16976            && (any_dependent_template_arguments_p
16977                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
16978     return true;
16979
16980   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
16981      argument of the `typeof' expression is not type-dependent, then
16982      it should already been have resolved.  */
16983   if (TREE_CODE (type) == TYPEOF_TYPE
16984       || TREE_CODE (type) == DECLTYPE_TYPE)
16985     return true;
16986
16987   /* A template argument pack is dependent if any of its packed
16988      arguments are.  */
16989   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
16990     {
16991       tree args = ARGUMENT_PACK_ARGS (type);
16992       int i, len = TREE_VEC_LENGTH (args);
16993       for (i = 0; i < len; ++i)
16994         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16995           return true;
16996     }
16997
16998   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
16999      be template parameters.  */
17000   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17001     return true;
17002
17003   /* The standard does not specifically mention types that are local
17004      to template functions or local classes, but they should be
17005      considered dependent too.  For example:
17006
17007        template <int I> void f() {
17008          enum E { a = I };
17009          S<sizeof (E)> s;
17010        }
17011
17012      The size of `E' cannot be known until the value of `I' has been
17013      determined.  Therefore, `E' must be considered dependent.  */
17014   scope = TYPE_CONTEXT (type);
17015   if (scope && TYPE_P (scope))
17016     return dependent_type_p (scope);
17017   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17018     return type_dependent_expression_p (scope);
17019
17020   /* Other types are non-dependent.  */
17021   return false;
17022 }
17023
17024 /* Returns TRUE if TYPE is dependent, in the sense of
17025    [temp.dep.type].  */
17026
17027 bool
17028 dependent_type_p (tree type)
17029 {
17030   /* If there are no template parameters in scope, then there can't be
17031      any dependent types.  */
17032   if (!processing_template_decl)
17033     {
17034       /* If we are not processing a template, then nobody should be
17035          providing us with a dependent type.  */
17036       gcc_assert (type);
17037       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17038       return false;
17039     }
17040
17041   /* If the type is NULL, we have not computed a type for the entity
17042      in question; in that case, the type is dependent.  */
17043   if (!type)
17044     return true;
17045
17046   /* Erroneous types can be considered non-dependent.  */
17047   if (type == error_mark_node)
17048     return false;
17049
17050   /* If we have not already computed the appropriate value for TYPE,
17051      do so now.  */
17052   if (!TYPE_DEPENDENT_P_VALID (type))
17053     {
17054       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17055       TYPE_DEPENDENT_P_VALID (type) = 1;
17056     }
17057
17058   return TYPE_DEPENDENT_P (type);
17059 }
17060
17061 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17062    lookup.  In other words, a dependent type that is not the current
17063    instantiation.  */
17064
17065 bool
17066 dependent_scope_p (tree scope)
17067 {
17068   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17069           && !currently_open_class (scope));
17070 }
17071
17072 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
17073
17074 static bool
17075 dependent_scope_ref_p (tree expression, bool criterion (tree))
17076 {
17077   tree scope;
17078   tree name;
17079
17080   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
17081
17082   if (!TYPE_P (TREE_OPERAND (expression, 0)))
17083     return true;
17084
17085   scope = TREE_OPERAND (expression, 0);
17086   name = TREE_OPERAND (expression, 1);
17087
17088   /* [temp.dep.expr]
17089
17090      An id-expression is type-dependent if it contains a
17091      nested-name-specifier that contains a class-name that names a
17092      dependent type.  */
17093   /* The suggested resolution to Core Issue 224 implies that if the
17094      qualifying type is the current class, then we must peek
17095      inside it.  */
17096   if (DECL_P (name)
17097       && currently_open_class (scope)
17098       && !criterion (name))
17099     return false;
17100   if (dependent_type_p (scope))
17101     return true;
17102
17103   return false;
17104 }
17105
17106 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17107    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17108    expression.  */
17109
17110 bool
17111 value_dependent_expression_p (tree expression)
17112 {
17113   if (!processing_template_decl)
17114     return false;
17115
17116   /* A name declared with a dependent type.  */
17117   if (DECL_P (expression) && type_dependent_expression_p (expression))
17118     return true;
17119
17120   switch (TREE_CODE (expression))
17121     {
17122     case IDENTIFIER_NODE:
17123       /* A name that has not been looked up -- must be dependent.  */
17124       return true;
17125
17126     case TEMPLATE_PARM_INDEX:
17127       /* A non-type template parm.  */
17128       return true;
17129
17130     case CONST_DECL:
17131       /* A non-type template parm.  */
17132       if (DECL_TEMPLATE_PARM_P (expression))
17133         return true;
17134       return value_dependent_expression_p (DECL_INITIAL (expression));
17135
17136     case VAR_DECL:
17137        /* A constant with integral or enumeration type and is initialized
17138           with an expression that is value-dependent.  */
17139       if (DECL_INITIAL (expression)
17140           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17141           && value_dependent_expression_p (DECL_INITIAL (expression)))
17142         return true;
17143       return false;
17144
17145     case DYNAMIC_CAST_EXPR:
17146     case STATIC_CAST_EXPR:
17147     case CONST_CAST_EXPR:
17148     case REINTERPRET_CAST_EXPR:
17149     case CAST_EXPR:
17150       /* These expressions are value-dependent if the type to which
17151          the cast occurs is dependent or the expression being casted
17152          is value-dependent.  */
17153       {
17154         tree type = TREE_TYPE (expression);
17155
17156         if (dependent_type_p (type))
17157           return true;
17158
17159         /* A functional cast has a list of operands.  */
17160         expression = TREE_OPERAND (expression, 0);
17161         if (!expression)
17162           {
17163             /* If there are no operands, it must be an expression such
17164                as "int()". This should not happen for aggregate types
17165                because it would form non-constant expressions.  */
17166             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17167
17168             return false;
17169           }
17170
17171         if (TREE_CODE (expression) == TREE_LIST)
17172           return any_value_dependent_elements_p (expression);
17173
17174         return value_dependent_expression_p (expression);
17175       }
17176
17177     case SIZEOF_EXPR:
17178     case ALIGNOF_EXPR:
17179       /* A `sizeof' expression is value-dependent if the operand is
17180          type-dependent or is a pack expansion.  */
17181       expression = TREE_OPERAND (expression, 0);
17182       if (PACK_EXPANSION_P (expression))
17183         return true;
17184       else if (TYPE_P (expression))
17185         return dependent_type_p (expression);
17186       return type_dependent_expression_p (expression);
17187
17188     case SCOPE_REF:
17189       return dependent_scope_ref_p (expression, value_dependent_expression_p);
17190
17191     case COMPONENT_REF:
17192       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17193               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17194
17195     case CALL_EXPR:
17196       /* A CALL_EXPR may appear in a constant expression if it is a
17197          call to a builtin function, e.g., __builtin_constant_p.  All
17198          such calls are value-dependent.  */
17199       return true;
17200
17201     case NONTYPE_ARGUMENT_PACK:
17202       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17203          is value-dependent.  */
17204       {
17205         tree values = ARGUMENT_PACK_ARGS (expression);
17206         int i, len = TREE_VEC_LENGTH (values);
17207         
17208         for (i = 0; i < len; ++i)
17209           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17210             return true;
17211         
17212         return false;
17213       }
17214
17215     case TRAIT_EXPR:
17216       {
17217         tree type2 = TRAIT_EXPR_TYPE2 (expression);
17218         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17219                 || (type2 ? dependent_type_p (type2) : false));
17220       }
17221
17222     case MODOP_EXPR:
17223       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17224               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17225
17226     default:
17227       /* A constant expression is value-dependent if any subexpression is
17228          value-dependent.  */
17229       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17230         {
17231         case tcc_reference:
17232         case tcc_unary:
17233           return (value_dependent_expression_p
17234                   (TREE_OPERAND (expression, 0)));
17235
17236         case tcc_comparison:
17237         case tcc_binary:
17238           return ((value_dependent_expression_p
17239                    (TREE_OPERAND (expression, 0)))
17240                   || (value_dependent_expression_p
17241                       (TREE_OPERAND (expression, 1))));
17242
17243         case tcc_expression:
17244         case tcc_vl_exp:
17245           {
17246             int i;
17247             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17248               /* In some cases, some of the operands may be missing.
17249                  (For example, in the case of PREDECREMENT_EXPR, the
17250                  amount to increment by may be missing.)  That doesn't
17251                  make the expression dependent.  */
17252               if (TREE_OPERAND (expression, i)
17253                   && (value_dependent_expression_p
17254                       (TREE_OPERAND (expression, i))))
17255                 return true;
17256             return false;
17257           }
17258
17259         default:
17260           break;
17261         }
17262     }
17263
17264   /* The expression is not value-dependent.  */
17265   return false;
17266 }
17267
17268 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17269    [temp.dep.expr].  */
17270
17271 bool
17272 type_dependent_expression_p (tree expression)
17273 {
17274   if (!processing_template_decl)
17275     return false;
17276
17277   if (expression == error_mark_node)
17278     return false;
17279
17280   /* An unresolved name is always dependent.  */
17281   if (TREE_CODE (expression) == IDENTIFIER_NODE
17282       || TREE_CODE (expression) == USING_DECL)
17283     return true;
17284
17285   /* Some expression forms are never type-dependent.  */
17286   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17287       || TREE_CODE (expression) == SIZEOF_EXPR
17288       || TREE_CODE (expression) == ALIGNOF_EXPR
17289       || TREE_CODE (expression) == TRAIT_EXPR
17290       || TREE_CODE (expression) == TYPEID_EXPR
17291       || TREE_CODE (expression) == DELETE_EXPR
17292       || TREE_CODE (expression) == VEC_DELETE_EXPR
17293       || TREE_CODE (expression) == THROW_EXPR)
17294     return false;
17295
17296   /* The types of these expressions depends only on the type to which
17297      the cast occurs.  */
17298   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17299       || TREE_CODE (expression) == STATIC_CAST_EXPR
17300       || TREE_CODE (expression) == CONST_CAST_EXPR
17301       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17302       || TREE_CODE (expression) == CAST_EXPR)
17303     return dependent_type_p (TREE_TYPE (expression));
17304
17305   /* The types of these expressions depends only on the type created
17306      by the expression.  */
17307   if (TREE_CODE (expression) == NEW_EXPR
17308       || TREE_CODE (expression) == VEC_NEW_EXPR)
17309     {
17310       /* For NEW_EXPR tree nodes created inside a template, either
17311          the object type itself or a TREE_LIST may appear as the
17312          operand 1.  */
17313       tree type = TREE_OPERAND (expression, 1);
17314       if (TREE_CODE (type) == TREE_LIST)
17315         /* This is an array type.  We need to check array dimensions
17316            as well.  */
17317         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17318                || value_dependent_expression_p
17319                     (TREE_OPERAND (TREE_VALUE (type), 1));
17320       else
17321         return dependent_type_p (type);
17322     }
17323
17324   if (TREE_CODE (expression) == SCOPE_REF
17325       && dependent_scope_ref_p (expression,
17326                                 type_dependent_expression_p))
17327     return true;
17328
17329   if (TREE_CODE (expression) == FUNCTION_DECL
17330       && DECL_LANG_SPECIFIC (expression)
17331       && DECL_TEMPLATE_INFO (expression)
17332       && (any_dependent_template_arguments_p
17333           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17334     return true;
17335
17336   if (TREE_CODE (expression) == TEMPLATE_DECL
17337       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17338     return false;
17339
17340   if (TREE_CODE (expression) == STMT_EXPR)
17341     expression = stmt_expr_value_expr (expression);
17342
17343   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17344     {
17345       tree elt;
17346       unsigned i;
17347
17348       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17349         {
17350           if (type_dependent_expression_p (elt))
17351             return true;
17352         }
17353       return false;
17354     }
17355
17356   if (TREE_TYPE (expression) == unknown_type_node)
17357     {
17358       if (TREE_CODE (expression) == ADDR_EXPR)
17359         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17360       if (TREE_CODE (expression) == COMPONENT_REF
17361           || TREE_CODE (expression) == OFFSET_REF)
17362         {
17363           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17364             return true;
17365           expression = TREE_OPERAND (expression, 1);
17366           if (TREE_CODE (expression) == IDENTIFIER_NODE)
17367             return false;
17368         }
17369       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17370       if (TREE_CODE (expression) == SCOPE_REF)
17371         return false;
17372
17373       if (TREE_CODE (expression) == BASELINK)
17374         expression = BASELINK_FUNCTIONS (expression);
17375
17376       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17377         {
17378           if (any_dependent_template_arguments_p
17379               (TREE_OPERAND (expression, 1)))
17380             return true;
17381           expression = TREE_OPERAND (expression, 0);
17382         }
17383       gcc_assert (TREE_CODE (expression) == OVERLOAD
17384                   || TREE_CODE (expression) == FUNCTION_DECL);
17385
17386       while (expression)
17387         {
17388           if (type_dependent_expression_p (OVL_CURRENT (expression)))
17389             return true;
17390           expression = OVL_NEXT (expression);
17391         }
17392       return false;
17393     }
17394
17395   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17396
17397   return (dependent_type_p (TREE_TYPE (expression)));
17398 }
17399
17400 /* Like type_dependent_expression_p, but it also works while not processing
17401    a template definition, i.e. during substitution or mangling.  */
17402
17403 bool
17404 type_dependent_expression_p_push (tree expr)
17405 {
17406   bool b;
17407   ++processing_template_decl;
17408   b = type_dependent_expression_p (expr);
17409   --processing_template_decl;
17410   return b;
17411 }
17412
17413 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17414
17415 bool
17416 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17417 {
17418   unsigned int i;
17419   tree arg;
17420
17421   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
17422     {
17423       if (type_dependent_expression_p (arg))
17424         return true;
17425     }
17426   return false;
17427 }
17428
17429 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17430    expressions) contains any value-dependent expressions.  */
17431
17432 bool
17433 any_value_dependent_elements_p (const_tree list)
17434 {
17435   for (; list; list = TREE_CHAIN (list))
17436     if (value_dependent_expression_p (TREE_VALUE (list)))
17437       return true;
17438
17439   return false;
17440 }
17441
17442 /* Returns TRUE if the ARG (a template argument) is dependent.  */
17443
17444 bool
17445 dependent_template_arg_p (tree arg)
17446 {
17447   if (!processing_template_decl)
17448     return false;
17449
17450   if (TREE_CODE (arg) == TEMPLATE_DECL
17451       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17452     return dependent_template_p (arg);
17453   else if (ARGUMENT_PACK_P (arg))
17454     {
17455       tree args = ARGUMENT_PACK_ARGS (arg);
17456       int i, len = TREE_VEC_LENGTH (args);
17457       for (i = 0; i < len; ++i)
17458         {
17459           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17460             return true;
17461         }
17462
17463       return false;
17464     }
17465   else if (TYPE_P (arg))
17466     return dependent_type_p (arg);
17467   else
17468     return (type_dependent_expression_p (arg)
17469             || value_dependent_expression_p (arg));
17470 }
17471
17472 /* Returns true if ARGS (a collection of template arguments) contains
17473    any types that require structural equality testing.  */
17474
17475 bool
17476 any_template_arguments_need_structural_equality_p (tree args)
17477 {
17478   int i;
17479   int j;
17480
17481   if (!args)
17482     return false;
17483   if (args == error_mark_node)
17484     return true;
17485
17486   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17487     {
17488       tree level = TMPL_ARGS_LEVEL (args, i + 1);
17489       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17490         {
17491           tree arg = TREE_VEC_ELT (level, j);
17492           tree packed_args = NULL_TREE;
17493           int k, len = 1;
17494
17495           if (ARGUMENT_PACK_P (arg))
17496             {
17497               /* Look inside the argument pack.  */
17498               packed_args = ARGUMENT_PACK_ARGS (arg);
17499               len = TREE_VEC_LENGTH (packed_args);
17500             }
17501
17502           for (k = 0; k < len; ++k)
17503             {
17504               if (packed_args)
17505                 arg = TREE_VEC_ELT (packed_args, k);
17506
17507               if (error_operand_p (arg))
17508                 return true;
17509               else if (TREE_CODE (arg) == TEMPLATE_DECL
17510                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17511                 continue;
17512               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17513                 return true;
17514               else if (!TYPE_P (arg) && TREE_TYPE (arg)
17515                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17516                 return true;
17517             }
17518         }
17519     }
17520
17521   return false;
17522 }
17523
17524 /* Returns true if ARGS (a collection of template arguments) contains
17525    any dependent arguments.  */
17526
17527 bool
17528 any_dependent_template_arguments_p (const_tree args)
17529 {
17530   int i;
17531   int j;
17532
17533   if (!args)
17534     return false;
17535   if (args == error_mark_node)
17536     return true;
17537
17538   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17539     {
17540       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17541       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17542         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17543           return true;
17544     }
17545
17546   return false;
17547 }
17548
17549 /* Returns TRUE if the template TMPL is dependent.  */
17550
17551 bool
17552 dependent_template_p (tree tmpl)
17553 {
17554   if (TREE_CODE (tmpl) == OVERLOAD)
17555     {
17556       while (tmpl)
17557         {
17558           if (dependent_template_p (OVL_FUNCTION (tmpl)))
17559             return true;
17560           tmpl = OVL_CHAIN (tmpl);
17561         }
17562       return false;
17563     }
17564
17565   /* Template template parameters are dependent.  */
17566   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
17567       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
17568     return true;
17569   /* So are names that have not been looked up.  */
17570   if (TREE_CODE (tmpl) == SCOPE_REF
17571       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
17572     return true;
17573   /* So are member templates of dependent classes.  */
17574   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
17575     return dependent_type_p (DECL_CONTEXT (tmpl));
17576   return false;
17577 }
17578
17579 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
17580
17581 bool
17582 dependent_template_id_p (tree tmpl, tree args)
17583 {
17584   return (dependent_template_p (tmpl)
17585           || any_dependent_template_arguments_p (args));
17586 }
17587
17588 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
17589    is dependent.  */
17590
17591 bool
17592 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
17593 {
17594   int i;
17595
17596   if (!processing_template_decl)
17597     return false;
17598
17599   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
17600     {
17601       tree decl = TREE_VEC_ELT (declv, i);
17602       tree init = TREE_VEC_ELT (initv, i);
17603       tree cond = TREE_VEC_ELT (condv, i);
17604       tree incr = TREE_VEC_ELT (incrv, i);
17605
17606       if (type_dependent_expression_p (decl))
17607         return true;
17608
17609       if (init && type_dependent_expression_p (init))
17610         return true;
17611
17612       if (type_dependent_expression_p (cond))
17613         return true;
17614
17615       if (COMPARISON_CLASS_P (cond)
17616           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
17617               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
17618         return true;
17619
17620       if (TREE_CODE (incr) == MODOP_EXPR)
17621         {
17622           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
17623               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
17624             return true;
17625         }
17626       else if (type_dependent_expression_p (incr))
17627         return true;
17628       else if (TREE_CODE (incr) == MODIFY_EXPR)
17629         {
17630           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
17631             return true;
17632           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
17633             {
17634               tree t = TREE_OPERAND (incr, 1);
17635               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
17636                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
17637                 return true;
17638             }
17639         }
17640     }
17641
17642   return false;
17643 }
17644
17645 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
17646    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
17647    no such TYPE can be found.  Note that this function peers inside
17648    uninstantiated templates and therefore should be used only in
17649    extremely limited situations.  ONLY_CURRENT_P restricts this
17650    peering to the currently open classes hierarchy (which is required
17651    when comparing types).  */
17652
17653 tree
17654 resolve_typename_type (tree type, bool only_current_p)
17655 {
17656   tree scope;
17657   tree name;
17658   tree decl;
17659   int quals;
17660   tree pushed_scope;
17661   tree result;
17662
17663   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
17664
17665   scope = TYPE_CONTEXT (type);
17666   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
17667      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
17668      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
17669      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
17670      identifier  of the TYPENAME_TYPE anymore.
17671      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
17672      TYPENAME_TYPE instead, we avoid messing up with a possible
17673      typedef variant case.  */
17674   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
17675
17676   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
17677      it first before we can figure out what NAME refers to.  */
17678   if (TREE_CODE (scope) == TYPENAME_TYPE)
17679     scope = resolve_typename_type (scope, only_current_p);
17680   /* If we don't know what SCOPE refers to, then we cannot resolve the
17681      TYPENAME_TYPE.  */
17682   if (TREE_CODE (scope) == TYPENAME_TYPE)
17683     return type;
17684   /* If the SCOPE is a template type parameter, we have no way of
17685      resolving the name.  */
17686   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
17687     return type;
17688   /* If the SCOPE is not the current instantiation, there's no reason
17689      to look inside it.  */
17690   if (only_current_p && !currently_open_class (scope))
17691     return type;
17692   /* If this is a typedef, we don't want to look inside (c++/11987).  */
17693   if (typedef_variant_p (type))
17694     return type;
17695   /* If SCOPE isn't the template itself, it will not have a valid
17696      TYPE_FIELDS list.  */
17697   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
17698     /* scope is either the template itself or a compatible instantiation
17699        like X<T>, so look up the name in the original template.  */
17700     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
17701   else
17702     /* scope is a partial instantiation, so we can't do the lookup or we
17703        will lose the template arguments.  */
17704     return type;
17705   /* Enter the SCOPE so that name lookup will be resolved as if we
17706      were in the class definition.  In particular, SCOPE will no
17707      longer be considered a dependent type.  */
17708   pushed_scope = push_scope (scope);
17709   /* Look up the declaration.  */
17710   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
17711
17712   result = NULL_TREE;
17713   
17714   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
17715      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
17716   if (!decl)
17717     /*nop*/;
17718   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
17719            && TREE_CODE (decl) == TYPE_DECL)
17720     {
17721       result = TREE_TYPE (decl);
17722       if (result == error_mark_node)
17723         result = NULL_TREE;
17724     }
17725   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
17726            && DECL_CLASS_TEMPLATE_P (decl))
17727     {
17728       tree tmpl;
17729       tree args;
17730       /* Obtain the template and the arguments.  */
17731       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
17732       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
17733       /* Instantiate the template.  */
17734       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
17735                                       /*entering_scope=*/0,
17736                                       tf_error | tf_user);
17737       if (result == error_mark_node)
17738         result = NULL_TREE;
17739     }
17740   
17741   /* Leave the SCOPE.  */
17742   if (pushed_scope)
17743     pop_scope (pushed_scope);
17744
17745   /* If we failed to resolve it, return the original typename.  */
17746   if (!result)
17747     return type;
17748   
17749   /* If lookup found a typename type, resolve that too.  */
17750   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
17751     {
17752       /* Ill-formed programs can cause infinite recursion here, so we
17753          must catch that.  */
17754       TYPENAME_IS_RESOLVING_P (type) = 1;
17755       result = resolve_typename_type (result, only_current_p);
17756       TYPENAME_IS_RESOLVING_P (type) = 0;
17757     }
17758   
17759   /* Qualify the resulting type.  */
17760   quals = cp_type_quals (type);
17761   if (quals)
17762     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
17763
17764   return result;
17765 }
17766
17767 /* EXPR is an expression which is not type-dependent.  Return a proxy
17768    for EXPR that can be used to compute the types of larger
17769    expressions containing EXPR.  */
17770
17771 tree
17772 build_non_dependent_expr (tree expr)
17773 {
17774   tree inner_expr;
17775
17776   /* Preserve null pointer constants so that the type of things like
17777      "p == 0" where "p" is a pointer can be determined.  */
17778   if (null_ptr_cst_p (expr))
17779     return expr;
17780   /* Preserve OVERLOADs; the functions must be available to resolve
17781      types.  */
17782   inner_expr = expr;
17783   if (TREE_CODE (inner_expr) == STMT_EXPR)
17784     inner_expr = stmt_expr_value_expr (inner_expr);
17785   if (TREE_CODE (inner_expr) == ADDR_EXPR)
17786     inner_expr = TREE_OPERAND (inner_expr, 0);
17787   if (TREE_CODE (inner_expr) == COMPONENT_REF)
17788     inner_expr = TREE_OPERAND (inner_expr, 1);
17789   if (is_overloaded_fn (inner_expr)
17790       || TREE_CODE (inner_expr) == OFFSET_REF)
17791     return expr;
17792   /* There is no need to return a proxy for a variable.  */
17793   if (TREE_CODE (expr) == VAR_DECL)
17794     return expr;
17795   /* Preserve string constants; conversions from string constants to
17796      "char *" are allowed, even though normally a "const char *"
17797      cannot be used to initialize a "char *".  */
17798   if (TREE_CODE (expr) == STRING_CST)
17799     return expr;
17800   /* Preserve arithmetic constants, as an optimization -- there is no
17801      reason to create a new node.  */
17802   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
17803     return expr;
17804   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
17805      There is at least one place where we want to know that a
17806      particular expression is a throw-expression: when checking a ?:
17807      expression, there are special rules if the second or third
17808      argument is a throw-expression.  */
17809   if (TREE_CODE (expr) == THROW_EXPR)
17810     return expr;
17811
17812   if (TREE_CODE (expr) == COND_EXPR)
17813     return build3 (COND_EXPR,
17814                    TREE_TYPE (expr),
17815                    TREE_OPERAND (expr, 0),
17816                    (TREE_OPERAND (expr, 1)
17817                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
17818                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
17819                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
17820   if (TREE_CODE (expr) == COMPOUND_EXPR
17821       && !COMPOUND_EXPR_OVERLOADED (expr))
17822     return build2 (COMPOUND_EXPR,
17823                    TREE_TYPE (expr),
17824                    TREE_OPERAND (expr, 0),
17825                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
17826
17827   /* If the type is unknown, it can't really be non-dependent */
17828   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
17829
17830   /* Otherwise, build a NON_DEPENDENT_EXPR.
17831
17832      REFERENCE_TYPEs are not stripped for expressions in templates
17833      because doing so would play havoc with mangling.  Consider, for
17834      example:
17835
17836        template <typename T> void f<T& g>() { g(); }
17837
17838      In the body of "f", the expression for "g" will have
17839      REFERENCE_TYPE, even though the standard says that it should
17840      not.  The reason is that we must preserve the syntactic form of
17841      the expression so that mangling (say) "f<g>" inside the body of
17842      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
17843      stripped here.  */
17844   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
17845 }
17846
17847 /* ARGS is a vector of expressions as arguments to a function call.
17848    Replace the arguments with equivalent non-dependent expressions.
17849    This modifies ARGS in place.  */
17850
17851 void
17852 make_args_non_dependent (VEC(tree,gc) *args)
17853 {
17854   unsigned int ix;
17855   tree arg;
17856
17857   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
17858     {
17859       tree newarg = build_non_dependent_expr (arg);
17860       if (newarg != arg)
17861         VEC_replace (tree, args, ix, newarg);
17862     }
17863 }
17864
17865 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
17866    with a level one deeper than the actual template parms.  */
17867
17868 tree
17869 make_auto (void)
17870 {
17871   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
17872   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
17873                                TYPE_DECL, get_identifier ("auto"), au);
17874   TYPE_STUB_DECL (au) = TYPE_NAME (au);
17875   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
17876     (0, processing_template_decl + 1, processing_template_decl + 1,
17877      TYPE_NAME (au), NULL_TREE);
17878   TYPE_CANONICAL (au) = canonical_type_parameter (au);
17879   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
17880   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
17881
17882   return au;
17883 }
17884
17885 /* Given type ARG, return std::initializer_list<ARG>.  */
17886
17887 static tree
17888 listify (tree arg)
17889 {
17890   tree std_init_list = namespace_binding
17891     (get_identifier ("initializer_list"), std_node);
17892   tree argvec;
17893   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
17894     {    
17895       error ("deducing from brace-enclosed initializer list requires "
17896              "#include <initializer_list>");
17897       return error_mark_node;
17898     }
17899   argvec = make_tree_vec (1);
17900   TREE_VEC_ELT (argvec, 0) = arg;
17901   return lookup_template_class (std_init_list, argvec, NULL_TREE,
17902                                 NULL_TREE, 0, tf_warning_or_error);
17903 }
17904
17905 /* Replace auto in TYPE with std::initializer_list<auto>.  */
17906
17907 static tree
17908 listify_autos (tree type, tree auto_node)
17909 {
17910   tree init_auto = listify (auto_node);
17911   tree argvec = make_tree_vec (1);
17912   TREE_VEC_ELT (argvec, 0) = init_auto;
17913   if (processing_template_decl)
17914     argvec = add_to_template_args (current_template_args (), argvec);
17915   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17916 }
17917
17918 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
17919    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
17920
17921 tree
17922 do_auto_deduction (tree type, tree init, tree auto_node)
17923 {
17924   tree parms, tparms, targs;
17925   tree args[1];
17926   int val;
17927
17928   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
17929      with either a new invented type template parameter U or, if the
17930      initializer is a braced-init-list (8.5.4), with
17931      std::initializer_list<U>.  */
17932   if (BRACE_ENCLOSED_INITIALIZER_P (init))
17933     type = listify_autos (type, auto_node);
17934
17935   parms = build_tree_list (NULL_TREE, type);
17936   args[0] = init;
17937   tparms = make_tree_vec (1);
17938   targs = make_tree_vec (1);
17939   TREE_VEC_ELT (tparms, 0)
17940     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
17941   val = type_unification_real (tparms, targs, parms, args, 1, 0,
17942                                DEDUCE_CALL, LOOKUP_NORMAL);
17943   if (val > 0)
17944     {
17945       error ("unable to deduce %qT from %qE", type, init);
17946       return error_mark_node;
17947     }
17948
17949   /* If the list of declarators contains more than one declarator, the type
17950      of each declared variable is determined as described above. If the
17951      type deduced for the template parameter U is not the same in each
17952      deduction, the program is ill-formed.  */
17953   if (TREE_TYPE (auto_node)
17954       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
17955     {
17956       error ("inconsistent deduction for %qT: %qT and then %qT",
17957              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
17958       return error_mark_node;
17959     }
17960   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
17961
17962   if (processing_template_decl)
17963     targs = add_to_template_args (current_template_args (), targs);
17964   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
17965 }
17966
17967 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
17968    result.  */
17969
17970 tree
17971 splice_late_return_type (tree type, tree late_return_type)
17972 {
17973   tree argvec;
17974
17975   if (late_return_type == NULL_TREE)
17976     return type;
17977   argvec = make_tree_vec (1);
17978   TREE_VEC_ELT (argvec, 0) = late_return_type;
17979   if (processing_template_decl)
17980     argvec = add_to_template_args (current_template_args (), argvec);
17981   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17982 }
17983
17984 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
17985
17986 bool
17987 is_auto (const_tree type)
17988 {
17989   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17990       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
17991     return true;
17992   else
17993     return false;
17994 }
17995
17996 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
17997    appear as a type-specifier for the declaration in question, we don't
17998    have to look through the whole type.  */
17999
18000 tree
18001 type_uses_auto (tree type)
18002 {
18003   enum tree_code code;
18004   if (is_auto (type))
18005     return type;
18006
18007   code = TREE_CODE (type);
18008
18009   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18010       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18011       || code == METHOD_TYPE || code == ARRAY_TYPE)
18012     return type_uses_auto (TREE_TYPE (type));
18013
18014   if (TYPE_PTRMEMFUNC_P (type))
18015     return type_uses_auto (TREE_TYPE (TREE_TYPE
18016                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18017
18018   return NULL_TREE;
18019 }
18020
18021 /* For a given template T, return the list of typedefs referenced
18022    in T for which access check is needed at T instantiation time.
18023    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18024    Those typedefs were added to T by the function
18025    append_type_to_template_for_access_check.  */
18026
18027 tree
18028 get_types_needing_access_check (tree t)
18029 {
18030   tree ti, result = NULL_TREE;
18031
18032   if (!t || t == error_mark_node)
18033     return t;
18034
18035   if (!(ti = get_template_info (t)))
18036     return NULL_TREE;
18037
18038   if (CLASS_TYPE_P (t)
18039       || TREE_CODE (t) == FUNCTION_DECL)
18040     {
18041       if (!TI_TEMPLATE (ti))
18042         return NULL_TREE;
18043
18044       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18045     }
18046
18047   return result;
18048 }
18049
18050 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
18051    tied to T. That list of typedefs will be access checked at
18052    T instantiation time.
18053    T is either a FUNCTION_DECL or a RECORD_TYPE.
18054    TYPE_DECL is a TYPE_DECL node representing a typedef.
18055    SCOPE is the scope through which TYPE_DECL is accessed.
18056
18057    This function is a subroutine of
18058    append_type_to_template_for_access_check.  */
18059
18060 static void
18061 append_type_to_template_for_access_check_1 (tree t,
18062                                             tree type_decl,
18063                                             tree scope)
18064 {
18065   tree ti;
18066
18067   if (!t || t == error_mark_node)
18068     return;
18069
18070   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18071                || CLASS_TYPE_P (t))
18072               && type_decl
18073               && TREE_CODE (type_decl) == TYPE_DECL
18074               && scope);
18075
18076   if (!(ti = get_template_info (t)))
18077     return;
18078
18079   gcc_assert (TI_TEMPLATE (ti));
18080
18081   TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti) =
18082     tree_cons (type_decl, scope, TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti));
18083 }
18084
18085 /* Append TYPE_DECL to the template TEMPL.
18086    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18087    At TEMPL instanciation time, TYPE_DECL will be checked to see
18088    if it can be accessed through SCOPE.
18089
18090    e.g. consider the following code snippet:
18091
18092      class C
18093      {
18094        typedef int myint;
18095      };
18096
18097      template<class U> struct S
18098      {
18099        C::myint mi;
18100      };
18101
18102      S<char> s;
18103
18104    At S<char> instantiation time, we need to check the access of C::myint
18105    In other words, we need to check the access of the myint typedef through
18106    the C scope. For that purpose, this function will add the myint typedef
18107    and the scope C through which its being accessed to a list of typedefs
18108    tied to the template S. That list will be walked at template instantiation
18109    time and access check performed on each typedefs it contains.
18110    Note that this particular code snippet should yield an error because
18111    myint is private to C.  */
18112
18113 void
18114 append_type_to_template_for_access_check (tree templ,
18115                                           tree type_decl,
18116                                           tree scope)
18117 {
18118   tree node;
18119
18120   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18121
18122   /* Make sure we don't append the type to the template twice.  */
18123   for (node = get_types_needing_access_check (templ);
18124        node;
18125        node = TREE_CHAIN (node))
18126     {
18127       tree decl = TREE_PURPOSE (node);
18128       tree type_scope = TREE_VALUE (node);
18129
18130       if (decl == type_decl && type_scope == scope)
18131         return;
18132     }
18133
18134   append_type_to_template_for_access_check_1 (templ, type_decl, scope);
18135 }
18136
18137 /* Set up the hash tables for template instantiations.  */
18138
18139 void
18140 init_template_processing (void)
18141 {
18142   decl_specializations = htab_create_ggc (37,
18143                                           hash_specialization,
18144                                           eq_specializations,
18145                                           ggc_free);
18146   type_specializations = htab_create_ggc (37,
18147                                           hash_specialization,
18148                                           eq_specializations,
18149                                           ggc_free);
18150 }
18151
18152 #include "gt-cp-pt.h"