OSDN Git Service

9c82e3c19a5885d658680a88e9198388e5129f6d
[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       candidates = 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 (arg == NULL_TREE)
3154         return args;
3155       if (ARGUMENT_PACK_P (arg))
3156         {
3157           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3158           if (num_result_args < 0)
3159             num_result_args = in_arg + num_packed;
3160           else
3161             num_result_args += num_packed;
3162         }
3163       else
3164         {
3165           if (num_result_args >= 0)
3166             num_result_args++;
3167         }
3168     }
3169
3170   /* If no expansion is necessary, we're done.  */
3171   if (num_result_args < 0)
3172     return args;
3173
3174   /* Expand arguments.  */
3175   result_args = make_tree_vec (num_result_args);
3176   for (in_arg = 0; in_arg < nargs; ++in_arg)
3177     {
3178       tree arg = TREE_VEC_ELT (args, in_arg);
3179       if (ARGUMENT_PACK_P (arg))
3180         {
3181           tree packed = ARGUMENT_PACK_ARGS (arg);
3182           int i, num_packed = TREE_VEC_LENGTH (packed);
3183           for (i = 0; i < num_packed; ++i, ++out_arg)
3184             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3185         }
3186       else
3187         {
3188           TREE_VEC_ELT (result_args, out_arg) = arg;
3189           ++out_arg;
3190         }
3191     }
3192
3193   return result_args;
3194 }
3195
3196 /* Checks if DECL shadows a template parameter.
3197
3198    [temp.local]: A template-parameter shall not be redeclared within its
3199    scope (including nested scopes).
3200
3201    Emits an error and returns TRUE if the DECL shadows a parameter,
3202    returns FALSE otherwise.  */
3203
3204 bool
3205 check_template_shadow (tree decl)
3206 {
3207   tree olddecl;
3208
3209   /* If we're not in a template, we can't possibly shadow a template
3210      parameter.  */
3211   if (!current_template_parms)
3212     return true;
3213
3214   /* Figure out what we're shadowing.  */
3215   if (TREE_CODE (decl) == OVERLOAD)
3216     decl = OVL_CURRENT (decl);
3217   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3218
3219   /* If there's no previous binding for this name, we're not shadowing
3220      anything, let alone a template parameter.  */
3221   if (!olddecl)
3222     return true;
3223
3224   /* If we're not shadowing a template parameter, we're done.  Note
3225      that OLDDECL might be an OVERLOAD (or perhaps even an
3226      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3227      node.  */
3228   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3229     return true;
3230
3231   /* We check for decl != olddecl to avoid bogus errors for using a
3232      name inside a class.  We check TPFI to avoid duplicate errors for
3233      inline member templates.  */
3234   if (decl == olddecl
3235       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3236     return true;
3237
3238   error ("declaration of %q+#D", decl);
3239   error (" shadows template parm %q+#D", olddecl);
3240   return false;
3241 }
3242
3243 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3244    ORIG_LEVEL, DECL, and TYPE.  */
3245
3246 static tree
3247 build_template_parm_index (int index,
3248                            int level,
3249                            int orig_level,
3250                            tree decl,
3251                            tree type)
3252 {
3253   tree t = make_node (TEMPLATE_PARM_INDEX);
3254   TEMPLATE_PARM_IDX (t) = index;
3255   TEMPLATE_PARM_LEVEL (t) = level;
3256   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3257   TEMPLATE_PARM_DECL (t) = decl;
3258   TREE_TYPE (t) = type;
3259   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3260   TREE_READONLY (t) = TREE_READONLY (decl);
3261
3262   return t;
3263 }
3264
3265 /* Find the canonical type parameter for the given template type
3266    parameter.  Returns the canonical type parameter, which may be TYPE
3267    if no such parameter existed.  */
3268 static tree
3269 canonical_type_parameter (tree type)
3270 {
3271   tree list;
3272   int idx = TEMPLATE_TYPE_IDX (type);
3273   if (!canonical_template_parms)
3274     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3275
3276   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3277     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3278
3279   list = VEC_index (tree, canonical_template_parms, idx);
3280   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3281     list = TREE_CHAIN (list);
3282
3283   if (list)
3284     return TREE_VALUE (list);
3285   else
3286     {
3287       VEC_replace(tree, canonical_template_parms, idx,
3288                   tree_cons (NULL_TREE, type, 
3289                              VEC_index (tree, canonical_template_parms, idx)));
3290       return type;
3291     }
3292 }
3293
3294 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3295    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3296    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3297    new one is created.  */
3298
3299 static tree
3300 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3301                             tsubst_flags_t complain)
3302 {
3303   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3304       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3305           != TEMPLATE_PARM_LEVEL (index) - levels))
3306     {
3307       tree orig_decl = TEMPLATE_PARM_DECL (index);
3308       tree decl, t;
3309
3310       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3311                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3312       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3313       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3314       DECL_ARTIFICIAL (decl) = 1;
3315       SET_DECL_TEMPLATE_PARM_P (decl);
3316
3317       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3318                                      TEMPLATE_PARM_LEVEL (index) - levels,
3319                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3320                                      decl, type);
3321       TEMPLATE_PARM_DESCENDANTS (index) = t;
3322       TEMPLATE_PARM_PARAMETER_PACK (t) 
3323         = TEMPLATE_PARM_PARAMETER_PACK (index);
3324
3325         /* Template template parameters need this.  */
3326       if (TREE_CODE (decl) == TEMPLATE_DECL)
3327         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3328           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3329            args, complain);
3330     }
3331
3332   return TEMPLATE_PARM_DESCENDANTS (index);
3333 }
3334
3335 /* Process information from new template parameter PARM and append it to the
3336    LIST being built.  This new parameter is a non-type parameter iff
3337    IS_NON_TYPE is true. This new parameter is a parameter
3338    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3339    PARM_LOC.  */
3340
3341 tree
3342 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3343                        bool is_parameter_pack)
3344 {
3345   tree decl = 0;
3346   tree defval;
3347   tree err_parm_list;
3348   int idx = 0;
3349
3350   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3351   defval = TREE_PURPOSE (parm);
3352
3353   if (list)
3354     {
3355       tree p = tree_last (list);
3356
3357       if (p && TREE_VALUE (p) != error_mark_node)
3358         {
3359           p = TREE_VALUE (p);
3360           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3361             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3362           else
3363             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3364         }
3365
3366       ++idx;
3367     }
3368   else
3369     idx = 0;
3370
3371   if (is_non_type)
3372     {
3373       parm = TREE_VALUE (parm);
3374
3375       SET_DECL_TEMPLATE_PARM_P (parm);
3376
3377       if (TREE_TYPE (parm) == error_mark_node)
3378         {
3379           err_parm_list = build_tree_list (defval, parm);
3380           TREE_VALUE (err_parm_list) = error_mark_node;
3381            return chainon (list, err_parm_list);
3382         }
3383       else
3384       {
3385         /* [temp.param]
3386
3387            The top-level cv-qualifiers on the template-parameter are
3388            ignored when determining its type.  */
3389         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3390         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3391           {
3392             err_parm_list = build_tree_list (defval, parm);
3393             TREE_VALUE (err_parm_list) = error_mark_node;
3394              return chainon (list, err_parm_list);
3395           }
3396
3397         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3398           {
3399             /* This template parameter is not a parameter pack, but it
3400                should be. Complain about "bare" parameter packs.  */
3401             check_for_bare_parameter_packs (TREE_TYPE (parm));
3402             
3403             /* Recover by calling this a parameter pack.  */
3404             is_parameter_pack = true;
3405           }
3406       }
3407
3408       /* A template parameter is not modifiable.  */
3409       TREE_CONSTANT (parm) = 1;
3410       TREE_READONLY (parm) = 1;
3411       decl = build_decl (parm_loc,
3412                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3413       TREE_CONSTANT (decl) = 1;
3414       TREE_READONLY (decl) = 1;
3415       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3416         = build_template_parm_index (idx, processing_template_decl,
3417                                      processing_template_decl,
3418                                      decl, TREE_TYPE (parm));
3419
3420       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3421         = is_parameter_pack;
3422     }
3423   else
3424     {
3425       tree t;
3426       parm = TREE_VALUE (TREE_VALUE (parm));
3427
3428       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3429         {
3430           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3431           /* This is for distinguishing between real templates and template
3432              template parameters */
3433           TREE_TYPE (parm) = t;
3434           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3435           decl = parm;
3436         }
3437       else
3438         {
3439           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3440           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3441           decl = build_decl (parm_loc,
3442                              TYPE_DECL, parm, t);
3443         }
3444
3445       TYPE_NAME (t) = decl;
3446       TYPE_STUB_DECL (t) = decl;
3447       parm = decl;
3448       TEMPLATE_TYPE_PARM_INDEX (t)
3449         = build_template_parm_index (idx, processing_template_decl,
3450                                      processing_template_decl,
3451                                      decl, TREE_TYPE (parm));
3452       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3453       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3454     }
3455   DECL_ARTIFICIAL (decl) = 1;
3456   SET_DECL_TEMPLATE_PARM_P (decl);
3457   pushdecl (decl);
3458   parm = build_tree_list (defval, parm);
3459   return chainon (list, parm);
3460 }
3461
3462 /* The end of a template parameter list has been reached.  Process the
3463    tree list into a parameter vector, converting each parameter into a more
3464    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3465    as PARM_DECLs.  */
3466
3467 tree
3468 end_template_parm_list (tree parms)
3469 {
3470   int nparms;
3471   tree parm, next;
3472   tree saved_parmlist = make_tree_vec (list_length (parms));
3473
3474   current_template_parms
3475     = tree_cons (size_int (processing_template_decl),
3476                  saved_parmlist, current_template_parms);
3477
3478   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3479     {
3480       next = TREE_CHAIN (parm);
3481       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3482       TREE_CHAIN (parm) = NULL_TREE;
3483     }
3484
3485   --processing_template_parmlist;
3486
3487   return saved_parmlist;
3488 }
3489
3490 /* end_template_decl is called after a template declaration is seen.  */
3491
3492 void
3493 end_template_decl (void)
3494 {
3495   reset_specialization ();
3496
3497   if (! processing_template_decl)
3498     return;
3499
3500   /* This matches the pushlevel in begin_template_parm_list.  */
3501   finish_scope ();
3502
3503   --processing_template_decl;
3504   current_template_parms = TREE_CHAIN (current_template_parms);
3505 }
3506
3507 /* Within the declaration of a template, return all levels of template
3508    parameters that apply.  The template parameters are represented as
3509    a TREE_VEC, in the form documented in cp-tree.h for template
3510    arguments.  */
3511
3512 static tree
3513 current_template_args (void)
3514 {
3515   tree header;
3516   tree args = NULL_TREE;
3517   int length = TMPL_PARMS_DEPTH (current_template_parms);
3518   int l = length;
3519
3520   /* If there is only one level of template parameters, we do not
3521      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3522      TREE_VEC containing the arguments.  */
3523   if (length > 1)
3524     args = make_tree_vec (length);
3525
3526   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3527     {
3528       tree a = copy_node (TREE_VALUE (header));
3529       int i;
3530
3531       TREE_TYPE (a) = NULL_TREE;
3532       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3533         {
3534           tree t = TREE_VEC_ELT (a, i);
3535
3536           /* T will be a list if we are called from within a
3537              begin/end_template_parm_list pair, but a vector directly
3538              if within a begin/end_member_template_processing pair.  */
3539           if (TREE_CODE (t) == TREE_LIST)
3540             {
3541               t = TREE_VALUE (t);
3542
3543               if (!error_operand_p (t))
3544                 {
3545                   if (TREE_CODE (t) == TYPE_DECL
3546                       || TREE_CODE (t) == TEMPLATE_DECL)
3547                     {
3548                       t = TREE_TYPE (t);
3549                       
3550                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3551                         {
3552                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3553                              with a single element, which expands T.  */
3554                           tree vec = make_tree_vec (1);
3555                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3556                           
3557                           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3558                           SET_ARGUMENT_PACK_ARGS (t, vec);
3559                         }
3560                     }
3561                   else
3562                     {
3563                       t = DECL_INITIAL (t);
3564                       
3565                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3566                         {
3567                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3568                              with a single element, which expands T.  */
3569                           tree vec = make_tree_vec (1);
3570                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3571                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3572                           
3573                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3574                           SET_ARGUMENT_PACK_ARGS (t, vec);
3575                           TREE_TYPE (t) = type;
3576                         }
3577                     }
3578                   TREE_VEC_ELT (a, i) = t;
3579                 }
3580             }
3581         }
3582
3583       if (length > 1)
3584         TREE_VEC_ELT (args, --l) = a;
3585       else
3586         args = a;
3587     }
3588
3589   return args;
3590 }
3591
3592 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3593    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3594    a member template.  Used by push_template_decl below.  */
3595
3596 static tree
3597 build_template_decl (tree decl, tree parms, bool member_template_p)
3598 {
3599   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3600   DECL_TEMPLATE_PARMS (tmpl) = parms;
3601   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3602   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3603
3604   return tmpl;
3605 }
3606
3607 struct template_parm_data
3608 {
3609   /* The level of the template parameters we are currently
3610      processing.  */
3611   int level;
3612
3613   /* The index of the specialization argument we are currently
3614      processing.  */
3615   int current_arg;
3616
3617   /* An array whose size is the number of template parameters.  The
3618      elements are nonzero if the parameter has been used in any one
3619      of the arguments processed so far.  */
3620   int* parms;
3621
3622   /* An array whose size is the number of template arguments.  The
3623      elements are nonzero if the argument makes use of template
3624      parameters of this level.  */
3625   int* arg_uses_template_parms;
3626 };
3627
3628 /* Subroutine of push_template_decl used to see if each template
3629    parameter in a partial specialization is used in the explicit
3630    argument list.  If T is of the LEVEL given in DATA (which is
3631    treated as a template_parm_data*), then DATA->PARMS is marked
3632    appropriately.  */
3633
3634 static int
3635 mark_template_parm (tree t, void* data)
3636 {
3637   int level;
3638   int idx;
3639   struct template_parm_data* tpd = (struct template_parm_data*) data;
3640
3641   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3642     {
3643       level = TEMPLATE_PARM_LEVEL (t);
3644       idx = TEMPLATE_PARM_IDX (t);
3645     }
3646   else
3647     {
3648       level = TEMPLATE_TYPE_LEVEL (t);
3649       idx = TEMPLATE_TYPE_IDX (t);
3650     }
3651
3652   if (level == tpd->level)
3653     {
3654       tpd->parms[idx] = 1;
3655       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3656     }
3657
3658   /* Return zero so that for_each_template_parm will continue the
3659      traversal of the tree; we want to mark *every* template parm.  */
3660   return 0;
3661 }
3662
3663 /* Process the partial specialization DECL.  */
3664
3665 static tree
3666 process_partial_specialization (tree decl)
3667 {
3668   tree type = TREE_TYPE (decl);
3669   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3670   tree specargs = CLASSTYPE_TI_ARGS (type);
3671   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3672   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3673   tree inner_parms;
3674   int nargs = TREE_VEC_LENGTH (inner_args);
3675   int ntparms;
3676   int  i;
3677   int did_error_intro = 0;
3678   struct template_parm_data tpd;
3679   struct template_parm_data tpd2;
3680
3681   gcc_assert (current_template_parms);
3682
3683   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3684   ntparms = TREE_VEC_LENGTH (inner_parms);
3685
3686   /* We check that each of the template parameters given in the
3687      partial specialization is used in the argument list to the
3688      specialization.  For example:
3689
3690        template <class T> struct S;
3691        template <class T> struct S<T*>;
3692
3693      The second declaration is OK because `T*' uses the template
3694      parameter T, whereas
3695
3696        template <class T> struct S<int>;
3697
3698      is no good.  Even trickier is:
3699
3700        template <class T>
3701        struct S1
3702        {
3703           template <class U>
3704           struct S2;
3705           template <class U>
3706           struct S2<T>;
3707        };
3708
3709      The S2<T> declaration is actually invalid; it is a
3710      full-specialization.  Of course,
3711
3712           template <class U>
3713           struct S2<T (*)(U)>;
3714
3715      or some such would have been OK.  */
3716   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3717   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3718   memset (tpd.parms, 0, sizeof (int) * ntparms);
3719
3720   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3721   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3722   for (i = 0; i < nargs; ++i)
3723     {
3724       tpd.current_arg = i;
3725       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3726                               &mark_template_parm,
3727                               &tpd,
3728                               NULL,
3729                               /*include_nondeduced_p=*/false);
3730     }
3731   for (i = 0; i < ntparms; ++i)
3732     if (tpd.parms[i] == 0)
3733       {
3734         /* One of the template parms was not used in the
3735            specialization.  */
3736         if (!did_error_intro)
3737           {
3738             error ("template parameters not used in partial specialization:");
3739             did_error_intro = 1;
3740           }
3741
3742         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3743       }
3744
3745   /* [temp.class.spec]
3746
3747      The argument list of the specialization shall not be identical to
3748      the implicit argument list of the primary template.  */
3749   if (comp_template_args
3750       (inner_args,
3751        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3752                                                    (maintmpl)))))
3753     error ("partial specialization %qT does not specialize any template arguments", type);
3754
3755   /* [temp.class.spec]
3756
3757      A partially specialized non-type argument expression shall not
3758      involve template parameters of the partial specialization except
3759      when the argument expression is a simple identifier.
3760
3761      The type of a template parameter corresponding to a specialized
3762      non-type argument shall not be dependent on a parameter of the
3763      specialization. 
3764
3765      Also, we verify that pack expansions only occur at the
3766      end of the argument list.  */
3767   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3768   tpd2.parms = 0;
3769   for (i = 0; i < nargs; ++i)
3770     {
3771       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3772       tree arg = TREE_VEC_ELT (inner_args, i);
3773       tree packed_args = NULL_TREE;
3774       int j, len = 1;
3775
3776       if (ARGUMENT_PACK_P (arg))
3777         {
3778           /* Extract the arguments from the argument pack. We'll be
3779              iterating over these in the following loop.  */
3780           packed_args = ARGUMENT_PACK_ARGS (arg);
3781           len = TREE_VEC_LENGTH (packed_args);
3782         }
3783
3784       for (j = 0; j < len; j++)
3785         {
3786           if (packed_args)
3787             /* Get the Jth argument in the parameter pack.  */
3788             arg = TREE_VEC_ELT (packed_args, j);
3789
3790           if (PACK_EXPANSION_P (arg))
3791             {
3792               /* Pack expansions must come at the end of the
3793                  argument list.  */
3794               if ((packed_args && j < len - 1)
3795                   || (!packed_args && i < nargs - 1))
3796                 {
3797                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3798                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3799                   else
3800                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3801
3802                   if (packed_args)
3803                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3804                 }
3805             }
3806
3807           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3808             /* We only care about the pattern.  */
3809             arg = PACK_EXPANSION_PATTERN (arg);
3810
3811           if (/* These first two lines are the `non-type' bit.  */
3812               !TYPE_P (arg)
3813               && TREE_CODE (arg) != TEMPLATE_DECL
3814               /* This next line is the `argument expression is not just a
3815                  simple identifier' condition and also the `specialized
3816                  non-type argument' bit.  */
3817               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3818             {
3819               if ((!packed_args && tpd.arg_uses_template_parms[i])
3820                   || (packed_args && uses_template_parms (arg)))
3821                 error ("template argument %qE involves template parameter(s)",
3822                        arg);
3823               else 
3824                 {
3825                   /* Look at the corresponding template parameter,
3826                      marking which template parameters its type depends
3827                      upon.  */
3828                   tree type = TREE_TYPE (parm);
3829
3830                   if (!tpd2.parms)
3831                     {
3832                       /* We haven't yet initialized TPD2.  Do so now.  */
3833                       tpd2.arg_uses_template_parms 
3834                         = (int *) alloca (sizeof (int) * nargs);
3835                       /* The number of parameters here is the number in the
3836                          main template, which, as checked in the assertion
3837                          above, is NARGS.  */
3838                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3839                       tpd2.level = 
3840                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3841                     }
3842
3843                   /* Mark the template parameters.  But this time, we're
3844                      looking for the template parameters of the main
3845                      template, not in the specialization.  */
3846                   tpd2.current_arg = i;
3847                   tpd2.arg_uses_template_parms[i] = 0;
3848                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3849                   for_each_template_parm (type,
3850                                           &mark_template_parm,
3851                                           &tpd2,
3852                                           NULL,
3853                                           /*include_nondeduced_p=*/false);
3854
3855                   if (tpd2.arg_uses_template_parms [i])
3856                     {
3857                       /* The type depended on some template parameters.
3858                          If they are fully specialized in the
3859                          specialization, that's OK.  */
3860                       int j;
3861                       for (j = 0; j < nargs; ++j)
3862                         if (tpd2.parms[j] != 0
3863                             && tpd.arg_uses_template_parms [j])
3864                           {
3865                             error ("type %qT of template argument %qE depends "
3866                                    "on template parameter(s)", 
3867                                    type,
3868                                    arg);
3869                             break;
3870                           }
3871                     }
3872                 }
3873             }
3874         }
3875     }
3876
3877   /* We should only get here once.  */
3878   gcc_assert (!COMPLETE_TYPE_P (type));
3879
3880   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3881     = tree_cons (specargs, inner_parms,
3882                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3883   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3884   return decl;
3885 }
3886
3887 /* Check that a template declaration's use of default arguments and
3888    parameter packs is not invalid.  Here, PARMS are the template
3889    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3890    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3891    specialization.
3892    
3893
3894    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3895    declaration (but not a definition); 1 indicates a declaration, 2
3896    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3897    emitted for extraneous default arguments.
3898
3899    Returns TRUE if there were no errors found, FALSE otherwise. */
3900
3901 bool
3902 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3903                          int is_partial, int is_friend_decl)
3904 {
3905   const char *msg;
3906   int last_level_to_check;
3907   tree parm_level;
3908   bool no_errors = true;
3909
3910   /* [temp.param]
3911
3912      A default template-argument shall not be specified in a
3913      function template declaration or a function template definition, nor
3914      in the template-parameter-list of the definition of a member of a
3915      class template.  */
3916
3917   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3918     /* You can't have a function template declaration in a local
3919        scope, nor you can you define a member of a class template in a
3920        local scope.  */
3921     return true;
3922
3923   if (current_class_type
3924       && !TYPE_BEING_DEFINED (current_class_type)
3925       && DECL_LANG_SPECIFIC (decl)
3926       && DECL_DECLARES_FUNCTION_P (decl)
3927       /* If this is either a friend defined in the scope of the class
3928          or a member function.  */
3929       && (DECL_FUNCTION_MEMBER_P (decl)
3930           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3931           : DECL_FRIEND_CONTEXT (decl)
3932           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3933           : false)
3934       /* And, if it was a member function, it really was defined in
3935          the scope of the class.  */
3936       && (!DECL_FUNCTION_MEMBER_P (decl)
3937           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3938     /* We already checked these parameters when the template was
3939        declared, so there's no need to do it again now.  This function
3940        was defined in class scope, but we're processing it's body now
3941        that the class is complete.  */
3942     return true;
3943
3944   /* Core issue 226 (C++0x only): the following only applies to class
3945      templates.  */
3946   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3947     {
3948       /* [temp.param]
3949
3950          If a template-parameter has a default template-argument, all
3951          subsequent template-parameters shall have a default
3952          template-argument supplied.  */
3953       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3954         {
3955           tree inner_parms = TREE_VALUE (parm_level);
3956           int ntparms = TREE_VEC_LENGTH (inner_parms);
3957           int seen_def_arg_p = 0;
3958           int i;
3959
3960           for (i = 0; i < ntparms; ++i)
3961             {
3962               tree parm = TREE_VEC_ELT (inner_parms, i);
3963
3964               if (parm == error_mark_node)
3965                 continue;
3966
3967               if (TREE_PURPOSE (parm))
3968                 seen_def_arg_p = 1;
3969               else if (seen_def_arg_p
3970                        && !template_parameter_pack_p (TREE_VALUE (parm)))
3971                 {
3972                   error ("no default argument for %qD", TREE_VALUE (parm));
3973                   /* For better subsequent error-recovery, we indicate that
3974                      there should have been a default argument.  */
3975                   TREE_PURPOSE (parm) = error_mark_node;
3976                   no_errors = false;
3977                 }
3978               else if (is_primary
3979                        && !is_partial
3980                        && !is_friend_decl
3981                        /* Don't complain about an enclosing partial
3982                           specialization.  */
3983                        && parm_level == parms
3984                        && TREE_CODE (decl) == TYPE_DECL
3985                        && i < ntparms - 1
3986                        && template_parameter_pack_p (TREE_VALUE (parm)))
3987                 {
3988                   /* A primary class template can only have one
3989                      parameter pack, at the end of the template
3990                      parameter list.  */
3991
3992                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
3993                     error ("parameter pack %qE must be at the end of the"
3994                            " template parameter list", TREE_VALUE (parm));
3995                   else
3996                     error ("parameter pack %qT must be at the end of the"
3997                            " template parameter list", 
3998                            TREE_TYPE (TREE_VALUE (parm)));
3999
4000                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4001                     = error_mark_node;
4002                   no_errors = false;
4003                 }
4004             }
4005         }
4006     }
4007
4008   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4009       || is_partial 
4010       || !is_primary
4011       || is_friend_decl)
4012     /* For an ordinary class template, default template arguments are
4013        allowed at the innermost level, e.g.:
4014          template <class T = int>
4015          struct S {};
4016        but, in a partial specialization, they're not allowed even
4017        there, as we have in [temp.class.spec]:
4018
4019          The template parameter list of a specialization shall not
4020          contain default template argument values.
4021
4022        So, for a partial specialization, or for a function template
4023        (in C++98/C++03), we look at all of them.  */
4024     ;
4025   else
4026     /* But, for a primary class template that is not a partial
4027        specialization we look at all template parameters except the
4028        innermost ones.  */
4029     parms = TREE_CHAIN (parms);
4030
4031   /* Figure out what error message to issue.  */
4032   if (is_friend_decl == 2)
4033     msg = "default template arguments may not be used in function template friend re-declaration";
4034   else if (is_friend_decl)
4035     msg = "default template arguments may not be used in function template friend declarations";
4036   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4037     msg = ("default template arguments may not be used in function templates "
4038            "without -std=c++0x or -std=gnu++0x");
4039   else if (is_partial)
4040     msg = "default template arguments may not be used in partial specializations";
4041   else
4042     msg = "default argument for template parameter for class enclosing %qD";
4043
4044   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4045     /* If we're inside a class definition, there's no need to
4046        examine the parameters to the class itself.  On the one
4047        hand, they will be checked when the class is defined, and,
4048        on the other, default arguments are valid in things like:
4049          template <class T = double>
4050          struct S { template <class U> void f(U); };
4051        Here the default argument for `S' has no bearing on the
4052        declaration of `f'.  */
4053     last_level_to_check = template_class_depth (current_class_type) + 1;
4054   else
4055     /* Check everything.  */
4056     last_level_to_check = 0;
4057
4058   for (parm_level = parms;
4059        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4060        parm_level = TREE_CHAIN (parm_level))
4061     {
4062       tree inner_parms = TREE_VALUE (parm_level);
4063       int i;
4064       int ntparms;
4065
4066       ntparms = TREE_VEC_LENGTH (inner_parms);
4067       for (i = 0; i < ntparms; ++i)
4068         {
4069           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4070             continue;
4071
4072           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4073             {
4074               if (msg)
4075                 {
4076                   no_errors = false;
4077                   if (is_friend_decl == 2)
4078                     return no_errors;
4079
4080                   error (msg, decl);
4081                   msg = 0;
4082                 }
4083
4084               /* Clear out the default argument so that we are not
4085                  confused later.  */
4086               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4087             }
4088         }
4089
4090       /* At this point, if we're still interested in issuing messages,
4091          they must apply to classes surrounding the object declared.  */
4092       if (msg)
4093         msg = "default argument for template parameter for class enclosing %qD";
4094     }
4095
4096   return no_errors;
4097 }
4098
4099 /* Worker for push_template_decl_real, called via
4100    for_each_template_parm.  DATA is really an int, indicating the
4101    level of the parameters we are interested in.  If T is a template
4102    parameter of that level, return nonzero.  */
4103
4104 static int
4105 template_parm_this_level_p (tree t, void* data)
4106 {
4107   int this_level = *(int *)data;
4108   int level;
4109
4110   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4111     level = TEMPLATE_PARM_LEVEL (t);
4112   else
4113     level = TEMPLATE_TYPE_LEVEL (t);
4114   return level == this_level;
4115 }
4116
4117 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4118    parameters given by current_template_args, or reuses a
4119    previously existing one, if appropriate.  Returns the DECL, or an
4120    equivalent one, if it is replaced via a call to duplicate_decls.
4121
4122    If IS_FRIEND is true, DECL is a friend declaration.  */
4123
4124 tree
4125 push_template_decl_real (tree decl, bool is_friend)
4126 {
4127   tree tmpl;
4128   tree args;
4129   tree info;
4130   tree ctx;
4131   int primary;
4132   int is_partial;
4133   int new_template_p = 0;
4134   /* True if the template is a member template, in the sense of
4135      [temp.mem].  */
4136   bool member_template_p = false;
4137
4138   if (decl == error_mark_node || !current_template_parms)
4139     return error_mark_node;
4140
4141   /* See if this is a partial specialization.  */
4142   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4143                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4144                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4145
4146   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4147     is_friend = true;
4148
4149   if (is_friend)
4150     /* For a friend, we want the context of the friend function, not
4151        the type of which it is a friend.  */
4152     ctx = DECL_CONTEXT (decl);
4153   else if (CP_DECL_CONTEXT (decl)
4154            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4155     /* In the case of a virtual function, we want the class in which
4156        it is defined.  */
4157     ctx = CP_DECL_CONTEXT (decl);
4158   else
4159     /* Otherwise, if we're currently defining some class, the DECL
4160        is assumed to be a member of the class.  */
4161     ctx = current_scope ();
4162
4163   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4164     ctx = NULL_TREE;
4165
4166   if (!DECL_CONTEXT (decl))
4167     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4168
4169   /* See if this is a primary template.  */
4170   if (is_friend && ctx)
4171     /* A friend template that specifies a class context, i.e.
4172          template <typename T> friend void A<T>::f();
4173        is not primary.  */
4174     primary = 0;
4175   else
4176     primary = template_parm_scope_p ();
4177
4178   if (primary)
4179     {
4180       if (DECL_CLASS_SCOPE_P (decl))
4181         member_template_p = true;
4182       if (TREE_CODE (decl) == TYPE_DECL
4183           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4184         {
4185           error ("template class without a name");
4186           return error_mark_node;
4187         }
4188       else if (TREE_CODE (decl) == FUNCTION_DECL)
4189         {
4190           if (DECL_DESTRUCTOR_P (decl))
4191             {
4192               /* [temp.mem]
4193
4194                  A destructor shall not be a member template.  */
4195               error ("destructor %qD declared as member template", decl);
4196               return error_mark_node;
4197             }
4198           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4199               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4200                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4201                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4202                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4203                       == void_list_node)))
4204             {
4205               /* [basic.stc.dynamic.allocation]
4206
4207                  An allocation function can be a function
4208                  template. ... Template allocation functions shall
4209                  have two or more parameters.  */
4210               error ("invalid template declaration of %qD", decl);
4211               return error_mark_node;
4212             }
4213         }
4214       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4215                && CLASS_TYPE_P (TREE_TYPE (decl)))
4216         /* OK */;
4217       else
4218         {
4219           error ("template declaration of %q#D", decl);
4220           return error_mark_node;
4221         }
4222     }
4223
4224   /* Check to see that the rules regarding the use of default
4225      arguments are not being violated.  */
4226   check_default_tmpl_args (decl, current_template_parms,
4227                            primary, is_partial, /*is_friend_decl=*/0);
4228
4229   /* Ensure that there are no parameter packs in the type of this
4230      declaration that have not been expanded.  */
4231   if (TREE_CODE (decl) == FUNCTION_DECL)
4232     {
4233       /* Check each of the arguments individually to see if there are
4234          any bare parameter packs.  */
4235       tree type = TREE_TYPE (decl);
4236       tree arg = DECL_ARGUMENTS (decl);
4237       tree argtype = TYPE_ARG_TYPES (type);
4238
4239       while (arg && argtype)
4240         {
4241           if (!FUNCTION_PARAMETER_PACK_P (arg)
4242               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4243             {
4244             /* This is a PARM_DECL that contains unexpanded parameter
4245                packs. We have already complained about this in the
4246                check_for_bare_parameter_packs call, so just replace
4247                these types with ERROR_MARK_NODE.  */
4248               TREE_TYPE (arg) = error_mark_node;
4249               TREE_VALUE (argtype) = error_mark_node;
4250             }
4251
4252           arg = TREE_CHAIN (arg);
4253           argtype = TREE_CHAIN (argtype);
4254         }
4255
4256       /* Check for bare parameter packs in the return type and the
4257          exception specifiers.  */
4258       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4259         /* Errors were already issued, set return type to int
4260            as the frontend doesn't expect error_mark_node as
4261            the return type.  */
4262         TREE_TYPE (type) = integer_type_node;
4263       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4264         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4265     }
4266   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4267     {
4268       TREE_TYPE (decl) = error_mark_node;
4269       return error_mark_node;
4270     }
4271
4272   if (is_partial)
4273     return process_partial_specialization (decl);
4274
4275   args = current_template_args ();
4276
4277   if (!ctx
4278       || TREE_CODE (ctx) == FUNCTION_DECL
4279       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4280       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4281     {
4282       if (DECL_LANG_SPECIFIC (decl)
4283           && DECL_TEMPLATE_INFO (decl)
4284           && DECL_TI_TEMPLATE (decl))
4285         tmpl = DECL_TI_TEMPLATE (decl);
4286       /* If DECL is a TYPE_DECL for a class-template, then there won't
4287          be DECL_LANG_SPECIFIC.  The information equivalent to
4288          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4289       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4290                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4291                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4292         {
4293           /* Since a template declaration already existed for this
4294              class-type, we must be redeclaring it here.  Make sure
4295              that the redeclaration is valid.  */
4296           redeclare_class_template (TREE_TYPE (decl),
4297                                     current_template_parms);
4298           /* We don't need to create a new TEMPLATE_DECL; just use the
4299              one we already had.  */
4300           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4301         }
4302       else
4303         {
4304           tmpl = build_template_decl (decl, current_template_parms,
4305                                       member_template_p);
4306           new_template_p = 1;
4307
4308           if (DECL_LANG_SPECIFIC (decl)
4309               && DECL_TEMPLATE_SPECIALIZATION (decl))
4310             {
4311               /* A specialization of a member template of a template
4312                  class.  */
4313               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4314               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4315               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4316             }
4317         }
4318     }
4319   else
4320     {
4321       tree a, t, current, parms;
4322       int i;
4323       tree tinfo = get_template_info (decl);
4324
4325       if (!tinfo)
4326         {
4327           error ("template definition of non-template %q#D", decl);
4328           return error_mark_node;
4329         }
4330
4331       tmpl = TI_TEMPLATE (tinfo);
4332
4333       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4334           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4335           && DECL_TEMPLATE_SPECIALIZATION (decl)
4336           && DECL_MEMBER_TEMPLATE_P (tmpl))
4337         {
4338           tree new_tmpl;
4339
4340           /* The declaration is a specialization of a member
4341              template, declared outside the class.  Therefore, the
4342              innermost template arguments will be NULL, so we
4343              replace them with the arguments determined by the
4344              earlier call to check_explicit_specialization.  */
4345           args = DECL_TI_ARGS (decl);
4346
4347           new_tmpl
4348             = build_template_decl (decl, current_template_parms,
4349                                    member_template_p);
4350           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4351           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4352           DECL_TI_TEMPLATE (decl) = new_tmpl;
4353           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4354           DECL_TEMPLATE_INFO (new_tmpl)
4355             = tree_cons (tmpl, args, NULL_TREE);
4356
4357           register_specialization (new_tmpl,
4358                                    most_general_template (tmpl),
4359                                    args,
4360                                    is_friend, 0);
4361           return decl;
4362         }
4363
4364       /* Make sure the template headers we got make sense.  */
4365
4366       parms = DECL_TEMPLATE_PARMS (tmpl);
4367       i = TMPL_PARMS_DEPTH (parms);
4368       if (TMPL_ARGS_DEPTH (args) != i)
4369         {
4370           error ("expected %d levels of template parms for %q#D, got %d",
4371                  i, decl, TMPL_ARGS_DEPTH (args));
4372         }
4373       else
4374         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4375           {
4376             a = TMPL_ARGS_LEVEL (args, i);
4377             t = INNERMOST_TEMPLATE_PARMS (parms);
4378
4379             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4380               {
4381                 if (current == decl)
4382                   error ("got %d template parameters for %q#D",
4383                          TREE_VEC_LENGTH (a), decl);
4384                 else
4385                   error ("got %d template parameters for %q#T",
4386                          TREE_VEC_LENGTH (a), current);
4387                 error ("  but %d required", TREE_VEC_LENGTH (t));
4388                 return error_mark_node;
4389               }
4390
4391             if (current == decl)
4392               current = ctx;
4393             else
4394               current = (TYPE_P (current)
4395                          ? TYPE_CONTEXT (current)
4396                          : DECL_CONTEXT (current));
4397           }
4398
4399       /* Check that the parms are used in the appropriate qualifying scopes
4400          in the declarator.  */
4401       if (!comp_template_args
4402           (TI_ARGS (tinfo),
4403            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4404         {
4405           error ("\
4406 template arguments to %qD do not match original template %qD",
4407                  decl, DECL_TEMPLATE_RESULT (tmpl));
4408           if (!uses_template_parms (TI_ARGS (tinfo)))
4409             inform (input_location, "use template<> for an explicit specialization");
4410           /* Avoid crash in import_export_decl.  */
4411           DECL_INTERFACE_KNOWN (decl) = 1;
4412           return error_mark_node;
4413         }
4414     }
4415
4416   DECL_TEMPLATE_RESULT (tmpl) = decl;
4417   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4418
4419   /* Push template declarations for global functions and types.  Note
4420      that we do not try to push a global template friend declared in a
4421      template class; such a thing may well depend on the template
4422      parameters of the class.  */
4423   if (new_template_p && !ctx
4424       && !(is_friend && template_class_depth (current_class_type) > 0))
4425     {
4426       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4427       if (tmpl == error_mark_node)
4428         return error_mark_node;
4429
4430       /* Hide template friend classes that haven't been declared yet.  */
4431       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4432         {
4433           DECL_ANTICIPATED (tmpl) = 1;
4434           DECL_FRIEND_P (tmpl) = 1;
4435         }
4436     }
4437
4438   if (primary)
4439     {
4440       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4441       int i;
4442
4443       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4444       if (DECL_CONV_FN_P (tmpl))
4445         {
4446           int depth = TMPL_PARMS_DEPTH (parms);
4447
4448           /* It is a conversion operator. See if the type converted to
4449              depends on innermost template operands.  */
4450
4451           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4452                                          depth))
4453             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4454         }
4455
4456       /* Give template template parms a DECL_CONTEXT of the template
4457          for which they are a parameter.  */
4458       parms = INNERMOST_TEMPLATE_PARMS (parms);
4459       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4460         {
4461           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4462           if (TREE_CODE (parm) == TEMPLATE_DECL)
4463             DECL_CONTEXT (parm) = tmpl;
4464         }
4465     }
4466
4467   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4468      back to its most general template.  If TMPL is a specialization,
4469      ARGS may only have the innermost set of arguments.  Add the missing
4470      argument levels if necessary.  */
4471   if (DECL_TEMPLATE_INFO (tmpl))
4472     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4473
4474   info = tree_cons (tmpl, args, NULL_TREE);
4475
4476   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4477     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4478   else if (DECL_LANG_SPECIFIC (decl))
4479     DECL_TEMPLATE_INFO (decl) = info;
4480
4481   return DECL_TEMPLATE_RESULT (tmpl);
4482 }
4483
4484 tree
4485 push_template_decl (tree decl)
4486 {
4487   return push_template_decl_real (decl, false);
4488 }
4489
4490 /* Called when a class template TYPE is redeclared with the indicated
4491    template PARMS, e.g.:
4492
4493      template <class T> struct S;
4494      template <class T> struct S {};  */
4495
4496 bool
4497 redeclare_class_template (tree type, tree parms)
4498 {
4499   tree tmpl;
4500   tree tmpl_parms;
4501   int i;
4502
4503   if (!TYPE_TEMPLATE_INFO (type))
4504     {
4505       error ("%qT is not a template type", type);
4506       return false;
4507     }
4508
4509   tmpl = TYPE_TI_TEMPLATE (type);
4510   if (!PRIMARY_TEMPLATE_P (tmpl))
4511     /* The type is nested in some template class.  Nothing to worry
4512        about here; there are no new template parameters for the nested
4513        type.  */
4514     return true;
4515
4516   if (!parms)
4517     {
4518       error ("template specifiers not specified in declaration of %qD",
4519              tmpl);
4520       return false;
4521     }
4522
4523   parms = INNERMOST_TEMPLATE_PARMS (parms);
4524   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4525
4526   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4527     {
4528       error ("redeclared with %d template parameter(s)", 
4529              TREE_VEC_LENGTH (parms));
4530       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4531              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4532       return false;
4533     }
4534
4535   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4536     {
4537       tree tmpl_parm;
4538       tree parm;
4539       tree tmpl_default;
4540       tree parm_default;
4541
4542       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4543           || TREE_VEC_ELT (parms, i) == error_mark_node)
4544         continue;
4545
4546       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4547       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4548       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4549       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4550
4551       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4552          TEMPLATE_DECL.  */
4553       if (tmpl_parm != error_mark_node
4554           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4555               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4556                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4557               || (TREE_CODE (tmpl_parm) != PARM_DECL
4558                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4559                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4560               || (TREE_CODE (tmpl_parm) == PARM_DECL
4561                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4562                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4563         {
4564           error ("template parameter %q+#D", tmpl_parm);
4565           error ("redeclared here as %q#D", parm);
4566           return false;
4567         }
4568
4569       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4570         {
4571           /* We have in [temp.param]:
4572
4573              A template-parameter may not be given default arguments
4574              by two different declarations in the same scope.  */
4575           error_at (input_location, "redefinition of default argument for %q#D", parm);
4576           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4577                   "original definition appeared here");
4578           return false;
4579         }
4580
4581       if (parm_default != NULL_TREE)
4582         /* Update the previous template parameters (which are the ones
4583            that will really count) with the new default value.  */
4584         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4585       else if (tmpl_default != NULL_TREE)
4586         /* Update the new parameters, too; they'll be used as the
4587            parameters for any members.  */
4588         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4589     }
4590
4591     return true;
4592 }
4593
4594 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4595    (possibly simplified) expression.  */
4596
4597 tree
4598 fold_non_dependent_expr (tree expr)
4599 {
4600   if (expr == NULL_TREE)
4601     return NULL_TREE;
4602
4603   /* If we're in a template, but EXPR isn't value dependent, simplify
4604      it.  We're supposed to treat:
4605
4606        template <typename T> void f(T[1 + 1]);
4607        template <typename T> void f(T[2]);
4608
4609      as two declarations of the same function, for example.  */
4610   if (processing_template_decl
4611       && !type_dependent_expression_p (expr)
4612       && !value_dependent_expression_p (expr))
4613     {
4614       HOST_WIDE_INT saved_processing_template_decl;
4615
4616       saved_processing_template_decl = processing_template_decl;
4617       processing_template_decl = 0;
4618       expr = tsubst_copy_and_build (expr,
4619                                     /*args=*/NULL_TREE,
4620                                     tf_error,
4621                                     /*in_decl=*/NULL_TREE,
4622                                     /*function_p=*/false,
4623                                     /*integral_constant_expression_p=*/true);
4624       processing_template_decl = saved_processing_template_decl;
4625     }
4626   return expr;
4627 }
4628
4629 /* EXPR is an expression which is used in a constant-expression context.
4630    For instance, it could be a VAR_DECL with a constant initializer.
4631    Extract the innermost constant expression.
4632
4633    This is basically a more powerful version of
4634    integral_constant_value, which can be used also in templates where
4635    initializers can maintain a syntactic rather than semantic form
4636    (even if they are non-dependent, for access-checking purposes).  */
4637
4638 static tree
4639 fold_decl_constant_value (tree expr)
4640 {
4641   tree const_expr = expr;
4642   do
4643     {
4644       expr = fold_non_dependent_expr (const_expr);
4645       const_expr = integral_constant_value (expr);
4646     }
4647   while (expr != const_expr);
4648
4649   return expr;
4650 }
4651
4652 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4653    must be a function or a pointer-to-function type, as specified
4654    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4655    and check that the resulting function has external linkage.  */
4656
4657 static tree
4658 convert_nontype_argument_function (tree type, tree expr)
4659 {
4660   tree fns = expr;
4661   tree fn, fn_no_ptr;
4662
4663   fn = instantiate_type (type, fns, tf_none);
4664   if (fn == error_mark_node)
4665     return error_mark_node;
4666
4667   fn_no_ptr = fn;
4668   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4669     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4670   if (TREE_CODE (fn_no_ptr) == BASELINK)
4671     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4672  
4673   /* [temp.arg.nontype]/1
4674
4675      A template-argument for a non-type, non-template template-parameter
4676      shall be one of:
4677      [...]
4678      -- the address of an object or function with external linkage.  */
4679   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4680     {
4681       error ("%qE is not a valid template argument for type %qT "
4682              "because function %qD has not external linkage",
4683              expr, type, fn_no_ptr);
4684       return NULL_TREE;
4685     }
4686
4687   return fn;
4688 }
4689
4690 /* Subroutine of convert_nontype_argument.
4691    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4692    Emit an error otherwise.  */
4693
4694 static bool
4695 check_valid_ptrmem_cst_expr (tree type, tree expr)
4696 {
4697   STRIP_NOPS (expr);
4698   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4699     return true;
4700   error ("%qE is not a valid template argument for type %qT",
4701          expr, type);
4702   error ("it must be a pointer-to-member of the form `&X::Y'");
4703   return false;
4704 }
4705
4706 /* Attempt to convert the non-type template parameter EXPR to the
4707    indicated TYPE.  If the conversion is successful, return the
4708    converted value.  If the conversion is unsuccessful, return
4709    NULL_TREE if we issued an error message, or error_mark_node if we
4710    did not.  We issue error messages for out-and-out bad template
4711    parameters, but not simply because the conversion failed, since we
4712    might be just trying to do argument deduction.  Both TYPE and EXPR
4713    must be non-dependent.
4714
4715    The conversion follows the special rules described in
4716    [temp.arg.nontype], and it is much more strict than an implicit
4717    conversion.
4718
4719    This function is called twice for each template argument (see
4720    lookup_template_class for a more accurate description of this
4721    problem). This means that we need to handle expressions which
4722    are not valid in a C++ source, but can be created from the
4723    first call (for instance, casts to perform conversions). These
4724    hacks can go away after we fix the double coercion problem.  */
4725
4726 static tree
4727 convert_nontype_argument (tree type, tree expr)
4728 {
4729   tree expr_type;
4730
4731   /* Detect immediately string literals as invalid non-type argument.
4732      This special-case is not needed for correctness (we would easily
4733      catch this later), but only to provide better diagnostic for this
4734      common user mistake. As suggested by DR 100, we do not mention
4735      linkage issues in the diagnostic as this is not the point.  */
4736   if (TREE_CODE (expr) == STRING_CST)
4737     {
4738       error ("%qE is not a valid template argument for type %qT "
4739              "because string literals can never be used in this context",
4740              expr, type);
4741       return NULL_TREE;
4742     }
4743
4744   /* If we are in a template, EXPR may be non-dependent, but still
4745      have a syntactic, rather than semantic, form.  For example, EXPR
4746      might be a SCOPE_REF, rather than the VAR_DECL to which the
4747      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4748      so that access checking can be performed when the template is
4749      instantiated -- but here we need the resolved form so that we can
4750      convert the argument.  */
4751   expr = fold_non_dependent_expr (expr);
4752   if (error_operand_p (expr))
4753     return error_mark_node;
4754   expr_type = TREE_TYPE (expr);
4755
4756   /* HACK: Due to double coercion, we can get a
4757      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4758      which is the tree that we built on the first call (see
4759      below when coercing to reference to object or to reference to
4760      function). We just strip everything and get to the arg.
4761      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4762      for examples.  */
4763   if (TREE_CODE (expr) == NOP_EXPR)
4764     {
4765       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4766         {
4767           /* ??? Maybe we could use convert_from_reference here, but we
4768              would need to relax its constraints because the NOP_EXPR
4769              could actually change the type to something more cv-qualified,
4770              and this is not folded by convert_from_reference.  */
4771           tree addr = TREE_OPERAND (expr, 0);
4772           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4773           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4774           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4775           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4776                       (TREE_TYPE (expr_type),
4777                        TREE_TYPE (TREE_TYPE (addr))));
4778
4779           expr = TREE_OPERAND (addr, 0);
4780           expr_type = TREE_TYPE (expr);
4781         }
4782
4783       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4784          parameter is a pointer to object, through decay and
4785          qualification conversion. Let's strip everything.  */
4786       else if (TYPE_PTROBV_P (type))
4787         {
4788           STRIP_NOPS (expr);
4789           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4790           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4791           /* Skip the ADDR_EXPR only if it is part of the decay for
4792              an array. Otherwise, it is part of the original argument
4793              in the source code.  */
4794           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4795             expr = TREE_OPERAND (expr, 0);
4796           expr_type = TREE_TYPE (expr);
4797         }
4798     }
4799
4800   /* [temp.arg.nontype]/5, bullet 1
4801
4802      For a non-type template-parameter of integral or enumeration type,
4803      integral promotions (_conv.prom_) and integral conversions
4804      (_conv.integral_) are applied.  */
4805   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4806     {
4807       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4808         return error_mark_node;
4809
4810       expr = fold_decl_constant_value (expr);
4811       /* Notice that there are constant expressions like '4 % 0' which
4812          do not fold into integer constants.  */
4813       if (TREE_CODE (expr) != INTEGER_CST)
4814         {
4815           error ("%qE is not a valid template argument for type %qT "
4816                  "because it is a non-constant expression", expr, type);
4817           return NULL_TREE;
4818         }
4819
4820       /* At this point, an implicit conversion does what we want,
4821          because we already know that the expression is of integral
4822          type.  */
4823       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4824       if (expr == error_mark_node)
4825         return error_mark_node;
4826
4827       /* Conversion was allowed: fold it to a bare integer constant.  */
4828       expr = fold (expr);
4829     }
4830   /* [temp.arg.nontype]/5, bullet 2
4831
4832      For a non-type template-parameter of type pointer to object,
4833      qualification conversions (_conv.qual_) and the array-to-pointer
4834      conversion (_conv.array_) are applied.  */
4835   else if (TYPE_PTROBV_P (type))
4836     {
4837       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4838
4839          A template-argument for a non-type, non-template template-parameter
4840          shall be one of: [...]
4841
4842          -- the name of a non-type template-parameter;
4843          -- the address of an object or function with external linkage, [...]
4844             expressed as "& id-expression" where the & is optional if the name
4845             refers to a function or array, or if the corresponding
4846             template-parameter is a reference.
4847
4848         Here, we do not care about functions, as they are invalid anyway
4849         for a parameter of type pointer-to-object.  */
4850
4851       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4852         /* Non-type template parameters are OK.  */
4853         ;
4854       else if (TREE_CODE (expr) != ADDR_EXPR
4855                && TREE_CODE (expr_type) != ARRAY_TYPE)
4856         {
4857           if (TREE_CODE (expr) == VAR_DECL)
4858             {
4859               error ("%qD is not a valid template argument "
4860                      "because %qD is a variable, not the address of "
4861                      "a variable",
4862                      expr, expr);
4863               return NULL_TREE;
4864             }
4865           /* Other values, like integer constants, might be valid
4866              non-type arguments of some other type.  */
4867           return error_mark_node;
4868         }
4869       else
4870         {
4871           tree decl;
4872
4873           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4874                   ? TREE_OPERAND (expr, 0) : expr);
4875           if (TREE_CODE (decl) != VAR_DECL)
4876             {
4877               error ("%qE is not a valid template argument of type %qT "
4878                      "because %qE is not a variable",
4879                      expr, type, decl);
4880               return NULL_TREE;
4881             }
4882           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4883             {
4884               error ("%qE is not a valid template argument of type %qT "
4885                      "because %qD does not have external linkage",
4886                      expr, type, decl);
4887               return NULL_TREE;
4888             }
4889         }
4890
4891       expr = decay_conversion (expr);
4892       if (expr == error_mark_node)
4893         return error_mark_node;
4894
4895       expr = perform_qualification_conversions (type, expr);
4896       if (expr == error_mark_node)
4897         return error_mark_node;
4898     }
4899   /* [temp.arg.nontype]/5, bullet 3
4900
4901      For a non-type template-parameter of type reference to object, no
4902      conversions apply. The type referred to by the reference may be more
4903      cv-qualified than the (otherwise identical) type of the
4904      template-argument. The template-parameter is bound directly to the
4905      template-argument, which must be an lvalue.  */
4906   else if (TYPE_REF_OBJ_P (type))
4907     {
4908       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4909                                                       expr_type))
4910         return error_mark_node;
4911
4912       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4913         {
4914           error ("%qE is not a valid template argument for type %qT "
4915                  "because of conflicts in cv-qualification", expr, type);
4916           return NULL_TREE;
4917         }
4918
4919       if (!real_lvalue_p (expr))
4920         {
4921           error ("%qE is not a valid template argument for type %qT "
4922                  "because it is not an lvalue", expr, type);
4923           return NULL_TREE;
4924         }
4925
4926       /* [temp.arg.nontype]/1
4927
4928          A template-argument for a non-type, non-template template-parameter
4929          shall be one of: [...]
4930
4931          -- the address of an object or function with external linkage.  */
4932       if (TREE_CODE (expr) == INDIRECT_REF
4933           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
4934         {
4935           expr = TREE_OPERAND (expr, 0);
4936           if (DECL_P (expr))
4937             {
4938               error ("%q#D is not a valid template argument for type %qT "
4939                      "because a reference variable does not have a constant "
4940                      "address", expr, type);
4941               return NULL_TREE;
4942             }
4943         }
4944
4945       if (!DECL_P (expr))
4946         {
4947           error ("%qE is not a valid template argument for type %qT "
4948                  "because it is not an object with external linkage",
4949                  expr, type);
4950           return NULL_TREE;
4951         }
4952
4953       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4954         {
4955           error ("%qE is not a valid template argument for type %qT "
4956                  "because object %qD has not external linkage",
4957                  expr, type, expr);
4958           return NULL_TREE;
4959         }
4960
4961       expr = build_nop (type, build_address (expr));
4962     }
4963   /* [temp.arg.nontype]/5, bullet 4
4964
4965      For a non-type template-parameter of type pointer to function, only
4966      the function-to-pointer conversion (_conv.func_) is applied. If the
4967      template-argument represents a set of overloaded functions (or a
4968      pointer to such), the matching function is selected from the set
4969      (_over.over_).  */
4970   else if (TYPE_PTRFN_P (type))
4971     {
4972       /* If the argument is a template-id, we might not have enough
4973          context information to decay the pointer.  */
4974       if (!type_unknown_p (expr_type))
4975         {
4976           expr = decay_conversion (expr);
4977           if (expr == error_mark_node)
4978             return error_mark_node;
4979         }
4980
4981       expr = convert_nontype_argument_function (type, expr);
4982       if (!expr || expr == error_mark_node)
4983         return expr;
4984
4985       if (TREE_CODE (expr) != ADDR_EXPR)
4986         {
4987           error ("%qE is not a valid template argument for type %qT", expr, type);
4988           error ("it must be the address of a function with external linkage");
4989           return NULL_TREE;
4990         }
4991     }
4992   /* [temp.arg.nontype]/5, bullet 5
4993
4994      For a non-type template-parameter of type reference to function, no
4995      conversions apply. If the template-argument represents a set of
4996      overloaded functions, the matching function is selected from the set
4997      (_over.over_).  */
4998   else if (TYPE_REFFN_P (type))
4999     {
5000       if (TREE_CODE (expr) == ADDR_EXPR)
5001         {
5002           error ("%qE is not a valid template argument for type %qT "
5003                  "because it is a pointer", expr, type);
5004           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5005           return NULL_TREE;
5006         }
5007
5008       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5009       if (!expr || expr == error_mark_node)
5010         return expr;
5011
5012       expr = build_nop (type, build_address (expr));
5013     }
5014   /* [temp.arg.nontype]/5, bullet 6
5015
5016      For a non-type template-parameter of type pointer to member function,
5017      no conversions apply. If the template-argument represents a set of
5018      overloaded member functions, the matching member function is selected
5019      from the set (_over.over_).  */
5020   else if (TYPE_PTRMEMFUNC_P (type))
5021     {
5022       expr = instantiate_type (type, expr, tf_none);
5023       if (expr == error_mark_node)
5024         return error_mark_node;
5025
5026       /* [temp.arg.nontype] bullet 1 says the pointer to member
5027          expression must be a pointer-to-member constant.  */
5028       if (!check_valid_ptrmem_cst_expr (type, expr))
5029         return error_mark_node;
5030
5031       /* There is no way to disable standard conversions in
5032          resolve_address_of_overloaded_function (called by
5033          instantiate_type). It is possible that the call succeeded by
5034          converting &B::I to &D::I (where B is a base of D), so we need
5035          to reject this conversion here.
5036
5037          Actually, even if there was a way to disable standard conversions,
5038          it would still be better to reject them here so that we can
5039          provide a superior diagnostic.  */
5040       if (!same_type_p (TREE_TYPE (expr), type))
5041         {
5042           /* Make sure we are just one standard conversion off.  */
5043           gcc_assert (can_convert (type, TREE_TYPE (expr)));
5044           error ("%qE is not a valid template argument for type %qT "
5045                  "because it is of type %qT", expr, type,
5046                  TREE_TYPE (expr));
5047           inform (input_location, "standard conversions are not allowed in this context");
5048           return NULL_TREE;
5049         }
5050     }
5051   /* [temp.arg.nontype]/5, bullet 7
5052
5053      For a non-type template-parameter of type pointer to data member,
5054      qualification conversions (_conv.qual_) are applied.  */
5055   else if (TYPE_PTRMEM_P (type))
5056     {
5057       /* [temp.arg.nontype] bullet 1 says the pointer to member
5058          expression must be a pointer-to-member constant.  */
5059       if (!check_valid_ptrmem_cst_expr (type, expr))
5060         return error_mark_node;
5061
5062       expr = perform_qualification_conversions (type, expr);
5063       if (expr == error_mark_node)
5064         return expr;
5065     }
5066   /* A template non-type parameter must be one of the above.  */
5067   else
5068     gcc_unreachable ();
5069
5070   /* Sanity check: did we actually convert the argument to the
5071      right type?  */
5072   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5073   return expr;
5074 }
5075
5076 /* Subroutine of coerce_template_template_parms, which returns 1 if
5077    PARM_PARM and ARG_PARM match using the rule for the template
5078    parameters of template template parameters. Both PARM and ARG are
5079    template parameters; the rest of the arguments are the same as for
5080    coerce_template_template_parms.
5081  */
5082 static int
5083 coerce_template_template_parm (tree parm,
5084                               tree arg,
5085                               tsubst_flags_t complain,
5086                               tree in_decl,
5087                               tree outer_args)
5088 {
5089   if (arg == NULL_TREE || arg == error_mark_node
5090       || parm == NULL_TREE || parm == error_mark_node)
5091     return 0;
5092   
5093   if (TREE_CODE (arg) != TREE_CODE (parm))
5094     return 0;
5095   
5096   switch (TREE_CODE (parm))
5097     {
5098     case TEMPLATE_DECL:
5099       /* We encounter instantiations of templates like
5100          template <template <template <class> class> class TT>
5101          class C;  */
5102       {
5103         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5104         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5105         
5106         if (!coerce_template_template_parms
5107             (parmparm, argparm, complain, in_decl, outer_args))
5108           return 0;
5109       }
5110       /* Fall through.  */
5111       
5112     case TYPE_DECL:
5113       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5114           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5115         /* Argument is a parameter pack but parameter is not.  */
5116         return 0;
5117       break;
5118       
5119     case PARM_DECL:
5120       /* The tsubst call is used to handle cases such as
5121          
5122            template <int> class C {};
5123            template <class T, template <T> class TT> class D {};
5124            D<int, C> d;
5125
5126          i.e. the parameter list of TT depends on earlier parameters.  */
5127       if (!uses_template_parms (TREE_TYPE (arg))
5128           && !same_type_p
5129                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5130                  TREE_TYPE (arg)))
5131         return 0;
5132       
5133       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5134           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5135         /* Argument is a parameter pack but parameter is not.  */
5136         return 0;
5137       
5138       break;
5139
5140     default:
5141       gcc_unreachable ();
5142     }
5143
5144   return 1;
5145 }
5146
5147
5148 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5149    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5150    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5151    or PARM_DECL.
5152
5153    Consider the example:
5154      template <class T> class A;
5155      template<template <class U> class TT> class B;
5156
5157    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5158    the parameters to A, and OUTER_ARGS contains A.  */
5159
5160 static int
5161 coerce_template_template_parms (tree parm_parms,
5162                                 tree arg_parms,
5163                                 tsubst_flags_t complain,
5164                                 tree in_decl,
5165                                 tree outer_args)
5166 {
5167   int nparms, nargs, i;
5168   tree parm, arg;
5169   int variadic_p = 0;
5170
5171   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5172   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5173
5174   nparms = TREE_VEC_LENGTH (parm_parms);
5175   nargs = TREE_VEC_LENGTH (arg_parms);
5176
5177   /* Determine whether we have a parameter pack at the end of the
5178      template template parameter's template parameter list.  */
5179   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5180     {
5181       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5182       
5183       if (parm == error_mark_node)
5184         return 0;
5185
5186       switch (TREE_CODE (parm))
5187         {
5188         case TEMPLATE_DECL:
5189         case TYPE_DECL:
5190           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5191             variadic_p = 1;
5192           break;
5193           
5194         case PARM_DECL:
5195           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5196             variadic_p = 1;
5197           break;
5198           
5199         default:
5200           gcc_unreachable ();
5201         }
5202     }
5203  
5204   if (nargs != nparms
5205       && !(variadic_p && nargs >= nparms - 1))
5206     return 0;
5207
5208   /* Check all of the template parameters except the parameter pack at
5209      the end (if any).  */
5210   for (i = 0; i < nparms - variadic_p; ++i)
5211     {
5212       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5213           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5214         continue;
5215
5216       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
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   if (variadic_p)
5226     {
5227       /* Check each of the template parameters in the template
5228          argument against the template parameter pack at the end of
5229          the template template parameter.  */
5230       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5231         return 0;
5232
5233       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5234
5235       for (; i < nargs; ++i)
5236         {
5237           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5238             continue;
5239  
5240           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5241  
5242           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5243                                               outer_args))
5244             return 0;
5245         }
5246     }
5247
5248   return 1;
5249 }
5250
5251 /* Verifies that the deduced template arguments (in TARGS) for the
5252    template template parameters (in TPARMS) represent valid bindings,
5253    by comparing the template parameter list of each template argument
5254    to the template parameter list of its corresponding template
5255    template parameter, in accordance with DR150. This
5256    routine can only be called after all template arguments have been
5257    deduced. It will return TRUE if all of the template template
5258    parameter bindings are okay, FALSE otherwise.  */
5259 bool 
5260 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5261 {
5262   int i, ntparms = TREE_VEC_LENGTH (tparms);
5263   bool ret = true;
5264
5265   /* We're dealing with template parms in this process.  */
5266   ++processing_template_decl;
5267
5268   targs = INNERMOST_TEMPLATE_ARGS (targs);
5269
5270   for (i = 0; i < ntparms; ++i)
5271     {
5272       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5273       tree targ = TREE_VEC_ELT (targs, i);
5274
5275       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5276         {
5277           tree packed_args = NULL_TREE;
5278           int idx, len = 1;
5279
5280           if (ARGUMENT_PACK_P (targ))
5281             {
5282               /* Look inside the argument pack.  */
5283               packed_args = ARGUMENT_PACK_ARGS (targ);
5284               len = TREE_VEC_LENGTH (packed_args);
5285             }
5286
5287           for (idx = 0; idx < len; ++idx)
5288             {
5289               tree targ_parms = NULL_TREE;
5290
5291               if (packed_args)
5292                 /* Extract the next argument from the argument
5293                    pack.  */
5294                 targ = TREE_VEC_ELT (packed_args, idx);
5295
5296               if (PACK_EXPANSION_P (targ))
5297                 /* Look at the pattern of the pack expansion.  */
5298                 targ = PACK_EXPANSION_PATTERN (targ);
5299
5300               /* Extract the template parameters from the template
5301                  argument.  */
5302               if (TREE_CODE (targ) == TEMPLATE_DECL)
5303                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5304               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5305                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5306
5307               /* Verify that we can coerce the template template
5308                  parameters from the template argument to the template
5309                  parameter.  This requires an exact match.  */
5310               if (targ_parms
5311                   && !coerce_template_template_parms
5312                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5313                         targ_parms,
5314                         tf_none,
5315                         tparm,
5316                         targs))
5317                 {
5318                   ret = false;
5319                   goto out;
5320                 }
5321             }
5322         }
5323     }
5324
5325  out:
5326
5327   --processing_template_decl;
5328   return ret;
5329 }
5330
5331 /* Convert the indicated template ARG as necessary to match the
5332    indicated template PARM.  Returns the converted ARG, or
5333    error_mark_node if the conversion was unsuccessful.  Error and
5334    warning messages are issued under control of COMPLAIN.  This
5335    conversion is for the Ith parameter in the parameter list.  ARGS is
5336    the full set of template arguments deduced so far.  */
5337
5338 static tree
5339 convert_template_argument (tree parm,
5340                            tree arg,
5341                            tree args,
5342                            tsubst_flags_t complain,
5343                            int i,
5344                            tree in_decl)
5345 {
5346   tree orig_arg;
5347   tree val;
5348   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5349
5350   if (TREE_CODE (arg) == TREE_LIST
5351       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5352     {
5353       /* The template argument was the name of some
5354          member function.  That's usually
5355          invalid, but static members are OK.  In any
5356          case, grab the underlying fields/functions
5357          and issue an error later if required.  */
5358       orig_arg = TREE_VALUE (arg);
5359       TREE_TYPE (arg) = unknown_type_node;
5360     }
5361
5362   orig_arg = arg;
5363
5364   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5365   requires_type = (TREE_CODE (parm) == TYPE_DECL
5366                    || requires_tmpl_type);
5367
5368   /* When determining whether an argument pack expansion is a template,
5369      look at the pattern.  */
5370   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5371     arg = PACK_EXPANSION_PATTERN (arg);
5372
5373   is_tmpl_type = 
5374     ((TREE_CODE (arg) == TEMPLATE_DECL
5375       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5376      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5377      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5378
5379   if (is_tmpl_type
5380       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5381           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5382     arg = TYPE_STUB_DECL (arg);
5383
5384   is_type = TYPE_P (arg) || is_tmpl_type;
5385
5386   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5387       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5388     {
5389       permerror (input_location, "to refer to a type member of a template parameter, "
5390                  "use %<typename %E%>", orig_arg);
5391
5392       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5393                                      TREE_OPERAND (arg, 1),
5394                                      typename_type,
5395                                      complain & tf_error);
5396       arg = orig_arg;
5397       is_type = 1;
5398     }
5399   if (is_type != requires_type)
5400     {
5401       if (in_decl)
5402         {
5403           if (complain & tf_error)
5404             {
5405               error ("type/value mismatch at argument %d in template "
5406                      "parameter list for %qD",
5407                      i + 1, in_decl);
5408               if (is_type)
5409                 error ("  expected a constant of type %qT, got %qT",
5410                        TREE_TYPE (parm),
5411                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5412               else if (requires_tmpl_type)
5413                 error ("  expected a class template, got %qE", orig_arg);
5414               else
5415                 error ("  expected a type, got %qE", orig_arg);
5416             }
5417         }
5418       return error_mark_node;
5419     }
5420   if (is_tmpl_type ^ requires_tmpl_type)
5421     {
5422       if (in_decl && (complain & tf_error))
5423         {
5424           error ("type/value mismatch at argument %d in template "
5425                  "parameter list for %qD",
5426                  i + 1, in_decl);
5427           if (is_tmpl_type)
5428             error ("  expected a type, got %qT", DECL_NAME (arg));
5429           else
5430             error ("  expected a class template, got %qT", orig_arg);
5431         }
5432       return error_mark_node;
5433     }
5434
5435   if (is_type)
5436     {
5437       if (requires_tmpl_type)
5438         {
5439           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5440             /* The number of argument required is not known yet.
5441                Just accept it for now.  */
5442             val = TREE_TYPE (arg);
5443           else
5444             {
5445               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5446               tree argparm;
5447
5448               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5449
5450               if (coerce_template_template_parms (parmparm, argparm,
5451                                                   complain, in_decl,
5452                                                   args))
5453                 {
5454                   val = arg;
5455
5456                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5457                      TEMPLATE_DECL.  */
5458                   if (val != error_mark_node)
5459                     {
5460                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5461                         val = TREE_TYPE (val);
5462                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
5463                         val = make_pack_expansion (val);
5464                     }
5465                 }
5466               else
5467                 {
5468                   if (in_decl && (complain & tf_error))
5469                     {
5470                       error ("type/value mismatch at argument %d in "
5471                              "template parameter list for %qD",
5472                              i + 1, in_decl);
5473                       error ("  expected a template of type %qD, got %qT",
5474                              parm, orig_arg);
5475                     }
5476
5477                   val = error_mark_node;
5478                 }
5479             }
5480         }
5481       else
5482         val = orig_arg;
5483       /* We only form one instance of each template specialization.
5484          Therefore, if we use a non-canonical variant (i.e., a
5485          typedef), any future messages referring to the type will use
5486          the typedef, which is confusing if those future uses do not
5487          themselves also use the typedef.  */
5488       if (TYPE_P (val))
5489         val = strip_typedefs (val);
5490     }
5491   else
5492     {
5493       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5494
5495       if (invalid_nontype_parm_type_p (t, complain))
5496         return error_mark_node;
5497
5498       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5499         {
5500           if (same_type_p (t, TREE_TYPE (orig_arg)))
5501             val = orig_arg;
5502           else
5503             {
5504               /* Not sure if this is reachable, but it doesn't hurt
5505                  to be robust.  */
5506               error ("type mismatch in nontype parameter pack");
5507               val = error_mark_node;
5508             }
5509         }
5510       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5511         /* We used to call digest_init here.  However, digest_init
5512            will report errors, which we don't want when complain
5513            is zero.  More importantly, digest_init will try too
5514            hard to convert things: for example, `0' should not be
5515            converted to pointer type at this point according to
5516            the standard.  Accepting this is not merely an
5517            extension, since deciding whether or not these
5518            conversions can occur is part of determining which
5519            function template to call, or whether a given explicit
5520            argument specification is valid.  */
5521         val = convert_nontype_argument (t, orig_arg);
5522       else
5523         val = orig_arg;
5524
5525       if (val == NULL_TREE)
5526         val = error_mark_node;
5527       else if (val == error_mark_node && (complain & tf_error))
5528         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5529     }
5530
5531   return val;
5532 }
5533
5534 /* Coerces the remaining template arguments in INNER_ARGS (from
5535    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5536    Returns the coerced argument pack. PARM_IDX is the position of this
5537    parameter in the template parameter list. ARGS is the original
5538    template argument list.  */
5539 static tree
5540 coerce_template_parameter_pack (tree parms,
5541                                 int parm_idx,
5542                                 tree args,
5543                                 tree inner_args,
5544                                 int arg_idx,
5545                                 tree new_args,
5546                                 int* lost,
5547                                 tree in_decl,
5548                                 tsubst_flags_t complain)
5549 {
5550   tree parm = TREE_VEC_ELT (parms, parm_idx);
5551   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5552   tree packed_args;
5553   tree argument_pack;
5554   tree packed_types = NULL_TREE;
5555
5556   if (arg_idx > nargs)
5557     arg_idx = nargs;
5558
5559   packed_args = make_tree_vec (nargs - arg_idx);
5560
5561   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5562       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5563     {
5564       /* When the template parameter is a non-type template
5565          parameter pack whose type uses parameter packs, we need
5566          to look at each of the template arguments
5567          separately. Build a vector of the types for these
5568          non-type template parameters in PACKED_TYPES.  */
5569       tree expansion 
5570         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5571       packed_types = tsubst_pack_expansion (expansion, args,
5572                                             complain, in_decl);
5573
5574       if (packed_types == error_mark_node)
5575         return error_mark_node;
5576
5577       /* Check that we have the right number of arguments.  */
5578       if (arg_idx < nargs
5579           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5580           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5581         {
5582           int needed_parms 
5583             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5584           error ("wrong number of template arguments (%d, should be %d)",
5585                  nargs, needed_parms);
5586           return error_mark_node;
5587         }
5588
5589       /* If we aren't able to check the actual arguments now
5590          (because they haven't been expanded yet), we can at least
5591          verify that all of the types used for the non-type
5592          template parameter pack are, in fact, valid for non-type
5593          template parameters.  */
5594       if (arg_idx < nargs 
5595           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5596         {
5597           int j, len = TREE_VEC_LENGTH (packed_types);
5598           for (j = 0; j < len; ++j)
5599             {
5600               tree t = TREE_VEC_ELT (packed_types, j);
5601               if (invalid_nontype_parm_type_p (t, complain))
5602                 return error_mark_node;
5603             }
5604         }
5605     }
5606
5607   /* Convert the remaining arguments, which will be a part of the
5608      parameter pack "parm".  */
5609   for (; arg_idx < nargs; ++arg_idx)
5610     {
5611       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5612       tree actual_parm = TREE_VALUE (parm);
5613
5614       if (packed_types && !PACK_EXPANSION_P (arg))
5615         {
5616           /* When we have a vector of types (corresponding to the
5617              non-type template parameter pack that uses parameter
5618              packs in its type, as mention above), and the
5619              argument is not an expansion (which expands to a
5620              currently unknown number of arguments), clone the
5621              parm and give it the next type in PACKED_TYPES.  */
5622           actual_parm = copy_node (actual_parm);
5623           TREE_TYPE (actual_parm) = 
5624             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5625         }
5626
5627       if (arg != error_mark_node)
5628         arg = convert_template_argument (actual_parm, 
5629                                          arg, new_args, complain, parm_idx,
5630                                          in_decl);
5631       if (arg == error_mark_node)
5632         (*lost)++;
5633       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5634     }
5635
5636   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5637       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5638     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5639   else
5640     {
5641       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5642       TREE_TYPE (argument_pack) 
5643         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5644       TREE_CONSTANT (argument_pack) = 1;
5645     }
5646
5647   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5648   return argument_pack;
5649 }
5650
5651 /* Convert all template arguments to their appropriate types, and
5652    return a vector containing the innermost resulting template
5653    arguments.  If any error occurs, return error_mark_node. Error and
5654    warning messages are issued under control of COMPLAIN.
5655
5656    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5657    for arguments not specified in ARGS.  Otherwise, if
5658    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5659    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5660    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5661    ARGS.  */
5662
5663 static tree
5664 coerce_template_parms (tree parms,
5665                        tree args,
5666                        tree in_decl,
5667                        tsubst_flags_t complain,
5668                        bool require_all_args,
5669                        bool use_default_args)
5670 {
5671   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5672   tree inner_args;
5673   tree new_args;
5674   tree new_inner_args;
5675   int saved_unevaluated_operand;
5676   int saved_inhibit_evaluation_warnings;
5677
5678   /* When used as a boolean value, indicates whether this is a
5679      variadic template parameter list. Since it's an int, we can also
5680      subtract it from nparms to get the number of non-variadic
5681      parameters.  */
5682   int variadic_p = 0;
5683
5684   nparms = TREE_VEC_LENGTH (parms);
5685
5686   /* Determine if there are any parameter packs.  */
5687   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5688     {
5689       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5690       if (template_parameter_pack_p (tparm))
5691         ++variadic_p;
5692     }
5693
5694   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5695   /* If there are 0 or 1 parameter packs, we need to expand any argument
5696      packs so that we can deduce a parameter pack from some non-packed args
5697      followed by an argument pack, as in variadic85.C.  If there are more
5698      than that, we need to leave argument packs intact so the arguments are
5699      assigned to the right parameter packs.  This should only happen when
5700      dealing with a nested class inside a partial specialization of a class
5701      template, as in variadic92.C.  */
5702   if (variadic_p <= 1)
5703     inner_args = expand_template_argument_pack (inner_args);
5704
5705   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5706   if ((nargs > nparms && !variadic_p)
5707       || (nargs < nparms - variadic_p
5708           && require_all_args
5709           && (!use_default_args
5710               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5711                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5712     {
5713       if (complain & tf_error)
5714         {
5715           const char *or_more = "";
5716           if (variadic_p)
5717             {
5718               or_more = " or more";
5719               --nparms;
5720             }
5721
5722           error ("wrong number of template arguments (%d, should be %d%s)",
5723                  nargs, nparms, or_more);
5724
5725           if (in_decl)
5726             error ("provided for %q+D", in_decl);
5727         }
5728
5729       return error_mark_node;
5730     }
5731
5732   /* We need to evaluate the template arguments, even though this
5733      template-id may be nested within a "sizeof".  */
5734   saved_unevaluated_operand = cp_unevaluated_operand;
5735   cp_unevaluated_operand = 0;
5736   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5737   c_inhibit_evaluation_warnings = 0;
5738   new_inner_args = make_tree_vec (nparms);
5739   new_args = add_outermost_template_args (args, new_inner_args);
5740   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5741     {
5742       tree arg;
5743       tree parm;
5744
5745       /* Get the Ith template parameter.  */
5746       parm = TREE_VEC_ELT (parms, parm_idx);
5747  
5748       if (parm == error_mark_node)
5749       {
5750         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5751         continue;
5752       }
5753
5754       /* Calculate the next argument.  */
5755       if (arg_idx < nargs)
5756         arg = TREE_VEC_ELT (inner_args, arg_idx);
5757       else
5758         arg = NULL_TREE;
5759
5760       if (template_parameter_pack_p (TREE_VALUE (parm))
5761           && !(arg && ARGUMENT_PACK_P (arg)))
5762         {
5763           /* All remaining arguments will be placed in the
5764              template parameter pack PARM.  */
5765           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5766                                                 inner_args, arg_idx,
5767                                                 new_args, &lost,
5768                                                 in_decl, complain);
5769
5770           /* Store this argument.  */
5771           if (arg == error_mark_node)
5772             lost++;
5773           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5774
5775           /* We are done with all of the arguments.  */
5776           arg_idx = nargs;
5777           
5778           continue;
5779         }
5780       else if (arg)
5781         {
5782           if (PACK_EXPANSION_P (arg))
5783             {
5784               if (complain & tf_error)
5785                 {
5786                   /* FIXME this restriction was removed by N2555; see
5787                      bug 35722.  */
5788                   /* If ARG is a pack expansion, but PARM is not a
5789                      template parameter pack (if it were, we would have
5790                      handled it above), we're trying to expand into a
5791                      fixed-length argument list.  */
5792                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5793                     sorry ("cannot expand %<%E%> into a fixed-length "
5794                            "argument list", arg);
5795                   else
5796                     sorry ("cannot expand %<%T%> into a fixed-length "
5797                            "argument list", arg);
5798                 }
5799               return error_mark_node;
5800             }
5801         }
5802       else if (require_all_args)
5803         /* There must be a default arg in this case.  */
5804         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5805                                    complain, in_decl);
5806       else
5807         break;
5808
5809       if (arg == error_mark_node)
5810         {
5811           if (complain & tf_error)
5812             error ("template argument %d is invalid", arg_idx + 1);
5813         }
5814       else if (!arg)
5815         /* This only occurs if there was an error in the template
5816            parameter list itself (which we would already have
5817            reported) that we are trying to recover from, e.g., a class
5818            template with a parameter list such as
5819            template<typename..., typename>.  */
5820         return error_mark_node;
5821       else
5822         arg = convert_template_argument (TREE_VALUE (parm),
5823                                          arg, new_args, complain, 
5824                                          parm_idx, in_decl);
5825
5826       if (arg == error_mark_node)
5827         lost++;
5828       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5829     }
5830   cp_unevaluated_operand = saved_unevaluated_operand;
5831   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
5832
5833   if (lost)
5834     return error_mark_node;
5835
5836   return new_inner_args;
5837 }
5838
5839 /* Returns 1 if template args OT and NT are equivalent.  */
5840
5841 static int
5842 template_args_equal (tree ot, tree nt)
5843 {
5844   if (nt == ot)
5845     return 1;
5846
5847   if (TREE_CODE (nt) == TREE_VEC)
5848     /* For member templates */
5849     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5850   else if (PACK_EXPANSION_P (ot))
5851     return PACK_EXPANSION_P (nt) 
5852       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5853                               PACK_EXPANSION_PATTERN (nt));
5854   else if (ARGUMENT_PACK_P (ot))
5855     {
5856       int i, len;
5857       tree opack, npack;
5858
5859       if (!ARGUMENT_PACK_P (nt))
5860         return 0;
5861
5862       opack = ARGUMENT_PACK_ARGS (ot);
5863       npack = ARGUMENT_PACK_ARGS (nt);
5864       len = TREE_VEC_LENGTH (opack);
5865       if (TREE_VEC_LENGTH (npack) != len)
5866         return 0;
5867       for (i = 0; i < len; ++i)
5868         if (!template_args_equal (TREE_VEC_ELT (opack, i),
5869                                   TREE_VEC_ELT (npack, i)))
5870           return 0;
5871       return 1;
5872     }
5873   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
5874     {
5875       /* We get here probably because we are in the middle of substituting
5876          into the pattern of a pack expansion. In that case the
5877          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
5878          interested in. So we want to use the initial pack argument for
5879          the comparison.  */
5880       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
5881       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
5882         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
5883       return template_args_equal (ot, nt);
5884     }
5885   else if (TYPE_P (nt))
5886     return TYPE_P (ot) && same_type_p (ot, nt);
5887   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5888     return 0;
5889   else
5890     return cp_tree_equal (ot, nt);
5891 }
5892
5893 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5894    of template arguments.  Returns 0 otherwise.  */
5895
5896 int
5897 comp_template_args (tree oldargs, tree newargs)
5898 {
5899   int i;
5900
5901   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5902     return 0;
5903
5904   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5905     {
5906       tree nt = TREE_VEC_ELT (newargs, i);
5907       tree ot = TREE_VEC_ELT (oldargs, i);
5908
5909       if (! template_args_equal (ot, nt))
5910         return 0;
5911     }
5912   return 1;
5913 }
5914
5915 static void
5916 add_pending_template (tree d)
5917 {
5918   tree ti = (TYPE_P (d)
5919              ? CLASSTYPE_TEMPLATE_INFO (d)
5920              : DECL_TEMPLATE_INFO (d));
5921   struct pending_template *pt;
5922   int level;
5923
5924   if (TI_PENDING_TEMPLATE_FLAG (ti))
5925     return;
5926
5927   /* We are called both from instantiate_decl, where we've already had a
5928      tinst_level pushed, and instantiate_template, where we haven't.
5929      Compensate.  */
5930   level = !current_tinst_level || current_tinst_level->decl != d;
5931
5932   if (level)
5933     push_tinst_level (d);
5934
5935   pt = GGC_NEW (struct pending_template);
5936   pt->next = NULL;
5937   pt->tinst = current_tinst_level;
5938   if (last_pending_template)
5939     last_pending_template->next = pt;
5940   else
5941     pending_templates = pt;
5942
5943   last_pending_template = pt;
5944
5945   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5946
5947   if (level)
5948     pop_tinst_level ();
5949 }
5950
5951
5952 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5953    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5954    documentation for TEMPLATE_ID_EXPR.  */
5955
5956 tree
5957 lookup_template_function (tree fns, tree arglist)
5958 {
5959   tree type;
5960
5961   if (fns == error_mark_node || arglist == error_mark_node)
5962     return error_mark_node;
5963
5964   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5965   gcc_assert (fns && (is_overloaded_fn (fns)
5966                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5967
5968   if (BASELINK_P (fns))
5969     {
5970       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5971                                          unknown_type_node,
5972                                          BASELINK_FUNCTIONS (fns),
5973                                          arglist);
5974       return fns;
5975     }
5976
5977   type = TREE_TYPE (fns);
5978   if (TREE_CODE (fns) == OVERLOAD || !type)
5979     type = unknown_type_node;
5980
5981   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5982 }
5983
5984 /* Within the scope of a template class S<T>, the name S gets bound
5985    (in build_self_reference) to a TYPE_DECL for the class, not a
5986    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5987    or one of its enclosing classes, and that type is a template,
5988    return the associated TEMPLATE_DECL.  Otherwise, the original
5989    DECL is returned.
5990
5991    Also handle the case when DECL is a TREE_LIST of ambiguous
5992    injected-class-names from different bases.  */
5993
5994 tree
5995 maybe_get_template_decl_from_type_decl (tree decl)
5996 {
5997   if (decl == NULL_TREE)
5998     return decl;
5999
6000   /* DR 176: A lookup that finds an injected-class-name (10.2
6001      [class.member.lookup]) can result in an ambiguity in certain cases
6002      (for example, if it is found in more than one base class). If all of
6003      the injected-class-names that are found refer to specializations of
6004      the same class template, and if the name is followed by a
6005      template-argument-list, the reference refers to the class template
6006      itself and not a specialization thereof, and is not ambiguous.  */
6007   if (TREE_CODE (decl) == TREE_LIST)
6008     {
6009       tree t, tmpl = NULL_TREE;
6010       for (t = decl; t; t = TREE_CHAIN (t))
6011         {
6012           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6013           if (!tmpl)
6014             tmpl = elt;
6015           else if (tmpl != elt)
6016             break;
6017         }
6018       if (tmpl && t == NULL_TREE)
6019         return tmpl;
6020       else
6021         return decl;
6022     }
6023
6024   return (decl != NULL_TREE
6025           && DECL_SELF_REFERENCE_P (decl)
6026           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6027     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6028 }
6029
6030 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6031    parameters, find the desired type.
6032
6033    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6034
6035    IN_DECL, if non-NULL, is the template declaration we are trying to
6036    instantiate.
6037
6038    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6039    the class we are looking up.
6040
6041    Issue error and warning messages under control of COMPLAIN.
6042
6043    If the template class is really a local class in a template
6044    function, then the FUNCTION_CONTEXT is the function in which it is
6045    being instantiated.
6046
6047    ??? Note that this function is currently called *twice* for each
6048    template-id: the first time from the parser, while creating the
6049    incomplete type (finish_template_type), and the second type during the
6050    real instantiation (instantiate_template_class). This is surely something
6051    that we want to avoid. It also causes some problems with argument
6052    coercion (see convert_nontype_argument for more information on this).  */
6053
6054 tree
6055 lookup_template_class (tree d1,
6056                        tree arglist,
6057                        tree in_decl,
6058                        tree context,
6059                        int entering_scope,
6060                        tsubst_flags_t complain)
6061 {
6062   tree templ = NULL_TREE, parmlist;
6063   tree t;
6064   spec_entry **slot;
6065   spec_entry *entry;
6066   spec_entry elt;
6067   hashval_t hash;
6068
6069   timevar_push (TV_NAME_LOOKUP);
6070
6071   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6072     {
6073       tree value = innermost_non_namespace_value (d1);
6074       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6075         templ = value;
6076       else
6077         {
6078           if (context)
6079             push_decl_namespace (context);
6080           templ = lookup_name (d1);
6081           templ = maybe_get_template_decl_from_type_decl (templ);
6082           if (context)
6083             pop_decl_namespace ();
6084         }
6085       if (templ)
6086         context = DECL_CONTEXT (templ);
6087     }
6088   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6089     {
6090       tree type = TREE_TYPE (d1);
6091
6092       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6093          an implicit typename for the second A.  Deal with it.  */
6094       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6095         type = TREE_TYPE (type);
6096
6097       if (CLASSTYPE_TEMPLATE_INFO (type))
6098         {
6099           templ = CLASSTYPE_TI_TEMPLATE (type);
6100           d1 = DECL_NAME (templ);
6101         }
6102     }
6103   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6104            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6105     {
6106       templ = TYPE_TI_TEMPLATE (d1);
6107       d1 = DECL_NAME (templ);
6108     }
6109   else if (TREE_CODE (d1) == TEMPLATE_DECL
6110            && DECL_TEMPLATE_RESULT (d1)
6111            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6112     {
6113       templ = d1;
6114       d1 = DECL_NAME (templ);
6115       context = DECL_CONTEXT (templ);
6116     }
6117
6118   /* Issue an error message if we didn't find a template.  */
6119   if (! templ)
6120     {
6121       if (complain & tf_error)
6122         error ("%qT is not a template", d1);
6123       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6124     }
6125
6126   if (TREE_CODE (templ) != TEMPLATE_DECL
6127          /* Make sure it's a user visible template, if it was named by
6128             the user.  */
6129       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6130           && !PRIMARY_TEMPLATE_P (templ)))
6131     {
6132       if (complain & tf_error)
6133         {
6134           error ("non-template type %qT used as a template", d1);
6135           if (in_decl)
6136             error ("for template declaration %q+D", in_decl);
6137         }
6138       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6139     }
6140
6141   complain &= ~tf_user;
6142
6143   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6144     {
6145       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6146          template arguments */
6147
6148       tree parm;
6149       tree arglist2;
6150       tree outer;
6151
6152       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6153
6154       /* Consider an example where a template template parameter declared as
6155
6156            template <class T, class U = std::allocator<T> > class TT
6157
6158          The template parameter level of T and U are one level larger than
6159          of TT.  To proper process the default argument of U, say when an
6160          instantiation `TT<int>' is seen, we need to build the full
6161          arguments containing {int} as the innermost level.  Outer levels,
6162          available when not appearing as default template argument, can be
6163          obtained from the arguments of the enclosing template.
6164
6165          Suppose that TT is later substituted with std::vector.  The above
6166          instantiation is `TT<int, std::allocator<T> >' with TT at
6167          level 1, and T at level 2, while the template arguments at level 1
6168          becomes {std::vector} and the inner level 2 is {int}.  */
6169
6170       outer = DECL_CONTEXT (templ);
6171       if (outer)
6172         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6173       else if (current_template_parms)
6174         /* This is an argument of the current template, so we haven't set
6175            DECL_CONTEXT yet.  */
6176         outer = current_template_args ();
6177
6178       if (outer)
6179         arglist = add_to_template_args (outer, arglist);
6180
6181       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6182                                         complain,
6183                                         /*require_all_args=*/true,
6184                                         /*use_default_args=*/true);
6185       if (arglist2 == error_mark_node
6186           || (!uses_template_parms (arglist2)
6187               && check_instantiated_args (templ, arglist2, complain)))
6188         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6189
6190       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6191       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6192     }
6193   else
6194     {
6195       tree template_type = TREE_TYPE (templ);
6196       tree gen_tmpl;
6197       tree type_decl;
6198       tree found = NULL_TREE;
6199       int arg_depth;
6200       int parm_depth;
6201       int is_partial_instantiation;
6202
6203       gen_tmpl = most_general_template (templ);
6204       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6205       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6206       arg_depth = TMPL_ARGS_DEPTH (arglist);
6207
6208       if (arg_depth == 1 && parm_depth > 1)
6209         {
6210           /* We've been given an incomplete set of template arguments.
6211              For example, given:
6212
6213                template <class T> struct S1 {
6214                  template <class U> struct S2 {};
6215                  template <class U> struct S2<U*> {};
6216                 };
6217
6218              we will be called with an ARGLIST of `U*', but the
6219              TEMPLATE will be `template <class T> template
6220              <class U> struct S1<T>::S2'.  We must fill in the missing
6221              arguments.  */
6222           arglist
6223             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6224                                            arglist);
6225           arg_depth = TMPL_ARGS_DEPTH (arglist);
6226         }
6227
6228       /* Now we should have enough arguments.  */
6229       gcc_assert (parm_depth == arg_depth);
6230
6231       /* From here on, we're only interested in the most general
6232          template.  */
6233
6234       /* Calculate the BOUND_ARGS.  These will be the args that are
6235          actually tsubst'd into the definition to create the
6236          instantiation.  */
6237       if (parm_depth > 1)
6238         {
6239           /* We have multiple levels of arguments to coerce, at once.  */
6240           int i;
6241           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6242
6243           tree bound_args = make_tree_vec (parm_depth);
6244
6245           for (i = saved_depth,
6246                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6247                i > 0 && t != NULL_TREE;
6248                --i, t = TREE_CHAIN (t))
6249             {
6250               tree a = coerce_template_parms (TREE_VALUE (t),
6251                                               arglist, gen_tmpl,
6252                                               complain,
6253                                               /*require_all_args=*/true,
6254                                               /*use_default_args=*/true);
6255
6256               /* Don't process further if one of the levels fails.  */
6257               if (a == error_mark_node)
6258                 {
6259                   /* Restore the ARGLIST to its full size.  */
6260                   TREE_VEC_LENGTH (arglist) = saved_depth;
6261                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6262                 }
6263
6264               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6265
6266               /* We temporarily reduce the length of the ARGLIST so
6267                  that coerce_template_parms will see only the arguments
6268                  corresponding to the template parameters it is
6269                  examining.  */
6270               TREE_VEC_LENGTH (arglist)--;
6271             }
6272
6273           /* Restore the ARGLIST to its full size.  */
6274           TREE_VEC_LENGTH (arglist) = saved_depth;
6275
6276           arglist = bound_args;
6277         }
6278       else
6279         arglist
6280           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6281                                    INNERMOST_TEMPLATE_ARGS (arglist),
6282                                    gen_tmpl,
6283                                    complain,
6284                                    /*require_all_args=*/true,
6285                                    /*use_default_args=*/true);
6286
6287       if (arglist == error_mark_node)
6288         /* We were unable to bind the arguments.  */
6289         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6290
6291       /* In the scope of a template class, explicit references to the
6292          template class refer to the type of the template, not any
6293          instantiation of it.  For example, in:
6294
6295            template <class T> class C { void f(C<T>); }
6296
6297          the `C<T>' is just the same as `C'.  Outside of the
6298          class, however, such a reference is an instantiation.  */
6299       if ((entering_scope
6300            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6301            || currently_open_class (template_type))
6302           /* comp_template_args is expensive, check it last.  */
6303           && comp_template_args (TYPE_TI_ARGS (template_type),
6304                                  arglist))
6305         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6306
6307       /* If we already have this specialization, return it.  */
6308       elt.tmpl = gen_tmpl;
6309       elt.args = arglist;
6310       hash = hash_specialization (&elt);
6311       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6312                                                   &elt, hash);
6313
6314       if (entry)
6315         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6316
6317       /* This type is a "partial instantiation" if any of the template
6318          arguments still involve template parameters.  Note that we set
6319          IS_PARTIAL_INSTANTIATION for partial specializations as
6320          well.  */
6321       is_partial_instantiation = uses_template_parms (arglist);
6322
6323       /* If the deduced arguments are invalid, then the binding
6324          failed.  */
6325       if (!is_partial_instantiation
6326           && check_instantiated_args (gen_tmpl,
6327                                       INNERMOST_TEMPLATE_ARGS (arglist),
6328                                       complain))
6329         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6330
6331       if (!is_partial_instantiation
6332           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6333           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6334           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6335         {
6336           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6337                                       DECL_NAME (gen_tmpl),
6338                                       /*tag_scope=*/ts_global);
6339           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6340         }
6341
6342       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6343                         complain, in_decl);
6344       if (!context)
6345         context = global_namespace;
6346
6347       /* Create the type.  */
6348       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6349         {
6350           if (!is_partial_instantiation)
6351             {
6352               set_current_access_from_decl (TYPE_NAME (template_type));
6353               t = start_enum (TYPE_IDENTIFIER (template_type),
6354                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6355                                       arglist, complain, in_decl),
6356                               SCOPED_ENUM_P (template_type));
6357             }
6358           else
6359             {
6360               /* We don't want to call start_enum for this type, since
6361                  the values for the enumeration constants may involve
6362                  template parameters.  And, no one should be interested
6363                  in the enumeration constants for such a type.  */
6364               t = cxx_make_type (ENUMERAL_TYPE);
6365               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6366             }
6367         }
6368       else
6369         {
6370           t = make_class_type (TREE_CODE (template_type));
6371           CLASSTYPE_DECLARED_CLASS (t)
6372             = CLASSTYPE_DECLARED_CLASS (template_type);
6373           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6374           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6375
6376           /* A local class.  Make sure the decl gets registered properly.  */
6377           if (context == current_function_decl)
6378             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6379
6380           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6381             /* This instantiation is another name for the primary
6382                template type. Set the TYPE_CANONICAL field
6383                appropriately. */
6384             TYPE_CANONICAL (t) = template_type;
6385           else if (any_template_arguments_need_structural_equality_p (arglist))
6386             /* Some of the template arguments require structural
6387                equality testing, so this template class requires
6388                structural equality testing. */
6389             SET_TYPE_STRUCTURAL_EQUALITY (t);
6390         }
6391
6392       /* If we called start_enum or pushtag above, this information
6393          will already be set up.  */
6394       if (!TYPE_NAME (t))
6395         {
6396           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6397
6398           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6399           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6400           DECL_SOURCE_LOCATION (type_decl)
6401             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6402         }
6403       else
6404         type_decl = TYPE_NAME (t);
6405
6406       TREE_PRIVATE (type_decl)
6407         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6408       TREE_PROTECTED (type_decl)
6409         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6410       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6411         {
6412           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6413           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6414         }
6415
6416       /* Set up the template information.  We have to figure out which
6417          template is the immediate parent if this is a full
6418          instantiation.  */
6419       if (parm_depth == 1 || is_partial_instantiation
6420           || !PRIMARY_TEMPLATE_P (gen_tmpl))
6421         /* This case is easy; there are no member templates involved.  */
6422         found = gen_tmpl;
6423       else
6424         {
6425           /* This is a full instantiation of a member template.  Find
6426              the partial instantiation of which this is an instance.  */
6427
6428           /* Temporarily reduce by one the number of levels in the ARGLIST
6429              so as to avoid comparing the last set of arguments.  */
6430           TREE_VEC_LENGTH (arglist)--;
6431           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6432           TREE_VEC_LENGTH (arglist)++;
6433           found = CLASSTYPE_TI_TEMPLATE (found);
6434         }
6435
6436       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
6437
6438       elt.spec = t;
6439       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6440                                                        &elt, hash, INSERT);
6441       *slot = GGC_NEW (spec_entry);
6442       **slot = elt;
6443
6444       /* Note this use of the partial instantiation so we can check it
6445          later in maybe_process_partial_specialization.  */
6446       DECL_TEMPLATE_INSTANTIATIONS (templ)
6447         = tree_cons (arglist, t,
6448                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6449
6450       if (TREE_CODE (t) == ENUMERAL_TYPE
6451           && !is_partial_instantiation)
6452         /* Now that the type has been registered on the instantiations
6453            list, we set up the enumerators.  Because the enumeration
6454            constants may involve the enumeration type itself, we make
6455            sure to register the type first, and then create the
6456            constants.  That way, doing tsubst_expr for the enumeration
6457            constants won't result in recursive calls here; we'll find
6458            the instantiation and exit above.  */
6459         tsubst_enum (template_type, t, arglist);
6460
6461       if (is_partial_instantiation)
6462         /* If the type makes use of template parameters, the
6463            code that generates debugging information will crash.  */
6464         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6465
6466       /* Possibly limit visibility based on template args.  */
6467       TREE_PUBLIC (type_decl) = 1;
6468       determine_visibility (type_decl);
6469
6470       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6471     }
6472   timevar_pop (TV_NAME_LOOKUP);
6473 }
6474 \f
6475 struct pair_fn_data
6476 {
6477   tree_fn_t fn;
6478   void *data;
6479   /* True when we should also visit template parameters that occur in
6480      non-deduced contexts.  */
6481   bool include_nondeduced_p;
6482   struct pointer_set_t *visited;
6483 };
6484
6485 /* Called from for_each_template_parm via walk_tree.  */
6486
6487 static tree
6488 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6489 {
6490   tree t = *tp;
6491   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6492   tree_fn_t fn = pfd->fn;
6493   void *data = pfd->data;
6494
6495   if (TYPE_P (t)
6496       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6497       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6498                                  pfd->include_nondeduced_p))
6499     return error_mark_node;
6500
6501   switch (TREE_CODE (t))
6502     {
6503     case RECORD_TYPE:
6504       if (TYPE_PTRMEMFUNC_P (t))
6505         break;
6506       /* Fall through.  */
6507
6508     case UNION_TYPE:
6509     case ENUMERAL_TYPE:
6510       if (!TYPE_TEMPLATE_INFO (t))
6511         *walk_subtrees = 0;
6512       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
6513                                        fn, data, pfd->visited, 
6514                                        pfd->include_nondeduced_p))
6515         return error_mark_node;
6516       break;
6517
6518     case INTEGER_TYPE:
6519       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6520                                   fn, data, pfd->visited, 
6521                                   pfd->include_nondeduced_p)
6522           || for_each_template_parm (TYPE_MAX_VALUE (t),
6523                                      fn, data, pfd->visited,
6524                                      pfd->include_nondeduced_p))
6525         return error_mark_node;
6526       break;
6527
6528     case METHOD_TYPE:
6529       /* Since we're not going to walk subtrees, we have to do this
6530          explicitly here.  */
6531       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6532                                   pfd->visited, pfd->include_nondeduced_p))
6533         return error_mark_node;
6534       /* Fall through.  */
6535
6536     case FUNCTION_TYPE:
6537       /* Check the return type.  */
6538       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6539                                   pfd->include_nondeduced_p))
6540         return error_mark_node;
6541
6542       /* Check the parameter types.  Since default arguments are not
6543          instantiated until they are needed, the TYPE_ARG_TYPES may
6544          contain expressions that involve template parameters.  But,
6545          no-one should be looking at them yet.  And, once they're
6546          instantiated, they don't contain template parameters, so
6547          there's no point in looking at them then, either.  */
6548       {
6549         tree parm;
6550
6551         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6552           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6553                                       pfd->visited, pfd->include_nondeduced_p))
6554             return error_mark_node;
6555
6556         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6557            want walk_tree walking into them itself.  */
6558         *walk_subtrees = 0;
6559       }
6560       break;
6561
6562     case TYPEOF_TYPE:
6563       if (pfd->include_nondeduced_p
6564           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6565                                      pfd->visited, 
6566                                      pfd->include_nondeduced_p))
6567         return error_mark_node;
6568       break;
6569
6570     case FUNCTION_DECL:
6571     case VAR_DECL:
6572       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6573           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6574                                      pfd->visited, pfd->include_nondeduced_p))
6575         return error_mark_node;
6576       /* Fall through.  */
6577
6578     case PARM_DECL:
6579     case CONST_DECL:
6580       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6581           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6582                                      pfd->visited, pfd->include_nondeduced_p))
6583         return error_mark_node;
6584       if (DECL_CONTEXT (t)
6585           && pfd->include_nondeduced_p
6586           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6587                                      pfd->visited, pfd->include_nondeduced_p))
6588         return error_mark_node;
6589       break;
6590
6591     case BOUND_TEMPLATE_TEMPLATE_PARM:
6592       /* Record template parameters such as `T' inside `TT<T>'.  */
6593       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6594                                   pfd->include_nondeduced_p))
6595         return error_mark_node;
6596       /* Fall through.  */
6597
6598     case TEMPLATE_TEMPLATE_PARM:
6599     case TEMPLATE_TYPE_PARM:
6600     case TEMPLATE_PARM_INDEX:
6601       if (fn && (*fn)(t, data))
6602         return error_mark_node;
6603       else if (!fn)
6604         return error_mark_node;
6605       break;
6606
6607     case TEMPLATE_DECL:
6608       /* A template template parameter is encountered.  */
6609       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6610           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6611                                      pfd->include_nondeduced_p))
6612         return error_mark_node;
6613
6614       /* Already substituted template template parameter */
6615       *walk_subtrees = 0;
6616       break;
6617
6618     case TYPENAME_TYPE:
6619       if (!fn
6620           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6621                                      data, pfd->visited, 
6622                                      pfd->include_nondeduced_p))
6623         return error_mark_node;
6624       break;
6625
6626     case CONSTRUCTOR:
6627       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6628           && pfd->include_nondeduced_p
6629           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6630                                      (TREE_TYPE (t)), fn, data,
6631                                      pfd->visited, pfd->include_nondeduced_p))
6632         return error_mark_node;
6633       break;
6634
6635     case INDIRECT_REF:
6636     case COMPONENT_REF:
6637       /* If there's no type, then this thing must be some expression
6638          involving template parameters.  */
6639       if (!fn && !TREE_TYPE (t))
6640         return error_mark_node;
6641       break;
6642
6643     case MODOP_EXPR:
6644     case CAST_EXPR:
6645     case REINTERPRET_CAST_EXPR:
6646     case CONST_CAST_EXPR:
6647     case STATIC_CAST_EXPR:
6648     case DYNAMIC_CAST_EXPR:
6649     case ARROW_EXPR:
6650     case DOTSTAR_EXPR:
6651     case TYPEID_EXPR:
6652     case PSEUDO_DTOR_EXPR:
6653       if (!fn)
6654         return error_mark_node;
6655       break;
6656
6657     default:
6658       break;
6659     }
6660
6661   /* We didn't find any template parameters we liked.  */
6662   return NULL_TREE;
6663 }
6664
6665 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6666    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6667    call FN with the parameter and the DATA.
6668    If FN returns nonzero, the iteration is terminated, and
6669    for_each_template_parm returns 1.  Otherwise, the iteration
6670    continues.  If FN never returns a nonzero value, the value
6671    returned by for_each_template_parm is 0.  If FN is NULL, it is
6672    considered to be the function which always returns 1.
6673
6674    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6675    parameters that occur in non-deduced contexts.  When false, only
6676    visits those template parameters that can be deduced.  */
6677
6678 static int
6679 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6680                         struct pointer_set_t *visited,
6681                         bool include_nondeduced_p)
6682 {
6683   struct pair_fn_data pfd;
6684   int result;
6685
6686   /* Set up.  */
6687   pfd.fn = fn;
6688   pfd.data = data;
6689   pfd.include_nondeduced_p = include_nondeduced_p;
6690
6691   /* Walk the tree.  (Conceptually, we would like to walk without
6692      duplicates, but for_each_template_parm_r recursively calls
6693      for_each_template_parm, so we would need to reorganize a fair
6694      bit to use walk_tree_without_duplicates, so we keep our own
6695      visited list.)  */
6696   if (visited)
6697     pfd.visited = visited;
6698   else
6699     pfd.visited = pointer_set_create ();
6700   result = cp_walk_tree (&t,
6701                          for_each_template_parm_r,
6702                          &pfd,
6703                          pfd.visited) != NULL_TREE;
6704
6705   /* Clean up.  */
6706   if (!visited)
6707     {
6708       pointer_set_destroy (pfd.visited);
6709       pfd.visited = 0;
6710     }
6711
6712   return result;
6713 }
6714
6715 /* Returns true if T depends on any template parameter.  */
6716
6717 int
6718 uses_template_parms (tree t)
6719 {
6720   bool dependent_p;
6721   int saved_processing_template_decl;
6722
6723   saved_processing_template_decl = processing_template_decl;
6724   if (!saved_processing_template_decl)
6725     processing_template_decl = 1;
6726   if (TYPE_P (t))
6727     dependent_p = dependent_type_p (t);
6728   else if (TREE_CODE (t) == TREE_VEC)
6729     dependent_p = any_dependent_template_arguments_p (t);
6730   else if (TREE_CODE (t) == TREE_LIST)
6731     dependent_p = (uses_template_parms (TREE_VALUE (t))
6732                    || uses_template_parms (TREE_CHAIN (t)));
6733   else if (TREE_CODE (t) == TYPE_DECL)
6734     dependent_p = dependent_type_p (TREE_TYPE (t));
6735   else if (DECL_P (t)
6736            || EXPR_P (t)
6737            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6738            || TREE_CODE (t) == OVERLOAD
6739            || TREE_CODE (t) == BASELINK
6740            || TREE_CODE (t) == IDENTIFIER_NODE
6741            || TREE_CODE (t) == TRAIT_EXPR
6742            || TREE_CODE (t) == CONSTRUCTOR
6743            || CONSTANT_CLASS_P (t))
6744     dependent_p = (type_dependent_expression_p (t)
6745                    || value_dependent_expression_p (t));
6746   else
6747     {
6748       gcc_assert (t == error_mark_node);
6749       dependent_p = false;
6750     }
6751
6752   processing_template_decl = saved_processing_template_decl;
6753
6754   return dependent_p;
6755 }
6756
6757 /* Returns true if T depends on any template parameter with level LEVEL.  */
6758
6759 int
6760 uses_template_parms_level (tree t, int level)
6761 {
6762   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6763                                  /*include_nondeduced_p=*/true);
6764 }
6765
6766 static int tinst_depth;
6767 extern int max_tinst_depth;
6768 #ifdef GATHER_STATISTICS
6769 int depth_reached;
6770 #endif
6771 static int tinst_level_tick;
6772 static int last_template_error_tick;
6773
6774 /* We're starting to instantiate D; record the template instantiation context
6775    for diagnostics and to restore it later.  */
6776
6777 static int
6778 push_tinst_level (tree d)
6779 {
6780   struct tinst_level *new_level;
6781
6782   if (tinst_depth >= max_tinst_depth)
6783     {
6784       /* If the instantiation in question still has unbound template parms,
6785          we don't really care if we can't instantiate it, so just return.
6786          This happens with base instantiation for implicit `typename'.  */
6787       if (uses_template_parms (d))
6788         return 0;
6789
6790       last_template_error_tick = tinst_level_tick;
6791       error ("template instantiation depth exceeds maximum of %d (use "
6792              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6793              max_tinst_depth, d);
6794
6795       print_instantiation_context ();
6796
6797       return 0;
6798     }
6799
6800   new_level = GGC_NEW (struct tinst_level);
6801   new_level->decl = d;
6802   new_level->locus = input_location;
6803   new_level->in_system_header_p = in_system_header;
6804   new_level->next = current_tinst_level;
6805   current_tinst_level = new_level;
6806
6807   ++tinst_depth;
6808 #ifdef GATHER_STATISTICS
6809   if (tinst_depth > depth_reached)
6810     depth_reached = tinst_depth;
6811 #endif
6812
6813   ++tinst_level_tick;
6814   return 1;
6815 }
6816
6817 /* We're done instantiating this template; return to the instantiation
6818    context.  */
6819
6820 static void
6821 pop_tinst_level (void)
6822 {
6823   /* Restore the filename and line number stashed away when we started
6824      this instantiation.  */
6825   input_location = current_tinst_level->locus;
6826   current_tinst_level = current_tinst_level->next;
6827   --tinst_depth;
6828   ++tinst_level_tick;
6829 }
6830
6831 /* We're instantiating a deferred template; restore the template
6832    instantiation context in which the instantiation was requested, which
6833    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6834
6835 static tree
6836 reopen_tinst_level (struct tinst_level *level)
6837 {
6838   struct tinst_level *t;
6839
6840   tinst_depth = 0;
6841   for (t = level; t; t = t->next)
6842     ++tinst_depth;
6843
6844   current_tinst_level = level;
6845   pop_tinst_level ();
6846   return level->decl;
6847 }
6848
6849 /* Returns the TINST_LEVEL which gives the original instantiation
6850    context.  */
6851
6852 struct tinst_level *
6853 outermost_tinst_level (void)
6854 {
6855   struct tinst_level *level = current_tinst_level;
6856   if (level)
6857     while (level->next)
6858       level = level->next;
6859   return level;
6860 }
6861
6862 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
6863
6864 bool
6865 parameter_of_template_p (tree parm, tree templ)
6866 {
6867   tree parms;
6868   int i;
6869
6870   if (!parm || !templ)
6871     return false;
6872
6873   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
6874   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6875
6876   parms = DECL_TEMPLATE_PARMS (templ);
6877   parms = INNERMOST_TEMPLATE_PARMS (parms);
6878
6879   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
6880     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
6881       return true;
6882
6883   return false;
6884 }
6885
6886 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6887    vector of template arguments, as for tsubst.
6888
6889    Returns an appropriate tsubst'd friend declaration.  */
6890
6891 static tree
6892 tsubst_friend_function (tree decl, tree args)
6893 {
6894   tree new_friend;
6895
6896   if (TREE_CODE (decl) == FUNCTION_DECL
6897       && DECL_TEMPLATE_INSTANTIATION (decl)
6898       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6899     /* This was a friend declared with an explicit template
6900        argument list, e.g.:
6901
6902        friend void f<>(T);
6903
6904        to indicate that f was a template instantiation, not a new
6905        function declaration.  Now, we have to figure out what
6906        instantiation of what template.  */
6907     {
6908       tree template_id, arglist, fns;
6909       tree new_args;
6910       tree tmpl;
6911       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6912
6913       /* Friend functions are looked up in the containing namespace scope.
6914          We must enter that scope, to avoid finding member functions of the
6915          current class with same name.  */
6916       push_nested_namespace (ns);
6917       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6918                          tf_warning_or_error, NULL_TREE,
6919                          /*integral_constant_expression_p=*/false);
6920       pop_nested_namespace (ns);
6921       arglist = tsubst (DECL_TI_ARGS (decl), args,
6922                         tf_warning_or_error, NULL_TREE);
6923       template_id = lookup_template_function (fns, arglist);
6924
6925       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6926       tmpl = determine_specialization (template_id, new_friend,
6927                                        &new_args,
6928                                        /*need_member_template=*/0,
6929                                        TREE_VEC_LENGTH (args),
6930                                        tsk_none);
6931       return instantiate_template (tmpl, new_args, tf_error);
6932     }
6933
6934   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6935
6936   /* The NEW_FRIEND will look like an instantiation, to the
6937      compiler, but is not an instantiation from the point of view of
6938      the language.  For example, we might have had:
6939
6940      template <class T> struct S {
6941        template <class U> friend void f(T, U);
6942      };
6943
6944      Then, in S<int>, template <class U> void f(int, U) is not an
6945      instantiation of anything.  */
6946   if (new_friend == error_mark_node)
6947     return error_mark_node;
6948
6949   DECL_USE_TEMPLATE (new_friend) = 0;
6950   if (TREE_CODE (decl) == TEMPLATE_DECL)
6951     {
6952       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6953       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6954         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6955     }
6956
6957   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6958      is not a template instantiation and should not be mangled like
6959      one.  Therefore, we forget the mangling here; we'll recompute it
6960      later if we need it.  */
6961   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6962     {
6963       SET_DECL_RTL (new_friend, NULL_RTX);
6964       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6965     }
6966
6967   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6968     {
6969       tree old_decl;
6970       tree new_friend_template_info;
6971       tree new_friend_result_template_info;
6972       tree ns;
6973       int  new_friend_is_defn;
6974
6975       /* We must save some information from NEW_FRIEND before calling
6976          duplicate decls since that function will free NEW_FRIEND if
6977          possible.  */
6978       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6979       new_friend_is_defn =
6980             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6981                            (template_for_substitution (new_friend)))
6982              != NULL_TREE);
6983       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6984         {
6985           /* This declaration is a `primary' template.  */
6986           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6987
6988           new_friend_result_template_info
6989             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6990         }
6991       else
6992         new_friend_result_template_info = NULL_TREE;
6993
6994       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6995       if (new_friend_is_defn)
6996         DECL_INITIAL (new_friend) = error_mark_node;
6997
6998       /* Inside pushdecl_namespace_level, we will push into the
6999          current namespace. However, the friend function should go
7000          into the namespace of the template.  */
7001       ns = decl_namespace_context (new_friend);
7002       push_nested_namespace (ns);
7003       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7004       pop_nested_namespace (ns);
7005
7006       if (old_decl == error_mark_node)
7007         return error_mark_node;
7008
7009       if (old_decl != new_friend)
7010         {
7011           /* This new friend declaration matched an existing
7012              declaration.  For example, given:
7013
7014                template <class T> void f(T);
7015                template <class U> class C {
7016                  template <class T> friend void f(T) {}
7017                };
7018
7019              the friend declaration actually provides the definition
7020              of `f', once C has been instantiated for some type.  So,
7021              old_decl will be the out-of-class template declaration,
7022              while new_friend is the in-class definition.
7023
7024              But, if `f' was called before this point, the
7025              instantiation of `f' will have DECL_TI_ARGS corresponding
7026              to `T' but not to `U', references to which might appear
7027              in the definition of `f'.  Previously, the most general
7028              template for an instantiation of `f' was the out-of-class
7029              version; now it is the in-class version.  Therefore, we
7030              run through all specialization of `f', adding to their
7031              DECL_TI_ARGS appropriately.  In particular, they need a
7032              new set of outer arguments, corresponding to the
7033              arguments for this class instantiation.
7034
7035              The same situation can arise with something like this:
7036
7037                friend void f(int);
7038                template <class T> class C {
7039                  friend void f(T) {}
7040                };
7041
7042              when `C<int>' is instantiated.  Now, `f(int)' is defined
7043              in the class.  */
7044
7045           if (!new_friend_is_defn)
7046             /* On the other hand, if the in-class declaration does
7047                *not* provide a definition, then we don't want to alter
7048                existing definitions.  We can just leave everything
7049                alone.  */
7050             ;
7051           else
7052             {
7053               tree new_template = TI_TEMPLATE (new_friend_template_info);
7054               tree new_args = TI_ARGS (new_friend_template_info);
7055
7056               /* Overwrite whatever template info was there before, if
7057                  any, with the new template information pertaining to
7058                  the declaration.  */
7059               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7060
7061               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7062                 /* We should have called reregister_specialization in
7063                    duplicate_decls.  */
7064                 gcc_assert (retrieve_specialization (new_template,
7065                                                      new_args, 0)
7066                             == old_decl);
7067               else
7068                 {
7069                   tree t;
7070
7071                   /* Indicate that the old function template is a partial
7072                      instantiation.  */
7073                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7074                     = new_friend_result_template_info;
7075
7076                   gcc_assert (new_template
7077                               == most_general_template (new_template));
7078                   gcc_assert (new_template != old_decl);
7079
7080                   /* Reassign any specializations already in the hash table
7081                      to the new more general template, and add the
7082                      additional template args.  */
7083                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7084                        t != NULL_TREE;
7085                        t = TREE_CHAIN (t))
7086                     {
7087                       tree spec = TREE_VALUE (t);
7088                       spec_entry elt;
7089
7090                       elt.tmpl = old_decl;
7091                       elt.args = DECL_TI_ARGS (spec);
7092                       elt.spec = NULL_TREE;
7093
7094                       htab_remove_elt (decl_specializations, &elt);
7095
7096                       DECL_TI_ARGS (spec)
7097                         = add_outermost_template_args (new_args,
7098                                                        DECL_TI_ARGS (spec));
7099
7100                       register_specialization
7101                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7102
7103                     }
7104                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7105                 }
7106             }
7107
7108           /* The information from NEW_FRIEND has been merged into OLD_DECL
7109              by duplicate_decls.  */
7110           new_friend = old_decl;
7111         }
7112     }
7113   else
7114     {
7115       tree context = DECL_CONTEXT (new_friend);
7116       bool dependent_p;
7117
7118       /* In the code
7119            template <class T> class C {
7120              template <class U> friend void C1<U>::f (); // case 1
7121              friend void C2<T>::f ();                    // case 2
7122            };
7123          we only need to make sure CONTEXT is a complete type for
7124          case 2.  To distinguish between the two cases, we note that
7125          CONTEXT of case 1 remains dependent type after tsubst while
7126          this isn't true for case 2.  */
7127       ++processing_template_decl;
7128       dependent_p = dependent_type_p (context);
7129       --processing_template_decl;
7130
7131       if (!dependent_p
7132           && !complete_type_or_else (context, NULL_TREE))
7133         return error_mark_node;
7134
7135       if (COMPLETE_TYPE_P (context))
7136         {
7137           /* Check to see that the declaration is really present, and,
7138              possibly obtain an improved declaration.  */
7139           tree fn = check_classfn (context,
7140                                    new_friend, NULL_TREE);
7141
7142           if (fn)
7143             new_friend = fn;
7144         }
7145     }
7146
7147   return new_friend;
7148 }
7149
7150 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7151    template arguments, as for tsubst.
7152
7153    Returns an appropriate tsubst'd friend type or error_mark_node on
7154    failure.  */
7155
7156 static tree
7157 tsubst_friend_class (tree friend_tmpl, tree args)
7158 {
7159   tree friend_type;
7160   tree tmpl;
7161   tree context;
7162
7163   context = DECL_CONTEXT (friend_tmpl);
7164
7165   if (context)
7166     {
7167       if (TREE_CODE (context) == NAMESPACE_DECL)
7168         push_nested_namespace (context);
7169       else
7170         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7171     }
7172
7173   /* Look for a class template declaration.  We look for hidden names
7174      because two friend declarations of the same template are the
7175      same.  For example, in:
7176
7177        struct A { 
7178          template <typename> friend class F;
7179        };
7180        template <typename> struct B { 
7181          template <typename> friend class F;
7182        };
7183
7184      both F templates are the same.  */
7185   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7186                            /*block_p=*/true, 0, 
7187                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7188
7189   /* But, if we don't find one, it might be because we're in a
7190      situation like this:
7191
7192        template <class T>
7193        struct S {
7194          template <class U>
7195          friend struct S;
7196        };
7197
7198      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7199      for `S<int>', not the TEMPLATE_DECL.  */
7200   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7201     {
7202       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7203       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7204     }
7205
7206   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7207     {
7208       /* The friend template has already been declared.  Just
7209          check to see that the declarations match, and install any new
7210          default parameters.  We must tsubst the default parameters,
7211          of course.  We only need the innermost template parameters
7212          because that is all that redeclare_class_template will look
7213          at.  */
7214       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7215           > TMPL_ARGS_DEPTH (args))
7216         {
7217           tree parms;
7218           location_t saved_input_location;
7219           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7220                                          args, tf_warning_or_error);
7221
7222           saved_input_location = input_location;
7223           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7224           redeclare_class_template (TREE_TYPE (tmpl), parms);
7225           input_location = saved_input_location;
7226           
7227         }
7228
7229       friend_type = TREE_TYPE (tmpl);
7230     }
7231   else
7232     {
7233       /* The friend template has not already been declared.  In this
7234          case, the instantiation of the template class will cause the
7235          injection of this template into the global scope.  */
7236       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7237       if (tmpl == error_mark_node)
7238         return error_mark_node;
7239
7240       /* The new TMPL is not an instantiation of anything, so we
7241          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7242          the new type because that is supposed to be the corresponding
7243          template decl, i.e., TMPL.  */
7244       DECL_USE_TEMPLATE (tmpl) = 0;
7245       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7246       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7247       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7248         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7249
7250       /* Inject this template into the global scope.  */
7251       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7252     }
7253
7254   if (context)
7255     {
7256       if (TREE_CODE (context) == NAMESPACE_DECL)
7257         pop_nested_namespace (context);
7258       else
7259         pop_nested_class ();
7260     }
7261
7262   return friend_type;
7263 }
7264
7265 /* Returns zero if TYPE cannot be completed later due to circularity.
7266    Otherwise returns one.  */
7267
7268 static int
7269 can_complete_type_without_circularity (tree type)
7270 {
7271   if (type == NULL_TREE || type == error_mark_node)
7272     return 0;
7273   else if (COMPLETE_TYPE_P (type))
7274     return 1;
7275   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7276     return can_complete_type_without_circularity (TREE_TYPE (type));
7277   else if (CLASS_TYPE_P (type)
7278            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7279     return 0;
7280   else
7281     return 1;
7282 }
7283
7284 /* Apply any attributes which had to be deferred until instantiation
7285    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7286    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7287
7288 static void
7289 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7290                                 tree args, tsubst_flags_t complain, tree in_decl)
7291 {
7292   tree last_dep = NULL_TREE;
7293   tree t;
7294   tree *p;
7295
7296   for (t = attributes; t; t = TREE_CHAIN (t))
7297     if (ATTR_IS_DEPENDENT (t))
7298       {
7299         last_dep = t;
7300         attributes = copy_list (attributes);
7301         break;
7302       }
7303
7304   if (DECL_P (*decl_p))
7305     {
7306       if (TREE_TYPE (*decl_p) == error_mark_node)
7307         return;
7308       p = &DECL_ATTRIBUTES (*decl_p);
7309     }
7310   else
7311     p = &TYPE_ATTRIBUTES (*decl_p);
7312
7313   if (last_dep)
7314     {
7315       tree late_attrs = NULL_TREE;
7316       tree *q = &late_attrs;
7317
7318       for (*p = attributes; *p; )
7319         {
7320           t = *p;
7321           if (ATTR_IS_DEPENDENT (t))
7322             {
7323               *p = TREE_CHAIN (t);
7324               TREE_CHAIN (t) = NULL_TREE;
7325               /* If the first attribute argument is an identifier, don't
7326                  pass it through tsubst.  Attributes like mode, format,
7327                  cleanup and several target specific attributes expect it
7328                  unmodified.  */
7329               if (TREE_VALUE (t)
7330                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7331                   && TREE_VALUE (TREE_VALUE (t))
7332                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7333                       == IDENTIFIER_NODE))
7334                 {
7335                   tree chain
7336                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7337                                    in_decl,
7338                                    /*integral_constant_expression_p=*/false);
7339                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7340                     TREE_VALUE (t)
7341                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7342                                    chain);
7343                 }
7344               else
7345                 TREE_VALUE (t)
7346                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7347                                  /*integral_constant_expression_p=*/false);
7348               *q = t;
7349               q = &TREE_CHAIN (t);
7350             }
7351           else
7352             p = &TREE_CHAIN (t);
7353         }
7354
7355       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7356     }
7357 }
7358
7359 /* Perform (or defer) access check for typedefs that were referenced
7360    from within the template TMPL code.
7361    This is a subroutine of instantiate_template and instantiate_class_template.
7362    TMPL is the template to consider and TARGS is the list of arguments of
7363    that template.  */
7364
7365 static void
7366 perform_typedefs_access_check (tree tmpl, tree targs)
7367 {
7368   tree t;
7369
7370   if (!tmpl
7371       || (!CLASS_TYPE_P (tmpl)
7372           && TREE_CODE (tmpl) != FUNCTION_DECL))
7373     return;
7374
7375   for (t = get_types_needing_access_check (tmpl); t; t = TREE_CHAIN (t))
7376     {
7377       tree type_decl = TREE_PURPOSE (t);
7378       tree type_scope = TREE_VALUE (t);
7379
7380       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7381         continue;
7382
7383       if (uses_template_parms (type_decl))
7384         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7385       if (uses_template_parms (type_scope))
7386         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7387
7388       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7389                                      type_decl, type_decl);
7390     }
7391 }
7392
7393 tree
7394 instantiate_class_template (tree type)
7395 {
7396   tree templ, args, pattern, t, member;
7397   tree typedecl;
7398   tree pbinfo;
7399   tree base_list;
7400   unsigned int saved_maximum_field_alignment;
7401
7402   if (type == error_mark_node)
7403     return error_mark_node;
7404
7405   if (TYPE_BEING_DEFINED (type)
7406       || COMPLETE_TYPE_P (type)
7407       || uses_template_parms (type))
7408     return type;
7409
7410   /* Figure out which template is being instantiated.  */
7411   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7412   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7413
7414   /* Determine what specialization of the original template to
7415      instantiate.  */
7416   t = most_specialized_class (type, templ);
7417   if (t == error_mark_node)
7418     {
7419       TYPE_BEING_DEFINED (type) = 1;
7420       return error_mark_node;
7421     }
7422   else if (t)
7423     {
7424       /* This TYPE is actually an instantiation of a partial
7425          specialization.  We replace the innermost set of ARGS with
7426          the arguments appropriate for substitution.  For example,
7427          given:
7428
7429            template <class T> struct S {};
7430            template <class T> struct S<T*> {};
7431
7432          and supposing that we are instantiating S<int*>, ARGS will
7433          presently be {int*} -- but we need {int}.  */
7434       pattern = TREE_TYPE (t);
7435       args = TREE_PURPOSE (t);
7436     }
7437   else
7438     {
7439       pattern = TREE_TYPE (templ);
7440       args = CLASSTYPE_TI_ARGS (type);
7441     }
7442
7443   /* If the template we're instantiating is incomplete, then clearly
7444      there's nothing we can do.  */
7445   if (!COMPLETE_TYPE_P (pattern))
7446     return type;
7447
7448   /* If we've recursively instantiated too many templates, stop.  */
7449   if (! push_tinst_level (type))
7450     return type;
7451
7452   /* Now we're really doing the instantiation.  Mark the type as in
7453      the process of being defined.  */
7454   TYPE_BEING_DEFINED (type) = 1;
7455
7456   /* We may be in the middle of deferred access check.  Disable
7457      it now.  */
7458   push_deferring_access_checks (dk_no_deferred);
7459
7460   push_to_top_level ();
7461   /* Use #pragma pack from the template context.  */
7462   saved_maximum_field_alignment = maximum_field_alignment;
7463   maximum_field_alignment = TYPE_PRECISION (pattern);
7464
7465   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7466
7467   /* Set the input location to the most specialized template definition.
7468      This is needed if tsubsting causes an error.  */
7469   typedecl = TYPE_MAIN_DECL (pattern);
7470   input_location = DECL_SOURCE_LOCATION (typedecl);
7471
7472   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7473   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7474   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7475   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7476   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7477   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7478   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7479   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7480   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7481   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7482   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7483   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7484   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7485   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7486   if (ANON_AGGR_TYPE_P (pattern))
7487     SET_ANON_AGGR_TYPE_P (type);
7488   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7489     {
7490       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7491       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7492     }
7493
7494   pbinfo = TYPE_BINFO (pattern);
7495
7496   /* We should never instantiate a nested class before its enclosing
7497      class; we need to look up the nested class by name before we can
7498      instantiate it, and that lookup should instantiate the enclosing
7499      class.  */
7500   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7501               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7502               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7503
7504   base_list = NULL_TREE;
7505   if (BINFO_N_BASE_BINFOS (pbinfo))
7506     {
7507       tree pbase_binfo;
7508       tree context = TYPE_CONTEXT (type);
7509       tree pushed_scope;
7510       int i;
7511
7512       /* We must enter the scope containing the type, as that is where
7513          the accessibility of types named in dependent bases are
7514          looked up from.  */
7515       pushed_scope = push_scope (context ? context : global_namespace);
7516
7517       /* Substitute into each of the bases to determine the actual
7518          basetypes.  */
7519       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7520         {
7521           tree base;
7522           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7523           tree expanded_bases = NULL_TREE;
7524           int idx, len = 1;
7525
7526           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7527             {
7528               expanded_bases = 
7529                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7530                                        args, tf_error, NULL_TREE);
7531               if (expanded_bases == error_mark_node)
7532                 continue;
7533
7534               len = TREE_VEC_LENGTH (expanded_bases);
7535             }
7536
7537           for (idx = 0; idx < len; idx++)
7538             {
7539               if (expanded_bases)
7540                 /* Extract the already-expanded base class.  */
7541                 base = TREE_VEC_ELT (expanded_bases, idx);
7542               else
7543                 /* Substitute to figure out the base class.  */
7544                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7545                                NULL_TREE);
7546
7547               if (base == error_mark_node)
7548                 continue;
7549
7550               base_list = tree_cons (access, base, base_list);
7551               if (BINFO_VIRTUAL_P (pbase_binfo))
7552                 TREE_TYPE (base_list) = integer_type_node;
7553             }
7554         }
7555
7556       /* The list is now in reverse order; correct that.  */
7557       base_list = nreverse (base_list);
7558
7559       if (pushed_scope)
7560         pop_scope (pushed_scope);
7561     }
7562   /* Now call xref_basetypes to set up all the base-class
7563      information.  */
7564   xref_basetypes (type, base_list);
7565
7566   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7567                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7568                                   args, tf_error, NULL_TREE);
7569
7570   /* Now that our base classes are set up, enter the scope of the
7571      class, so that name lookups into base classes, etc. will work
7572      correctly.  This is precisely analogous to what we do in
7573      begin_class_definition when defining an ordinary non-template
7574      class, except we also need to push the enclosing classes.  */
7575   push_nested_class (type);
7576
7577   /* Now members are processed in the order of declaration.  */
7578   for (member = CLASSTYPE_DECL_LIST (pattern);
7579        member; member = TREE_CHAIN (member))
7580     {
7581       tree t = TREE_VALUE (member);
7582
7583       if (TREE_PURPOSE (member))
7584         {
7585           if (TYPE_P (t))
7586             {
7587               /* Build new CLASSTYPE_NESTED_UTDS.  */
7588
7589               tree newtag;
7590               bool class_template_p;
7591
7592               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7593                                   && TYPE_LANG_SPECIFIC (t)
7594                                   && CLASSTYPE_IS_TEMPLATE (t));
7595               /* If the member is a class template, then -- even after
7596                  substitution -- there may be dependent types in the
7597                  template argument list for the class.  We increment
7598                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7599                  that function will assume that no types are dependent
7600                  when outside of a template.  */
7601               if (class_template_p)
7602                 ++processing_template_decl;
7603               newtag = tsubst (t, args, tf_error, NULL_TREE);
7604               if (class_template_p)
7605                 --processing_template_decl;
7606               if (newtag == error_mark_node)
7607                 continue;
7608
7609               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7610                 {
7611                   tree name = TYPE_IDENTIFIER (t);
7612
7613                   if (class_template_p)
7614                     /* Unfortunately, lookup_template_class sets
7615                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7616                        instantiation (i.e., for the type of a member
7617                        template class nested within a template class.)
7618                        This behavior is required for
7619                        maybe_process_partial_specialization to work
7620                        correctly, but is not accurate in this case;
7621                        the TAG is not an instantiation of anything.
7622                        (The corresponding TEMPLATE_DECL is an
7623                        instantiation, but the TYPE is not.) */
7624                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7625
7626                   /* Now, we call pushtag to put this NEWTAG into the scope of
7627                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7628                      pushtag calling push_template_decl.  We don't have to do
7629                      this for enums because it will already have been done in
7630                      tsubst_enum.  */
7631                   if (name)
7632                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7633                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7634                 }
7635             }
7636           else if (TREE_CODE (t) == FUNCTION_DECL
7637                    || DECL_FUNCTION_TEMPLATE_P (t))
7638             {
7639               /* Build new TYPE_METHODS.  */
7640               tree r;
7641
7642               if (TREE_CODE (t) == TEMPLATE_DECL)
7643                 ++processing_template_decl;
7644               r = tsubst (t, args, tf_error, NULL_TREE);
7645               if (TREE_CODE (t) == TEMPLATE_DECL)
7646                 --processing_template_decl;
7647               set_current_access_from_decl (r);
7648               finish_member_declaration (r);
7649             }
7650           else
7651             {
7652               /* Build new TYPE_FIELDS.  */
7653               if (TREE_CODE (t) == STATIC_ASSERT)
7654                 {
7655                   tree condition = 
7656                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7657                                  tf_warning_or_error, NULL_TREE,
7658                                  /*integral_constant_expression_p=*/true);
7659                   finish_static_assert (condition,
7660                                         STATIC_ASSERT_MESSAGE (t), 
7661                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7662                                         /*member_p=*/true);
7663                 }
7664               else if (TREE_CODE (t) != CONST_DECL)
7665                 {
7666                   tree r;
7667
7668                   /* The file and line for this declaration, to
7669                      assist in error message reporting.  Since we
7670                      called push_tinst_level above, we don't need to
7671                      restore these.  */
7672                   input_location = DECL_SOURCE_LOCATION (t);
7673
7674                   if (TREE_CODE (t) == TEMPLATE_DECL)
7675                     ++processing_template_decl;
7676                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7677                   if (TREE_CODE (t) == TEMPLATE_DECL)
7678                     --processing_template_decl;
7679                   if (TREE_CODE (r) == VAR_DECL)
7680                     {
7681                       /* In [temp.inst]:
7682
7683                            [t]he initialization (and any associated
7684                            side-effects) of a static data member does
7685                            not occur unless the static data member is
7686                            itself used in a way that requires the
7687                            definition of the static data member to
7688                            exist.
7689
7690                          Therefore, we do not substitute into the
7691                          initialized for the static data member here.  */
7692                       finish_static_data_member_decl
7693                         (r,
7694                          /*init=*/NULL_TREE,
7695                          /*init_const_expr_p=*/false,
7696                          /*asmspec_tree=*/NULL_TREE,
7697                          /*flags=*/0);
7698                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7699                         check_static_variable_definition (r, TREE_TYPE (r));
7700                     }
7701                   else if (TREE_CODE (r) == FIELD_DECL)
7702                     {
7703                       /* Determine whether R has a valid type and can be
7704                          completed later.  If R is invalid, then it is
7705                          replaced by error_mark_node so that it will not be
7706                          added to TYPE_FIELDS.  */
7707                       tree rtype = TREE_TYPE (r);
7708                       if (can_complete_type_without_circularity (rtype))
7709                         complete_type (rtype);
7710
7711                       if (!COMPLETE_TYPE_P (rtype))
7712                         {
7713                           cxx_incomplete_type_error (r, rtype);
7714                           r = error_mark_node;
7715                         }
7716                     }
7717
7718                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7719                      such a thing will already have been added to the field
7720                      list by tsubst_enum in finish_member_declaration in the
7721                      CLASSTYPE_NESTED_UTDS case above.  */
7722                   if (!(TREE_CODE (r) == TYPE_DECL
7723                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7724                         && DECL_ARTIFICIAL (r)))
7725                     {
7726                       set_current_access_from_decl (r);
7727                       finish_member_declaration (r);
7728                     }
7729                 }
7730             }
7731         }
7732       else
7733         {
7734           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7735             {
7736               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7737
7738               tree friend_type = t;
7739               bool adjust_processing_template_decl = false;
7740
7741               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7742                 {
7743                   /* template <class T> friend class C;  */
7744                   friend_type = tsubst_friend_class (friend_type, args);
7745                   adjust_processing_template_decl = true;
7746                 }
7747               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7748                 {
7749                   /* template <class T> friend class C::D;  */
7750                   friend_type = tsubst (friend_type, args,
7751                                         tf_warning_or_error, NULL_TREE);
7752                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7753                     friend_type = TREE_TYPE (friend_type);
7754                   adjust_processing_template_decl = true;
7755                 }
7756               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7757                 {
7758                   /* This could be either
7759
7760                        friend class T::C;
7761
7762                      when dependent_type_p is false or
7763
7764                        template <class U> friend class T::C;
7765
7766                      otherwise.  */
7767                   friend_type = tsubst (friend_type, args,
7768                                         tf_warning_or_error, NULL_TREE);
7769                   /* Bump processing_template_decl for correct
7770                      dependent_type_p calculation.  */
7771                   ++processing_template_decl;
7772                   if (dependent_type_p (friend_type))
7773                     adjust_processing_template_decl = true;
7774                   --processing_template_decl;
7775                 }
7776               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7777                        && hidden_name_p (TYPE_NAME (friend_type)))
7778                 {
7779                   /* friend class C;
7780
7781                      where C hasn't been declared yet.  Let's lookup name
7782                      from namespace scope directly, bypassing any name that
7783                      come from dependent base class.  */
7784                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7785
7786                   /* The call to xref_tag_from_type does injection for friend
7787                      classes.  */
7788                   push_nested_namespace (ns);
7789                   friend_type =
7790                     xref_tag_from_type (friend_type, NULL_TREE,
7791                                         /*tag_scope=*/ts_current);
7792                   pop_nested_namespace (ns);
7793                 }
7794               else if (uses_template_parms (friend_type))
7795                 /* friend class C<T>;  */
7796                 friend_type = tsubst (friend_type, args,
7797                                       tf_warning_or_error, NULL_TREE);
7798               /* Otherwise it's
7799
7800                    friend class C;
7801
7802                  where C is already declared or
7803
7804                    friend class C<int>;
7805
7806                  We don't have to do anything in these cases.  */
7807
7808               if (adjust_processing_template_decl)
7809                 /* Trick make_friend_class into realizing that the friend
7810                    we're adding is a template, not an ordinary class.  It's
7811                    important that we use make_friend_class since it will
7812                    perform some error-checking and output cross-reference
7813                    information.  */
7814                 ++processing_template_decl;
7815
7816               if (friend_type != error_mark_node)
7817                 make_friend_class (type, friend_type, /*complain=*/false);
7818
7819               if (adjust_processing_template_decl)
7820                 --processing_template_decl;
7821             }
7822           else
7823             {
7824               /* Build new DECL_FRIENDLIST.  */
7825               tree r;
7826
7827               /* The file and line for this declaration, to
7828                  assist in error message reporting.  Since we
7829                  called push_tinst_level above, we don't need to
7830                  restore these.  */
7831               input_location = DECL_SOURCE_LOCATION (t);
7832
7833               if (TREE_CODE (t) == TEMPLATE_DECL)
7834                 {
7835                   ++processing_template_decl;
7836                   push_deferring_access_checks (dk_no_check);
7837                 }
7838
7839               r = tsubst_friend_function (t, args);
7840               add_friend (type, r, /*complain=*/false);
7841               if (TREE_CODE (t) == TEMPLATE_DECL)
7842                 {
7843                   pop_deferring_access_checks ();
7844                   --processing_template_decl;
7845                 }
7846             }
7847         }
7848     }
7849
7850   /* Set the file and line number information to whatever is given for
7851      the class itself.  This puts error messages involving generated
7852      implicit functions at a predictable point, and the same point
7853      that would be used for non-template classes.  */
7854   input_location = DECL_SOURCE_LOCATION (typedecl);
7855
7856   unreverse_member_declarations (type);
7857   finish_struct_1 (type);
7858   TYPE_BEING_DEFINED (type) = 0;
7859
7860   /* Now that the class is complete, instantiate default arguments for
7861      any member functions.  We don't do this earlier because the
7862      default arguments may reference members of the class.  */
7863   if (!PRIMARY_TEMPLATE_P (templ))
7864     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7865       if (TREE_CODE (t) == FUNCTION_DECL
7866           /* Implicitly generated member functions will not have template
7867              information; they are not instantiations, but instead are
7868              created "fresh" for each instantiation.  */
7869           && DECL_TEMPLATE_INFO (t))
7870         tsubst_default_arguments (t);
7871
7872   /* Some typedefs referenced from within the template code need to be access
7873      checked at template instantiation time, i.e now. These types were
7874      added to the template at parsing time. Let's get those and perform
7875      the access checks then.  */
7876   perform_typedefs_access_check (pattern, args);
7877   perform_deferred_access_checks ();
7878   pop_nested_class ();
7879   maximum_field_alignment = saved_maximum_field_alignment;
7880   pop_from_top_level ();
7881   pop_deferring_access_checks ();
7882   pop_tinst_level ();
7883
7884   /* The vtable for a template class can be emitted in any translation
7885      unit in which the class is instantiated.  When there is no key
7886      method, however, finish_struct_1 will already have added TYPE to
7887      the keyed_classes list.  */
7888   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7889     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7890
7891   return type;
7892 }
7893
7894 static tree
7895 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7896 {
7897   tree r;
7898
7899   if (!t)
7900     r = t;
7901   else if (TYPE_P (t))
7902     r = tsubst (t, args, complain, in_decl);
7903   else
7904     {
7905       r = tsubst_expr (t, args, complain, in_decl,
7906                        /*integral_constant_expression_p=*/true);
7907       r = fold_non_dependent_expr (r);
7908     }
7909   return r;
7910 }
7911
7912 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
7913    NONTYPE_ARGUMENT_PACK.  */
7914
7915 static tree
7916 make_fnparm_pack (tree spec_parm)
7917 {
7918   /* Collect all of the extra "packed" parameters into an
7919      argument pack.  */
7920   tree parmvec;
7921   tree parmtypevec;
7922   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
7923   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
7924   int i, len = list_length (spec_parm);
7925
7926   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
7927   parmvec = make_tree_vec (len);
7928   parmtypevec = make_tree_vec (len);
7929   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
7930     {
7931       TREE_VEC_ELT (parmvec, i) = spec_parm;
7932       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
7933     }
7934
7935   /* Build the argument packs.  */
7936   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
7937   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
7938   TREE_TYPE (argpack) = argtypepack;
7939
7940   return argpack;
7941 }        
7942
7943 /* Substitute ARGS into T, which is an pack expansion
7944    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7945    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7946    (if only a partial substitution could be performed) or
7947    ERROR_MARK_NODE if there was an error.  */
7948 tree
7949 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7950                        tree in_decl)
7951 {
7952   tree pattern;
7953   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7954   tree first_arg_pack; int i, len = -1;
7955   tree result;
7956   int incomplete = 0;
7957   bool very_local_specializations = false;
7958
7959   gcc_assert (PACK_EXPANSION_P (t));
7960   pattern = PACK_EXPANSION_PATTERN (t);
7961
7962   /* Determine the argument packs that will instantiate the parameter
7963      packs used in the expansion expression. While we're at it,
7964      compute the number of arguments to be expanded and make sure it
7965      is consistent.  */
7966   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7967        pack = TREE_CHAIN (pack))
7968     {
7969       tree parm_pack = TREE_VALUE (pack);
7970       tree arg_pack = NULL_TREE;
7971       tree orig_arg = NULL_TREE;
7972
7973       if (TREE_CODE (parm_pack) == PARM_DECL)
7974         {
7975           arg_pack = retrieve_local_specialization (parm_pack);
7976           if (arg_pack == NULL_TREE)
7977             {
7978               /* This can happen for a parameter name used later in a function
7979                  declaration (such as in a late-specified return type).  Just
7980                  make a dummy decl, since it's only used for its type.  */
7981               gcc_assert (cp_unevaluated_operand != 0);
7982               arg_pack = tsubst_decl (parm_pack, args, complain);
7983               arg_pack = make_fnparm_pack (arg_pack);
7984             }
7985         }
7986       else
7987         {
7988           int level, idx, levels;
7989           template_parm_level_and_index (parm_pack, &level, &idx);
7990
7991           levels = TMPL_ARGS_DEPTH (args);
7992           if (level <= levels)
7993             arg_pack = TMPL_ARG (args, level, idx);
7994         }
7995
7996       orig_arg = arg_pack;
7997       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7998         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7999       
8000       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8001         /* This can only happen if we forget to expand an argument
8002            pack somewhere else. Just return an error, silently.  */
8003         {
8004           result = make_tree_vec (1);
8005           TREE_VEC_ELT (result, 0) = error_mark_node;
8006           return result;
8007         }
8008
8009       if (arg_pack
8010           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8011           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8012         {
8013           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8014           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8015           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8016               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8017             /* The argument pack that the parameter maps to is just an
8018                expansion of the parameter itself, such as one would
8019                find in the implicit typedef of a class inside the
8020                class itself.  Consider this parameter "unsubstituted",
8021                so that we will maintain the outer pack expansion.  */
8022             arg_pack = NULL_TREE;
8023         }
8024           
8025       if (arg_pack)
8026         {
8027           int my_len = 
8028             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8029
8030           /* It's all-or-nothing with incomplete argument packs.  */
8031           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8032             return error_mark_node;
8033           
8034           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8035             incomplete = 1;
8036
8037           if (len < 0)
8038             {
8039               len = my_len;
8040               first_arg_pack = arg_pack;
8041             }
8042           else if (len != my_len)
8043             {
8044               if (incomplete)
8045                 /* We got explicit args for some packs but not others;
8046                    do nothing now and try again after deduction.  */
8047                 return t;
8048               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8049                 error ("mismatched argument pack lengths while expanding "
8050                        "%<%T%>",
8051                        pattern);
8052               else
8053                 error ("mismatched argument pack lengths while expanding "
8054                        "%<%E%>",
8055                        pattern);
8056               return error_mark_node;
8057             }
8058
8059           /* Keep track of the parameter packs and their corresponding
8060              argument packs.  */
8061           packs = tree_cons (parm_pack, arg_pack, packs);
8062           TREE_TYPE (packs) = orig_arg;
8063         }
8064       else
8065         /* We can't substitute for this parameter pack.  */
8066         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8067                                          TREE_VALUE (pack),
8068                                          unsubstituted_packs);
8069     }
8070
8071   /* We cannot expand this expansion expression, because we don't have
8072      all of the argument packs we need. Substitute into the pattern
8073      and return a PACK_EXPANSION_*. The caller will need to deal with
8074      that.  */
8075   if (unsubstituted_packs)
8076     {
8077       tree new_pat;
8078       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8079         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8080                                /*integral_constant_expression_p=*/false);
8081       else
8082         new_pat = tsubst (pattern, args, complain, in_decl);
8083       return make_pack_expansion (new_pat);
8084     }
8085
8086   /* We could not find any argument packs that work.  */
8087   if (len < 0)
8088     return error_mark_node;
8089
8090   if (!local_specializations)
8091     {
8092       /* We're in a late-specified return type, so we don't have a local
8093          specializations table.  Create one for doing this expansion.  */
8094       very_local_specializations = true;
8095       local_specializations = htab_create (37,
8096                                            hash_local_specialization,
8097                                            eq_local_specializations,
8098                                            NULL);
8099     }
8100
8101   /* For each argument in each argument pack, substitute into the
8102      pattern.  */
8103   result = make_tree_vec (len + incomplete);
8104   for (i = 0; i < len + incomplete; ++i)
8105     {
8106       /* For parameter pack, change the substitution of the parameter
8107          pack to the ith argument in its argument pack, then expand
8108          the pattern.  */
8109       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8110         {
8111           tree parm = TREE_PURPOSE (pack);
8112
8113           if (TREE_CODE (parm) == PARM_DECL)
8114             {
8115               /* Select the Ith argument from the pack.  */
8116               tree arg = make_node (ARGUMENT_PACK_SELECT);
8117               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8118               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8119               mark_used (parm);
8120               register_local_specialization (arg, parm);
8121             }
8122           else
8123             {
8124               tree value = parm;
8125               int idx, level;
8126               template_parm_level_and_index (parm, &level, &idx);
8127               
8128               if (i < len) 
8129                 {
8130                   /* Select the Ith argument from the pack. */
8131                   value = make_node (ARGUMENT_PACK_SELECT);
8132                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8133                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8134                 }
8135
8136               /* Update the corresponding argument.  */
8137               TMPL_ARG (args, level, idx) = value;
8138             }
8139         }
8140
8141       /* Substitute into the PATTERN with the altered arguments.  */
8142       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8143         TREE_VEC_ELT (result, i) = 
8144           tsubst_expr (pattern, args, complain, in_decl,
8145                        /*integral_constant_expression_p=*/false);
8146       else
8147         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8148
8149       if (i == len)
8150         /* When we have incomplete argument packs, the last "expanded"
8151            result is itself a pack expansion, which allows us
8152            to deduce more arguments.  */
8153         TREE_VEC_ELT (result, i) = 
8154           make_pack_expansion (TREE_VEC_ELT (result, i));
8155
8156       if (TREE_VEC_ELT (result, i) == error_mark_node)
8157         {
8158           result = error_mark_node;
8159           break;
8160         }
8161     }
8162
8163   /* Update ARGS to restore the substitution from parameter packs to
8164      their argument packs.  */
8165   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8166     {
8167       tree parm = TREE_PURPOSE (pack);
8168
8169       if (TREE_CODE (parm) == PARM_DECL)
8170         register_local_specialization (TREE_TYPE (pack), parm);
8171       else
8172         {
8173           int idx, level;
8174           template_parm_level_and_index (parm, &level, &idx);
8175           
8176           /* Update the corresponding argument.  */
8177           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8178             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8179               TREE_TYPE (pack);
8180           else
8181             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8182         }
8183     }
8184
8185   if (very_local_specializations)
8186     {
8187       htab_delete (local_specializations);
8188       local_specializations = NULL;
8189     }
8190   
8191   return result;
8192 }
8193
8194 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8195    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8196    parameter packs; all parms generated from a function parameter pack will
8197    have the same DECL_PARM_INDEX.  */
8198
8199 tree
8200 get_pattern_parm (tree parm, tree tmpl)
8201 {
8202   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8203   tree patparm;
8204
8205   if (DECL_ARTIFICIAL (parm))
8206     {
8207       for (patparm = DECL_ARGUMENTS (pattern);
8208            patparm; patparm = TREE_CHAIN (patparm))
8209         if (DECL_ARTIFICIAL (patparm)
8210             && DECL_NAME (parm) == DECL_NAME (patparm))
8211           break;
8212     }
8213   else
8214     {
8215       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8216       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8217       gcc_assert (DECL_PARM_INDEX (patparm)
8218                   == DECL_PARM_INDEX (parm));
8219     }
8220
8221   return patparm;
8222 }
8223
8224 /* Substitute ARGS into the vector or list of template arguments T.  */
8225
8226 static tree
8227 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8228 {
8229   tree orig_t = t;
8230   int len = TREE_VEC_LENGTH (t);
8231   int need_new = 0, i, expanded_len_adjust = 0, out;
8232   tree *elts = (tree *) alloca (len * sizeof (tree));
8233
8234   for (i = 0; i < len; i++)
8235     {
8236       tree orig_arg = TREE_VEC_ELT (t, i);
8237       tree new_arg;
8238
8239       if (TREE_CODE (orig_arg) == TREE_VEC)
8240         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8241       else if (PACK_EXPANSION_P (orig_arg))
8242         {
8243           /* Substitute into an expansion expression.  */
8244           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8245
8246           if (TREE_CODE (new_arg) == TREE_VEC)
8247             /* Add to the expanded length adjustment the number of
8248                expanded arguments. We subtract one from this
8249                measurement, because the argument pack expression
8250                itself is already counted as 1 in
8251                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8252                the argument pack is empty.  */
8253             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8254         }
8255       else if (ARGUMENT_PACK_P (orig_arg))
8256         {
8257           /* Substitute into each of the arguments.  */
8258           new_arg = TYPE_P (orig_arg)
8259             ? cxx_make_type (TREE_CODE (orig_arg))
8260             : make_node (TREE_CODE (orig_arg));
8261           
8262           SET_ARGUMENT_PACK_ARGS (
8263             new_arg,
8264             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8265                                   args, complain, in_decl));
8266
8267           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8268             new_arg = error_mark_node;
8269
8270           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8271             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8272                                           complain, in_decl);
8273             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8274
8275             if (TREE_TYPE (new_arg) == error_mark_node)
8276               new_arg = error_mark_node;
8277           }
8278         }
8279       else
8280         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8281
8282       if (new_arg == error_mark_node)
8283         return error_mark_node;
8284
8285       elts[i] = new_arg;
8286       if (new_arg != orig_arg)
8287         need_new = 1;
8288     }
8289
8290   if (!need_new)
8291     return t;
8292
8293   /* Make space for the expanded arguments coming from template
8294      argument packs.  */
8295   t = make_tree_vec (len + expanded_len_adjust);
8296   for (i = 0, out = 0; i < len; i++)
8297     {
8298       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8299            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8300           && TREE_CODE (elts[i]) == TREE_VEC)
8301         {
8302           int idx;
8303
8304           /* Now expand the template argument pack "in place".  */
8305           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8306             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8307         }
8308       else
8309         {
8310           TREE_VEC_ELT (t, out) = elts[i];
8311           out++;
8312         }
8313     }
8314
8315   return t;
8316 }
8317
8318 /* Return the result of substituting ARGS into the template parameters
8319    given by PARMS.  If there are m levels of ARGS and m + n levels of
8320    PARMS, then the result will contain n levels of PARMS.  For
8321    example, if PARMS is `template <class T> template <class U>
8322    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8323    result will be `template <int*, double, class V>'.  */
8324
8325 static tree
8326 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8327 {
8328   tree r = NULL_TREE;
8329   tree* new_parms;
8330
8331   /* When substituting into a template, we must set
8332      PROCESSING_TEMPLATE_DECL as the template parameters may be
8333      dependent if they are based on one-another, and the dependency
8334      predicates are short-circuit outside of templates.  */
8335   ++processing_template_decl;
8336
8337   for (new_parms = &r;
8338        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8339        new_parms = &(TREE_CHAIN (*new_parms)),
8340          parms = TREE_CHAIN (parms))
8341     {
8342       tree new_vec =
8343         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8344       int i;
8345
8346       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8347         {
8348           tree tuple;
8349           tree default_value;
8350           tree parm_decl;
8351
8352           if (parms == error_mark_node)
8353             continue;
8354
8355           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8356
8357           if (tuple == error_mark_node)
8358             continue;
8359
8360           default_value = TREE_PURPOSE (tuple);
8361           parm_decl = TREE_VALUE (tuple);
8362
8363           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8364           if (TREE_CODE (parm_decl) == PARM_DECL
8365               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8366             parm_decl = error_mark_node;
8367           default_value = tsubst_template_arg (default_value, args,
8368                                                complain, NULL_TREE);
8369
8370           tuple = build_tree_list (default_value, parm_decl);
8371           TREE_VEC_ELT (new_vec, i) = tuple;
8372         }
8373
8374       *new_parms =
8375         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8376                              - TMPL_ARGS_DEPTH (args)),
8377                    new_vec, NULL_TREE);
8378     }
8379
8380   --processing_template_decl;
8381
8382   return r;
8383 }
8384
8385 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8386    type T.  If T is not an aggregate or enumeration type, it is
8387    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8388    ENTERING_SCOPE is nonzero, T is the context for a template which
8389    we are presently tsubst'ing.  Return the substituted value.  */
8390
8391 static tree
8392 tsubst_aggr_type (tree t,
8393                   tree args,
8394                   tsubst_flags_t complain,
8395                   tree in_decl,
8396                   int entering_scope)
8397 {
8398   if (t == NULL_TREE)
8399     return NULL_TREE;
8400
8401   switch (TREE_CODE (t))
8402     {
8403     case RECORD_TYPE:
8404       if (TYPE_PTRMEMFUNC_P (t))
8405         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8406
8407       /* Else fall through.  */
8408     case ENUMERAL_TYPE:
8409     case UNION_TYPE:
8410       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8411         {
8412           tree argvec;
8413           tree context;
8414           tree r;
8415           int saved_unevaluated_operand;
8416           int saved_inhibit_evaluation_warnings;
8417
8418           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8419           saved_unevaluated_operand = cp_unevaluated_operand;
8420           cp_unevaluated_operand = 0;
8421           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8422           c_inhibit_evaluation_warnings = 0;
8423
8424           /* First, determine the context for the type we are looking
8425              up.  */
8426           context = TYPE_CONTEXT (t);
8427           if (context)
8428             {
8429               context = tsubst_aggr_type (context, args, complain,
8430                                           in_decl, /*entering_scope=*/1);
8431               /* If context is a nested class inside a class template,
8432                  it may still need to be instantiated (c++/33959).  */
8433               if (TYPE_P (context))
8434                 context = complete_type (context);
8435             }
8436
8437           /* Then, figure out what arguments are appropriate for the
8438              type we are trying to find.  For example, given:
8439
8440                template <class T> struct S;
8441                template <class T, class U> void f(T, U) { S<U> su; }
8442
8443              and supposing that we are instantiating f<int, double>,
8444              then our ARGS will be {int, double}, but, when looking up
8445              S we only want {double}.  */
8446           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8447                                          complain, in_decl);
8448           if (argvec == error_mark_node)
8449             r = error_mark_node;
8450           else
8451             {
8452               r = lookup_template_class (t, argvec, in_decl, context,
8453                                          entering_scope, complain);
8454               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8455             }
8456
8457           cp_unevaluated_operand = saved_unevaluated_operand;
8458           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8459
8460           return r;
8461         }
8462       else
8463         /* This is not a template type, so there's nothing to do.  */
8464         return t;
8465
8466     default:
8467       return tsubst (t, args, complain, in_decl);
8468     }
8469 }
8470
8471 /* Substitute into the default argument ARG (a default argument for
8472    FN), which has the indicated TYPE.  */
8473
8474 tree
8475 tsubst_default_argument (tree fn, tree type, tree arg)
8476 {
8477   tree saved_class_ptr = NULL_TREE;
8478   tree saved_class_ref = NULL_TREE;
8479
8480   /* This default argument came from a template.  Instantiate the
8481      default argument here, not in tsubst.  In the case of
8482      something like:
8483
8484        template <class T>
8485        struct S {
8486          static T t();
8487          void f(T = t());
8488        };
8489
8490      we must be careful to do name lookup in the scope of S<T>,
8491      rather than in the current class.  */
8492   push_access_scope (fn);
8493   /* The "this" pointer is not valid in a default argument.  */
8494   if (cfun)
8495     {
8496       saved_class_ptr = current_class_ptr;
8497       cp_function_chain->x_current_class_ptr = NULL_TREE;
8498       saved_class_ref = current_class_ref;
8499       cp_function_chain->x_current_class_ref = NULL_TREE;
8500     }
8501
8502   push_deferring_access_checks(dk_no_deferred);
8503   /* The default argument expression may cause implicitly defined
8504      member functions to be synthesized, which will result in garbage
8505      collection.  We must treat this situation as if we were within
8506      the body of function so as to avoid collecting live data on the
8507      stack.  */
8508   ++function_depth;
8509   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8510                      tf_warning_or_error, NULL_TREE,
8511                      /*integral_constant_expression_p=*/false);
8512   --function_depth;
8513   pop_deferring_access_checks();
8514
8515   /* Restore the "this" pointer.  */
8516   if (cfun)
8517     {
8518       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8519       cp_function_chain->x_current_class_ref = saved_class_ref;
8520     }
8521
8522   /* Make sure the default argument is reasonable.  */
8523   arg = check_default_argument (type, arg);
8524
8525   pop_access_scope (fn);
8526
8527   return arg;
8528 }
8529
8530 /* Substitute into all the default arguments for FN.  */
8531
8532 static void
8533 tsubst_default_arguments (tree fn)
8534 {
8535   tree arg;
8536   tree tmpl_args;
8537
8538   tmpl_args = DECL_TI_ARGS (fn);
8539
8540   /* If this function is not yet instantiated, we certainly don't need
8541      its default arguments.  */
8542   if (uses_template_parms (tmpl_args))
8543     return;
8544
8545   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8546        arg;
8547        arg = TREE_CHAIN (arg))
8548     if (TREE_PURPOSE (arg))
8549       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8550                                                     TREE_VALUE (arg),
8551                                                     TREE_PURPOSE (arg));
8552 }
8553
8554 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8555    result of the substitution.  Issue error and warning messages under
8556    control of COMPLAIN.  */
8557
8558 static tree
8559 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8560 {
8561 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8562   location_t saved_loc;
8563   tree r = NULL_TREE;
8564   tree in_decl = t;
8565   hashval_t hash = 0;
8566
8567   /* Set the filename and linenumber to improve error-reporting.  */
8568   saved_loc = input_location;
8569   input_location = DECL_SOURCE_LOCATION (t);
8570
8571   switch (TREE_CODE (t))
8572     {
8573     case TEMPLATE_DECL:
8574       {
8575         /* We can get here when processing a member function template,
8576            member class template, or template template parameter.  */
8577         tree decl = DECL_TEMPLATE_RESULT (t);
8578         tree spec;
8579         tree tmpl_args;
8580         tree full_args;
8581
8582         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8583           {
8584             /* Template template parameter is treated here.  */
8585             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8586             if (new_type == error_mark_node)
8587               RETURN (error_mark_node);
8588
8589             r = copy_decl (t);
8590             TREE_CHAIN (r) = NULL_TREE;
8591             TREE_TYPE (r) = new_type;
8592             DECL_TEMPLATE_RESULT (r)
8593               = build_decl (DECL_SOURCE_LOCATION (decl),
8594                             TYPE_DECL, DECL_NAME (decl), new_type);
8595             DECL_TEMPLATE_PARMS (r)
8596               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8597                                        complain);
8598             TYPE_NAME (new_type) = r;
8599             break;
8600           }
8601
8602         /* We might already have an instance of this template.
8603            The ARGS are for the surrounding class type, so the
8604            full args contain the tsubst'd args for the context,
8605            plus the innermost args from the template decl.  */
8606         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8607           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8608           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8609         /* Because this is a template, the arguments will still be
8610            dependent, even after substitution.  If
8611            PROCESSING_TEMPLATE_DECL is not set, the dependency
8612            predicates will short-circuit.  */
8613         ++processing_template_decl;
8614         full_args = tsubst_template_args (tmpl_args, args,
8615                                           complain, in_decl);
8616         --processing_template_decl;
8617         if (full_args == error_mark_node)
8618           RETURN (error_mark_node);
8619
8620         /* If this is a default template template argument,
8621            tsubst might not have changed anything.  */
8622         if (full_args == tmpl_args)
8623           RETURN (t);
8624
8625         hash = hash_tmpl_and_args (t, full_args);
8626         spec = retrieve_specialization (t, full_args, hash);
8627         if (spec != NULL_TREE)
8628           {
8629             r = spec;
8630             break;
8631           }
8632
8633         /* Make a new template decl.  It will be similar to the
8634            original, but will record the current template arguments.
8635            We also create a new function declaration, which is just
8636            like the old one, but points to this new template, rather
8637            than the old one.  */
8638         r = copy_decl (t);
8639         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8640         TREE_CHAIN (r) = NULL_TREE;
8641
8642         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
8643
8644         if (TREE_CODE (decl) == TYPE_DECL)
8645           {
8646             tree new_type;
8647             ++processing_template_decl;
8648             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8649             --processing_template_decl;
8650             if (new_type == error_mark_node)
8651               RETURN (error_mark_node);
8652
8653             TREE_TYPE (r) = new_type;
8654             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8655             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8656             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8657             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8658           }
8659         else
8660           {
8661             tree new_decl;
8662             ++processing_template_decl;
8663             new_decl = tsubst (decl, args, complain, in_decl);
8664             --processing_template_decl;
8665             if (new_decl == error_mark_node)
8666               RETURN (error_mark_node);
8667
8668             DECL_TEMPLATE_RESULT (r) = new_decl;
8669             DECL_TI_TEMPLATE (new_decl) = r;
8670             TREE_TYPE (r) = TREE_TYPE (new_decl);
8671             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8672             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8673           }
8674
8675         SET_DECL_IMPLICIT_INSTANTIATION (r);
8676         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8677         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8678
8679         /* The template parameters for this new template are all the
8680            template parameters for the old template, except the
8681            outermost level of parameters.  */
8682         DECL_TEMPLATE_PARMS (r)
8683           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8684                                    complain);
8685
8686         if (PRIMARY_TEMPLATE_P (t))
8687           DECL_PRIMARY_TEMPLATE (r) = r;
8688
8689         if (TREE_CODE (decl) != TYPE_DECL)
8690           /* Record this non-type partial instantiation.  */
8691           register_specialization (r, t,
8692                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8693                                    false, hash);
8694       }
8695       break;
8696
8697     case FUNCTION_DECL:
8698       {
8699         tree ctx;
8700         tree argvec = NULL_TREE;
8701         tree *friends;
8702         tree gen_tmpl;
8703         tree type;
8704         int member;
8705         int args_depth;
8706         int parms_depth;
8707
8708         /* Nobody should be tsubst'ing into non-template functions.  */
8709         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8710
8711         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8712           {
8713             tree spec;
8714             bool dependent_p;
8715
8716             /* If T is not dependent, just return it.  We have to
8717                increment PROCESSING_TEMPLATE_DECL because
8718                value_dependent_expression_p assumes that nothing is
8719                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8720             ++processing_template_decl;
8721             dependent_p = value_dependent_expression_p (t);
8722             --processing_template_decl;
8723             if (!dependent_p)
8724               RETURN (t);
8725
8726             /* Calculate the most general template of which R is a
8727                specialization, and the complete set of arguments used to
8728                specialize R.  */
8729             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8730             argvec = tsubst_template_args (DECL_TI_ARGS
8731                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8732                                            args, complain, in_decl);
8733
8734             /* Check to see if we already have this specialization.  */
8735             hash = hash_tmpl_and_args (gen_tmpl, argvec);
8736             spec = retrieve_specialization (gen_tmpl, argvec, hash);
8737
8738             if (spec)
8739               {
8740                 r = spec;
8741                 break;
8742               }
8743
8744             /* We can see more levels of arguments than parameters if
8745                there was a specialization of a member template, like
8746                this:
8747
8748                  template <class T> struct S { template <class U> void f(); }
8749                  template <> template <class U> void S<int>::f(U);
8750
8751                Here, we'll be substituting into the specialization,
8752                because that's where we can find the code we actually
8753                want to generate, but we'll have enough arguments for
8754                the most general template.
8755
8756                We also deal with the peculiar case:
8757
8758                  template <class T> struct S {
8759                    template <class U> friend void f();
8760                  };
8761                  template <class U> void f() {}
8762                  template S<int>;
8763                  template void f<double>();
8764
8765                Here, the ARGS for the instantiation of will be {int,
8766                double}.  But, we only need as many ARGS as there are
8767                levels of template parameters in CODE_PATTERN.  We are
8768                careful not to get fooled into reducing the ARGS in
8769                situations like:
8770
8771                  template <class T> struct S { template <class U> void f(U); }
8772                  template <class T> template <> void S<T>::f(int) {}
8773
8774                which we can spot because the pattern will be a
8775                specialization in this case.  */
8776             args_depth = TMPL_ARGS_DEPTH (args);
8777             parms_depth =
8778               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8779             if (args_depth > parms_depth
8780                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8781               args = get_innermost_template_args (args, parms_depth);
8782           }
8783         else
8784           {
8785             /* This special case arises when we have something like this:
8786
8787                  template <class T> struct S {
8788                    friend void f<int>(int, double);
8789                  };
8790
8791                Here, the DECL_TI_TEMPLATE for the friend declaration
8792                will be an IDENTIFIER_NODE.  We are being called from
8793                tsubst_friend_function, and we want only to create a
8794                new decl (R) with appropriate types so that we can call
8795                determine_specialization.  */
8796             gen_tmpl = NULL_TREE;
8797           }
8798
8799         if (DECL_CLASS_SCOPE_P (t))
8800           {
8801             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8802               member = 2;
8803             else
8804               member = 1;
8805             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8806                                     complain, t, /*entering_scope=*/1);
8807           }
8808         else
8809           {
8810             member = 0;
8811             ctx = DECL_CONTEXT (t);
8812           }
8813         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8814         if (type == error_mark_node)
8815           RETURN (error_mark_node);
8816
8817         /* We do NOT check for matching decls pushed separately at this
8818            point, as they may not represent instantiations of this
8819            template, and in any case are considered separate under the
8820            discrete model.  */
8821         r = copy_decl (t);
8822         DECL_USE_TEMPLATE (r) = 0;
8823         TREE_TYPE (r) = type;
8824         /* Clear out the mangled name and RTL for the instantiation.  */
8825         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8826         SET_DECL_RTL (r, NULL_RTX);
8827         /* Leave DECL_INITIAL set on deleted instantiations.  */
8828         if (!DECL_DELETED_FN (r))
8829           DECL_INITIAL (r) = NULL_TREE;
8830         DECL_CONTEXT (r) = ctx;
8831
8832         if (member && DECL_CONV_FN_P (r))
8833           /* Type-conversion operator.  Reconstruct the name, in
8834              case it's the name of one of the template's parameters.  */
8835           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8836
8837         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8838                                      complain, t);
8839         DECL_RESULT (r) = NULL_TREE;
8840
8841         TREE_STATIC (r) = 0;
8842         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8843         DECL_EXTERNAL (r) = 1;
8844         /* If this is an instantiation of a function with internal
8845            linkage, we already know what object file linkage will be
8846            assigned to the instantiation.  */
8847         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8848         DECL_DEFER_OUTPUT (r) = 0;
8849         TREE_CHAIN (r) = NULL_TREE;
8850         DECL_PENDING_INLINE_INFO (r) = 0;
8851         DECL_PENDING_INLINE_P (r) = 0;
8852         DECL_SAVED_TREE (r) = NULL_TREE;
8853         DECL_STRUCT_FUNCTION (r) = NULL;
8854         TREE_USED (r) = 0;
8855         /* We'll re-clone as appropriate in instantiate_template.  */
8856         DECL_CLONED_FUNCTION (r) = NULL_TREE;
8857
8858         /* If we aren't complaining now, return on error before we register
8859            the specialization so that we'll complain eventually.  */
8860         if ((complain & tf_error) == 0
8861             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
8862             && !grok_op_properties (r, /*complain=*/false))
8863           RETURN (error_mark_node);
8864
8865         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8866            this in the special friend case mentioned above where
8867            GEN_TMPL is NULL.  */
8868         if (gen_tmpl)
8869           {
8870             DECL_TEMPLATE_INFO (r)
8871               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8872             SET_DECL_IMPLICIT_INSTANTIATION (r);
8873             register_specialization (r, gen_tmpl, argvec, false, hash);
8874
8875             /* We're not supposed to instantiate default arguments
8876                until they are called, for a template.  But, for a
8877                declaration like:
8878
8879                  template <class T> void f ()
8880                  { extern void g(int i = T()); }
8881
8882                we should do the substitution when the template is
8883                instantiated.  We handle the member function case in
8884                instantiate_class_template since the default arguments
8885                might refer to other members of the class.  */
8886             if (!member
8887                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8888                 && !uses_template_parms (argvec))
8889               tsubst_default_arguments (r);
8890           }
8891         else
8892           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8893
8894         /* Copy the list of befriending classes.  */
8895         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8896              *friends;
8897              friends = &TREE_CHAIN (*friends))
8898           {
8899             *friends = copy_node (*friends);
8900             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8901                                             args, complain,
8902                                             in_decl);
8903           }
8904
8905         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8906           {
8907             maybe_retrofit_in_chrg (r);
8908             if (DECL_CONSTRUCTOR_P (r))
8909               grok_ctor_properties (ctx, r);
8910             /* If this is an instantiation of a member template, clone it.
8911                If it isn't, that'll be handled by
8912                clone_constructors_and_destructors.  */
8913             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8914               clone_function_decl (r, /*update_method_vec_p=*/0);
8915           }
8916         else if ((complain & tf_error) != 0
8917                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
8918                  && !grok_op_properties (r, /*complain=*/true))
8919           RETURN (error_mark_node);
8920
8921         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8922           SET_DECL_FRIEND_CONTEXT (r,
8923                                    tsubst (DECL_FRIEND_CONTEXT (t),
8924                                             args, complain, in_decl));
8925
8926         /* Possibly limit visibility based on template args.  */
8927         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8928         if (DECL_VISIBILITY_SPECIFIED (t))
8929           {
8930             DECL_VISIBILITY_SPECIFIED (r) = 0;
8931             DECL_ATTRIBUTES (r)
8932               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8933           }
8934         determine_visibility (r);
8935         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
8936             && !processing_template_decl)
8937           defaulted_late_check (r);
8938
8939         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8940                                         args, complain, in_decl);
8941       }
8942       break;
8943
8944     case PARM_DECL:
8945       {
8946         tree type = NULL_TREE;
8947         int i, len = 1;
8948         tree expanded_types = NULL_TREE;
8949         tree prev_r = NULL_TREE;
8950         tree first_r = NULL_TREE;
8951
8952         if (FUNCTION_PARAMETER_PACK_P (t))
8953           {
8954             /* If there is a local specialization that isn't a
8955                parameter pack, it means that we're doing a "simple"
8956                substitution from inside tsubst_pack_expansion. Just
8957                return the local specialization (which will be a single
8958                parm).  */
8959             tree spec = retrieve_local_specialization (t);
8960             if (spec 
8961                 && TREE_CODE (spec) == PARM_DECL
8962                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8963               RETURN (spec);
8964
8965             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8966                the parameters in this function parameter pack.  */
8967             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8968                                                     complain, in_decl);
8969             if (TREE_CODE (expanded_types) == TREE_VEC)
8970               {
8971                 len = TREE_VEC_LENGTH (expanded_types);
8972
8973                 /* Zero-length parameter packs are boring. Just substitute
8974                    into the chain.  */
8975                 if (len == 0)
8976                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
8977                                   TREE_CHAIN (t)));
8978               }
8979             else
8980               {
8981                 /* All we did was update the type. Make a note of that.  */
8982                 type = expanded_types;
8983                 expanded_types = NULL_TREE;
8984               }
8985           }
8986
8987         /* Loop through all of the parameter's we'll build. When T is
8988            a function parameter pack, LEN is the number of expanded
8989            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8990         r = NULL_TREE;
8991         for (i = 0; i < len; ++i)
8992           {
8993             prev_r = r;
8994             r = copy_node (t);
8995             if (DECL_TEMPLATE_PARM_P (t))
8996               SET_DECL_TEMPLATE_PARM_P (r);
8997
8998             /* An argument of a function parameter pack is not a parameter
8999                pack.  */
9000             FUNCTION_PARAMETER_PACK_P (r) = false;
9001
9002             if (expanded_types)
9003               /* We're on the Ith parameter of the function parameter
9004                  pack.  */
9005               {
9006                 /* Get the Ith type.  */
9007                 type = TREE_VEC_ELT (expanded_types, i);
9008
9009                 if (DECL_NAME (r))
9010                   /* Rename the parameter to include the index.  */
9011                   DECL_NAME (r) =
9012                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9013               }
9014             else if (!type)
9015               /* We're dealing with a normal parameter.  */
9016               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9017
9018             type = type_decays_to (type);
9019             TREE_TYPE (r) = type;
9020             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9021
9022             if (DECL_INITIAL (r))
9023               {
9024                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9025                   DECL_INITIAL (r) = TREE_TYPE (r);
9026                 else
9027                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9028                                              complain, in_decl);
9029               }
9030
9031             DECL_CONTEXT (r) = NULL_TREE;
9032
9033             if (!DECL_TEMPLATE_PARM_P (r))
9034               DECL_ARG_TYPE (r) = type_passed_as (type);
9035
9036             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9037                                             args, complain, in_decl);
9038
9039             /* Keep track of the first new parameter we
9040                generate. That's what will be returned to the
9041                caller.  */
9042             if (!first_r)
9043               first_r = r;
9044
9045             /* Build a proper chain of parameters when substituting
9046                into a function parameter pack.  */
9047             if (prev_r)
9048               TREE_CHAIN (prev_r) = r;
9049           }
9050
9051         if (TREE_CHAIN (t))
9052           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
9053                                    complain, TREE_CHAIN (t));
9054
9055         /* FIRST_R contains the start of the chain we've built.  */
9056         r = first_r;
9057       }
9058       break;
9059
9060     case FIELD_DECL:
9061       {
9062         tree type;
9063
9064         r = copy_decl (t);
9065         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9066         if (type == error_mark_node)
9067           RETURN (error_mark_node);
9068         TREE_TYPE (r) = type;
9069         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9070
9071         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9072         DECL_INITIAL (r)
9073           = tsubst_expr (DECL_INITIAL (t), args,
9074                          complain, in_decl,
9075                          /*integral_constant_expression_p=*/true);
9076         /* We don't have to set DECL_CONTEXT here; it is set by
9077            finish_member_declaration.  */
9078         TREE_CHAIN (r) = NULL_TREE;
9079         if (VOID_TYPE_P (type))
9080           error ("instantiation of %q+D as type %qT", r, type);
9081
9082         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9083                                         args, complain, in_decl);
9084       }
9085       break;
9086
9087     case USING_DECL:
9088       /* We reach here only for member using decls.  */
9089       if (DECL_DEPENDENT_P (t))
9090         {
9091           r = do_class_using_decl
9092             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9093              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9094           if (!r)
9095             r = error_mark_node;
9096           else
9097             {
9098               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9099               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9100             }
9101         }
9102       else
9103         {
9104           r = copy_node (t);
9105           TREE_CHAIN (r) = NULL_TREE;
9106         }
9107       break;
9108
9109     case TYPE_DECL:
9110     case VAR_DECL:
9111       {
9112         tree argvec = NULL_TREE;
9113         tree gen_tmpl = NULL_TREE;
9114         tree spec;
9115         tree tmpl = NULL_TREE;
9116         tree ctx;
9117         tree type = NULL_TREE;
9118         bool local_p;
9119
9120         if (TREE_CODE (t) == TYPE_DECL
9121             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9122           {
9123             /* If this is the canonical decl, we don't have to
9124                mess with instantiations, and often we can't (for
9125                typename, template type parms and such).  Note that
9126                TYPE_NAME is not correct for the above test if
9127                we've copied the type for a typedef.  */
9128             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9129             if (type == error_mark_node)
9130               RETURN (error_mark_node);
9131             r = TYPE_NAME (type);
9132             break;
9133           }
9134
9135         /* Check to see if we already have the specialization we
9136            need.  */
9137         spec = NULL_TREE;
9138         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9139           {
9140             /* T is a static data member or namespace-scope entity.
9141                We have to substitute into namespace-scope variables
9142                (even though such entities are never templates) because
9143                of cases like:
9144                
9145                  template <class T> void f() { extern T t; }
9146
9147                where the entity referenced is not known until
9148                instantiation time.  */
9149             local_p = false;
9150             ctx = DECL_CONTEXT (t);
9151             if (DECL_CLASS_SCOPE_P (t))
9152               {
9153                 ctx = tsubst_aggr_type (ctx, args,
9154                                         complain,
9155                                         in_decl, /*entering_scope=*/1);
9156                 /* If CTX is unchanged, then T is in fact the
9157                    specialization we want.  That situation occurs when
9158                    referencing a static data member within in its own
9159                    class.  We can use pointer equality, rather than
9160                    same_type_p, because DECL_CONTEXT is always
9161                    canonical.  */
9162                 if (ctx == DECL_CONTEXT (t))
9163                   spec = t;
9164               }
9165
9166             if (!spec)
9167               {
9168                 tmpl = DECL_TI_TEMPLATE (t);
9169                 gen_tmpl = most_general_template (tmpl);
9170                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9171                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9172                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9173               }
9174           }
9175         else
9176           {
9177             /* A local variable.  */
9178             local_p = true;
9179             /* Subsequent calls to pushdecl will fill this in.  */
9180             ctx = NULL_TREE;
9181             spec = retrieve_local_specialization (t);
9182           }
9183         /* If we already have the specialization we need, there is
9184            nothing more to do.  */ 
9185         if (spec)
9186           {
9187             r = spec;
9188             break;
9189           }
9190
9191         /* Create a new node for the specialization we need.  */
9192         r = copy_decl (t);
9193         if (type == NULL_TREE)
9194           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9195         if (TREE_CODE (r) == VAR_DECL)
9196           {
9197             /* Even if the original location is out of scope, the
9198                newly substituted one is not.  */
9199             DECL_DEAD_FOR_LOCAL (r) = 0;
9200             DECL_INITIALIZED_P (r) = 0;
9201             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9202             if (type == error_mark_node)
9203               RETURN (error_mark_node);
9204             if (TREE_CODE (type) == FUNCTION_TYPE)
9205               {
9206                 /* It may seem that this case cannot occur, since:
9207
9208                      typedef void f();
9209                      void g() { f x; }
9210
9211                    declares a function, not a variable.  However:
9212       
9213                      typedef void f();
9214                      template <typename T> void g() { T t; }
9215                      template void g<f>();
9216
9217                    is an attempt to declare a variable with function
9218                    type.  */
9219                 error ("variable %qD has function type",
9220                        /* R is not yet sufficiently initialized, so we
9221                           just use its name.  */
9222                        DECL_NAME (r));
9223                 RETURN (error_mark_node);
9224               }
9225             type = complete_type (type);
9226             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9227               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9228             type = check_var_type (DECL_NAME (r), type);
9229
9230             if (DECL_HAS_VALUE_EXPR_P (t))
9231               {
9232                 tree ve = DECL_VALUE_EXPR (t);
9233                 ve = tsubst_expr (ve, args, complain, in_decl,
9234                                   /*constant_expression_p=*/false);
9235                 SET_DECL_VALUE_EXPR (r, ve);
9236               }
9237           }
9238         else if (DECL_SELF_REFERENCE_P (t))
9239           SET_DECL_SELF_REFERENCE_P (r);
9240         TREE_TYPE (r) = type;
9241         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9242         DECL_CONTEXT (r) = ctx;
9243         /* Clear out the mangled name and RTL for the instantiation.  */
9244         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9245         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9246           SET_DECL_RTL (r, NULL_RTX);
9247         /* The initializer must not be expanded until it is required;
9248            see [temp.inst].  */
9249         DECL_INITIAL (r) = NULL_TREE;
9250         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9251           SET_DECL_RTL (r, NULL_RTX);
9252         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9253         if (TREE_CODE (r) == VAR_DECL)
9254           {
9255             /* Possibly limit visibility based on template args.  */
9256             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9257             if (DECL_VISIBILITY_SPECIFIED (t))
9258               {
9259                 DECL_VISIBILITY_SPECIFIED (r) = 0;
9260                 DECL_ATTRIBUTES (r)
9261                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9262               }
9263             determine_visibility (r);
9264           }
9265         /* Preserve a typedef that names a type.  */
9266         else if (TREE_CODE (r) == TYPE_DECL
9267                  && DECL_ORIGINAL_TYPE (t)
9268                  && type != error_mark_node)
9269           {
9270             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
9271                                              args, complain, in_decl);
9272             TREE_TYPE (r) = type = build_variant_type_copy (type);
9273             TYPE_NAME (type) = r;
9274           }
9275
9276         if (!local_p)
9277           {
9278             /* A static data member declaration is always marked
9279                external when it is declared in-class, even if an
9280                initializer is present.  We mimic the non-template
9281                processing here.  */
9282             DECL_EXTERNAL (r) = 1;
9283
9284             register_specialization (r, gen_tmpl, argvec, false, hash);
9285             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
9286             SET_DECL_IMPLICIT_INSTANTIATION (r);
9287           }
9288         else if (cp_unevaluated_operand)
9289           {
9290             /* We're substituting this var in a decltype outside of its
9291                scope, such as for a lambda return type.  Don't add it to
9292                local_specializations, do perform auto deduction.  */
9293             tree auto_node = type_uses_auto (type);
9294             tree init
9295               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9296                              /*constant_expression_p=*/false);
9297
9298             if (auto_node && init && describable_type (init))
9299               {
9300                 type = do_auto_deduction (type, init, auto_node);
9301                 TREE_TYPE (r) = type;
9302               }
9303           }
9304         else
9305           register_local_specialization (r, t);
9306
9307         TREE_CHAIN (r) = NULL_TREE;
9308
9309         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9310                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
9311                                         args, complain, in_decl);
9312         layout_decl (r, 0);
9313       }
9314       break;
9315
9316     default:
9317       gcc_unreachable ();
9318     }
9319 #undef RETURN
9320
9321  out:
9322   /* Restore the file and line information.  */
9323   input_location = saved_loc;
9324
9325   return r;
9326 }
9327
9328 /* Substitute into the ARG_TYPES of a function type.  */
9329
9330 static tree
9331 tsubst_arg_types (tree arg_types,
9332                   tree args,
9333                   tsubst_flags_t complain,
9334                   tree in_decl)
9335 {
9336   tree remaining_arg_types;
9337   tree type = NULL_TREE;
9338   int i = 1;
9339   tree expanded_args = NULL_TREE;
9340   tree default_arg;
9341
9342   if (!arg_types || arg_types == void_list_node)
9343     return arg_types;
9344
9345   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9346                                           args, complain, in_decl);
9347   if (remaining_arg_types == error_mark_node)
9348     return error_mark_node;
9349
9350   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9351     {
9352       /* For a pack expansion, perform substitution on the
9353          entire expression. Later on, we'll handle the arguments
9354          one-by-one.  */
9355       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9356                                             args, complain, in_decl);
9357
9358       if (TREE_CODE (expanded_args) == TREE_VEC)
9359         /* So that we'll spin through the parameters, one by one.  */
9360         i = TREE_VEC_LENGTH (expanded_args);
9361       else
9362         {
9363           /* We only partially substituted into the parameter
9364              pack. Our type is TYPE_PACK_EXPANSION.  */
9365           type = expanded_args;
9366           expanded_args = NULL_TREE;
9367         }
9368     }
9369
9370   while (i > 0) {
9371     --i;
9372     
9373     if (expanded_args)
9374       type = TREE_VEC_ELT (expanded_args, i);
9375     else if (!type)
9376       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9377
9378     if (type == error_mark_node)
9379       return error_mark_node;
9380     if (VOID_TYPE_P (type))
9381       {
9382         if (complain & tf_error)
9383           {
9384             error ("invalid parameter type %qT", type);
9385             if (in_decl)
9386               error ("in declaration %q+D", in_decl);
9387           }
9388         return error_mark_node;
9389     }
9390     
9391     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9392        top-level qualifiers as required.  */
9393     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9394
9395     /* We do not substitute into default arguments here.  The standard
9396        mandates that they be instantiated only when needed, which is
9397        done in build_over_call.  */
9398     default_arg = TREE_PURPOSE (arg_types);
9399
9400     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9401       {
9402         /* We've instantiated a template before its default arguments
9403            have been parsed.  This can happen for a nested template
9404            class, and is not an error unless we require the default
9405            argument in a call of this function.  */
9406         remaining_arg_types = 
9407           tree_cons (default_arg, type, remaining_arg_types);
9408         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9409                        remaining_arg_types);
9410       }
9411     else
9412       remaining_arg_types = 
9413         hash_tree_cons (default_arg, type, remaining_arg_types);
9414   }
9415         
9416   return remaining_arg_types;
9417 }
9418
9419 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9420    *not* handle the exception-specification for FNTYPE, because the
9421    initial substitution of explicitly provided template parameters
9422    during argument deduction forbids substitution into the
9423    exception-specification:
9424
9425      [temp.deduct]
9426
9427      All references in the function type of the function template to  the
9428      corresponding template parameters are replaced by the specified tem-
9429      plate argument values.  If a substitution in a template parameter or
9430      in  the function type of the function template results in an invalid
9431      type, type deduction fails.  [Note: The equivalent  substitution  in
9432      exception specifications is done only when the function is instanti-
9433      ated, at which point a program is  ill-formed  if  the  substitution
9434      results in an invalid type.]  */
9435
9436 static tree
9437 tsubst_function_type (tree t,
9438                       tree args,
9439                       tsubst_flags_t complain,
9440                       tree in_decl)
9441 {
9442   tree return_type;
9443   tree arg_types;
9444   tree fntype;
9445
9446   /* The TYPE_CONTEXT is not used for function/method types.  */
9447   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9448
9449   /* Substitute the return type.  */
9450   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9451   if (return_type == error_mark_node)
9452     return error_mark_node;
9453   /* The standard does not presently indicate that creation of a
9454      function type with an invalid return type is a deduction failure.
9455      However, that is clearly analogous to creating an array of "void"
9456      or a reference to a reference.  This is core issue #486.  */
9457   if (TREE_CODE (return_type) == ARRAY_TYPE
9458       || TREE_CODE (return_type) == FUNCTION_TYPE)
9459     {
9460       if (complain & tf_error)
9461         {
9462           if (TREE_CODE (return_type) == ARRAY_TYPE)
9463             error ("function returning an array");
9464           else
9465             error ("function returning a function");
9466         }
9467       return error_mark_node;
9468     }
9469
9470   /* Substitute the argument types.  */
9471   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9472                                 complain, in_decl);
9473   if (arg_types == error_mark_node)
9474     return error_mark_node;
9475
9476   /* Construct a new type node and return it.  */
9477   if (TREE_CODE (t) == FUNCTION_TYPE)
9478     fntype = build_function_type (return_type, arg_types);
9479   else
9480     {
9481       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9482       if (! MAYBE_CLASS_TYPE_P (r))
9483         {
9484           /* [temp.deduct]
9485
9486              Type deduction may fail for any of the following
9487              reasons:
9488
9489              -- Attempting to create "pointer to member of T" when T
9490              is not a class type.  */
9491           if (complain & tf_error)
9492             error ("creating pointer to member function of non-class type %qT",
9493                       r);
9494           return error_mark_node;
9495         }
9496
9497       fntype = build_method_type_directly (r, return_type,
9498                                            TREE_CHAIN (arg_types));
9499     }
9500   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9501   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9502
9503   return fntype;
9504 }
9505
9506 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9507    ARGS into that specification, and return the substituted
9508    specification.  If there is no specification, return NULL_TREE.  */
9509
9510 static tree
9511 tsubst_exception_specification (tree fntype,
9512                                 tree args,
9513                                 tsubst_flags_t complain,
9514                                 tree in_decl)
9515 {
9516   tree specs;
9517   tree new_specs;
9518
9519   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9520   new_specs = NULL_TREE;
9521   if (specs)
9522     {
9523       if (! TREE_VALUE (specs))
9524         new_specs = specs;
9525       else
9526         while (specs)
9527           {
9528             tree spec;
9529             int i, len = 1;
9530             tree expanded_specs = NULL_TREE;
9531
9532             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9533               {
9534                 /* Expand the pack expansion type.  */
9535                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9536                                                        args, complain,
9537                                                        in_decl);
9538
9539                 if (expanded_specs == error_mark_node)
9540                   return error_mark_node;
9541                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9542                   len = TREE_VEC_LENGTH (expanded_specs);
9543                 else
9544                   {
9545                     /* We're substituting into a member template, so
9546                        we got a TYPE_PACK_EXPANSION back.  Add that
9547                        expansion and move on.  */
9548                     gcc_assert (TREE_CODE (expanded_specs) 
9549                                 == TYPE_PACK_EXPANSION);
9550                     new_specs = add_exception_specifier (new_specs,
9551                                                          expanded_specs,
9552                                                          complain);
9553                     specs = TREE_CHAIN (specs);
9554                     continue;
9555                   }
9556               }
9557
9558             for (i = 0; i < len; ++i)
9559               {
9560                 if (expanded_specs)
9561                   spec = TREE_VEC_ELT (expanded_specs, i);
9562                 else
9563                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9564                 if (spec == error_mark_node)
9565                   return spec;
9566                 new_specs = add_exception_specifier (new_specs, spec, 
9567                                                      complain);
9568               }
9569
9570             specs = TREE_CHAIN (specs);
9571           }
9572     }
9573   return new_specs;
9574 }
9575
9576 /* Take the tree structure T and replace template parameters used
9577    therein with the argument vector ARGS.  IN_DECL is an associated
9578    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9579    Issue error and warning messages under control of COMPLAIN.  Note
9580    that we must be relatively non-tolerant of extensions here, in
9581    order to preserve conformance; if we allow substitutions that
9582    should not be allowed, we may allow argument deductions that should
9583    not succeed, and therefore report ambiguous overload situations
9584    where there are none.  In theory, we could allow the substitution,
9585    but indicate that it should have failed, and allow our caller to
9586    make sure that the right thing happens, but we don't try to do this
9587    yet.
9588
9589    This function is used for dealing with types, decls and the like;
9590    for expressions, use tsubst_expr or tsubst_copy.  */
9591
9592 tree
9593 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9594 {
9595   tree type, r;
9596
9597   if (t == NULL_TREE || t == error_mark_node
9598       || t == integer_type_node
9599       || t == void_type_node
9600       || t == char_type_node
9601       || t == unknown_type_node
9602       || TREE_CODE (t) == NAMESPACE_DECL)
9603     return t;
9604
9605   if (DECL_P (t))
9606     return tsubst_decl (t, args, complain);
9607
9608   if (args == NULL_TREE)
9609     return t;
9610
9611   if (TREE_CODE (t) == IDENTIFIER_NODE)
9612     type = IDENTIFIER_TYPE_VALUE (t);
9613   else
9614     type = TREE_TYPE (t);
9615
9616   gcc_assert (type != unknown_type_node);
9617
9618   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9619      such as attribute aligned.  */
9620   if (TYPE_P (t)
9621       && TYPE_NAME (t)
9622       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9623     {
9624       tree decl = TYPE_NAME (t);
9625       
9626       if (DECL_CLASS_SCOPE_P (decl)
9627           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9628           && uses_template_parms (DECL_CONTEXT (decl)))
9629         {
9630           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9631           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9632           r = retrieve_specialization (tmpl, gen_args, 0);
9633         }
9634       else if (DECL_FUNCTION_SCOPE_P (decl)
9635                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9636                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9637         r = retrieve_local_specialization (decl);
9638       else
9639         /* The typedef is from a non-template context.  */
9640         return t;
9641
9642       if (r)
9643         {
9644           r = TREE_TYPE (r);
9645           r = cp_build_qualified_type_real
9646             (r, cp_type_quals (t) | cp_type_quals (r),
9647              complain | tf_ignore_bad_quals);
9648           return r;
9649         }
9650       /* Else we must be instantiating the typedef, so fall through.  */
9651     }
9652
9653   if (type
9654       && TREE_CODE (t) != TYPENAME_TYPE
9655       && TREE_CODE (t) != IDENTIFIER_NODE
9656       && TREE_CODE (t) != FUNCTION_TYPE
9657       && TREE_CODE (t) != METHOD_TYPE)
9658     type = tsubst (type, args, complain, in_decl);
9659   if (type == error_mark_node)
9660     return error_mark_node;
9661
9662   switch (TREE_CODE (t))
9663     {
9664     case RECORD_TYPE:
9665     case UNION_TYPE:
9666     case ENUMERAL_TYPE:
9667       return tsubst_aggr_type (t, args, complain, in_decl,
9668                                /*entering_scope=*/0);
9669
9670     case ERROR_MARK:
9671     case IDENTIFIER_NODE:
9672     case VOID_TYPE:
9673     case REAL_TYPE:
9674     case COMPLEX_TYPE:
9675     case VECTOR_TYPE:
9676     case BOOLEAN_TYPE:
9677     case INTEGER_CST:
9678     case REAL_CST:
9679     case STRING_CST:
9680       return t;
9681
9682     case INTEGER_TYPE:
9683       if (t == integer_type_node)
9684         return t;
9685
9686       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9687           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9688         return t;
9689
9690       {
9691         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9692
9693         max = tsubst_expr (omax, args, complain, in_decl,
9694                            /*integral_constant_expression_p=*/false);
9695
9696         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9697            needed.  */
9698         if (TREE_CODE (max) == NOP_EXPR
9699             && TREE_SIDE_EFFECTS (omax)
9700             && !TREE_TYPE (max))
9701           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9702
9703         max = fold_decl_constant_value (max);
9704
9705         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9706            with TREE_SIDE_EFFECTS that indicates this is not an integral
9707            constant expression.  */
9708         if (processing_template_decl
9709             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9710           {
9711             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9712             TREE_SIDE_EFFECTS (max) = 1;
9713           }
9714
9715         if (TREE_CODE (max) != INTEGER_CST
9716             && !at_function_scope_p ()
9717             && !TREE_SIDE_EFFECTS (max)
9718             && !value_dependent_expression_p (max))
9719           {
9720             if (complain & tf_error)
9721               error ("array bound is not an integer constant");
9722             return error_mark_node;
9723           }
9724
9725         /* [temp.deduct]
9726
9727            Type deduction may fail for any of the following
9728            reasons:
9729
9730              Attempting to create an array with a size that is
9731              zero or negative.  */
9732         if (integer_zerop (max) && !(complain & tf_error))
9733           /* We must fail if performing argument deduction (as
9734              indicated by the state of complain), so that
9735              another substitution can be found.  */
9736           return error_mark_node;
9737         else if (TREE_CODE (max) == INTEGER_CST
9738                  && INT_CST_LT (max, integer_zero_node))
9739           {
9740             if (complain & tf_error)
9741               error ("creating array with negative size (%qE)", max);
9742
9743             return error_mark_node;
9744           }
9745
9746         return compute_array_index_type (NULL_TREE, max);
9747       }
9748
9749     case TEMPLATE_TYPE_PARM:
9750     case TEMPLATE_TEMPLATE_PARM:
9751     case BOUND_TEMPLATE_TEMPLATE_PARM:
9752     case TEMPLATE_PARM_INDEX:
9753       {
9754         int idx;
9755         int level;
9756         int levels;
9757         tree arg = NULL_TREE;
9758
9759         r = NULL_TREE;
9760
9761         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9762         template_parm_level_and_index (t, &level, &idx); 
9763
9764         levels = TMPL_ARGS_DEPTH (args);
9765         if (level <= levels)
9766           {
9767             arg = TMPL_ARG (args, level, idx);
9768
9769             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9770               /* See through ARGUMENT_PACK_SELECT arguments. */
9771               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9772           }
9773
9774         if (arg == error_mark_node)
9775           return error_mark_node;
9776         else if (arg != NULL_TREE)
9777           {
9778             if (ARGUMENT_PACK_P (arg))
9779               /* If ARG is an argument pack, we don't actually want to
9780                  perform a substitution here, because substitutions
9781                  for argument packs are only done
9782                  element-by-element. We can get to this point when
9783                  substituting the type of a non-type template
9784                  parameter pack, when that type actually contains
9785                  template parameter packs from an outer template, e.g.,
9786
9787                  template<typename... Types> struct A {
9788                    template<Types... Values> struct B { };
9789                  };  */
9790               return t;
9791
9792             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9793               {
9794                 int quals;
9795                 gcc_assert (TYPE_P (arg));
9796
9797                 /* cv-quals from the template are discarded when
9798                    substituting in a function or reference type.  */
9799                 if (TREE_CODE (arg) == FUNCTION_TYPE
9800                     || TREE_CODE (arg) == METHOD_TYPE
9801                     || TREE_CODE (arg) == REFERENCE_TYPE)
9802                   quals = cp_type_quals (arg);
9803                 else
9804                   quals = cp_type_quals (arg) | cp_type_quals (t);
9805                   
9806                 return cp_build_qualified_type_real
9807                   (arg, quals, complain | tf_ignore_bad_quals);
9808               }
9809             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9810               {
9811                 /* We are processing a type constructed from a
9812                    template template parameter.  */
9813                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9814                                       args, complain, in_decl);
9815                 if (argvec == error_mark_node)
9816                   return error_mark_node;
9817
9818                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9819                    are resolving nested-types in the signature of a
9820                    member function templates.  Otherwise ARG is a
9821                    TEMPLATE_DECL and is the real template to be
9822                    instantiated.  */
9823                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9824                   arg = TYPE_NAME (arg);
9825
9826                 r = lookup_template_class (arg,
9827                                            argvec, in_decl,
9828                                            DECL_CONTEXT (arg),
9829                                             /*entering_scope=*/0,
9830                                            complain);
9831                 return cp_build_qualified_type_real
9832                   (r, TYPE_QUALS (t), complain);
9833               }
9834             else
9835               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9836               return arg;
9837           }
9838
9839         if (level == 1)
9840           /* This can happen during the attempted tsubst'ing in
9841              unify.  This means that we don't yet have any information
9842              about the template parameter in question.  */
9843           return t;
9844
9845         /* If we get here, we must have been looking at a parm for a
9846            more deeply nested template.  Make a new version of this
9847            template parameter, but with a lower level.  */
9848         switch (TREE_CODE (t))
9849           {
9850           case TEMPLATE_TYPE_PARM:
9851           case TEMPLATE_TEMPLATE_PARM:
9852           case BOUND_TEMPLATE_TEMPLATE_PARM:
9853             if (cp_type_quals (t))
9854               {
9855                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9856                 r = cp_build_qualified_type_real
9857                   (r, cp_type_quals (t),
9858                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9859                                ? tf_ignore_bad_quals : 0));
9860               }
9861             else
9862               {
9863                 r = copy_type (t);
9864                 TEMPLATE_TYPE_PARM_INDEX (r)
9865                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9866                                                 r, levels, args, complain);
9867                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9868                 TYPE_MAIN_VARIANT (r) = r;
9869                 TYPE_POINTER_TO (r) = NULL_TREE;
9870                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9871
9872                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9873                   /* We have reduced the level of the template
9874                      template parameter, but not the levels of its
9875                      template parameters, so canonical_type_parameter
9876                      will not be able to find the canonical template
9877                      template parameter for this level. Thus, we
9878                      require structural equality checking to compare
9879                      TEMPLATE_TEMPLATE_PARMs. */
9880                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9881                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9882                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9883                 else
9884                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9885
9886                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9887                   {
9888                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9889                                           complain, in_decl);
9890                     if (argvec == error_mark_node)
9891                       return error_mark_node;
9892
9893                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9894                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9895                   }
9896               }
9897             break;
9898
9899           case TEMPLATE_PARM_INDEX:
9900             r = reduce_template_parm_level (t, type, levels, args, complain);
9901             break;
9902
9903           default:
9904             gcc_unreachable ();
9905           }
9906
9907         return r;
9908       }
9909
9910     case TREE_LIST:
9911       {
9912         tree purpose, value, chain;
9913
9914         if (t == void_list_node)
9915           return t;
9916
9917         purpose = TREE_PURPOSE (t);
9918         if (purpose)
9919           {
9920             purpose = tsubst (purpose, args, complain, in_decl);
9921             if (purpose == error_mark_node)
9922               return error_mark_node;
9923           }
9924         value = TREE_VALUE (t);
9925         if (value)
9926           {
9927             value = tsubst (value, args, complain, in_decl);
9928             if (value == error_mark_node)
9929               return error_mark_node;
9930           }
9931         chain = TREE_CHAIN (t);
9932         if (chain && chain != void_type_node)
9933           {
9934             chain = tsubst (chain, args, complain, in_decl);
9935             if (chain == error_mark_node)
9936               return error_mark_node;
9937           }
9938         if (purpose == TREE_PURPOSE (t)
9939             && value == TREE_VALUE (t)
9940             && chain == TREE_CHAIN (t))
9941           return t;
9942         return hash_tree_cons (purpose, value, chain);
9943       }
9944
9945     case TREE_BINFO:
9946       /* We should never be tsubsting a binfo.  */
9947       gcc_unreachable ();
9948
9949     case TREE_VEC:
9950       /* A vector of template arguments.  */
9951       gcc_assert (!type);
9952       return tsubst_template_args (t, args, complain, in_decl);
9953
9954     case POINTER_TYPE:
9955     case REFERENCE_TYPE:
9956       {
9957         enum tree_code code;
9958
9959         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9960           return t;
9961
9962         code = TREE_CODE (t);
9963
9964
9965         /* [temp.deduct]
9966
9967            Type deduction may fail for any of the following
9968            reasons:
9969
9970            -- Attempting to create a pointer to reference type.
9971            -- Attempting to create a reference to a reference type or
9972               a reference to void.
9973
9974           Core issue 106 says that creating a reference to a reference
9975           during instantiation is no longer a cause for failure. We
9976           only enforce this check in strict C++98 mode.  */
9977         if ((TREE_CODE (type) == REFERENCE_TYPE
9978              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9979             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9980           {
9981             static location_t last_loc;
9982
9983             /* We keep track of the last time we issued this error
9984                message to avoid spewing a ton of messages during a
9985                single bad template instantiation.  */
9986             if (complain & tf_error
9987                 && last_loc != input_location)
9988               {
9989                 if (TREE_CODE (type) == VOID_TYPE)
9990                   error ("forming reference to void");
9991                 else
9992                   error ("forming %s to reference type %qT",
9993                          (code == POINTER_TYPE) ? "pointer" : "reference",
9994                          type);
9995                 last_loc = input_location;
9996               }
9997
9998             return error_mark_node;
9999           }
10000         else if (code == POINTER_TYPE)
10001           {
10002             r = build_pointer_type (type);
10003             if (TREE_CODE (type) == METHOD_TYPE)
10004               r = build_ptrmemfunc_type (r);
10005           }
10006         else if (TREE_CODE (type) == REFERENCE_TYPE)
10007           /* In C++0x, during template argument substitution, when there is an
10008              attempt to create a reference to a reference type, reference
10009              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10010
10011              "If a template-argument for a template-parameter T names a type
10012              that is a reference to a type A, an attempt to create the type
10013              'lvalue reference to cv T' creates the type 'lvalue reference to
10014              A,' while an attempt to create the type type rvalue reference to
10015              cv T' creates the type T"
10016           */
10017           r = cp_build_reference_type
10018               (TREE_TYPE (type),
10019                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10020         else
10021           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10022         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
10023
10024         if (r != error_mark_node)
10025           /* Will this ever be needed for TYPE_..._TO values?  */
10026           layout_type (r);
10027
10028         return r;
10029       }
10030     case OFFSET_TYPE:
10031       {
10032         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10033         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10034           {
10035             /* [temp.deduct]
10036
10037                Type deduction may fail for any of the following
10038                reasons:
10039
10040                -- Attempting to create "pointer to member of T" when T
10041                   is not a class type.  */
10042             if (complain & tf_error)
10043               error ("creating pointer to member of non-class type %qT", r);
10044             return error_mark_node;
10045           }
10046         if (TREE_CODE (type) == REFERENCE_TYPE)
10047           {
10048             if (complain & tf_error)
10049               error ("creating pointer to member reference type %qT", type);
10050             return error_mark_node;
10051           }
10052         if (TREE_CODE (type) == VOID_TYPE)
10053           {
10054             if (complain & tf_error)
10055               error ("creating pointer to member of type void");
10056             return error_mark_node;
10057           }
10058         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10059         if (TREE_CODE (type) == FUNCTION_TYPE)
10060           {
10061             /* The type of the implicit object parameter gets its
10062                cv-qualifiers from the FUNCTION_TYPE. */
10063             tree memptr;
10064             tree method_type = build_memfn_type (type, r, cp_type_quals (type));
10065             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10066             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10067                                                  complain);
10068           }
10069         else
10070           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10071                                                TYPE_QUALS (t),
10072                                                complain);
10073       }
10074     case FUNCTION_TYPE:
10075     case METHOD_TYPE:
10076       {
10077         tree fntype;
10078         tree specs;
10079         fntype = tsubst_function_type (t, args, complain, in_decl);
10080         if (fntype == error_mark_node)
10081           return error_mark_node;
10082
10083         /* Substitute the exception specification.  */
10084         specs = tsubst_exception_specification (t, args, complain,
10085                                                 in_decl);
10086         if (specs == error_mark_node)
10087           return error_mark_node;
10088         if (specs)
10089           fntype = build_exception_variant (fntype, specs);
10090         return fntype;
10091       }
10092     case ARRAY_TYPE:
10093       {
10094         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10095         if (domain == error_mark_node)
10096           return error_mark_node;
10097
10098         /* As an optimization, we avoid regenerating the array type if
10099            it will obviously be the same as T.  */
10100         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10101           return t;
10102
10103         /* These checks should match the ones in grokdeclarator.
10104
10105            [temp.deduct]
10106
10107            The deduction may fail for any of the following reasons:
10108
10109            -- Attempting to create an array with an element type that
10110               is void, a function type, or a reference type, or [DR337]
10111               an abstract class type.  */
10112         if (TREE_CODE (type) == VOID_TYPE
10113             || TREE_CODE (type) == FUNCTION_TYPE
10114             || TREE_CODE (type) == REFERENCE_TYPE)
10115           {
10116             if (complain & tf_error)
10117               error ("creating array of %qT", type);
10118             return error_mark_node;
10119           }
10120         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10121           {
10122             if (complain & tf_error)
10123               error ("creating array of %qT, which is an abstract class type",
10124                      type);
10125             return error_mark_node;
10126           }
10127
10128         r = build_cplus_array_type (type, domain);
10129
10130         if (TYPE_USER_ALIGN (t))
10131           {
10132             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10133             TYPE_USER_ALIGN (r) = 1;
10134           }
10135
10136         return r;
10137       }
10138
10139     case PLUS_EXPR:
10140     case MINUS_EXPR:
10141       {
10142         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10143         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10144
10145         if (e1 == error_mark_node || e2 == error_mark_node)
10146           return error_mark_node;
10147
10148         return fold_build2_loc (input_location,
10149                             TREE_CODE (t), TREE_TYPE (t), e1, e2);
10150       }
10151
10152     case NEGATE_EXPR:
10153     case NOP_EXPR:
10154       {
10155         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10156         if (e == error_mark_node)
10157           return error_mark_node;
10158
10159         return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
10160       }
10161
10162     case TYPENAME_TYPE:
10163       {
10164         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10165                                      in_decl, /*entering_scope=*/1);
10166         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10167                               complain, in_decl);
10168
10169         if (ctx == error_mark_node || f == error_mark_node)
10170           return error_mark_node;
10171
10172         if (!MAYBE_CLASS_TYPE_P (ctx))
10173           {
10174             if (complain & tf_error)
10175               error ("%qT is not a class, struct, or union type", ctx);
10176             return error_mark_node;
10177           }
10178         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10179           {
10180             /* Normally, make_typename_type does not require that the CTX
10181                have complete type in order to allow things like:
10182
10183                  template <class T> struct S { typename S<T>::X Y; };
10184
10185                But, such constructs have already been resolved by this
10186                point, so here CTX really should have complete type, unless
10187                it's a partial instantiation.  */
10188             if (!(complain & tf_no_class_instantiations))
10189               ctx = complete_type (ctx);
10190             if (!COMPLETE_TYPE_P (ctx))
10191               {
10192                 if (complain & tf_error)
10193                   cxx_incomplete_type_error (NULL_TREE, ctx);
10194                 return error_mark_node;
10195               }
10196           }
10197
10198         f = make_typename_type (ctx, f, typename_type,
10199                                 (complain & tf_error) | tf_keep_type_decl);
10200         if (f == error_mark_node)
10201           return f;
10202         if (TREE_CODE (f) == TYPE_DECL)
10203           {
10204             complain |= tf_ignore_bad_quals;
10205             f = TREE_TYPE (f);
10206           }
10207
10208         if (TREE_CODE (f) != TYPENAME_TYPE)
10209           {
10210             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10211               error ("%qT resolves to %qT, which is not an enumeration type",
10212                      t, f);
10213             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10214               error ("%qT resolves to %qT, which is is not a class type",
10215                      t, f);
10216           }
10217
10218         return cp_build_qualified_type_real
10219           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10220       }
10221
10222     case UNBOUND_CLASS_TEMPLATE:
10223       {
10224         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10225                                      in_decl, /*entering_scope=*/1);
10226         tree name = TYPE_IDENTIFIER (t);
10227         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10228
10229         if (ctx == error_mark_node || name == error_mark_node)
10230           return error_mark_node;
10231
10232         if (parm_list)
10233           parm_list = tsubst_template_parms (parm_list, args, complain);
10234         return make_unbound_class_template (ctx, name, parm_list, complain);
10235       }
10236
10237     case INDIRECT_REF:
10238     case ADDR_EXPR:
10239     case CALL_EXPR:
10240       gcc_unreachable ();
10241
10242     case ARRAY_REF:
10243       {
10244         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10245         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10246                                /*integral_constant_expression_p=*/false);
10247         if (e1 == error_mark_node || e2 == error_mark_node)
10248           return error_mark_node;
10249
10250         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10251       }
10252
10253     case SCOPE_REF:
10254       {
10255         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10256         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10257         if (e1 == error_mark_node || e2 == error_mark_node)
10258           return error_mark_node;
10259
10260         return build_qualified_name (/*type=*/NULL_TREE,
10261                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10262       }
10263
10264     case TYPEOF_TYPE:
10265       {
10266         tree type;
10267
10268         ++cp_unevaluated_operand;
10269         ++c_inhibit_evaluation_warnings;
10270
10271         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10272                             complain, in_decl,
10273                             /*integral_constant_expression_p=*/false);
10274
10275         --cp_unevaluated_operand;
10276         --c_inhibit_evaluation_warnings;
10277
10278         type = finish_typeof (type);
10279         return cp_build_qualified_type_real (type,
10280                                              cp_type_quals (t)
10281                                              | cp_type_quals (type),
10282                                              complain);
10283       }
10284
10285     case DECLTYPE_TYPE:
10286       {
10287         tree type;
10288
10289         ++cp_unevaluated_operand;
10290         ++c_inhibit_evaluation_warnings;
10291
10292         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10293                             complain, in_decl,
10294                             /*integral_constant_expression_p=*/false);
10295
10296         --cp_unevaluated_operand;
10297         --c_inhibit_evaluation_warnings;
10298
10299         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10300           type = lambda_capture_field_type (type);
10301         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10302           type = lambda_return_type (type);
10303         else
10304           type = finish_decltype_type
10305             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10306         return cp_build_qualified_type_real (type,
10307                                              cp_type_quals (t)
10308                                              | cp_type_quals (type),
10309                                              complain);
10310       }
10311
10312     case TYPE_ARGUMENT_PACK:
10313     case NONTYPE_ARGUMENT_PACK:
10314       {
10315         tree r = TYPE_P (t)
10316           ? cxx_make_type (TREE_CODE (t))
10317           : make_node (TREE_CODE (t));
10318         tree packed_out = 
10319           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10320                                 args,
10321                                 complain,
10322                                 in_decl);
10323         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10324
10325         /* For template nontype argument packs, also substitute into
10326            the type.  */
10327         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10328           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10329
10330         return r;
10331       }
10332       break;
10333
10334     default:
10335       sorry ("use of %qs in template",
10336              tree_code_name [(int) TREE_CODE (t)]);
10337       return error_mark_node;
10338     }
10339 }
10340
10341 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10342    type of the expression on the left-hand side of the "." or "->"
10343    operator.  */
10344
10345 static tree
10346 tsubst_baselink (tree baselink, tree object_type,
10347                  tree args, tsubst_flags_t complain, tree in_decl)
10348 {
10349     tree name;
10350     tree qualifying_scope;
10351     tree fns;
10352     tree optype;
10353     tree template_args = 0;
10354     bool template_id_p = false;
10355
10356     /* A baselink indicates a function from a base class.  Both the
10357        BASELINK_ACCESS_BINFO and the base class referenced may
10358        indicate bases of the template class, rather than the
10359        instantiated class.  In addition, lookups that were not
10360        ambiguous before may be ambiguous now.  Therefore, we perform
10361        the lookup again.  */
10362     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10363     qualifying_scope = tsubst (qualifying_scope, args,
10364                                complain, in_decl);
10365     fns = BASELINK_FUNCTIONS (baselink);
10366     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10367     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10368       {
10369         template_id_p = true;
10370         template_args = TREE_OPERAND (fns, 1);
10371         fns = TREE_OPERAND (fns, 0);
10372         if (template_args)
10373           template_args = tsubst_template_args (template_args, args,
10374                                                 complain, in_decl);
10375       }
10376     name = DECL_NAME (get_first_fn (fns));
10377     if (IDENTIFIER_TYPENAME_P (name))
10378       name = mangle_conv_op_name_for_type (optype);
10379     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10380
10381     /* If lookup found a single function, mark it as used at this
10382        point.  (If it lookup found multiple functions the one selected
10383        later by overload resolution will be marked as used at that
10384        point.)  */
10385     if (BASELINK_P (baselink))
10386       fns = BASELINK_FUNCTIONS (baselink);
10387     if (!template_id_p && !really_overloaded_fn (fns))
10388       mark_used (OVL_CURRENT (fns));
10389
10390     /* Add back the template arguments, if present.  */
10391     if (BASELINK_P (baselink) && template_id_p)
10392       BASELINK_FUNCTIONS (baselink)
10393         = build_nt (TEMPLATE_ID_EXPR,
10394                     BASELINK_FUNCTIONS (baselink),
10395                     template_args);
10396     /* Update the conversion operator type.  */
10397     BASELINK_OPTYPE (baselink) = optype;
10398
10399     if (!object_type)
10400       object_type = current_class_type;
10401     return adjust_result_of_qualified_name_lookup (baselink,
10402                                                    qualifying_scope,
10403                                                    object_type);
10404 }
10405
10406 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10407    true if the qualified-id will be a postfix-expression in-and-of
10408    itself; false if more of the postfix-expression follows the
10409    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10410    of "&".  */
10411
10412 static tree
10413 tsubst_qualified_id (tree qualified_id, tree args,
10414                      tsubst_flags_t complain, tree in_decl,
10415                      bool done, bool address_p)
10416 {
10417   tree expr;
10418   tree scope;
10419   tree name;
10420   bool is_template;
10421   tree template_args;
10422
10423   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10424
10425   /* Figure out what name to look up.  */
10426   name = TREE_OPERAND (qualified_id, 1);
10427   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10428     {
10429       is_template = true;
10430       template_args = TREE_OPERAND (name, 1);
10431       if (template_args)
10432         template_args = tsubst_template_args (template_args, args,
10433                                               complain, in_decl);
10434       name = TREE_OPERAND (name, 0);
10435     }
10436   else
10437     {
10438       is_template = false;
10439       template_args = NULL_TREE;
10440     }
10441
10442   /* Substitute into the qualifying scope.  When there are no ARGS, we
10443      are just trying to simplify a non-dependent expression.  In that
10444      case the qualifying scope may be dependent, and, in any case,
10445      substituting will not help.  */
10446   scope = TREE_OPERAND (qualified_id, 0);
10447   if (args)
10448     {
10449       scope = tsubst (scope, args, complain, in_decl);
10450       expr = tsubst_copy (name, args, complain, in_decl);
10451     }
10452   else
10453     expr = name;
10454
10455   if (dependent_type_p (scope))
10456     {
10457       tree type = NULL_TREE;
10458       if (DECL_P (expr) && !dependent_scope_p (scope))
10459         type = TREE_TYPE (expr);
10460       return build_qualified_name (type, scope, expr,
10461                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10462     }
10463
10464   if (!BASELINK_P (name) && !DECL_P (expr))
10465     {
10466       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10467         {
10468           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10469           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10470             {
10471               error ("qualifying type %qT does not match destructor name ~%qT",
10472                      scope, TREE_OPERAND (expr, 0));
10473               expr = error_mark_node;
10474             }
10475           else
10476             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10477                                           /*is_type_p=*/0, false);
10478         }
10479       else
10480         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10481       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10482                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10483         {
10484           if (complain & tf_error)
10485             {
10486               error ("dependent-name %qE is parsed as a non-type, but "
10487                      "instantiation yields a type", qualified_id);
10488               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10489             }
10490           return error_mark_node;
10491         }
10492     }
10493
10494   if (DECL_P (expr))
10495     {
10496       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10497                                            scope);
10498       /* Remember that there was a reference to this entity.  */
10499       mark_used (expr);
10500     }
10501
10502   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10503     {
10504       if (complain & tf_error)
10505         qualified_name_lookup_error (scope,
10506                                      TREE_OPERAND (qualified_id, 1),
10507                                      expr, input_location);
10508       return error_mark_node;
10509     }
10510
10511   if (is_template)
10512     expr = lookup_template_function (expr, template_args);
10513
10514   if (expr == error_mark_node && complain & tf_error)
10515     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10516                                  expr, input_location);
10517   else if (TYPE_P (scope))
10518     {
10519       expr = (adjust_result_of_qualified_name_lookup
10520               (expr, scope, current_class_type));
10521       expr = (finish_qualified_id_expr
10522               (scope, expr, done, address_p,
10523                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10524                /*template_arg_p=*/false));
10525     }
10526
10527   /* Expressions do not generally have reference type.  */
10528   if (TREE_CODE (expr) != SCOPE_REF
10529       /* However, if we're about to form a pointer-to-member, we just
10530          want the referenced member referenced.  */
10531       && TREE_CODE (expr) != OFFSET_REF)
10532     expr = convert_from_reference (expr);
10533
10534   return expr;
10535 }
10536
10537 /* Like tsubst, but deals with expressions.  This function just replaces
10538    template parms; to finish processing the resultant expression, use
10539    tsubst_expr.  */
10540
10541 static tree
10542 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10543 {
10544   enum tree_code code;
10545   tree r;
10546
10547   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10548     return t;
10549
10550   code = TREE_CODE (t);
10551
10552   switch (code)
10553     {
10554     case PARM_DECL:
10555       r = retrieve_local_specialization (t);
10556
10557       if (r == NULL)
10558         {
10559           tree c;
10560           /* This can happen for a parameter name used later in a function
10561              declaration (such as in a late-specified return type).  Just
10562              make a dummy decl, since it's only used for its type.  */
10563           gcc_assert (cp_unevaluated_operand != 0);
10564           /* We copy T because want to tsubst the PARM_DECL only,
10565              not the following PARM_DECLs that are chained to T.  */
10566           c = copy_node (t);
10567           r = tsubst_decl (c, args, complain);
10568           /* Give it the template pattern as its context; its true context
10569              hasn't been instantiated yet and this is good enough for
10570              mangling.  */
10571           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10572         }
10573       
10574       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10575         r = ARGUMENT_PACK_SELECT_ARG (r);
10576       mark_used (r);
10577       return r;
10578
10579     case CONST_DECL:
10580       {
10581         tree enum_type;
10582         tree v;
10583
10584         if (DECL_TEMPLATE_PARM_P (t))
10585           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10586         /* There is no need to substitute into namespace-scope
10587            enumerators.  */
10588         if (DECL_NAMESPACE_SCOPE_P (t))
10589           return t;
10590         /* If ARGS is NULL, then T is known to be non-dependent.  */
10591         if (args == NULL_TREE)
10592           return integral_constant_value (t);
10593
10594         /* Unfortunately, we cannot just call lookup_name here.
10595            Consider:
10596
10597              template <int I> int f() {
10598              enum E { a = I };
10599              struct S { void g() { E e = a; } };
10600              };
10601
10602            When we instantiate f<7>::S::g(), say, lookup_name is not
10603            clever enough to find f<7>::a.  */
10604         enum_type
10605           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10606                               /*entering_scope=*/0);
10607
10608         for (v = TYPE_VALUES (enum_type);
10609              v != NULL_TREE;
10610              v = TREE_CHAIN (v))
10611           if (TREE_PURPOSE (v) == DECL_NAME (t))
10612             return TREE_VALUE (v);
10613
10614           /* We didn't find the name.  That should never happen; if
10615              name-lookup found it during preliminary parsing, we
10616              should find it again here during instantiation.  */
10617         gcc_unreachable ();
10618       }
10619       return t;
10620
10621     case FIELD_DECL:
10622       if (DECL_CONTEXT (t))
10623         {
10624           tree ctx;
10625
10626           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10627                                   /*entering_scope=*/1);
10628           if (ctx != DECL_CONTEXT (t))
10629             {
10630               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10631               if (!r)
10632                 {
10633                   if (complain & tf_error)
10634                     error ("using invalid field %qD", t);
10635                   return error_mark_node;
10636                 }
10637               return r;
10638             }
10639         }
10640
10641       return t;
10642
10643     case VAR_DECL:
10644     case FUNCTION_DECL:
10645       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10646           || local_variable_p (t))
10647         t = tsubst (t, args, complain, in_decl);
10648       mark_used (t);
10649       return t;
10650
10651     case BASELINK:
10652       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10653
10654     case TEMPLATE_DECL:
10655       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10656         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10657                        args, complain, in_decl);
10658       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10659         return tsubst (t, args, complain, in_decl);
10660       else if (DECL_CLASS_SCOPE_P (t)
10661                && uses_template_parms (DECL_CONTEXT (t)))
10662         {
10663           /* Template template argument like the following example need
10664              special treatment:
10665
10666                template <template <class> class TT> struct C {};
10667                template <class T> struct D {
10668                  template <class U> struct E {};
10669                  C<E> c;                                // #1
10670                };
10671                D<int> d;                                // #2
10672
10673              We are processing the template argument `E' in #1 for
10674              the template instantiation #2.  Originally, `E' is a
10675              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10676              have to substitute this with one having context `D<int>'.  */
10677
10678           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10679           return lookup_field (context, DECL_NAME(t), 0, false);
10680         }
10681       else
10682         /* Ordinary template template argument.  */
10683         return t;
10684
10685     case CAST_EXPR:
10686     case REINTERPRET_CAST_EXPR:
10687     case CONST_CAST_EXPR:
10688     case STATIC_CAST_EXPR:
10689     case DYNAMIC_CAST_EXPR:
10690     case NOP_EXPR:
10691       return build1
10692         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10693          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10694
10695     case SIZEOF_EXPR:
10696       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10697         {
10698           /* We only want to compute the number of arguments.  */
10699           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10700                                                 complain, in_decl);
10701           int len = 0;
10702
10703           if (TREE_CODE (expanded) == TREE_VEC)
10704             len = TREE_VEC_LENGTH (expanded);
10705
10706           if (expanded == error_mark_node)
10707             return error_mark_node;
10708           else if (PACK_EXPANSION_P (expanded)
10709                    || (TREE_CODE (expanded) == TREE_VEC
10710                        && len > 0
10711                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10712             {
10713               if (TREE_CODE (expanded) == TREE_VEC)
10714                 expanded = TREE_VEC_ELT (expanded, len - 1);
10715
10716               if (TYPE_P (expanded))
10717                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10718                                                    complain & tf_error);
10719               else
10720                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10721                                                    complain & tf_error);
10722             }
10723           else
10724             return build_int_cst (size_type_node, len);
10725         }
10726       /* Fall through */
10727
10728     case INDIRECT_REF:
10729     case NEGATE_EXPR:
10730     case TRUTH_NOT_EXPR:
10731     case BIT_NOT_EXPR:
10732     case ADDR_EXPR:
10733     case UNARY_PLUS_EXPR:      /* Unary + */
10734     case ALIGNOF_EXPR:
10735     case ARROW_EXPR:
10736     case THROW_EXPR:
10737     case TYPEID_EXPR:
10738     case REALPART_EXPR:
10739     case IMAGPART_EXPR:
10740       return build1
10741         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10742          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10743
10744     case COMPONENT_REF:
10745       {
10746         tree object;
10747         tree name;
10748
10749         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10750         name = TREE_OPERAND (t, 1);
10751         if (TREE_CODE (name) == BIT_NOT_EXPR)
10752           {
10753             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10754                                 complain, in_decl);
10755             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10756           }
10757         else if (TREE_CODE (name) == SCOPE_REF
10758                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10759           {
10760             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10761                                      complain, in_decl);
10762             name = TREE_OPERAND (name, 1);
10763             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10764                                 complain, in_decl);
10765             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10766             name = build_qualified_name (/*type=*/NULL_TREE,
10767                                          base, name,
10768                                          /*template_p=*/false);
10769           }
10770         else if (TREE_CODE (name) == BASELINK)
10771           name = tsubst_baselink (name,
10772                                   non_reference (TREE_TYPE (object)),
10773                                   args, complain,
10774                                   in_decl);
10775         else
10776           name = tsubst_copy (name, args, complain, in_decl);
10777         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10778       }
10779
10780     case PLUS_EXPR:
10781     case MINUS_EXPR:
10782     case MULT_EXPR:
10783     case TRUNC_DIV_EXPR:
10784     case CEIL_DIV_EXPR:
10785     case FLOOR_DIV_EXPR:
10786     case ROUND_DIV_EXPR:
10787     case EXACT_DIV_EXPR:
10788     case BIT_AND_EXPR:
10789     case BIT_IOR_EXPR:
10790     case BIT_XOR_EXPR:
10791     case TRUNC_MOD_EXPR:
10792     case FLOOR_MOD_EXPR:
10793     case TRUTH_ANDIF_EXPR:
10794     case TRUTH_ORIF_EXPR:
10795     case TRUTH_AND_EXPR:
10796     case TRUTH_OR_EXPR:
10797     case RSHIFT_EXPR:
10798     case LSHIFT_EXPR:
10799     case RROTATE_EXPR:
10800     case LROTATE_EXPR:
10801     case EQ_EXPR:
10802     case NE_EXPR:
10803     case MAX_EXPR:
10804     case MIN_EXPR:
10805     case LE_EXPR:
10806     case GE_EXPR:
10807     case LT_EXPR:
10808     case GT_EXPR:
10809     case COMPOUND_EXPR:
10810     case DOTSTAR_EXPR:
10811     case MEMBER_REF:
10812     case PREDECREMENT_EXPR:
10813     case PREINCREMENT_EXPR:
10814     case POSTDECREMENT_EXPR:
10815     case POSTINCREMENT_EXPR:
10816       return build_nt
10817         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10818          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10819
10820     case SCOPE_REF:
10821       return build_qualified_name (/*type=*/NULL_TREE,
10822                                    tsubst_copy (TREE_OPERAND (t, 0),
10823                                                 args, complain, in_decl),
10824                                    tsubst_copy (TREE_OPERAND (t, 1),
10825                                                 args, complain, in_decl),
10826                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10827
10828     case ARRAY_REF:
10829       return build_nt
10830         (ARRAY_REF,
10831          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10832          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10833          NULL_TREE, NULL_TREE);
10834
10835     case CALL_EXPR:
10836       {
10837         int n = VL_EXP_OPERAND_LENGTH (t);
10838         tree result = build_vl_exp (CALL_EXPR, n);
10839         int i;
10840         for (i = 0; i < n; i++)
10841           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10842                                              complain, in_decl);
10843         return result;
10844       }
10845
10846     case COND_EXPR:
10847     case MODOP_EXPR:
10848     case PSEUDO_DTOR_EXPR:
10849       {
10850         r = build_nt
10851           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10852            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10853            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10854         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10855         return r;
10856       }
10857
10858     case NEW_EXPR:
10859       {
10860         r = build_nt
10861         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10862          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10863          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10864         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10865         return r;
10866       }
10867
10868     case DELETE_EXPR:
10869       {
10870         r = build_nt
10871         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10872          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10873         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10874         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10875         return r;
10876       }
10877
10878     case TEMPLATE_ID_EXPR:
10879       {
10880         /* Substituted template arguments */
10881         tree fn = TREE_OPERAND (t, 0);
10882         tree targs = TREE_OPERAND (t, 1);
10883
10884         fn = tsubst_copy (fn, args, complain, in_decl);
10885         if (targs)
10886           targs = tsubst_template_args (targs, args, complain, in_decl);
10887
10888         return lookup_template_function (fn, targs);
10889       }
10890
10891     case TREE_LIST:
10892       {
10893         tree purpose, value, chain;
10894
10895         if (t == void_list_node)
10896           return t;
10897
10898         purpose = TREE_PURPOSE (t);
10899         if (purpose)
10900           purpose = tsubst_copy (purpose, args, complain, in_decl);
10901         value = TREE_VALUE (t);
10902         if (value)
10903           value = tsubst_copy (value, args, complain, in_decl);
10904         chain = TREE_CHAIN (t);
10905         if (chain && chain != void_type_node)
10906           chain = tsubst_copy (chain, args, complain, in_decl);
10907         if (purpose == TREE_PURPOSE (t)
10908             && value == TREE_VALUE (t)
10909             && chain == TREE_CHAIN (t))
10910           return t;
10911         return tree_cons (purpose, value, chain);
10912       }
10913
10914     case RECORD_TYPE:
10915     case UNION_TYPE:
10916     case ENUMERAL_TYPE:
10917     case INTEGER_TYPE:
10918     case TEMPLATE_TYPE_PARM:
10919     case TEMPLATE_TEMPLATE_PARM:
10920     case BOUND_TEMPLATE_TEMPLATE_PARM:
10921     case TEMPLATE_PARM_INDEX:
10922     case POINTER_TYPE:
10923     case REFERENCE_TYPE:
10924     case OFFSET_TYPE:
10925     case FUNCTION_TYPE:
10926     case METHOD_TYPE:
10927     case ARRAY_TYPE:
10928     case TYPENAME_TYPE:
10929     case UNBOUND_CLASS_TEMPLATE:
10930     case TYPEOF_TYPE:
10931     case DECLTYPE_TYPE:
10932     case TYPE_DECL:
10933       return tsubst (t, args, complain, in_decl);
10934
10935     case IDENTIFIER_NODE:
10936       if (IDENTIFIER_TYPENAME_P (t))
10937         {
10938           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10939           return mangle_conv_op_name_for_type (new_type);
10940         }
10941       else
10942         return t;
10943
10944     case CONSTRUCTOR:
10945       /* This is handled by tsubst_copy_and_build.  */
10946       gcc_unreachable ();
10947
10948     case VA_ARG_EXPR:
10949       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10950                                           in_decl),
10951                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10952
10953     case CLEANUP_POINT_EXPR:
10954       /* We shouldn't have built any of these during initial template
10955          generation.  Instead, they should be built during instantiation
10956          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10957       gcc_unreachable ();
10958
10959     case OFFSET_REF:
10960       mark_used (TREE_OPERAND (t, 1));
10961       return t;
10962
10963     case EXPR_PACK_EXPANSION:
10964       error ("invalid use of pack expansion expression");
10965       return error_mark_node;
10966
10967     case NONTYPE_ARGUMENT_PACK:
10968       error ("use %<...%> to expand argument pack");
10969       return error_mark_node;
10970
10971     default:
10972       return t;
10973     }
10974 }
10975
10976 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10977
10978 static tree
10979 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10980                     tree in_decl)
10981 {
10982   tree new_clauses = NULL, nc, oc;
10983
10984   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10985     {
10986       nc = copy_node (oc);
10987       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10988       new_clauses = nc;
10989
10990       switch (OMP_CLAUSE_CODE (nc))
10991         {
10992         case OMP_CLAUSE_LASTPRIVATE:
10993           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
10994             {
10995               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
10996               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
10997                            in_decl, /*integral_constant_expression_p=*/false);
10998               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
10999                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11000             }
11001           /* FALLTHRU */
11002         case OMP_CLAUSE_PRIVATE:
11003         case OMP_CLAUSE_SHARED:
11004         case OMP_CLAUSE_FIRSTPRIVATE:
11005         case OMP_CLAUSE_REDUCTION:
11006         case OMP_CLAUSE_COPYIN:
11007         case OMP_CLAUSE_COPYPRIVATE:
11008         case OMP_CLAUSE_IF:
11009         case OMP_CLAUSE_NUM_THREADS:
11010         case OMP_CLAUSE_SCHEDULE:
11011         case OMP_CLAUSE_COLLAPSE:
11012           OMP_CLAUSE_OPERAND (nc, 0)
11013             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11014                            in_decl, /*integral_constant_expression_p=*/false);
11015           break;
11016         case OMP_CLAUSE_NOWAIT:
11017         case OMP_CLAUSE_ORDERED:
11018         case OMP_CLAUSE_DEFAULT:
11019         case OMP_CLAUSE_UNTIED:
11020           break;
11021         default:
11022           gcc_unreachable ();
11023         }
11024     }
11025
11026   return finish_omp_clauses (nreverse (new_clauses));
11027 }
11028
11029 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11030
11031 static tree
11032 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11033                           tree in_decl)
11034 {
11035 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11036
11037   tree purpose, value, chain;
11038
11039   if (t == NULL)
11040     return t;
11041
11042   if (TREE_CODE (t) != TREE_LIST)
11043     return tsubst_copy_and_build (t, args, complain, in_decl,
11044                                   /*function_p=*/false,
11045                                   /*integral_constant_expression_p=*/false);
11046
11047   if (t == void_list_node)
11048     return t;
11049
11050   purpose = TREE_PURPOSE (t);
11051   if (purpose)
11052     purpose = RECUR (purpose);
11053   value = TREE_VALUE (t);
11054   if (value && TREE_CODE (value) != LABEL_DECL)
11055     value = RECUR (value);
11056   chain = TREE_CHAIN (t);
11057   if (chain && chain != void_type_node)
11058     chain = RECUR (chain);
11059   return tree_cons (purpose, value, chain);
11060 #undef RECUR
11061 }
11062
11063 /* Substitute one OMP_FOR iterator.  */
11064
11065 static void
11066 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11067                          tree condv, tree incrv, tree *clauses,
11068                          tree args, tsubst_flags_t complain, tree in_decl,
11069                          bool integral_constant_expression_p)
11070 {
11071 #define RECUR(NODE)                             \
11072   tsubst_expr ((NODE), args, complain, in_decl, \
11073                integral_constant_expression_p)
11074   tree decl, init, cond, incr, auto_node;
11075
11076   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11077   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11078   decl = RECUR (TREE_OPERAND (init, 0));
11079   init = TREE_OPERAND (init, 1);
11080   auto_node = type_uses_auto (TREE_TYPE (decl));
11081   if (auto_node && init)
11082     {
11083       tree init_expr = init;
11084       if (TREE_CODE (init_expr) == DECL_EXPR)
11085         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11086       init_expr = RECUR (init_expr);
11087       TREE_TYPE (decl)
11088         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11089     }
11090   gcc_assert (!type_dependent_expression_p (decl));
11091
11092   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11093     {
11094       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11095       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11096       if (TREE_CODE (incr) == MODIFY_EXPR)
11097         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11098                                     RECUR (TREE_OPERAND (incr, 1)),
11099                                     complain);
11100       else
11101         incr = RECUR (incr);
11102       TREE_VEC_ELT (declv, i) = decl;
11103       TREE_VEC_ELT (initv, i) = init;
11104       TREE_VEC_ELT (condv, i) = cond;
11105       TREE_VEC_ELT (incrv, i) = incr;
11106       return;
11107     }
11108
11109   if (init && TREE_CODE (init) != DECL_EXPR)
11110     {
11111       tree c;
11112       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11113         {
11114           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11115                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11116               && OMP_CLAUSE_DECL (c) == decl)
11117             break;
11118           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11119                    && OMP_CLAUSE_DECL (c) == decl)
11120             error ("iteration variable %qD should not be firstprivate", decl);
11121           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11122                    && OMP_CLAUSE_DECL (c) == decl)
11123             error ("iteration variable %qD should not be reduction", decl);
11124         }
11125       if (c == NULL)
11126         {
11127           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11128           OMP_CLAUSE_DECL (c) = decl;
11129           c = finish_omp_clauses (c);
11130           if (c)
11131             {
11132               OMP_CLAUSE_CHAIN (c) = *clauses;
11133               *clauses = c;
11134             }
11135         }
11136     }
11137   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11138   if (COMPARISON_CLASS_P (cond))
11139     cond = build2 (TREE_CODE (cond), boolean_type_node,
11140                    RECUR (TREE_OPERAND (cond, 0)),
11141                    RECUR (TREE_OPERAND (cond, 1)));
11142   else
11143     cond = RECUR (cond);
11144   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11145   switch (TREE_CODE (incr))
11146     {
11147     case PREINCREMENT_EXPR:
11148     case PREDECREMENT_EXPR:
11149     case POSTINCREMENT_EXPR:
11150     case POSTDECREMENT_EXPR:
11151       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11152                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11153       break;
11154     case MODIFY_EXPR:
11155       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11156           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11157         {
11158           tree rhs = TREE_OPERAND (incr, 1);
11159           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11160                          RECUR (TREE_OPERAND (incr, 0)),
11161                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11162                                  RECUR (TREE_OPERAND (rhs, 0)),
11163                                  RECUR (TREE_OPERAND (rhs, 1))));
11164         }
11165       else
11166         incr = RECUR (incr);
11167       break;
11168     case MODOP_EXPR:
11169       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11170           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11171         {
11172           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11173           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11174                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11175                                  TREE_TYPE (decl), lhs,
11176                                  RECUR (TREE_OPERAND (incr, 2))));
11177         }
11178       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11179                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11180                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11181         {
11182           tree rhs = TREE_OPERAND (incr, 2);
11183           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11184                          RECUR (TREE_OPERAND (incr, 0)),
11185                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11186                                  RECUR (TREE_OPERAND (rhs, 0)),
11187                                  RECUR (TREE_OPERAND (rhs, 1))));
11188         }
11189       else
11190         incr = RECUR (incr);
11191       break;
11192     default:
11193       incr = RECUR (incr);
11194       break;
11195     }
11196
11197   TREE_VEC_ELT (declv, i) = decl;
11198   TREE_VEC_ELT (initv, i) = init;
11199   TREE_VEC_ELT (condv, i) = cond;
11200   TREE_VEC_ELT (incrv, i) = incr;
11201 #undef RECUR
11202 }
11203
11204 /* Like tsubst_copy for expressions, etc. but also does semantic
11205    processing.  */
11206
11207 static tree
11208 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11209              bool integral_constant_expression_p)
11210 {
11211 #define RECUR(NODE)                             \
11212   tsubst_expr ((NODE), args, complain, in_decl, \
11213                integral_constant_expression_p)
11214
11215   tree stmt, tmp;
11216
11217   if (t == NULL_TREE || t == error_mark_node)
11218     return t;
11219
11220   if (EXPR_HAS_LOCATION (t))
11221     input_location = EXPR_LOCATION (t);
11222   if (STATEMENT_CODE_P (TREE_CODE (t)))
11223     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11224
11225   switch (TREE_CODE (t))
11226     {
11227     case STATEMENT_LIST:
11228       {
11229         tree_stmt_iterator i;
11230         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11231           RECUR (tsi_stmt (i));
11232         break;
11233       }
11234
11235     case CTOR_INITIALIZER:
11236       finish_mem_initializers (tsubst_initializer_list
11237                                (TREE_OPERAND (t, 0), args));
11238       break;
11239
11240     case RETURN_EXPR:
11241       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11242       break;
11243
11244     case EXPR_STMT:
11245       tmp = RECUR (EXPR_STMT_EXPR (t));
11246       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11247         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11248       else
11249         finish_expr_stmt (tmp);
11250       break;
11251
11252     case USING_STMT:
11253       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11254       break;
11255
11256     case DECL_EXPR:
11257       {
11258         tree decl;
11259         tree init;
11260
11261         decl = DECL_EXPR_DECL (t);
11262         if (TREE_CODE (decl) == LABEL_DECL)
11263           finish_label_decl (DECL_NAME (decl));
11264         else if (TREE_CODE (decl) == USING_DECL)
11265           {
11266             tree scope = USING_DECL_SCOPE (decl);
11267             tree name = DECL_NAME (decl);
11268             tree decl;
11269
11270             scope = RECUR (scope);
11271             decl = lookup_qualified_name (scope, name,
11272                                           /*is_type_p=*/false,
11273                                           /*complain=*/false);
11274             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11275               qualified_name_lookup_error (scope, name, decl, input_location);
11276             else
11277               do_local_using_decl (decl, scope, name);
11278           }
11279         else
11280           {
11281             init = DECL_INITIAL (decl);
11282             decl = tsubst (decl, args, complain, in_decl);
11283             if (decl != error_mark_node)
11284               {
11285                 /* By marking the declaration as instantiated, we avoid
11286                    trying to instantiate it.  Since instantiate_decl can't
11287                    handle local variables, and since we've already done
11288                    all that needs to be done, that's the right thing to
11289                    do.  */
11290                 if (TREE_CODE (decl) == VAR_DECL)
11291                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11292                 if (TREE_CODE (decl) == VAR_DECL
11293                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11294                   /* Anonymous aggregates are a special case.  */
11295                   finish_anon_union (decl);
11296                 else
11297                   {
11298                     maybe_push_decl (decl);
11299                     if (TREE_CODE (decl) == VAR_DECL
11300                         && DECL_PRETTY_FUNCTION_P (decl))
11301                       {
11302                         /* For __PRETTY_FUNCTION__ we have to adjust the
11303                            initializer.  */
11304                         const char *const name
11305                           = cxx_printable_name (current_function_decl, 2);
11306                         init = cp_fname_init (name, &TREE_TYPE (decl));
11307                       }
11308                     else
11309                       {
11310                         tree t = RECUR (init);
11311
11312                         if (init && !t)
11313                           /* If we had an initializer but it
11314                              instantiated to nothing,
11315                              value-initialize the object.  This will
11316                              only occur when the initializer was a
11317                              pack expansion where the parameter packs
11318                              used in that expansion were of length
11319                              zero.  */
11320                           init = build_value_init (TREE_TYPE (decl));
11321                         else
11322                           init = t;
11323                       }
11324
11325                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11326                   }
11327               }
11328           }
11329
11330         /* A DECL_EXPR can also be used as an expression, in the condition
11331            clause of an if/for/while construct.  */
11332         return decl;
11333       }
11334
11335     case FOR_STMT:
11336       stmt = begin_for_stmt ();
11337                           RECUR (FOR_INIT_STMT (t));
11338       finish_for_init_stmt (stmt);
11339       tmp = RECUR (FOR_COND (t));
11340       finish_for_cond (tmp, stmt);
11341       tmp = RECUR (FOR_EXPR (t));
11342       finish_for_expr (tmp, stmt);
11343       RECUR (FOR_BODY (t));
11344       finish_for_stmt (stmt);
11345       break;
11346
11347     case WHILE_STMT:
11348       stmt = begin_while_stmt ();
11349       tmp = RECUR (WHILE_COND (t));
11350       finish_while_stmt_cond (tmp, stmt);
11351       RECUR (WHILE_BODY (t));
11352       finish_while_stmt (stmt);
11353       break;
11354
11355     case DO_STMT:
11356       stmt = begin_do_stmt ();
11357       RECUR (DO_BODY (t));
11358       finish_do_body (stmt);
11359       tmp = RECUR (DO_COND (t));
11360       finish_do_stmt (tmp, stmt);
11361       break;
11362
11363     case IF_STMT:
11364       stmt = begin_if_stmt ();
11365       tmp = RECUR (IF_COND (t));
11366       finish_if_stmt_cond (tmp, stmt);
11367       RECUR (THEN_CLAUSE (t));
11368       finish_then_clause (stmt);
11369
11370       if (ELSE_CLAUSE (t))
11371         {
11372           begin_else_clause (stmt);
11373           RECUR (ELSE_CLAUSE (t));
11374           finish_else_clause (stmt);
11375         }
11376
11377       finish_if_stmt (stmt);
11378       break;
11379
11380     case BIND_EXPR:
11381       if (BIND_EXPR_BODY_BLOCK (t))
11382         stmt = begin_function_body ();
11383       else
11384         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11385                                     ? BCS_TRY_BLOCK : 0);
11386
11387       RECUR (BIND_EXPR_BODY (t));
11388
11389       if (BIND_EXPR_BODY_BLOCK (t))
11390         finish_function_body (stmt);
11391       else
11392         finish_compound_stmt (stmt);
11393       break;
11394
11395     case BREAK_STMT:
11396       finish_break_stmt ();
11397       break;
11398
11399     case CONTINUE_STMT:
11400       finish_continue_stmt ();
11401       break;
11402
11403     case SWITCH_STMT:
11404       stmt = begin_switch_stmt ();
11405       tmp = RECUR (SWITCH_STMT_COND (t));
11406       finish_switch_cond (tmp, stmt);
11407       RECUR (SWITCH_STMT_BODY (t));
11408       finish_switch_stmt (stmt);
11409       break;
11410
11411     case CASE_LABEL_EXPR:
11412       finish_case_label (EXPR_LOCATION (t),
11413                          RECUR (CASE_LOW (t)),
11414                          RECUR (CASE_HIGH (t)));
11415       break;
11416
11417     case LABEL_EXPR:
11418       {
11419         tree decl = LABEL_EXPR_LABEL (t);
11420         tree label;
11421
11422         label = finish_label_stmt (DECL_NAME (decl));
11423         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11424           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11425       }
11426       break;
11427
11428     case GOTO_EXPR:
11429       tmp = GOTO_DESTINATION (t);
11430       if (TREE_CODE (tmp) != LABEL_DECL)
11431         /* Computed goto's must be tsubst'd into.  On the other hand,
11432            non-computed gotos must not be; the identifier in question
11433            will have no binding.  */
11434         tmp = RECUR (tmp);
11435       else
11436         tmp = DECL_NAME (tmp);
11437       finish_goto_stmt (tmp);
11438       break;
11439
11440     case ASM_EXPR:
11441       tmp = finish_asm_stmt
11442         (ASM_VOLATILE_P (t),
11443          RECUR (ASM_STRING (t)),
11444          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11445          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11446          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11447          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11448       {
11449         tree asm_expr = tmp;
11450         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11451           asm_expr = TREE_OPERAND (asm_expr, 0);
11452         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11453       }
11454       break;
11455
11456     case TRY_BLOCK:
11457       if (CLEANUP_P (t))
11458         {
11459           stmt = begin_try_block ();
11460           RECUR (TRY_STMTS (t));
11461           finish_cleanup_try_block (stmt);
11462           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11463         }
11464       else
11465         {
11466           tree compound_stmt = NULL_TREE;
11467
11468           if (FN_TRY_BLOCK_P (t))
11469             stmt = begin_function_try_block (&compound_stmt);
11470           else
11471             stmt = begin_try_block ();
11472
11473           RECUR (TRY_STMTS (t));
11474
11475           if (FN_TRY_BLOCK_P (t))
11476             finish_function_try_block (stmt);
11477           else
11478             finish_try_block (stmt);
11479
11480           RECUR (TRY_HANDLERS (t));
11481           if (FN_TRY_BLOCK_P (t))
11482             finish_function_handler_sequence (stmt, compound_stmt);
11483           else
11484             finish_handler_sequence (stmt);
11485         }
11486       break;
11487
11488     case HANDLER:
11489       {
11490         tree decl = HANDLER_PARMS (t);
11491
11492         if (decl)
11493           {
11494             decl = tsubst (decl, args, complain, in_decl);
11495             /* Prevent instantiate_decl from trying to instantiate
11496                this variable.  We've already done all that needs to be
11497                done.  */
11498             if (decl != error_mark_node)
11499               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11500           }
11501         stmt = begin_handler ();
11502         finish_handler_parms (decl, stmt);
11503         RECUR (HANDLER_BODY (t));
11504         finish_handler (stmt);
11505       }
11506       break;
11507
11508     case TAG_DEFN:
11509       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11510       break;
11511
11512     case STATIC_ASSERT:
11513       {
11514         tree condition = 
11515           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11516                        args,
11517                        complain, in_decl,
11518                        /*integral_constant_expression_p=*/true);
11519         finish_static_assert (condition,
11520                               STATIC_ASSERT_MESSAGE (t),
11521                               STATIC_ASSERT_SOURCE_LOCATION (t),
11522                               /*member_p=*/false);
11523       }
11524       break;
11525
11526     case OMP_PARALLEL:
11527       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11528                                 args, complain, in_decl);
11529       stmt = begin_omp_parallel ();
11530       RECUR (OMP_PARALLEL_BODY (t));
11531       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11532         = OMP_PARALLEL_COMBINED (t);
11533       break;
11534
11535     case OMP_TASK:
11536       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11537                                 args, complain, in_decl);
11538       stmt = begin_omp_task ();
11539       RECUR (OMP_TASK_BODY (t));
11540       finish_omp_task (tmp, stmt);
11541       break;
11542
11543     case OMP_FOR:
11544       {
11545         tree clauses, body, pre_body;
11546         tree declv, initv, condv, incrv;
11547         int i;
11548
11549         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11550                                       args, complain, in_decl);
11551         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11552         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11553         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11554         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11555
11556         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11557           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11558                                    &clauses, args, complain, in_decl,
11559                                    integral_constant_expression_p);
11560
11561         stmt = begin_omp_structured_block ();
11562
11563         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11564           if (TREE_VEC_ELT (initv, i) == NULL
11565               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11566             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11567           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11568             {
11569               tree init = RECUR (TREE_VEC_ELT (initv, i));
11570               gcc_assert (init == TREE_VEC_ELT (declv, i));
11571               TREE_VEC_ELT (initv, i) = NULL_TREE;
11572             }
11573           else
11574             {
11575               tree decl_expr = TREE_VEC_ELT (initv, i);
11576               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11577               gcc_assert (init != NULL);
11578               TREE_VEC_ELT (initv, i) = RECUR (init);
11579               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11580               RECUR (decl_expr);
11581               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11582             }
11583
11584         pre_body = push_stmt_list ();
11585         RECUR (OMP_FOR_PRE_BODY (t));
11586         pre_body = pop_stmt_list (pre_body);
11587
11588         body = push_stmt_list ();
11589         RECUR (OMP_FOR_BODY (t));
11590         body = pop_stmt_list (body);
11591
11592         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11593                             body, pre_body, clauses);
11594
11595         add_stmt (finish_omp_structured_block (stmt));
11596       }
11597       break;
11598
11599     case OMP_SECTIONS:
11600     case OMP_SINGLE:
11601       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11602       stmt = push_stmt_list ();
11603       RECUR (OMP_BODY (t));
11604       stmt = pop_stmt_list (stmt);
11605
11606       t = copy_node (t);
11607       OMP_BODY (t) = stmt;
11608       OMP_CLAUSES (t) = tmp;
11609       add_stmt (t);
11610       break;
11611
11612     case OMP_SECTION:
11613     case OMP_CRITICAL:
11614     case OMP_MASTER:
11615     case OMP_ORDERED:
11616       stmt = push_stmt_list ();
11617       RECUR (OMP_BODY (t));
11618       stmt = pop_stmt_list (stmt);
11619
11620       t = copy_node (t);
11621       OMP_BODY (t) = stmt;
11622       add_stmt (t);
11623       break;
11624
11625     case OMP_ATOMIC:
11626       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11627       {
11628         tree op1 = TREE_OPERAND (t, 1);
11629         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11630         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11631         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11632       }
11633       break;
11634
11635     case EXPR_PACK_EXPANSION:
11636       error ("invalid use of pack expansion expression");
11637       return error_mark_node;
11638
11639     case NONTYPE_ARGUMENT_PACK:
11640       error ("use %<...%> to expand argument pack");
11641       return error_mark_node;
11642
11643     default:
11644       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11645
11646       return tsubst_copy_and_build (t, args, complain, in_decl,
11647                                     /*function_p=*/false,
11648                                     integral_constant_expression_p);
11649     }
11650
11651   return NULL_TREE;
11652 #undef RECUR
11653 }
11654
11655 /* T is a postfix-expression that is not being used in a function
11656    call.  Return the substituted version of T.  */
11657
11658 static tree
11659 tsubst_non_call_postfix_expression (tree t, tree args,
11660                                     tsubst_flags_t complain,
11661                                     tree in_decl)
11662 {
11663   if (TREE_CODE (t) == SCOPE_REF)
11664     t = tsubst_qualified_id (t, args, complain, in_decl,
11665                              /*done=*/false, /*address_p=*/false);
11666   else
11667     t = tsubst_copy_and_build (t, args, complain, in_decl,
11668                                /*function_p=*/false,
11669                                /*integral_constant_expression_p=*/false);
11670
11671   return t;
11672 }
11673
11674 /* Like tsubst but deals with expressions and performs semantic
11675    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11676
11677 tree
11678 tsubst_copy_and_build (tree t,
11679                        tree args,
11680                        tsubst_flags_t complain,
11681                        tree in_decl,
11682                        bool function_p,
11683                        bool integral_constant_expression_p)
11684 {
11685 #define RECUR(NODE)                                             \
11686   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11687                          /*function_p=*/false,                  \
11688                          integral_constant_expression_p)
11689
11690   tree op1;
11691
11692   if (t == NULL_TREE || t == error_mark_node)
11693     return t;
11694
11695   switch (TREE_CODE (t))
11696     {
11697     case USING_DECL:
11698       t = DECL_NAME (t);
11699       /* Fall through.  */
11700     case IDENTIFIER_NODE:
11701       {
11702         tree decl;
11703         cp_id_kind idk;
11704         bool non_integral_constant_expression_p;
11705         const char *error_msg;
11706
11707         if (IDENTIFIER_TYPENAME_P (t))
11708           {
11709             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11710             t = mangle_conv_op_name_for_type (new_type);
11711           }
11712
11713         /* Look up the name.  */
11714         decl = lookup_name (t);
11715
11716         /* By convention, expressions use ERROR_MARK_NODE to indicate
11717            failure, not NULL_TREE.  */
11718         if (decl == NULL_TREE)
11719           decl = error_mark_node;
11720
11721         decl = finish_id_expression (t, decl, NULL_TREE,
11722                                      &idk,
11723                                      integral_constant_expression_p,
11724                                      /*allow_non_integral_constant_expression_p=*/false,
11725                                      &non_integral_constant_expression_p,
11726                                      /*template_p=*/false,
11727                                      /*done=*/true,
11728                                      /*address_p=*/false,
11729                                      /*template_arg_p=*/false,
11730                                      &error_msg,
11731                                      input_location);
11732         if (error_msg)
11733           error (error_msg);
11734         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11735           decl = unqualified_name_lookup_error (decl);
11736         return decl;
11737       }
11738
11739     case TEMPLATE_ID_EXPR:
11740       {
11741         tree object;
11742         tree templ = RECUR (TREE_OPERAND (t, 0));
11743         tree targs = TREE_OPERAND (t, 1);
11744
11745         if (targs)
11746           targs = tsubst_template_args (targs, args, complain, in_decl);
11747
11748         if (TREE_CODE (templ) == COMPONENT_REF)
11749           {
11750             object = TREE_OPERAND (templ, 0);
11751             templ = TREE_OPERAND (templ, 1);
11752           }
11753         else
11754           object = NULL_TREE;
11755         templ = lookup_template_function (templ, targs);
11756
11757         if (object)
11758           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11759                          object, templ, NULL_TREE);
11760         else
11761           return baselink_for_fns (templ);
11762       }
11763
11764     case INDIRECT_REF:
11765       {
11766         tree r = RECUR (TREE_OPERAND (t, 0));
11767
11768         if (REFERENCE_REF_P (t))
11769           {
11770             /* A type conversion to reference type will be enclosed in
11771                such an indirect ref, but the substitution of the cast
11772                will have also added such an indirect ref.  */
11773             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11774               r = convert_from_reference (r);
11775           }
11776         else
11777           r = build_x_indirect_ref (r, "unary *", complain);
11778         return r;
11779       }
11780
11781     case NOP_EXPR:
11782       return build_nop
11783         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11784          RECUR (TREE_OPERAND (t, 0)));
11785
11786     case CAST_EXPR:
11787     case REINTERPRET_CAST_EXPR:
11788     case CONST_CAST_EXPR:
11789     case DYNAMIC_CAST_EXPR:
11790     case STATIC_CAST_EXPR:
11791       {
11792         tree type;
11793         tree op;
11794
11795         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11796         if (integral_constant_expression_p
11797             && !cast_valid_in_integral_constant_expression_p (type))
11798           {
11799             if (complain & tf_error)
11800               error ("a cast to a type other than an integral or "
11801                      "enumeration type cannot appear in a constant-expression");
11802             return error_mark_node; 
11803           }
11804
11805         op = RECUR (TREE_OPERAND (t, 0));
11806
11807         switch (TREE_CODE (t))
11808           {
11809           case CAST_EXPR:
11810             return build_functional_cast (type, op, complain);
11811           case REINTERPRET_CAST_EXPR:
11812             return build_reinterpret_cast (type, op, complain);
11813           case CONST_CAST_EXPR:
11814             return build_const_cast (type, op, complain);
11815           case DYNAMIC_CAST_EXPR:
11816             return build_dynamic_cast (type, op, complain);
11817           case STATIC_CAST_EXPR:
11818             return build_static_cast (type, op, complain);
11819           default:
11820             gcc_unreachable ();
11821           }
11822       }
11823
11824     case POSTDECREMENT_EXPR:
11825     case POSTINCREMENT_EXPR:
11826       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11827                                                 args, complain, in_decl);
11828       return build_x_unary_op (TREE_CODE (t), op1, complain);
11829
11830     case PREDECREMENT_EXPR:
11831     case PREINCREMENT_EXPR:
11832     case NEGATE_EXPR:
11833     case BIT_NOT_EXPR:
11834     case ABS_EXPR:
11835     case TRUTH_NOT_EXPR:
11836     case UNARY_PLUS_EXPR:  /* Unary + */
11837     case REALPART_EXPR:
11838     case IMAGPART_EXPR:
11839       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11840                                complain);
11841
11842     case ADDR_EXPR:
11843       op1 = TREE_OPERAND (t, 0);
11844       if (TREE_CODE (op1) == SCOPE_REF)
11845         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11846                                    /*done=*/true, /*address_p=*/true);
11847       else
11848         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11849                                                   in_decl);
11850       if (TREE_CODE (op1) == LABEL_DECL)
11851         return finish_label_address_expr (DECL_NAME (op1),
11852                                           EXPR_LOCATION (op1));
11853       return build_x_unary_op (ADDR_EXPR, op1, complain);
11854
11855     case PLUS_EXPR:
11856     case MINUS_EXPR:
11857     case MULT_EXPR:
11858     case TRUNC_DIV_EXPR:
11859     case CEIL_DIV_EXPR:
11860     case FLOOR_DIV_EXPR:
11861     case ROUND_DIV_EXPR:
11862     case EXACT_DIV_EXPR:
11863     case BIT_AND_EXPR:
11864     case BIT_IOR_EXPR:
11865     case BIT_XOR_EXPR:
11866     case TRUNC_MOD_EXPR:
11867     case FLOOR_MOD_EXPR:
11868     case TRUTH_ANDIF_EXPR:
11869     case TRUTH_ORIF_EXPR:
11870     case TRUTH_AND_EXPR:
11871     case TRUTH_OR_EXPR:
11872     case RSHIFT_EXPR:
11873     case LSHIFT_EXPR:
11874     case RROTATE_EXPR:
11875     case LROTATE_EXPR:
11876     case EQ_EXPR:
11877     case NE_EXPR:
11878     case MAX_EXPR:
11879     case MIN_EXPR:
11880     case LE_EXPR:
11881     case GE_EXPR:
11882     case LT_EXPR:
11883     case GT_EXPR:
11884     case MEMBER_REF:
11885     case DOTSTAR_EXPR:
11886       return build_x_binary_op
11887         (TREE_CODE (t),
11888          RECUR (TREE_OPERAND (t, 0)),
11889          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11890           ? ERROR_MARK
11891           : TREE_CODE (TREE_OPERAND (t, 0))),
11892          RECUR (TREE_OPERAND (t, 1)),
11893          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11894           ? ERROR_MARK
11895           : TREE_CODE (TREE_OPERAND (t, 1))),
11896          /*overloaded_p=*/NULL,
11897          complain);
11898
11899     case SCOPE_REF:
11900       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11901                                   /*address_p=*/false);
11902     case ARRAY_REF:
11903       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11904                                                 args, complain, in_decl);
11905       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11906
11907     case SIZEOF_EXPR:
11908       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11909         return tsubst_copy (t, args, complain, in_decl);
11910       /* Fall through */
11911       
11912     case ALIGNOF_EXPR:
11913       op1 = TREE_OPERAND (t, 0);
11914       if (!args)
11915         {
11916           /* When there are no ARGS, we are trying to evaluate a
11917              non-dependent expression from the parser.  Trying to do
11918              the substitutions may not work.  */
11919           if (!TYPE_P (op1))
11920             op1 = TREE_TYPE (op1);
11921         }
11922       else
11923         {
11924           ++cp_unevaluated_operand;
11925           ++c_inhibit_evaluation_warnings;
11926           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11927                                        /*function_p=*/false,
11928                                        /*integral_constant_expression_p=*/false);
11929           --cp_unevaluated_operand;
11930           --c_inhibit_evaluation_warnings;
11931         }
11932       if (TYPE_P (op1))
11933         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11934                                            complain & tf_error);
11935       else
11936         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11937                                            complain & tf_error);
11938
11939     case MODOP_EXPR:
11940       {
11941         tree r = build_x_modify_expr
11942           (RECUR (TREE_OPERAND (t, 0)),
11943            TREE_CODE (TREE_OPERAND (t, 1)),
11944            RECUR (TREE_OPERAND (t, 2)),
11945            complain);
11946         /* TREE_NO_WARNING must be set if either the expression was
11947            parenthesized or it uses an operator such as >>= rather
11948            than plain assignment.  In the former case, it was already
11949            set and must be copied.  In the latter case,
11950            build_x_modify_expr sets it and it must not be reset
11951            here.  */
11952         if (TREE_NO_WARNING (t))
11953           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11954         return r;
11955       }
11956
11957     case ARROW_EXPR:
11958       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11959                                                 args, complain, in_decl);
11960       /* Remember that there was a reference to this entity.  */
11961       if (DECL_P (op1))
11962         mark_used (op1);
11963       return build_x_arrow (op1);
11964
11965     case NEW_EXPR:
11966       {
11967         tree placement = RECUR (TREE_OPERAND (t, 0));
11968         tree init = RECUR (TREE_OPERAND (t, 3));
11969         VEC(tree,gc) *placement_vec;
11970         VEC(tree,gc) *init_vec;
11971         tree ret;
11972
11973         if (placement == NULL_TREE)
11974           placement_vec = NULL;
11975         else
11976           {
11977             placement_vec = make_tree_vector ();
11978             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
11979               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
11980           }
11981
11982         /* If there was an initializer in the original tree, but it
11983            instantiated to an empty list, then we should pass a
11984            non-NULL empty vector to tell build_new that it was an
11985            empty initializer() rather than no initializer.  This can
11986            only happen when the initializer is a pack expansion whose
11987            parameter packs are of length zero.  */
11988         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
11989           init_vec = NULL;
11990         else
11991           {
11992             init_vec = make_tree_vector ();
11993             if (init == void_zero_node)
11994               gcc_assert (init_vec != NULL);
11995             else
11996               {
11997                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
11998                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
11999               }
12000           }
12001
12002         ret = build_new (&placement_vec,
12003                          RECUR (TREE_OPERAND (t, 1)),
12004                          RECUR (TREE_OPERAND (t, 2)),
12005                          &init_vec,
12006                          NEW_EXPR_USE_GLOBAL (t),
12007                          complain);
12008
12009         if (placement_vec != NULL)
12010           release_tree_vector (placement_vec);
12011         if (init_vec != NULL)
12012           release_tree_vector (init_vec);
12013
12014         return ret;
12015       }
12016
12017     case DELETE_EXPR:
12018      return delete_sanity
12019        (RECUR (TREE_OPERAND (t, 0)),
12020         RECUR (TREE_OPERAND (t, 1)),
12021         DELETE_EXPR_USE_VEC (t),
12022         DELETE_EXPR_USE_GLOBAL (t));
12023
12024     case COMPOUND_EXPR:
12025       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12026                                     RECUR (TREE_OPERAND (t, 1)),
12027                                     complain);
12028
12029     case CALL_EXPR:
12030       {
12031         tree function;
12032         VEC(tree,gc) *call_args;
12033         unsigned int nargs, i;
12034         bool qualified_p;
12035         bool koenig_p;
12036         tree ret;
12037
12038         function = CALL_EXPR_FN (t);
12039         /* When we parsed the expression,  we determined whether or
12040            not Koenig lookup should be performed.  */
12041         koenig_p = KOENIG_LOOKUP_P (t);
12042         if (TREE_CODE (function) == SCOPE_REF)
12043           {
12044             qualified_p = true;
12045             function = tsubst_qualified_id (function, args, complain, in_decl,
12046                                             /*done=*/false,
12047                                             /*address_p=*/false);
12048           }
12049         else
12050           {
12051             if (TREE_CODE (function) == COMPONENT_REF)
12052               {
12053                 tree op = TREE_OPERAND (function, 1);
12054
12055                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12056                                || (BASELINK_P (op)
12057                                    && BASELINK_QUALIFIED_P (op)));
12058               }
12059             else
12060               qualified_p = false;
12061
12062             function = tsubst_copy_and_build (function, args, complain,
12063                                               in_decl,
12064                                               !qualified_p,
12065                                               integral_constant_expression_p);
12066
12067             if (BASELINK_P (function))
12068               qualified_p = true;
12069           }
12070
12071         nargs = call_expr_nargs (t);
12072         call_args = make_tree_vector ();
12073         for (i = 0; i < nargs; ++i)
12074           {
12075             tree arg = CALL_EXPR_ARG (t, i);
12076
12077             if (!PACK_EXPANSION_P (arg))
12078               VEC_safe_push (tree, gc, call_args,
12079                              RECUR (CALL_EXPR_ARG (t, i)));
12080             else
12081               {
12082                 /* Expand the pack expansion and push each entry onto
12083                    CALL_ARGS.  */
12084                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12085                 if (TREE_CODE (arg) == TREE_VEC)
12086                   {
12087                     unsigned int len, j;
12088
12089                     len = TREE_VEC_LENGTH (arg);
12090                     for (j = 0; j < len; ++j)
12091                       {
12092                         tree value = TREE_VEC_ELT (arg, j);
12093                         if (value != NULL_TREE)
12094                           value = convert_from_reference (value);
12095                         VEC_safe_push (tree, gc, call_args, value);
12096                       }
12097                   }
12098                 else
12099                   {
12100                     /* A partial substitution.  Add one entry.  */
12101                     VEC_safe_push (tree, gc, call_args, arg);
12102                   }
12103               }
12104           }
12105
12106         /* We do not perform argument-dependent lookup if normal
12107            lookup finds a non-function, in accordance with the
12108            expected resolution of DR 218.  */
12109         if (koenig_p
12110             && ((is_overloaded_fn (function)
12111                  /* If lookup found a member function, the Koenig lookup is
12112                     not appropriate, even if an unqualified-name was used
12113                     to denote the function.  */
12114                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12115                 || TREE_CODE (function) == IDENTIFIER_NODE)
12116             /* Only do this when substitution turns a dependent call
12117                into a non-dependent call.  */
12118             && type_dependent_expression_p_push (t)
12119             && !any_type_dependent_arguments_p (call_args))
12120           function = perform_koenig_lookup (function, call_args);
12121
12122         if (TREE_CODE (function) == IDENTIFIER_NODE)
12123           {
12124             unqualified_name_lookup_error (function);
12125             release_tree_vector (call_args);
12126             return error_mark_node;
12127           }
12128
12129         /* Remember that there was a reference to this entity.  */
12130         if (DECL_P (function))
12131           mark_used (function);
12132
12133         if (TREE_CODE (function) == OFFSET_REF)
12134           ret = build_offset_ref_call_from_tree (function, &call_args);
12135         else if (TREE_CODE (function) == COMPONENT_REF)
12136           {
12137             if (!BASELINK_P (TREE_OPERAND (function, 1)))
12138               ret = finish_call_expr (function, &call_args,
12139                                        /*disallow_virtual=*/false,
12140                                        /*koenig_p=*/false,
12141                                        complain);
12142             else
12143               ret = (build_new_method_call
12144                       (TREE_OPERAND (function, 0),
12145                        TREE_OPERAND (function, 1),
12146                        &call_args, NULL_TREE,
12147                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12148                        /*fn_p=*/NULL,
12149                        complain));
12150           }
12151         else
12152           ret = finish_call_expr (function, &call_args,
12153                                   /*disallow_virtual=*/qualified_p,
12154                                   koenig_p,
12155                                   complain);
12156
12157         release_tree_vector (call_args);
12158
12159         return ret;
12160       }
12161
12162     case COND_EXPR:
12163       return build_x_conditional_expr
12164         (RECUR (TREE_OPERAND (t, 0)),
12165          RECUR (TREE_OPERAND (t, 1)),
12166          RECUR (TREE_OPERAND (t, 2)),
12167          complain);
12168
12169     case PSEUDO_DTOR_EXPR:
12170       return finish_pseudo_destructor_expr
12171         (RECUR (TREE_OPERAND (t, 0)),
12172          RECUR (TREE_OPERAND (t, 1)),
12173          RECUR (TREE_OPERAND (t, 2)));
12174
12175     case TREE_LIST:
12176       {
12177         tree purpose, value, chain;
12178
12179         if (t == void_list_node)
12180           return t;
12181
12182         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12183             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12184           {
12185             /* We have pack expansions, so expand those and
12186                create a new list out of it.  */
12187             tree purposevec = NULL_TREE;
12188             tree valuevec = NULL_TREE;
12189             tree chain;
12190             int i, len = -1;
12191
12192             /* Expand the argument expressions.  */
12193             if (TREE_PURPOSE (t))
12194               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12195                                                  complain, in_decl);
12196             if (TREE_VALUE (t))
12197               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12198                                                complain, in_decl);
12199
12200             /* Build the rest of the list.  */
12201             chain = TREE_CHAIN (t);
12202             if (chain && chain != void_type_node)
12203               chain = RECUR (chain);
12204
12205             /* Determine the number of arguments.  */
12206             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12207               {
12208                 len = TREE_VEC_LENGTH (purposevec);
12209                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12210               }
12211             else if (TREE_CODE (valuevec) == TREE_VEC)
12212               len = TREE_VEC_LENGTH (valuevec);
12213             else
12214               {
12215                 /* Since we only performed a partial substitution into
12216                    the argument pack, we only return a single list
12217                    node.  */
12218                 if (purposevec == TREE_PURPOSE (t)
12219                     && valuevec == TREE_VALUE (t)
12220                     && chain == TREE_CHAIN (t))
12221                   return t;
12222
12223                 return tree_cons (purposevec, valuevec, chain);
12224               }
12225             
12226             /* Convert the argument vectors into a TREE_LIST */
12227             i = len;
12228             while (i > 0)
12229               {
12230                 /* Grab the Ith values.  */
12231                 i--;
12232                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12233                                      : NULL_TREE;
12234                 value 
12235                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12236                              : NULL_TREE;
12237
12238                 /* Build the list (backwards).  */
12239                 chain = tree_cons (purpose, value, chain);
12240               }
12241
12242             return chain;
12243           }
12244
12245         purpose = TREE_PURPOSE (t);
12246         if (purpose)
12247           purpose = RECUR (purpose);
12248         value = TREE_VALUE (t);
12249         if (value)
12250           value = RECUR (value);
12251         chain = TREE_CHAIN (t);
12252         if (chain && chain != void_type_node)
12253           chain = RECUR (chain);
12254         if (purpose == TREE_PURPOSE (t)
12255             && value == TREE_VALUE (t)
12256             && chain == TREE_CHAIN (t))
12257           return t;
12258         return tree_cons (purpose, value, chain);
12259       }
12260
12261     case COMPONENT_REF:
12262       {
12263         tree object;
12264         tree object_type;
12265         tree member;
12266
12267         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12268                                                      args, complain, in_decl);
12269         /* Remember that there was a reference to this entity.  */
12270         if (DECL_P (object))
12271           mark_used (object);
12272         object_type = TREE_TYPE (object);
12273
12274         member = TREE_OPERAND (t, 1);
12275         if (BASELINK_P (member))
12276           member = tsubst_baselink (member,
12277                                     non_reference (TREE_TYPE (object)),
12278                                     args, complain, in_decl);
12279         else
12280           member = tsubst_copy (member, args, complain, in_decl);
12281         if (member == error_mark_node)
12282           return error_mark_node;
12283
12284         if (object_type && !CLASS_TYPE_P (object_type))
12285           {
12286             if (SCALAR_TYPE_P (object_type))
12287               {
12288                 tree s = NULL_TREE;
12289                 tree dtor = member;
12290
12291                 if (TREE_CODE (dtor) == SCOPE_REF)
12292                   {
12293                     s = TREE_OPERAND (dtor, 0);
12294                     dtor = TREE_OPERAND (dtor, 1);
12295                   }
12296                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12297                   {
12298                     dtor = TREE_OPERAND (dtor, 0);
12299                     if (TYPE_P (dtor))
12300                       return finish_pseudo_destructor_expr (object, s, dtor);
12301                   }
12302               }
12303           }
12304         else if (TREE_CODE (member) == SCOPE_REF
12305                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12306           {
12307             tree tmpl;
12308             tree args;
12309
12310             /* Lookup the template functions now that we know what the
12311                scope is.  */
12312             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12313             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12314             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12315                                             /*is_type_p=*/false,
12316                                             /*complain=*/false);
12317             if (BASELINK_P (member))
12318               {
12319                 BASELINK_FUNCTIONS (member)
12320                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12321                               args);
12322                 member = (adjust_result_of_qualified_name_lookup
12323                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12324                            object_type));
12325               }
12326             else
12327               {
12328                 qualified_name_lookup_error (object_type, tmpl, member,
12329                                              input_location);
12330                 return error_mark_node;
12331               }
12332           }
12333         else if (TREE_CODE (member) == SCOPE_REF
12334                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12335                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12336           {
12337             if (complain & tf_error)
12338               {
12339                 if (TYPE_P (TREE_OPERAND (member, 0)))
12340                   error ("%qT is not a class or namespace",
12341                          TREE_OPERAND (member, 0));
12342                 else
12343                   error ("%qD is not a class or namespace",
12344                          TREE_OPERAND (member, 0));
12345               }
12346             return error_mark_node;
12347           }
12348         else if (TREE_CODE (member) == FIELD_DECL)
12349           return finish_non_static_data_member (member, object, NULL_TREE);
12350
12351         return finish_class_member_access_expr (object, member,
12352                                                 /*template_p=*/false,
12353                                                 complain);
12354       }
12355
12356     case THROW_EXPR:
12357       return build_throw
12358         (RECUR (TREE_OPERAND (t, 0)));
12359
12360     case CONSTRUCTOR:
12361       {
12362         VEC(constructor_elt,gc) *n;
12363         constructor_elt *ce;
12364         unsigned HOST_WIDE_INT idx;
12365         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12366         bool process_index_p;
12367         int newlen;
12368         bool need_copy_p = false;
12369         tree r;
12370
12371         if (type == error_mark_node)
12372           return error_mark_node;
12373
12374         /* digest_init will do the wrong thing if we let it.  */
12375         if (type && TYPE_PTRMEMFUNC_P (type))
12376           return t;
12377
12378         /* We do not want to process the index of aggregate
12379            initializers as they are identifier nodes which will be
12380            looked up by digest_init.  */
12381         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12382
12383         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12384         newlen = VEC_length (constructor_elt, n);
12385         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12386           {
12387             if (ce->index && process_index_p)
12388               ce->index = RECUR (ce->index);
12389
12390             if (PACK_EXPANSION_P (ce->value))
12391               {
12392                 /* Substitute into the pack expansion.  */
12393                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12394                                                   in_decl);
12395
12396                 if (ce->value == error_mark_node)
12397                   ;
12398                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12399                   /* Just move the argument into place.  */
12400                   ce->value = TREE_VEC_ELT (ce->value, 0);
12401                 else
12402                   {
12403                     /* Update the length of the final CONSTRUCTOR
12404                        arguments vector, and note that we will need to
12405                        copy.*/
12406                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12407                     need_copy_p = true;
12408                   }
12409               }
12410             else
12411               ce->value = RECUR (ce->value);
12412           }
12413
12414         if (need_copy_p)
12415           {
12416             VEC(constructor_elt,gc) *old_n = n;
12417
12418             n = VEC_alloc (constructor_elt, gc, newlen);
12419             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
12420                  idx++)
12421               {
12422                 if (TREE_CODE (ce->value) == TREE_VEC)
12423                   {
12424                     int i, len = TREE_VEC_LENGTH (ce->value);
12425                     for (i = 0; i < len; ++i)
12426                       CONSTRUCTOR_APPEND_ELT (n, 0,
12427                                               TREE_VEC_ELT (ce->value, i));
12428                   }
12429                 else
12430                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12431               }
12432           }
12433
12434         r = build_constructor (init_list_type_node, n);
12435         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12436
12437         if (TREE_HAS_CONSTRUCTOR (t))
12438           return finish_compound_literal (type, r);
12439
12440         return r;
12441       }
12442
12443     case TYPEID_EXPR:
12444       {
12445         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12446         if (TYPE_P (operand_0))
12447           return get_typeid (operand_0);
12448         return build_typeid (operand_0);
12449       }
12450
12451     case VAR_DECL:
12452       if (!args)
12453         return t;
12454       /* Fall through */
12455
12456     case PARM_DECL:
12457       {
12458         tree r = tsubst_copy (t, args, complain, in_decl);
12459
12460         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12461           /* If the original type was a reference, we'll be wrapped in
12462              the appropriate INDIRECT_REF.  */
12463           r = convert_from_reference (r);
12464         return r;
12465       }
12466
12467     case VA_ARG_EXPR:
12468       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12469                              tsubst_copy (TREE_TYPE (t), args, complain,
12470                                           in_decl));
12471
12472     case OFFSETOF_EXPR:
12473       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12474
12475     case TRAIT_EXPR:
12476       {
12477         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12478                                   complain, in_decl);
12479
12480         tree type2 = TRAIT_EXPR_TYPE2 (t);
12481         if (type2)
12482           type2 = tsubst_copy (type2, args, complain, in_decl);
12483         
12484         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12485       }
12486
12487     case STMT_EXPR:
12488       {
12489         tree old_stmt_expr = cur_stmt_expr;
12490         tree stmt_expr = begin_stmt_expr ();
12491
12492         cur_stmt_expr = stmt_expr;
12493         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12494                      integral_constant_expression_p);
12495         stmt_expr = finish_stmt_expr (stmt_expr, false);
12496         cur_stmt_expr = old_stmt_expr;
12497
12498         return stmt_expr;
12499       }
12500
12501     case CONST_DECL:
12502       t = tsubst_copy (t, args, complain, in_decl);
12503       /* As in finish_id_expression, we resolve enumeration constants
12504          to their underlying values.  */
12505       if (TREE_CODE (t) == CONST_DECL)
12506         {
12507           used_types_insert (TREE_TYPE (t));
12508           return DECL_INITIAL (t);
12509         }
12510       return t;
12511
12512     case LAMBDA_EXPR:
12513       {
12514         tree r = build_lambda_expr ();
12515
12516         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12517         TREE_TYPE (r) = type;
12518         CLASSTYPE_LAMBDA_EXPR (type) = r;
12519
12520         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12521           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12522         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12523         LAMBDA_EXPR_DISCRIMINATOR (r)
12524           = (LAMBDA_EXPR_DISCRIMINATOR (t));
12525         LAMBDA_EXPR_CAPTURE_LIST (r)
12526           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12527         LAMBDA_EXPR_THIS_CAPTURE (r)
12528           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12529         LAMBDA_EXPR_EXTRA_SCOPE (r)
12530           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12531
12532         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12533         determine_visibility (TYPE_NAME (type));
12534         /* Now that we know visibility, instantiate the type so we have a
12535            declaration of the op() for later calls to lambda_function.  */
12536         complete_type (type);
12537
12538         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12539         if (type)
12540           apply_lambda_return_type (r, type);
12541
12542         return build_lambda_object (r);
12543       }
12544
12545     default:
12546       /* Handle Objective-C++ constructs, if appropriate.  */
12547       {
12548         tree subst
12549           = objcp_tsubst_copy_and_build (t, args, complain,
12550                                          in_decl, /*function_p=*/false);
12551         if (subst)
12552           return subst;
12553       }
12554       return tsubst_copy (t, args, complain, in_decl);
12555     }
12556
12557 #undef RECUR
12558 }
12559
12560 /* Verify that the instantiated ARGS are valid. For type arguments,
12561    make sure that the type's linkage is ok. For non-type arguments,
12562    make sure they are constants if they are integral or enumerations.
12563    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12564
12565 static bool
12566 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12567 {
12568   if (ARGUMENT_PACK_P (t))
12569     {
12570       tree vec = ARGUMENT_PACK_ARGS (t);
12571       int len = TREE_VEC_LENGTH (vec);
12572       bool result = false;
12573       int i;
12574
12575       for (i = 0; i < len; ++i)
12576         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12577           result = true;
12578       return result;
12579     }
12580   else if (TYPE_P (t))
12581     {
12582       /* [basic.link]: A name with no linkage (notably, the name
12583          of a class or enumeration declared in a local scope)
12584          shall not be used to declare an entity with linkage.
12585          This implies that names with no linkage cannot be used as
12586          template arguments
12587
12588          DR 757 relaxes this restriction for C++0x.  */
12589       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
12590                  : no_linkage_check (t, /*relaxed_p=*/false));
12591
12592       if (nt)
12593         {
12594           /* DR 488 makes use of a type with no linkage cause
12595              type deduction to fail.  */
12596           if (complain & tf_error)
12597             {
12598               if (TYPE_ANONYMOUS_P (nt))
12599                 error ("%qT is/uses anonymous type", t);
12600               else
12601                 error ("template argument for %qD uses local type %qT",
12602                        tmpl, t);
12603             }
12604           return true;
12605         }
12606       /* In order to avoid all sorts of complications, we do not
12607          allow variably-modified types as template arguments.  */
12608       else if (variably_modified_type_p (t, NULL_TREE))
12609         {
12610           if (complain & tf_error)
12611             error ("%qT is a variably modified type", t);
12612           return true;
12613         }
12614     }
12615   /* A non-type argument of integral or enumerated type must be a
12616      constant.  */
12617   else if (TREE_TYPE (t)
12618            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12619            && !TREE_CONSTANT (t))
12620     {
12621       if (complain & tf_error)
12622         error ("integral expression %qE is not constant", t);
12623       return true;
12624     }
12625   return false;
12626 }
12627
12628 static bool
12629 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12630 {
12631   int ix, len = DECL_NTPARMS (tmpl);
12632   bool result = false;
12633
12634   for (ix = 0; ix != len; ix++)
12635     {
12636       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12637         result = true;
12638     }
12639   if (result && (complain & tf_error))
12640     error ("  trying to instantiate %qD", tmpl);
12641   return result;
12642 }
12643
12644 /* Instantiate the indicated variable or function template TMPL with
12645    the template arguments in TARG_PTR.  */
12646
12647 tree
12648 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
12649 {
12650   tree targ_ptr = orig_args;
12651   tree fndecl;
12652   tree gen_tmpl;
12653   tree spec;
12654   HOST_WIDE_INT saved_processing_template_decl;
12655
12656   if (tmpl == error_mark_node)
12657     return error_mark_node;
12658
12659   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12660
12661   /* If this function is a clone, handle it specially.  */
12662   if (DECL_CLONED_FUNCTION_P (tmpl))
12663     {
12664       tree spec;
12665       tree clone;
12666
12667       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
12668          DECL_CLONED_FUNCTION.  */
12669       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
12670                                    targ_ptr, complain);
12671       if (spec == error_mark_node)
12672         return error_mark_node;
12673
12674       /* Look for the clone.  */
12675       FOR_EACH_CLONE (clone, spec)
12676         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12677           return clone;
12678       /* We should always have found the clone by now.  */
12679       gcc_unreachable ();
12680       return NULL_TREE;
12681     }
12682
12683   /* Check to see if we already have this specialization.  */
12684   gen_tmpl = most_general_template (tmpl);
12685   if (tmpl != gen_tmpl)
12686     /* The TMPL is a partial instantiation.  To get a full set of
12687        arguments we must add the arguments used to perform the
12688        partial instantiation.  */
12689     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12690                                             targ_ptr);
12691
12692   /* It would be nice to avoid hashing here and then again in tsubst_decl,
12693      but it doesn't seem to be on the hot path.  */
12694   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
12695
12696   gcc_assert (tmpl == gen_tmpl
12697               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
12698                   == spec)
12699               || fndecl == NULL_TREE);
12700
12701   if (spec != NULL_TREE)
12702     return spec;
12703
12704   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12705                                complain))
12706     return error_mark_node;
12707
12708   /* We are building a FUNCTION_DECL, during which the access of its
12709      parameters and return types have to be checked.  However this
12710      FUNCTION_DECL which is the desired context for access checking
12711      is not built yet.  We solve this chicken-and-egg problem by
12712      deferring all checks until we have the FUNCTION_DECL.  */
12713   push_deferring_access_checks (dk_deferred);
12714
12715   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12716      (because, for example, we have encountered a non-dependent
12717      function call in the body of a template function and must now
12718      determine which of several overloaded functions will be called),
12719      within the instantiation itself we are not processing a
12720      template.  */  
12721   saved_processing_template_decl = processing_template_decl;
12722   processing_template_decl = 0;
12723   /* Substitute template parameters to obtain the specialization.  */
12724   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12725                    targ_ptr, complain, gen_tmpl);
12726   processing_template_decl = saved_processing_template_decl;
12727   if (fndecl == error_mark_node)
12728     return error_mark_node;
12729
12730   /* Now we know the specialization, compute access previously
12731      deferred.  */
12732   push_access_scope (fndecl);
12733
12734   /* Some typedefs referenced from within the template code need to be access
12735      checked at template instantiation time, i.e now. These types were
12736      added to the template at parsing time. Let's get those and perfom
12737      the acces checks then.  */
12738   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
12739   perform_deferred_access_checks ();
12740   pop_access_scope (fndecl);
12741   pop_deferring_access_checks ();
12742
12743   /* The DECL_TI_TEMPLATE should always be the immediate parent
12744      template, not the most general template.  */
12745   DECL_TI_TEMPLATE (fndecl) = tmpl;
12746
12747   /* If we've just instantiated the main entry point for a function,
12748      instantiate all the alternate entry points as well.  We do this
12749      by cloning the instantiation of the main entry point, not by
12750      instantiating the template clones.  */
12751   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
12752     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
12753
12754   return fndecl;
12755 }
12756
12757 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
12758    NARGS elements of the arguments that are being used when calling
12759    it.  TARGS is a vector into which the deduced template arguments
12760    are placed.
12761
12762    Return zero for success, 2 for an incomplete match that doesn't resolve
12763    all the types, and 1 for complete failure.  An error message will be
12764    printed only for an incomplete match.
12765
12766    If FN is a conversion operator, or we are trying to produce a specific
12767    specialization, RETURN_TYPE is the return type desired.
12768
12769    The EXPLICIT_TARGS are explicit template arguments provided via a
12770    template-id.
12771
12772    The parameter STRICT is one of:
12773
12774    DEDUCE_CALL:
12775      We are deducing arguments for a function call, as in
12776      [temp.deduct.call].
12777
12778    DEDUCE_CONV:
12779      We are deducing arguments for a conversion function, as in
12780      [temp.deduct.conv].
12781
12782    DEDUCE_EXACT:
12783      We are deducing arguments when doing an explicit instantiation
12784      as in [temp.explicit], when determining an explicit specialization
12785      as in [temp.expl.spec], or when taking the address of a function
12786      template, as in [temp.deduct.funcaddr].  */
12787
12788 int
12789 fn_type_unification (tree fn,
12790                      tree explicit_targs,
12791                      tree targs,
12792                      const tree *args,
12793                      unsigned int nargs,
12794                      tree return_type,
12795                      unification_kind_t strict,
12796                      int flags)
12797 {
12798   tree parms;
12799   tree fntype;
12800   int result;
12801   bool incomplete_argument_packs_p = false;
12802
12803   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12804
12805   fntype = TREE_TYPE (fn);
12806   if (explicit_targs)
12807     {
12808       /* [temp.deduct]
12809
12810          The specified template arguments must match the template
12811          parameters in kind (i.e., type, nontype, template), and there
12812          must not be more arguments than there are parameters;
12813          otherwise type deduction fails.
12814
12815          Nontype arguments must match the types of the corresponding
12816          nontype template parameters, or must be convertible to the
12817          types of the corresponding nontype parameters as specified in
12818          _temp.arg.nontype_, otherwise type deduction fails.
12819
12820          All references in the function type of the function template
12821          to the corresponding template parameters are replaced by the
12822          specified template argument values.  If a substitution in a
12823          template parameter or in the function type of the function
12824          template results in an invalid type, type deduction fails.  */
12825       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12826       int i, len = TREE_VEC_LENGTH (tparms);
12827       tree converted_args;
12828       bool incomplete = false;
12829
12830       if (explicit_targs == error_mark_node)
12831         return 1;
12832
12833       converted_args
12834         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12835                                   /*require_all_args=*/false,
12836                                   /*use_default_args=*/false));
12837       if (converted_args == error_mark_node)
12838         return 1;
12839
12840       /* Substitute the explicit args into the function type.  This is
12841          necessary so that, for instance, explicitly declared function
12842          arguments can match null pointed constants.  If we were given
12843          an incomplete set of explicit args, we must not do semantic
12844          processing during substitution as we could create partial
12845          instantiations.  */
12846       for (i = 0; i < len; i++)
12847         {
12848           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12849           bool parameter_pack = false;
12850
12851           /* Dig out the actual parm.  */
12852           if (TREE_CODE (parm) == TYPE_DECL
12853               || TREE_CODE (parm) == TEMPLATE_DECL)
12854             {
12855               parm = TREE_TYPE (parm);
12856               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12857             }
12858           else if (TREE_CODE (parm) == PARM_DECL)
12859             {
12860               parm = DECL_INITIAL (parm);
12861               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12862             }
12863
12864           if (parameter_pack)
12865             {
12866               int level, idx;
12867               tree targ;
12868               template_parm_level_and_index (parm, &level, &idx);
12869
12870               /* Mark the argument pack as "incomplete". We could
12871                  still deduce more arguments during unification.  */
12872               targ = TMPL_ARG (converted_args, level, idx);
12873               if (targ)
12874                 {
12875                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12876                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12877                     = ARGUMENT_PACK_ARGS (targ);
12878                 }
12879
12880               /* We have some incomplete argument packs.  */
12881               incomplete_argument_packs_p = true;
12882             }
12883         }
12884
12885       if (incomplete_argument_packs_p)
12886         /* Any substitution is guaranteed to be incomplete if there
12887            are incomplete argument packs, because we can still deduce
12888            more arguments.  */
12889         incomplete = 1;
12890       else
12891         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12892
12893       processing_template_decl += incomplete;
12894       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12895       processing_template_decl -= incomplete;
12896
12897       if (fntype == error_mark_node)
12898         return 1;
12899
12900       /* Place the explicitly specified arguments in TARGS.  */
12901       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12902         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12903     }
12904
12905   /* Never do unification on the 'this' parameter.  */
12906   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12907
12908   if (return_type)
12909     {
12910       tree *new_args;
12911
12912       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12913       new_args = XALLOCAVEC (tree, nargs + 1);
12914       new_args[0] = return_type;
12915       memcpy (new_args + 1, args, nargs * sizeof (tree));
12916       args = new_args;
12917       ++nargs;
12918     }
12919
12920   /* We allow incomplete unification without an error message here
12921      because the standard doesn't seem to explicitly prohibit it.  Our
12922      callers must be ready to deal with unification failures in any
12923      event.  */
12924   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12925                                   targs, parms, args, nargs, /*subr=*/0,
12926                                   strict, flags);
12927
12928   if (result == 0 && incomplete_argument_packs_p)
12929     {
12930       int i, len = NUM_TMPL_ARGS (targs);
12931
12932       /* Clear the "incomplete" flags on all argument packs.  */
12933       for (i = 0; i < len; i++)
12934         {
12935           tree arg = TREE_VEC_ELT (targs, i);
12936           if (ARGUMENT_PACK_P (arg))
12937             {
12938               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12939               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12940             }
12941         }
12942     }
12943
12944   /* Now that we have bindings for all of the template arguments,
12945      ensure that the arguments deduced for the template template
12946      parameters have compatible template parameter lists.  We cannot
12947      check this property before we have deduced all template
12948      arguments, because the template parameter types of a template
12949      template parameter might depend on prior template parameters
12950      deduced after the template template parameter.  The following
12951      ill-formed example illustrates this issue:
12952
12953        template<typename T, template<T> class C> void f(C<5>, T);
12954
12955        template<int N> struct X {};
12956
12957        void g() {
12958          f(X<5>(), 5l); // error: template argument deduction fails
12959        }
12960
12961      The template parameter list of 'C' depends on the template type
12962      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
12963      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
12964      time that we deduce 'C'.  */
12965   if (result == 0
12966       && !template_template_parm_bindings_ok_p 
12967            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
12968     return 1;
12969
12970   if (result == 0)
12971     /* All is well so far.  Now, check:
12972
12973        [temp.deduct]
12974
12975        When all template arguments have been deduced, all uses of
12976        template parameters in nondeduced contexts are replaced with
12977        the corresponding deduced argument values.  If the
12978        substitution results in an invalid type, as described above,
12979        type deduction fails.  */
12980     {
12981       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
12982       if (substed == error_mark_node)
12983         return 1;
12984
12985       /* If we're looking for an exact match, check that what we got
12986          is indeed an exact match.  It might not be if some template
12987          parameters are used in non-deduced contexts.  */
12988       if (strict == DEDUCE_EXACT)
12989         {
12990           unsigned int i;
12991
12992           tree sarg
12993             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
12994           if (return_type)
12995             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
12996           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
12997             if (!same_type_p (args[i], TREE_VALUE (sarg)))
12998               return 1;
12999         }
13000     }
13001
13002   return result;
13003 }
13004
13005 /* Adjust types before performing type deduction, as described in
13006    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13007    sections are symmetric.  PARM is the type of a function parameter
13008    or the return type of the conversion function.  ARG is the type of
13009    the argument passed to the call, or the type of the value
13010    initialized with the result of the conversion function.
13011    ARG_EXPR is the original argument expression, which may be null.  */
13012
13013 static int
13014 maybe_adjust_types_for_deduction (unification_kind_t strict,
13015                                   tree* parm,
13016                                   tree* arg,
13017                                   tree arg_expr)
13018 {
13019   int result = 0;
13020
13021   switch (strict)
13022     {
13023     case DEDUCE_CALL:
13024       break;
13025
13026     case DEDUCE_CONV:
13027       {
13028         /* Swap PARM and ARG throughout the remainder of this
13029            function; the handling is precisely symmetric since PARM
13030            will initialize ARG rather than vice versa.  */
13031         tree* temp = parm;
13032         parm = arg;
13033         arg = temp;
13034         break;
13035       }
13036
13037     case DEDUCE_EXACT:
13038       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13039          too, but here handle it by stripping the reference from PARM
13040          rather than by adding it to ARG.  */
13041       if (TREE_CODE (*parm) == REFERENCE_TYPE
13042           && TYPE_REF_IS_RVALUE (*parm)
13043           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13044           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13045           && TREE_CODE (*arg) == REFERENCE_TYPE
13046           && !TYPE_REF_IS_RVALUE (*arg))
13047         *parm = TREE_TYPE (*parm);
13048       /* Nothing else to do in this case.  */
13049       return 0;
13050
13051     default:
13052       gcc_unreachable ();
13053     }
13054
13055   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13056     {
13057       /* [temp.deduct.call]
13058
13059          If P is not a reference type:
13060
13061          --If A is an array type, the pointer type produced by the
13062          array-to-pointer standard conversion (_conv.array_) is
13063          used in place of A for type deduction; otherwise,
13064
13065          --If A is a function type, the pointer type produced by
13066          the function-to-pointer standard conversion
13067          (_conv.func_) is used in place of A for type deduction;
13068          otherwise,
13069
13070          --If A is a cv-qualified type, the top level
13071          cv-qualifiers of A's type are ignored for type
13072          deduction.  */
13073       if (TREE_CODE (*arg) == ARRAY_TYPE)
13074         *arg = build_pointer_type (TREE_TYPE (*arg));
13075       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13076         *arg = build_pointer_type (*arg);
13077       else
13078         *arg = TYPE_MAIN_VARIANT (*arg);
13079     }
13080
13081   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13082      of the form T&&, where T is a template parameter, and the argument
13083      is an lvalue, T is deduced as A& */
13084   if (TREE_CODE (*parm) == REFERENCE_TYPE
13085       && TYPE_REF_IS_RVALUE (*parm)
13086       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13087       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13088       && arg_expr && real_lvalue_p (arg_expr))
13089     *arg = build_reference_type (*arg);
13090
13091   /* [temp.deduct.call]
13092
13093      If P is a cv-qualified type, the top level cv-qualifiers
13094      of P's type are ignored for type deduction.  If P is a
13095      reference type, the type referred to by P is used for
13096      type deduction.  */
13097   *parm = TYPE_MAIN_VARIANT (*parm);
13098   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13099     {
13100       *parm = TREE_TYPE (*parm);
13101       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13102     }
13103
13104   /* DR 322. For conversion deduction, remove a reference type on parm
13105      too (which has been swapped into ARG).  */
13106   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13107     *arg = TREE_TYPE (*arg);
13108
13109   return result;
13110 }
13111
13112 /* Most parms like fn_type_unification.
13113
13114    If SUBR is 1, we're being called recursively (to unify the
13115    arguments of a function or method parameter of a function
13116    template). */
13117
13118 static int
13119 type_unification_real (tree tparms,
13120                        tree targs,
13121                        tree xparms,
13122                        const tree *xargs,
13123                        unsigned int xnargs,
13124                        int subr,
13125                        unification_kind_t strict,
13126                        int flags)
13127 {
13128   tree parm, arg, arg_expr;
13129   int i;
13130   int ntparms = TREE_VEC_LENGTH (tparms);
13131   int sub_strict;
13132   int saw_undeduced = 0;
13133   tree parms;
13134   const tree *args;
13135   unsigned int nargs;
13136   unsigned int ia;
13137
13138   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13139   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13140   gcc_assert (ntparms > 0);
13141
13142   switch (strict)
13143     {
13144     case DEDUCE_CALL:
13145       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13146                     | UNIFY_ALLOW_DERIVED);
13147       break;
13148
13149     case DEDUCE_CONV:
13150       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13151       break;
13152
13153     case DEDUCE_EXACT:
13154       sub_strict = UNIFY_ALLOW_NONE;
13155       break;
13156
13157     default:
13158       gcc_unreachable ();
13159     }
13160
13161  again:
13162   parms = xparms;
13163   args = xargs;
13164   nargs = xnargs;
13165
13166   ia = 0;
13167   while (parms && parms != void_list_node
13168          && ia < nargs)
13169     {
13170       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13171         break;
13172
13173       parm = TREE_VALUE (parms);
13174       parms = TREE_CHAIN (parms);
13175       arg = args[ia];
13176       ++ia;
13177       arg_expr = NULL;
13178
13179       if (arg == error_mark_node)
13180         return 1;
13181       if (arg == unknown_type_node)
13182         /* We can't deduce anything from this, but we might get all the
13183            template args from other function args.  */
13184         continue;
13185
13186       /* Conversions will be performed on a function argument that
13187          corresponds with a function parameter that contains only
13188          non-deducible template parameters and explicitly specified
13189          template parameters.  */
13190       if (!uses_template_parms (parm))
13191         {
13192           tree type;
13193
13194           if (!TYPE_P (arg))
13195             type = TREE_TYPE (arg);
13196           else
13197             type = arg;
13198
13199           if (same_type_p (parm, type))
13200             continue;
13201           if (strict != DEDUCE_EXACT
13202               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13203                                   flags))
13204             continue;
13205
13206           return 1;
13207         }
13208
13209       if (!TYPE_P (arg))
13210         {
13211           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13212           if (type_unknown_p (arg))
13213             {
13214               /* [temp.deduct.type] 
13215
13216                  A template-argument can be deduced from a pointer to
13217                  function or pointer to member function argument if
13218                  the set of overloaded functions does not contain
13219                  function templates and at most one of a set of
13220                  overloaded functions provides a unique match.  */
13221               if (resolve_overloaded_unification
13222                   (tparms, targs, parm, arg, strict, sub_strict))
13223                 continue;
13224
13225               return 1;
13226             }
13227           arg_expr = arg;
13228           arg = unlowered_expr_type (arg);
13229           if (arg == error_mark_node)
13230             return 1;
13231         }
13232
13233       {
13234         int arg_strict = sub_strict;
13235
13236         if (!subr)
13237           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13238                                                           arg_expr);
13239
13240         if (arg == init_list_type_node && arg_expr)
13241           arg = arg_expr;
13242         if (unify (tparms, targs, parm, arg, arg_strict))
13243           return 1;
13244       }
13245     }
13246
13247
13248   if (parms 
13249       && parms != void_list_node
13250       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13251     {
13252       /* Unify the remaining arguments with the pack expansion type.  */
13253       tree argvec;
13254       tree parmvec = make_tree_vec (1);
13255
13256       /* Allocate a TREE_VEC and copy in all of the arguments */ 
13257       argvec = make_tree_vec (nargs - ia);
13258       for (i = 0; ia < nargs; ++ia, ++i)
13259         TREE_VEC_ELT (argvec, i) = args[ia];
13260
13261       /* Copy the parameter into parmvec.  */
13262       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13263       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13264                                 /*call_args_p=*/true, /*subr=*/subr))
13265         return 1;
13266
13267       /* Advance to the end of the list of parameters.  */
13268       parms = TREE_CHAIN (parms);
13269     }
13270
13271   /* Fail if we've reached the end of the parm list, and more args
13272      are present, and the parm list isn't variadic.  */
13273   if (ia < nargs && parms == void_list_node)
13274     return 1;
13275   /* Fail if parms are left and they don't have default values.  */
13276   if (parms && parms != void_list_node
13277       && TREE_PURPOSE (parms) == NULL_TREE)
13278     return 1;
13279
13280   if (!subr)
13281     for (i = 0; i < ntparms; i++)
13282       if (!TREE_VEC_ELT (targs, i))
13283         {
13284           tree tparm;
13285
13286           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13287             continue;
13288
13289           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13290
13291           /* If this is an undeduced nontype parameter that depends on
13292              a type parameter, try another pass; its type may have been
13293              deduced from a later argument than the one from which
13294              this parameter can be deduced.  */
13295           if (TREE_CODE (tparm) == PARM_DECL
13296               && uses_template_parms (TREE_TYPE (tparm))
13297               && !saw_undeduced++)
13298             goto again;
13299
13300           /* Core issue #226 (C++0x) [temp.deduct]:
13301
13302                If a template argument has not been deduced, its
13303                default template argument, if any, is used. 
13304
13305              When we are in C++98 mode, TREE_PURPOSE will either
13306              be NULL_TREE or ERROR_MARK_NODE, so we do not need
13307              to explicitly check cxx_dialect here.  */
13308           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13309             {
13310               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13311               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13312               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13313               arg = convert_template_argument (parm, arg, targs, tf_none,
13314                                                i, NULL_TREE);
13315               if (arg == error_mark_node)
13316                 return 1;
13317               else
13318                 {
13319                   TREE_VEC_ELT (targs, i) = arg;
13320                   continue;
13321                 }
13322             }
13323
13324           /* If the type parameter is a parameter pack, then it will
13325              be deduced to an empty parameter pack.  */
13326           if (template_parameter_pack_p (tparm))
13327             {
13328               tree arg;
13329
13330               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13331                 {
13332                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13333                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13334                   TREE_CONSTANT (arg) = 1;
13335                 }
13336               else
13337                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13338
13339               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13340
13341               TREE_VEC_ELT (targs, i) = arg;
13342               continue;
13343             }
13344
13345           return 2;
13346         }
13347
13348   return 0;
13349 }
13350
13351 /* Subroutine of type_unification_real.  Args are like the variables
13352    at the call site.  ARG is an overloaded function (or template-id);
13353    we try deducing template args from each of the overloads, and if
13354    only one succeeds, we go with that.  Modifies TARGS and returns
13355    true on success.  */
13356
13357 static bool
13358 resolve_overloaded_unification (tree tparms,
13359                                 tree targs,
13360                                 tree parm,
13361                                 tree arg,
13362                                 unification_kind_t strict,
13363                                 int sub_strict)
13364 {
13365   tree tempargs = copy_node (targs);
13366   int good = 0;
13367   tree goodfn = NULL_TREE;
13368   bool addr_p;
13369
13370   if (TREE_CODE (arg) == ADDR_EXPR)
13371     {
13372       arg = TREE_OPERAND (arg, 0);
13373       addr_p = true;
13374     }
13375   else
13376     addr_p = false;
13377
13378   if (TREE_CODE (arg) == COMPONENT_REF)
13379     /* Handle `&x' where `x' is some static or non-static member
13380        function name.  */
13381     arg = TREE_OPERAND (arg, 1);
13382
13383   if (TREE_CODE (arg) == OFFSET_REF)
13384     arg = TREE_OPERAND (arg, 1);
13385
13386   /* Strip baselink information.  */
13387   if (BASELINK_P (arg))
13388     arg = BASELINK_FUNCTIONS (arg);
13389
13390   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13391     {
13392       /* If we got some explicit template args, we need to plug them into
13393          the affected templates before we try to unify, in case the
13394          explicit args will completely resolve the templates in question.  */
13395
13396       tree expl_subargs = TREE_OPERAND (arg, 1);
13397       arg = TREE_OPERAND (arg, 0);
13398
13399       for (; arg; arg = OVL_NEXT (arg))
13400         {
13401           tree fn = OVL_CURRENT (arg);
13402           tree subargs, elem;
13403
13404           if (TREE_CODE (fn) != TEMPLATE_DECL)
13405             continue;
13406
13407           ++processing_template_decl;
13408           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13409                                   expl_subargs, /*check_ret=*/false);
13410           if (subargs)
13411             {
13412               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13413               if (try_one_overload (tparms, targs, tempargs, parm,
13414                                     elem, strict, sub_strict, addr_p)
13415                   && (!goodfn || !decls_match (goodfn, elem)))
13416                 {
13417                   goodfn = elem;
13418                   ++good;
13419                 }
13420             }
13421           --processing_template_decl;
13422         }
13423     }
13424   else if (TREE_CODE (arg) != OVERLOAD
13425            && TREE_CODE (arg) != FUNCTION_DECL)
13426     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13427        -- but the deduction does not succeed because the expression is
13428        not just the function on its own.  */
13429     return false;
13430   else
13431     for (; arg; arg = OVL_NEXT (arg))
13432       if (try_one_overload (tparms, targs, tempargs, parm,
13433                             TREE_TYPE (OVL_CURRENT (arg)),
13434                             strict, sub_strict, addr_p)
13435           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13436         {
13437           goodfn = OVL_CURRENT (arg);
13438           ++good;
13439         }
13440
13441   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13442      to function or pointer to member function argument if the set of
13443      overloaded functions does not contain function templates and at most
13444      one of a set of overloaded functions provides a unique match.
13445
13446      So if we found multiple possibilities, we return success but don't
13447      deduce anything.  */
13448
13449   if (good == 1)
13450     {
13451       int i = TREE_VEC_LENGTH (targs);
13452       for (; i--; )
13453         if (TREE_VEC_ELT (tempargs, i))
13454           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13455     }
13456   if (good)
13457     return true;
13458
13459   return false;
13460 }
13461
13462 /* Core DR 115: In contexts where deduction is done and fails, or in
13463    contexts where deduction is not done, if a template argument list is
13464    specified and it, along with any default template arguments, identifies
13465    a single function template specialization, then the template-id is an
13466    lvalue for the function template specialization.  */
13467
13468 tree
13469 resolve_nondeduced_context (tree orig_expr)
13470 {
13471   tree expr, offset, baselink;
13472   bool addr;
13473
13474   if (!type_unknown_p (orig_expr))
13475     return orig_expr;
13476
13477   expr = orig_expr;
13478   addr = false;
13479   offset = NULL_TREE;
13480   baselink = NULL_TREE;
13481
13482   if (TREE_CODE (expr) == ADDR_EXPR)
13483     {
13484       expr = TREE_OPERAND (expr, 0);
13485       addr = true;
13486     }
13487   if (TREE_CODE (expr) == OFFSET_REF)
13488     {
13489       offset = expr;
13490       expr = TREE_OPERAND (expr, 1);
13491     }
13492   if (TREE_CODE (expr) == BASELINK)
13493     {
13494       baselink = expr;
13495       expr = BASELINK_FUNCTIONS (expr);
13496     }
13497
13498   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13499     {
13500       int good = 0;
13501       tree goodfn = NULL_TREE;
13502
13503       /* If we got some explicit template args, we need to plug them into
13504          the affected templates before we try to unify, in case the
13505          explicit args will completely resolve the templates in question.  */
13506
13507       tree expl_subargs = TREE_OPERAND (expr, 1);
13508       tree arg = TREE_OPERAND (expr, 0);
13509       tree badfn = NULL_TREE;
13510       tree badargs = NULL_TREE;
13511
13512       for (; arg; arg = OVL_NEXT (arg))
13513         {
13514           tree fn = OVL_CURRENT (arg);
13515           tree subargs, elem;
13516
13517           if (TREE_CODE (fn) != TEMPLATE_DECL)
13518             continue;
13519
13520           ++processing_template_decl;
13521           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13522                                   expl_subargs, /*check_ret=*/false);
13523           if (subargs && !any_dependent_template_arguments_p (subargs))
13524             {
13525               elem = instantiate_template (fn, subargs, tf_none);
13526               if (elem == error_mark_node)
13527                 {
13528                   badfn = fn;
13529                   badargs = subargs;
13530                 }
13531               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13532                 {
13533                   goodfn = elem;
13534                   ++good;
13535                 }
13536             }
13537           --processing_template_decl;
13538         }
13539       if (good == 1)
13540         {
13541           expr = goodfn;
13542           if (baselink)
13543             expr = build_baselink (BASELINK_BINFO (baselink),
13544                                    BASELINK_ACCESS_BINFO (baselink),
13545                                    expr, BASELINK_OPTYPE (baselink));
13546           if (offset)
13547             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13548                            TREE_OPERAND (offset, 0), expr);
13549           if (addr)
13550             expr = build_address (expr);
13551           return expr;
13552         }
13553       else if (good == 0 && badargs)
13554         /* There were no good options and at least one bad one, so let the
13555            user know what the problem is.  */
13556         instantiate_template (badfn, badargs, tf_warning_or_error);
13557     }
13558   return orig_expr;
13559 }
13560
13561 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13562    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13563    different overloads deduce different arguments for a given parm.
13564    ADDR_P is true if the expression for which deduction is being
13565    performed was of the form "& fn" rather than simply "fn".
13566
13567    Returns 1 on success.  */
13568
13569 static int
13570 try_one_overload (tree tparms,
13571                   tree orig_targs,
13572                   tree targs,
13573                   tree parm,
13574                   tree arg,
13575                   unification_kind_t strict,
13576                   int sub_strict,
13577                   bool addr_p)
13578 {
13579   int nargs;
13580   tree tempargs;
13581   int i;
13582
13583   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13584      to function or pointer to member function argument if the set of
13585      overloaded functions does not contain function templates and at most
13586      one of a set of overloaded functions provides a unique match.
13587
13588      So if this is a template, just return success.  */
13589
13590   if (uses_template_parms (arg))
13591     return 1;
13592
13593   if (TREE_CODE (arg) == METHOD_TYPE)
13594     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13595   else if (addr_p)
13596     arg = build_pointer_type (arg);
13597
13598   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13599
13600   /* We don't copy orig_targs for this because if we have already deduced
13601      some template args from previous args, unify would complain when we
13602      try to deduce a template parameter for the same argument, even though
13603      there isn't really a conflict.  */
13604   nargs = TREE_VEC_LENGTH (targs);
13605   tempargs = make_tree_vec (nargs);
13606
13607   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13608     return 0;
13609
13610   /* First make sure we didn't deduce anything that conflicts with
13611      explicitly specified args.  */
13612   for (i = nargs; i--; )
13613     {
13614       tree elt = TREE_VEC_ELT (tempargs, i);
13615       tree oldelt = TREE_VEC_ELT (orig_targs, i);
13616
13617       if (!elt)
13618         /*NOP*/;
13619       else if (uses_template_parms (elt))
13620         /* Since we're unifying against ourselves, we will fill in
13621            template args used in the function parm list with our own
13622            template parms.  Discard them.  */
13623         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13624       else if (oldelt && !template_args_equal (oldelt, elt))
13625         return 0;
13626     }
13627
13628   for (i = nargs; i--; )
13629     {
13630       tree elt = TREE_VEC_ELT (tempargs, i);
13631
13632       if (elt)
13633         TREE_VEC_ELT (targs, i) = elt;
13634     }
13635
13636   return 1;
13637 }
13638
13639 /* PARM is a template class (perhaps with unbound template
13640    parameters).  ARG is a fully instantiated type.  If ARG can be
13641    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
13642    TARGS are as for unify.  */
13643
13644 static tree
13645 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
13646 {
13647   tree copy_of_targs;
13648
13649   if (!CLASSTYPE_TEMPLATE_INFO (arg)
13650       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
13651           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
13652     return NULL_TREE;
13653
13654   /* We need to make a new template argument vector for the call to
13655      unify.  If we used TARGS, we'd clutter it up with the result of
13656      the attempted unification, even if this class didn't work out.
13657      We also don't want to commit ourselves to all the unifications
13658      we've already done, since unification is supposed to be done on
13659      an argument-by-argument basis.  In other words, consider the
13660      following pathological case:
13661
13662        template <int I, int J, int K>
13663        struct S {};
13664
13665        template <int I, int J>
13666        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
13667
13668        template <int I, int J, int K>
13669        void f(S<I, J, K>, S<I, I, I>);
13670
13671        void g() {
13672          S<0, 0, 0> s0;
13673          S<0, 1, 2> s2;
13674
13675          f(s0, s2);
13676        }
13677
13678      Now, by the time we consider the unification involving `s2', we
13679      already know that we must have `f<0, 0, 0>'.  But, even though
13680      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
13681      because there are two ways to unify base classes of S<0, 1, 2>
13682      with S<I, I, I>.  If we kept the already deduced knowledge, we
13683      would reject the possibility I=1.  */
13684   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
13685
13686   /* If unification failed, we're done.  */
13687   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
13688              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
13689     return NULL_TREE;
13690
13691   return arg;
13692 }
13693
13694 /* Given a template type PARM and a class type ARG, find the unique
13695    base type in ARG that is an instance of PARM.  We do not examine
13696    ARG itself; only its base-classes.  If there is not exactly one
13697    appropriate base class, return NULL_TREE.  PARM may be the type of
13698    a partial specialization, as well as a plain template type.  Used
13699    by unify.  */
13700
13701 static tree
13702 get_template_base (tree tparms, tree targs, tree parm, tree arg)
13703 {
13704   tree rval = NULL_TREE;
13705   tree binfo;
13706
13707   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
13708
13709   binfo = TYPE_BINFO (complete_type (arg));
13710   if (!binfo)
13711     /* The type could not be completed.  */
13712     return NULL_TREE;
13713
13714   /* Walk in inheritance graph order.  The search order is not
13715      important, and this avoids multiple walks of virtual bases.  */
13716   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
13717     {
13718       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
13719
13720       if (r)
13721         {
13722           /* If there is more than one satisfactory baseclass, then:
13723
13724                [temp.deduct.call]
13725
13726               If they yield more than one possible deduced A, the type
13727               deduction fails.
13728
13729              applies.  */
13730           if (rval && !same_type_p (r, rval))
13731             return NULL_TREE;
13732
13733           rval = r;
13734         }
13735     }
13736
13737   return rval;
13738 }
13739
13740 /* Returns the level of DECL, which declares a template parameter.  */
13741
13742 static int
13743 template_decl_level (tree decl)
13744 {
13745   switch (TREE_CODE (decl))
13746     {
13747     case TYPE_DECL:
13748     case TEMPLATE_DECL:
13749       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
13750
13751     case PARM_DECL:
13752       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
13753
13754     default:
13755       gcc_unreachable ();
13756     }
13757   return 0;
13758 }
13759
13760 /* Decide whether ARG can be unified with PARM, considering only the
13761    cv-qualifiers of each type, given STRICT as documented for unify.
13762    Returns nonzero iff the unification is OK on that basis.  */
13763
13764 static int
13765 check_cv_quals_for_unify (int strict, tree arg, tree parm)
13766 {
13767   int arg_quals = cp_type_quals (arg);
13768   int parm_quals = cp_type_quals (parm);
13769
13770   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13771       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13772     {
13773       /*  Although a CVR qualifier is ignored when being applied to a
13774           substituted template parameter ([8.3.2]/1 for example), that
13775           does not apply during deduction [14.8.2.4]/1, (even though
13776           that is not explicitly mentioned, [14.8.2.4]/9 indicates
13777           this).  Except when we're allowing additional CV qualifiers
13778           at the outer level [14.8.2.1]/3,1st bullet.  */
13779       if ((TREE_CODE (arg) == REFERENCE_TYPE
13780            || TREE_CODE (arg) == FUNCTION_TYPE
13781            || TREE_CODE (arg) == METHOD_TYPE)
13782           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
13783         return 0;
13784
13785       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
13786           && (parm_quals & TYPE_QUAL_RESTRICT))
13787         return 0;
13788     }
13789
13790   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13791       && (arg_quals & parm_quals) != parm_quals)
13792     return 0;
13793
13794   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
13795       && (parm_quals & arg_quals) != arg_quals)
13796     return 0;
13797
13798   return 1;
13799 }
13800
13801 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
13802 void 
13803 template_parm_level_and_index (tree parm, int* level, int* index)
13804 {
13805   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13806       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13807       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13808     {
13809       *index = TEMPLATE_TYPE_IDX (parm);
13810       *level = TEMPLATE_TYPE_LEVEL (parm);
13811     }
13812   else
13813     {
13814       *index = TEMPLATE_PARM_IDX (parm);
13815       *level = TEMPLATE_PARM_LEVEL (parm);
13816     }
13817 }
13818
13819 /* Unifies the remaining arguments in PACKED_ARGS with the pack
13820    expansion at the end of PACKED_PARMS. Returns 0 if the type
13821    deduction succeeds, 1 otherwise. STRICT is the same as in
13822    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
13823    call argument list. We'll need to adjust the arguments to make them
13824    types. SUBR tells us if this is from a recursive call to
13825    type_unification_real.  */
13826 int
13827 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
13828                       tree packed_args, int strict, bool call_args_p,
13829                       bool subr)
13830 {
13831   tree parm 
13832     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
13833   tree pattern = PACK_EXPANSION_PATTERN (parm);
13834   tree pack, packs = NULL_TREE;
13835   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
13836   int len = TREE_VEC_LENGTH (packed_args);
13837
13838   /* Determine the parameter packs we will be deducing from the
13839      pattern, and record their current deductions.  */
13840   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
13841        pack; pack = TREE_CHAIN (pack))
13842     {
13843       tree parm_pack = TREE_VALUE (pack);
13844       int idx, level;
13845
13846       /* Determine the index and level of this parameter pack.  */
13847       template_parm_level_and_index (parm_pack, &level, &idx);
13848
13849       /* Keep track of the parameter packs and their corresponding
13850          argument packs.  */
13851       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
13852       TREE_TYPE (packs) = make_tree_vec (len - start);
13853     }
13854   
13855   /* Loop through all of the arguments that have not yet been
13856      unified and unify each with the pattern.  */
13857   for (i = start; i < len; i++)
13858     {
13859       tree parm = pattern;
13860
13861       /* For each parameter pack, clear out the deduced value so that
13862          we can deduce it again.  */
13863       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13864         {
13865           int idx, level;
13866           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13867
13868           TMPL_ARG (targs, level, idx) = NULL_TREE;
13869         }
13870
13871       /* Unify the pattern with the current argument.  */
13872       {
13873         tree arg = TREE_VEC_ELT (packed_args, i);
13874         tree arg_expr = NULL_TREE;
13875         int arg_strict = strict;
13876         bool skip_arg_p = false;
13877
13878         if (call_args_p)
13879           {
13880             int sub_strict;
13881
13882             /* This mirrors what we do in type_unification_real.  */
13883             switch (strict)
13884               {
13885               case DEDUCE_CALL:
13886                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
13887                               | UNIFY_ALLOW_MORE_CV_QUAL
13888                               | UNIFY_ALLOW_DERIVED);
13889                 break;
13890                 
13891               case DEDUCE_CONV:
13892                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13893                 break;
13894                 
13895               case DEDUCE_EXACT:
13896                 sub_strict = UNIFY_ALLOW_NONE;
13897                 break;
13898                 
13899               default:
13900                 gcc_unreachable ();
13901               }
13902
13903             if (!TYPE_P (arg))
13904               {
13905                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13906                 if (type_unknown_p (arg))
13907                   {
13908                     /* [temp.deduct.type] A template-argument can be
13909                        deduced from a pointer to function or pointer
13910                        to member function argument if the set of
13911                        overloaded functions does not contain function
13912                        templates and at most one of a set of
13913                        overloaded functions provides a unique
13914                        match.  */
13915
13916                     if (resolve_overloaded_unification
13917                         (tparms, targs, parm, arg,
13918                          (unification_kind_t) strict,
13919                          sub_strict)
13920                         != 0)
13921                       return 1;
13922                     skip_arg_p = true;
13923                   }
13924
13925                 if (!skip_arg_p)
13926                   {
13927                     arg_expr = arg;
13928                     arg = unlowered_expr_type (arg);
13929                     if (arg == error_mark_node)
13930                       return 1;
13931                   }
13932               }
13933       
13934             arg_strict = sub_strict;
13935
13936             if (!subr)
13937               arg_strict |= 
13938                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
13939                                                   &parm, &arg, arg_expr);
13940           }
13941
13942         if (!skip_arg_p)
13943           {
13944             if (unify (tparms, targs, parm, arg, arg_strict))
13945               return 1;
13946           }
13947       }
13948
13949       /* For each parameter pack, collect the deduced value.  */
13950       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13951         {
13952           int idx, level;
13953           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13954
13955           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
13956             TMPL_ARG (targs, level, idx);
13957         }
13958     }
13959
13960   /* Verify that the results of unification with the parameter packs
13961      produce results consistent with what we've seen before, and make
13962      the deduced argument packs available.  */
13963   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13964     {
13965       tree old_pack = TREE_VALUE (pack);
13966       tree new_args = TREE_TYPE (pack);
13967       int i, len = TREE_VEC_LENGTH (new_args);
13968       bool nondeduced_p = false;
13969
13970       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
13971          actually deduce anything.  */
13972       for (i = 0; i < len && !nondeduced_p; ++i)
13973         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
13974           nondeduced_p = true;
13975       if (nondeduced_p)
13976         continue;
13977
13978       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
13979         {
13980           /* Prepend the explicit arguments onto NEW_ARGS.  */
13981           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13982           tree old_args = new_args;
13983           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
13984           int len = explicit_len + TREE_VEC_LENGTH (old_args);
13985
13986           /* Copy the explicit arguments.  */
13987           new_args = make_tree_vec (len);
13988           for (i = 0; i < explicit_len; i++)
13989             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
13990
13991           /* Copy the deduced arguments.  */
13992           for (; i < len; i++)
13993             TREE_VEC_ELT (new_args, i) =
13994               TREE_VEC_ELT (old_args, i - explicit_len);
13995         }
13996
13997       if (!old_pack)
13998         {
13999           tree result;
14000           int idx, level;
14001           
14002           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14003
14004           /* Build the deduced *_ARGUMENT_PACK.  */
14005           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14006             {
14007               result = make_node (NONTYPE_ARGUMENT_PACK);
14008               TREE_TYPE (result) = 
14009                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14010               TREE_CONSTANT (result) = 1;
14011             }
14012           else
14013             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14014
14015           SET_ARGUMENT_PACK_ARGS (result, new_args);
14016
14017           /* Note the deduced argument packs for this parameter
14018              pack.  */
14019           TMPL_ARG (targs, level, idx) = result;
14020         }
14021       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14022                && (ARGUMENT_PACK_ARGS (old_pack) 
14023                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14024         {
14025           /* We only had the explicitly-provided arguments before, but
14026              now we have a complete set of arguments.  */
14027           int idx, level;
14028           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14029           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14030
14031           /* Keep the original deduced argument pack.  */
14032           TMPL_ARG (targs, level, idx) = old_pack;
14033
14034           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14035           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14036           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14037         }
14038       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14039                                     new_args))
14040         /* Inconsistent unification of this parameter pack.  */
14041         return 1;
14042       else
14043         {
14044           int idx, level;
14045           
14046           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14047
14048           /* Keep the original deduced argument pack.  */
14049           TMPL_ARG (targs, level, idx) = old_pack;
14050         }
14051     }
14052
14053   return 0;
14054 }
14055
14056 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14057    set of template parameters to a template.  TARGS is the bindings
14058    for those template parameters, as determined thus far; TARGS may
14059    include template arguments for outer levels of template parameters
14060    as well.  PARM is a parameter to a template function, or a
14061    subcomponent of that parameter; ARG is the corresponding argument.
14062    This function attempts to match PARM with ARG in a manner
14063    consistent with the existing assignments in TARGS.  If more values
14064    are deduced, then TARGS is updated.
14065
14066    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14067    parameter STRICT is a bitwise or of the following flags:
14068
14069      UNIFY_ALLOW_NONE:
14070        Require an exact match between PARM and ARG.
14071      UNIFY_ALLOW_MORE_CV_QUAL:
14072        Allow the deduced ARG to be more cv-qualified (by qualification
14073        conversion) than ARG.
14074      UNIFY_ALLOW_LESS_CV_QUAL:
14075        Allow the deduced ARG to be less cv-qualified than ARG.
14076      UNIFY_ALLOW_DERIVED:
14077        Allow the deduced ARG to be a template base class of ARG,
14078        or a pointer to a template base class of the type pointed to by
14079        ARG.
14080      UNIFY_ALLOW_INTEGER:
14081        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14082        case for more information.
14083      UNIFY_ALLOW_OUTER_LEVEL:
14084        This is the outermost level of a deduction. Used to determine validity
14085        of qualification conversions. A valid qualification conversion must
14086        have const qualified pointers leading up to the inner type which
14087        requires additional CV quals, except at the outer level, where const
14088        is not required [conv.qual]. It would be normal to set this flag in
14089        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14090      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14091        This is the outermost level of a deduction, and PARM can be more CV
14092        qualified at this point.
14093      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14094        This is the outermost level of a deduction, and PARM can be less CV
14095        qualified at this point.  */
14096
14097 static int
14098 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14099 {
14100   int idx;
14101   tree targ;
14102   tree tparm;
14103   int strict_in = strict;
14104
14105   /* I don't think this will do the right thing with respect to types.
14106      But the only case I've seen it in so far has been array bounds, where
14107      signedness is the only information lost, and I think that will be
14108      okay.  */
14109   while (TREE_CODE (parm) == NOP_EXPR)
14110     parm = TREE_OPERAND (parm, 0);
14111
14112   if (arg == error_mark_node)
14113     return 1;
14114   if (arg == unknown_type_node
14115       || arg == init_list_type_node)
14116     /* We can't deduce anything from this, but we might get all the
14117        template args from other function args.  */
14118     return 0;
14119
14120   /* If PARM uses template parameters, then we can't bail out here,
14121      even if ARG == PARM, since we won't record unifications for the
14122      template parameters.  We might need them if we're trying to
14123      figure out which of two things is more specialized.  */
14124   if (arg == parm && !uses_template_parms (parm))
14125     return 0;
14126
14127   /* Handle init lists early, so the rest of the function can assume
14128      we're dealing with a type. */
14129   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14130     {
14131       tree elt, elttype;
14132       unsigned i;
14133       tree orig_parm = parm;
14134
14135       /* Replace T with std::initializer_list<T> for deduction.  */
14136       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14137           && flag_deduce_init_list)
14138         parm = listify (parm);
14139
14140       if (!is_std_init_list (parm))
14141         /* We can only deduce from an initializer list argument if the
14142            parameter is std::initializer_list; otherwise this is a
14143            non-deduced context. */
14144         return 0;
14145
14146       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14147
14148       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14149         {
14150           int elt_strict = strict;
14151           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14152             {
14153               tree type = TREE_TYPE (elt);
14154               /* It should only be possible to get here for a call.  */
14155               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14156               elt_strict |= maybe_adjust_types_for_deduction
14157                 (DEDUCE_CALL, &elttype, &type, elt);
14158               elt = type;
14159             }
14160
14161           if (unify (tparms, targs, elttype, elt, elt_strict))
14162             return 1;
14163         }
14164
14165       /* If the std::initializer_list<T> deduction worked, replace the
14166          deduced A with std::initializer_list<A>.  */
14167       if (orig_parm != parm)
14168         {
14169           idx = TEMPLATE_TYPE_IDX (orig_parm);
14170           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14171           targ = listify (targ);
14172           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14173         }
14174       return 0;
14175     }
14176
14177   /* Immediately reject some pairs that won't unify because of
14178      cv-qualification mismatches.  */
14179   if (TREE_CODE (arg) == TREE_CODE (parm)
14180       && TYPE_P (arg)
14181       /* It is the elements of the array which hold the cv quals of an array
14182          type, and the elements might be template type parms. We'll check
14183          when we recurse.  */
14184       && TREE_CODE (arg) != ARRAY_TYPE
14185       /* We check the cv-qualifiers when unifying with template type
14186          parameters below.  We want to allow ARG `const T' to unify with
14187          PARM `T' for example, when computing which of two templates
14188          is more specialized, for example.  */
14189       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14190       && !check_cv_quals_for_unify (strict_in, arg, parm))
14191     return 1;
14192
14193   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14194       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14195     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14196   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14197   strict &= ~UNIFY_ALLOW_DERIVED;
14198   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14199   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14200
14201   switch (TREE_CODE (parm))
14202     {
14203     case TYPENAME_TYPE:
14204     case SCOPE_REF:
14205     case UNBOUND_CLASS_TEMPLATE:
14206       /* In a type which contains a nested-name-specifier, template
14207          argument values cannot be deduced for template parameters used
14208          within the nested-name-specifier.  */
14209       return 0;
14210
14211     case TEMPLATE_TYPE_PARM:
14212     case TEMPLATE_TEMPLATE_PARM:
14213     case BOUND_TEMPLATE_TEMPLATE_PARM:
14214       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14215       if (tparm == error_mark_node)
14216         return 1;
14217
14218       if (TEMPLATE_TYPE_LEVEL (parm)
14219           != template_decl_level (tparm))
14220         /* The PARM is not one we're trying to unify.  Just check
14221            to see if it matches ARG.  */
14222         return (TREE_CODE (arg) == TREE_CODE (parm)
14223                 && same_type_p (parm, arg)) ? 0 : 1;
14224       idx = TEMPLATE_TYPE_IDX (parm);
14225       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14226       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14227
14228       /* Check for mixed types and values.  */
14229       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14230            && TREE_CODE (tparm) != TYPE_DECL)
14231           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14232               && TREE_CODE (tparm) != TEMPLATE_DECL))
14233         return 1;
14234
14235       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14236         {
14237           /* ARG must be constructed from a template class or a template
14238              template parameter.  */
14239           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14240               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14241             return 1;
14242
14243           {
14244             tree parmvec = TYPE_TI_ARGS (parm);
14245             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14246             tree parm_parms 
14247               = DECL_INNERMOST_TEMPLATE_PARMS
14248                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14249             int i, len;
14250             int parm_variadic_p = 0;
14251
14252             /* The resolution to DR150 makes clear that default
14253                arguments for an N-argument may not be used to bind T
14254                to a template template parameter with fewer than N
14255                parameters.  It is not safe to permit the binding of
14256                default arguments as an extension, as that may change
14257                the meaning of a conforming program.  Consider:
14258
14259                   struct Dense { static const unsigned int dim = 1; };
14260
14261                   template <template <typename> class View,
14262                             typename Block>
14263                   void operator+(float, View<Block> const&);
14264
14265                   template <typename Block,
14266                             unsigned int Dim = Block::dim>
14267                   struct Lvalue_proxy { operator float() const; };
14268
14269                   void
14270                   test_1d (void) {
14271                     Lvalue_proxy<Dense> p;
14272                     float b;
14273                     b + p;
14274                   }
14275
14276               Here, if Lvalue_proxy is permitted to bind to View, then
14277               the global operator+ will be used; if they are not, the
14278               Lvalue_proxy will be converted to float.  */
14279             if (coerce_template_parms (parm_parms,
14280                                        argvec,
14281                                        TYPE_TI_TEMPLATE (parm),
14282                                        tf_none,
14283                                        /*require_all_args=*/true,
14284                                        /*use_default_args=*/false)
14285                 == error_mark_node)
14286               return 1;
14287
14288             /* Deduce arguments T, i from TT<T> or TT<i>.
14289                We check each element of PARMVEC and ARGVEC individually
14290                rather than the whole TREE_VEC since they can have
14291                different number of elements.  */
14292
14293             parmvec = expand_template_argument_pack (parmvec);
14294             argvec = expand_template_argument_pack (argvec);
14295
14296             len = TREE_VEC_LENGTH (parmvec);
14297
14298             /* Check if the parameters end in a pack, making them
14299                variadic.  */
14300             if (len > 0
14301                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14302               parm_variadic_p = 1;
14303             
14304             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14305               return 1;
14306
14307              for (i = 0; i < len - parm_variadic_p; ++i)
14308               {
14309                 if (unify (tparms, targs,
14310                            TREE_VEC_ELT (parmvec, i),
14311                            TREE_VEC_ELT (argvec, i),
14312                            UNIFY_ALLOW_NONE))
14313                   return 1;
14314               }
14315
14316             if (parm_variadic_p
14317                 && unify_pack_expansion (tparms, targs,
14318                                          parmvec, argvec,
14319                                          UNIFY_ALLOW_NONE,
14320                                          /*call_args_p=*/false,
14321                                          /*subr=*/false))
14322               return 1;
14323           }
14324           arg = TYPE_TI_TEMPLATE (arg);
14325
14326           /* Fall through to deduce template name.  */
14327         }
14328
14329       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14330           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14331         {
14332           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14333
14334           /* Simple cases: Value already set, does match or doesn't.  */
14335           if (targ != NULL_TREE && template_args_equal (targ, arg))
14336             return 0;
14337           else if (targ)
14338             return 1;
14339         }
14340       else
14341         {
14342           /* If PARM is `const T' and ARG is only `int', we don't have
14343              a match unless we are allowing additional qualification.
14344              If ARG is `const int' and PARM is just `T' that's OK;
14345              that binds `const int' to `T'.  */
14346           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14347                                          arg, parm))
14348             return 1;
14349
14350           /* Consider the case where ARG is `const volatile int' and
14351              PARM is `const T'.  Then, T should be `volatile int'.  */
14352           arg = cp_build_qualified_type_real
14353             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14354           if (arg == error_mark_node)
14355             return 1;
14356
14357           /* Simple cases: Value already set, does match or doesn't.  */
14358           if (targ != NULL_TREE && same_type_p (targ, arg))
14359             return 0;
14360           else if (targ)
14361             return 1;
14362
14363           /* Make sure that ARG is not a variable-sized array.  (Note
14364              that were talking about variable-sized arrays (like
14365              `int[n]'), rather than arrays of unknown size (like
14366              `int[]').)  We'll get very confused by such a type since
14367              the bound of the array will not be computable in an
14368              instantiation.  Besides, such types are not allowed in
14369              ISO C++, so we can do as we please here.  */
14370           if (variably_modified_type_p (arg, NULL_TREE))
14371             return 1;
14372
14373           /* Strip typedefs as in convert_template_argument.  */
14374           arg = strip_typedefs (arg);
14375         }
14376
14377       /* If ARG is a parameter pack or an expansion, we cannot unify
14378          against it unless PARM is also a parameter pack.  */
14379       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14380           && !template_parameter_pack_p (parm))
14381         return 1;
14382
14383       /* If the argument deduction results is a METHOD_TYPE,
14384          then there is a problem.
14385          METHOD_TYPE doesn't map to any real C++ type the result of
14386          the deduction can not be of that type.  */
14387       if (TREE_CODE (arg) == METHOD_TYPE)
14388         return 1;
14389
14390       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14391       return 0;
14392
14393     case TEMPLATE_PARM_INDEX:
14394       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14395       if (tparm == error_mark_node)
14396         return 1;
14397
14398       if (TEMPLATE_PARM_LEVEL (parm)
14399           != template_decl_level (tparm))
14400         /* The PARM is not one we're trying to unify.  Just check
14401            to see if it matches ARG.  */
14402         return !(TREE_CODE (arg) == TREE_CODE (parm)
14403                  && cp_tree_equal (parm, arg));
14404
14405       idx = TEMPLATE_PARM_IDX (parm);
14406       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14407
14408       if (targ)
14409         return !cp_tree_equal (targ, arg);
14410
14411       /* [temp.deduct.type] If, in the declaration of a function template
14412          with a non-type template-parameter, the non-type
14413          template-parameter is used in an expression in the function
14414          parameter-list and, if the corresponding template-argument is
14415          deduced, the template-argument type shall match the type of the
14416          template-parameter exactly, except that a template-argument
14417          deduced from an array bound may be of any integral type.
14418          The non-type parameter might use already deduced type parameters.  */
14419       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14420       if (!TREE_TYPE (arg))
14421         /* Template-parameter dependent expression.  Just accept it for now.
14422            It will later be processed in convert_template_argument.  */
14423         ;
14424       else if (same_type_p (TREE_TYPE (arg), tparm))
14425         /* OK */;
14426       else if ((strict & UNIFY_ALLOW_INTEGER)
14427                && (TREE_CODE (tparm) == INTEGER_TYPE
14428                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
14429         /* Convert the ARG to the type of PARM; the deduced non-type
14430            template argument must exactly match the types of the
14431            corresponding parameter.  */
14432         arg = fold (build_nop (tparm, arg));
14433       else if (uses_template_parms (tparm))
14434         /* We haven't deduced the type of this parameter yet.  Try again
14435            later.  */
14436         return 0;
14437       else
14438         return 1;
14439
14440       /* If ARG is a parameter pack or an expansion, we cannot unify
14441          against it unless PARM is also a parameter pack.  */
14442       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14443           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14444         return 1;
14445
14446       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14447       return 0;
14448
14449     case PTRMEM_CST:
14450      {
14451         /* A pointer-to-member constant can be unified only with
14452          another constant.  */
14453       if (TREE_CODE (arg) != PTRMEM_CST)
14454         return 1;
14455
14456       /* Just unify the class member. It would be useless (and possibly
14457          wrong, depending on the strict flags) to unify also
14458          PTRMEM_CST_CLASS, because we want to be sure that both parm and
14459          arg refer to the same variable, even if through different
14460          classes. For instance:
14461
14462          struct A { int x; };
14463          struct B : A { };
14464
14465          Unification of &A::x and &B::x must succeed.  */
14466       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14467                     PTRMEM_CST_MEMBER (arg), strict);
14468      }
14469
14470     case POINTER_TYPE:
14471       {
14472         if (TREE_CODE (arg) != POINTER_TYPE)
14473           return 1;
14474
14475         /* [temp.deduct.call]
14476
14477            A can be another pointer or pointer to member type that can
14478            be converted to the deduced A via a qualification
14479            conversion (_conv.qual_).
14480
14481            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14482            This will allow for additional cv-qualification of the
14483            pointed-to types if appropriate.  */
14484
14485         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14486           /* The derived-to-base conversion only persists through one
14487              level of pointers.  */
14488           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14489
14490         return unify (tparms, targs, TREE_TYPE (parm),
14491                       TREE_TYPE (arg), strict);
14492       }
14493
14494     case REFERENCE_TYPE:
14495       if (TREE_CODE (arg) != REFERENCE_TYPE)
14496         return 1;
14497       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14498                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14499
14500     case ARRAY_TYPE:
14501       if (TREE_CODE (arg) != ARRAY_TYPE)
14502         return 1;
14503       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14504           != (TYPE_DOMAIN (arg) == NULL_TREE))
14505         return 1;
14506       if (TYPE_DOMAIN (parm) != NULL_TREE)
14507         {
14508           tree parm_max;
14509           tree arg_max;
14510           bool parm_cst;
14511           bool arg_cst;
14512
14513           /* Our representation of array types uses "N - 1" as the
14514              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14515              not an integer constant.  We cannot unify arbitrarily
14516              complex expressions, so we eliminate the MINUS_EXPRs
14517              here.  */
14518           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14519           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14520           if (!parm_cst)
14521             {
14522               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14523               parm_max = TREE_OPERAND (parm_max, 0);
14524             }
14525           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14526           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14527           if (!arg_cst)
14528             {
14529               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14530                  trying to unify the type of a variable with the type
14531                  of a template parameter.  For example:
14532
14533                    template <unsigned int N>
14534                    void f (char (&) [N]);
14535                    int g(); 
14536                    void h(int i) {
14537                      char a[g(i)];
14538                      f(a); 
14539                    }
14540
14541                 Here, the type of the ARG will be "int [g(i)]", and
14542                 may be a SAVE_EXPR, etc.  */
14543               if (TREE_CODE (arg_max) != MINUS_EXPR)
14544                 return 1;
14545               arg_max = TREE_OPERAND (arg_max, 0);
14546             }
14547
14548           /* If only one of the bounds used a MINUS_EXPR, compensate
14549              by adding one to the other bound.  */
14550           if (parm_cst && !arg_cst)
14551             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14552                                     integer_type_node,
14553                                     parm_max,
14554                                     integer_one_node);
14555           else if (arg_cst && !parm_cst)
14556             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14557                                    integer_type_node,
14558                                    arg_max,
14559                                    integer_one_node);
14560
14561           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14562             return 1;
14563         }
14564       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14565                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14566
14567     case REAL_TYPE:
14568     case COMPLEX_TYPE:
14569     case VECTOR_TYPE:
14570     case INTEGER_TYPE:
14571     case BOOLEAN_TYPE:
14572     case ENUMERAL_TYPE:
14573     case VOID_TYPE:
14574       if (TREE_CODE (arg) != TREE_CODE (parm))
14575         return 1;
14576
14577       /* We have already checked cv-qualification at the top of the
14578          function.  */
14579       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14580         return 1;
14581
14582       /* As far as unification is concerned, this wins.  Later checks
14583          will invalidate it if necessary.  */
14584       return 0;
14585
14586       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14587       /* Type INTEGER_CST can come from ordinary constant template args.  */
14588     case INTEGER_CST:
14589       while (TREE_CODE (arg) == NOP_EXPR)
14590         arg = TREE_OPERAND (arg, 0);
14591
14592       if (TREE_CODE (arg) != INTEGER_CST)
14593         return 1;
14594       return !tree_int_cst_equal (parm, arg);
14595
14596     case TREE_VEC:
14597       {
14598         int i;
14599         if (TREE_CODE (arg) != TREE_VEC)
14600           return 1;
14601         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14602           return 1;
14603         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14604           if (unify (tparms, targs,
14605                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14606                      UNIFY_ALLOW_NONE))
14607             return 1;
14608         return 0;
14609       }
14610
14611     case RECORD_TYPE:
14612     case UNION_TYPE:
14613       if (TREE_CODE (arg) != TREE_CODE (parm))
14614         return 1;
14615
14616       if (TYPE_PTRMEMFUNC_P (parm))
14617         {
14618           if (!TYPE_PTRMEMFUNC_P (arg))
14619             return 1;
14620
14621           return unify (tparms, targs,
14622                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
14623                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
14624                         strict);
14625         }
14626
14627       if (CLASSTYPE_TEMPLATE_INFO (parm))
14628         {
14629           tree t = NULL_TREE;
14630
14631           if (strict_in & UNIFY_ALLOW_DERIVED)
14632             {
14633               /* First, we try to unify the PARM and ARG directly.  */
14634               t = try_class_unification (tparms, targs,
14635                                          parm, arg);
14636
14637               if (!t)
14638                 {
14639                   /* Fallback to the special case allowed in
14640                      [temp.deduct.call]:
14641
14642                        If P is a class, and P has the form
14643                        template-id, then A can be a derived class of
14644                        the deduced A.  Likewise, if P is a pointer to
14645                        a class of the form template-id, A can be a
14646                        pointer to a derived class pointed to by the
14647                        deduced A.  */
14648                   t = get_template_base (tparms, targs, parm, arg);
14649
14650                   if (!t)
14651                     return 1;
14652                 }
14653             }
14654           else if (CLASSTYPE_TEMPLATE_INFO (arg)
14655                    && (CLASSTYPE_TI_TEMPLATE (parm)
14656                        == CLASSTYPE_TI_TEMPLATE (arg)))
14657             /* Perhaps PARM is something like S<U> and ARG is S<int>.
14658                Then, we should unify `int' and `U'.  */
14659             t = arg;
14660           else
14661             /* There's no chance of unification succeeding.  */
14662             return 1;
14663
14664           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
14665                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
14666         }
14667       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
14668         return 1;
14669       return 0;
14670
14671     case METHOD_TYPE:
14672     case FUNCTION_TYPE:
14673       {
14674         unsigned int nargs;
14675         tree *args;
14676         tree a;
14677         unsigned int i;
14678
14679         if (TREE_CODE (arg) != TREE_CODE (parm))
14680           return 1;
14681
14682         /* CV qualifications for methods can never be deduced, they must
14683            match exactly.  We need to check them explicitly here,
14684            because type_unification_real treats them as any other
14685            cv-qualified parameter.  */
14686         if (TREE_CODE (parm) == METHOD_TYPE
14687             && (!check_cv_quals_for_unify
14688                 (UNIFY_ALLOW_NONE,
14689                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
14690                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
14691           return 1;
14692
14693         if (unify (tparms, targs, TREE_TYPE (parm),
14694                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
14695           return 1;
14696
14697         nargs = list_length (TYPE_ARG_TYPES (arg));
14698         args = XALLOCAVEC (tree, nargs);
14699         for (a = TYPE_ARG_TYPES (arg), i = 0;
14700              a != NULL_TREE && a != void_list_node;
14701              a = TREE_CHAIN (a), ++i)
14702           args[i] = TREE_VALUE (a);
14703         nargs = i;
14704
14705         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
14706                                       args, nargs, 1, DEDUCE_EXACT,
14707                                       LOOKUP_NORMAL);
14708       }
14709
14710     case OFFSET_TYPE:
14711       /* Unify a pointer to member with a pointer to member function, which
14712          deduces the type of the member as a function type. */
14713       if (TYPE_PTRMEMFUNC_P (arg))
14714         {
14715           tree method_type;
14716           tree fntype;
14717           cp_cv_quals cv_quals;
14718
14719           /* Check top-level cv qualifiers */
14720           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
14721             return 1;
14722
14723           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14724                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
14725             return 1;
14726
14727           /* Determine the type of the function we are unifying against. */
14728           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
14729           fntype =
14730             build_function_type (TREE_TYPE (method_type),
14731                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
14732
14733           /* Extract the cv-qualifiers of the member function from the
14734              implicit object parameter and place them on the function
14735              type to be restored later. */
14736           cv_quals =
14737             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
14738           fntype = build_qualified_type (fntype, cv_quals);
14739           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
14740         }
14741
14742       if (TREE_CODE (arg) != OFFSET_TYPE)
14743         return 1;
14744       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14745                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
14746         return 1;
14747       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14748                     strict);
14749
14750     case CONST_DECL:
14751       if (DECL_TEMPLATE_PARM_P (parm))
14752         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
14753       if (arg != integral_constant_value (parm))
14754         return 1;
14755       return 0;
14756
14757     case FIELD_DECL:
14758     case TEMPLATE_DECL:
14759       /* Matched cases are handled by the ARG == PARM test above.  */
14760       return 1;
14761
14762     case TYPE_ARGUMENT_PACK:
14763     case NONTYPE_ARGUMENT_PACK:
14764       {
14765         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
14766         tree packed_args = ARGUMENT_PACK_ARGS (arg);
14767         int i, len = TREE_VEC_LENGTH (packed_parms);
14768         int argslen = TREE_VEC_LENGTH (packed_args);
14769         int parm_variadic_p = 0;
14770
14771         for (i = 0; i < len; ++i)
14772           {
14773             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
14774               {
14775                 if (i == len - 1)
14776                   /* We can unify against something with a trailing
14777                      parameter pack.  */
14778                   parm_variadic_p = 1;
14779                 else
14780                   /* Since there is something following the pack
14781                      expansion, we cannot unify this template argument
14782                      list.  */
14783                   return 0;
14784               }
14785           }
14786           
14787
14788         /* If we don't have enough arguments to satisfy the parameters
14789            (not counting the pack expression at the end), or we have
14790            too many arguments for a parameter list that doesn't end in
14791            a pack expression, we can't unify.  */
14792         if (argslen < (len - parm_variadic_p)
14793             || (argslen > len && !parm_variadic_p))
14794           return 1;
14795
14796         /* Unify all of the parameters that precede the (optional)
14797            pack expression.  */
14798         for (i = 0; i < len - parm_variadic_p; ++i)
14799           {
14800             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
14801                        TREE_VEC_ELT (packed_args, i), strict))
14802               return 1;
14803           }
14804
14805         if (parm_variadic_p)
14806           return unify_pack_expansion (tparms, targs, 
14807                                        packed_parms, packed_args,
14808                                        strict, /*call_args_p=*/false,
14809                                        /*subr=*/false);
14810         return 0;
14811       }
14812
14813       break;
14814
14815     case TYPEOF_TYPE:
14816     case DECLTYPE_TYPE:
14817       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
14818          nodes.  */
14819       return 0;
14820
14821     case ERROR_MARK:
14822       /* Unification fails if we hit an error node.  */
14823       return 1;
14824
14825     default:
14826       gcc_assert (EXPR_P (parm));
14827
14828       /* We must be looking at an expression.  This can happen with
14829          something like:
14830
14831            template <int I>
14832            void foo(S<I>, S<I + 2>);
14833
14834          This is a "nondeduced context":
14835
14836            [deduct.type]
14837
14838            The nondeduced contexts are:
14839
14840            --A type that is a template-id in which one or more of
14841              the template-arguments is an expression that references
14842              a template-parameter.
14843
14844          In these cases, we assume deduction succeeded, but don't
14845          actually infer any unifications.  */
14846
14847       if (!uses_template_parms (parm)
14848           && !template_args_equal (parm, arg))
14849         return 1;
14850       else
14851         return 0;
14852     }
14853 }
14854 \f
14855 /* Note that DECL can be defined in this translation unit, if
14856    required.  */
14857
14858 static void
14859 mark_definable (tree decl)
14860 {
14861   tree clone;
14862   DECL_NOT_REALLY_EXTERN (decl) = 1;
14863   FOR_EACH_CLONE (clone, decl)
14864     DECL_NOT_REALLY_EXTERN (clone) = 1;
14865 }
14866
14867 /* Called if RESULT is explicitly instantiated, or is a member of an
14868    explicitly instantiated class.  */
14869
14870 void
14871 mark_decl_instantiated (tree result, int extern_p)
14872 {
14873   SET_DECL_EXPLICIT_INSTANTIATION (result);
14874
14875   /* If this entity has already been written out, it's too late to
14876      make any modifications.  */
14877   if (TREE_ASM_WRITTEN (result))
14878     return;
14879
14880   if (TREE_CODE (result) != FUNCTION_DECL)
14881     /* The TREE_PUBLIC flag for function declarations will have been
14882        set correctly by tsubst.  */
14883     TREE_PUBLIC (result) = 1;
14884
14885   /* This might have been set by an earlier implicit instantiation.  */
14886   DECL_COMDAT (result) = 0;
14887
14888   if (extern_p)
14889     DECL_NOT_REALLY_EXTERN (result) = 0;
14890   else
14891     {
14892       mark_definable (result);
14893       /* Always make artificials weak.  */
14894       if (DECL_ARTIFICIAL (result) && flag_weak)
14895         comdat_linkage (result);
14896       /* For WIN32 we also want to put explicit instantiations in
14897          linkonce sections.  */
14898       else if (TREE_PUBLIC (result))
14899         maybe_make_one_only (result);
14900     }
14901
14902   /* If EXTERN_P, then this function will not be emitted -- unless
14903      followed by an explicit instantiation, at which point its linkage
14904      will be adjusted.  If !EXTERN_P, then this function will be
14905      emitted here.  In neither circumstance do we want
14906      import_export_decl to adjust the linkage.  */
14907   DECL_INTERFACE_KNOWN (result) = 1;
14908 }
14909
14910 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
14911    important template arguments.  If any are missing, we check whether
14912    they're important by using error_mark_node for substituting into any
14913    args that were used for partial ordering (the ones between ARGS and END)
14914    and seeing if it bubbles up.  */
14915
14916 static bool
14917 check_undeduced_parms (tree targs, tree args, tree end)
14918 {
14919   bool found = false;
14920   int i;
14921   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
14922     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
14923       {
14924         found = true;
14925         TREE_VEC_ELT (targs, i) = error_mark_node;
14926       }
14927   if (found)
14928     {
14929       for (; args != end; args = TREE_CHAIN (args))
14930         {
14931           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
14932           if (substed == error_mark_node)
14933             return true;
14934         }
14935     }
14936   return false;
14937 }
14938
14939 /* Given two function templates PAT1 and PAT2, return:
14940
14941    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
14942    -1 if PAT2 is more specialized than PAT1.
14943    0 if neither is more specialized.
14944
14945    LEN indicates the number of parameters we should consider
14946    (defaulted parameters should not be considered).
14947
14948    The 1998 std underspecified function template partial ordering, and
14949    DR214 addresses the issue.  We take pairs of arguments, one from
14950    each of the templates, and deduce them against each other.  One of
14951    the templates will be more specialized if all the *other*
14952    template's arguments deduce against its arguments and at least one
14953    of its arguments *does* *not* deduce against the other template's
14954    corresponding argument.  Deduction is done as for class templates.
14955    The arguments used in deduction have reference and top level cv
14956    qualifiers removed.  Iff both arguments were originally reference
14957    types *and* deduction succeeds in both directions, the template
14958    with the more cv-qualified argument wins for that pairing (if
14959    neither is more cv-qualified, they both are equal).  Unlike regular
14960    deduction, after all the arguments have been deduced in this way,
14961    we do *not* verify the deduced template argument values can be
14962    substituted into non-deduced contexts.
14963
14964    The logic can be a bit confusing here, because we look at deduce1 and
14965    targs1 to see if pat2 is at least as specialized, and vice versa; if we
14966    can find template arguments for pat1 to make arg1 look like arg2, that
14967    means that arg2 is at least as specialized as arg1.  */
14968
14969 int
14970 more_specialized_fn (tree pat1, tree pat2, int len)
14971 {
14972   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
14973   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
14974   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
14975   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
14976   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
14977   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
14978   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
14979   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
14980   tree origs1, origs2;
14981   bool lose1 = false;
14982   bool lose2 = false;
14983
14984   /* Remove the this parameter from non-static member functions.  If
14985      one is a non-static member function and the other is not a static
14986      member function, remove the first parameter from that function
14987      also.  This situation occurs for operator functions where we
14988      locate both a member function (with this pointer) and non-member
14989      operator (with explicit first operand).  */
14990   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
14991     {
14992       len--; /* LEN is the number of significant arguments for DECL1 */
14993       args1 = TREE_CHAIN (args1);
14994       if (!DECL_STATIC_FUNCTION_P (decl2))
14995         args2 = TREE_CHAIN (args2);
14996     }
14997   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
14998     {
14999       args2 = TREE_CHAIN (args2);
15000       if (!DECL_STATIC_FUNCTION_P (decl1))
15001         {
15002           len--;
15003           args1 = TREE_CHAIN (args1);
15004         }
15005     }
15006
15007   /* If only one is a conversion operator, they are unordered.  */
15008   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15009     return 0;
15010
15011   /* Consider the return type for a conversion function */
15012   if (DECL_CONV_FN_P (decl1))
15013     {
15014       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15015       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15016       len++;
15017     }
15018
15019   processing_template_decl++;
15020
15021   origs1 = args1;
15022   origs2 = args2;
15023
15024   while (len--
15025          /* Stop when an ellipsis is seen.  */
15026          && args1 != NULL_TREE && args2 != NULL_TREE)
15027     {
15028       tree arg1 = TREE_VALUE (args1);
15029       tree arg2 = TREE_VALUE (args2);
15030       int deduce1, deduce2;
15031       int quals1 = -1;
15032       int quals2 = -1;
15033
15034       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15035           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15036         {
15037           /* When both arguments are pack expansions, we need only
15038              unify the patterns themselves.  */
15039           arg1 = PACK_EXPANSION_PATTERN (arg1);
15040           arg2 = PACK_EXPANSION_PATTERN (arg2);
15041
15042           /* This is the last comparison we need to do.  */
15043           len = 0;
15044         }
15045
15046       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15047         {
15048           arg1 = TREE_TYPE (arg1);
15049           quals1 = cp_type_quals (arg1);
15050         }
15051
15052       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15053         {
15054           arg2 = TREE_TYPE (arg2);
15055           quals2 = cp_type_quals (arg2);
15056         }
15057
15058       if ((quals1 < 0) != (quals2 < 0))
15059         {
15060           /* Only of the args is a reference, see if we should apply
15061              array/function pointer decay to it.  This is not part of
15062              DR214, but is, IMHO, consistent with the deduction rules
15063              for the function call itself, and with our earlier
15064              implementation of the underspecified partial ordering
15065              rules.  (nathan).  */
15066           if (quals1 >= 0)
15067             {
15068               switch (TREE_CODE (arg1))
15069                 {
15070                 case ARRAY_TYPE:
15071                   arg1 = TREE_TYPE (arg1);
15072                   /* FALLTHROUGH. */
15073                 case FUNCTION_TYPE:
15074                   arg1 = build_pointer_type (arg1);
15075                   break;
15076
15077                 default:
15078                   break;
15079                 }
15080             }
15081           else
15082             {
15083               switch (TREE_CODE (arg2))
15084                 {
15085                 case ARRAY_TYPE:
15086                   arg2 = TREE_TYPE (arg2);
15087                   /* FALLTHROUGH. */
15088                 case FUNCTION_TYPE:
15089                   arg2 = build_pointer_type (arg2);
15090                   break;
15091
15092                 default:
15093                   break;
15094                 }
15095             }
15096         }
15097
15098       arg1 = TYPE_MAIN_VARIANT (arg1);
15099       arg2 = TYPE_MAIN_VARIANT (arg2);
15100
15101       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15102         {
15103           int i, len2 = list_length (args2);
15104           tree parmvec = make_tree_vec (1);
15105           tree argvec = make_tree_vec (len2);
15106           tree ta = args2;
15107
15108           /* Setup the parameter vector, which contains only ARG1.  */
15109           TREE_VEC_ELT (parmvec, 0) = arg1;
15110
15111           /* Setup the argument vector, which contains the remaining
15112              arguments.  */
15113           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15114             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15115
15116           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15117                                            argvec, UNIFY_ALLOW_NONE, 
15118                                            /*call_args_p=*/false, 
15119                                            /*subr=*/0);
15120
15121           /* We cannot deduce in the other direction, because ARG1 is
15122              a pack expansion but ARG2 is not.  */
15123           deduce2 = 0;
15124         }
15125       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15126         {
15127           int i, len1 = list_length (args1);
15128           tree parmvec = make_tree_vec (1);
15129           tree argvec = make_tree_vec (len1);
15130           tree ta = args1;
15131
15132           /* Setup the parameter vector, which contains only ARG1.  */
15133           TREE_VEC_ELT (parmvec, 0) = arg2;
15134
15135           /* Setup the argument vector, which contains the remaining
15136              arguments.  */
15137           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15138             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15139
15140           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15141                                            argvec, UNIFY_ALLOW_NONE, 
15142                                            /*call_args_p=*/false, 
15143                                            /*subr=*/0);
15144
15145           /* We cannot deduce in the other direction, because ARG2 is
15146              a pack expansion but ARG1 is not.*/
15147           deduce1 = 0;
15148         }
15149
15150       else
15151         {
15152           /* The normal case, where neither argument is a pack
15153              expansion.  */
15154           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15155           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15156         }
15157
15158       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15159          arg2, then arg2 is not as specialized as arg1.  */
15160       if (!deduce1)
15161         lose2 = true;
15162       if (!deduce2)
15163         lose1 = true;
15164
15165       /* "If, for a given type, deduction succeeds in both directions
15166          (i.e., the types are identical after the transformations above)
15167          and if the type from the argument template is more cv-qualified
15168          than the type from the parameter template (as described above)
15169          that type is considered to be more specialized than the other. If
15170          neither type is more cv-qualified than the other then neither type
15171          is more specialized than the other."
15172
15173          We check same_type_p explicitly because deduction can also succeed
15174          in both directions when there is a nondeduced context.  */
15175       if (deduce1 && deduce2
15176           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0
15177           && same_type_p (arg1, arg2))
15178         {
15179           if ((quals1 & quals2) == quals2)
15180             lose2 = true;
15181           if ((quals1 & quals2) == quals1)
15182             lose1 = true;
15183         }
15184
15185       if (lose1 && lose2)
15186         /* We've failed to deduce something in either direction.
15187            These must be unordered.  */
15188         break;
15189
15190       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15191           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15192         /* We have already processed all of the arguments in our
15193            handing of the pack expansion type.  */
15194         len = 0;
15195
15196       args1 = TREE_CHAIN (args1);
15197       args2 = TREE_CHAIN (args2);
15198     }
15199
15200   /* "In most cases, all template parameters must have values in order for
15201      deduction to succeed, but for partial ordering purposes a template
15202      parameter may remain without a value provided it is not used in the
15203      types being used for partial ordering."
15204
15205      Thus, if we are missing any of the targs1 we need to substitute into
15206      origs1, then pat2 is not as specialized as pat1.  This can happen when
15207      there is a nondeduced context.  */
15208   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15209     lose2 = true;
15210   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15211     lose1 = true;
15212
15213   processing_template_decl--;
15214
15215   /* All things being equal, if the next argument is a pack expansion
15216      for one function but not for the other, prefer the
15217      non-variadic function.  FIXME this is bogus; see c++/41958.  */
15218   if (lose1 == lose2
15219       && args1 && TREE_VALUE (args1)
15220       && args2 && TREE_VALUE (args2))
15221     {
15222       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15223       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15224     }
15225
15226   if (lose1 == lose2)
15227     return 0;
15228   else if (!lose1)
15229     return 1;
15230   else
15231     return -1;
15232 }
15233
15234 /* Determine which of two partial specializations is more specialized.
15235
15236    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15237    to the first partial specialization.  The TREE_VALUE is the
15238    innermost set of template parameters for the partial
15239    specialization.  PAT2 is similar, but for the second template.
15240
15241    Return 1 if the first partial specialization is more specialized;
15242    -1 if the second is more specialized; 0 if neither is more
15243    specialized.
15244
15245    See [temp.class.order] for information about determining which of
15246    two templates is more specialized.  */
15247
15248 static int
15249 more_specialized_class (tree pat1, tree pat2)
15250 {
15251   tree targs;
15252   tree tmpl1, tmpl2;
15253   int winner = 0;
15254   bool any_deductions = false;
15255
15256   tmpl1 = TREE_TYPE (pat1);
15257   tmpl2 = TREE_TYPE (pat2);
15258
15259   /* Just like what happens for functions, if we are ordering between
15260      different class template specializations, we may encounter dependent
15261      types in the arguments, and we need our dependency check functions
15262      to behave correctly.  */
15263   ++processing_template_decl;
15264   targs = get_class_bindings (TREE_VALUE (pat1),
15265                               CLASSTYPE_TI_ARGS (tmpl1),
15266                               CLASSTYPE_TI_ARGS (tmpl2));
15267   if (targs)
15268     {
15269       --winner;
15270       any_deductions = true;
15271     }
15272
15273   targs = get_class_bindings (TREE_VALUE (pat2),
15274                               CLASSTYPE_TI_ARGS (tmpl2),
15275                               CLASSTYPE_TI_ARGS (tmpl1));
15276   if (targs)
15277     {
15278       ++winner;
15279       any_deductions = true;
15280     }
15281   --processing_template_decl;
15282
15283   /* In the case of a tie where at least one of the class templates
15284      has a parameter pack at the end, the template with the most
15285      non-packed parameters wins.  */
15286   if (winner == 0
15287       && any_deductions
15288       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15289           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15290     {
15291       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15292       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15293       int len1 = TREE_VEC_LENGTH (args1);
15294       int len2 = TREE_VEC_LENGTH (args2);
15295
15296       /* We don't count the pack expansion at the end.  */
15297       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15298         --len1;
15299       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15300         --len2;
15301
15302       if (len1 > len2)
15303         return 1;
15304       else if (len1 < len2)
15305         return -1;
15306     }
15307
15308   return winner;
15309 }
15310
15311 /* Return the template arguments that will produce the function signature
15312    DECL from the function template FN, with the explicit template
15313    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15314    also match.  Return NULL_TREE if no satisfactory arguments could be
15315    found.  */
15316
15317 static tree
15318 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15319 {
15320   int ntparms = DECL_NTPARMS (fn);
15321   tree targs = make_tree_vec (ntparms);
15322   tree decl_type;
15323   tree decl_arg_types;
15324   tree *args;
15325   unsigned int nargs, ix;
15326   tree arg;
15327
15328   /* Substitute the explicit template arguments into the type of DECL.
15329      The call to fn_type_unification will handle substitution into the
15330      FN.  */
15331   decl_type = TREE_TYPE (decl);
15332   if (explicit_args && uses_template_parms (decl_type))
15333     {
15334       tree tmpl;
15335       tree converted_args;
15336
15337       if (DECL_TEMPLATE_INFO (decl))
15338         tmpl = DECL_TI_TEMPLATE (decl);
15339       else
15340         /* We can get here for some invalid specializations.  */
15341         return NULL_TREE;
15342
15343       converted_args
15344         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15345                                  explicit_args, NULL_TREE,
15346                                  tf_none,
15347                                  /*require_all_args=*/false,
15348                                  /*use_default_args=*/false);
15349       if (converted_args == error_mark_node)
15350         return NULL_TREE;
15351
15352       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15353       if (decl_type == error_mark_node)
15354         return NULL_TREE;
15355     }
15356
15357   /* Never do unification on the 'this' parameter.  */
15358   decl_arg_types = skip_artificial_parms_for (decl, 
15359                                               TYPE_ARG_TYPES (decl_type));
15360
15361   nargs = list_length (decl_arg_types);
15362   args = XALLOCAVEC (tree, nargs);
15363   for (arg = decl_arg_types, ix = 0;
15364        arg != NULL_TREE && arg != void_list_node;
15365        arg = TREE_CHAIN (arg), ++ix)
15366     args[ix] = TREE_VALUE (arg);
15367
15368   if (fn_type_unification (fn, explicit_args, targs,
15369                            args, ix,
15370                            (check_rettype || DECL_CONV_FN_P (fn)
15371                             ? TREE_TYPE (decl_type) : NULL_TREE),
15372                            DEDUCE_EXACT, LOOKUP_NORMAL))
15373     return NULL_TREE;
15374
15375   return targs;
15376 }
15377
15378 /* Return the innermost template arguments that, when applied to a
15379    template specialization whose innermost template parameters are
15380    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15381    ARGS.
15382
15383    For example, suppose we have:
15384
15385      template <class T, class U> struct S {};
15386      template <class T> struct S<T*, int> {};
15387
15388    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15389    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15390    int}.  The resulting vector will be {double}, indicating that `T'
15391    is bound to `double'.  */
15392
15393 static tree
15394 get_class_bindings (tree tparms, tree spec_args, tree args)
15395 {
15396   int i, ntparms = TREE_VEC_LENGTH (tparms);
15397   tree deduced_args;
15398   tree innermost_deduced_args;
15399
15400   innermost_deduced_args = make_tree_vec (ntparms);
15401   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15402     {
15403       deduced_args = copy_node (args);
15404       SET_TMPL_ARGS_LEVEL (deduced_args,
15405                            TMPL_ARGS_DEPTH (deduced_args),
15406                            innermost_deduced_args);
15407     }
15408   else
15409     deduced_args = innermost_deduced_args;
15410
15411   if (unify (tparms, deduced_args,
15412              INNERMOST_TEMPLATE_ARGS (spec_args),
15413              INNERMOST_TEMPLATE_ARGS (args),
15414              UNIFY_ALLOW_NONE))
15415     return NULL_TREE;
15416
15417   for (i =  0; i < ntparms; ++i)
15418     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15419       return NULL_TREE;
15420
15421   /* Verify that nondeduced template arguments agree with the type
15422      obtained from argument deduction.
15423
15424      For example:
15425
15426        struct A { typedef int X; };
15427        template <class T, class U> struct C {};
15428        template <class T> struct C<T, typename T::X> {};
15429
15430      Then with the instantiation `C<A, int>', we can deduce that
15431      `T' is `A' but unify () does not check whether `typename T::X'
15432      is `int'.  */
15433   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15434   if (spec_args == error_mark_node
15435       /* We only need to check the innermost arguments; the other
15436          arguments will always agree.  */
15437       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15438                               INNERMOST_TEMPLATE_ARGS (args)))
15439     return NULL_TREE;
15440
15441   /* Now that we have bindings for all of the template arguments,
15442      ensure that the arguments deduced for the template template
15443      parameters have compatible template parameter lists.  See the use
15444      of template_template_parm_bindings_ok_p in fn_type_unification
15445      for more information.  */
15446   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15447     return NULL_TREE;
15448
15449   return deduced_args;
15450 }
15451
15452 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15453    Return the TREE_LIST node with the most specialized template, if
15454    any.  If there is no most specialized template, the error_mark_node
15455    is returned.
15456
15457    Note that this function does not look at, or modify, the
15458    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15459    returned is one of the elements of INSTANTIATIONS, callers may
15460    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15461    and retrieve it from the value returned.  */
15462
15463 tree
15464 most_specialized_instantiation (tree templates)
15465 {
15466   tree fn, champ;
15467
15468   ++processing_template_decl;
15469
15470   champ = templates;
15471   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15472     {
15473       int fate = 0;
15474
15475       if (get_bindings (TREE_VALUE (champ),
15476                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15477                         NULL_TREE, /*check_ret=*/false))
15478         fate--;
15479
15480       if (get_bindings (TREE_VALUE (fn),
15481                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15482                         NULL_TREE, /*check_ret=*/false))
15483         fate++;
15484
15485       if (fate == -1)
15486         champ = fn;
15487       else if (!fate)
15488         {
15489           /* Equally specialized, move to next function.  If there
15490              is no next function, nothing's most specialized.  */
15491           fn = TREE_CHAIN (fn);
15492           champ = fn;
15493           if (!fn)
15494             break;
15495         }
15496     }
15497
15498   if (champ)
15499     /* Now verify that champ is better than everything earlier in the
15500        instantiation list.  */
15501     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15502       if (get_bindings (TREE_VALUE (champ),
15503                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15504                         NULL_TREE, /*check_ret=*/false)
15505           || !get_bindings (TREE_VALUE (fn),
15506                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15507                             NULL_TREE, /*check_ret=*/false))
15508         {
15509           champ = NULL_TREE;
15510           break;
15511         }
15512
15513   processing_template_decl--;
15514
15515   if (!champ)
15516     return error_mark_node;
15517
15518   return champ;
15519 }
15520
15521 /* If DECL is a specialization of some template, return the most
15522    general such template.  Otherwise, returns NULL_TREE.
15523
15524    For example, given:
15525
15526      template <class T> struct S { template <class U> void f(U); };
15527
15528    if TMPL is `template <class U> void S<int>::f(U)' this will return
15529    the full template.  This function will not trace past partial
15530    specializations, however.  For example, given in addition:
15531
15532      template <class T> struct S<T*> { template <class U> void f(U); };
15533
15534    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15535    `template <class T> template <class U> S<T*>::f(U)'.  */
15536
15537 tree
15538 most_general_template (tree decl)
15539 {
15540   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15541      an immediate specialization.  */
15542   if (TREE_CODE (decl) == FUNCTION_DECL)
15543     {
15544       if (DECL_TEMPLATE_INFO (decl)) {
15545         decl = DECL_TI_TEMPLATE (decl);
15546
15547         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15548            template friend.  */
15549         if (TREE_CODE (decl) != TEMPLATE_DECL)
15550           return NULL_TREE;
15551       } else
15552         return NULL_TREE;
15553     }
15554
15555   /* Look for more and more general templates.  */
15556   while (DECL_TEMPLATE_INFO (decl))
15557     {
15558       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15559          (See cp-tree.h for details.)  */
15560       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15561         break;
15562
15563       if (CLASS_TYPE_P (TREE_TYPE (decl))
15564           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15565         break;
15566
15567       /* Stop if we run into an explicitly specialized class template.  */
15568       if (!DECL_NAMESPACE_SCOPE_P (decl)
15569           && DECL_CONTEXT (decl)
15570           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15571         break;
15572
15573       decl = DECL_TI_TEMPLATE (decl);
15574     }
15575
15576   return decl;
15577 }
15578
15579 /* Return the most specialized of the class template partial
15580    specializations of TMPL which can produce TYPE, a specialization of
15581    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15582    a _TYPE node corresponding to the partial specialization, while the
15583    TREE_PURPOSE is the set of template arguments that must be
15584    substituted into the TREE_TYPE in order to generate TYPE.
15585
15586    If the choice of partial specialization is ambiguous, a diagnostic
15587    is issued, and the error_mark_node is returned.  If there are no
15588    partial specializations of TMPL matching TYPE, then NULL_TREE is
15589    returned.  */
15590
15591 static tree
15592 most_specialized_class (tree type, tree tmpl)
15593 {
15594   tree list = NULL_TREE;
15595   tree t;
15596   tree champ;
15597   int fate;
15598   bool ambiguous_p;
15599   tree args;
15600   tree outer_args = NULL_TREE;
15601
15602   tmpl = most_general_template (tmpl);
15603   args = CLASSTYPE_TI_ARGS (type);
15604
15605   /* For determining which partial specialization to use, only the
15606      innermost args are interesting.  */
15607   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15608     {
15609       outer_args = strip_innermost_template_args (args, 1);
15610       args = INNERMOST_TEMPLATE_ARGS (args);
15611     }
15612
15613   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15614     {
15615       tree partial_spec_args;
15616       tree spec_args;
15617       tree parms = TREE_VALUE (t);
15618
15619       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15620       if (outer_args)
15621         {
15622           int i;
15623
15624           ++processing_template_decl;
15625
15626           /* Discard the outer levels of args, and then substitute in the
15627              template args from the enclosing class.  */
15628           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
15629           partial_spec_args = tsubst_template_args
15630             (partial_spec_args, outer_args, tf_none, NULL_TREE);
15631
15632           /* PARMS already refers to just the innermost parms, but the
15633              template parms in partial_spec_args had their levels lowered
15634              by tsubst, so we need to do the same for the parm list.  We
15635              can't just tsubst the TREE_VEC itself, as tsubst wants to
15636              treat a TREE_VEC as an argument vector.  */
15637           parms = copy_node (parms);
15638           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
15639             TREE_VEC_ELT (parms, i) =
15640               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
15641
15642           --processing_template_decl;
15643         }
15644       spec_args = get_class_bindings (parms,
15645                                       partial_spec_args,
15646                                       args);
15647       if (spec_args)
15648         {
15649           if (outer_args)
15650             spec_args = add_to_template_args (outer_args, spec_args);
15651           list = tree_cons (spec_args, TREE_VALUE (t), list);
15652           TREE_TYPE (list) = TREE_TYPE (t);
15653         }
15654     }
15655
15656   if (! list)
15657     return NULL_TREE;
15658
15659   ambiguous_p = false;
15660   t = list;
15661   champ = t;
15662   t = TREE_CHAIN (t);
15663   for (; t; t = TREE_CHAIN (t))
15664     {
15665       fate = more_specialized_class (champ, t);
15666       if (fate == 1)
15667         ;
15668       else
15669         {
15670           if (fate == 0)
15671             {
15672               t = TREE_CHAIN (t);
15673               if (! t)
15674                 {
15675                   ambiguous_p = true;
15676                   break;
15677                 }
15678             }
15679           champ = t;
15680         }
15681     }
15682
15683   if (!ambiguous_p)
15684     for (t = list; t && t != champ; t = TREE_CHAIN (t))
15685       {
15686         fate = more_specialized_class (champ, t);
15687         if (fate != 1)
15688           {
15689             ambiguous_p = true;
15690             break;
15691           }
15692       }
15693
15694   if (ambiguous_p)
15695     {
15696       const char *str = "candidates are:";
15697       error ("ambiguous class template instantiation for %q#T", type);
15698       for (t = list; t; t = TREE_CHAIN (t))
15699         {
15700           error ("%s %+#T", str, TREE_TYPE (t));
15701           str = "               ";
15702         }
15703       return error_mark_node;
15704     }
15705
15706   return champ;
15707 }
15708
15709 /* Explicitly instantiate DECL.  */
15710
15711 void
15712 do_decl_instantiation (tree decl, tree storage)
15713 {
15714   tree result = NULL_TREE;
15715   int extern_p = 0;
15716
15717   if (!decl || decl == error_mark_node)
15718     /* An error occurred, for which grokdeclarator has already issued
15719        an appropriate message.  */
15720     return;
15721   else if (! DECL_LANG_SPECIFIC (decl))
15722     {
15723       error ("explicit instantiation of non-template %q#D", decl);
15724       return;
15725     }
15726   else if (TREE_CODE (decl) == VAR_DECL)
15727     {
15728       /* There is an asymmetry here in the way VAR_DECLs and
15729          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
15730          the latter, the DECL we get back will be marked as a
15731          template instantiation, and the appropriate
15732          DECL_TEMPLATE_INFO will be set up.  This does not happen for
15733          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
15734          should handle VAR_DECLs as it currently handles
15735          FUNCTION_DECLs.  */
15736       if (!DECL_CLASS_SCOPE_P (decl))
15737         {
15738           error ("%qD is not a static data member of a class template", decl);
15739           return;
15740         }
15741       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
15742       if (!result || TREE_CODE (result) != VAR_DECL)
15743         {
15744           error ("no matching template for %qD found", decl);
15745           return;
15746         }
15747       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
15748         {
15749           error ("type %qT for explicit instantiation %qD does not match "
15750                  "declared type %qT", TREE_TYPE (result), decl,
15751                  TREE_TYPE (decl));
15752           return;
15753         }
15754     }
15755   else if (TREE_CODE (decl) != FUNCTION_DECL)
15756     {
15757       error ("explicit instantiation of %q#D", decl);
15758       return;
15759     }
15760   else
15761     result = decl;
15762
15763   /* Check for various error cases.  Note that if the explicit
15764      instantiation is valid the RESULT will currently be marked as an
15765      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
15766      until we get here.  */
15767
15768   if (DECL_TEMPLATE_SPECIALIZATION (result))
15769     {
15770       /* DR 259 [temp.spec].
15771
15772          Both an explicit instantiation and a declaration of an explicit
15773          specialization shall not appear in a program unless the explicit
15774          instantiation follows a declaration of the explicit specialization.
15775
15776          For a given set of template parameters, if an explicit
15777          instantiation of a template appears after a declaration of an
15778          explicit specialization for that template, the explicit
15779          instantiation has no effect.  */
15780       return;
15781     }
15782   else if (DECL_EXPLICIT_INSTANTIATION (result))
15783     {
15784       /* [temp.spec]
15785
15786          No program shall explicitly instantiate any template more
15787          than once.
15788
15789          We check DECL_NOT_REALLY_EXTERN so as not to complain when
15790          the first instantiation was `extern' and the second is not,
15791          and EXTERN_P for the opposite case.  */
15792       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
15793         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
15794       /* If an "extern" explicit instantiation follows an ordinary
15795          explicit instantiation, the template is instantiated.  */
15796       if (extern_p)
15797         return;
15798     }
15799   else if (!DECL_IMPLICIT_INSTANTIATION (result))
15800     {
15801       error ("no matching template for %qD found", result);
15802       return;
15803     }
15804   else if (!DECL_TEMPLATE_INFO (result))
15805     {
15806       permerror (input_location, "explicit instantiation of non-template %q#D", result);
15807       return;
15808     }
15809
15810   if (storage == NULL_TREE)
15811     ;
15812   else if (storage == ridpointers[(int) RID_EXTERN])
15813     {
15814       if (!in_system_header && (cxx_dialect == cxx98))
15815         pedwarn (input_location, OPT_pedantic, 
15816                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
15817                  "instantiations");
15818       extern_p = 1;
15819     }
15820   else
15821     error ("storage class %qD applied to template instantiation", storage);
15822
15823   check_explicit_instantiation_namespace (result);
15824   mark_decl_instantiated (result, extern_p);
15825   if (! extern_p)
15826     instantiate_decl (result, /*defer_ok=*/1,
15827                       /*expl_inst_class_mem_p=*/false);
15828 }
15829
15830 static void
15831 mark_class_instantiated (tree t, int extern_p)
15832 {
15833   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
15834   SET_CLASSTYPE_INTERFACE_KNOWN (t);
15835   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
15836   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
15837   if (! extern_p)
15838     {
15839       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
15840       rest_of_type_compilation (t, 1);
15841     }
15842 }
15843
15844 /* Called from do_type_instantiation through binding_table_foreach to
15845    do recursive instantiation for the type bound in ENTRY.  */
15846 static void
15847 bt_instantiate_type_proc (binding_entry entry, void *data)
15848 {
15849   tree storage = *(tree *) data;
15850
15851   if (MAYBE_CLASS_TYPE_P (entry->type)
15852       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
15853     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
15854 }
15855
15856 /* Called from do_type_instantiation to instantiate a member
15857    (a member function or a static member variable) of an
15858    explicitly instantiated class template.  */
15859 static void
15860 instantiate_class_member (tree decl, int extern_p)
15861 {
15862   mark_decl_instantiated (decl, extern_p);
15863   if (! extern_p)
15864     instantiate_decl (decl, /*defer_ok=*/1,
15865                       /*expl_inst_class_mem_p=*/true);
15866 }
15867
15868 /* Perform an explicit instantiation of template class T.  STORAGE, if
15869    non-null, is the RID for extern, inline or static.  COMPLAIN is
15870    nonzero if this is called from the parser, zero if called recursively,
15871    since the standard is unclear (as detailed below).  */
15872
15873 void
15874 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
15875 {
15876   int extern_p = 0;
15877   int nomem_p = 0;
15878   int static_p = 0;
15879   int previous_instantiation_extern_p = 0;
15880
15881   if (TREE_CODE (t) == TYPE_DECL)
15882     t = TREE_TYPE (t);
15883
15884   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
15885     {
15886       error ("explicit instantiation of non-template type %qT", t);
15887       return;
15888     }
15889
15890   complete_type (t);
15891
15892   if (!COMPLETE_TYPE_P (t))
15893     {
15894       if (complain & tf_error)
15895         error ("explicit instantiation of %q#T before definition of template",
15896                t);
15897       return;
15898     }
15899
15900   if (storage != NULL_TREE)
15901     {
15902       if (!in_system_header)
15903         {
15904           if (storage == ridpointers[(int) RID_EXTERN])
15905             {
15906               if (cxx_dialect == cxx98)
15907                 pedwarn (input_location, OPT_pedantic, 
15908                          "ISO C++ 1998 forbids the use of %<extern%> on "
15909                          "explicit instantiations");
15910             }
15911           else
15912             pedwarn (input_location, OPT_pedantic, 
15913                      "ISO C++ forbids the use of %qE"
15914                      " on explicit instantiations", storage);
15915         }
15916
15917       if (storage == ridpointers[(int) RID_INLINE])
15918         nomem_p = 1;
15919       else if (storage == ridpointers[(int) RID_EXTERN])
15920         extern_p = 1;
15921       else if (storage == ridpointers[(int) RID_STATIC])
15922         static_p = 1;
15923       else
15924         {
15925           error ("storage class %qD applied to template instantiation",
15926                  storage);
15927           extern_p = 0;
15928         }
15929     }
15930
15931   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
15932     {
15933       /* DR 259 [temp.spec].
15934
15935          Both an explicit instantiation and a declaration of an explicit
15936          specialization shall not appear in a program unless the explicit
15937          instantiation follows a declaration of the explicit specialization.
15938
15939          For a given set of template parameters, if an explicit
15940          instantiation of a template appears after a declaration of an
15941          explicit specialization for that template, the explicit
15942          instantiation has no effect.  */
15943       return;
15944     }
15945   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
15946     {
15947       /* [temp.spec]
15948
15949          No program shall explicitly instantiate any template more
15950          than once.
15951
15952          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
15953          instantiation was `extern'.  If EXTERN_P then the second is.
15954          These cases are OK.  */
15955       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
15956
15957       if (!previous_instantiation_extern_p && !extern_p
15958           && (complain & tf_error))
15959         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
15960
15961       /* If we've already instantiated the template, just return now.  */
15962       if (!CLASSTYPE_INTERFACE_ONLY (t))
15963         return;
15964     }
15965
15966   check_explicit_instantiation_namespace (TYPE_NAME (t));
15967   mark_class_instantiated (t, extern_p);
15968
15969   if (nomem_p)
15970     return;
15971
15972   {
15973     tree tmp;
15974
15975     /* In contrast to implicit instantiation, where only the
15976        declarations, and not the definitions, of members are
15977        instantiated, we have here:
15978
15979          [temp.explicit]
15980
15981          The explicit instantiation of a class template specialization
15982          implies the instantiation of all of its members not
15983          previously explicitly specialized in the translation unit
15984          containing the explicit instantiation.
15985
15986        Of course, we can't instantiate member template classes, since
15987        we don't have any arguments for them.  Note that the standard
15988        is unclear on whether the instantiation of the members are
15989        *explicit* instantiations or not.  However, the most natural
15990        interpretation is that it should be an explicit instantiation.  */
15991
15992     if (! static_p)
15993       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
15994         if (TREE_CODE (tmp) == FUNCTION_DECL
15995             && DECL_TEMPLATE_INSTANTIATION (tmp))
15996           instantiate_class_member (tmp, extern_p);
15997
15998     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
15999       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16000         instantiate_class_member (tmp, extern_p);
16001
16002     if (CLASSTYPE_NESTED_UTDS (t))
16003       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16004                              bt_instantiate_type_proc, &storage);
16005   }
16006 }
16007
16008 /* Given a function DECL, which is a specialization of TMPL, modify
16009    DECL to be a re-instantiation of TMPL with the same template
16010    arguments.  TMPL should be the template into which tsubst'ing
16011    should occur for DECL, not the most general template.
16012
16013    One reason for doing this is a scenario like this:
16014
16015      template <class T>
16016      void f(const T&, int i);
16017
16018      void g() { f(3, 7); }
16019
16020      template <class T>
16021      void f(const T& t, const int i) { }
16022
16023    Note that when the template is first instantiated, with
16024    instantiate_template, the resulting DECL will have no name for the
16025    first parameter, and the wrong type for the second.  So, when we go
16026    to instantiate the DECL, we regenerate it.  */
16027
16028 static void
16029 regenerate_decl_from_template (tree decl, tree tmpl)
16030 {
16031   /* The arguments used to instantiate DECL, from the most general
16032      template.  */
16033   tree args;
16034   tree code_pattern;
16035
16036   args = DECL_TI_ARGS (decl);
16037   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16038
16039   /* Make sure that we can see identifiers, and compute access
16040      correctly.  */
16041   push_access_scope (decl);
16042
16043   if (TREE_CODE (decl) == FUNCTION_DECL)
16044     {
16045       tree decl_parm;
16046       tree pattern_parm;
16047       tree specs;
16048       int args_depth;
16049       int parms_depth;
16050
16051       args_depth = TMPL_ARGS_DEPTH (args);
16052       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16053       if (args_depth > parms_depth)
16054         args = get_innermost_template_args (args, parms_depth);
16055
16056       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16057                                               args, tf_error, NULL_TREE);
16058       if (specs)
16059         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16060                                                     specs);
16061
16062       /* Merge parameter declarations.  */
16063       decl_parm = skip_artificial_parms_for (decl,
16064                                              DECL_ARGUMENTS (decl));
16065       pattern_parm
16066         = skip_artificial_parms_for (code_pattern,
16067                                      DECL_ARGUMENTS (code_pattern));
16068       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16069         {
16070           tree parm_type;
16071           tree attributes;
16072           
16073           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16074             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16075           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16076                               NULL_TREE);
16077           parm_type = type_decays_to (parm_type);
16078           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16079             TREE_TYPE (decl_parm) = parm_type;
16080           attributes = DECL_ATTRIBUTES (pattern_parm);
16081           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16082             {
16083               DECL_ATTRIBUTES (decl_parm) = attributes;
16084               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16085             }
16086           decl_parm = TREE_CHAIN (decl_parm);
16087           pattern_parm = TREE_CHAIN (pattern_parm);
16088         }
16089       /* Merge any parameters that match with the function parameter
16090          pack.  */
16091       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16092         {
16093           int i, len;
16094           tree expanded_types;
16095           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16096              the parameters in this function parameter pack.  */
16097           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16098                                                  args, tf_error, NULL_TREE);
16099           len = TREE_VEC_LENGTH (expanded_types);
16100           for (i = 0; i < len; i++)
16101             {
16102               tree parm_type;
16103               tree attributes;
16104           
16105               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16106                 /* Rename the parameter to include the index.  */
16107                 DECL_NAME (decl_parm) = 
16108                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16109               parm_type = TREE_VEC_ELT (expanded_types, i);
16110               parm_type = type_decays_to (parm_type);
16111               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16112                 TREE_TYPE (decl_parm) = parm_type;
16113               attributes = DECL_ATTRIBUTES (pattern_parm);
16114               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16115                 {
16116                   DECL_ATTRIBUTES (decl_parm) = attributes;
16117                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16118                 }
16119               decl_parm = TREE_CHAIN (decl_parm);
16120             }
16121         }
16122       /* Merge additional specifiers from the CODE_PATTERN.  */
16123       if (DECL_DECLARED_INLINE_P (code_pattern)
16124           && !DECL_DECLARED_INLINE_P (decl))
16125         DECL_DECLARED_INLINE_P (decl) = 1;
16126     }
16127   else if (TREE_CODE (decl) == VAR_DECL)
16128     DECL_INITIAL (decl) =
16129       tsubst_expr (DECL_INITIAL (code_pattern), args,
16130                    tf_error, DECL_TI_TEMPLATE (decl),
16131                    /*integral_constant_expression_p=*/false);
16132   else
16133     gcc_unreachable ();
16134
16135   pop_access_scope (decl);
16136 }
16137
16138 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16139    substituted to get DECL.  */
16140
16141 tree
16142 template_for_substitution (tree decl)
16143 {
16144   tree tmpl = DECL_TI_TEMPLATE (decl);
16145
16146   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16147      for the instantiation.  This is not always the most general
16148      template.  Consider, for example:
16149
16150         template <class T>
16151         struct S { template <class U> void f();
16152                    template <> void f<int>(); };
16153
16154      and an instantiation of S<double>::f<int>.  We want TD to be the
16155      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16156   while (/* An instantiation cannot have a definition, so we need a
16157             more general template.  */
16158          DECL_TEMPLATE_INSTANTIATION (tmpl)
16159            /* We must also deal with friend templates.  Given:
16160
16161                 template <class T> struct S {
16162                   template <class U> friend void f() {};
16163                 };
16164
16165               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16166               so far as the language is concerned, but that's still
16167               where we get the pattern for the instantiation from.  On
16168               other hand, if the definition comes outside the class, say:
16169
16170                 template <class T> struct S {
16171                   template <class U> friend void f();
16172                 };
16173                 template <class U> friend void f() {}
16174
16175               we don't need to look any further.  That's what the check for
16176               DECL_INITIAL is for.  */
16177           || (TREE_CODE (decl) == FUNCTION_DECL
16178               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16179               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16180     {
16181       /* The present template, TD, should not be a definition.  If it
16182          were a definition, we should be using it!  Note that we
16183          cannot restructure the loop to just keep going until we find
16184          a template with a definition, since that might go too far if
16185          a specialization was declared, but not defined.  */
16186       gcc_assert (TREE_CODE (decl) != VAR_DECL
16187                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16188
16189       /* Fetch the more general template.  */
16190       tmpl = DECL_TI_TEMPLATE (tmpl);
16191     }
16192
16193   return tmpl;
16194 }
16195
16196 /* Returns true if we need to instantiate this template instance even if we
16197    know we aren't going to emit it..  */
16198
16199 bool
16200 always_instantiate_p (tree decl)
16201 {
16202   /* We always instantiate inline functions so that we can inline them.  An
16203      explicit instantiation declaration prohibits implicit instantiation of
16204      non-inline functions.  With high levels of optimization, we would
16205      normally inline non-inline functions -- but we're not allowed to do
16206      that for "extern template" functions.  Therefore, we check
16207      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16208   return ((TREE_CODE (decl) == FUNCTION_DECL
16209            && DECL_DECLARED_INLINE_P (decl))
16210           /* And we need to instantiate static data members so that
16211              their initializers are available in integral constant
16212              expressions.  */
16213           || (TREE_CODE (decl) == VAR_DECL
16214               && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16215 }
16216
16217 /* Produce the definition of D, a _DECL generated from a template.  If
16218    DEFER_OK is nonzero, then we don't have to actually do the
16219    instantiation now; we just have to do it sometime.  Normally it is
16220    an error if this is an explicit instantiation but D is undefined.
16221    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16222    explicitly instantiated class template.  */
16223
16224 tree
16225 instantiate_decl (tree d, int defer_ok,
16226                   bool expl_inst_class_mem_p)
16227 {
16228   tree tmpl = DECL_TI_TEMPLATE (d);
16229   tree gen_args;
16230   tree args;
16231   tree td;
16232   tree code_pattern;
16233   tree spec;
16234   tree gen_tmpl;
16235   bool pattern_defined;
16236   int need_push;
16237   location_t saved_loc = input_location;
16238   bool external_p;
16239
16240   /* This function should only be used to instantiate templates for
16241      functions and static member variables.  */
16242   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16243               || TREE_CODE (d) == VAR_DECL);
16244
16245   /* Variables are never deferred; if instantiation is required, they
16246      are instantiated right away.  That allows for better code in the
16247      case that an expression refers to the value of the variable --
16248      if the variable has a constant value the referring expression can
16249      take advantage of that fact.  */
16250   if (TREE_CODE (d) == VAR_DECL)
16251     defer_ok = 0;
16252
16253   /* Don't instantiate cloned functions.  Instead, instantiate the
16254      functions they cloned.  */
16255   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16256     d = DECL_CLONED_FUNCTION (d);
16257
16258   if (DECL_TEMPLATE_INSTANTIATED (d)
16259       || DECL_TEMPLATE_SPECIALIZATION (d))
16260     /* D has already been instantiated or explicitly specialized, so
16261        there's nothing for us to do here.
16262
16263        It might seem reasonable to check whether or not D is an explicit
16264        instantiation, and, if so, stop here.  But when an explicit
16265        instantiation is deferred until the end of the compilation,
16266        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16267        the instantiation.  */
16268     return d;
16269
16270   /* Check to see whether we know that this template will be
16271      instantiated in some other file, as with "extern template"
16272      extension.  */
16273   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16274
16275   /* In general, we do not instantiate such templates.  */
16276   if (external_p && !always_instantiate_p (d))
16277     return d;
16278
16279   gen_tmpl = most_general_template (tmpl);
16280   gen_args = DECL_TI_ARGS (d);
16281
16282   if (tmpl != gen_tmpl)
16283     /* We should already have the extra args.  */
16284     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16285                 == TMPL_ARGS_DEPTH (gen_args));
16286   /* And what's in the hash table should match D.  */
16287   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16288               || spec == NULL_TREE);
16289
16290   /* This needs to happen before any tsubsting.  */
16291   if (! push_tinst_level (d))
16292     return d;
16293
16294   timevar_push (TV_PARSE);
16295
16296   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16297      for the instantiation.  */
16298   td = template_for_substitution (d);
16299   code_pattern = DECL_TEMPLATE_RESULT (td);
16300
16301   /* We should never be trying to instantiate a member of a class
16302      template or partial specialization.  */
16303   gcc_assert (d != code_pattern);
16304
16305   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16306       || DECL_TEMPLATE_SPECIALIZATION (td))
16307     /* In the case of a friend template whose definition is provided
16308        outside the class, we may have too many arguments.  Drop the
16309        ones we don't need.  The same is true for specializations.  */
16310     args = get_innermost_template_args
16311       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16312   else
16313     args = gen_args;
16314
16315   if (TREE_CODE (d) == FUNCTION_DECL)
16316     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16317   else
16318     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16319
16320   /* We may be in the middle of deferred access check.  Disable it now.  */
16321   push_deferring_access_checks (dk_no_deferred);
16322
16323   /* Unless an explicit instantiation directive has already determined
16324      the linkage of D, remember that a definition is available for
16325      this entity.  */
16326   if (pattern_defined
16327       && !DECL_INTERFACE_KNOWN (d)
16328       && !DECL_NOT_REALLY_EXTERN (d))
16329     mark_definable (d);
16330
16331   input_location = DECL_SOURCE_LOCATION (d);
16332
16333   /* If D is a member of an explicitly instantiated class template,
16334      and no definition is available, treat it like an implicit
16335      instantiation.  */
16336   if (!pattern_defined && expl_inst_class_mem_p
16337       && DECL_EXPLICIT_INSTANTIATION (d))
16338     {
16339       DECL_NOT_REALLY_EXTERN (d) = 0;
16340       DECL_INTERFACE_KNOWN (d) = 0;
16341       SET_DECL_IMPLICIT_INSTANTIATION (d);
16342     }
16343
16344   /* Recheck the substitutions to obtain any warning messages
16345      about ignoring cv qualifiers.  Don't do this for artificial decls,
16346      as it breaks the context-sensitive substitution for lambda op(). */
16347   if (!defer_ok && !DECL_ARTIFICIAL (d))
16348     {
16349       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16350       tree type = TREE_TYPE (gen);
16351
16352       /* Make sure that we can see identifiers, and compute access
16353          correctly.  D is already the target FUNCTION_DECL with the
16354          right context.  */
16355       push_access_scope (d);
16356
16357       if (TREE_CODE (gen) == FUNCTION_DECL)
16358         {
16359           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16360           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16361                                           d);
16362           /* Don't simply tsubst the function type, as that will give
16363              duplicate warnings about poor parameter qualifications.
16364              The function arguments are the same as the decl_arguments
16365              without the top level cv qualifiers.  */
16366           type = TREE_TYPE (type);
16367         }
16368       tsubst (type, gen_args, tf_warning_or_error, d);
16369
16370       pop_access_scope (d);
16371     }
16372
16373   /* Defer all other templates, unless we have been explicitly
16374      forbidden from doing so.  */
16375   if (/* If there is no definition, we cannot instantiate the
16376          template.  */
16377       ! pattern_defined
16378       /* If it's OK to postpone instantiation, do so.  */
16379       || defer_ok
16380       /* If this is a static data member that will be defined
16381          elsewhere, we don't want to instantiate the entire data
16382          member, but we do want to instantiate the initializer so that
16383          we can substitute that elsewhere.  */
16384       || (external_p && TREE_CODE (d) == VAR_DECL))
16385     {
16386       /* The definition of the static data member is now required so
16387          we must substitute the initializer.  */
16388       if (TREE_CODE (d) == VAR_DECL
16389           && !DECL_INITIAL (d)
16390           && DECL_INITIAL (code_pattern))
16391         {
16392           tree ns;
16393           tree init;
16394
16395           ns = decl_namespace_context (d);
16396           push_nested_namespace (ns);
16397           push_nested_class (DECL_CONTEXT (d));
16398           init = tsubst_expr (DECL_INITIAL (code_pattern),
16399                               args,
16400                               tf_warning_or_error, NULL_TREE,
16401                               /*integral_constant_expression_p=*/false);
16402           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16403                           /*asmspec_tree=*/NULL_TREE,
16404                           LOOKUP_ONLYCONVERTING);
16405           pop_nested_class ();
16406           pop_nested_namespace (ns);
16407         }
16408
16409       /* We restore the source position here because it's used by
16410          add_pending_template.  */
16411       input_location = saved_loc;
16412
16413       if (at_eof && !pattern_defined
16414           && DECL_EXPLICIT_INSTANTIATION (d)
16415           && DECL_NOT_REALLY_EXTERN (d))
16416         /* [temp.explicit]
16417
16418            The definition of a non-exported function template, a
16419            non-exported member function template, or a non-exported
16420            member function or static data member of a class template
16421            shall be present in every translation unit in which it is
16422            explicitly instantiated.  */
16423         permerror (input_location,  "explicit instantiation of %qD "
16424                    "but no definition available", d);
16425
16426       /* ??? Historically, we have instantiated inline functions, even
16427          when marked as "extern template".  */
16428       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16429         add_pending_template (d);
16430       goto out;
16431     }
16432   /* Tell the repository that D is available in this translation unit
16433      -- and see if it is supposed to be instantiated here.  */
16434   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16435     {
16436       /* In a PCH file, despite the fact that the repository hasn't
16437          requested instantiation in the PCH it is still possible that
16438          an instantiation will be required in a file that includes the
16439          PCH.  */
16440       if (pch_file)
16441         add_pending_template (d);
16442       /* Instantiate inline functions so that the inliner can do its
16443          job, even though we'll not be emitting a copy of this
16444          function.  */
16445       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16446         goto out;
16447     }
16448
16449   need_push = !cfun || !global_bindings_p ();
16450   if (need_push)
16451     push_to_top_level ();
16452
16453   /* Mark D as instantiated so that recursive calls to
16454      instantiate_decl do not try to instantiate it again.  */
16455   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16456
16457   /* Regenerate the declaration in case the template has been modified
16458      by a subsequent redeclaration.  */
16459   regenerate_decl_from_template (d, td);
16460
16461   /* We already set the file and line above.  Reset them now in case
16462      they changed as a result of calling regenerate_decl_from_template.  */
16463   input_location = DECL_SOURCE_LOCATION (d);
16464
16465   if (TREE_CODE (d) == VAR_DECL)
16466     {
16467       tree init;
16468
16469       /* Clear out DECL_RTL; whatever was there before may not be right
16470          since we've reset the type of the declaration.  */
16471       SET_DECL_RTL (d, NULL_RTX);
16472       DECL_IN_AGGR_P (d) = 0;
16473
16474       /* The initializer is placed in DECL_INITIAL by
16475          regenerate_decl_from_template.  Pull it out so that
16476          cp_finish_decl can process it.  */
16477       init = DECL_INITIAL (d);
16478       DECL_INITIAL (d) = NULL_TREE;
16479       DECL_INITIALIZED_P (d) = 0;
16480
16481       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16482          initializer.  That function will defer actual emission until
16483          we have a chance to determine linkage.  */
16484       DECL_EXTERNAL (d) = 0;
16485
16486       /* Enter the scope of D so that access-checking works correctly.  */
16487       push_nested_class (DECL_CONTEXT (d));
16488       cp_finish_decl (d, init, false, NULL_TREE, 0);
16489       pop_nested_class ();
16490     }
16491   else if (TREE_CODE (d) == FUNCTION_DECL)
16492     {
16493       htab_t saved_local_specializations;
16494       tree subst_decl;
16495       tree tmpl_parm;
16496       tree spec_parm;
16497
16498       /* Save away the current list, in case we are instantiating one
16499          template from within the body of another.  */
16500       saved_local_specializations = local_specializations;
16501
16502       /* Set up the list of local specializations.  */
16503       local_specializations = htab_create (37,
16504                                            hash_local_specialization,
16505                                            eq_local_specializations,
16506                                            NULL);
16507
16508       /* Set up context.  */
16509       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16510
16511       /* Create substitution entries for the parameters.  */
16512       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16513       tmpl_parm = DECL_ARGUMENTS (subst_decl);
16514       spec_parm = DECL_ARGUMENTS (d);
16515       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16516         {
16517           register_local_specialization (spec_parm, tmpl_parm);
16518           spec_parm = skip_artificial_parms_for (d, spec_parm);
16519           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16520         }
16521       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16522         {
16523           register_local_specialization (spec_parm, tmpl_parm);
16524           tmpl_parm = TREE_CHAIN (tmpl_parm);
16525           spec_parm = TREE_CHAIN (spec_parm);
16526         }
16527       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16528         {
16529           /* Register the (value) argument pack as a specialization of
16530              TMPL_PARM, then move on.  */
16531           tree argpack = make_fnparm_pack (spec_parm);
16532           register_local_specialization (argpack, tmpl_parm);
16533           tmpl_parm = TREE_CHAIN (tmpl_parm);
16534           spec_parm = NULL_TREE;
16535         }
16536       gcc_assert (!spec_parm);
16537
16538       /* Substitute into the body of the function.  */
16539       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16540                    tf_warning_or_error, tmpl,
16541                    /*integral_constant_expression_p=*/false);
16542
16543       /* Set the current input_location to the end of the function
16544          so that finish_function knows where we are.  */
16545       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16546
16547       /* We don't need the local specializations any more.  */
16548       htab_delete (local_specializations);
16549       local_specializations = saved_local_specializations;
16550
16551       /* Finish the function.  */
16552       d = finish_function (0);
16553       expand_or_defer_fn (d);
16554     }
16555
16556   /* We're not deferring instantiation any more.  */
16557   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16558
16559   if (need_push)
16560     pop_from_top_level ();
16561
16562 out:
16563   input_location = saved_loc;
16564   pop_deferring_access_checks ();
16565   pop_tinst_level ();
16566
16567   timevar_pop (TV_PARSE);
16568
16569   return d;
16570 }
16571
16572 /* Run through the list of templates that we wish we could
16573    instantiate, and instantiate any we can.  RETRIES is the
16574    number of times we retry pending template instantiation.  */
16575
16576 void
16577 instantiate_pending_templates (int retries)
16578 {
16579   int reconsider;
16580   location_t saved_loc = input_location;
16581
16582   /* Instantiating templates may trigger vtable generation.  This in turn
16583      may require further template instantiations.  We place a limit here
16584      to avoid infinite loop.  */
16585   if (pending_templates && retries >= max_tinst_depth)
16586     {
16587       tree decl = pending_templates->tinst->decl;
16588
16589       error ("template instantiation depth exceeds maximum of %d"
16590              " instantiating %q+D, possibly from virtual table generation"
16591              " (use -ftemplate-depth-NN to increase the maximum)",
16592              max_tinst_depth, decl);
16593       if (TREE_CODE (decl) == FUNCTION_DECL)
16594         /* Pretend that we defined it.  */
16595         DECL_INITIAL (decl) = error_mark_node;
16596       return;
16597     }
16598
16599   do
16600     {
16601       struct pending_template **t = &pending_templates;
16602       struct pending_template *last = NULL;
16603       reconsider = 0;
16604       while (*t)
16605         {
16606           tree instantiation = reopen_tinst_level ((*t)->tinst);
16607           bool complete = false;
16608
16609           if (TYPE_P (instantiation))
16610             {
16611               tree fn;
16612
16613               if (!COMPLETE_TYPE_P (instantiation))
16614                 {
16615                   instantiate_class_template (instantiation);
16616                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
16617                     for (fn = TYPE_METHODS (instantiation);
16618                          fn;
16619                          fn = TREE_CHAIN (fn))
16620                       if (! DECL_ARTIFICIAL (fn))
16621                         instantiate_decl (fn,
16622                                           /*defer_ok=*/0,
16623                                           /*expl_inst_class_mem_p=*/false);
16624                   if (COMPLETE_TYPE_P (instantiation))
16625                     reconsider = 1;
16626                 }
16627
16628               complete = COMPLETE_TYPE_P (instantiation);
16629             }
16630           else
16631             {
16632               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
16633                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
16634                 {
16635                   instantiation
16636                     = instantiate_decl (instantiation,
16637                                         /*defer_ok=*/0,
16638                                         /*expl_inst_class_mem_p=*/false);
16639                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
16640                     reconsider = 1;
16641                 }
16642
16643               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
16644                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
16645             }
16646
16647           if (complete)
16648             /* If INSTANTIATION has been instantiated, then we don't
16649                need to consider it again in the future.  */
16650             *t = (*t)->next;
16651           else
16652             {
16653               last = *t;
16654               t = &(*t)->next;
16655             }
16656           tinst_depth = 0;
16657           current_tinst_level = NULL;
16658         }
16659       last_pending_template = last;
16660     }
16661   while (reconsider);
16662
16663   input_location = saved_loc;
16664 }
16665
16666 /* Substitute ARGVEC into T, which is a list of initializers for
16667    either base class or a non-static data member.  The TREE_PURPOSEs
16668    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
16669    instantiate_decl.  */
16670
16671 static tree
16672 tsubst_initializer_list (tree t, tree argvec)
16673 {
16674   tree inits = NULL_TREE;
16675
16676   for (; t; t = TREE_CHAIN (t))
16677     {
16678       tree decl;
16679       tree init;
16680       tree expanded_bases = NULL_TREE;
16681       tree expanded_arguments = NULL_TREE;
16682       int i, len = 1;
16683
16684       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
16685         {
16686           tree expr;
16687           tree arg;
16688
16689           /* Expand the base class expansion type into separate base
16690              classes.  */
16691           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
16692                                                  tf_warning_or_error,
16693                                                  NULL_TREE);
16694           if (expanded_bases == error_mark_node)
16695             continue;
16696           
16697           /* We'll be building separate TREE_LISTs of arguments for
16698              each base.  */
16699           len = TREE_VEC_LENGTH (expanded_bases);
16700           expanded_arguments = make_tree_vec (len);
16701           for (i = 0; i < len; i++)
16702             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
16703
16704           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
16705              expand each argument in the TREE_VALUE of t.  */
16706           expr = make_node (EXPR_PACK_EXPANSION);
16707           PACK_EXPANSION_PARAMETER_PACKS (expr) =
16708             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
16709
16710           if (TREE_VALUE (t) == void_type_node)
16711             /* VOID_TYPE_NODE is used to indicate
16712                value-initialization.  */
16713             {
16714               for (i = 0; i < len; i++)
16715                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
16716             }
16717           else
16718             {
16719               /* Substitute parameter packs into each argument in the
16720                  TREE_LIST.  */
16721               in_base_initializer = 1;
16722               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
16723                 {
16724                   tree expanded_exprs;
16725
16726                   /* Expand the argument.  */
16727                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
16728                   expanded_exprs 
16729                     = tsubst_pack_expansion (expr, argvec,
16730                                              tf_warning_or_error,
16731                                              NULL_TREE);
16732                   if (expanded_exprs == error_mark_node)
16733                     continue;
16734
16735                   /* Prepend each of the expanded expressions to the
16736                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
16737                   for (i = 0; i < len; i++)
16738                     {
16739                       TREE_VEC_ELT (expanded_arguments, i) = 
16740                         tree_cons (NULL_TREE, 
16741                                    TREE_VEC_ELT (expanded_exprs, i),
16742                                    TREE_VEC_ELT (expanded_arguments, i));
16743                     }
16744                 }
16745               in_base_initializer = 0;
16746
16747               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
16748                  since we built them backwards.  */
16749               for (i = 0; i < len; i++)
16750                 {
16751                   TREE_VEC_ELT (expanded_arguments, i) = 
16752                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
16753                 }
16754             }
16755         }
16756
16757       for (i = 0; i < len; ++i)
16758         {
16759           if (expanded_bases)
16760             {
16761               decl = TREE_VEC_ELT (expanded_bases, i);
16762               decl = expand_member_init (decl);
16763               init = TREE_VEC_ELT (expanded_arguments, i);
16764             }
16765           else
16766             {
16767               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
16768                                   tf_warning_or_error, NULL_TREE);
16769
16770               decl = expand_member_init (decl);
16771               if (decl && !DECL_P (decl))
16772                 in_base_initializer = 1;
16773
16774               init = tsubst_expr (TREE_VALUE (t), argvec, 
16775                                   tf_warning_or_error, NULL_TREE,
16776                                   /*integral_constant_expression_p=*/false);
16777               in_base_initializer = 0;
16778             }
16779
16780           if (decl)
16781             {
16782               init = build_tree_list (decl, init);
16783               TREE_CHAIN (init) = inits;
16784               inits = init;
16785             }
16786         }
16787     }
16788   return inits;
16789 }
16790
16791 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
16792
16793 static void
16794 set_current_access_from_decl (tree decl)
16795 {
16796   if (TREE_PRIVATE (decl))
16797     current_access_specifier = access_private_node;
16798   else if (TREE_PROTECTED (decl))
16799     current_access_specifier = access_protected_node;
16800   else
16801     current_access_specifier = access_public_node;
16802 }
16803
16804 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
16805    is the instantiation (which should have been created with
16806    start_enum) and ARGS are the template arguments to use.  */
16807
16808 static void
16809 tsubst_enum (tree tag, tree newtag, tree args)
16810 {
16811   tree e;
16812
16813   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
16814     {
16815       tree value;
16816       tree decl;
16817
16818       decl = TREE_VALUE (e);
16819       /* Note that in a template enum, the TREE_VALUE is the
16820          CONST_DECL, not the corresponding INTEGER_CST.  */
16821       value = tsubst_expr (DECL_INITIAL (decl),
16822                            args, tf_warning_or_error, NULL_TREE,
16823                            /*integral_constant_expression_p=*/true);
16824
16825       /* Give this enumeration constant the correct access.  */
16826       set_current_access_from_decl (decl);
16827
16828       /* Actually build the enumerator itself.  */
16829       build_enumerator (DECL_NAME (decl), value, newtag);
16830     }
16831
16832   finish_enum (newtag);
16833   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
16834     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
16835 }
16836
16837 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
16838    its type -- but without substituting the innermost set of template
16839    arguments.  So, innermost set of template parameters will appear in
16840    the type.  */
16841
16842 tree
16843 get_mostly_instantiated_function_type (tree decl)
16844 {
16845   tree fn_type;
16846   tree tmpl;
16847   tree targs;
16848   tree tparms;
16849   int parm_depth;
16850
16851   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16852   targs = DECL_TI_ARGS (decl);
16853   tparms = DECL_TEMPLATE_PARMS (tmpl);
16854   parm_depth = TMPL_PARMS_DEPTH (tparms);
16855
16856   /* There should be as many levels of arguments as there are levels
16857      of parameters.  */
16858   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
16859
16860   fn_type = TREE_TYPE (tmpl);
16861
16862   if (parm_depth == 1)
16863     /* No substitution is necessary.  */
16864     ;
16865   else
16866     {
16867       int i, save_access_control;
16868       tree partial_args;
16869
16870       /* Replace the innermost level of the TARGS with NULL_TREEs to
16871          let tsubst know not to substitute for those parameters.  */
16872       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
16873       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
16874         SET_TMPL_ARGS_LEVEL (partial_args, i,
16875                              TMPL_ARGS_LEVEL (targs, i));
16876       SET_TMPL_ARGS_LEVEL (partial_args,
16877                            TMPL_ARGS_DEPTH (targs),
16878                            make_tree_vec (DECL_NTPARMS (tmpl)));
16879
16880       /* Disable access control as this function is used only during
16881          name-mangling.  */
16882       save_access_control = flag_access_control;
16883       flag_access_control = 0;
16884
16885       ++processing_template_decl;
16886       /* Now, do the (partial) substitution to figure out the
16887          appropriate function type.  */
16888       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
16889       --processing_template_decl;
16890
16891       /* Substitute into the template parameters to obtain the real
16892          innermost set of parameters.  This step is important if the
16893          innermost set of template parameters contains value
16894          parameters whose types depend on outer template parameters.  */
16895       TREE_VEC_LENGTH (partial_args)--;
16896       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
16897
16898       flag_access_control = save_access_control;
16899     }
16900
16901   return fn_type;
16902 }
16903
16904 /* Return truthvalue if we're processing a template different from
16905    the last one involved in diagnostics.  */
16906 int
16907 problematic_instantiation_changed (void)
16908 {
16909   return last_template_error_tick != tinst_level_tick;
16910 }
16911
16912 /* Remember current template involved in diagnostics.  */
16913 void
16914 record_last_problematic_instantiation (void)
16915 {
16916   last_template_error_tick = tinst_level_tick;
16917 }
16918
16919 struct tinst_level *
16920 current_instantiation (void)
16921 {
16922   return current_tinst_level;
16923 }
16924
16925 /* [temp.param] Check that template non-type parm TYPE is of an allowable
16926    type. Return zero for ok, nonzero for disallowed. Issue error and
16927    warning messages under control of COMPLAIN.  */
16928
16929 static int
16930 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
16931 {
16932   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
16933     return 0;
16934   else if (POINTER_TYPE_P (type))
16935     return 0;
16936   else if (TYPE_PTR_TO_MEMBER_P (type))
16937     return 0;
16938   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16939     return 0;
16940   else if (TREE_CODE (type) == TYPENAME_TYPE)
16941     return 0;
16942
16943   if (complain & tf_error)
16944     error ("%q#T is not a valid type for a template constant parameter", type);
16945   return 1;
16946 }
16947
16948 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
16949    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
16950
16951 static bool
16952 dependent_type_p_r (tree type)
16953 {
16954   tree scope;
16955
16956   /* [temp.dep.type]
16957
16958      A type is dependent if it is:
16959
16960      -- a template parameter. Template template parameters are types
16961         for us (since TYPE_P holds true for them) so we handle
16962         them here.  */
16963   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16964       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
16965     return true;
16966   /* -- a qualified-id with a nested-name-specifier which contains a
16967         class-name that names a dependent type or whose unqualified-id
16968         names a dependent type.  */
16969   if (TREE_CODE (type) == TYPENAME_TYPE)
16970     return true;
16971   /* -- a cv-qualified type where the cv-unqualified type is
16972         dependent.  */
16973   type = TYPE_MAIN_VARIANT (type);
16974   /* -- a compound type constructed from any dependent type.  */
16975   if (TYPE_PTR_TO_MEMBER_P (type))
16976     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
16977             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
16978                                            (type)));
16979   else if (TREE_CODE (type) == POINTER_TYPE
16980            || TREE_CODE (type) == REFERENCE_TYPE)
16981     return dependent_type_p (TREE_TYPE (type));
16982   else if (TREE_CODE (type) == FUNCTION_TYPE
16983            || TREE_CODE (type) == METHOD_TYPE)
16984     {
16985       tree arg_type;
16986
16987       if (dependent_type_p (TREE_TYPE (type)))
16988         return true;
16989       for (arg_type = TYPE_ARG_TYPES (type);
16990            arg_type;
16991            arg_type = TREE_CHAIN (arg_type))
16992         if (dependent_type_p (TREE_VALUE (arg_type)))
16993           return true;
16994       return false;
16995     }
16996   /* -- an array type constructed from any dependent type or whose
16997         size is specified by a constant expression that is
16998         value-dependent.  */
16999   if (TREE_CODE (type) == ARRAY_TYPE)
17000     {
17001       if (TYPE_DOMAIN (type)
17002           && dependent_type_p (TYPE_DOMAIN (type)))
17003         return true;
17004       return dependent_type_p (TREE_TYPE (type));
17005     }
17006   else if (TREE_CODE (type) == INTEGER_TYPE
17007            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
17008     {
17009       /* If this is the TYPE_DOMAIN of an array type, consider it
17010          dependent.  We already checked for value-dependence in
17011          compute_array_index_type.  */
17012       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
17013     }
17014
17015   /* -- a template-id in which either the template name is a template
17016      parameter ...  */
17017   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17018     return true;
17019   /* ... or any of the template arguments is a dependent type or
17020         an expression that is type-dependent or value-dependent.  */
17021   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17022            && (any_dependent_template_arguments_p
17023                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17024     return true;
17025
17026   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17027      argument of the `typeof' expression is not type-dependent, then
17028      it should already been have resolved.  */
17029   if (TREE_CODE (type) == TYPEOF_TYPE
17030       || TREE_CODE (type) == DECLTYPE_TYPE)
17031     return true;
17032
17033   /* A template argument pack is dependent if any of its packed
17034      arguments are.  */
17035   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17036     {
17037       tree args = ARGUMENT_PACK_ARGS (type);
17038       int i, len = TREE_VEC_LENGTH (args);
17039       for (i = 0; i < len; ++i)
17040         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17041           return true;
17042     }
17043
17044   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17045      be template parameters.  */
17046   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17047     return true;
17048
17049   /* The standard does not specifically mention types that are local
17050      to template functions or local classes, but they should be
17051      considered dependent too.  For example:
17052
17053        template <int I> void f() {
17054          enum E { a = I };
17055          S<sizeof (E)> s;
17056        }
17057
17058      The size of `E' cannot be known until the value of `I' has been
17059      determined.  Therefore, `E' must be considered dependent.  */
17060   scope = TYPE_CONTEXT (type);
17061   if (scope && TYPE_P (scope))
17062     return dependent_type_p (scope);
17063   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17064     return type_dependent_expression_p (scope);
17065
17066   /* Other types are non-dependent.  */
17067   return false;
17068 }
17069
17070 /* Returns TRUE if TYPE is dependent, in the sense of
17071    [temp.dep.type].  */
17072
17073 bool
17074 dependent_type_p (tree type)
17075 {
17076   /* If there are no template parameters in scope, then there can't be
17077      any dependent types.  */
17078   if (!processing_template_decl)
17079     {
17080       /* If we are not processing a template, then nobody should be
17081          providing us with a dependent type.  */
17082       gcc_assert (type);
17083       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17084       return false;
17085     }
17086
17087   /* If the type is NULL, we have not computed a type for the entity
17088      in question; in that case, the type is dependent.  */
17089   if (!type)
17090     return true;
17091
17092   /* Erroneous types can be considered non-dependent.  */
17093   if (type == error_mark_node)
17094     return false;
17095
17096   /* If we have not already computed the appropriate value for TYPE,
17097      do so now.  */
17098   if (!TYPE_DEPENDENT_P_VALID (type))
17099     {
17100       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17101       TYPE_DEPENDENT_P_VALID (type) = 1;
17102     }
17103
17104   return TYPE_DEPENDENT_P (type);
17105 }
17106
17107 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17108    lookup.  In other words, a dependent type that is not the current
17109    instantiation.  */
17110
17111 bool
17112 dependent_scope_p (tree scope)
17113 {
17114   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17115           && !currently_open_class (scope));
17116 }
17117
17118 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
17119
17120 static bool
17121 dependent_scope_ref_p (tree expression, bool criterion (tree))
17122 {
17123   tree scope;
17124   tree name;
17125
17126   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
17127
17128   if (!TYPE_P (TREE_OPERAND (expression, 0)))
17129     return true;
17130
17131   scope = TREE_OPERAND (expression, 0);
17132   name = TREE_OPERAND (expression, 1);
17133
17134   /* [temp.dep.expr]
17135
17136      An id-expression is type-dependent if it contains a
17137      nested-name-specifier that contains a class-name that names a
17138      dependent type.  */
17139   /* The suggested resolution to Core Issue 224 implies that if the
17140      qualifying type is the current class, then we must peek
17141      inside it.  */
17142   if (DECL_P (name)
17143       && currently_open_class (scope)
17144       && !criterion (name))
17145     return false;
17146   if (dependent_type_p (scope))
17147     return true;
17148
17149   return false;
17150 }
17151
17152 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17153    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17154    expression.  */
17155
17156 bool
17157 value_dependent_expression_p (tree expression)
17158 {
17159   if (!processing_template_decl)
17160     return false;
17161
17162   /* A name declared with a dependent type.  */
17163   if (DECL_P (expression) && type_dependent_expression_p (expression))
17164     return true;
17165
17166   switch (TREE_CODE (expression))
17167     {
17168     case IDENTIFIER_NODE:
17169       /* A name that has not been looked up -- must be dependent.  */
17170       return true;
17171
17172     case TEMPLATE_PARM_INDEX:
17173       /* A non-type template parm.  */
17174       return true;
17175
17176     case CONST_DECL:
17177       /* A non-type template parm.  */
17178       if (DECL_TEMPLATE_PARM_P (expression))
17179         return true;
17180       return value_dependent_expression_p (DECL_INITIAL (expression));
17181
17182     case VAR_DECL:
17183        /* A constant with integral or enumeration type and is initialized
17184           with an expression that is value-dependent.  */
17185       if (DECL_INITIAL (expression)
17186           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17187           && value_dependent_expression_p (DECL_INITIAL (expression)))
17188         return true;
17189       return false;
17190
17191     case DYNAMIC_CAST_EXPR:
17192     case STATIC_CAST_EXPR:
17193     case CONST_CAST_EXPR:
17194     case REINTERPRET_CAST_EXPR:
17195     case CAST_EXPR:
17196       /* These expressions are value-dependent if the type to which
17197          the cast occurs is dependent or the expression being casted
17198          is value-dependent.  */
17199       {
17200         tree type = TREE_TYPE (expression);
17201
17202         if (dependent_type_p (type))
17203           return true;
17204
17205         /* A functional cast has a list of operands.  */
17206         expression = TREE_OPERAND (expression, 0);
17207         if (!expression)
17208           {
17209             /* If there are no operands, it must be an expression such
17210                as "int()". This should not happen for aggregate types
17211                because it would form non-constant expressions.  */
17212             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17213
17214             return false;
17215           }
17216
17217         if (TREE_CODE (expression) == TREE_LIST)
17218           return any_value_dependent_elements_p (expression);
17219
17220         return value_dependent_expression_p (expression);
17221       }
17222
17223     case SIZEOF_EXPR:
17224     case ALIGNOF_EXPR:
17225       /* A `sizeof' expression is value-dependent if the operand is
17226          type-dependent or is a pack expansion.  */
17227       expression = TREE_OPERAND (expression, 0);
17228       if (PACK_EXPANSION_P (expression))
17229         return true;
17230       else if (TYPE_P (expression))
17231         return dependent_type_p (expression);
17232       return type_dependent_expression_p (expression);
17233
17234     case SCOPE_REF:
17235       return dependent_scope_ref_p (expression, value_dependent_expression_p);
17236
17237     case COMPONENT_REF:
17238       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17239               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17240
17241     case CALL_EXPR:
17242       /* A CALL_EXPR may appear in a constant expression if it is a
17243          call to a builtin function, e.g., __builtin_constant_p.  All
17244          such calls are value-dependent.  */
17245       return true;
17246
17247     case NONTYPE_ARGUMENT_PACK:
17248       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17249          is value-dependent.  */
17250       {
17251         tree values = ARGUMENT_PACK_ARGS (expression);
17252         int i, len = TREE_VEC_LENGTH (values);
17253         
17254         for (i = 0; i < len; ++i)
17255           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17256             return true;
17257         
17258         return false;
17259       }
17260
17261     case TRAIT_EXPR:
17262       {
17263         tree type2 = TRAIT_EXPR_TYPE2 (expression);
17264         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17265                 || (type2 ? dependent_type_p (type2) : false));
17266       }
17267
17268     case MODOP_EXPR:
17269       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17270               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17271
17272     default:
17273       /* A constant expression is value-dependent if any subexpression is
17274          value-dependent.  */
17275       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17276         {
17277         case tcc_reference:
17278         case tcc_unary:
17279           return (value_dependent_expression_p
17280                   (TREE_OPERAND (expression, 0)));
17281
17282         case tcc_comparison:
17283         case tcc_binary:
17284           return ((value_dependent_expression_p
17285                    (TREE_OPERAND (expression, 0)))
17286                   || (value_dependent_expression_p
17287                       (TREE_OPERAND (expression, 1))));
17288
17289         case tcc_expression:
17290         case tcc_vl_exp:
17291           {
17292             int i;
17293             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17294               /* In some cases, some of the operands may be missing.
17295                  (For example, in the case of PREDECREMENT_EXPR, the
17296                  amount to increment by may be missing.)  That doesn't
17297                  make the expression dependent.  */
17298               if (TREE_OPERAND (expression, i)
17299                   && (value_dependent_expression_p
17300                       (TREE_OPERAND (expression, i))))
17301                 return true;
17302             return false;
17303           }
17304
17305         default:
17306           break;
17307         }
17308     }
17309
17310   /* The expression is not value-dependent.  */
17311   return false;
17312 }
17313
17314 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17315    [temp.dep.expr].  */
17316
17317 bool
17318 type_dependent_expression_p (tree expression)
17319 {
17320   if (!processing_template_decl)
17321     return false;
17322
17323   if (expression == error_mark_node)
17324     return false;
17325
17326   /* An unresolved name is always dependent.  */
17327   if (TREE_CODE (expression) == IDENTIFIER_NODE
17328       || TREE_CODE (expression) == USING_DECL)
17329     return true;
17330
17331   /* Some expression forms are never type-dependent.  */
17332   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17333       || TREE_CODE (expression) == SIZEOF_EXPR
17334       || TREE_CODE (expression) == ALIGNOF_EXPR
17335       || TREE_CODE (expression) == TRAIT_EXPR
17336       || TREE_CODE (expression) == TYPEID_EXPR
17337       || TREE_CODE (expression) == DELETE_EXPR
17338       || TREE_CODE (expression) == VEC_DELETE_EXPR
17339       || TREE_CODE (expression) == THROW_EXPR)
17340     return false;
17341
17342   /* The types of these expressions depends only on the type to which
17343      the cast occurs.  */
17344   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17345       || TREE_CODE (expression) == STATIC_CAST_EXPR
17346       || TREE_CODE (expression) == CONST_CAST_EXPR
17347       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17348       || TREE_CODE (expression) == CAST_EXPR)
17349     return dependent_type_p (TREE_TYPE (expression));
17350
17351   /* The types of these expressions depends only on the type created
17352      by the expression.  */
17353   if (TREE_CODE (expression) == NEW_EXPR
17354       || TREE_CODE (expression) == VEC_NEW_EXPR)
17355     {
17356       /* For NEW_EXPR tree nodes created inside a template, either
17357          the object type itself or a TREE_LIST may appear as the
17358          operand 1.  */
17359       tree type = TREE_OPERAND (expression, 1);
17360       if (TREE_CODE (type) == TREE_LIST)
17361         /* This is an array type.  We need to check array dimensions
17362            as well.  */
17363         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17364                || value_dependent_expression_p
17365                     (TREE_OPERAND (TREE_VALUE (type), 1));
17366       else
17367         return dependent_type_p (type);
17368     }
17369
17370   if (TREE_CODE (expression) == SCOPE_REF
17371       && dependent_scope_ref_p (expression,
17372                                 type_dependent_expression_p))
17373     return true;
17374
17375   if (TREE_CODE (expression) == FUNCTION_DECL
17376       && DECL_LANG_SPECIFIC (expression)
17377       && DECL_TEMPLATE_INFO (expression)
17378       && (any_dependent_template_arguments_p
17379           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17380     return true;
17381
17382   if (TREE_CODE (expression) == TEMPLATE_DECL
17383       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17384     return false;
17385
17386   if (TREE_CODE (expression) == STMT_EXPR)
17387     expression = stmt_expr_value_expr (expression);
17388
17389   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17390     {
17391       tree elt;
17392       unsigned i;
17393
17394       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17395         {
17396           if (type_dependent_expression_p (elt))
17397             return true;
17398         }
17399       return false;
17400     }
17401
17402   if (TREE_TYPE (expression) == unknown_type_node)
17403     {
17404       if (TREE_CODE (expression) == ADDR_EXPR)
17405         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17406       if (TREE_CODE (expression) == COMPONENT_REF
17407           || TREE_CODE (expression) == OFFSET_REF)
17408         {
17409           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17410             return true;
17411           expression = TREE_OPERAND (expression, 1);
17412           if (TREE_CODE (expression) == IDENTIFIER_NODE)
17413             return false;
17414         }
17415       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17416       if (TREE_CODE (expression) == SCOPE_REF)
17417         return false;
17418
17419       if (TREE_CODE (expression) == BASELINK)
17420         expression = BASELINK_FUNCTIONS (expression);
17421
17422       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17423         {
17424           if (any_dependent_template_arguments_p
17425               (TREE_OPERAND (expression, 1)))
17426             return true;
17427           expression = TREE_OPERAND (expression, 0);
17428         }
17429       gcc_assert (TREE_CODE (expression) == OVERLOAD
17430                   || TREE_CODE (expression) == FUNCTION_DECL);
17431
17432       while (expression)
17433         {
17434           if (type_dependent_expression_p (OVL_CURRENT (expression)))
17435             return true;
17436           expression = OVL_NEXT (expression);
17437         }
17438       return false;
17439     }
17440
17441   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17442
17443   return (dependent_type_p (TREE_TYPE (expression)));
17444 }
17445
17446 /* Like type_dependent_expression_p, but it also works while not processing
17447    a template definition, i.e. during substitution or mangling.  */
17448
17449 bool
17450 type_dependent_expression_p_push (tree expr)
17451 {
17452   bool b;
17453   ++processing_template_decl;
17454   b = type_dependent_expression_p (expr);
17455   --processing_template_decl;
17456   return b;
17457 }
17458
17459 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17460
17461 bool
17462 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17463 {
17464   unsigned int i;
17465   tree arg;
17466
17467   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
17468     {
17469       if (type_dependent_expression_p (arg))
17470         return true;
17471     }
17472   return false;
17473 }
17474
17475 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17476    expressions) contains any value-dependent expressions.  */
17477
17478 bool
17479 any_value_dependent_elements_p (const_tree list)
17480 {
17481   for (; list; list = TREE_CHAIN (list))
17482     if (value_dependent_expression_p (TREE_VALUE (list)))
17483       return true;
17484
17485   return false;
17486 }
17487
17488 /* Returns TRUE if the ARG (a template argument) is dependent.  */
17489
17490 bool
17491 dependent_template_arg_p (tree arg)
17492 {
17493   if (!processing_template_decl)
17494     return false;
17495
17496   if (TREE_CODE (arg) == TEMPLATE_DECL
17497       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17498     return dependent_template_p (arg);
17499   else if (ARGUMENT_PACK_P (arg))
17500     {
17501       tree args = ARGUMENT_PACK_ARGS (arg);
17502       int i, len = TREE_VEC_LENGTH (args);
17503       for (i = 0; i < len; ++i)
17504         {
17505           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17506             return true;
17507         }
17508
17509       return false;
17510     }
17511   else if (TYPE_P (arg))
17512     return dependent_type_p (arg);
17513   else
17514     return (type_dependent_expression_p (arg)
17515             || value_dependent_expression_p (arg));
17516 }
17517
17518 /* Returns true if ARGS (a collection of template arguments) contains
17519    any types that require structural equality testing.  */
17520
17521 bool
17522 any_template_arguments_need_structural_equality_p (tree args)
17523 {
17524   int i;
17525   int j;
17526
17527   if (!args)
17528     return false;
17529   if (args == error_mark_node)
17530     return true;
17531
17532   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17533     {
17534       tree level = TMPL_ARGS_LEVEL (args, i + 1);
17535       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17536         {
17537           tree arg = TREE_VEC_ELT (level, j);
17538           tree packed_args = NULL_TREE;
17539           int k, len = 1;
17540
17541           if (ARGUMENT_PACK_P (arg))
17542             {
17543               /* Look inside the argument pack.  */
17544               packed_args = ARGUMENT_PACK_ARGS (arg);
17545               len = TREE_VEC_LENGTH (packed_args);
17546             }
17547
17548           for (k = 0; k < len; ++k)
17549             {
17550               if (packed_args)
17551                 arg = TREE_VEC_ELT (packed_args, k);
17552
17553               if (error_operand_p (arg))
17554                 return true;
17555               else if (TREE_CODE (arg) == TEMPLATE_DECL
17556                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17557                 continue;
17558               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17559                 return true;
17560               else if (!TYPE_P (arg) && TREE_TYPE (arg)
17561                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17562                 return true;
17563             }
17564         }
17565     }
17566
17567   return false;
17568 }
17569
17570 /* Returns true if ARGS (a collection of template arguments) contains
17571    any dependent arguments.  */
17572
17573 bool
17574 any_dependent_template_arguments_p (const_tree args)
17575 {
17576   int i;
17577   int j;
17578
17579   if (!args)
17580     return false;
17581   if (args == error_mark_node)
17582     return true;
17583
17584   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17585     {
17586       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17587       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17588         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17589           return true;
17590     }
17591
17592   return false;
17593 }
17594
17595 /* Returns TRUE if the template TMPL is dependent.  */
17596
17597 bool
17598 dependent_template_p (tree tmpl)
17599 {
17600   if (TREE_CODE (tmpl) == OVERLOAD)
17601     {
17602       while (tmpl)
17603         {
17604           if (dependent_template_p (OVL_FUNCTION (tmpl)))
17605             return true;
17606           tmpl = OVL_CHAIN (tmpl);
17607         }
17608       return false;
17609     }
17610
17611   /* Template template parameters are dependent.  */
17612   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
17613       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
17614     return true;
17615   /* So are names that have not been looked up.  */
17616   if (TREE_CODE (tmpl) == SCOPE_REF
17617       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
17618     return true;
17619   /* So are member templates of dependent classes.  */
17620   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
17621     return dependent_type_p (DECL_CONTEXT (tmpl));
17622   return false;
17623 }
17624
17625 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
17626
17627 bool
17628 dependent_template_id_p (tree tmpl, tree args)
17629 {
17630   return (dependent_template_p (tmpl)
17631           || any_dependent_template_arguments_p (args));
17632 }
17633
17634 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
17635    is dependent.  */
17636
17637 bool
17638 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
17639 {
17640   int i;
17641
17642   if (!processing_template_decl)
17643     return false;
17644
17645   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
17646     {
17647       tree decl = TREE_VEC_ELT (declv, i);
17648       tree init = TREE_VEC_ELT (initv, i);
17649       tree cond = TREE_VEC_ELT (condv, i);
17650       tree incr = TREE_VEC_ELT (incrv, i);
17651
17652       if (type_dependent_expression_p (decl))
17653         return true;
17654
17655       if (init && type_dependent_expression_p (init))
17656         return true;
17657
17658       if (type_dependent_expression_p (cond))
17659         return true;
17660
17661       if (COMPARISON_CLASS_P (cond)
17662           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
17663               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
17664         return true;
17665
17666       if (TREE_CODE (incr) == MODOP_EXPR)
17667         {
17668           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
17669               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
17670             return true;
17671         }
17672       else if (type_dependent_expression_p (incr))
17673         return true;
17674       else if (TREE_CODE (incr) == MODIFY_EXPR)
17675         {
17676           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
17677             return true;
17678           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
17679             {
17680               tree t = TREE_OPERAND (incr, 1);
17681               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
17682                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
17683                 return true;
17684             }
17685         }
17686     }
17687
17688   return false;
17689 }
17690
17691 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
17692    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
17693    no such TYPE can be found.  Note that this function peers inside
17694    uninstantiated templates and therefore should be used only in
17695    extremely limited situations.  ONLY_CURRENT_P restricts this
17696    peering to the currently open classes hierarchy (which is required
17697    when comparing types).  */
17698
17699 tree
17700 resolve_typename_type (tree type, bool only_current_p)
17701 {
17702   tree scope;
17703   tree name;
17704   tree decl;
17705   int quals;
17706   tree pushed_scope;
17707   tree result;
17708
17709   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
17710
17711   scope = TYPE_CONTEXT (type);
17712   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
17713      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
17714      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
17715      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
17716      identifier  of the TYPENAME_TYPE anymore.
17717      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
17718      TYPENAME_TYPE instead, we avoid messing up with a possible
17719      typedef variant case.  */
17720   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
17721
17722   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
17723      it first before we can figure out what NAME refers to.  */
17724   if (TREE_CODE (scope) == TYPENAME_TYPE)
17725     scope = resolve_typename_type (scope, only_current_p);
17726   /* If we don't know what SCOPE refers to, then we cannot resolve the
17727      TYPENAME_TYPE.  */
17728   if (TREE_CODE (scope) == TYPENAME_TYPE)
17729     return type;
17730   /* If the SCOPE is a template type parameter, we have no way of
17731      resolving the name.  */
17732   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
17733     return type;
17734   /* If the SCOPE is not the current instantiation, there's no reason
17735      to look inside it.  */
17736   if (only_current_p && !currently_open_class (scope))
17737     return type;
17738   /* If this is a typedef, we don't want to look inside (c++/11987).  */
17739   if (typedef_variant_p (type))
17740     return type;
17741   /* If SCOPE isn't the template itself, it will not have a valid
17742      TYPE_FIELDS list.  */
17743   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
17744     /* scope is either the template itself or a compatible instantiation
17745        like X<T>, so look up the name in the original template.  */
17746     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
17747   else
17748     /* scope is a partial instantiation, so we can't do the lookup or we
17749        will lose the template arguments.  */
17750     return type;
17751   /* Enter the SCOPE so that name lookup will be resolved as if we
17752      were in the class definition.  In particular, SCOPE will no
17753      longer be considered a dependent type.  */
17754   pushed_scope = push_scope (scope);
17755   /* Look up the declaration.  */
17756   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
17757
17758   result = NULL_TREE;
17759   
17760   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
17761      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
17762   if (!decl)
17763     /*nop*/;
17764   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
17765            && TREE_CODE (decl) == TYPE_DECL)
17766     {
17767       result = TREE_TYPE (decl);
17768       if (result == error_mark_node)
17769         result = NULL_TREE;
17770     }
17771   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
17772            && DECL_CLASS_TEMPLATE_P (decl))
17773     {
17774       tree tmpl;
17775       tree args;
17776       /* Obtain the template and the arguments.  */
17777       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
17778       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
17779       /* Instantiate the template.  */
17780       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
17781                                       /*entering_scope=*/0,
17782                                       tf_error | tf_user);
17783       if (result == error_mark_node)
17784         result = NULL_TREE;
17785     }
17786   
17787   /* Leave the SCOPE.  */
17788   if (pushed_scope)
17789     pop_scope (pushed_scope);
17790
17791   /* If we failed to resolve it, return the original typename.  */
17792   if (!result)
17793     return type;
17794   
17795   /* If lookup found a typename type, resolve that too.  */
17796   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
17797     {
17798       /* Ill-formed programs can cause infinite recursion here, so we
17799          must catch that.  */
17800       TYPENAME_IS_RESOLVING_P (type) = 1;
17801       result = resolve_typename_type (result, only_current_p);
17802       TYPENAME_IS_RESOLVING_P (type) = 0;
17803     }
17804   
17805   /* Qualify the resulting type.  */
17806   quals = cp_type_quals (type);
17807   if (quals)
17808     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
17809
17810   return result;
17811 }
17812
17813 /* EXPR is an expression which is not type-dependent.  Return a proxy
17814    for EXPR that can be used to compute the types of larger
17815    expressions containing EXPR.  */
17816
17817 tree
17818 build_non_dependent_expr (tree expr)
17819 {
17820   tree inner_expr;
17821
17822   /* Preserve null pointer constants so that the type of things like
17823      "p == 0" where "p" is a pointer can be determined.  */
17824   if (null_ptr_cst_p (expr))
17825     return expr;
17826   /* Preserve OVERLOADs; the functions must be available to resolve
17827      types.  */
17828   inner_expr = expr;
17829   if (TREE_CODE (inner_expr) == STMT_EXPR)
17830     inner_expr = stmt_expr_value_expr (inner_expr);
17831   if (TREE_CODE (inner_expr) == ADDR_EXPR)
17832     inner_expr = TREE_OPERAND (inner_expr, 0);
17833   if (TREE_CODE (inner_expr) == COMPONENT_REF)
17834     inner_expr = TREE_OPERAND (inner_expr, 1);
17835   if (is_overloaded_fn (inner_expr)
17836       || TREE_CODE (inner_expr) == OFFSET_REF)
17837     return expr;
17838   /* There is no need to return a proxy for a variable.  */
17839   if (TREE_CODE (expr) == VAR_DECL)
17840     return expr;
17841   /* Preserve string constants; conversions from string constants to
17842      "char *" are allowed, even though normally a "const char *"
17843      cannot be used to initialize a "char *".  */
17844   if (TREE_CODE (expr) == STRING_CST)
17845     return expr;
17846   /* Preserve arithmetic constants, as an optimization -- there is no
17847      reason to create a new node.  */
17848   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
17849     return expr;
17850   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
17851      There is at least one place where we want to know that a
17852      particular expression is a throw-expression: when checking a ?:
17853      expression, there are special rules if the second or third
17854      argument is a throw-expression.  */
17855   if (TREE_CODE (expr) == THROW_EXPR)
17856     return expr;
17857
17858   if (TREE_CODE (expr) == COND_EXPR)
17859     return build3 (COND_EXPR,
17860                    TREE_TYPE (expr),
17861                    TREE_OPERAND (expr, 0),
17862                    (TREE_OPERAND (expr, 1)
17863                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
17864                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
17865                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
17866   if (TREE_CODE (expr) == COMPOUND_EXPR
17867       && !COMPOUND_EXPR_OVERLOADED (expr))
17868     return build2 (COMPOUND_EXPR,
17869                    TREE_TYPE (expr),
17870                    TREE_OPERAND (expr, 0),
17871                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
17872
17873   /* If the type is unknown, it can't really be non-dependent */
17874   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
17875
17876   /* Otherwise, build a NON_DEPENDENT_EXPR.
17877
17878      REFERENCE_TYPEs are not stripped for expressions in templates
17879      because doing so would play havoc with mangling.  Consider, for
17880      example:
17881
17882        template <typename T> void f<T& g>() { g(); }
17883
17884      In the body of "f", the expression for "g" will have
17885      REFERENCE_TYPE, even though the standard says that it should
17886      not.  The reason is that we must preserve the syntactic form of
17887      the expression so that mangling (say) "f<g>" inside the body of
17888      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
17889      stripped here.  */
17890   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
17891 }
17892
17893 /* ARGS is a vector of expressions as arguments to a function call.
17894    Replace the arguments with equivalent non-dependent expressions.
17895    This modifies ARGS in place.  */
17896
17897 void
17898 make_args_non_dependent (VEC(tree,gc) *args)
17899 {
17900   unsigned int ix;
17901   tree arg;
17902
17903   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
17904     {
17905       tree newarg = build_non_dependent_expr (arg);
17906       if (newarg != arg)
17907         VEC_replace (tree, args, ix, newarg);
17908     }
17909 }
17910
17911 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
17912    with a level one deeper than the actual template parms.  */
17913
17914 tree
17915 make_auto (void)
17916 {
17917   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
17918   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
17919                                TYPE_DECL, get_identifier ("auto"), au);
17920   TYPE_STUB_DECL (au) = TYPE_NAME (au);
17921   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
17922     (0, processing_template_decl + 1, processing_template_decl + 1,
17923      TYPE_NAME (au), NULL_TREE);
17924   TYPE_CANONICAL (au) = canonical_type_parameter (au);
17925   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
17926   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
17927
17928   return au;
17929 }
17930
17931 /* Given type ARG, return std::initializer_list<ARG>.  */
17932
17933 static tree
17934 listify (tree arg)
17935 {
17936   tree std_init_list = namespace_binding
17937     (get_identifier ("initializer_list"), std_node);
17938   tree argvec;
17939   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
17940     {    
17941       error ("deducing from brace-enclosed initializer list requires "
17942              "#include <initializer_list>");
17943       return error_mark_node;
17944     }
17945   argvec = make_tree_vec (1);
17946   TREE_VEC_ELT (argvec, 0) = arg;
17947   return lookup_template_class (std_init_list, argvec, NULL_TREE,
17948                                 NULL_TREE, 0, tf_warning_or_error);
17949 }
17950
17951 /* Replace auto in TYPE with std::initializer_list<auto>.  */
17952
17953 static tree
17954 listify_autos (tree type, tree auto_node)
17955 {
17956   tree init_auto = listify (auto_node);
17957   tree argvec = make_tree_vec (1);
17958   TREE_VEC_ELT (argvec, 0) = init_auto;
17959   if (processing_template_decl)
17960     argvec = add_to_template_args (current_template_args (), argvec);
17961   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17962 }
17963
17964 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
17965    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
17966
17967 tree
17968 do_auto_deduction (tree type, tree init, tree auto_node)
17969 {
17970   tree parms, tparms, targs;
17971   tree args[1];
17972   int val;
17973
17974   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
17975      with either a new invented type template parameter U or, if the
17976      initializer is a braced-init-list (8.5.4), with
17977      std::initializer_list<U>.  */
17978   if (BRACE_ENCLOSED_INITIALIZER_P (init))
17979     type = listify_autos (type, auto_node);
17980
17981   parms = build_tree_list (NULL_TREE, type);
17982   args[0] = init;
17983   tparms = make_tree_vec (1);
17984   targs = make_tree_vec (1);
17985   TREE_VEC_ELT (tparms, 0)
17986     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
17987   val = type_unification_real (tparms, targs, parms, args, 1, 0,
17988                                DEDUCE_CALL, LOOKUP_NORMAL);
17989   if (val > 0)
17990     {
17991       error ("unable to deduce %qT from %qE", type, init);
17992       return error_mark_node;
17993     }
17994
17995   /* If the list of declarators contains more than one declarator, the type
17996      of each declared variable is determined as described above. If the
17997      type deduced for the template parameter U is not the same in each
17998      deduction, the program is ill-formed.  */
17999   if (TREE_TYPE (auto_node)
18000       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18001     {
18002       error ("inconsistent deduction for %qT: %qT and then %qT",
18003              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18004       return error_mark_node;
18005     }
18006   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18007
18008   if (processing_template_decl)
18009     targs = add_to_template_args (current_template_args (), targs);
18010   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18011 }
18012
18013 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18014    result.  */
18015
18016 tree
18017 splice_late_return_type (tree type, tree late_return_type)
18018 {
18019   tree argvec;
18020
18021   if (late_return_type == NULL_TREE)
18022     return type;
18023   argvec = make_tree_vec (1);
18024   TREE_VEC_ELT (argvec, 0) = late_return_type;
18025   if (processing_template_decl)
18026     argvec = add_to_template_args (current_template_args (), argvec);
18027   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18028 }
18029
18030 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18031
18032 bool
18033 is_auto (const_tree type)
18034 {
18035   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18036       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18037     return true;
18038   else
18039     return false;
18040 }
18041
18042 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18043    appear as a type-specifier for the declaration in question, we don't
18044    have to look through the whole type.  */
18045
18046 tree
18047 type_uses_auto (tree type)
18048 {
18049   enum tree_code code;
18050   if (is_auto (type))
18051     return type;
18052
18053   code = TREE_CODE (type);
18054
18055   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18056       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18057       || code == METHOD_TYPE || code == ARRAY_TYPE)
18058     return type_uses_auto (TREE_TYPE (type));
18059
18060   if (TYPE_PTRMEMFUNC_P (type))
18061     return type_uses_auto (TREE_TYPE (TREE_TYPE
18062                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18063
18064   return NULL_TREE;
18065 }
18066
18067 /* For a given template T, return the list of typedefs referenced
18068    in T for which access check is needed at T instantiation time.
18069    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18070    Those typedefs were added to T by the function
18071    append_type_to_template_for_access_check.  */
18072
18073 tree
18074 get_types_needing_access_check (tree t)
18075 {
18076   tree ti, result = NULL_TREE;
18077
18078   if (!t || t == error_mark_node)
18079     return t;
18080
18081   if (!(ti = get_template_info (t)))
18082     return NULL_TREE;
18083
18084   if (CLASS_TYPE_P (t)
18085       || TREE_CODE (t) == FUNCTION_DECL)
18086     {
18087       if (!TI_TEMPLATE (ti))
18088         return NULL_TREE;
18089
18090       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18091     }
18092
18093   return result;
18094 }
18095
18096 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
18097    tied to T. That list of typedefs will be access checked at
18098    T instantiation time.
18099    T is either a FUNCTION_DECL or a RECORD_TYPE.
18100    TYPE_DECL is a TYPE_DECL node representing a typedef.
18101    SCOPE is the scope through which TYPE_DECL is accessed.
18102
18103    This function is a subroutine of
18104    append_type_to_template_for_access_check.  */
18105
18106 static void
18107 append_type_to_template_for_access_check_1 (tree t,
18108                                             tree type_decl,
18109                                             tree scope)
18110 {
18111   tree ti;
18112
18113   if (!t || t == error_mark_node)
18114     return;
18115
18116   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18117                || CLASS_TYPE_P (t))
18118               && type_decl
18119               && TREE_CODE (type_decl) == TYPE_DECL
18120               && scope);
18121
18122   if (!(ti = get_template_info (t)))
18123     return;
18124
18125   gcc_assert (TI_TEMPLATE (ti));
18126
18127   TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti) =
18128     tree_cons (type_decl, scope, TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti));
18129 }
18130
18131 /* Append TYPE_DECL to the template TEMPL.
18132    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18133    At TEMPL instanciation time, TYPE_DECL will be checked to see
18134    if it can be accessed through SCOPE.
18135
18136    e.g. consider the following code snippet:
18137
18138      class C
18139      {
18140        typedef int myint;
18141      };
18142
18143      template<class U> struct S
18144      {
18145        C::myint mi;
18146      };
18147
18148      S<char> s;
18149
18150    At S<char> instantiation time, we need to check the access of C::myint
18151    In other words, we need to check the access of the myint typedef through
18152    the C scope. For that purpose, this function will add the myint typedef
18153    and the scope C through which its being accessed to a list of typedefs
18154    tied to the template S. That list will be walked at template instantiation
18155    time and access check performed on each typedefs it contains.
18156    Note that this particular code snippet should yield an error because
18157    myint is private to C.  */
18158
18159 void
18160 append_type_to_template_for_access_check (tree templ,
18161                                           tree type_decl,
18162                                           tree scope)
18163 {
18164   tree node;
18165
18166   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18167
18168   /* Make sure we don't append the type to the template twice.  */
18169   for (node = get_types_needing_access_check (templ);
18170        node;
18171        node = TREE_CHAIN (node))
18172     {
18173       tree decl = TREE_PURPOSE (node);
18174       tree type_scope = TREE_VALUE (node);
18175
18176       if (decl == type_decl && type_scope == scope)
18177         return;
18178     }
18179
18180   append_type_to_template_for_access_check_1 (templ, type_decl, scope);
18181 }
18182
18183 /* Set up the hash tables for template instantiations.  */
18184
18185 void
18186 init_template_processing (void)
18187 {
18188   decl_specializations = htab_create_ggc (37,
18189                                           hash_specialization,
18190                                           eq_specializations,
18191                                           ggc_free);
18192   type_specializations = htab_create_ggc (37,
18193                                           hash_specialization,
18194                                           eq_specializations,
18195                                           ggc_free);
18196 }
18197
18198 #include "gt-cp-pt.h"