OSDN Git Service

* pt.c (deduction_tsubst_fntype): Don't free the tinst entry
[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, 2010, 2011
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 "tree.h"
34 #include "intl.h"
35 #include "pointer-set.h"
36 #include "flags.h"
37 #include "cp-tree.h"
38 #include "c-family/c-common.h"
39 #include "c-family/c-objc.h"
40 #include "cp-objcp-common.h"
41 #include "tree-inline.h"
42 #include "decl.h"
43 #include "output.h"
44 #include "toplev.h"
45 #include "timevar.h"
46 #include "tree-iterator.h"
47 #include "vecprim.h"
48
49 /* The type of functions taking a tree, and some additional data, and
50    returning an int.  */
51 typedef int (*tree_fn_t) (tree, void*);
52
53 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
54    instantiations have been deferred, either because their definitions
55    were not yet available, or because we were putting off doing the work.  */
56 struct GTY ((chain_next ("%h.next"))) pending_template {
57   struct pending_template *next;
58   struct tinst_level *tinst;
59 };
60
61 static GTY(()) struct pending_template *pending_templates;
62 static GTY(()) struct pending_template *last_pending_template;
63
64 int processing_template_parmlist;
65 static int template_header_count;
66
67 static GTY(()) tree saved_trees;
68 static VEC(int,heap) *inline_parm_levels;
69
70 static GTY(()) struct tinst_level *current_tinst_level;
71
72 static GTY(()) tree saved_access_scope;
73
74 /* Live only within one (recursive) call to tsubst_expr.  We use
75    this to pass the statement expression node from the STMT_EXPR
76    to the EXPR_STMT that is its result.  */
77 static tree cur_stmt_expr;
78
79 /* A map from local variable declarations in the body of the template
80    presently being instantiated to the corresponding instantiated
81    local variables.  */
82 static htab_t local_specializations;
83
84 typedef struct GTY(()) spec_entry
85 {
86   tree tmpl;
87   tree args;
88   tree spec;
89 } spec_entry;
90
91 static GTY ((param_is (spec_entry)))
92   htab_t decl_specializations;
93
94 static GTY ((param_is (spec_entry)))
95   htab_t type_specializations;
96
97 /* Contains canonical template parameter types. The vector is indexed by
98    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
99    TREE_LIST, whose TREE_VALUEs contain the canonical template
100    parameters of various types and levels.  */
101 static GTY(()) VEC(tree,gc) *canonical_template_parms;
102
103 #define UNIFY_ALLOW_NONE 0
104 #define UNIFY_ALLOW_MORE_CV_QUAL 1
105 #define UNIFY_ALLOW_LESS_CV_QUAL 2
106 #define UNIFY_ALLOW_DERIVED 4
107 #define UNIFY_ALLOW_INTEGER 8
108 #define UNIFY_ALLOW_OUTER_LEVEL 16
109 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
110 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
111
112 static void push_access_scope (tree);
113 static void pop_access_scope (tree);
114 static void push_deduction_access_scope (tree);
115 static void pop_deduction_access_scope (tree);
116 static bool resolve_overloaded_unification (tree, tree, tree, tree,
117                                             unification_kind_t, int);
118 static int try_one_overload (tree, tree, tree, tree, tree,
119                              unification_kind_t, int, bool);
120 static int unify (tree, tree, tree, tree, int);
121 static void add_pending_template (tree);
122 static tree reopen_tinst_level (struct tinst_level *);
123 static tree tsubst_initializer_list (tree, tree);
124 static tree get_class_bindings (tree, tree, tree);
125 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
126                                    bool, bool);
127 static void tsubst_enum (tree, tree, tree);
128 static tree add_to_template_args (tree, tree);
129 static tree add_outermost_template_args (tree, tree);
130 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
131 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
132                                              tree);
133 static int type_unification_real (tree, tree, tree, const tree *,
134                                   unsigned int, int, unification_kind_t, int);
135 static void note_template_header (int);
136 static tree convert_nontype_argument_function (tree, tree);
137 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
138 static tree convert_template_argument (tree, tree, tree,
139                                        tsubst_flags_t, int, tree);
140 static int for_each_template_parm (tree, tree_fn_t, void*,
141                                    struct pointer_set_t*, bool);
142 static tree expand_template_argument_pack (tree);
143 static tree build_template_parm_index (int, int, int, int, tree, tree);
144 static bool inline_needs_template_parms (tree);
145 static void push_inline_template_parms_recursive (tree, int);
146 static tree retrieve_local_specialization (tree);
147 static void register_local_specialization (tree, tree);
148 static hashval_t hash_specialization (const void *p);
149 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
150 static int mark_template_parm (tree, void *);
151 static int template_parm_this_level_p (tree, void *);
152 static tree tsubst_friend_function (tree, tree);
153 static tree tsubst_friend_class (tree, tree);
154 static int can_complete_type_without_circularity (tree);
155 static tree get_bindings (tree, tree, tree, bool);
156 static int template_decl_level (tree);
157 static int check_cv_quals_for_unify (int, tree, tree);
158 static void template_parm_level_and_index (tree, int*, int*);
159 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
160 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
161 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
162 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
163 static void regenerate_decl_from_template (tree, tree);
164 static tree most_specialized_class (tree, tree, tsubst_flags_t);
165 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
166 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
167 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
168 static bool check_specialization_scope (void);
169 static tree process_partial_specialization (tree);
170 static void set_current_access_from_decl (tree);
171 static tree get_template_base (tree, tree, tree, tree);
172 static tree try_class_unification (tree, tree, tree, tree);
173 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
174                                            tree, tree);
175 static bool template_template_parm_bindings_ok_p (tree, tree);
176 static int template_args_equal (tree, tree);
177 static void tsubst_default_arguments (tree);
178 static tree for_each_template_parm_r (tree *, int *, void *);
179 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
180 static void copy_default_args_to_explicit_spec (tree);
181 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
182 static int eq_local_specializations (const void *, const void *);
183 static bool dependent_template_arg_p (tree);
184 static bool any_template_arguments_need_structural_equality_p (tree);
185 static bool dependent_type_p_r (tree);
186 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
187 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
188 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_decl (tree, tree, tsubst_flags_t);
190 static void perform_typedefs_access_check (tree tmpl, tree targs);
191 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
192                                                         location_t);
193 static tree listify (tree);
194 static tree listify_autos (tree, tree);
195 static tree template_parm_to_arg (tree t);
196 static tree current_template_args (void);
197 static tree fixup_template_type_parm_type (tree, int);
198 static tree fixup_template_parm_index (tree, tree, int);
199 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
200
201 /* Make the current scope suitable for access checking when we are
202    processing T.  T can be FUNCTION_DECL for instantiated function
203    template, or VAR_DECL for static member variable (need by
204    instantiate_decl).  */
205
206 static void
207 push_access_scope (tree t)
208 {
209   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
210               || TREE_CODE (t) == VAR_DECL);
211
212   if (DECL_FRIEND_CONTEXT (t))
213     push_nested_class (DECL_FRIEND_CONTEXT (t));
214   else if (DECL_CLASS_SCOPE_P (t))
215     push_nested_class (DECL_CONTEXT (t));
216   else
217     pushclass (NULL_TREE);
218
219   if (TREE_CODE (t) == FUNCTION_DECL)
220     {
221       saved_access_scope = tree_cons
222         (NULL_TREE, current_function_decl, saved_access_scope);
223       current_function_decl = t;
224     }
225 }
226
227 /* Restore the scope set up by push_access_scope.  T is the node we
228    are processing.  */
229
230 static void
231 pop_access_scope (tree t)
232 {
233   if (TREE_CODE (t) == FUNCTION_DECL)
234     {
235       current_function_decl = TREE_VALUE (saved_access_scope);
236       saved_access_scope = TREE_CHAIN (saved_access_scope);
237     }
238
239   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
240     pop_nested_class ();
241   else
242     popclass ();
243 }
244
245 /* Do any processing required when DECL (a member template
246    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
247    to DECL, unless it is a specialization, in which case the DECL
248    itself is returned.  */
249
250 tree
251 finish_member_template_decl (tree decl)
252 {
253   if (decl == error_mark_node)
254     return error_mark_node;
255
256   gcc_assert (DECL_P (decl));
257
258   if (TREE_CODE (decl) == TYPE_DECL)
259     {
260       tree type;
261
262       type = TREE_TYPE (decl);
263       if (type == error_mark_node)
264         return error_mark_node;
265       if (MAYBE_CLASS_TYPE_P (type)
266           && CLASSTYPE_TEMPLATE_INFO (type)
267           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
268         {
269           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
270           check_member_template (tmpl);
271           return tmpl;
272         }
273       return NULL_TREE;
274     }
275   else if (TREE_CODE (decl) == FIELD_DECL)
276     error ("data member %qD cannot be a member template", decl);
277   else if (DECL_TEMPLATE_INFO (decl))
278     {
279       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
280         {
281           check_member_template (DECL_TI_TEMPLATE (decl));
282           return DECL_TI_TEMPLATE (decl);
283         }
284       else
285         return decl;
286     }
287   else
288     error ("invalid member template declaration %qD", decl);
289
290   return error_mark_node;
291 }
292
293 /* Create a template info node.  */
294
295 tree
296 build_template_info (tree template_decl, tree template_args)
297 {
298   tree result = make_node (TEMPLATE_INFO);
299   TI_TEMPLATE (result) = template_decl;
300   TI_ARGS (result) = template_args;
301   return result;
302 }
303
304 /* Return the template info node corresponding to T, whatever T is.  */
305
306 tree
307 get_template_info (const_tree t)
308 {
309   tree tinfo = NULL_TREE;
310
311   if (!t || t == error_mark_node)
312     return NULL;
313
314   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
315     tinfo = DECL_TEMPLATE_INFO (t);
316
317   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
318     t = TREE_TYPE (t);
319
320   if (TAGGED_TYPE_P (t))
321     tinfo = TYPE_TEMPLATE_INFO (t);
322   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
323     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
324
325   return tinfo;
326 }
327
328 /* Returns the template nesting level of the indicated class TYPE.
329
330    For example, in:
331      template <class T>
332      struct A
333      {
334        template <class U>
335        struct B {};
336      };
337
338    A<T>::B<U> has depth two, while A<T> has depth one.
339    Both A<T>::B<int> and A<int>::B<U> have depth one, if
340    they are instantiations, not specializations.
341
342    This function is guaranteed to return 0 if passed NULL_TREE so
343    that, for example, `template_class_depth (current_class_type)' is
344    always safe.  */
345
346 int
347 template_class_depth (tree type)
348 {
349   int depth;
350
351   for (depth = 0;
352        type && TREE_CODE (type) != NAMESPACE_DECL;
353        type = (TREE_CODE (type) == FUNCTION_DECL)
354          ? CP_DECL_CONTEXT (type) : CP_TYPE_CONTEXT (type))
355     {
356       tree tinfo = get_template_info (type);
357
358       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
359           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
360         ++depth;
361     }
362
363   return depth;
364 }
365
366 /* Subroutine of maybe_begin_member_template_processing.
367    Returns true if processing DECL needs us to push template parms.  */
368
369 static bool
370 inline_needs_template_parms (tree decl)
371 {
372   if (! DECL_TEMPLATE_INFO (decl))
373     return false;
374
375   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
376           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
377 }
378
379 /* Subroutine of maybe_begin_member_template_processing.
380    Push the template parms in PARMS, starting from LEVELS steps into the
381    chain, and ending at the beginning, since template parms are listed
382    innermost first.  */
383
384 static void
385 push_inline_template_parms_recursive (tree parmlist, int levels)
386 {
387   tree parms = TREE_VALUE (parmlist);
388   int i;
389
390   if (levels > 1)
391     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
392
393   ++processing_template_decl;
394   current_template_parms
395     = tree_cons (size_int (processing_template_decl),
396                  parms, current_template_parms);
397   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
398
399   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
400                NULL);
401   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
402     {
403       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
404
405       if (parm == error_mark_node)
406         continue;
407
408       gcc_assert (DECL_P (parm));
409
410       switch (TREE_CODE (parm))
411         {
412         case TYPE_DECL:
413         case TEMPLATE_DECL:
414           pushdecl (parm);
415           break;
416
417         case PARM_DECL:
418           {
419             /* Make a CONST_DECL as is done in process_template_parm.
420                It is ugly that we recreate this here; the original
421                version built in process_template_parm is no longer
422                available.  */
423             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
424                                     CONST_DECL, DECL_NAME (parm),
425                                     TREE_TYPE (parm));
426             DECL_ARTIFICIAL (decl) = 1;
427             TREE_CONSTANT (decl) = 1;
428             TREE_READONLY (decl) = 1;
429             DECL_INITIAL (decl) = DECL_INITIAL (parm);
430             SET_DECL_TEMPLATE_PARM_P (decl);
431             pushdecl (decl);
432           }
433           break;
434
435         default:
436           gcc_unreachable ();
437         }
438     }
439 }
440
441 /* Restore the template parameter context for a member template or
442    a friend template defined in a class definition.  */
443
444 void
445 maybe_begin_member_template_processing (tree decl)
446 {
447   tree parms;
448   int levels = 0;
449
450   if (inline_needs_template_parms (decl))
451     {
452       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
453       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
454
455       if (DECL_TEMPLATE_SPECIALIZATION (decl))
456         {
457           --levels;
458           parms = TREE_CHAIN (parms);
459         }
460
461       push_inline_template_parms_recursive (parms, levels);
462     }
463
464   /* Remember how many levels of template parameters we pushed so that
465      we can pop them later.  */
466   VEC_safe_push (int, heap, inline_parm_levels, levels);
467 }
468
469 /* Undo the effects of maybe_begin_member_template_processing.  */
470
471 void
472 maybe_end_member_template_processing (void)
473 {
474   int i;
475   int last;
476
477   if (VEC_length (int, inline_parm_levels) == 0)
478     return;
479
480   last = VEC_pop (int, inline_parm_levels);
481   for (i = 0; i < last; ++i)
482     {
483       --processing_template_decl;
484       current_template_parms = TREE_CHAIN (current_template_parms);
485       poplevel (0, 0, 0);
486     }
487 }
488
489 /* Return a new template argument vector which contains all of ARGS,
490    but has as its innermost set of arguments the EXTRA_ARGS.  */
491
492 static tree
493 add_to_template_args (tree args, tree extra_args)
494 {
495   tree new_args;
496   int extra_depth;
497   int i;
498   int j;
499
500   if (args == NULL_TREE || extra_args == error_mark_node)
501     return extra_args;
502
503   extra_depth = TMPL_ARGS_DEPTH (extra_args);
504   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
505
506   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
507     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
508
509   for (j = 1; j <= extra_depth; ++j, ++i)
510     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
511
512   return new_args;
513 }
514
515 /* Like add_to_template_args, but only the outermost ARGS are added to
516    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
517    (EXTRA_ARGS) levels are added.  This function is used to combine
518    the template arguments from a partial instantiation with the
519    template arguments used to attain the full instantiation from the
520    partial instantiation.  */
521
522 static tree
523 add_outermost_template_args (tree args, tree extra_args)
524 {
525   tree new_args;
526
527   /* If there are more levels of EXTRA_ARGS than there are ARGS,
528      something very fishy is going on.  */
529   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
530
531   /* If *all* the new arguments will be the EXTRA_ARGS, just return
532      them.  */
533   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
534     return extra_args;
535
536   /* For the moment, we make ARGS look like it contains fewer levels.  */
537   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
538
539   new_args = add_to_template_args (args, extra_args);
540
541   /* Now, we restore ARGS to its full dimensions.  */
542   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
543
544   return new_args;
545 }
546
547 /* Return the N levels of innermost template arguments from the ARGS.  */
548
549 tree
550 get_innermost_template_args (tree args, int n)
551 {
552   tree new_args;
553   int extra_levels;
554   int i;
555
556   gcc_assert (n >= 0);
557
558   /* If N is 1, just return the innermost set of template arguments.  */
559   if (n == 1)
560     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
561
562   /* If we're not removing anything, just return the arguments we were
563      given.  */
564   extra_levels = TMPL_ARGS_DEPTH (args) - n;
565   gcc_assert (extra_levels >= 0);
566   if (extra_levels == 0)
567     return args;
568
569   /* Make a new set of arguments, not containing the outer arguments.  */
570   new_args = make_tree_vec (n);
571   for (i = 1; i <= n; ++i)
572     SET_TMPL_ARGS_LEVEL (new_args, i,
573                          TMPL_ARGS_LEVEL (args, i + extra_levels));
574
575   return new_args;
576 }
577
578 /* The inverse of get_innermost_template_args: Return all but the innermost
579    EXTRA_LEVELS levels of template arguments from the ARGS.  */
580
581 static tree
582 strip_innermost_template_args (tree args, int extra_levels)
583 {
584   tree new_args;
585   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
586   int i;
587
588   gcc_assert (n >= 0);
589
590   /* If N is 1, just return the outermost set of template arguments.  */
591   if (n == 1)
592     return TMPL_ARGS_LEVEL (args, 1);
593
594   /* If we're not removing anything, just return the arguments we were
595      given.  */
596   gcc_assert (extra_levels >= 0);
597   if (extra_levels == 0)
598     return args;
599
600   /* Make a new set of arguments, not containing the inner arguments.  */
601   new_args = make_tree_vec (n);
602   for (i = 1; i <= n; ++i)
603     SET_TMPL_ARGS_LEVEL (new_args, i,
604                          TMPL_ARGS_LEVEL (args, i));
605
606   return new_args;
607 }
608
609 /* We've got a template header coming up; push to a new level for storing
610    the parms.  */
611
612 void
613 begin_template_parm_list (void)
614 {
615   /* We use a non-tag-transparent scope here, which causes pushtag to
616      put tags in this scope, rather than in the enclosing class or
617      namespace scope.  This is the right thing, since we want
618      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
619      global template class, push_template_decl handles putting the
620      TEMPLATE_DECL into top-level scope.  For a nested template class,
621      e.g.:
622
623        template <class T> struct S1 {
624          template <class T> struct S2 {};
625        };
626
627      pushtag contains special code to call pushdecl_with_scope on the
628      TEMPLATE_DECL for S2.  */
629   begin_scope (sk_template_parms, NULL);
630   ++processing_template_decl;
631   ++processing_template_parmlist;
632   note_template_header (0);
633 }
634
635 /* This routine is called when a specialization is declared.  If it is
636    invalid to declare a specialization here, an error is reported and
637    false is returned, otherwise this routine will return true.  */
638
639 static bool
640 check_specialization_scope (void)
641 {
642   tree scope = current_scope ();
643
644   /* [temp.expl.spec]
645
646      An explicit specialization shall be declared in the namespace of
647      which the template is a member, or, for member templates, in the
648      namespace of which the enclosing class or enclosing class
649      template is a member.  An explicit specialization of a member
650      function, member class or static data member of a class template
651      shall be declared in the namespace of which the class template
652      is a member.  */
653   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
654     {
655       error ("explicit specialization in non-namespace scope %qD", scope);
656       return false;
657     }
658
659   /* [temp.expl.spec]
660
661      In an explicit specialization declaration for a member of a class
662      template or a member template that appears in namespace scope,
663      the member template and some of its enclosing class templates may
664      remain unspecialized, except that the declaration shall not
665      explicitly specialize a class member template if its enclosing
666      class templates are not explicitly specialized as well.  */
667   if (current_template_parms)
668     {
669       error ("enclosing class templates are not explicitly specialized");
670       return false;
671     }
672
673   return true;
674 }
675
676 /* We've just seen template <>.  */
677
678 bool
679 begin_specialization (void)
680 {
681   begin_scope (sk_template_spec, NULL);
682   note_template_header (1);
683   return check_specialization_scope ();
684 }
685
686 /* Called at then end of processing a declaration preceded by
687    template<>.  */
688
689 void
690 end_specialization (void)
691 {
692   finish_scope ();
693   reset_specialization ();
694 }
695
696 /* Any template <>'s that we have seen thus far are not referring to a
697    function specialization.  */
698
699 void
700 reset_specialization (void)
701 {
702   processing_specialization = 0;
703   template_header_count = 0;
704 }
705
706 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
707    it was of the form template <>.  */
708
709 static void
710 note_template_header (int specialization)
711 {
712   processing_specialization = specialization;
713   template_header_count++;
714 }
715
716 /* We're beginning an explicit instantiation.  */
717
718 void
719 begin_explicit_instantiation (void)
720 {
721   gcc_assert (!processing_explicit_instantiation);
722   processing_explicit_instantiation = true;
723 }
724
725
726 void
727 end_explicit_instantiation (void)
728 {
729   gcc_assert (processing_explicit_instantiation);
730   processing_explicit_instantiation = false;
731 }
732
733 /* An explicit specialization or partial specialization TMPL is being
734    declared.  Check that the namespace in which the specialization is
735    occurring is permissible.  Returns false iff it is invalid to
736    specialize TMPL in the current namespace.  */
737
738 static bool
739 check_specialization_namespace (tree tmpl)
740 {
741   tree tpl_ns = decl_namespace_context (tmpl);
742
743   /* [tmpl.expl.spec]
744
745      An explicit specialization shall be declared in the namespace of
746      which the template is a member, or, for member templates, in the
747      namespace of which the enclosing class or enclosing class
748      template is a member.  An explicit specialization of a member
749      function, member class or static data member of a class template
750      shall be declared in the namespace of which the class template is
751      a member.  */
752   if (current_scope() != DECL_CONTEXT (tmpl)
753       && !at_namespace_scope_p ())
754     {
755       error ("specialization of %qD must appear at namespace scope", tmpl);
756       return false;
757     }
758   if (is_associated_namespace (current_namespace, tpl_ns))
759     /* Same or super-using namespace.  */
760     return true;
761   else
762     {
763       permerror (input_location, "specialization of %qD in different namespace", tmpl);
764       permerror (input_location, "  from definition of %q+#D", tmpl);
765       return false;
766     }
767 }
768
769 /* SPEC is an explicit instantiation.  Check that it is valid to
770    perform this explicit instantiation in the current namespace.  */
771
772 static void
773 check_explicit_instantiation_namespace (tree spec)
774 {
775   tree ns;
776
777   /* DR 275: An explicit instantiation shall appear in an enclosing
778      namespace of its template.  */
779   ns = decl_namespace_context (spec);
780   if (!is_ancestor (current_namespace, ns))
781     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
782                "(which does not enclose namespace %qD)",
783                spec, current_namespace, ns);
784 }
785
786 /* The TYPE is being declared.  If it is a template type, that means it
787    is a partial specialization.  Do appropriate error-checking.  */
788
789 tree
790 maybe_process_partial_specialization (tree type)
791 {
792   tree context;
793
794   if (type == error_mark_node)
795     return error_mark_node;
796
797   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
798     {
799       error ("name of class shadows template template parameter %qD",
800              TYPE_NAME (type));
801       return error_mark_node;
802     }
803
804   context = TYPE_CONTEXT (type);
805
806   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
807     {
808       /* This is for ordinary explicit specialization and partial
809          specialization of a template class such as:
810
811            template <> class C<int>;
812
813          or:
814
815            template <class T> class C<T*>;
816
817          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
818
819       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
820           && !COMPLETE_TYPE_P (type))
821         {
822           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
823           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
824           if (processing_template_decl)
825             {
826               if (push_template_decl (TYPE_MAIN_DECL (type))
827                   == error_mark_node)
828                 return error_mark_node;
829             }
830         }
831       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
832         error ("specialization of %qT after instantiation", type);
833     }
834   else if (CLASS_TYPE_P (type)
835            && !CLASSTYPE_USE_TEMPLATE (type)
836            && CLASSTYPE_TEMPLATE_INFO (type)
837            && context && CLASS_TYPE_P (context)
838            && CLASSTYPE_TEMPLATE_INFO (context))
839     {
840       /* This is for an explicit specialization of member class
841          template according to [temp.expl.spec/18]:
842
843            template <> template <class U> class C<int>::D;
844
845          The context `C<int>' must be an implicit instantiation.
846          Otherwise this is just a member class template declared
847          earlier like:
848
849            template <> class C<int> { template <class U> class D; };
850            template <> template <class U> class C<int>::D;
851
852          In the first case, `C<int>::D' is a specialization of `C<T>::D'
853          while in the second case, `C<int>::D' is a primary template
854          and `C<T>::D' may not exist.  */
855
856       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
857           && !COMPLETE_TYPE_P (type))
858         {
859           tree t;
860           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
861
862           if (current_namespace
863               != decl_namespace_context (tmpl))
864             {
865               permerror (input_location, "specializing %q#T in different namespace", type);
866               permerror (input_location, "  from definition of %q+#D", tmpl);
867             }
868
869           /* Check for invalid specialization after instantiation:
870
871                template <> template <> class C<int>::D<int>;
872                template <> template <class U> class C<int>::D;  */
873
874           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
875                t; t = TREE_CHAIN (t))
876             {
877               tree inst = TREE_VALUE (t);
878               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
879                 {
880                   /* We already have a full specialization of this partial
881                      instantiation.  Reassign it to the new member
882                      specialization template.  */
883                   spec_entry elt;
884                   spec_entry **slot;
885
886                   elt.tmpl = most_general_template (tmpl);
887                   elt.args = CLASSTYPE_TI_ARGS (inst);
888                   elt.spec = inst;
889
890                   htab_remove_elt (type_specializations, &elt);
891
892                   elt.tmpl = tmpl;
893                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
894
895                   slot = (spec_entry **)
896                     htab_find_slot (type_specializations, &elt, INSERT);
897                   *slot = ggc_alloc_spec_entry ();
898                   **slot = elt;
899                 }
900               else if (COMPLETE_OR_OPEN_TYPE_P (inst))
901                 /* But if we've had an implicit instantiation, that's a
902                    problem ([temp.expl.spec]/6).  */
903                 error ("specialization %qT after instantiation %qT",
904                        type, inst);
905             }
906
907           /* Mark TYPE as a specialization.  And as a result, we only
908              have one level of template argument for the innermost
909              class template.  */
910           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
911           CLASSTYPE_TI_ARGS (type)
912             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
913         }
914     }
915   else if (processing_specialization)
916     {
917        /* Someday C++0x may allow for enum template specialization.  */
918       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
919           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
920         pedwarn (input_location, OPT_pedantic, "template specialization "
921                  "of %qD not allowed by ISO C++", type);
922       else
923         {
924           error ("explicit specialization of non-template %qT", type);
925           return error_mark_node;
926         }
927     }
928
929   return type;
930 }
931
932 /* Returns nonzero if we can optimize the retrieval of specializations
933    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
934    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
935
936 static inline bool
937 optimize_specialization_lookup_p (tree tmpl)
938 {
939   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
940           && DECL_CLASS_SCOPE_P (tmpl)
941           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
942              parameter.  */
943           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
944           /* The optimized lookup depends on the fact that the
945              template arguments for the member function template apply
946              purely to the containing class, which is not true if the
947              containing class is an explicit or partial
948              specialization.  */
949           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
950           && !DECL_MEMBER_TEMPLATE_P (tmpl)
951           && !DECL_CONV_FN_P (tmpl)
952           /* It is possible to have a template that is not a member
953              template and is not a member of a template class:
954
955              template <typename T>
956              struct S { friend A::f(); };
957
958              Here, the friend function is a template, but the context does
959              not have template information.  The optimized lookup relies
960              on having ARGS be the template arguments for both the class
961              and the function template.  */
962           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
963 }
964
965 /* Retrieve the specialization (in the sense of [temp.spec] - a
966    specialization is either an instantiation or an explicit
967    specialization) of TMPL for the given template ARGS.  If there is
968    no such specialization, return NULL_TREE.  The ARGS are a vector of
969    arguments, or a vector of vectors of arguments, in the case of
970    templates with more than one level of parameters.
971
972    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
973    then we search for a partial specialization matching ARGS.  This
974    parameter is ignored if TMPL is not a class template.  */
975
976 static tree
977 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
978 {
979   if (args == error_mark_node)
980     return NULL_TREE;
981
982   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
983
984   /* There should be as many levels of arguments as there are
985      levels of parameters.  */
986   gcc_assert (TMPL_ARGS_DEPTH (args)
987               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
988
989   if (optimize_specialization_lookup_p (tmpl))
990     {
991       tree class_template;
992       tree class_specialization;
993       VEC(tree,gc) *methods;
994       tree fns;
995       int idx;
996
997       /* The template arguments actually apply to the containing
998          class.  Find the class specialization with those
999          arguments.  */
1000       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1001       class_specialization
1002         = retrieve_specialization (class_template, args, 0);
1003       if (!class_specialization)
1004         return NULL_TREE;
1005       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
1006          for the specialization.  */
1007       idx = class_method_index_for_fn (class_specialization, tmpl);
1008       if (idx == -1)
1009         return NULL_TREE;
1010       /* Iterate through the methods with the indicated name, looking
1011          for the one that has an instance of TMPL.  */
1012       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1013       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1014         {
1015           tree fn = OVL_CURRENT (fns);
1016           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1017               /* using-declarations can add base methods to the method vec,
1018                  and we don't want those here.  */
1019               && DECL_CONTEXT (fn) == class_specialization)
1020             return fn;
1021         }
1022       return NULL_TREE;
1023     }
1024   else
1025     {
1026       spec_entry *found;
1027       spec_entry elt;
1028       htab_t specializations;
1029
1030       elt.tmpl = tmpl;
1031       elt.args = args;
1032       elt.spec = NULL_TREE;
1033
1034       if (DECL_CLASS_TEMPLATE_P (tmpl))
1035         specializations = type_specializations;
1036       else
1037         specializations = decl_specializations;
1038
1039       if (hash == 0)
1040         hash = hash_specialization (&elt);
1041       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1042       if (found)
1043         return found->spec;
1044     }
1045
1046   return NULL_TREE;
1047 }
1048
1049 /* Like retrieve_specialization, but for local declarations.  */
1050
1051 static tree
1052 retrieve_local_specialization (tree tmpl)
1053 {
1054   tree spec;
1055
1056   if (local_specializations == NULL)
1057     return NULL_TREE;
1058
1059   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1060                                      htab_hash_pointer (tmpl));
1061   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1062 }
1063
1064 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1065
1066 int
1067 is_specialization_of (tree decl, tree tmpl)
1068 {
1069   tree t;
1070
1071   if (TREE_CODE (decl) == FUNCTION_DECL)
1072     {
1073       for (t = decl;
1074            t != NULL_TREE;
1075            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1076         if (t == tmpl)
1077           return 1;
1078     }
1079   else
1080     {
1081       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1082
1083       for (t = TREE_TYPE (decl);
1084            t != NULL_TREE;
1085            t = CLASSTYPE_USE_TEMPLATE (t)
1086              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1087         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1088           return 1;
1089     }
1090
1091   return 0;
1092 }
1093
1094 /* Returns nonzero iff DECL is a specialization of friend declaration
1095    FRIEND_DECL according to [temp.friend].  */
1096
1097 bool
1098 is_specialization_of_friend (tree decl, tree friend_decl)
1099 {
1100   bool need_template = true;
1101   int template_depth;
1102
1103   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1104               || TREE_CODE (decl) == TYPE_DECL);
1105
1106   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1107      of a template class, we want to check if DECL is a specialization
1108      if this.  */
1109   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1110       && DECL_TEMPLATE_INFO (friend_decl)
1111       && !DECL_USE_TEMPLATE (friend_decl))
1112     {
1113       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1114       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1115       need_template = false;
1116     }
1117   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1118            && !PRIMARY_TEMPLATE_P (friend_decl))
1119     need_template = false;
1120
1121   /* There is nothing to do if this is not a template friend.  */
1122   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1123     return false;
1124
1125   if (is_specialization_of (decl, friend_decl))
1126     return true;
1127
1128   /* [temp.friend/6]
1129      A member of a class template may be declared to be a friend of a
1130      non-template class.  In this case, the corresponding member of
1131      every specialization of the class template is a friend of the
1132      class granting friendship.
1133
1134      For example, given a template friend declaration
1135
1136        template <class T> friend void A<T>::f();
1137
1138      the member function below is considered a friend
1139
1140        template <> struct A<int> {
1141          void f();
1142        };
1143
1144      For this type of template friend, TEMPLATE_DEPTH below will be
1145      nonzero.  To determine if DECL is a friend of FRIEND, we first
1146      check if the enclosing class is a specialization of another.  */
1147
1148   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1149   if (template_depth
1150       && DECL_CLASS_SCOPE_P (decl)
1151       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1152                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1153     {
1154       /* Next, we check the members themselves.  In order to handle
1155          a few tricky cases, such as when FRIEND_DECL's are
1156
1157            template <class T> friend void A<T>::g(T t);
1158            template <class T> template <T t> friend void A<T>::h();
1159
1160          and DECL's are
1161
1162            void A<int>::g(int);
1163            template <int> void A<int>::h();
1164
1165          we need to figure out ARGS, the template arguments from
1166          the context of DECL.  This is required for template substitution
1167          of `T' in the function parameter of `g' and template parameter
1168          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1169
1170       tree context = DECL_CONTEXT (decl);
1171       tree args = NULL_TREE;
1172       int current_depth = 0;
1173
1174       while (current_depth < template_depth)
1175         {
1176           if (CLASSTYPE_TEMPLATE_INFO (context))
1177             {
1178               if (current_depth == 0)
1179                 args = TYPE_TI_ARGS (context);
1180               else
1181                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1182               current_depth++;
1183             }
1184           context = TYPE_CONTEXT (context);
1185         }
1186
1187       if (TREE_CODE (decl) == FUNCTION_DECL)
1188         {
1189           bool is_template;
1190           tree friend_type;
1191           tree decl_type;
1192           tree friend_args_type;
1193           tree decl_args_type;
1194
1195           /* Make sure that both DECL and FRIEND_DECL are templates or
1196              non-templates.  */
1197           is_template = DECL_TEMPLATE_INFO (decl)
1198                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1199           if (need_template ^ is_template)
1200             return false;
1201           else if (is_template)
1202             {
1203               /* If both are templates, check template parameter list.  */
1204               tree friend_parms
1205                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1206                                          args, tf_none);
1207               if (!comp_template_parms
1208                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1209                       friend_parms))
1210                 return false;
1211
1212               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1213             }
1214           else
1215             decl_type = TREE_TYPE (decl);
1216
1217           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1218                                               tf_none, NULL_TREE);
1219           if (friend_type == error_mark_node)
1220             return false;
1221
1222           /* Check if return types match.  */
1223           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1224             return false;
1225
1226           /* Check if function parameter types match, ignoring the
1227              `this' parameter.  */
1228           friend_args_type = TYPE_ARG_TYPES (friend_type);
1229           decl_args_type = TYPE_ARG_TYPES (decl_type);
1230           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1231             friend_args_type = TREE_CHAIN (friend_args_type);
1232           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1233             decl_args_type = TREE_CHAIN (decl_args_type);
1234
1235           return compparms (decl_args_type, friend_args_type);
1236         }
1237       else
1238         {
1239           /* DECL is a TYPE_DECL */
1240           bool is_template;
1241           tree decl_type = TREE_TYPE (decl);
1242
1243           /* Make sure that both DECL and FRIEND_DECL are templates or
1244              non-templates.  */
1245           is_template
1246             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1247               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1248
1249           if (need_template ^ is_template)
1250             return false;
1251           else if (is_template)
1252             {
1253               tree friend_parms;
1254               /* If both are templates, check the name of the two
1255                  TEMPLATE_DECL's first because is_friend didn't.  */
1256               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1257                   != DECL_NAME (friend_decl))
1258                 return false;
1259
1260               /* Now check template parameter list.  */
1261               friend_parms
1262                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1263                                          args, tf_none);
1264               return comp_template_parms
1265                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1266                  friend_parms);
1267             }
1268           else
1269             return (DECL_NAME (decl)
1270                     == DECL_NAME (friend_decl));
1271         }
1272     }
1273   return false;
1274 }
1275
1276 /* Register the specialization SPEC as a specialization of TMPL with
1277    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1278    is actually just a friend declaration.  Returns SPEC, or an
1279    equivalent prior declaration, if available.  */
1280
1281 static tree
1282 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1283                          hashval_t hash)
1284 {
1285   tree fn;
1286   spec_entry **slot = NULL;
1287   spec_entry elt;
1288
1289   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1290
1291   if (TREE_CODE (spec) == FUNCTION_DECL
1292       && uses_template_parms (DECL_TI_ARGS (spec)))
1293     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1294        register it; we want the corresponding TEMPLATE_DECL instead.
1295        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1296        the more obvious `uses_template_parms (spec)' to avoid problems
1297        with default function arguments.  In particular, given
1298        something like this:
1299
1300           template <class T> void f(T t1, T t = T())
1301
1302        the default argument expression is not substituted for in an
1303        instantiation unless and until it is actually needed.  */
1304     return spec;
1305
1306   if (optimize_specialization_lookup_p (tmpl))
1307     /* We don't put these specializations in the hash table, but we might
1308        want to give an error about a mismatch.  */
1309     fn = retrieve_specialization (tmpl, args, 0);
1310   else
1311     {
1312       elt.tmpl = tmpl;
1313       elt.args = args;
1314       elt.spec = spec;
1315
1316       if (hash == 0)
1317         hash = hash_specialization (&elt);
1318
1319       slot = (spec_entry **)
1320         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1321       if (*slot)
1322         fn = (*slot)->spec;
1323       else
1324         fn = NULL_TREE;
1325     }
1326
1327   /* We can sometimes try to re-register a specialization that we've
1328      already got.  In particular, regenerate_decl_from_template calls
1329      duplicate_decls which will update the specialization list.  But,
1330      we'll still get called again here anyhow.  It's more convenient
1331      to simply allow this than to try to prevent it.  */
1332   if (fn == spec)
1333     return spec;
1334   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1335     {
1336       if (DECL_TEMPLATE_INSTANTIATION (fn))
1337         {
1338           if (DECL_ODR_USED (fn)
1339               || DECL_EXPLICIT_INSTANTIATION (fn))
1340             {
1341               error ("specialization of %qD after instantiation",
1342                      fn);
1343               return error_mark_node;
1344             }
1345           else
1346             {
1347               tree clone;
1348               /* This situation should occur only if the first
1349                  specialization is an implicit instantiation, the
1350                  second is an explicit specialization, and the
1351                  implicit instantiation has not yet been used.  That
1352                  situation can occur if we have implicitly
1353                  instantiated a member function and then specialized
1354                  it later.
1355
1356                  We can also wind up here if a friend declaration that
1357                  looked like an instantiation turns out to be a
1358                  specialization:
1359
1360                    template <class T> void foo(T);
1361                    class S { friend void foo<>(int) };
1362                    template <> void foo(int);
1363
1364                  We transform the existing DECL in place so that any
1365                  pointers to it become pointers to the updated
1366                  declaration.
1367
1368                  If there was a definition for the template, but not
1369                  for the specialization, we want this to look as if
1370                  there were no definition, and vice versa.  */
1371               DECL_INITIAL (fn) = NULL_TREE;
1372               duplicate_decls (spec, fn, is_friend);
1373               /* The call to duplicate_decls will have applied
1374                  [temp.expl.spec]:
1375
1376                    An explicit specialization of a function template
1377                    is inline only if it is explicitly declared to be,
1378                    and independently of whether its function template
1379                    is.
1380
1381                 to the primary function; now copy the inline bits to
1382                 the various clones.  */
1383               FOR_EACH_CLONE (clone, fn)
1384                 {
1385                   DECL_DECLARED_INLINE_P (clone)
1386                     = DECL_DECLARED_INLINE_P (fn);
1387                   DECL_SOURCE_LOCATION (clone)
1388                     = DECL_SOURCE_LOCATION (fn);
1389                 }
1390               check_specialization_namespace (fn);
1391
1392               return fn;
1393             }
1394         }
1395       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1396         {
1397           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1398             /* Dup decl failed, but this is a new definition. Set the
1399                line number so any errors match this new
1400                definition.  */
1401             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1402
1403           return fn;
1404         }
1405     }
1406   else if (fn)
1407     return duplicate_decls (spec, fn, is_friend);
1408
1409   /* A specialization must be declared in the same namespace as the
1410      template it is specializing.  */
1411   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1412       && !check_specialization_namespace (tmpl))
1413     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1414
1415   if (!optimize_specialization_lookup_p (tmpl))
1416     {
1417       gcc_assert (tmpl && args && spec);
1418       *slot = ggc_alloc_spec_entry ();
1419       **slot = elt;
1420       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1421           && PRIMARY_TEMPLATE_P (tmpl)
1422           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1423         /* TMPL is a forward declaration of a template function; keep a list
1424            of all specializations in case we need to reassign them to a friend
1425            template later in tsubst_friend_function.  */
1426         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1427           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1428     }
1429
1430   return spec;
1431 }
1432
1433 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1434    TMPL and ARGS members, ignores SPEC.  */
1435
1436 static int
1437 eq_specializations (const void *p1, const void *p2)
1438 {
1439   const spec_entry *e1 = (const spec_entry *)p1;
1440   const spec_entry *e2 = (const spec_entry *)p2;
1441
1442   return (e1->tmpl == e2->tmpl
1443           && comp_template_args (e1->args, e2->args));
1444 }
1445
1446 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1447
1448 static hashval_t
1449 hash_tmpl_and_args (tree tmpl, tree args)
1450 {
1451   hashval_t val = DECL_UID (tmpl);
1452   return iterative_hash_template_arg (args, val);
1453 }
1454
1455 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1456    ignoring SPEC.  */
1457
1458 static hashval_t
1459 hash_specialization (const void *p)
1460 {
1461   const spec_entry *e = (const spec_entry *)p;
1462   return hash_tmpl_and_args (e->tmpl, e->args);
1463 }
1464
1465 /* Recursively calculate a hash value for a template argument ARG, for use
1466    in the hash tables of template specializations.  */
1467
1468 hashval_t
1469 iterative_hash_template_arg (tree arg, hashval_t val)
1470 {
1471   unsigned HOST_WIDE_INT i;
1472   enum tree_code code;
1473   char tclass;
1474
1475   if (arg == NULL_TREE)
1476     return iterative_hash_object (arg, val);
1477
1478   if (!TYPE_P (arg))
1479     STRIP_NOPS (arg);
1480
1481   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1482     /* We can get one of these when re-hashing a previous entry in the middle
1483        of substituting into a pack expansion.  Just look through it.  */
1484     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1485
1486   code = TREE_CODE (arg);
1487   tclass = TREE_CODE_CLASS (code);
1488
1489   val = iterative_hash_object (code, val);
1490
1491   switch (code)
1492     {
1493     case ERROR_MARK:
1494       return val;
1495
1496     case IDENTIFIER_NODE:
1497       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1498
1499     case TREE_VEC:
1500       {
1501         int i, len = TREE_VEC_LENGTH (arg);
1502         for (i = 0; i < len; ++i)
1503           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1504         return val;
1505       }
1506
1507     case TYPE_PACK_EXPANSION:
1508     case EXPR_PACK_EXPANSION:
1509       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1510
1511     case TYPE_ARGUMENT_PACK:
1512     case NONTYPE_ARGUMENT_PACK:
1513       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1514
1515     case TREE_LIST:
1516       for (; arg; arg = TREE_CHAIN (arg))
1517         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1518       return val;
1519
1520     case OVERLOAD:
1521       for (; arg; arg = OVL_NEXT (arg))
1522         val = iterative_hash_template_arg (OVL_CURRENT (arg), val);
1523       return val;
1524
1525     case CONSTRUCTOR:
1526       {
1527         tree field, value;
1528         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1529           {
1530             val = iterative_hash_template_arg (field, val);
1531             val = iterative_hash_template_arg (value, val);
1532           }
1533         return val;
1534       }
1535
1536     case PARM_DECL:
1537       if (!DECL_ARTIFICIAL (arg))
1538         {
1539           val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1540           val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1541         }
1542       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1543
1544     case TARGET_EXPR:
1545       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1546
1547     case PTRMEM_CST:
1548       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1549       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1550
1551     case TEMPLATE_PARM_INDEX:
1552       val = iterative_hash_template_arg
1553         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1554       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1555       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1556
1557     case TRAIT_EXPR:
1558       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1559       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1560       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1561
1562     case BASELINK:
1563       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1564                                          val);
1565       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1566                                           val);
1567
1568     case MODOP_EXPR:
1569       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1570       code = TREE_CODE (TREE_OPERAND (arg, 1));
1571       val = iterative_hash_object (code, val);
1572       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1573
1574     case LAMBDA_EXPR:
1575       /* A lambda can't appear in a template arg, but don't crash on
1576          erroneous input.  */
1577       gcc_assert (seen_error ());
1578       return val;
1579
1580     case CAST_EXPR:
1581     case STATIC_CAST_EXPR:
1582     case REINTERPRET_CAST_EXPR:
1583     case CONST_CAST_EXPR:
1584     case DYNAMIC_CAST_EXPR:
1585     case NEW_EXPR:
1586       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1587       /* Now hash operands as usual.  */
1588       break;
1589
1590     default:
1591       break;
1592     }
1593
1594   switch (tclass)
1595     {
1596     case tcc_type:
1597       if (TYPE_CANONICAL (arg))
1598         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1599                                       val);
1600       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1601         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1602       /* Otherwise just compare the types during lookup.  */
1603       return val;
1604
1605     case tcc_declaration:
1606     case tcc_constant:
1607       return iterative_hash_expr (arg, val);
1608
1609     default:
1610       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1611       {
1612         unsigned n = TREE_OPERAND_LENGTH (arg);
1613         for (i = 0; i < n; ++i)
1614           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1615         return val;
1616       }
1617     }
1618   gcc_unreachable ();
1619   return 0;
1620 }
1621
1622 /* Unregister the specialization SPEC as a specialization of TMPL.
1623    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1624    if the SPEC was listed as a specialization of TMPL.
1625
1626    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1627
1628 bool
1629 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1630 {
1631   spec_entry **slot;
1632   spec_entry elt;
1633
1634   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1635   elt.args = TI_ARGS (tinfo);
1636   elt.spec = NULL_TREE;
1637
1638   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1639   if (*slot)
1640     {
1641       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1642       gcc_assert (new_spec != NULL_TREE);
1643       (*slot)->spec = new_spec;
1644       return 1;
1645     }
1646
1647   return 0;
1648 }
1649
1650 /* Compare an entry in the local specializations hash table P1 (which
1651    is really a pointer to a TREE_LIST) with P2 (which is really a
1652    DECL).  */
1653
1654 static int
1655 eq_local_specializations (const void *p1, const void *p2)
1656 {
1657   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1658 }
1659
1660 /* Hash P1, an entry in the local specializations table.  */
1661
1662 static hashval_t
1663 hash_local_specialization (const void* p1)
1664 {
1665   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1666 }
1667
1668 /* Like register_specialization, but for local declarations.  We are
1669    registering SPEC, an instantiation of TMPL.  */
1670
1671 static void
1672 register_local_specialization (tree spec, tree tmpl)
1673 {
1674   void **slot;
1675
1676   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1677                                    htab_hash_pointer (tmpl), INSERT);
1678   *slot = build_tree_list (spec, tmpl);
1679 }
1680
1681 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1682    specialized class.  */
1683
1684 bool
1685 explicit_class_specialization_p (tree type)
1686 {
1687   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1688     return false;
1689   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1690 }
1691
1692 /* Print the list of functions at FNS, going through all the overloads
1693    for each element of the list.  Alternatively, FNS can not be a
1694    TREE_LIST, in which case it will be printed together with all the
1695    overloads.
1696
1697    MORE and *STR should respectively be FALSE and NULL when the function
1698    is called from the outside.  They are used internally on recursive
1699    calls.  print_candidates manages the two parameters and leaves NULL
1700    in *STR when it ends.  */
1701
1702 static void
1703 print_candidates_1 (tree fns, bool more, const char **str)
1704 {
1705   tree fn, fn2;
1706   char *spaces = NULL;
1707
1708   for (fn = fns; fn; fn = OVL_NEXT (fn))
1709     if (TREE_CODE (fn) == TREE_LIST)
1710       {
1711         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1712           print_candidates_1 (TREE_VALUE (fn2),
1713                               TREE_CHAIN (fn2) || more, str);
1714       }
1715     else
1716       {
1717         if (!*str)
1718           {
1719             /* Pick the prefix string.  */
1720             if (!more && !OVL_NEXT (fns))
1721               {
1722                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1723                 continue;
1724               }
1725
1726             *str = _("candidates are:");
1727             spaces = get_spaces (*str);
1728           }
1729         error ("%s %+#D", *str, OVL_CURRENT (fn));
1730         *str = spaces ? spaces : *str;
1731       }
1732
1733   if (!more)
1734     {
1735       free (spaces);
1736       *str = NULL;
1737     }
1738 }
1739
1740 /* Print the list of candidate FNS in an error message.  FNS can also
1741    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1742
1743 void
1744 print_candidates (tree fns)
1745 {
1746   const char *str = NULL;
1747   print_candidates_1 (fns, false, &str);
1748   gcc_assert (str == NULL);
1749 }
1750
1751 /* Returns the template (one of the functions given by TEMPLATE_ID)
1752    which can be specialized to match the indicated DECL with the
1753    explicit template args given in TEMPLATE_ID.  The DECL may be
1754    NULL_TREE if none is available.  In that case, the functions in
1755    TEMPLATE_ID are non-members.
1756
1757    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1758    specialization of a member template.
1759
1760    The TEMPLATE_COUNT is the number of references to qualifying
1761    template classes that appeared in the name of the function. See
1762    check_explicit_specialization for a more accurate description.
1763
1764    TSK indicates what kind of template declaration (if any) is being
1765    declared.  TSK_TEMPLATE indicates that the declaration given by
1766    DECL, though a FUNCTION_DECL, has template parameters, and is
1767    therefore a template function.
1768
1769    The template args (those explicitly specified and those deduced)
1770    are output in a newly created vector *TARGS_OUT.
1771
1772    If it is impossible to determine the result, an error message is
1773    issued.  The error_mark_node is returned to indicate failure.  */
1774
1775 static tree
1776 determine_specialization (tree template_id,
1777                           tree decl,
1778                           tree* targs_out,
1779                           int need_member_template,
1780                           int template_count,
1781                           tmpl_spec_kind tsk)
1782 {
1783   tree fns;
1784   tree targs;
1785   tree explicit_targs;
1786   tree candidates = NULL_TREE;
1787   /* A TREE_LIST of templates of which DECL may be a specialization.
1788      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1789      corresponding TREE_PURPOSE is the set of template arguments that,
1790      when used to instantiate the template, would produce a function
1791      with the signature of DECL.  */
1792   tree templates = NULL_TREE;
1793   int header_count;
1794   struct cp_binding_level *b;
1795
1796   *targs_out = NULL_TREE;
1797
1798   if (template_id == error_mark_node || decl == error_mark_node)
1799     return error_mark_node;
1800
1801   fns = TREE_OPERAND (template_id, 0);
1802   explicit_targs = TREE_OPERAND (template_id, 1);
1803
1804   if (fns == error_mark_node)
1805     return error_mark_node;
1806
1807   /* Check for baselinks.  */
1808   if (BASELINK_P (fns))
1809     fns = BASELINK_FUNCTIONS (fns);
1810
1811   if (!is_overloaded_fn (fns))
1812     {
1813       error ("%qD is not a function template", fns);
1814       return error_mark_node;
1815     }
1816
1817   /* Count the number of template headers specified for this
1818      specialization.  */
1819   header_count = 0;
1820   for (b = current_binding_level;
1821        b->kind == sk_template_parms;
1822        b = b->level_chain)
1823     ++header_count;
1824
1825   for (; fns; fns = OVL_NEXT (fns))
1826     {
1827       tree fn = OVL_CURRENT (fns);
1828
1829       if (TREE_CODE (fn) == TEMPLATE_DECL)
1830         {
1831           tree decl_arg_types;
1832           tree fn_arg_types;
1833
1834           /* In case of explicit specialization, we need to check if
1835              the number of template headers appearing in the specialization
1836              is correct. This is usually done in check_explicit_specialization,
1837              but the check done there cannot be exhaustive when specializing
1838              member functions. Consider the following code:
1839
1840              template <> void A<int>::f(int);
1841              template <> template <> void A<int>::f(int);
1842
1843              Assuming that A<int> is not itself an explicit specialization
1844              already, the first line specializes "f" which is a non-template
1845              member function, whilst the second line specializes "f" which
1846              is a template member function. So both lines are syntactically
1847              correct, and check_explicit_specialization does not reject
1848              them.
1849
1850              Here, we can do better, as we are matching the specialization
1851              against the declarations. We count the number of template
1852              headers, and we check if they match TEMPLATE_COUNT + 1
1853              (TEMPLATE_COUNT is the number of qualifying template classes,
1854              plus there must be another header for the member template
1855              itself).
1856
1857              Notice that if header_count is zero, this is not a
1858              specialization but rather a template instantiation, so there
1859              is no check we can perform here.  */
1860           if (header_count && header_count != template_count + 1)
1861             continue;
1862
1863           /* Check that the number of template arguments at the
1864              innermost level for DECL is the same as for FN.  */
1865           if (current_binding_level->kind == sk_template_parms
1866               && !current_binding_level->explicit_spec_p
1867               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1868                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1869                                       (current_template_parms))))
1870             continue;
1871
1872           /* DECL might be a specialization of FN.  */
1873           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1874           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1875
1876           /* For a non-static member function, we need to make sure
1877              that the const qualification is the same.  Since
1878              get_bindings does not try to merge the "this" parameter,
1879              we must do the comparison explicitly.  */
1880           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1881               && !same_type_p (TREE_VALUE (fn_arg_types),
1882                                TREE_VALUE (decl_arg_types)))
1883             continue;
1884
1885           /* Skip the "this" parameter and, for constructors of
1886              classes with virtual bases, the VTT parameter.  A
1887              full specialization of a constructor will have a VTT
1888              parameter, but a template never will.  */ 
1889           decl_arg_types 
1890             = skip_artificial_parms_for (decl, decl_arg_types);
1891           fn_arg_types 
1892             = skip_artificial_parms_for (fn, fn_arg_types);
1893
1894           /* Check that the number of function parameters matches.
1895              For example,
1896                template <class T> void f(int i = 0);
1897                template <> void f<int>();
1898              The specialization f<int> is invalid but is not caught
1899              by get_bindings below.  */
1900           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1901             continue;
1902
1903           /* Function templates cannot be specializations; there are
1904              no partial specializations of functions.  Therefore, if
1905              the type of DECL does not match FN, there is no
1906              match.  */
1907           if (tsk == tsk_template)
1908             {
1909               if (compparms (fn_arg_types, decl_arg_types))
1910                 candidates = tree_cons (NULL_TREE, fn, candidates);
1911               continue;
1912             }
1913
1914           /* See whether this function might be a specialization of this
1915              template.  */
1916           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1917
1918           if (!targs)
1919             /* We cannot deduce template arguments that when used to
1920                specialize TMPL will produce DECL.  */
1921             continue;
1922
1923           /* Save this template, and the arguments deduced.  */
1924           templates = tree_cons (targs, fn, templates);
1925         }
1926       else if (need_member_template)
1927         /* FN is an ordinary member function, and we need a
1928            specialization of a member template.  */
1929         ;
1930       else if (TREE_CODE (fn) != FUNCTION_DECL)
1931         /* We can get IDENTIFIER_NODEs here in certain erroneous
1932            cases.  */
1933         ;
1934       else if (!DECL_FUNCTION_MEMBER_P (fn))
1935         /* This is just an ordinary non-member function.  Nothing can
1936            be a specialization of that.  */
1937         ;
1938       else if (DECL_ARTIFICIAL (fn))
1939         /* Cannot specialize functions that are created implicitly.  */
1940         ;
1941       else
1942         {
1943           tree decl_arg_types;
1944
1945           /* This is an ordinary member function.  However, since
1946              we're here, we can assume it's enclosing class is a
1947              template class.  For example,
1948
1949                template <typename T> struct S { void f(); };
1950                template <> void S<int>::f() {}
1951
1952              Here, S<int>::f is a non-template, but S<int> is a
1953              template class.  If FN has the same type as DECL, we
1954              might be in business.  */
1955
1956           if (!DECL_TEMPLATE_INFO (fn))
1957             /* Its enclosing class is an explicit specialization
1958                of a template class.  This is not a candidate.  */
1959             continue;
1960
1961           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1962                             TREE_TYPE (TREE_TYPE (fn))))
1963             /* The return types differ.  */
1964             continue;
1965
1966           /* Adjust the type of DECL in case FN is a static member.  */
1967           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1968           if (DECL_STATIC_FUNCTION_P (fn)
1969               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1970             decl_arg_types = TREE_CHAIN (decl_arg_types);
1971
1972           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1973                          decl_arg_types))
1974             /* They match!  */
1975             candidates = tree_cons (NULL_TREE, fn, candidates);
1976         }
1977     }
1978
1979   if (templates && TREE_CHAIN (templates))
1980     {
1981       /* We have:
1982
1983            [temp.expl.spec]
1984
1985            It is possible for a specialization with a given function
1986            signature to be instantiated from more than one function
1987            template.  In such cases, explicit specification of the
1988            template arguments must be used to uniquely identify the
1989            function template specialization being specialized.
1990
1991          Note that here, there's no suggestion that we're supposed to
1992          determine which of the candidate templates is most
1993          specialized.  However, we, also have:
1994
1995            [temp.func.order]
1996
1997            Partial ordering of overloaded function template
1998            declarations is used in the following contexts to select
1999            the function template to which a function template
2000            specialization refers:
2001
2002            -- when an explicit specialization refers to a function
2003               template.
2004
2005          So, we do use the partial ordering rules, at least for now.
2006          This extension can only serve to make invalid programs valid,
2007          so it's safe.  And, there is strong anecdotal evidence that
2008          the committee intended the partial ordering rules to apply;
2009          the EDG front end has that behavior, and John Spicer claims
2010          that the committee simply forgot to delete the wording in
2011          [temp.expl.spec].  */
2012       tree tmpl = most_specialized_instantiation (templates);
2013       if (tmpl != error_mark_node)
2014         {
2015           templates = tmpl;
2016           TREE_CHAIN (templates) = NULL_TREE;
2017         }
2018     }
2019
2020   if (templates == NULL_TREE && candidates == NULL_TREE)
2021     {
2022       error ("template-id %qD for %q+D does not match any template "
2023              "declaration", template_id, decl);
2024       if (header_count && header_count != template_count + 1)
2025         inform (input_location, "saw %d %<template<>%>, need %d for "
2026                 "specializing a member function template",
2027                 header_count, template_count + 1);
2028       return error_mark_node;
2029     }
2030   else if ((templates && TREE_CHAIN (templates))
2031            || (candidates && TREE_CHAIN (candidates))
2032            || (templates && candidates))
2033     {
2034       error ("ambiguous template specialization %qD for %q+D",
2035              template_id, decl);
2036       candidates = chainon (candidates, templates);
2037       print_candidates (candidates);
2038       return error_mark_node;
2039     }
2040
2041   /* We have one, and exactly one, match.  */
2042   if (candidates)
2043     {
2044       tree fn = TREE_VALUE (candidates);
2045       *targs_out = copy_node (DECL_TI_ARGS (fn));
2046       /* DECL is a re-declaration or partial instantiation of a template
2047          function.  */
2048       if (TREE_CODE (fn) == TEMPLATE_DECL)
2049         return fn;
2050       /* It was a specialization of an ordinary member function in a
2051          template class.  */
2052       return DECL_TI_TEMPLATE (fn);
2053     }
2054
2055   /* It was a specialization of a template.  */
2056   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2057   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2058     {
2059       *targs_out = copy_node (targs);
2060       SET_TMPL_ARGS_LEVEL (*targs_out,
2061                            TMPL_ARGS_DEPTH (*targs_out),
2062                            TREE_PURPOSE (templates));
2063     }
2064   else
2065     *targs_out = TREE_PURPOSE (templates);
2066   return TREE_VALUE (templates);
2067 }
2068
2069 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2070    but with the default argument values filled in from those in the
2071    TMPL_TYPES.  */
2072
2073 static tree
2074 copy_default_args_to_explicit_spec_1 (tree spec_types,
2075                                       tree tmpl_types)
2076 {
2077   tree new_spec_types;
2078
2079   if (!spec_types)
2080     return NULL_TREE;
2081
2082   if (spec_types == void_list_node)
2083     return void_list_node;
2084
2085   /* Substitute into the rest of the list.  */
2086   new_spec_types =
2087     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2088                                           TREE_CHAIN (tmpl_types));
2089
2090   /* Add the default argument for this parameter.  */
2091   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2092                          TREE_VALUE (spec_types),
2093                          new_spec_types);
2094 }
2095
2096 /* DECL is an explicit specialization.  Replicate default arguments
2097    from the template it specializes.  (That way, code like:
2098
2099      template <class T> void f(T = 3);
2100      template <> void f(double);
2101      void g () { f (); }
2102
2103    works, as required.)  An alternative approach would be to look up
2104    the correct default arguments at the call-site, but this approach
2105    is consistent with how implicit instantiations are handled.  */
2106
2107 static void
2108 copy_default_args_to_explicit_spec (tree decl)
2109 {
2110   tree tmpl;
2111   tree spec_types;
2112   tree tmpl_types;
2113   tree new_spec_types;
2114   tree old_type;
2115   tree new_type;
2116   tree t;
2117   tree object_type = NULL_TREE;
2118   tree in_charge = NULL_TREE;
2119   tree vtt = NULL_TREE;
2120
2121   /* See if there's anything we need to do.  */
2122   tmpl = DECL_TI_TEMPLATE (decl);
2123   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2124   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2125     if (TREE_PURPOSE (t))
2126       break;
2127   if (!t)
2128     return;
2129
2130   old_type = TREE_TYPE (decl);
2131   spec_types = TYPE_ARG_TYPES (old_type);
2132
2133   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2134     {
2135       /* Remove the this pointer, but remember the object's type for
2136          CV quals.  */
2137       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2138       spec_types = TREE_CHAIN (spec_types);
2139       tmpl_types = TREE_CHAIN (tmpl_types);
2140
2141       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2142         {
2143           /* DECL may contain more parameters than TMPL due to the extra
2144              in-charge parameter in constructors and destructors.  */
2145           in_charge = spec_types;
2146           spec_types = TREE_CHAIN (spec_types);
2147         }
2148       if (DECL_HAS_VTT_PARM_P (decl))
2149         {
2150           vtt = spec_types;
2151           spec_types = TREE_CHAIN (spec_types);
2152         }
2153     }
2154
2155   /* Compute the merged default arguments.  */
2156   new_spec_types =
2157     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2158
2159   /* Compute the new FUNCTION_TYPE.  */
2160   if (object_type)
2161     {
2162       if (vtt)
2163         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2164                                          TREE_VALUE (vtt),
2165                                          new_spec_types);
2166
2167       if (in_charge)
2168         /* Put the in-charge parameter back.  */
2169         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2170                                          TREE_VALUE (in_charge),
2171                                          new_spec_types);
2172
2173       new_type = build_method_type_directly (object_type,
2174                                              TREE_TYPE (old_type),
2175                                              new_spec_types);
2176     }
2177   else
2178     new_type = build_function_type (TREE_TYPE (old_type),
2179                                     new_spec_types);
2180   new_type = cp_build_type_attribute_variant (new_type,
2181                                               TYPE_ATTRIBUTES (old_type));
2182   new_type = build_exception_variant (new_type,
2183                                       TYPE_RAISES_EXCEPTIONS (old_type));
2184   TREE_TYPE (decl) = new_type;
2185 }
2186
2187 /* Check to see if the function just declared, as indicated in
2188    DECLARATOR, and in DECL, is a specialization of a function
2189    template.  We may also discover that the declaration is an explicit
2190    instantiation at this point.
2191
2192    Returns DECL, or an equivalent declaration that should be used
2193    instead if all goes well.  Issues an error message if something is
2194    amiss.  Returns error_mark_node if the error is not easily
2195    recoverable.
2196
2197    FLAGS is a bitmask consisting of the following flags:
2198
2199    2: The function has a definition.
2200    4: The function is a friend.
2201
2202    The TEMPLATE_COUNT is the number of references to qualifying
2203    template classes that appeared in the name of the function.  For
2204    example, in
2205
2206      template <class T> struct S { void f(); };
2207      void S<int>::f();
2208
2209    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2210    classes are not counted in the TEMPLATE_COUNT, so that in
2211
2212      template <class T> struct S {};
2213      template <> struct S<int> { void f(); }
2214      template <> void S<int>::f();
2215
2216    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2217    invalid; there should be no template <>.)
2218
2219    If the function is a specialization, it is marked as such via
2220    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2221    is set up correctly, and it is added to the list of specializations
2222    for that template.  */
2223
2224 tree
2225 check_explicit_specialization (tree declarator,
2226                                tree decl,
2227                                int template_count,
2228                                int flags)
2229 {
2230   int have_def = flags & 2;
2231   int is_friend = flags & 4;
2232   int specialization = 0;
2233   int explicit_instantiation = 0;
2234   int member_specialization = 0;
2235   tree ctype = DECL_CLASS_CONTEXT (decl);
2236   tree dname = DECL_NAME (decl);
2237   tmpl_spec_kind tsk;
2238
2239   if (is_friend)
2240     {
2241       if (!processing_specialization)
2242         tsk = tsk_none;
2243       else
2244         tsk = tsk_excessive_parms;
2245     }
2246   else
2247     tsk = current_tmpl_spec_kind (template_count);
2248
2249   switch (tsk)
2250     {
2251     case tsk_none:
2252       if (processing_specialization)
2253         {
2254           specialization = 1;
2255           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2256         }
2257       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2258         {
2259           if (is_friend)
2260             /* This could be something like:
2261
2262                template <class T> void f(T);
2263                class S { friend void f<>(int); }  */
2264             specialization = 1;
2265           else
2266             {
2267               /* This case handles bogus declarations like template <>
2268                  template <class T> void f<int>(); */
2269
2270               error ("template-id %qD in declaration of primary template",
2271                      declarator);
2272               return decl;
2273             }
2274         }
2275       break;
2276
2277     case tsk_invalid_member_spec:
2278       /* The error has already been reported in
2279          check_specialization_scope.  */
2280       return error_mark_node;
2281
2282     case tsk_invalid_expl_inst:
2283       error ("template parameter list used in explicit instantiation");
2284
2285       /* Fall through.  */
2286
2287     case tsk_expl_inst:
2288       if (have_def)
2289         error ("definition provided for explicit instantiation");
2290
2291       explicit_instantiation = 1;
2292       break;
2293
2294     case tsk_excessive_parms:
2295     case tsk_insufficient_parms:
2296       if (tsk == tsk_excessive_parms)
2297         error ("too many template parameter lists in declaration of %qD",
2298                decl);
2299       else if (template_header_count)
2300         error("too few template parameter lists in declaration of %qD", decl);
2301       else
2302         error("explicit specialization of %qD must be introduced by "
2303               "%<template <>%>", decl);
2304
2305       /* Fall through.  */
2306     case tsk_expl_spec:
2307       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2308       if (ctype)
2309         member_specialization = 1;
2310       else
2311         specialization = 1;
2312       break;
2313
2314     case tsk_template:
2315       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2316         {
2317           /* This case handles bogus declarations like template <>
2318              template <class T> void f<int>(); */
2319
2320           if (uses_template_parms (declarator))
2321             error ("function template partial specialization %qD "
2322                    "is not allowed", declarator);
2323           else
2324             error ("template-id %qD in declaration of primary template",
2325                    declarator);
2326           return decl;
2327         }
2328
2329       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2330         /* This is a specialization of a member template, without
2331            specialization the containing class.  Something like:
2332
2333              template <class T> struct S {
2334                template <class U> void f (U);
2335              };
2336              template <> template <class U> void S<int>::f(U) {}
2337
2338            That's a specialization -- but of the entire template.  */
2339         specialization = 1;
2340       break;
2341
2342     default:
2343       gcc_unreachable ();
2344     }
2345
2346   if (specialization || member_specialization)
2347     {
2348       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2349       for (; t; t = TREE_CHAIN (t))
2350         if (TREE_PURPOSE (t))
2351           {
2352             permerror (input_location, 
2353                        "default argument specified in explicit specialization");
2354             break;
2355           }
2356     }
2357
2358   if (specialization || member_specialization || explicit_instantiation)
2359     {
2360       tree tmpl = NULL_TREE;
2361       tree targs = NULL_TREE;
2362
2363       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2364       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2365         {
2366           tree fns;
2367
2368           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2369           if (ctype)
2370             fns = dname;
2371           else
2372             {
2373               /* If there is no class context, the explicit instantiation
2374                  must be at namespace scope.  */
2375               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2376
2377               /* Find the namespace binding, using the declaration
2378                  context.  */
2379               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2380                                            false, true);
2381               if (fns == error_mark_node || !is_overloaded_fn (fns))
2382                 {
2383                   error ("%qD is not a template function", dname);
2384                   fns = error_mark_node;
2385                 }
2386               else
2387                 {
2388                   tree fn = OVL_CURRENT (fns);
2389                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2390                                                 CP_DECL_CONTEXT (fn)))
2391                     error ("%qD is not declared in %qD",
2392                            decl, current_namespace);
2393                 }
2394             }
2395
2396           declarator = lookup_template_function (fns, NULL_TREE);
2397         }
2398
2399       if (declarator == error_mark_node)
2400         return error_mark_node;
2401
2402       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2403         {
2404           if (!explicit_instantiation)
2405             /* A specialization in class scope.  This is invalid,
2406                but the error will already have been flagged by
2407                check_specialization_scope.  */
2408             return error_mark_node;
2409           else
2410             {
2411               /* It's not valid to write an explicit instantiation in
2412                  class scope, e.g.:
2413
2414                    class C { template void f(); }
2415
2416                    This case is caught by the parser.  However, on
2417                    something like:
2418
2419                    template class C { void f(); };
2420
2421                    (which is invalid) we can get here.  The error will be
2422                    issued later.  */
2423               ;
2424             }
2425
2426           return decl;
2427         }
2428       else if (ctype != NULL_TREE
2429                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2430                    IDENTIFIER_NODE))
2431         {
2432           /* Find the list of functions in ctype that have the same
2433              name as the declared function.  */
2434           tree name = TREE_OPERAND (declarator, 0);
2435           tree fns = NULL_TREE;
2436           int idx;
2437
2438           if (constructor_name_p (name, ctype))
2439             {
2440               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2441
2442               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2443                   : !CLASSTYPE_DESTRUCTORS (ctype))
2444                 {
2445                   /* From [temp.expl.spec]:
2446
2447                      If such an explicit specialization for the member
2448                      of a class template names an implicitly-declared
2449                      special member function (clause _special_), the
2450                      program is ill-formed.
2451
2452                      Similar language is found in [temp.explicit].  */
2453                   error ("specialization of implicitly-declared special member function");
2454                   return error_mark_node;
2455                 }
2456
2457               name = is_constructor ? ctor_identifier : dtor_identifier;
2458             }
2459
2460           if (!DECL_CONV_FN_P (decl))
2461             {
2462               idx = lookup_fnfields_1 (ctype, name);
2463               if (idx >= 0)
2464                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2465             }
2466           else
2467             {
2468               VEC(tree,gc) *methods;
2469               tree ovl;
2470
2471               /* For a type-conversion operator, we cannot do a
2472                  name-based lookup.  We might be looking for `operator
2473                  int' which will be a specialization of `operator T'.
2474                  So, we find *all* the conversion operators, and then
2475                  select from them.  */
2476               fns = NULL_TREE;
2477
2478               methods = CLASSTYPE_METHOD_VEC (ctype);
2479               if (methods)
2480                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2481                      VEC_iterate (tree, methods, idx, ovl);
2482                      ++idx)
2483                   {
2484                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2485                       /* There are no more conversion functions.  */
2486                       break;
2487
2488                     /* Glue all these conversion functions together
2489                        with those we already have.  */
2490                     for (; ovl; ovl = OVL_NEXT (ovl))
2491                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2492                   }
2493             }
2494
2495           if (fns == NULL_TREE)
2496             {
2497               error ("no member function %qD declared in %qT", name, ctype);
2498               return error_mark_node;
2499             }
2500           else
2501             TREE_OPERAND (declarator, 0) = fns;
2502         }
2503
2504       /* Figure out what exactly is being specialized at this point.
2505          Note that for an explicit instantiation, even one for a
2506          member function, we cannot tell apriori whether the
2507          instantiation is for a member template, or just a member
2508          function of a template class.  Even if a member template is
2509          being instantiated, the member template arguments may be
2510          elided if they can be deduced from the rest of the
2511          declaration.  */
2512       tmpl = determine_specialization (declarator, decl,
2513                                        &targs,
2514                                        member_specialization,
2515                                        template_count,
2516                                        tsk);
2517
2518       if (!tmpl || tmpl == error_mark_node)
2519         /* We couldn't figure out what this declaration was
2520            specializing.  */
2521         return error_mark_node;
2522       else
2523         {
2524           tree gen_tmpl = most_general_template (tmpl);
2525
2526           if (explicit_instantiation)
2527             {
2528               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2529                  is done by do_decl_instantiation later.  */
2530
2531               int arg_depth = TMPL_ARGS_DEPTH (targs);
2532               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2533
2534               if (arg_depth > parm_depth)
2535                 {
2536                   /* If TMPL is not the most general template (for
2537                      example, if TMPL is a friend template that is
2538                      injected into namespace scope), then there will
2539                      be too many levels of TARGS.  Remove some of them
2540                      here.  */
2541                   int i;
2542                   tree new_targs;
2543
2544                   new_targs = make_tree_vec (parm_depth);
2545                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2546                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2547                       = TREE_VEC_ELT (targs, i);
2548                   targs = new_targs;
2549                 }
2550
2551               return instantiate_template (tmpl, targs, tf_error);
2552             }
2553
2554           /* If we thought that the DECL was a member function, but it
2555              turns out to be specializing a static member function,
2556              make DECL a static member function as well.  */
2557           if (DECL_STATIC_FUNCTION_P (tmpl)
2558               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2559             revert_static_member_fn (decl);
2560
2561           /* If this is a specialization of a member template of a
2562              template class, we want to return the TEMPLATE_DECL, not
2563              the specialization of it.  */
2564           if (tsk == tsk_template)
2565             {
2566               tree result = DECL_TEMPLATE_RESULT (tmpl);
2567               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2568               DECL_INITIAL (result) = NULL_TREE;
2569               if (have_def)
2570                 {
2571                   tree parm;
2572                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2573                   DECL_SOURCE_LOCATION (result)
2574                     = DECL_SOURCE_LOCATION (decl);
2575                   /* We want to use the argument list specified in the
2576                      definition, not in the original declaration.  */
2577                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2578                   for (parm = DECL_ARGUMENTS (result); parm;
2579                        parm = DECL_CHAIN (parm))
2580                     DECL_CONTEXT (parm) = result;
2581                 }
2582               return register_specialization (tmpl, gen_tmpl, targs,
2583                                               is_friend, 0);
2584             }
2585
2586           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2587           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2588
2589           /* Inherit default function arguments from the template
2590              DECL is specializing.  */
2591           copy_default_args_to_explicit_spec (decl);
2592
2593           /* This specialization has the same protection as the
2594              template it specializes.  */
2595           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2596           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2597
2598           /* 7.1.1-1 [dcl.stc]
2599
2600              A storage-class-specifier shall not be specified in an
2601              explicit specialization...
2602
2603              The parser rejects these, so unless action is taken here,
2604              explicit function specializations will always appear with
2605              global linkage.
2606
2607              The action recommended by the C++ CWG in response to C++
2608              defect report 605 is to make the storage class and linkage
2609              of the explicit specialization match the templated function:
2610
2611              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2612            */
2613           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2614             {
2615               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2616               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2617
2618               /* This specialization has the same linkage and visibility as
2619                  the function template it specializes.  */
2620               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2621               if (! TREE_PUBLIC (decl))
2622                 {
2623                   DECL_INTERFACE_KNOWN (decl) = 1;
2624                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2625                 }
2626               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2627               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2628                 {
2629                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2630                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2631                 }
2632             }
2633
2634           /* If DECL is a friend declaration, declared using an
2635              unqualified name, the namespace associated with DECL may
2636              have been set incorrectly.  For example, in:
2637
2638                template <typename T> void f(T);
2639                namespace N {
2640                  struct S { friend void f<int>(int); }
2641                }
2642
2643              we will have set the DECL_CONTEXT for the friend
2644              declaration to N, rather than to the global namespace.  */
2645           if (DECL_NAMESPACE_SCOPE_P (decl))
2646             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2647
2648           if (is_friend && !have_def)
2649             /* This is not really a declaration of a specialization.
2650                It's just the name of an instantiation.  But, it's not
2651                a request for an instantiation, either.  */
2652             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2653           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2654             /* This is indeed a specialization.  In case of constructors
2655                and destructors, we need in-charge and not-in-charge
2656                versions in V3 ABI.  */
2657             clone_function_decl (decl, /*update_method_vec_p=*/0);
2658
2659           /* Register this specialization so that we can find it
2660              again.  */
2661           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2662         }
2663     }
2664
2665   return decl;
2666 }
2667
2668 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2669    parameters.  These are represented in the same format used for
2670    DECL_TEMPLATE_PARMS.  */
2671
2672 int
2673 comp_template_parms (const_tree parms1, const_tree parms2)
2674 {
2675   const_tree p1;
2676   const_tree p2;
2677
2678   if (parms1 == parms2)
2679     return 1;
2680
2681   for (p1 = parms1, p2 = parms2;
2682        p1 != NULL_TREE && p2 != NULL_TREE;
2683        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2684     {
2685       tree t1 = TREE_VALUE (p1);
2686       tree t2 = TREE_VALUE (p2);
2687       int i;
2688
2689       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2690       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2691
2692       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2693         return 0;
2694
2695       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2696         {
2697           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2698           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2699
2700           /* If either of the template parameters are invalid, assume
2701              they match for the sake of error recovery. */
2702           if (parm1 == error_mark_node || parm2 == error_mark_node)
2703             return 1;
2704
2705           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2706             return 0;
2707
2708           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2709               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2710                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2711             continue;
2712           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2713             return 0;
2714         }
2715     }
2716
2717   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2718     /* One set of parameters has more parameters lists than the
2719        other.  */
2720     return 0;
2721
2722   return 1;
2723 }
2724
2725 /* Determine whether PARM is a parameter pack.  */
2726
2727 bool 
2728 template_parameter_pack_p (const_tree parm)
2729 {
2730   /* Determine if we have a non-type template parameter pack.  */
2731   if (TREE_CODE (parm) == PARM_DECL)
2732     return (DECL_TEMPLATE_PARM_P (parm) 
2733             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2734
2735   /* If this is a list of template parameters, we could get a
2736      TYPE_DECL or a TEMPLATE_DECL.  */ 
2737   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2738     parm = TREE_TYPE (parm);
2739
2740   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2741            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2742           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2743 }
2744
2745 /* Determine if T is a function parameter pack.  */
2746
2747 bool
2748 function_parameter_pack_p (const_tree t)
2749 {
2750   if (t && TREE_CODE (t) == PARM_DECL)
2751     return FUNCTION_PARAMETER_PACK_P (t);
2752   return false;
2753 }
2754
2755 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2756    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2757
2758 tree
2759 get_function_template_decl (const_tree primary_func_tmpl_inst)
2760 {
2761   if (! primary_func_tmpl_inst
2762       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2763       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2764     return NULL;
2765
2766   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2767 }
2768
2769 /* Return true iff the function parameter PARAM_DECL was expanded
2770    from the function parameter pack PACK.  */
2771
2772 bool
2773 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2774 {
2775   if (DECL_ARTIFICIAL (param_decl)
2776       || !function_parameter_pack_p (pack))
2777     return false;
2778
2779   /* The parameter pack and its pack arguments have the same
2780      DECL_PARM_INDEX.  */
2781   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2782 }
2783
2784 /* Determine whether ARGS describes a variadic template args list,
2785    i.e., one that is terminated by a template argument pack.  */
2786
2787 static bool 
2788 template_args_variadic_p (tree args)
2789 {
2790   int nargs;
2791   tree last_parm;
2792
2793   if (args == NULL_TREE)
2794     return false;
2795
2796   args = INNERMOST_TEMPLATE_ARGS (args);
2797   nargs = TREE_VEC_LENGTH (args);
2798
2799   if (nargs == 0)
2800     return false;
2801
2802   last_parm = TREE_VEC_ELT (args, nargs - 1);
2803
2804   return ARGUMENT_PACK_P (last_parm);
2805 }
2806
2807 /* Generate a new name for the parameter pack name NAME (an
2808    IDENTIFIER_NODE) that incorporates its */
2809
2810 static tree
2811 make_ith_pack_parameter_name (tree name, int i)
2812 {
2813   /* Munge the name to include the parameter index.  */
2814 #define NUMBUF_LEN 128
2815   char numbuf[NUMBUF_LEN];
2816   char* newname;
2817   int newname_len;
2818
2819   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2820   newname_len = IDENTIFIER_LENGTH (name)
2821                 + strlen (numbuf) + 2;
2822   newname = (char*)alloca (newname_len);
2823   snprintf (newname, newname_len,
2824             "%s#%i", IDENTIFIER_POINTER (name), i);
2825   return get_identifier (newname);
2826 }
2827
2828 /* Return true if T is a primary function
2829    or class template instantiation.  */
2830
2831 bool
2832 primary_template_instantiation_p (const_tree t)
2833 {
2834   if (!t)
2835     return false;
2836
2837   if (TREE_CODE (t) == FUNCTION_DECL)
2838     return DECL_LANG_SPECIFIC (t)
2839            && DECL_TEMPLATE_INSTANTIATION (t)
2840            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2841   else if (CLASS_TYPE_P (t))
2842     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2843            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2844   return false;
2845 }
2846
2847 /* Return true if PARM is a template template parameter.  */
2848
2849 bool
2850 template_template_parameter_p (const_tree parm)
2851 {
2852   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2853 }
2854
2855 /* Return the template parameters of T if T is a
2856    primary template instantiation, NULL otherwise.  */
2857
2858 tree
2859 get_primary_template_innermost_parameters (const_tree t)
2860 {
2861   tree parms = NULL, template_info = NULL;
2862
2863   if ((template_info = get_template_info (t))
2864       && primary_template_instantiation_p (t))
2865     parms = INNERMOST_TEMPLATE_PARMS
2866         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2867
2868   return parms;
2869 }
2870
2871 /* Return the template parameters of the LEVELth level from the full list
2872    of template parameters PARMS.  */
2873
2874 tree
2875 get_template_parms_at_level (tree parms, int level)
2876 {
2877   tree p;
2878   if (!parms
2879       || TREE_CODE (parms) != TREE_LIST
2880       || level > TMPL_PARMS_DEPTH (parms))
2881     return NULL_TREE;
2882
2883   for (p = parms; p; p = TREE_CHAIN (p))
2884     if (TMPL_PARMS_DEPTH (p) == level)
2885       return p;
2886
2887   return NULL_TREE;
2888 }
2889
2890 /* Returns the template arguments of T if T is a template instantiation,
2891    NULL otherwise.  */
2892
2893 tree
2894 get_template_innermost_arguments (const_tree t)
2895 {
2896   tree args = NULL, template_info = NULL;
2897
2898   if ((template_info = get_template_info (t))
2899       && TI_ARGS (template_info))
2900     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2901
2902   return args;
2903 }
2904
2905 /* Return the argument pack elements of T if T is a template argument pack,
2906    NULL otherwise.  */
2907
2908 tree
2909 get_template_argument_pack_elems (const_tree t)
2910 {
2911   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2912       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2913     return NULL;
2914
2915   return ARGUMENT_PACK_ARGS (t);
2916 }
2917
2918 /* Structure used to track the progress of find_parameter_packs_r.  */
2919 struct find_parameter_pack_data 
2920 {
2921   /* TREE_LIST that will contain all of the parameter packs found by
2922      the traversal.  */
2923   tree* parameter_packs;
2924
2925   /* Set of AST nodes that have been visited by the traversal.  */
2926   struct pointer_set_t *visited;
2927 };
2928
2929 /* Identifies all of the argument packs that occur in a template
2930    argument and appends them to the TREE_LIST inside DATA, which is a
2931    find_parameter_pack_data structure. This is a subroutine of
2932    make_pack_expansion and uses_parameter_packs.  */
2933 static tree
2934 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2935 {
2936   tree t = *tp;
2937   struct find_parameter_pack_data* ppd = 
2938     (struct find_parameter_pack_data*)data;
2939   bool parameter_pack_p = false;
2940
2941   /* Identify whether this is a parameter pack or not.  */
2942   switch (TREE_CODE (t))
2943     {
2944     case TEMPLATE_PARM_INDEX:
2945       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2946         parameter_pack_p = true;
2947       break;
2948
2949     case TEMPLATE_TYPE_PARM:
2950     case TEMPLATE_TEMPLATE_PARM:
2951       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2952         parameter_pack_p = true;
2953       break;
2954
2955     case PARM_DECL:
2956       if (FUNCTION_PARAMETER_PACK_P (t))
2957         {
2958           /* We don't want to walk into the type of a PARM_DECL,
2959              because we don't want to see the type parameter pack.  */
2960           *walk_subtrees = 0;
2961           parameter_pack_p = true;
2962         }
2963       break;
2964
2965     default:
2966       /* Not a parameter pack.  */
2967       break;
2968     }
2969
2970   if (parameter_pack_p)
2971     {
2972       /* Add this parameter pack to the list.  */
2973       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2974     }
2975
2976   if (TYPE_P (t))
2977     cp_walk_tree (&TYPE_CONTEXT (t), 
2978                   &find_parameter_packs_r, ppd, ppd->visited);
2979
2980   /* This switch statement will return immediately if we don't find a
2981      parameter pack.  */
2982   switch (TREE_CODE (t)) 
2983     {
2984     case TEMPLATE_PARM_INDEX:
2985       return NULL_TREE;
2986
2987     case BOUND_TEMPLATE_TEMPLATE_PARM:
2988       /* Check the template itself.  */
2989       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2990                     &find_parameter_packs_r, ppd, ppd->visited);
2991       /* Check the template arguments.  */
2992       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2993                     ppd->visited);
2994       *walk_subtrees = 0;
2995       return NULL_TREE;
2996
2997     case TEMPLATE_TYPE_PARM:
2998     case TEMPLATE_TEMPLATE_PARM:
2999       return NULL_TREE;
3000
3001     case PARM_DECL:
3002       return NULL_TREE;
3003
3004     case RECORD_TYPE:
3005       if (TYPE_PTRMEMFUNC_P (t))
3006         return NULL_TREE;
3007       /* Fall through.  */
3008
3009     case UNION_TYPE:
3010     case ENUMERAL_TYPE:
3011       if (TYPE_TEMPLATE_INFO (t))
3012         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3013                       &find_parameter_packs_r, ppd, ppd->visited);
3014
3015       *walk_subtrees = 0;
3016       return NULL_TREE;
3017
3018     case TEMPLATE_DECL:
3019       cp_walk_tree (&TREE_TYPE (t),
3020                     &find_parameter_packs_r, ppd, ppd->visited);
3021       return NULL_TREE;
3022  
3023     case TYPENAME_TYPE:
3024       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3025                    ppd, ppd->visited);
3026       *walk_subtrees = 0;
3027       return NULL_TREE;
3028       
3029     case TYPE_PACK_EXPANSION:
3030     case EXPR_PACK_EXPANSION:
3031       *walk_subtrees = 0;
3032       return NULL_TREE;
3033
3034     case INTEGER_TYPE:
3035       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3036                     ppd, ppd->visited);
3037       *walk_subtrees = 0;
3038       return NULL_TREE;
3039
3040     case IDENTIFIER_NODE:
3041       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3042                     ppd->visited);
3043       *walk_subtrees = 0;
3044       return NULL_TREE;
3045
3046     default:
3047       return NULL_TREE;
3048     }
3049
3050   return NULL_TREE;
3051 }
3052
3053 /* Determines if the expression or type T uses any parameter packs.  */
3054 bool
3055 uses_parameter_packs (tree t)
3056 {
3057   tree parameter_packs = NULL_TREE;
3058   struct find_parameter_pack_data ppd;
3059   ppd.parameter_packs = &parameter_packs;
3060   ppd.visited = pointer_set_create ();
3061   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3062   pointer_set_destroy (ppd.visited);
3063   return parameter_packs != NULL_TREE;
3064 }
3065
3066 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3067    representation a base-class initializer into a parameter pack
3068    expansion. If all goes well, the resulting node will be an
3069    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3070    respectively.  */
3071 tree 
3072 make_pack_expansion (tree arg)
3073 {
3074   tree result;
3075   tree parameter_packs = NULL_TREE;
3076   bool for_types = false;
3077   struct find_parameter_pack_data ppd;
3078
3079   if (!arg || arg == error_mark_node)
3080     return arg;
3081
3082   if (TREE_CODE (arg) == TREE_LIST)
3083     {
3084       /* The only time we will see a TREE_LIST here is for a base
3085          class initializer.  In this case, the TREE_PURPOSE will be a
3086          _TYPE node (representing the base class expansion we're
3087          initializing) and the TREE_VALUE will be a TREE_LIST
3088          containing the initialization arguments. 
3089
3090          The resulting expansion looks somewhat different from most
3091          expansions. Rather than returning just one _EXPANSION, we
3092          return a TREE_LIST whose TREE_PURPOSE is a
3093          TYPE_PACK_EXPANSION containing the bases that will be
3094          initialized.  The TREE_VALUE will be identical to the
3095          original TREE_VALUE, which is a list of arguments that will
3096          be passed to each base.  We do not introduce any new pack
3097          expansion nodes into the TREE_VALUE (although it is possible
3098          that some already exist), because the TREE_PURPOSE and
3099          TREE_VALUE all need to be expanded together with the same
3100          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3101          resulting TREE_PURPOSE will mention the parameter packs in
3102          both the bases and the arguments to the bases.  */
3103       tree purpose;
3104       tree value;
3105       tree parameter_packs = NULL_TREE;
3106
3107       /* Determine which parameter packs will be used by the base
3108          class expansion.  */
3109       ppd.visited = pointer_set_create ();
3110       ppd.parameter_packs = &parameter_packs;
3111       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3112                     &ppd, ppd.visited);
3113
3114       if (parameter_packs == NULL_TREE)
3115         {
3116           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3117           pointer_set_destroy (ppd.visited);
3118           return error_mark_node;
3119         }
3120
3121       if (TREE_VALUE (arg) != void_type_node)
3122         {
3123           /* Collect the sets of parameter packs used in each of the
3124              initialization arguments.  */
3125           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3126             {
3127               /* Determine which parameter packs will be expanded in this
3128                  argument.  */
3129               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3130                             &ppd, ppd.visited);
3131             }
3132         }
3133
3134       pointer_set_destroy (ppd.visited);
3135
3136       /* Create the pack expansion type for the base type.  */
3137       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3138       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3139       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3140
3141       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3142          they will rarely be compared to anything.  */
3143       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3144
3145       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3146     }
3147
3148   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3149     for_types = true;
3150
3151   /* Build the PACK_EXPANSION_* node.  */
3152   result = for_types
3153      ? cxx_make_type (TYPE_PACK_EXPANSION)
3154      : make_node (EXPR_PACK_EXPANSION);
3155   SET_PACK_EXPANSION_PATTERN (result, arg);
3156   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3157     {
3158       /* Propagate type and const-expression information.  */
3159       TREE_TYPE (result) = TREE_TYPE (arg);
3160       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3161     }
3162   else
3163     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3164        they will rarely be compared to anything.  */
3165     SET_TYPE_STRUCTURAL_EQUALITY (result);
3166
3167   /* Determine which parameter packs will be expanded.  */
3168   ppd.parameter_packs = &parameter_packs;
3169   ppd.visited = pointer_set_create ();
3170   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3171   pointer_set_destroy (ppd.visited);
3172
3173   /* Make sure we found some parameter packs.  */
3174   if (parameter_packs == NULL_TREE)
3175     {
3176       if (TYPE_P (arg))
3177         error ("expansion pattern %<%T%> contains no argument packs", arg);
3178       else
3179         error ("expansion pattern %<%E%> contains no argument packs", arg);
3180       return error_mark_node;
3181     }
3182   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3183
3184   return result;
3185 }
3186
3187 /* Checks T for any "bare" parameter packs, which have not yet been
3188    expanded, and issues an error if any are found. This operation can
3189    only be done on full expressions or types (e.g., an expression
3190    statement, "if" condition, etc.), because we could have expressions like:
3191
3192      foo(f(g(h(args)))...)
3193
3194    where "args" is a parameter pack. check_for_bare_parameter_packs
3195    should not be called for the subexpressions args, h(args),
3196    g(h(args)), or f(g(h(args))), because we would produce erroneous
3197    error messages. 
3198
3199    Returns TRUE and emits an error if there were bare parameter packs,
3200    returns FALSE otherwise.  */
3201 bool 
3202 check_for_bare_parameter_packs (tree t)
3203 {
3204   tree parameter_packs = NULL_TREE;
3205   struct find_parameter_pack_data ppd;
3206
3207   if (!processing_template_decl || !t || t == error_mark_node)
3208     return false;
3209
3210   if (TREE_CODE (t) == TYPE_DECL)
3211     t = TREE_TYPE (t);
3212
3213   ppd.parameter_packs = &parameter_packs;
3214   ppd.visited = pointer_set_create ();
3215   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3216   pointer_set_destroy (ppd.visited);
3217
3218   if (parameter_packs) 
3219     {
3220       error ("parameter packs not expanded with %<...%>:");
3221       while (parameter_packs)
3222         {
3223           tree pack = TREE_VALUE (parameter_packs);
3224           tree name = NULL_TREE;
3225
3226           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3227               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3228             name = TYPE_NAME (pack);
3229           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3230             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3231           else
3232             name = DECL_NAME (pack);
3233
3234           if (name)
3235             inform (input_location, "        %qD", name);
3236           else
3237             inform (input_location, "        <anonymous>");
3238
3239           parameter_packs = TREE_CHAIN (parameter_packs);
3240         }
3241
3242       return true;
3243     }
3244
3245   return false;
3246 }
3247
3248 /* Expand any parameter packs that occur in the template arguments in
3249    ARGS.  */
3250 tree
3251 expand_template_argument_pack (tree args)
3252 {
3253   tree result_args = NULL_TREE;
3254   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3255   int num_result_args = -1;
3256   int non_default_args_count = -1;
3257
3258   /* First, determine if we need to expand anything, and the number of
3259      slots we'll need.  */
3260   for (in_arg = 0; in_arg < nargs; ++in_arg)
3261     {
3262       tree arg = TREE_VEC_ELT (args, in_arg);
3263       if (arg == NULL_TREE)
3264         return args;
3265       if (ARGUMENT_PACK_P (arg))
3266         {
3267           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3268           if (num_result_args < 0)
3269             num_result_args = in_arg + num_packed;
3270           else
3271             num_result_args += num_packed;
3272         }
3273       else
3274         {
3275           if (num_result_args >= 0)
3276             num_result_args++;
3277         }
3278     }
3279
3280   /* If no expansion is necessary, we're done.  */
3281   if (num_result_args < 0)
3282     return args;
3283
3284   /* Expand arguments.  */
3285   result_args = make_tree_vec (num_result_args);
3286   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3287     non_default_args_count =
3288       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3289   for (in_arg = 0; in_arg < nargs; ++in_arg)
3290     {
3291       tree arg = TREE_VEC_ELT (args, in_arg);
3292       if (ARGUMENT_PACK_P (arg))
3293         {
3294           tree packed = ARGUMENT_PACK_ARGS (arg);
3295           int i, num_packed = TREE_VEC_LENGTH (packed);
3296           for (i = 0; i < num_packed; ++i, ++out_arg)
3297             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3298           if (non_default_args_count > 0)
3299             non_default_args_count += num_packed;
3300         }
3301       else
3302         {
3303           TREE_VEC_ELT (result_args, out_arg) = arg;
3304           ++out_arg;
3305         }
3306     }
3307   if (non_default_args_count >= 0)
3308     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3309   return result_args;
3310 }
3311
3312 /* Checks if DECL shadows a template parameter.
3313
3314    [temp.local]: A template-parameter shall not be redeclared within its
3315    scope (including nested scopes).
3316
3317    Emits an error and returns TRUE if the DECL shadows a parameter,
3318    returns FALSE otherwise.  */
3319
3320 bool
3321 check_template_shadow (tree decl)
3322 {
3323   tree olddecl;
3324
3325   /* If we're not in a template, we can't possibly shadow a template
3326      parameter.  */
3327   if (!current_template_parms)
3328     return true;
3329
3330   /* Figure out what we're shadowing.  */
3331   if (TREE_CODE (decl) == OVERLOAD)
3332     decl = OVL_CURRENT (decl);
3333   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3334
3335   /* If there's no previous binding for this name, we're not shadowing
3336      anything, let alone a template parameter.  */
3337   if (!olddecl)
3338     return true;
3339
3340   /* If we're not shadowing a template parameter, we're done.  Note
3341      that OLDDECL might be an OVERLOAD (or perhaps even an
3342      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3343      node.  */
3344   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3345     return true;
3346
3347   /* We check for decl != olddecl to avoid bogus errors for using a
3348      name inside a class.  We check TPFI to avoid duplicate errors for
3349      inline member templates.  */
3350   if (decl == olddecl
3351       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3352     return true;
3353
3354   error ("declaration of %q+#D", decl);
3355   error (" shadows template parm %q+#D", olddecl);
3356   return false;
3357 }
3358
3359 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3360    ORIG_LEVEL, DECL, and TYPE.  NUM_SIBLINGS is the total number of
3361    template parameters.  */
3362
3363 static tree
3364 build_template_parm_index (int index,
3365                            int level,
3366                            int orig_level,
3367                            int num_siblings,
3368                            tree decl,
3369                            tree type)
3370 {
3371   tree t = make_node (TEMPLATE_PARM_INDEX);
3372   TEMPLATE_PARM_IDX (t) = index;
3373   TEMPLATE_PARM_LEVEL (t) = level;
3374   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3375   TEMPLATE_PARM_NUM_SIBLINGS (t) = num_siblings;
3376   TEMPLATE_PARM_DECL (t) = decl;
3377   TREE_TYPE (t) = type;
3378   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3379   TREE_READONLY (t) = TREE_READONLY (decl);
3380
3381   return t;
3382 }
3383
3384 /* Find the canonical type parameter for the given template type
3385    parameter.  Returns the canonical type parameter, which may be TYPE
3386    if no such parameter existed.  */
3387
3388 static tree
3389 canonical_type_parameter (tree type)
3390 {
3391   tree list;
3392   int idx = TEMPLATE_TYPE_IDX (type);
3393   if (!canonical_template_parms)
3394     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3395
3396   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3397     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3398
3399   list = VEC_index (tree, canonical_template_parms, idx);
3400   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3401     list = TREE_CHAIN (list);
3402
3403   if (list)
3404     return TREE_VALUE (list);
3405   else
3406     {
3407       VEC_replace(tree, canonical_template_parms, idx,
3408                   tree_cons (NULL_TREE, type, 
3409                              VEC_index (tree, canonical_template_parms, idx)));
3410       return type;
3411     }
3412 }
3413
3414 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3415    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3416    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3417    new one is created.  */
3418
3419 static tree
3420 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3421                             tsubst_flags_t complain)
3422 {
3423   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3424       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3425           != TEMPLATE_PARM_LEVEL (index) - levels)
3426       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3427     {
3428       tree orig_decl = TEMPLATE_PARM_DECL (index);
3429       tree decl, t;
3430
3431       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3432                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3433       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3434       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3435       DECL_ARTIFICIAL (decl) = 1;
3436       SET_DECL_TEMPLATE_PARM_P (decl);
3437
3438       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3439                                      TEMPLATE_PARM_LEVEL (index) - levels,
3440                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3441                                      TEMPLATE_PARM_NUM_SIBLINGS (index),
3442                                      decl, type);
3443       TEMPLATE_PARM_DESCENDANTS (index) = t;
3444       TEMPLATE_PARM_PARAMETER_PACK (t) 
3445         = TEMPLATE_PARM_PARAMETER_PACK (index);
3446
3447         /* Template template parameters need this.  */
3448       if (TREE_CODE (decl) == TEMPLATE_DECL)
3449         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3450           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3451            args, complain);
3452     }
3453
3454   return TEMPLATE_PARM_DESCENDANTS (index);
3455 }
3456
3457 /* Process information from new template parameter PARM and append it
3458    to the LIST being built.  This new parameter is a non-type
3459    parameter iff IS_NON_TYPE is true. This new parameter is a
3460    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3461    is in PARM_LOC. NUM_TEMPLATE_PARMS is the size of the template
3462    parameter list PARM belongs to. This is used used to create a
3463    proper canonical type for the type of PARM that is to be created,
3464    iff PARM is a type.  If the size is not known, this parameter shall
3465    be set to 0.  */
3466
3467 tree
3468 process_template_parm (tree list, location_t parm_loc, tree parm,
3469                        bool is_non_type, bool is_parameter_pack,
3470                        unsigned num_template_parms)
3471 {
3472   tree decl = 0;
3473   tree defval;
3474   tree err_parm_list;
3475   int idx = 0;
3476
3477   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3478   defval = TREE_PURPOSE (parm);
3479
3480   if (list)
3481     {
3482       tree p = tree_last (list);
3483
3484       if (p && TREE_VALUE (p) != error_mark_node)
3485         {
3486           p = TREE_VALUE (p);
3487           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3488             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3489           else
3490             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3491         }
3492
3493       ++idx;
3494     }
3495   else
3496     idx = 0;
3497
3498   if (is_non_type)
3499     {
3500       parm = TREE_VALUE (parm);
3501
3502       SET_DECL_TEMPLATE_PARM_P (parm);
3503
3504       if (TREE_TYPE (parm) == error_mark_node)
3505         {
3506           err_parm_list = build_tree_list (defval, parm);
3507           TREE_VALUE (err_parm_list) = error_mark_node;
3508            return chainon (list, err_parm_list);
3509         }
3510       else
3511       {
3512         /* [temp.param]
3513
3514            The top-level cv-qualifiers on the template-parameter are
3515            ignored when determining its type.  */
3516         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3517         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3518           {
3519             err_parm_list = build_tree_list (defval, parm);
3520             TREE_VALUE (err_parm_list) = error_mark_node;
3521              return chainon (list, err_parm_list);
3522           }
3523
3524         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3525           {
3526             /* This template parameter is not a parameter pack, but it
3527                should be. Complain about "bare" parameter packs.  */
3528             check_for_bare_parameter_packs (TREE_TYPE (parm));
3529             
3530             /* Recover by calling this a parameter pack.  */
3531             is_parameter_pack = true;
3532           }
3533       }
3534
3535       /* A template parameter is not modifiable.  */
3536       TREE_CONSTANT (parm) = 1;
3537       TREE_READONLY (parm) = 1;
3538       decl = build_decl (parm_loc,
3539                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3540       TREE_CONSTANT (decl) = 1;
3541       TREE_READONLY (decl) = 1;
3542       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3543         = build_template_parm_index (idx, processing_template_decl,
3544                                      processing_template_decl,
3545                                      num_template_parms,
3546                                      decl, TREE_TYPE (parm));
3547
3548       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3549         = is_parameter_pack;
3550     }
3551   else
3552     {
3553       tree t;
3554       parm = TREE_VALUE (TREE_VALUE (parm));
3555
3556       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3557         {
3558           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3559           /* This is for distinguishing between real templates and template
3560              template parameters */
3561           TREE_TYPE (parm) = t;
3562           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3563           decl = parm;
3564         }
3565       else
3566         {
3567           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3568           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3569           decl = build_decl (parm_loc,
3570                              TYPE_DECL, parm, t);
3571         }
3572
3573       TYPE_NAME (t) = decl;
3574       TYPE_STUB_DECL (t) = decl;
3575       parm = decl;
3576       TEMPLATE_TYPE_PARM_INDEX (t)
3577         = build_template_parm_index (idx, processing_template_decl,
3578                                      processing_template_decl,
3579                                      num_template_parms,
3580                                      decl, TREE_TYPE (parm));
3581       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3582       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3583     }
3584   DECL_ARTIFICIAL (decl) = 1;
3585   SET_DECL_TEMPLATE_PARM_P (decl);
3586   pushdecl (decl);
3587   parm = build_tree_list (defval, parm);
3588   return chainon (list, parm);
3589 }
3590
3591 /* The end of a template parameter list has been reached.  Process the
3592    tree list into a parameter vector, converting each parameter into a more
3593    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3594    as PARM_DECLs.  */
3595
3596 tree
3597 end_template_parm_list (tree parms)
3598 {
3599   int nparms;
3600   tree parm, next;
3601   tree saved_parmlist = make_tree_vec (list_length (parms));
3602
3603   current_template_parms
3604     = tree_cons (size_int (processing_template_decl),
3605                  saved_parmlist, current_template_parms);
3606
3607   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3608     {
3609       next = TREE_CHAIN (parm);
3610       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3611       TREE_CHAIN (parm) = NULL_TREE;
3612     }
3613
3614   --processing_template_parmlist;
3615
3616   return saved_parmlist;
3617 }
3618
3619 /* Create a new type almost identical to TYPE but which has the
3620    following differences:
3621
3622      1/ T has a new TEMPLATE_PARM_INDEX that carries the new number of
3623      template sibling parameters of T.
3624
3625      2/ T has a new canonical type that matches the new number
3626      of sibling parms.
3627
3628      3/ From now on, T is going to be what lookups referring to the
3629      name of TYPE will return. No lookup should return TYPE anymore.
3630
3631    NUM_PARMS is the new number of sibling parms TYPE belongs to.
3632
3633    This is a subroutine of fixup_template_parms.  */
3634
3635 static tree
3636 fixup_template_type_parm_type (tree type, int num_parms)
3637 {
3638   tree orig_idx = TEMPLATE_TYPE_PARM_INDEX (type), idx;
3639   tree t;
3640   /* This is the decl which name is inserted into the symbol table for
3641      the template parm type. So whenever we lookup the type name, this
3642      is the DECL we get.  */
3643   tree decl;
3644
3645   /* Do not fix up the type twice.  */
3646   if (orig_idx && TEMPLATE_PARM_NUM_SIBLINGS (orig_idx) != 0)
3647     return type;
3648
3649   t = copy_type (type);
3650   decl = TYPE_NAME (t);
3651
3652   TYPE_MAIN_VARIANT (t) = t;
3653   TYPE_NEXT_VARIANT (t)= NULL_TREE;
3654   TYPE_POINTER_TO (t) = 0;
3655   TYPE_REFERENCE_TO (t) = 0;
3656
3657   idx = build_template_parm_index (TEMPLATE_PARM_IDX (orig_idx),
3658                                    TEMPLATE_PARM_LEVEL (orig_idx),
3659                                    TEMPLATE_PARM_ORIG_LEVEL (orig_idx),
3660                                    num_parms,
3661                                    decl, t);
3662   TEMPLATE_PARM_DESCENDANTS (idx) = TEMPLATE_PARM_DESCENDANTS (orig_idx);
3663   TEMPLATE_PARM_PARAMETER_PACK (idx) = TEMPLATE_PARM_PARAMETER_PACK (orig_idx);
3664   TEMPLATE_TYPE_PARM_INDEX (t) = idx;
3665
3666   TYPE_STUB_DECL (t) = decl;
3667   TEMPLATE_TYPE_DECL (t) = decl;
3668   if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
3669     TREE_TYPE (DECL_TEMPLATE_RESULT  (decl)) = t;
3670
3671   /* Update the type associated to the type name stored in the symbol
3672      table. Now, whenever the type name is looked up, the resulting
3673      type is properly fixed up.  */
3674   TREE_TYPE (decl) = t;
3675
3676   TYPE_CANONICAL (t) = canonical_type_parameter (t);
3677
3678   return t;
3679 }
3680
3681 /* Create and return a new TEMPLATE_PARM_INDEX that is almost
3682    identical to I, but that is fixed up as to:
3683
3684    1/ carry the number of sibling parms (NUM_PARMS) of the template
3685    parm represented by I.
3686
3687    2/ replace all references to template parm types declared before I
3688    (in the same template parm list as I) by references to template
3689    parm types contained in ARGS. ARGS should contain the list of
3690    template parms that have been fixed up so far, in a form suitable
3691    to be passed to tsubst.
3692
3693    This is a subroutine of fixup_template_parms.  */
3694
3695 static tree
3696 fixup_template_parm_index (tree i, tree args, int num_parms)
3697 {
3698   tree index, decl, type;
3699
3700   if (i == NULL_TREE
3701       || TREE_CODE (i) != TEMPLATE_PARM_INDEX
3702       /* Do not fix up the index twice.  */
3703       || (TEMPLATE_PARM_NUM_SIBLINGS (i) != 0))
3704     return i;
3705
3706   decl = TEMPLATE_PARM_DECL (i);
3707   type = TREE_TYPE (decl);
3708
3709   index = build_template_parm_index (TEMPLATE_PARM_IDX (i),
3710                                      TEMPLATE_PARM_LEVEL (i),
3711                                      TEMPLATE_PARM_ORIG_LEVEL (i),
3712                                      num_parms,
3713                                      decl, type);
3714
3715   TEMPLATE_PARM_DESCENDANTS (index) = TEMPLATE_PARM_DESCENDANTS (i);
3716   TEMPLATE_PARM_PARAMETER_PACK (index) = TEMPLATE_PARM_PARAMETER_PACK (i);
3717
3718   type = tsubst (type, args, tf_none, NULL_TREE);
3719   
3720   TREE_TYPE (decl) = type;
3721   TREE_TYPE (index) = type;
3722
3723   return index;
3724 }
3725
3726 /* 
3727    This is a subroutine of fixup_template_parms.
3728
3729    It computes the canonical type of the type of the template
3730    parameter PARM_DESC and update all references to that type so that
3731    they use the newly computed canonical type. No access check is
3732    performed during the fixup. PARM_DESC is a TREE_LIST which
3733    TREE_VALUE is the template parameter and its TREE_PURPOSE is the
3734    default argument of the template parm if any. IDX is the index of
3735    the template parameter, starting at 0. NUM_PARMS is the number of
3736    template parameters in the set PARM_DESC belongs to. ARGLIST is a
3737    TREE_VEC containing the full set of template parameters in a form
3738    suitable to be passed to substs functions as their ARGS
3739    argument. This is what current_template_args returns for a given
3740    template. The innermost vector of args in ARGLIST is the set of
3741    template parms that have been fixed up so far. This function adds
3742    the fixed up parameter into that vector.  */
3743
3744 static void
3745 fixup_template_parm (tree parm_desc,
3746                      int idx,
3747                      int num_parms,
3748                      tree arglist)
3749 {
3750   tree parm = TREE_VALUE (parm_desc);
3751   tree fixedup_args = INNERMOST_TEMPLATE_ARGS (arglist);
3752
3753   push_deferring_access_checks (dk_no_check);
3754
3755   if (TREE_CODE (parm) == TYPE_DECL)
3756     {
3757       /* PARM is a template type parameter. Fix up its type, add
3758          the fixed-up template parm to the vector of fixed-up
3759          template parms so far, and substitute the fixed-up
3760          template parms into the default argument of this
3761          parameter.  */
3762       tree t =
3763         fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3764       TREE_TYPE (parm) = t;
3765
3766       TREE_VEC_ELT (fixedup_args, idx) = template_parm_to_arg (parm_desc);
3767     }
3768   else if (TREE_CODE (parm) == TEMPLATE_DECL)
3769     {
3770       /* PARM is a template template parameter. This is going to
3771          be interesting.  */
3772       tree tparms, targs, innermost_args, t;
3773       int j;
3774
3775       /* First, fix up the parms of the template template parm
3776          because the parms are involved in defining the new canonical
3777          type of the template template parm.  */
3778
3779       /* So we need to substitute the template parm types that have
3780          been fixed up so far into the template parms of this template
3781          template parm. E.g, consider this:
3782
3783          template<class T, template<T u> class TT> class S;
3784
3785          In this case we want to substitute T into the
3786          template parameters of TT.
3787
3788          So let's walk the template parms of PARM here, and
3789          tsubst ARGLIST into into each of the template
3790          parms.   */
3791
3792       /* For this substitution we need to build the full set of
3793          template parameters and use that as arguments for the
3794          tsubsting function.  */
3795       tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
3796
3797       /* This will contain the innermost parms of PARM into which
3798          we have substituted so far.  */
3799       innermost_args = make_tree_vec (TREE_VEC_LENGTH (tparms));
3800       targs = add_to_template_args (arglist, innermost_args);
3801       for (j = 0; j < TREE_VEC_LENGTH (tparms); ++j)
3802         {
3803           tree parameter;
3804
3805           parameter = TREE_VEC_ELT (tparms, j);
3806
3807           /* INNERMOST_ARGS needs to have at least the same number
3808              of elements as the index PARAMETER, ortherwise
3809              tsubsting into PARAMETER will result in partially
3810              instantiating it, reducing its tempate parm
3811              level. Let's tactically fill INNERMOST_ARGS for that
3812              purpose.  */
3813           TREE_VEC_ELT (innermost_args, j) =
3814             template_parm_to_arg (parameter);
3815
3816           fixup_template_parm (parameter, j,
3817                                TREE_VEC_LENGTH (tparms),
3818                                targs);
3819         }
3820
3821       /* Now fix up the type of the template template parm.  */
3822
3823       t = fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3824       TREE_TYPE (parm) = t;
3825
3826       TREE_VEC_ELT (fixedup_args, idx) =
3827         template_parm_to_arg (parm_desc);
3828     }
3829   else if (TREE_CODE (parm) == PARM_DECL)
3830     {
3831       /* PARM is a non-type template parameter. We need to:
3832
3833        * Fix up its TEMPLATE_PARM_INDEX to make it carry the
3834        proper number of sibling parameters.
3835
3836        * Make lookups of the template parameter return a reference
3837        to the fixed-up index. No lookup should return references
3838        to the former index anymore.
3839
3840        * Substitute the template parms that got fixed up so far
3841
3842        * into the type of PARM.  */
3843
3844       tree index = DECL_INITIAL (parm);
3845
3846       /* PUSHED_DECL is the decl added to the symbol table with
3847          the name of the parameter. E,g:
3848              
3849          template<class T, T u> //#0
3850          auto my_function(T t) -> decltype(u); //#1
3851
3852          Here, when looking up u at //#1, we get the decl of u
3853          resulting from the declaration in #0. This is what
3854          PUSHED_DECL is. We need to replace the reference to the
3855          old TEMPLATE_PARM_INDEX carried by PUSHED_DECL by the
3856          fixed-up TEMPLATE_PARM_INDEX.  */
3857       tree pushed_decl = TEMPLATE_PARM_DECL (index);
3858
3859       /* Let's fix up the TEMPLATE_PARM_INDEX then. Note that we must
3860          fixup the type of PUSHED_DECL as well and luckily
3861          fixup_template_parm_index does it for us too.  */
3862       tree fixed_up_index =
3863         fixup_template_parm_index (index, arglist, num_parms);
3864
3865       DECL_INITIAL (pushed_decl) = DECL_INITIAL (parm) = fixed_up_index;
3866
3867       /* Add this fixed up PARM to the template parms we've fixed
3868          up so far and use that to substitute the fixed-up
3869          template parms into the type of PARM.  */
3870       TREE_VEC_ELT (fixedup_args, idx) =
3871         template_parm_to_arg (parm_desc);
3872       TREE_TYPE (parm) = tsubst (TREE_TYPE (parm), arglist,
3873                                  tf_none, NULL_TREE);
3874     }
3875
3876   TREE_PURPOSE (parm_desc) =
3877     tsubst_template_arg (TREE_PURPOSE (parm_desc),
3878                          arglist, tf_none, parm);
3879
3880   pop_deferring_access_checks ();
3881 }
3882
3883 /* Walk the current template parms and properly compute the canonical
3884    types of the dependent types created during
3885    cp_parser_template_parameter_list.  */
3886
3887 void
3888 fixup_template_parms (void)
3889 {
3890   tree arglist;
3891   tree parameter_vec;
3892   tree fixedup_args;
3893   int i, num_parms;
3894
3895   parameter_vec = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3896   if (parameter_vec == NULL_TREE)
3897     return;
3898
3899   num_parms = TREE_VEC_LENGTH (parameter_vec);
3900
3901   /* This vector contains the current innermost template parms that
3902      have been fixed up so far.  The form of FIXEDUP_ARGS is suitable
3903      to be passed to tsubst* functions as their ARGS argument.  */
3904   fixedup_args = make_tree_vec (num_parms);
3905
3906   /* This vector contains the full set of template parms in a form
3907      suitable to be passed to substs functions as their ARGS
3908      argument.  */
3909   arglist = current_template_args ();
3910   arglist = add_outermost_template_args (arglist, fixedup_args);
3911
3912   /* Let's do the proper fixup now.  */
3913   for (i = 0; i < num_parms; ++i)
3914     fixup_template_parm (TREE_VEC_ELT (parameter_vec, i),
3915                          i, num_parms, arglist);
3916 }
3917
3918 /* end_template_decl is called after a template declaration is seen.  */
3919
3920 void
3921 end_template_decl (void)
3922 {
3923   reset_specialization ();
3924
3925   if (! processing_template_decl)
3926     return;
3927
3928   /* This matches the pushlevel in begin_template_parm_list.  */
3929   finish_scope ();
3930
3931   --processing_template_decl;
3932   current_template_parms = TREE_CHAIN (current_template_parms);
3933 }
3934
3935 /* Takes a TREE_LIST representing a template parameter and convert it
3936    into an argument suitable to be passed to the type substitution
3937    functions.  Note that If the TREE_LIST contains an error_mark
3938    node, the returned argument is error_mark_node.  */
3939
3940 static tree
3941 template_parm_to_arg (tree t)
3942 {
3943
3944   if (t == NULL_TREE
3945       || TREE_CODE (t) != TREE_LIST)
3946     return t;
3947
3948   if (error_operand_p (TREE_VALUE (t)))
3949     return error_mark_node;
3950
3951   t = TREE_VALUE (t);
3952
3953   if (TREE_CODE (t) == TYPE_DECL
3954       || TREE_CODE (t) == TEMPLATE_DECL)
3955     {
3956       t = TREE_TYPE (t);
3957
3958       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3959         {
3960           /* Turn this argument into a TYPE_ARGUMENT_PACK
3961              with a single element, which expands T.  */
3962           tree vec = make_tree_vec (1);
3963 #ifdef ENABLE_CHECKING
3964           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3965             (vec, TREE_VEC_LENGTH (vec));
3966 #endif
3967           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3968
3969           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3970           SET_ARGUMENT_PACK_ARGS (t, vec);
3971         }
3972     }
3973   else
3974     {
3975       t = DECL_INITIAL (t);
3976
3977       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3978         {
3979           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3980              with a single element, which expands T.  */
3981           tree vec = make_tree_vec (1);
3982           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3983 #ifdef ENABLE_CHECKING
3984           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3985             (vec, TREE_VEC_LENGTH (vec));
3986 #endif
3987           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3988
3989           t  = make_node (NONTYPE_ARGUMENT_PACK);
3990           SET_ARGUMENT_PACK_ARGS (t, vec);
3991           TREE_TYPE (t) = type;
3992         }
3993     }
3994   return t;
3995 }
3996
3997 /* Within the declaration of a template, return all levels of template
3998    parameters that apply.  The template parameters are represented as
3999    a TREE_VEC, in the form documented in cp-tree.h for template
4000    arguments.  */
4001
4002 static tree
4003 current_template_args (void)
4004 {
4005   tree header;
4006   tree args = NULL_TREE;
4007   int length = TMPL_PARMS_DEPTH (current_template_parms);
4008   int l = length;
4009
4010   /* If there is only one level of template parameters, we do not
4011      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4012      TREE_VEC containing the arguments.  */
4013   if (length > 1)
4014     args = make_tree_vec (length);
4015
4016   for (header = current_template_parms; header; header = TREE_CHAIN (header))
4017     {
4018       tree a = copy_node (TREE_VALUE (header));
4019       int i;
4020
4021       TREE_TYPE (a) = NULL_TREE;
4022       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4023         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4024
4025 #ifdef ENABLE_CHECKING
4026       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4027 #endif
4028
4029       if (length > 1)
4030         TREE_VEC_ELT (args, --l) = a;
4031       else
4032         args = a;
4033     }
4034
4035     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
4036       /* This can happen for template parms of a template template
4037          parameter, e.g:
4038
4039          template<template<class T, class U> class TT> struct S;
4040
4041          Consider the level of the parms of TT; T and U both have
4042          level 2; TT has no template parm of level 1. So in this case
4043          the first element of full_template_args is NULL_TREE. If we
4044          leave it like this TMPL_ARG_DEPTH on args returns 1 instead
4045          of 2. This will make tsubst wrongly consider that T and U
4046          have level 1. Instead, let's create a dummy vector as the
4047          first element of full_template_args so that TMPL_ARG_DEPTH
4048          returns the correct depth for args.  */
4049       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
4050   return args;
4051 }
4052
4053 /* Update the declared TYPE by doing any lookups which were thought to be
4054    dependent, but are not now that we know the SCOPE of the declarator.  */
4055
4056 tree
4057 maybe_update_decl_type (tree orig_type, tree scope)
4058 {
4059   tree type = orig_type;
4060
4061   if (type == NULL_TREE)
4062     return type;
4063
4064   if (TREE_CODE (orig_type) == TYPE_DECL)
4065     type = TREE_TYPE (type);
4066
4067   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4068       && dependent_type_p (type)
4069       /* Don't bother building up the args in this case.  */
4070       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4071     {
4072       /* tsubst in the args corresponding to the template parameters,
4073          including auto if present.  Most things will be unchanged, but
4074          make_typename_type and tsubst_qualified_id will resolve
4075          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4076       tree args = current_template_args ();
4077       tree auto_node = type_uses_auto (type);
4078       tree pushed;
4079       if (auto_node)
4080         {
4081           tree auto_vec = make_tree_vec (1);
4082           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4083           args = add_to_template_args (args, auto_vec);
4084         }
4085       pushed = push_scope (scope);
4086       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4087       if (pushed)
4088         pop_scope (scope);
4089     }
4090
4091   if (type == error_mark_node)
4092     return orig_type;
4093
4094   if (TREE_CODE (orig_type) == TYPE_DECL)
4095     {
4096       if (same_type_p (type, TREE_TYPE (orig_type)))
4097         type = orig_type;
4098       else
4099         type = TYPE_NAME (type);
4100     }
4101   return type;
4102 }
4103
4104 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4105    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
4106    a member template.  Used by push_template_decl below.  */
4107
4108 static tree
4109 build_template_decl (tree decl, tree parms, bool member_template_p)
4110 {
4111   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4112   DECL_TEMPLATE_PARMS (tmpl) = parms;
4113   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4114   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4115
4116   return tmpl;
4117 }
4118
4119 struct template_parm_data
4120 {
4121   /* The level of the template parameters we are currently
4122      processing.  */
4123   int level;
4124
4125   /* The index of the specialization argument we are currently
4126      processing.  */
4127   int current_arg;
4128
4129   /* An array whose size is the number of template parameters.  The
4130      elements are nonzero if the parameter has been used in any one
4131      of the arguments processed so far.  */
4132   int* parms;
4133
4134   /* An array whose size is the number of template arguments.  The
4135      elements are nonzero if the argument makes use of template
4136      parameters of this level.  */
4137   int* arg_uses_template_parms;
4138 };
4139
4140 /* Subroutine of push_template_decl used to see if each template
4141    parameter in a partial specialization is used in the explicit
4142    argument list.  If T is of the LEVEL given in DATA (which is
4143    treated as a template_parm_data*), then DATA->PARMS is marked
4144    appropriately.  */
4145
4146 static int
4147 mark_template_parm (tree t, void* data)
4148 {
4149   int level;
4150   int idx;
4151   struct template_parm_data* tpd = (struct template_parm_data*) data;
4152
4153   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4154     {
4155       level = TEMPLATE_PARM_LEVEL (t);
4156       idx = TEMPLATE_PARM_IDX (t);
4157     }
4158   else
4159     {
4160       level = TEMPLATE_TYPE_LEVEL (t);
4161       idx = TEMPLATE_TYPE_IDX (t);
4162     }
4163
4164   if (level == tpd->level)
4165     {
4166       tpd->parms[idx] = 1;
4167       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4168     }
4169
4170   /* Return zero so that for_each_template_parm will continue the
4171      traversal of the tree; we want to mark *every* template parm.  */
4172   return 0;
4173 }
4174
4175 /* Process the partial specialization DECL.  */
4176
4177 static tree
4178 process_partial_specialization (tree decl)
4179 {
4180   tree type = TREE_TYPE (decl);
4181   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
4182   tree specargs = CLASSTYPE_TI_ARGS (type);
4183   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4184   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4185   tree inner_parms;
4186   tree inst;
4187   int nargs = TREE_VEC_LENGTH (inner_args);
4188   int ntparms;
4189   int  i;
4190   bool did_error_intro = false;
4191   struct template_parm_data tpd;
4192   struct template_parm_data tpd2;
4193
4194   gcc_assert (current_template_parms);
4195
4196   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4197   ntparms = TREE_VEC_LENGTH (inner_parms);
4198
4199   /* We check that each of the template parameters given in the
4200      partial specialization is used in the argument list to the
4201      specialization.  For example:
4202
4203        template <class T> struct S;
4204        template <class T> struct S<T*>;
4205
4206      The second declaration is OK because `T*' uses the template
4207      parameter T, whereas
4208
4209        template <class T> struct S<int>;
4210
4211      is no good.  Even trickier is:
4212
4213        template <class T>
4214        struct S1
4215        {
4216           template <class U>
4217           struct S2;
4218           template <class U>
4219           struct S2<T>;
4220        };
4221
4222      The S2<T> declaration is actually invalid; it is a
4223      full-specialization.  Of course,
4224
4225           template <class U>
4226           struct S2<T (*)(U)>;
4227
4228      or some such would have been OK.  */
4229   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4230   tpd.parms = XALLOCAVEC (int, ntparms);
4231   memset (tpd.parms, 0, sizeof (int) * ntparms);
4232
4233   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4234   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4235   for (i = 0; i < nargs; ++i)
4236     {
4237       tpd.current_arg = i;
4238       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4239                               &mark_template_parm,
4240                               &tpd,
4241                               NULL,
4242                               /*include_nondeduced_p=*/false);
4243     }
4244   for (i = 0; i < ntparms; ++i)
4245     if (tpd.parms[i] == 0)
4246       {
4247         /* One of the template parms was not used in the
4248            specialization.  */
4249         if (!did_error_intro)
4250           {
4251             error ("template parameters not used in partial specialization:");
4252             did_error_intro = true;
4253           }
4254
4255         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4256       }
4257
4258   if (did_error_intro)
4259     return error_mark_node;
4260
4261   /* [temp.class.spec]
4262
4263      The argument list of the specialization shall not be identical to
4264      the implicit argument list of the primary template.  */
4265   if (comp_template_args
4266       (inner_args,
4267        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
4268                                                    (maintmpl)))))
4269     error ("partial specialization %qT does not specialize any template arguments", type);
4270
4271   /* [temp.class.spec]
4272
4273      A partially specialized non-type argument expression shall not
4274      involve template parameters of the partial specialization except
4275      when the argument expression is a simple identifier.
4276
4277      The type of a template parameter corresponding to a specialized
4278      non-type argument shall not be dependent on a parameter of the
4279      specialization. 
4280
4281      Also, we verify that pack expansions only occur at the
4282      end of the argument list.  */
4283   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4284   tpd2.parms = 0;
4285   for (i = 0; i < nargs; ++i)
4286     {
4287       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4288       tree arg = TREE_VEC_ELT (inner_args, i);
4289       tree packed_args = NULL_TREE;
4290       int j, len = 1;
4291
4292       if (ARGUMENT_PACK_P (arg))
4293         {
4294           /* Extract the arguments from the argument pack. We'll be
4295              iterating over these in the following loop.  */
4296           packed_args = ARGUMENT_PACK_ARGS (arg);
4297           len = TREE_VEC_LENGTH (packed_args);
4298         }
4299
4300       for (j = 0; j < len; j++)
4301         {
4302           if (packed_args)
4303             /* Get the Jth argument in the parameter pack.  */
4304             arg = TREE_VEC_ELT (packed_args, j);
4305
4306           if (PACK_EXPANSION_P (arg))
4307             {
4308               /* Pack expansions must come at the end of the
4309                  argument list.  */
4310               if ((packed_args && j < len - 1)
4311                   || (!packed_args && i < nargs - 1))
4312                 {
4313                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4314                     error ("parameter pack argument %qE must be at the "
4315                            "end of the template argument list", arg);
4316                   else
4317                     error ("parameter pack argument %qT must be at the "
4318                            "end of the template argument list", arg);
4319                 }
4320             }
4321
4322           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4323             /* We only care about the pattern.  */
4324             arg = PACK_EXPANSION_PATTERN (arg);
4325
4326           if (/* These first two lines are the `non-type' bit.  */
4327               !TYPE_P (arg)
4328               && TREE_CODE (arg) != TEMPLATE_DECL
4329               /* This next line is the `argument expression is not just a
4330                  simple identifier' condition and also the `specialized
4331                  non-type argument' bit.  */
4332               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
4333             {
4334               if ((!packed_args && tpd.arg_uses_template_parms[i])
4335                   || (packed_args && uses_template_parms (arg)))
4336                 error ("template argument %qE involves template parameter(s)",
4337                        arg);
4338               else 
4339                 {
4340                   /* Look at the corresponding template parameter,
4341                      marking which template parameters its type depends
4342                      upon.  */
4343                   tree type = TREE_TYPE (parm);
4344
4345                   if (!tpd2.parms)
4346                     {
4347                       /* We haven't yet initialized TPD2.  Do so now.  */
4348                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4349                       /* The number of parameters here is the number in the
4350                          main template, which, as checked in the assertion
4351                          above, is NARGS.  */
4352                       tpd2.parms = XALLOCAVEC (int, nargs);
4353                       tpd2.level = 
4354                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4355                     }
4356
4357                   /* Mark the template parameters.  But this time, we're
4358                      looking for the template parameters of the main
4359                      template, not in the specialization.  */
4360                   tpd2.current_arg = i;
4361                   tpd2.arg_uses_template_parms[i] = 0;
4362                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4363                   for_each_template_parm (type,
4364                                           &mark_template_parm,
4365                                           &tpd2,
4366                                           NULL,
4367                                           /*include_nondeduced_p=*/false);
4368
4369                   if (tpd2.arg_uses_template_parms [i])
4370                     {
4371                       /* The type depended on some template parameters.
4372                          If they are fully specialized in the
4373                          specialization, that's OK.  */
4374                       int j;
4375                       int count = 0;
4376                       for (j = 0; j < nargs; ++j)
4377                         if (tpd2.parms[j] != 0
4378                             && tpd.arg_uses_template_parms [j])
4379                           ++count;
4380                       if (count != 0)
4381                         error_n (input_location, count,
4382                                  "type %qT of template argument %qE depends "
4383                                  "on a template parameter",
4384                                  "type %qT of template argument %qE depends "
4385                                  "on template parameters",
4386                                  type,
4387                                  arg);
4388                     }
4389                 }
4390             }
4391         }
4392     }
4393
4394   /* We should only get here once.  */
4395   gcc_assert (!COMPLETE_TYPE_P (type));
4396
4397   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4398     = tree_cons (specargs, inner_parms,
4399                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4400   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4401
4402   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4403        inst = TREE_CHAIN (inst))
4404     {
4405       tree inst_type = TREE_VALUE (inst);
4406       if (COMPLETE_TYPE_P (inst_type)
4407           && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4408         {
4409           tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4410           if (spec && TREE_TYPE (spec) == type)
4411             permerror (input_location,
4412                        "partial specialization of %qT after instantiation "
4413                        "of %qT", type, inst_type);
4414         }
4415     }
4416
4417   return decl;
4418 }
4419
4420 /* Check that a template declaration's use of default arguments and
4421    parameter packs is not invalid.  Here, PARMS are the template
4422    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4423    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4424    specialization.
4425    
4426
4427    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4428    declaration (but not a definition); 1 indicates a declaration, 2
4429    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4430    emitted for extraneous default arguments.
4431
4432    Returns TRUE if there were no errors found, FALSE otherwise. */
4433
4434 bool
4435 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4436                          int is_partial, int is_friend_decl)
4437 {
4438   const char *msg;
4439   int last_level_to_check;
4440   tree parm_level;
4441   bool no_errors = true;
4442
4443   /* [temp.param]
4444
4445      A default template-argument shall not be specified in a
4446      function template declaration or a function template definition, nor
4447      in the template-parameter-list of the definition of a member of a
4448      class template.  */
4449
4450   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4451     /* You can't have a function template declaration in a local
4452        scope, nor you can you define a member of a class template in a
4453        local scope.  */
4454     return true;
4455
4456   if (current_class_type
4457       && !TYPE_BEING_DEFINED (current_class_type)
4458       && DECL_LANG_SPECIFIC (decl)
4459       && DECL_DECLARES_FUNCTION_P (decl)
4460       /* If this is either a friend defined in the scope of the class
4461          or a member function.  */
4462       && (DECL_FUNCTION_MEMBER_P (decl)
4463           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4464           : DECL_FRIEND_CONTEXT (decl)
4465           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4466           : false)
4467       /* And, if it was a member function, it really was defined in
4468          the scope of the class.  */
4469       && (!DECL_FUNCTION_MEMBER_P (decl)
4470           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4471     /* We already checked these parameters when the template was
4472        declared, so there's no need to do it again now.  This function
4473        was defined in class scope, but we're processing it's body now
4474        that the class is complete.  */
4475     return true;
4476
4477   /* Core issue 226 (C++0x only): the following only applies to class
4478      templates.  */
4479   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4480     {
4481       /* [temp.param]
4482
4483          If a template-parameter has a default template-argument, all
4484          subsequent template-parameters shall have a default
4485          template-argument supplied.  */
4486       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4487         {
4488           tree inner_parms = TREE_VALUE (parm_level);
4489           int ntparms = TREE_VEC_LENGTH (inner_parms);
4490           int seen_def_arg_p = 0;
4491           int i;
4492
4493           for (i = 0; i < ntparms; ++i)
4494             {
4495               tree parm = TREE_VEC_ELT (inner_parms, i);
4496
4497               if (parm == error_mark_node)
4498                 continue;
4499
4500               if (TREE_PURPOSE (parm))
4501                 seen_def_arg_p = 1;
4502               else if (seen_def_arg_p
4503                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4504                 {
4505                   error ("no default argument for %qD", TREE_VALUE (parm));
4506                   /* For better subsequent error-recovery, we indicate that
4507                      there should have been a default argument.  */
4508                   TREE_PURPOSE (parm) = error_mark_node;
4509                   no_errors = false;
4510                 }
4511               else if (is_primary
4512                        && !is_partial
4513                        && !is_friend_decl
4514                        /* Don't complain about an enclosing partial
4515                           specialization.  */
4516                        && parm_level == parms
4517                        && TREE_CODE (decl) == TYPE_DECL
4518                        && i < ntparms - 1
4519                        && template_parameter_pack_p (TREE_VALUE (parm)))
4520                 {
4521                   /* A primary class template can only have one
4522                      parameter pack, at the end of the template
4523                      parameter list.  */
4524
4525                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4526                     error ("parameter pack %qE must be at the end of the"
4527                            " template parameter list", TREE_VALUE (parm));
4528                   else
4529                     error ("parameter pack %qT must be at the end of the"
4530                            " template parameter list", 
4531                            TREE_TYPE (TREE_VALUE (parm)));
4532
4533                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4534                     = error_mark_node;
4535                   no_errors = false;
4536                 }
4537             }
4538         }
4539     }
4540
4541   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4542       || is_partial 
4543       || !is_primary
4544       || is_friend_decl)
4545     /* For an ordinary class template, default template arguments are
4546        allowed at the innermost level, e.g.:
4547          template <class T = int>
4548          struct S {};
4549        but, in a partial specialization, they're not allowed even
4550        there, as we have in [temp.class.spec]:
4551
4552          The template parameter list of a specialization shall not
4553          contain default template argument values.
4554
4555        So, for a partial specialization, or for a function template
4556        (in C++98/C++03), we look at all of them.  */
4557     ;
4558   else
4559     /* But, for a primary class template that is not a partial
4560        specialization we look at all template parameters except the
4561        innermost ones.  */
4562     parms = TREE_CHAIN (parms);
4563
4564   /* Figure out what error message to issue.  */
4565   if (is_friend_decl == 2)
4566     msg = G_("default template arguments may not be used in function template "
4567              "friend re-declaration");
4568   else if (is_friend_decl)
4569     msg = G_("default template arguments may not be used in function template "
4570              "friend declarations");
4571   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4572     msg = G_("default template arguments may not be used in function templates "
4573              "without -std=c++0x or -std=gnu++0x");
4574   else if (is_partial)
4575     msg = G_("default template arguments may not be used in "
4576              "partial specializations");
4577   else
4578     msg = G_("default argument for template parameter for class enclosing %qD");
4579
4580   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4581     /* If we're inside a class definition, there's no need to
4582        examine the parameters to the class itself.  On the one
4583        hand, they will be checked when the class is defined, and,
4584        on the other, default arguments are valid in things like:
4585          template <class T = double>
4586          struct S { template <class U> void f(U); };
4587        Here the default argument for `S' has no bearing on the
4588        declaration of `f'.  */
4589     last_level_to_check = template_class_depth (current_class_type) + 1;
4590   else
4591     /* Check everything.  */
4592     last_level_to_check = 0;
4593
4594   for (parm_level = parms;
4595        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4596        parm_level = TREE_CHAIN (parm_level))
4597     {
4598       tree inner_parms = TREE_VALUE (parm_level);
4599       int i;
4600       int ntparms;
4601
4602       ntparms = TREE_VEC_LENGTH (inner_parms);
4603       for (i = 0; i < ntparms; ++i)
4604         {
4605           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4606             continue;
4607
4608           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4609             {
4610               if (msg)
4611                 {
4612                   no_errors = false;
4613                   if (is_friend_decl == 2)
4614                     return no_errors;
4615
4616                   error (msg, decl);
4617                   msg = 0;
4618                 }
4619
4620               /* Clear out the default argument so that we are not
4621                  confused later.  */
4622               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4623             }
4624         }
4625
4626       /* At this point, if we're still interested in issuing messages,
4627          they must apply to classes surrounding the object declared.  */
4628       if (msg)
4629         msg = G_("default argument for template parameter for class "
4630                  "enclosing %qD");
4631     }
4632
4633   return no_errors;
4634 }
4635
4636 /* Worker for push_template_decl_real, called via
4637    for_each_template_parm.  DATA is really an int, indicating the
4638    level of the parameters we are interested in.  If T is a template
4639    parameter of that level, return nonzero.  */
4640
4641 static int
4642 template_parm_this_level_p (tree t, void* data)
4643 {
4644   int this_level = *(int *)data;
4645   int level;
4646
4647   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4648     level = TEMPLATE_PARM_LEVEL (t);
4649   else
4650     level = TEMPLATE_TYPE_LEVEL (t);
4651   return level == this_level;
4652 }
4653
4654 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4655    parameters given by current_template_args, or reuses a
4656    previously existing one, if appropriate.  Returns the DECL, or an
4657    equivalent one, if it is replaced via a call to duplicate_decls.
4658
4659    If IS_FRIEND is true, DECL is a friend declaration.  */
4660
4661 tree
4662 push_template_decl_real (tree decl, bool is_friend)
4663 {
4664   tree tmpl;
4665   tree args;
4666   tree info;
4667   tree ctx;
4668   int primary;
4669   int is_partial;
4670   int new_template_p = 0;
4671   /* True if the template is a member template, in the sense of
4672      [temp.mem].  */
4673   bool member_template_p = false;
4674
4675   if (decl == error_mark_node || !current_template_parms)
4676     return error_mark_node;
4677
4678   /* See if this is a partial specialization.  */
4679   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4680                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4681                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4682
4683   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4684     is_friend = true;
4685
4686   if (is_friend)
4687     /* For a friend, we want the context of the friend function, not
4688        the type of which it is a friend.  */
4689     ctx = CP_DECL_CONTEXT (decl);
4690   else if (CP_DECL_CONTEXT (decl)
4691            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4692     /* In the case of a virtual function, we want the class in which
4693        it is defined.  */
4694     ctx = CP_DECL_CONTEXT (decl);
4695   else
4696     /* Otherwise, if we're currently defining some class, the DECL
4697        is assumed to be a member of the class.  */
4698     ctx = current_scope ();
4699
4700   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4701     ctx = NULL_TREE;
4702
4703   if (!DECL_CONTEXT (decl))
4704     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4705
4706   /* See if this is a primary template.  */
4707   if (is_friend && ctx)
4708     /* A friend template that specifies a class context, i.e.
4709          template <typename T> friend void A<T>::f();
4710        is not primary.  */
4711     primary = 0;
4712   else
4713     primary = template_parm_scope_p ();
4714
4715   if (primary)
4716     {
4717       if (DECL_CLASS_SCOPE_P (decl))
4718         member_template_p = true;
4719       if (TREE_CODE (decl) == TYPE_DECL
4720           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4721         {
4722           error ("template class without a name");
4723           return error_mark_node;
4724         }
4725       else if (TREE_CODE (decl) == FUNCTION_DECL)
4726         {
4727           if (DECL_DESTRUCTOR_P (decl))
4728             {
4729               /* [temp.mem]
4730
4731                  A destructor shall not be a member template.  */
4732               error ("destructor %qD declared as member template", decl);
4733               return error_mark_node;
4734             }
4735           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4736               && (!prototype_p (TREE_TYPE (decl))
4737                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4738                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4739                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4740                       == void_list_node)))
4741             {
4742               /* [basic.stc.dynamic.allocation]
4743
4744                  An allocation function can be a function
4745                  template. ... Template allocation functions shall
4746                  have two or more parameters.  */
4747               error ("invalid template declaration of %qD", decl);
4748               return error_mark_node;
4749             }
4750         }
4751       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4752                && CLASS_TYPE_P (TREE_TYPE (decl)))
4753         /* OK */;
4754       else
4755         {
4756           error ("template declaration of %q#D", decl);
4757           return error_mark_node;
4758         }
4759     }
4760
4761   /* Check to see that the rules regarding the use of default
4762      arguments are not being violated.  */
4763   check_default_tmpl_args (decl, current_template_parms,
4764                            primary, is_partial, /*is_friend_decl=*/0);
4765
4766   /* Ensure that there are no parameter packs in the type of this
4767      declaration that have not been expanded.  */
4768   if (TREE_CODE (decl) == FUNCTION_DECL)
4769     {
4770       /* Check each of the arguments individually to see if there are
4771          any bare parameter packs.  */
4772       tree type = TREE_TYPE (decl);
4773       tree arg = DECL_ARGUMENTS (decl);
4774       tree argtype = TYPE_ARG_TYPES (type);
4775
4776       while (arg && argtype)
4777         {
4778           if (!FUNCTION_PARAMETER_PACK_P (arg)
4779               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4780             {
4781             /* This is a PARM_DECL that contains unexpanded parameter
4782                packs. We have already complained about this in the
4783                check_for_bare_parameter_packs call, so just replace
4784                these types with ERROR_MARK_NODE.  */
4785               TREE_TYPE (arg) = error_mark_node;
4786               TREE_VALUE (argtype) = error_mark_node;
4787             }
4788
4789           arg = DECL_CHAIN (arg);
4790           argtype = TREE_CHAIN (argtype);
4791         }
4792
4793       /* Check for bare parameter packs in the return type and the
4794          exception specifiers.  */
4795       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4796         /* Errors were already issued, set return type to int
4797            as the frontend doesn't expect error_mark_node as
4798            the return type.  */
4799         TREE_TYPE (type) = integer_type_node;
4800       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4801         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4802     }
4803   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4804     {
4805       TREE_TYPE (decl) = error_mark_node;
4806       return error_mark_node;
4807     }
4808
4809   if (is_partial)
4810     return process_partial_specialization (decl);
4811
4812   args = current_template_args ();
4813
4814   if (!ctx
4815       || TREE_CODE (ctx) == FUNCTION_DECL
4816       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4817       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4818     {
4819       if (DECL_LANG_SPECIFIC (decl)
4820           && DECL_TEMPLATE_INFO (decl)
4821           && DECL_TI_TEMPLATE (decl))
4822         tmpl = DECL_TI_TEMPLATE (decl);
4823       /* If DECL is a TYPE_DECL for a class-template, then there won't
4824          be DECL_LANG_SPECIFIC.  The information equivalent to
4825          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4826       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4827                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4828                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4829         {
4830           /* Since a template declaration already existed for this
4831              class-type, we must be redeclaring it here.  Make sure
4832              that the redeclaration is valid.  */
4833           redeclare_class_template (TREE_TYPE (decl),
4834                                     current_template_parms);
4835           /* We don't need to create a new TEMPLATE_DECL; just use the
4836              one we already had.  */
4837           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4838         }
4839       else
4840         {
4841           tmpl = build_template_decl (decl, current_template_parms,
4842                                       member_template_p);
4843           new_template_p = 1;
4844
4845           if (DECL_LANG_SPECIFIC (decl)
4846               && DECL_TEMPLATE_SPECIALIZATION (decl))
4847             {
4848               /* A specialization of a member template of a template
4849                  class.  */
4850               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4851               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4852               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4853             }
4854         }
4855     }
4856   else
4857     {
4858       tree a, t, current, parms;
4859       int i;
4860       tree tinfo = get_template_info (decl);
4861
4862       if (!tinfo)
4863         {
4864           error ("template definition of non-template %q#D", decl);
4865           return error_mark_node;
4866         }
4867
4868       tmpl = TI_TEMPLATE (tinfo);
4869
4870       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4871           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4872           && DECL_TEMPLATE_SPECIALIZATION (decl)
4873           && DECL_MEMBER_TEMPLATE_P (tmpl))
4874         {
4875           tree new_tmpl;
4876
4877           /* The declaration is a specialization of a member
4878              template, declared outside the class.  Therefore, the
4879              innermost template arguments will be NULL, so we
4880              replace them with the arguments determined by the
4881              earlier call to check_explicit_specialization.  */
4882           args = DECL_TI_ARGS (decl);
4883
4884           new_tmpl
4885             = build_template_decl (decl, current_template_parms,
4886                                    member_template_p);
4887           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4888           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4889           DECL_TI_TEMPLATE (decl) = new_tmpl;
4890           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4891           DECL_TEMPLATE_INFO (new_tmpl)
4892             = build_template_info (tmpl, args);
4893
4894           register_specialization (new_tmpl,
4895                                    most_general_template (tmpl),
4896                                    args,
4897                                    is_friend, 0);
4898           return decl;
4899         }
4900
4901       /* Make sure the template headers we got make sense.  */
4902
4903       parms = DECL_TEMPLATE_PARMS (tmpl);
4904       i = TMPL_PARMS_DEPTH (parms);
4905       if (TMPL_ARGS_DEPTH (args) != i)
4906         {
4907           error ("expected %d levels of template parms for %q#D, got %d",
4908                  i, decl, TMPL_ARGS_DEPTH (args));
4909         }
4910       else
4911         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4912           {
4913             a = TMPL_ARGS_LEVEL (args, i);
4914             t = INNERMOST_TEMPLATE_PARMS (parms);
4915
4916             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4917               {
4918                 if (current == decl)
4919                   error ("got %d template parameters for %q#D",
4920                          TREE_VEC_LENGTH (a), decl);
4921                 else
4922                   error ("got %d template parameters for %q#T",
4923                          TREE_VEC_LENGTH (a), current);
4924                 error ("  but %d required", TREE_VEC_LENGTH (t));
4925                 return error_mark_node;
4926               }
4927
4928             if (current == decl)
4929               current = ctx;
4930             else if (current == NULL_TREE)
4931               /* Can happen in erroneous input.  */
4932               break;
4933             else
4934               current = (TYPE_P (current)
4935                          ? TYPE_CONTEXT (current)
4936                          : DECL_CONTEXT (current));
4937           }
4938
4939       /* Check that the parms are used in the appropriate qualifying scopes
4940          in the declarator.  */
4941       if (!comp_template_args
4942           (TI_ARGS (tinfo),
4943            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4944         {
4945           error ("\
4946 template arguments to %qD do not match original template %qD",
4947                  decl, DECL_TEMPLATE_RESULT (tmpl));
4948           if (!uses_template_parms (TI_ARGS (tinfo)))
4949             inform (input_location, "use template<> for an explicit specialization");
4950           /* Avoid crash in import_export_decl.  */
4951           DECL_INTERFACE_KNOWN (decl) = 1;
4952           return error_mark_node;
4953         }
4954     }
4955
4956   DECL_TEMPLATE_RESULT (tmpl) = decl;
4957   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4958
4959   /* Push template declarations for global functions and types.  Note
4960      that we do not try to push a global template friend declared in a
4961      template class; such a thing may well depend on the template
4962      parameters of the class.  */
4963   if (new_template_p && !ctx
4964       && !(is_friend && template_class_depth (current_class_type) > 0))
4965     {
4966       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4967       if (tmpl == error_mark_node)
4968         return error_mark_node;
4969
4970       /* Hide template friend classes that haven't been declared yet.  */
4971       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4972         {
4973           DECL_ANTICIPATED (tmpl) = 1;
4974           DECL_FRIEND_P (tmpl) = 1;
4975         }
4976     }
4977
4978   if (primary)
4979     {
4980       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4981       int i;
4982
4983       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4984       if (DECL_CONV_FN_P (tmpl))
4985         {
4986           int depth = TMPL_PARMS_DEPTH (parms);
4987
4988           /* It is a conversion operator. See if the type converted to
4989              depends on innermost template operands.  */
4990
4991           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4992                                          depth))
4993             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4994         }
4995
4996       /* Give template template parms a DECL_CONTEXT of the template
4997          for which they are a parameter.  */
4998       parms = INNERMOST_TEMPLATE_PARMS (parms);
4999       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5000         {
5001           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5002           if (TREE_CODE (parm) == TEMPLATE_DECL)
5003             DECL_CONTEXT (parm) = tmpl;
5004         }
5005     }
5006
5007   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5008      back to its most general template.  If TMPL is a specialization,
5009      ARGS may only have the innermost set of arguments.  Add the missing
5010      argument levels if necessary.  */
5011   if (DECL_TEMPLATE_INFO (tmpl))
5012     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5013
5014   info = build_template_info (tmpl, args);
5015
5016   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5017     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5018   else if (DECL_LANG_SPECIFIC (decl))
5019     DECL_TEMPLATE_INFO (decl) = info;
5020
5021   return DECL_TEMPLATE_RESULT (tmpl);
5022 }
5023
5024 tree
5025 push_template_decl (tree decl)
5026 {
5027   return push_template_decl_real (decl, false);
5028 }
5029
5030 /* Called when a class template TYPE is redeclared with the indicated
5031    template PARMS, e.g.:
5032
5033      template <class T> struct S;
5034      template <class T> struct S {};  */
5035
5036 bool
5037 redeclare_class_template (tree type, tree parms)
5038 {
5039   tree tmpl;
5040   tree tmpl_parms;
5041   int i;
5042
5043   if (!TYPE_TEMPLATE_INFO (type))
5044     {
5045       error ("%qT is not a template type", type);
5046       return false;
5047     }
5048
5049   tmpl = TYPE_TI_TEMPLATE (type);
5050   if (!PRIMARY_TEMPLATE_P (tmpl))
5051     /* The type is nested in some template class.  Nothing to worry
5052        about here; there are no new template parameters for the nested
5053        type.  */
5054     return true;
5055
5056   if (!parms)
5057     {
5058       error ("template specifiers not specified in declaration of %qD",
5059              tmpl);
5060       return false;
5061     }
5062
5063   parms = INNERMOST_TEMPLATE_PARMS (parms);
5064   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5065
5066   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5067     {
5068       error_n (input_location, TREE_VEC_LENGTH (parms),
5069                "redeclared with %d template parameter",
5070                "redeclared with %d template parameters",
5071                TREE_VEC_LENGTH (parms));
5072       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
5073                 "previous declaration %q+D used %d template parameter",
5074                 "previous declaration %q+D used %d template parameters",
5075                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5076       return false;
5077     }
5078
5079   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5080     {
5081       tree tmpl_parm;
5082       tree parm;
5083       tree tmpl_default;
5084       tree parm_default;
5085
5086       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5087           || TREE_VEC_ELT (parms, i) == error_mark_node)
5088         continue;
5089
5090       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5091       if (tmpl_parm == error_mark_node)
5092         return false;
5093
5094       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5095       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5096       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5097
5098       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5099          TEMPLATE_DECL.  */
5100       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5101           || (TREE_CODE (tmpl_parm) != TYPE_DECL
5102               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5103           || (TREE_CODE (tmpl_parm) != PARM_DECL
5104               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5105                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5106           || (TREE_CODE (tmpl_parm) == PARM_DECL
5107               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5108                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5109         {
5110           error ("template parameter %q+#D", tmpl_parm);
5111           error ("redeclared here as %q#D", parm);
5112           return false;
5113         }
5114
5115       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5116         {
5117           /* We have in [temp.param]:
5118
5119              A template-parameter may not be given default arguments
5120              by two different declarations in the same scope.  */
5121           error_at (input_location, "redefinition of default argument for %q#D", parm);
5122           inform (DECL_SOURCE_LOCATION (tmpl_parm),
5123                   "original definition appeared here");
5124           return false;
5125         }
5126
5127       if (parm_default != NULL_TREE)
5128         /* Update the previous template parameters (which are the ones
5129            that will really count) with the new default value.  */
5130         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5131       else if (tmpl_default != NULL_TREE)
5132         /* Update the new parameters, too; they'll be used as the
5133            parameters for any members.  */
5134         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5135     }
5136
5137     return true;
5138 }
5139
5140 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5141    (possibly simplified) expression.  */
5142
5143 static tree
5144 fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5145 {
5146   if (expr == NULL_TREE)
5147     return NULL_TREE;
5148
5149   /* If we're in a template, but EXPR isn't value dependent, simplify
5150      it.  We're supposed to treat:
5151
5152        template <typename T> void f(T[1 + 1]);
5153        template <typename T> void f(T[2]);
5154
5155      as two declarations of the same function, for example.  */
5156   if (processing_template_decl
5157       && !type_dependent_expression_p (expr)
5158       && potential_constant_expression (expr)
5159       && !value_dependent_expression_p (expr))
5160     {
5161       HOST_WIDE_INT saved_processing_template_decl;
5162
5163       saved_processing_template_decl = processing_template_decl;
5164       processing_template_decl = 0;
5165       expr = tsubst_copy_and_build (expr,
5166                                     /*args=*/NULL_TREE,
5167                                     complain,
5168                                     /*in_decl=*/NULL_TREE,
5169                                     /*function_p=*/false,
5170                                     /*integral_constant_expression_p=*/true);
5171       processing_template_decl = saved_processing_template_decl;
5172     }
5173   return expr;
5174 }
5175
5176 tree
5177 fold_non_dependent_expr (tree expr)
5178 {
5179   return fold_non_dependent_expr_sfinae (expr, tf_error);
5180 }
5181
5182 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5183    must be a function or a pointer-to-function type, as specified
5184    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5185    and check that the resulting function has external linkage.  */
5186
5187 static tree
5188 convert_nontype_argument_function (tree type, tree expr)
5189 {
5190   tree fns = expr;
5191   tree fn, fn_no_ptr;
5192
5193   fn = instantiate_type (type, fns, tf_none);
5194   if (fn == error_mark_node)
5195     return error_mark_node;
5196
5197   fn_no_ptr = fn;
5198   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5199     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5200   if (TREE_CODE (fn_no_ptr) == BASELINK)
5201     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5202  
5203   /* [temp.arg.nontype]/1
5204
5205      A template-argument for a non-type, non-template template-parameter
5206      shall be one of:
5207      [...]
5208      -- the address of an object or function with external linkage.  */
5209   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
5210     {
5211       error ("%qE is not a valid template argument for type %qT "
5212              "because function %qD has not external linkage",
5213              expr, type, fn_no_ptr);
5214       return NULL_TREE;
5215     }
5216
5217   return fn;
5218 }
5219
5220 /* Subroutine of convert_nontype_argument.
5221    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5222    Emit an error otherwise.  */
5223
5224 static bool
5225 check_valid_ptrmem_cst_expr (tree type, tree expr,
5226                              tsubst_flags_t complain)
5227 {
5228   STRIP_NOPS (expr);
5229   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5230     return true;
5231   if (complain & tf_error)
5232     {
5233       error ("%qE is not a valid template argument for type %qT",
5234              expr, type);
5235       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5236     }
5237   return false;
5238 }
5239
5240 /* Returns TRUE iff the address of OP is value-dependent.
5241
5242    14.6.2.4 [temp.dep.temp]:
5243    A non-integral non-type template-argument is dependent if its type is
5244    dependent or it has either of the following forms
5245      qualified-id
5246      & qualified-id
5247    and contains a nested-name-specifier which specifies a class-name that
5248    names a dependent type.
5249
5250    We generalize this to just say that the address of a member of a
5251    dependent class is value-dependent; the above doesn't cover the
5252    address of a static data member named with an unqualified-id.  */
5253
5254 static bool
5255 has_value_dependent_address (tree op)
5256 {
5257   /* We could use get_inner_reference here, but there's no need;
5258      this is only relevant for template non-type arguments, which
5259      can only be expressed as &id-expression.  */
5260   if (DECL_P (op))
5261     {
5262       tree ctx = CP_DECL_CONTEXT (op);
5263       if (TYPE_P (ctx) && dependent_type_p (ctx))
5264         return true;
5265     }
5266
5267   return false;
5268 }
5269
5270 /* Attempt to convert the non-type template parameter EXPR to the
5271    indicated TYPE.  If the conversion is successful, return the
5272    converted value.  If the conversion is unsuccessful, return
5273    NULL_TREE if we issued an error message, or error_mark_node if we
5274    did not.  We issue error messages for out-and-out bad template
5275    parameters, but not simply because the conversion failed, since we
5276    might be just trying to do argument deduction.  Both TYPE and EXPR
5277    must be non-dependent.
5278
5279    The conversion follows the special rules described in
5280    [temp.arg.nontype], and it is much more strict than an implicit
5281    conversion.
5282
5283    This function is called twice for each template argument (see
5284    lookup_template_class for a more accurate description of this
5285    problem). This means that we need to handle expressions which
5286    are not valid in a C++ source, but can be created from the
5287    first call (for instance, casts to perform conversions). These
5288    hacks can go away after we fix the double coercion problem.  */
5289
5290 static tree
5291 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5292 {
5293   tree expr_type;
5294
5295   /* Detect immediately string literals as invalid non-type argument.
5296      This special-case is not needed for correctness (we would easily
5297      catch this later), but only to provide better diagnostic for this
5298      common user mistake. As suggested by DR 100, we do not mention
5299      linkage issues in the diagnostic as this is not the point.  */
5300   /* FIXME we're making this OK.  */
5301   if (TREE_CODE (expr) == STRING_CST)
5302     {
5303       if (complain & tf_error)
5304         error ("%qE is not a valid template argument for type %qT "
5305                "because string literals can never be used in this context",
5306                expr, type);
5307       return NULL_TREE;
5308     }
5309
5310   /* Add the ADDR_EXPR now for the benefit of
5311      value_dependent_expression_p.  */
5312   if (TYPE_PTROBV_P (type)
5313       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
5314     expr = decay_conversion (expr);
5315
5316   /* If we are in a template, EXPR may be non-dependent, but still
5317      have a syntactic, rather than semantic, form.  For example, EXPR
5318      might be a SCOPE_REF, rather than the VAR_DECL to which the
5319      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5320      so that access checking can be performed when the template is
5321      instantiated -- but here we need the resolved form so that we can
5322      convert the argument.  */
5323   if (TYPE_REF_OBJ_P (type)
5324       && has_value_dependent_address (expr))
5325     /* If we want the address and it's value-dependent, don't fold.  */;
5326   else if (!type_unknown_p (expr))
5327     expr = fold_non_dependent_expr_sfinae (expr, complain);
5328   if (error_operand_p (expr))
5329     return error_mark_node;
5330   expr_type = TREE_TYPE (expr);
5331   if (TREE_CODE (type) == REFERENCE_TYPE)
5332     expr = mark_lvalue_use (expr);
5333   else
5334     expr = mark_rvalue_use (expr);
5335
5336   /* HACK: Due to double coercion, we can get a
5337      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5338      which is the tree that we built on the first call (see
5339      below when coercing to reference to object or to reference to
5340      function). We just strip everything and get to the arg.
5341      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5342      for examples.  */
5343   if (TREE_CODE (expr) == NOP_EXPR)
5344     {
5345       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5346         {
5347           /* ??? Maybe we could use convert_from_reference here, but we
5348              would need to relax its constraints because the NOP_EXPR
5349              could actually change the type to something more cv-qualified,
5350              and this is not folded by convert_from_reference.  */
5351           tree addr = TREE_OPERAND (expr, 0);
5352           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
5353           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
5354           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
5355           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5356                       (TREE_TYPE (expr_type),
5357                        TREE_TYPE (TREE_TYPE (addr))));
5358
5359           expr = TREE_OPERAND (addr, 0);
5360           expr_type = TREE_TYPE (expr);
5361         }
5362
5363       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5364          parameter is a pointer to object, through decay and
5365          qualification conversion. Let's strip everything.  */
5366       else if (TYPE_PTROBV_P (type))
5367         {
5368           STRIP_NOPS (expr);
5369           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5370           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5371           /* Skip the ADDR_EXPR only if it is part of the decay for
5372              an array. Otherwise, it is part of the original argument
5373              in the source code.  */
5374           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5375             expr = TREE_OPERAND (expr, 0);
5376           expr_type = TREE_TYPE (expr);
5377         }
5378     }
5379
5380   /* [temp.arg.nontype]/5, bullet 1
5381
5382      For a non-type template-parameter of integral or enumeration type,
5383      integral promotions (_conv.prom_) and integral conversions
5384      (_conv.integral_) are applied.  */
5385   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5386     {
5387       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5388       t = maybe_constant_value (t);
5389       if (t != error_mark_node)
5390         expr = t;
5391
5392       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5393         return error_mark_node;
5394
5395       /* Notice that there are constant expressions like '4 % 0' which
5396          do not fold into integer constants.  */
5397       if (TREE_CODE (expr) != INTEGER_CST)
5398         {
5399           if (complain & tf_error)
5400             {
5401               int errs = errorcount, warns = warningcount;
5402               expr = cxx_constant_value (expr);
5403               if (errorcount > errs || warningcount > warns)
5404                 inform (EXPR_LOC_OR_HERE (expr),
5405                         "in template argument for type %qT ", type);
5406               if (expr == error_mark_node)
5407                 return NULL_TREE;
5408               /* else cxx_constant_value complained but gave us
5409                  a real constant, so go ahead.  */
5410               gcc_assert (TREE_CODE (expr) == INTEGER_CST);
5411             }
5412           else
5413             return NULL_TREE;
5414         }
5415     }
5416   /* [temp.arg.nontype]/5, bullet 2
5417
5418      For a non-type template-parameter of type pointer to object,
5419      qualification conversions (_conv.qual_) and the array-to-pointer
5420      conversion (_conv.array_) are applied.  */
5421   else if (TYPE_PTROBV_P (type))
5422     {
5423       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5424
5425          A template-argument for a non-type, non-template template-parameter
5426          shall be one of: [...]
5427
5428          -- the name of a non-type template-parameter;
5429          -- the address of an object or function with external linkage, [...]
5430             expressed as "& id-expression" where the & is optional if the name
5431             refers to a function or array, or if the corresponding
5432             template-parameter is a reference.
5433
5434         Here, we do not care about functions, as they are invalid anyway
5435         for a parameter of type pointer-to-object.  */
5436
5437       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5438         /* Non-type template parameters are OK.  */
5439         ;
5440       else if (TREE_CODE (expr) != ADDR_EXPR
5441                && TREE_CODE (expr_type) != ARRAY_TYPE)
5442         {
5443           if (TREE_CODE (expr) == VAR_DECL)
5444             {
5445               error ("%qD is not a valid template argument "
5446                      "because %qD is a variable, not the address of "
5447                      "a variable",
5448                      expr, expr);
5449               return NULL_TREE;
5450             }
5451           /* Other values, like integer constants, might be valid
5452              non-type arguments of some other type.  */
5453           return error_mark_node;
5454         }
5455       else
5456         {
5457           tree decl;
5458
5459           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5460                   ? TREE_OPERAND (expr, 0) : expr);
5461           if (TREE_CODE (decl) != VAR_DECL)
5462             {
5463               error ("%qE is not a valid template argument of type %qT "
5464                      "because %qE is not a variable",
5465                      expr, type, decl);
5466               return NULL_TREE;
5467             }
5468           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5469             {
5470               error ("%qE is not a valid template argument of type %qT "
5471                      "because %qD does not have external linkage",
5472                      expr, type, decl);
5473               return NULL_TREE;
5474             }
5475         }
5476
5477       expr = decay_conversion (expr);
5478       if (expr == error_mark_node)
5479         return error_mark_node;
5480
5481       expr = perform_qualification_conversions (type, expr);
5482       if (expr == error_mark_node)
5483         return error_mark_node;
5484     }
5485   /* [temp.arg.nontype]/5, bullet 3
5486
5487      For a non-type template-parameter of type reference to object, no
5488      conversions apply. The type referred to by the reference may be more
5489      cv-qualified than the (otherwise identical) type of the
5490      template-argument. The template-parameter is bound directly to the
5491      template-argument, which must be an lvalue.  */
5492   else if (TYPE_REF_OBJ_P (type))
5493     {
5494       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5495                                                       expr_type))
5496         return error_mark_node;
5497
5498       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5499         {
5500           error ("%qE is not a valid template argument for type %qT "
5501                  "because of conflicts in cv-qualification", expr, type);
5502           return NULL_TREE;
5503         }
5504
5505       if (!real_lvalue_p (expr))
5506         {
5507           error ("%qE is not a valid template argument for type %qT "
5508                  "because it is not an lvalue", expr, type);
5509           return NULL_TREE;
5510         }
5511
5512       /* [temp.arg.nontype]/1
5513
5514          A template-argument for a non-type, non-template template-parameter
5515          shall be one of: [...]
5516
5517          -- the address of an object or function with external linkage.  */
5518       if (TREE_CODE (expr) == INDIRECT_REF
5519           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5520         {
5521           expr = TREE_OPERAND (expr, 0);
5522           if (DECL_P (expr))
5523             {
5524               error ("%q#D is not a valid template argument for type %qT "
5525                      "because a reference variable does not have a constant "
5526                      "address", expr, type);
5527               return NULL_TREE;
5528             }
5529         }
5530
5531       if (!DECL_P (expr))
5532         {
5533           error ("%qE is not a valid template argument for type %qT "
5534                  "because it is not an object with external linkage",
5535                  expr, type);
5536           return NULL_TREE;
5537         }
5538
5539       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5540         {
5541           error ("%qE is not a valid template argument for type %qT "
5542                  "because object %qD has not external linkage",
5543                  expr, type, expr);
5544           return NULL_TREE;
5545         }
5546
5547       expr = build_nop (type, build_address (expr));
5548     }
5549   /* [temp.arg.nontype]/5, bullet 4
5550
5551      For a non-type template-parameter of type pointer to function, only
5552      the function-to-pointer conversion (_conv.func_) is applied. If the
5553      template-argument represents a set of overloaded functions (or a
5554      pointer to such), the matching function is selected from the set
5555      (_over.over_).  */
5556   else if (TYPE_PTRFN_P (type))
5557     {
5558       /* If the argument is a template-id, we might not have enough
5559          context information to decay the pointer.  */
5560       if (!type_unknown_p (expr_type))
5561         {
5562           expr = decay_conversion (expr);
5563           if (expr == error_mark_node)
5564             return error_mark_node;
5565         }
5566
5567       expr = convert_nontype_argument_function (type, expr);
5568       if (!expr || expr == error_mark_node)
5569         return expr;
5570
5571       if (TREE_CODE (expr) != ADDR_EXPR)
5572         {
5573           error ("%qE is not a valid template argument for type %qT", expr, type);
5574           error ("it must be the address of a function with external linkage");
5575           return NULL_TREE;
5576         }
5577     }
5578   /* [temp.arg.nontype]/5, bullet 5
5579
5580      For a non-type template-parameter of type reference to function, no
5581      conversions apply. If the template-argument represents a set of
5582      overloaded functions, the matching function is selected from the set
5583      (_over.over_).  */
5584   else if (TYPE_REFFN_P (type))
5585     {
5586       if (TREE_CODE (expr) == ADDR_EXPR)
5587         {
5588           error ("%qE is not a valid template argument for type %qT "
5589                  "because it is a pointer", expr, type);
5590           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5591           return NULL_TREE;
5592         }
5593
5594       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5595       if (!expr || expr == error_mark_node)
5596         return expr;
5597
5598       expr = build_nop (type, build_address (expr));
5599     }
5600   /* [temp.arg.nontype]/5, bullet 6
5601
5602      For a non-type template-parameter of type pointer to member function,
5603      no conversions apply. If the template-argument represents a set of
5604      overloaded member functions, the matching member function is selected
5605      from the set (_over.over_).  */
5606   else if (TYPE_PTRMEMFUNC_P (type))
5607     {
5608       expr = instantiate_type (type, expr, tf_none);
5609       if (expr == error_mark_node)
5610         return error_mark_node;
5611
5612       /* [temp.arg.nontype] bullet 1 says the pointer to member
5613          expression must be a pointer-to-member constant.  */
5614       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5615         return error_mark_node;
5616
5617       /* There is no way to disable standard conversions in
5618          resolve_address_of_overloaded_function (called by
5619          instantiate_type). It is possible that the call succeeded by
5620          converting &B::I to &D::I (where B is a base of D), so we need
5621          to reject this conversion here.
5622
5623          Actually, even if there was a way to disable standard conversions,
5624          it would still be better to reject them here so that we can
5625          provide a superior diagnostic.  */
5626       if (!same_type_p (TREE_TYPE (expr), type))
5627         {
5628           error ("%qE is not a valid template argument for type %qT "
5629                  "because it is of type %qT", expr, type,
5630                  TREE_TYPE (expr));
5631           /* If we are just one standard conversion off, explain.  */
5632           if (can_convert (type, TREE_TYPE (expr)))
5633             inform (input_location,
5634                     "standard conversions are not allowed in this context");
5635           return NULL_TREE;
5636         }
5637     }
5638   /* [temp.arg.nontype]/5, bullet 7
5639
5640      For a non-type template-parameter of type pointer to data member,
5641      qualification conversions (_conv.qual_) are applied.  */
5642   else if (TYPE_PTRMEM_P (type))
5643     {
5644       /* [temp.arg.nontype] bullet 1 says the pointer to member
5645          expression must be a pointer-to-member constant.  */
5646       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5647         return error_mark_node;
5648
5649       expr = perform_qualification_conversions (type, expr);
5650       if (expr == error_mark_node)
5651         return expr;
5652     }
5653   /* A template non-type parameter must be one of the above.  */
5654   else
5655     gcc_unreachable ();
5656
5657   /* Sanity check: did we actually convert the argument to the
5658      right type?  */
5659   gcc_assert (same_type_ignoring_top_level_qualifiers_p
5660               (type, TREE_TYPE (expr)));
5661   return expr;
5662 }
5663
5664 /* Subroutine of coerce_template_template_parms, which returns 1 if
5665    PARM_PARM and ARG_PARM match using the rule for the template
5666    parameters of template template parameters. Both PARM and ARG are
5667    template parameters; the rest of the arguments are the same as for
5668    coerce_template_template_parms.
5669  */
5670 static int
5671 coerce_template_template_parm (tree parm,
5672                               tree arg,
5673                               tsubst_flags_t complain,
5674                               tree in_decl,
5675                               tree outer_args)
5676 {
5677   if (arg == NULL_TREE || arg == error_mark_node
5678       || parm == NULL_TREE || parm == error_mark_node)
5679     return 0;
5680   
5681   if (TREE_CODE (arg) != TREE_CODE (parm))
5682     return 0;
5683   
5684   switch (TREE_CODE (parm))
5685     {
5686     case TEMPLATE_DECL:
5687       /* We encounter instantiations of templates like
5688          template <template <template <class> class> class TT>
5689          class C;  */
5690       {
5691         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5692         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5693         
5694         if (!coerce_template_template_parms
5695             (parmparm, argparm, complain, in_decl, outer_args))
5696           return 0;
5697       }
5698       /* Fall through.  */
5699       
5700     case TYPE_DECL:
5701       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5702           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5703         /* Argument is a parameter pack but parameter is not.  */
5704         return 0;
5705       break;
5706       
5707     case PARM_DECL:
5708       /* The tsubst call is used to handle cases such as
5709          
5710            template <int> class C {};
5711            template <class T, template <T> class TT> class D {};
5712            D<int, C> d;
5713
5714          i.e. the parameter list of TT depends on earlier parameters.  */
5715       if (!uses_template_parms (TREE_TYPE (arg))
5716           && !same_type_p
5717                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5718                  TREE_TYPE (arg)))
5719         return 0;
5720       
5721       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5722           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5723         /* Argument is a parameter pack but parameter is not.  */
5724         return 0;
5725       
5726       break;
5727
5728     default:
5729       gcc_unreachable ();
5730     }
5731
5732   return 1;
5733 }
5734
5735
5736 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5737    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5738    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5739    or PARM_DECL.
5740
5741    Consider the example:
5742      template <class T> class A;
5743      template<template <class U> class TT> class B;
5744
5745    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5746    the parameters to A, and OUTER_ARGS contains A.  */
5747
5748 static int
5749 coerce_template_template_parms (tree parm_parms,
5750                                 tree arg_parms,
5751                                 tsubst_flags_t complain,
5752                                 tree in_decl,
5753                                 tree outer_args)
5754 {
5755   int nparms, nargs, i;
5756   tree parm, arg;
5757   int variadic_p = 0;
5758
5759   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5760   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5761
5762   nparms = TREE_VEC_LENGTH (parm_parms);
5763   nargs = TREE_VEC_LENGTH (arg_parms);
5764
5765   /* Determine whether we have a parameter pack at the end of the
5766      template template parameter's template parameter list.  */
5767   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5768     {
5769       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5770       
5771       if (parm == error_mark_node)
5772         return 0;
5773
5774       switch (TREE_CODE (parm))
5775         {
5776         case TEMPLATE_DECL:
5777         case TYPE_DECL:
5778           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5779             variadic_p = 1;
5780           break;
5781           
5782         case PARM_DECL:
5783           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5784             variadic_p = 1;
5785           break;
5786           
5787         default:
5788           gcc_unreachable ();
5789         }
5790     }
5791  
5792   if (nargs != nparms
5793       && !(variadic_p && nargs >= nparms - 1))
5794     return 0;
5795
5796   /* Check all of the template parameters except the parameter pack at
5797      the end (if any).  */
5798   for (i = 0; i < nparms - variadic_p; ++i)
5799     {
5800       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5801           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5802         continue;
5803
5804       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5805       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5806
5807       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5808                                           outer_args))
5809         return 0;
5810
5811     }
5812
5813   if (variadic_p)
5814     {
5815       /* Check each of the template parameters in the template
5816          argument against the template parameter pack at the end of
5817          the template template parameter.  */
5818       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5819         return 0;
5820
5821       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5822
5823       for (; i < nargs; ++i)
5824         {
5825           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5826             continue;
5827  
5828           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5829  
5830           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5831                                               outer_args))
5832             return 0;
5833         }
5834     }
5835
5836   return 1;
5837 }
5838
5839 /* Verifies that the deduced template arguments (in TARGS) for the
5840    template template parameters (in TPARMS) represent valid bindings,
5841    by comparing the template parameter list of each template argument
5842    to the template parameter list of its corresponding template
5843    template parameter, in accordance with DR150. This
5844    routine can only be called after all template arguments have been
5845    deduced. It will return TRUE if all of the template template
5846    parameter bindings are okay, FALSE otherwise.  */
5847 bool 
5848 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5849 {
5850   int i, ntparms = TREE_VEC_LENGTH (tparms);
5851   bool ret = true;
5852
5853   /* We're dealing with template parms in this process.  */
5854   ++processing_template_decl;
5855
5856   targs = INNERMOST_TEMPLATE_ARGS (targs);
5857
5858   for (i = 0; i < ntparms; ++i)
5859     {
5860       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5861       tree targ = TREE_VEC_ELT (targs, i);
5862
5863       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5864         {
5865           tree packed_args = NULL_TREE;
5866           int idx, len = 1;
5867
5868           if (ARGUMENT_PACK_P (targ))
5869             {
5870               /* Look inside the argument pack.  */
5871               packed_args = ARGUMENT_PACK_ARGS (targ);
5872               len = TREE_VEC_LENGTH (packed_args);
5873             }
5874
5875           for (idx = 0; idx < len; ++idx)
5876             {
5877               tree targ_parms = NULL_TREE;
5878
5879               if (packed_args)
5880                 /* Extract the next argument from the argument
5881                    pack.  */
5882                 targ = TREE_VEC_ELT (packed_args, idx);
5883
5884               if (PACK_EXPANSION_P (targ))
5885                 /* Look at the pattern of the pack expansion.  */
5886                 targ = PACK_EXPANSION_PATTERN (targ);
5887
5888               /* Extract the template parameters from the template
5889                  argument.  */
5890               if (TREE_CODE (targ) == TEMPLATE_DECL)
5891                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5892               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5893                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5894
5895               /* Verify that we can coerce the template template
5896                  parameters from the template argument to the template
5897                  parameter.  This requires an exact match.  */
5898               if (targ_parms
5899                   && !coerce_template_template_parms
5900                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5901                         targ_parms,
5902                         tf_none,
5903                         tparm,
5904                         targs))
5905                 {
5906                   ret = false;
5907                   goto out;
5908                 }
5909             }
5910         }
5911     }
5912
5913  out:
5914
5915   --processing_template_decl;
5916   return ret;
5917 }
5918
5919 /* Convert the indicated template ARG as necessary to match the
5920    indicated template PARM.  Returns the converted ARG, or
5921    error_mark_node if the conversion was unsuccessful.  Error and
5922    warning messages are issued under control of COMPLAIN.  This
5923    conversion is for the Ith parameter in the parameter list.  ARGS is
5924    the full set of template arguments deduced so far.  */
5925
5926 static tree
5927 convert_template_argument (tree parm,
5928                            tree arg,
5929                            tree args,
5930                            tsubst_flags_t complain,
5931                            int i,
5932                            tree in_decl)
5933 {
5934   tree orig_arg;
5935   tree val;
5936   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5937
5938   if (TREE_CODE (arg) == TREE_LIST
5939       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5940     {
5941       /* The template argument was the name of some
5942          member function.  That's usually
5943          invalid, but static members are OK.  In any
5944          case, grab the underlying fields/functions
5945          and issue an error later if required.  */
5946       orig_arg = TREE_VALUE (arg);
5947       TREE_TYPE (arg) = unknown_type_node;
5948     }
5949
5950   orig_arg = arg;
5951
5952   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5953   requires_type = (TREE_CODE (parm) == TYPE_DECL
5954                    || requires_tmpl_type);
5955
5956   /* When determining whether an argument pack expansion is a template,
5957      look at the pattern.  */
5958   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5959     arg = PACK_EXPANSION_PATTERN (arg);
5960
5961   /* Deal with an injected-class-name used as a template template arg.  */
5962   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5963     {
5964       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5965       if (TREE_CODE (t) == TEMPLATE_DECL)
5966         {
5967           if (cxx_dialect >= cxx0x)
5968             /* OK under DR 1004.  */;
5969           else if (complain & tf_warning_or_error)
5970             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5971                      " used as template template argument", TYPE_NAME (arg));
5972           else if (flag_pedantic_errors)
5973             t = arg;
5974
5975           arg = t;
5976         }
5977     }
5978
5979   is_tmpl_type = 
5980     ((TREE_CODE (arg) == TEMPLATE_DECL
5981       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5982      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5983      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5984
5985   if (is_tmpl_type
5986       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5987           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5988     arg = TYPE_STUB_DECL (arg);
5989
5990   is_type = TYPE_P (arg) || is_tmpl_type;
5991
5992   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5993       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5994     {
5995       permerror (input_location, "to refer to a type member of a template parameter, "
5996                  "use %<typename %E%>", orig_arg);
5997
5998       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5999                                      TREE_OPERAND (arg, 1),
6000                                      typename_type,
6001                                      complain & tf_error);
6002       arg = orig_arg;
6003       is_type = 1;
6004     }
6005   if (is_type != requires_type)
6006     {
6007       if (in_decl)
6008         {
6009           if (complain & tf_error)
6010             {
6011               error ("type/value mismatch at argument %d in template "
6012                      "parameter list for %qD",
6013                      i + 1, in_decl);
6014               if (is_type)
6015                 error ("  expected a constant of type %qT, got %qT",
6016                        TREE_TYPE (parm),
6017                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6018               else if (requires_tmpl_type)
6019                 error ("  expected a class template, got %qE", orig_arg);
6020               else
6021                 error ("  expected a type, got %qE", orig_arg);
6022             }
6023         }
6024       return error_mark_node;
6025     }
6026   if (is_tmpl_type ^ requires_tmpl_type)
6027     {
6028       if (in_decl && (complain & tf_error))
6029         {
6030           error ("type/value mismatch at argument %d in template "
6031                  "parameter list for %qD",
6032                  i + 1, in_decl);
6033           if (is_tmpl_type)
6034             error ("  expected a type, got %qT", DECL_NAME (arg));
6035           else
6036             error ("  expected a class template, got %qT", orig_arg);
6037         }
6038       return error_mark_node;
6039     }
6040
6041   if (is_type)
6042     {
6043       if (requires_tmpl_type)
6044         {
6045           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6046             /* The number of argument required is not known yet.
6047                Just accept it for now.  */
6048             val = TREE_TYPE (arg);
6049           else
6050             {
6051               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6052               tree argparm;
6053
6054               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6055
6056               if (coerce_template_template_parms (parmparm, argparm,
6057                                                   complain, in_decl,
6058                                                   args))
6059                 {
6060                   val = arg;
6061
6062                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
6063                      TEMPLATE_DECL.  */
6064                   if (val != error_mark_node)
6065                     {
6066                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6067                         val = TREE_TYPE (val);
6068                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6069                         val = make_pack_expansion (val);
6070                     }
6071                 }
6072               else
6073                 {
6074                   if (in_decl && (complain & tf_error))
6075                     {
6076                       error ("type/value mismatch at argument %d in "
6077                              "template parameter list for %qD",
6078                              i + 1, in_decl);
6079                       error ("  expected a template of type %qD, got %qT",
6080                              parm, orig_arg);
6081                     }
6082
6083                   val = error_mark_node;
6084                 }
6085             }
6086         }
6087       else
6088         val = orig_arg;
6089       /* We only form one instance of each template specialization.
6090          Therefore, if we use a non-canonical variant (i.e., a
6091          typedef), any future messages referring to the type will use
6092          the typedef, which is confusing if those future uses do not
6093          themselves also use the typedef.  */
6094       if (TYPE_P (val))
6095         val = strip_typedefs (val);
6096     }
6097   else
6098     {
6099       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6100
6101       if (invalid_nontype_parm_type_p (t, complain))
6102         return error_mark_node;
6103
6104       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6105         {
6106           if (same_type_p (t, TREE_TYPE (orig_arg)))
6107             val = orig_arg;
6108           else
6109             {
6110               /* Not sure if this is reachable, but it doesn't hurt
6111                  to be robust.  */
6112               error ("type mismatch in nontype parameter pack");
6113               val = error_mark_node;
6114             }
6115         }
6116       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
6117         /* We used to call digest_init here.  However, digest_init
6118            will report errors, which we don't want when complain
6119            is zero.  More importantly, digest_init will try too
6120            hard to convert things: for example, `0' should not be
6121            converted to pointer type at this point according to
6122            the standard.  Accepting this is not merely an
6123            extension, since deciding whether or not these
6124            conversions can occur is part of determining which
6125            function template to call, or whether a given explicit
6126            argument specification is valid.  */
6127         val = convert_nontype_argument (t, orig_arg, complain);
6128       else
6129         val = orig_arg;
6130
6131       if (val == NULL_TREE)
6132         val = error_mark_node;
6133       else if (val == error_mark_node && (complain & tf_error))
6134         error ("could not convert template argument %qE to %qT",  orig_arg, t);
6135
6136       if (TREE_CODE (val) == SCOPE_REF)
6137         {
6138           /* Strip typedefs from the SCOPE_REF.  */
6139           tree type = strip_typedefs (TREE_TYPE (val));
6140           tree scope = strip_typedefs (TREE_OPERAND (val, 0));
6141           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6142                                       QUALIFIED_NAME_IS_TEMPLATE (val));
6143         }
6144     }
6145
6146   return val;
6147 }
6148
6149 /* Coerces the remaining template arguments in INNER_ARGS (from
6150    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6151    Returns the coerced argument pack. PARM_IDX is the position of this
6152    parameter in the template parameter list. ARGS is the original
6153    template argument list.  */
6154 static tree
6155 coerce_template_parameter_pack (tree parms,
6156                                 int parm_idx,
6157                                 tree args,
6158                                 tree inner_args,
6159                                 int arg_idx,
6160                                 tree new_args,
6161                                 int* lost,
6162                                 tree in_decl,
6163                                 tsubst_flags_t complain)
6164 {
6165   tree parm = TREE_VEC_ELT (parms, parm_idx);
6166   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6167   tree packed_args;
6168   tree argument_pack;
6169   tree packed_types = NULL_TREE;
6170
6171   if (arg_idx > nargs)
6172     arg_idx = nargs;
6173
6174   packed_args = make_tree_vec (nargs - arg_idx);
6175
6176   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
6177       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
6178     {
6179       /* When the template parameter is a non-type template
6180          parameter pack whose type uses parameter packs, we need
6181          to look at each of the template arguments
6182          separately. Build a vector of the types for these
6183          non-type template parameters in PACKED_TYPES.  */
6184       tree expansion 
6185         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
6186       packed_types = tsubst_pack_expansion (expansion, args,
6187                                             complain, in_decl);
6188
6189       if (packed_types == error_mark_node)
6190         return error_mark_node;
6191
6192       /* Check that we have the right number of arguments.  */
6193       if (arg_idx < nargs
6194           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
6195           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
6196         {
6197           int needed_parms 
6198             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
6199           error ("wrong number of template arguments (%d, should be %d)",
6200                  nargs, needed_parms);
6201           return error_mark_node;
6202         }
6203
6204       /* If we aren't able to check the actual arguments now
6205          (because they haven't been expanded yet), we can at least
6206          verify that all of the types used for the non-type
6207          template parameter pack are, in fact, valid for non-type
6208          template parameters.  */
6209       if (arg_idx < nargs 
6210           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6211         {
6212           int j, len = TREE_VEC_LENGTH (packed_types);
6213           for (j = 0; j < len; ++j)
6214             {
6215               tree t = TREE_VEC_ELT (packed_types, j);
6216               if (invalid_nontype_parm_type_p (t, complain))
6217                 return error_mark_node;
6218             }
6219         }
6220     }
6221
6222   /* Convert the remaining arguments, which will be a part of the
6223      parameter pack "parm".  */
6224   for (; arg_idx < nargs; ++arg_idx)
6225     {
6226       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6227       tree actual_parm = TREE_VALUE (parm);
6228
6229       if (packed_types && !PACK_EXPANSION_P (arg))
6230         {
6231           /* When we have a vector of types (corresponding to the
6232              non-type template parameter pack that uses parameter
6233              packs in its type, as mention above), and the
6234              argument is not an expansion (which expands to a
6235              currently unknown number of arguments), clone the
6236              parm and give it the next type in PACKED_TYPES.  */
6237           actual_parm = copy_node (actual_parm);
6238           TREE_TYPE (actual_parm) = 
6239             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
6240         }
6241
6242       if (arg != error_mark_node)
6243         arg = convert_template_argument (actual_parm, 
6244                                          arg, new_args, complain, parm_idx,
6245                                          in_decl);
6246       if (arg == error_mark_node)
6247         (*lost)++;
6248       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
6249     }
6250
6251   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6252       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6253     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6254   else
6255     {
6256       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6257       TREE_TYPE (argument_pack) 
6258         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6259       TREE_CONSTANT (argument_pack) = 1;
6260     }
6261
6262   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6263 #ifdef ENABLE_CHECKING
6264   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6265                                        TREE_VEC_LENGTH (packed_args));
6266 #endif
6267   return argument_pack;
6268 }
6269
6270 /* Convert all template arguments to their appropriate types, and
6271    return a vector containing the innermost resulting template
6272    arguments.  If any error occurs, return error_mark_node. Error and
6273    warning messages are issued under control of COMPLAIN.
6274
6275    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6276    for arguments not specified in ARGS.  Otherwise, if
6277    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6278    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6279    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6280    ARGS.  */
6281
6282 static tree
6283 coerce_template_parms (tree parms,
6284                        tree args,
6285                        tree in_decl,
6286                        tsubst_flags_t complain,
6287                        bool require_all_args,
6288                        bool use_default_args)
6289 {
6290   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6291   tree inner_args;
6292   tree new_args;
6293   tree new_inner_args;
6294   int saved_unevaluated_operand;
6295   int saved_inhibit_evaluation_warnings;
6296
6297   /* When used as a boolean value, indicates whether this is a
6298      variadic template parameter list. Since it's an int, we can also
6299      subtract it from nparms to get the number of non-variadic
6300      parameters.  */
6301   int variadic_p = 0;
6302
6303   if (args == error_mark_node)
6304     return error_mark_node;
6305
6306   nparms = TREE_VEC_LENGTH (parms);
6307
6308   /* Determine if there are any parameter packs.  */
6309   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
6310     {
6311       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
6312       if (template_parameter_pack_p (tparm))
6313         ++variadic_p;
6314     }
6315
6316   inner_args = INNERMOST_TEMPLATE_ARGS (args);
6317   /* If there are 0 or 1 parameter packs, we need to expand any argument
6318      packs so that we can deduce a parameter pack from some non-packed args
6319      followed by an argument pack, as in variadic85.C.  If there are more
6320      than that, we need to leave argument packs intact so the arguments are
6321      assigned to the right parameter packs.  This should only happen when
6322      dealing with a nested class inside a partial specialization of a class
6323      template, as in variadic92.C.  */
6324   if (variadic_p <= 1)
6325     inner_args = expand_template_argument_pack (inner_args);
6326
6327   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6328   if ((nargs > nparms && !variadic_p)
6329       || (nargs < nparms - variadic_p
6330           && require_all_args
6331           && (!use_default_args
6332               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6333                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6334     {
6335       if (complain & tf_error)
6336         {
6337           if (variadic_p)
6338             {
6339               --nparms;
6340               error ("wrong number of template arguments "
6341                      "(%d, should be %d or more)", nargs, nparms);
6342             }
6343           else
6344              error ("wrong number of template arguments "
6345                     "(%d, should be %d)", nargs, nparms);
6346
6347           if (in_decl)
6348             error ("provided for %q+D", in_decl);
6349         }
6350
6351       return error_mark_node;
6352     }
6353
6354   /* We need to evaluate the template arguments, even though this
6355      template-id may be nested within a "sizeof".  */
6356   saved_unevaluated_operand = cp_unevaluated_operand;
6357   cp_unevaluated_operand = 0;
6358   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6359   c_inhibit_evaluation_warnings = 0;
6360   new_inner_args = make_tree_vec (nparms);
6361   new_args = add_outermost_template_args (args, new_inner_args);
6362   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6363     {
6364       tree arg;
6365       tree parm;
6366
6367       /* Get the Ith template parameter.  */
6368       parm = TREE_VEC_ELT (parms, parm_idx);
6369  
6370       if (parm == error_mark_node)
6371       {
6372         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6373         continue;
6374       }
6375
6376       /* Calculate the next argument.  */
6377       if (arg_idx < nargs)
6378         arg = TREE_VEC_ELT (inner_args, arg_idx);
6379       else
6380         arg = NULL_TREE;
6381
6382       if (template_parameter_pack_p (TREE_VALUE (parm))
6383           && !(arg && ARGUMENT_PACK_P (arg)))
6384         {
6385           /* All remaining arguments will be placed in the
6386              template parameter pack PARM.  */
6387           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6388                                                 inner_args, arg_idx,
6389                                                 new_args, &lost,
6390                                                 in_decl, complain);
6391
6392           /* Store this argument.  */
6393           if (arg == error_mark_node)
6394             lost++;
6395           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6396
6397           /* We are done with all of the arguments.  */
6398           arg_idx = nargs;
6399           
6400           continue;
6401         }
6402       else if (arg)
6403         {
6404           if (PACK_EXPANSION_P (arg))
6405             {
6406               if (complain & tf_error)
6407                 {
6408                   /* FIXME this restriction was removed by N2555; see
6409                      bug 35722.  */
6410                   /* If ARG is a pack expansion, but PARM is not a
6411                      template parameter pack (if it were, we would have
6412                      handled it above), we're trying to expand into a
6413                      fixed-length argument list.  */
6414                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
6415                     sorry ("cannot expand %<%E%> into a fixed-length "
6416                            "argument list", arg);
6417                   else
6418                     sorry ("cannot expand %<%T%> into a fixed-length "
6419                            "argument list", arg);
6420                 }
6421               ++lost;
6422             }
6423         }
6424       else if (require_all_args)
6425         {
6426           /* There must be a default arg in this case.  */
6427           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6428                                      complain, in_decl);
6429           /* The position of the first default template argument,
6430              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6431              Record that.  */
6432           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6433             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6434         }
6435       else
6436         break;
6437
6438       if (arg == error_mark_node)
6439         {
6440           if (complain & tf_error)
6441             error ("template argument %d is invalid", arg_idx + 1);
6442         }
6443       else if (!arg)
6444         /* This only occurs if there was an error in the template
6445            parameter list itself (which we would already have
6446            reported) that we are trying to recover from, e.g., a class
6447            template with a parameter list such as
6448            template<typename..., typename>.  */
6449         ++lost;
6450       else
6451         arg = convert_template_argument (TREE_VALUE (parm),
6452                                          arg, new_args, complain, 
6453                                          parm_idx, in_decl);
6454
6455       if (arg == error_mark_node)
6456         lost++;
6457       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6458     }
6459   cp_unevaluated_operand = saved_unevaluated_operand;
6460   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6461
6462   if (lost)
6463     return error_mark_node;
6464
6465 #ifdef ENABLE_CHECKING
6466   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6467     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6468                                          TREE_VEC_LENGTH (new_inner_args));
6469 #endif
6470
6471   return new_inner_args;
6472 }
6473
6474 /* Returns 1 if template args OT and NT are equivalent.  */
6475
6476 static int
6477 template_args_equal (tree ot, tree nt)
6478 {
6479   if (nt == ot)
6480     return 1;
6481   if (nt == NULL_TREE || ot == NULL_TREE)
6482     return false;
6483
6484   if (TREE_CODE (nt) == TREE_VEC)
6485     /* For member templates */
6486     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6487   else if (PACK_EXPANSION_P (ot))
6488     return PACK_EXPANSION_P (nt) 
6489       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6490                               PACK_EXPANSION_PATTERN (nt));
6491   else if (ARGUMENT_PACK_P (ot))
6492     {
6493       int i, len;
6494       tree opack, npack;
6495
6496       if (!ARGUMENT_PACK_P (nt))
6497         return 0;
6498
6499       opack = ARGUMENT_PACK_ARGS (ot);
6500       npack = ARGUMENT_PACK_ARGS (nt);
6501       len = TREE_VEC_LENGTH (opack);
6502       if (TREE_VEC_LENGTH (npack) != len)
6503         return 0;
6504       for (i = 0; i < len; ++i)
6505         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6506                                   TREE_VEC_ELT (npack, i)))
6507           return 0;
6508       return 1;
6509     }
6510   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6511     {
6512       /* We get here probably because we are in the middle of substituting
6513          into the pattern of a pack expansion. In that case the
6514          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6515          interested in. So we want to use the initial pack argument for
6516          the comparison.  */
6517       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6518       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6519         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6520       return template_args_equal (ot, nt);
6521     }
6522   else if (TYPE_P (nt))
6523     return TYPE_P (ot) && same_type_p (ot, nt);
6524   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6525     return 0;
6526   else
6527     return cp_tree_equal (ot, nt);
6528 }
6529
6530 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6531    of template arguments.  Returns 0 otherwise.  */
6532
6533 int
6534 comp_template_args (tree oldargs, tree newargs)
6535 {
6536   int i;
6537
6538   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6539     return 0;
6540
6541   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6542     {
6543       tree nt = TREE_VEC_ELT (newargs, i);
6544       tree ot = TREE_VEC_ELT (oldargs, i);
6545
6546       if (! template_args_equal (ot, nt))
6547         return 0;
6548     }
6549   return 1;
6550 }
6551
6552 static void
6553 add_pending_template (tree d)
6554 {
6555   tree ti = (TYPE_P (d)
6556              ? CLASSTYPE_TEMPLATE_INFO (d)
6557              : DECL_TEMPLATE_INFO (d));
6558   struct pending_template *pt;
6559   int level;
6560
6561   if (TI_PENDING_TEMPLATE_FLAG (ti))
6562     return;
6563
6564   /* We are called both from instantiate_decl, where we've already had a
6565      tinst_level pushed, and instantiate_template, where we haven't.
6566      Compensate.  */
6567   level = !current_tinst_level || current_tinst_level->decl != d;
6568
6569   if (level)
6570     push_tinst_level (d);
6571
6572   pt = ggc_alloc_pending_template ();
6573   pt->next = NULL;
6574   pt->tinst = current_tinst_level;
6575   if (last_pending_template)
6576     last_pending_template->next = pt;
6577   else
6578     pending_templates = pt;
6579
6580   last_pending_template = pt;
6581
6582   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6583
6584   if (level)
6585     pop_tinst_level ();
6586 }
6587
6588
6589 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6590    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6591    documentation for TEMPLATE_ID_EXPR.  */
6592
6593 tree
6594 lookup_template_function (tree fns, tree arglist)
6595 {
6596   tree type;
6597
6598   if (fns == error_mark_node || arglist == error_mark_node)
6599     return error_mark_node;
6600
6601   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6602   gcc_assert (fns && (is_overloaded_fn (fns)
6603                       || TREE_CODE (fns) == IDENTIFIER_NODE));
6604
6605   if (BASELINK_P (fns))
6606     {
6607       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6608                                          unknown_type_node,
6609                                          BASELINK_FUNCTIONS (fns),
6610                                          arglist);
6611       return fns;
6612     }
6613
6614   type = TREE_TYPE (fns);
6615   if (TREE_CODE (fns) == OVERLOAD || !type)
6616     type = unknown_type_node;
6617
6618   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6619 }
6620
6621 /* Within the scope of a template class S<T>, the name S gets bound
6622    (in build_self_reference) to a TYPE_DECL for the class, not a
6623    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6624    or one of its enclosing classes, and that type is a template,
6625    return the associated TEMPLATE_DECL.  Otherwise, the original
6626    DECL is returned.
6627
6628    Also handle the case when DECL is a TREE_LIST of ambiguous
6629    injected-class-names from different bases.  */
6630
6631 tree
6632 maybe_get_template_decl_from_type_decl (tree decl)
6633 {
6634   if (decl == NULL_TREE)
6635     return decl;
6636
6637   /* DR 176: A lookup that finds an injected-class-name (10.2
6638      [class.member.lookup]) can result in an ambiguity in certain cases
6639      (for example, if it is found in more than one base class). If all of
6640      the injected-class-names that are found refer to specializations of
6641      the same class template, and if the name is followed by a
6642      template-argument-list, the reference refers to the class template
6643      itself and not a specialization thereof, and is not ambiguous.  */
6644   if (TREE_CODE (decl) == TREE_LIST)
6645     {
6646       tree t, tmpl = NULL_TREE;
6647       for (t = decl; t; t = TREE_CHAIN (t))
6648         {
6649           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6650           if (!tmpl)
6651             tmpl = elt;
6652           else if (tmpl != elt)
6653             break;
6654         }
6655       if (tmpl && t == NULL_TREE)
6656         return tmpl;
6657       else
6658         return decl;
6659     }
6660
6661   return (decl != NULL_TREE
6662           && DECL_SELF_REFERENCE_P (decl)
6663           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6664     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6665 }
6666
6667 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6668    parameters, find the desired type.
6669
6670    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6671
6672    IN_DECL, if non-NULL, is the template declaration we are trying to
6673    instantiate.
6674
6675    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6676    the class we are looking up.
6677
6678    Issue error and warning messages under control of COMPLAIN.
6679
6680    If the template class is really a local class in a template
6681    function, then the FUNCTION_CONTEXT is the function in which it is
6682    being instantiated.
6683
6684    ??? Note that this function is currently called *twice* for each
6685    template-id: the first time from the parser, while creating the
6686    incomplete type (finish_template_type), and the second type during the
6687    real instantiation (instantiate_template_class). This is surely something
6688    that we want to avoid. It also causes some problems with argument
6689    coercion (see convert_nontype_argument for more information on this).  */
6690
6691 static tree
6692 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
6693                          int entering_scope, tsubst_flags_t complain)
6694 {
6695   tree templ = NULL_TREE, parmlist;
6696   tree t;
6697   spec_entry **slot;
6698   spec_entry *entry;
6699   spec_entry elt;
6700   hashval_t hash;
6701
6702   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6703     {
6704       tree value = innermost_non_namespace_value (d1);
6705       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6706         templ = value;
6707       else
6708         {
6709           if (context)
6710             push_decl_namespace (context);
6711           templ = lookup_name (d1);
6712           templ = maybe_get_template_decl_from_type_decl (templ);
6713           if (context)
6714             pop_decl_namespace ();
6715         }
6716       if (templ)
6717         context = DECL_CONTEXT (templ);
6718     }
6719   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6720     {
6721       tree type = TREE_TYPE (d1);
6722
6723       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6724          an implicit typename for the second A.  Deal with it.  */
6725       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6726         type = TREE_TYPE (type);
6727
6728       if (CLASSTYPE_TEMPLATE_INFO (type))
6729         {
6730           templ = CLASSTYPE_TI_TEMPLATE (type);
6731           d1 = DECL_NAME (templ);
6732         }
6733     }
6734   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6735            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6736     {
6737       templ = TYPE_TI_TEMPLATE (d1);
6738       d1 = DECL_NAME (templ);
6739     }
6740   else if (TREE_CODE (d1) == TEMPLATE_DECL
6741            && DECL_TEMPLATE_RESULT (d1)
6742            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6743     {
6744       templ = d1;
6745       d1 = DECL_NAME (templ);
6746       context = DECL_CONTEXT (templ);
6747     }
6748
6749   /* Issue an error message if we didn't find a template.  */
6750   if (! templ)
6751     {
6752       if (complain & tf_error)
6753         error ("%qT is not a template", d1);
6754       return error_mark_node;
6755     }
6756
6757   if (TREE_CODE (templ) != TEMPLATE_DECL
6758          /* Make sure it's a user visible template, if it was named by
6759             the user.  */
6760       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6761           && !PRIMARY_TEMPLATE_P (templ)))
6762     {
6763       if (complain & tf_error)
6764         {
6765           error ("non-template type %qT used as a template", d1);
6766           if (in_decl)
6767             error ("for template declaration %q+D", in_decl);
6768         }
6769       return error_mark_node;
6770     }
6771
6772   complain &= ~tf_user;
6773
6774   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6775     {
6776       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6777          template arguments */
6778
6779       tree parm;
6780       tree arglist2;
6781       tree outer;
6782
6783       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6784
6785       /* Consider an example where a template template parameter declared as
6786
6787            template <class T, class U = std::allocator<T> > class TT
6788
6789          The template parameter level of T and U are one level larger than
6790          of TT.  To proper process the default argument of U, say when an
6791          instantiation `TT<int>' is seen, we need to build the full
6792          arguments containing {int} as the innermost level.  Outer levels,
6793          available when not appearing as default template argument, can be
6794          obtained from the arguments of the enclosing template.
6795
6796          Suppose that TT is later substituted with std::vector.  The above
6797          instantiation is `TT<int, std::allocator<T> >' with TT at
6798          level 1, and T at level 2, while the template arguments at level 1
6799          becomes {std::vector} and the inner level 2 is {int}.  */
6800
6801       outer = DECL_CONTEXT (templ);
6802       if (outer)
6803         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6804       else if (current_template_parms)
6805         /* This is an argument of the current template, so we haven't set
6806            DECL_CONTEXT yet.  */
6807         outer = current_template_args ();
6808
6809       if (outer)
6810         arglist = add_to_template_args (outer, arglist);
6811
6812       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6813                                         complain,
6814                                         /*require_all_args=*/true,
6815                                         /*use_default_args=*/true);
6816       if (arglist2 == error_mark_node
6817           || (!uses_template_parms (arglist2)
6818               && check_instantiated_args (templ, arglist2, complain)))
6819         return error_mark_node;
6820
6821       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6822       return parm;
6823     }
6824   else
6825     {
6826       tree template_type = TREE_TYPE (templ);
6827       tree gen_tmpl;
6828       tree type_decl;
6829       tree found = NULL_TREE;
6830       int arg_depth;
6831       int parm_depth;
6832       int is_dependent_type;
6833       int use_partial_inst_tmpl = false;
6834
6835       gen_tmpl = most_general_template (templ);
6836       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6837       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6838       arg_depth = TMPL_ARGS_DEPTH (arglist);
6839
6840       if (arg_depth == 1 && parm_depth > 1)
6841         {
6842           /* We've been given an incomplete set of template arguments.
6843              For example, given:
6844
6845                template <class T> struct S1 {
6846                  template <class U> struct S2 {};
6847                  template <class U> struct S2<U*> {};
6848                 };
6849
6850              we will be called with an ARGLIST of `U*', but the
6851              TEMPLATE will be `template <class T> template
6852              <class U> struct S1<T>::S2'.  We must fill in the missing
6853              arguments.  */
6854           arglist
6855             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6856                                            arglist);
6857           arg_depth = TMPL_ARGS_DEPTH (arglist);
6858         }
6859
6860       /* Now we should have enough arguments.  */
6861       gcc_assert (parm_depth == arg_depth);
6862
6863       /* From here on, we're only interested in the most general
6864          template.  */
6865
6866       /* Calculate the BOUND_ARGS.  These will be the args that are
6867          actually tsubst'd into the definition to create the
6868          instantiation.  */
6869       if (parm_depth > 1)
6870         {
6871           /* We have multiple levels of arguments to coerce, at once.  */
6872           int i;
6873           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6874
6875           tree bound_args = make_tree_vec (parm_depth);
6876
6877           for (i = saved_depth,
6878                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6879                i > 0 && t != NULL_TREE;
6880                --i, t = TREE_CHAIN (t))
6881             {
6882               tree a;
6883               if (i == saved_depth)
6884                 a = coerce_template_parms (TREE_VALUE (t),
6885                                            arglist, gen_tmpl,
6886                                            complain,
6887                                            /*require_all_args=*/true,
6888                                            /*use_default_args=*/true);
6889               else
6890                 /* Outer levels should have already been coerced.  */
6891                 a = TMPL_ARGS_LEVEL (arglist, i);
6892
6893               /* Don't process further if one of the levels fails.  */
6894               if (a == error_mark_node)
6895                 {
6896                   /* Restore the ARGLIST to its full size.  */
6897                   TREE_VEC_LENGTH (arglist) = saved_depth;
6898                   return error_mark_node;
6899                 }
6900
6901               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6902
6903               /* We temporarily reduce the length of the ARGLIST so
6904                  that coerce_template_parms will see only the arguments
6905                  corresponding to the template parameters it is
6906                  examining.  */
6907               TREE_VEC_LENGTH (arglist)--;
6908             }
6909
6910           /* Restore the ARGLIST to its full size.  */
6911           TREE_VEC_LENGTH (arglist) = saved_depth;
6912
6913           arglist = bound_args;
6914         }
6915       else
6916         arglist
6917           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6918                                    INNERMOST_TEMPLATE_ARGS (arglist),
6919                                    gen_tmpl,
6920                                    complain,
6921                                    /*require_all_args=*/true,
6922                                    /*use_default_args=*/true);
6923
6924       if (arglist == error_mark_node)
6925         /* We were unable to bind the arguments.  */
6926         return error_mark_node;
6927
6928       /* In the scope of a template class, explicit references to the
6929          template class refer to the type of the template, not any
6930          instantiation of it.  For example, in:
6931
6932            template <class T> class C { void f(C<T>); }
6933
6934          the `C<T>' is just the same as `C'.  Outside of the
6935          class, however, such a reference is an instantiation.  */
6936       if ((entering_scope
6937            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6938            || currently_open_class (template_type))
6939           /* comp_template_args is expensive, check it last.  */
6940           && comp_template_args (TYPE_TI_ARGS (template_type),
6941                                  arglist))
6942         return template_type;
6943
6944       /* If we already have this specialization, return it.  */
6945       elt.tmpl = gen_tmpl;
6946       elt.args = arglist;
6947       hash = hash_specialization (&elt);
6948       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6949                                                   &elt, hash);
6950
6951       if (entry)
6952         return entry->spec;
6953
6954       is_dependent_type = uses_template_parms (arglist);
6955
6956       /* If the deduced arguments are invalid, then the binding
6957          failed.  */
6958       if (!is_dependent_type
6959           && check_instantiated_args (gen_tmpl,
6960                                       INNERMOST_TEMPLATE_ARGS (arglist),
6961                                       complain))
6962         return error_mark_node;
6963
6964       if (!is_dependent_type
6965           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6966           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6967           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6968         {
6969           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6970                                       DECL_NAME (gen_tmpl),
6971                                       /*tag_scope=*/ts_global);
6972           return found;
6973         }
6974
6975       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6976                         complain, in_decl);
6977       if (!context)
6978         context = global_namespace;
6979
6980       /* Create the type.  */
6981       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6982         {
6983           if (!is_dependent_type)
6984             {
6985               set_current_access_from_decl (TYPE_NAME (template_type));
6986               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
6987                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6988                                       arglist, complain, in_decl),
6989                               SCOPED_ENUM_P (template_type), NULL);
6990             }
6991           else
6992             {
6993               /* We don't want to call start_enum for this type, since
6994                  the values for the enumeration constants may involve
6995                  template parameters.  And, no one should be interested
6996                  in the enumeration constants for such a type.  */
6997               t = cxx_make_type (ENUMERAL_TYPE);
6998               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6999             }
7000           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
7001           ENUM_FIXED_UNDERLYING_TYPE_P (t)
7002             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
7003         }
7004       else
7005         {
7006           t = make_class_type (TREE_CODE (template_type));
7007           CLASSTYPE_DECLARED_CLASS (t)
7008             = CLASSTYPE_DECLARED_CLASS (template_type);
7009           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7010           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7011
7012           /* A local class.  Make sure the decl gets registered properly.  */
7013           if (context == current_function_decl)
7014             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
7015
7016           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7017             /* This instantiation is another name for the primary
7018                template type. Set the TYPE_CANONICAL field
7019                appropriately. */
7020             TYPE_CANONICAL (t) = template_type;
7021           else if (any_template_arguments_need_structural_equality_p (arglist))
7022             /* Some of the template arguments require structural
7023                equality testing, so this template class requires
7024                structural equality testing. */
7025             SET_TYPE_STRUCTURAL_EQUALITY (t);
7026         }
7027
7028       /* If we called start_enum or pushtag above, this information
7029          will already be set up.  */
7030       if (!TYPE_NAME (t))
7031         {
7032           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7033
7034           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7035           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7036           DECL_SOURCE_LOCATION (type_decl)
7037             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7038         }
7039       else
7040         type_decl = TYPE_NAME (t);
7041
7042       TREE_PRIVATE (type_decl)
7043         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
7044       TREE_PROTECTED (type_decl)
7045         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
7046       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7047         {
7048           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7049           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7050         }
7051
7052       /* Let's consider the explicit specialization of a member
7053          of a class template specialization that is implicitely instantiated,
7054          e.g.:
7055              template<class T>
7056              struct S
7057              {
7058                template<class U> struct M {}; //#0
7059              };
7060
7061              template<>
7062              template<>
7063              struct S<int>::M<char> //#1
7064              {
7065                int i;
7066              };
7067         [temp.expl.spec]/4 says this is valid.
7068
7069         In this case, when we write:
7070         S<int>::M<char> m;
7071
7072         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
7073         the one of #0.
7074
7075         When we encounter #1, we want to store the partial instantiation
7076         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
7077
7078         For all cases other than this "explicit specialization of member of a
7079         class template", we just want to store the most general template into
7080         the CLASSTYPE_TI_TEMPLATE of M.
7081
7082         This case of "explicit specialization of member of a class template"
7083         only happens when:
7084         1/ the enclosing class is an instantiation of, and therefore not
7085         the same as, the context of the most general template, and
7086         2/ we aren't looking at the partial instantiation itself, i.e.
7087         the innermost arguments are not the same as the innermost parms of
7088         the most general template.
7089
7090         So it's only when 1/ and 2/ happens that we want to use the partial
7091         instantiation of the member template in lieu of its most general
7092         template.  */
7093
7094       if (PRIMARY_TEMPLATE_P (gen_tmpl)
7095           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
7096           /* the enclosing class must be an instantiation...  */
7097           && CLASS_TYPE_P (context)
7098           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
7099         {
7100           tree partial_inst_args;
7101           TREE_VEC_LENGTH (arglist)--;
7102           ++processing_template_decl;
7103           partial_inst_args =
7104             tsubst (INNERMOST_TEMPLATE_ARGS
7105                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
7106                     arglist, complain, NULL_TREE);
7107           --processing_template_decl;
7108           TREE_VEC_LENGTH (arglist)++;
7109           use_partial_inst_tmpl =
7110             /*...and we must not be looking at the partial instantiation
7111              itself. */
7112             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
7113                                  partial_inst_args);
7114         }
7115
7116       if (!use_partial_inst_tmpl)
7117         /* This case is easy; there are no member templates involved.  */
7118         found = gen_tmpl;
7119       else
7120         {
7121           /* This is a full instantiation of a member template.  Find
7122              the partial instantiation of which this is an instance.  */
7123
7124           /* Temporarily reduce by one the number of levels in the ARGLIST
7125              so as to avoid comparing the last set of arguments.  */
7126           TREE_VEC_LENGTH (arglist)--;
7127           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
7128           TREE_VEC_LENGTH (arglist)++;
7129           found = CLASSTYPE_TI_TEMPLATE (found);
7130         }
7131
7132       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
7133
7134       elt.spec = t;
7135       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
7136                                                        &elt, hash, INSERT);
7137       *slot = ggc_alloc_spec_entry ();
7138       **slot = elt;
7139
7140       /* Note this use of the partial instantiation so we can check it
7141          later in maybe_process_partial_specialization.  */
7142       DECL_TEMPLATE_INSTANTIATIONS (templ)
7143         = tree_cons (arglist, t,
7144                      DECL_TEMPLATE_INSTANTIATIONS (templ));
7145
7146       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
7147         /* Now that the type has been registered on the instantiations
7148            list, we set up the enumerators.  Because the enumeration
7149            constants may involve the enumeration type itself, we make
7150            sure to register the type first, and then create the
7151            constants.  That way, doing tsubst_expr for the enumeration
7152            constants won't result in recursive calls here; we'll find
7153            the instantiation and exit above.  */
7154         tsubst_enum (template_type, t, arglist);
7155
7156       if (is_dependent_type)
7157         /* If the type makes use of template parameters, the
7158            code that generates debugging information will crash.  */
7159         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
7160
7161       /* Possibly limit visibility based on template args.  */
7162       TREE_PUBLIC (type_decl) = 1;
7163       determine_visibility (type_decl);
7164
7165       return t;
7166     }
7167 }
7168
7169 /* Wrapper for lookup_template_class_1.  */
7170
7171 tree
7172 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
7173                        int entering_scope, tsubst_flags_t complain)
7174 {
7175   tree ret;
7176   timevar_push (TV_TEMPLATE_INST);
7177   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
7178                                  entering_scope, complain);
7179   timevar_pop (TV_TEMPLATE_INST);
7180   return ret;
7181 }
7182 \f
7183 struct pair_fn_data
7184 {
7185   tree_fn_t fn;
7186   void *data;
7187   /* True when we should also visit template parameters that occur in
7188      non-deduced contexts.  */
7189   bool include_nondeduced_p;
7190   struct pointer_set_t *visited;
7191 };
7192
7193 /* Called from for_each_template_parm via walk_tree.  */
7194
7195 static tree
7196 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
7197 {
7198   tree t = *tp;
7199   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
7200   tree_fn_t fn = pfd->fn;
7201   void *data = pfd->data;
7202
7203   if (TYPE_P (t)
7204       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
7205       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
7206                                  pfd->include_nondeduced_p))
7207     return error_mark_node;
7208
7209   switch (TREE_CODE (t))
7210     {
7211     case RECORD_TYPE:
7212       if (TYPE_PTRMEMFUNC_P (t))
7213         break;
7214       /* Fall through.  */
7215
7216     case UNION_TYPE:
7217     case ENUMERAL_TYPE:
7218       if (!TYPE_TEMPLATE_INFO (t))
7219         *walk_subtrees = 0;
7220       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
7221                                        fn, data, pfd->visited, 
7222                                        pfd->include_nondeduced_p))
7223         return error_mark_node;
7224       break;
7225
7226     case INTEGER_TYPE:
7227       if (for_each_template_parm (TYPE_MIN_VALUE (t),
7228                                   fn, data, pfd->visited, 
7229                                   pfd->include_nondeduced_p)
7230           || for_each_template_parm (TYPE_MAX_VALUE (t),
7231                                      fn, data, pfd->visited,
7232                                      pfd->include_nondeduced_p))
7233         return error_mark_node;
7234       break;
7235
7236     case METHOD_TYPE:
7237       /* Since we're not going to walk subtrees, we have to do this
7238          explicitly here.  */
7239       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
7240                                   pfd->visited, pfd->include_nondeduced_p))
7241         return error_mark_node;
7242       /* Fall through.  */
7243
7244     case FUNCTION_TYPE:
7245       /* Check the return type.  */
7246       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7247                                   pfd->include_nondeduced_p))
7248         return error_mark_node;
7249
7250       /* Check the parameter types.  Since default arguments are not
7251          instantiated until they are needed, the TYPE_ARG_TYPES may
7252          contain expressions that involve template parameters.  But,
7253          no-one should be looking at them yet.  And, once they're
7254          instantiated, they don't contain template parameters, so
7255          there's no point in looking at them then, either.  */
7256       {
7257         tree parm;
7258
7259         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
7260           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
7261                                       pfd->visited, pfd->include_nondeduced_p))
7262             return error_mark_node;
7263
7264         /* Since we've already handled the TYPE_ARG_TYPES, we don't
7265            want walk_tree walking into them itself.  */
7266         *walk_subtrees = 0;
7267       }
7268       break;
7269
7270     case TYPEOF_TYPE:
7271     case UNDERLYING_TYPE:
7272       if (pfd->include_nondeduced_p
7273           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
7274                                      pfd->visited, 
7275                                      pfd->include_nondeduced_p))
7276         return error_mark_node;
7277       break;
7278
7279     case FUNCTION_DECL:
7280     case VAR_DECL:
7281       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
7282           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
7283                                      pfd->visited, pfd->include_nondeduced_p))
7284         return error_mark_node;
7285       /* Fall through.  */
7286
7287     case PARM_DECL:
7288     case CONST_DECL:
7289       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
7290           && for_each_template_parm (DECL_INITIAL (t), fn, data,
7291                                      pfd->visited, pfd->include_nondeduced_p))
7292         return error_mark_node;
7293       if (DECL_CONTEXT (t)
7294           && pfd->include_nondeduced_p
7295           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
7296                                      pfd->visited, pfd->include_nondeduced_p))
7297         return error_mark_node;
7298       break;
7299
7300     case BOUND_TEMPLATE_TEMPLATE_PARM:
7301       /* Record template parameters such as `T' inside `TT<T>'.  */
7302       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
7303                                   pfd->include_nondeduced_p))
7304         return error_mark_node;
7305       /* Fall through.  */
7306
7307     case TEMPLATE_TEMPLATE_PARM:
7308     case TEMPLATE_TYPE_PARM:
7309     case TEMPLATE_PARM_INDEX:
7310       if (fn && (*fn)(t, data))
7311         return error_mark_node;
7312       else if (!fn)
7313         return error_mark_node;
7314       break;
7315
7316     case TEMPLATE_DECL:
7317       /* A template template parameter is encountered.  */
7318       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
7319           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7320                                      pfd->include_nondeduced_p))
7321         return error_mark_node;
7322
7323       /* Already substituted template template parameter */
7324       *walk_subtrees = 0;
7325       break;
7326
7327     case TYPENAME_TYPE:
7328       if (!fn
7329           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
7330                                      data, pfd->visited, 
7331                                      pfd->include_nondeduced_p))
7332         return error_mark_node;
7333       break;
7334
7335     case CONSTRUCTOR:
7336       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
7337           && pfd->include_nondeduced_p
7338           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
7339                                      (TREE_TYPE (t)), fn, data,
7340                                      pfd->visited, pfd->include_nondeduced_p))
7341         return error_mark_node;
7342       break;
7343
7344     case INDIRECT_REF:
7345     case COMPONENT_REF:
7346       /* If there's no type, then this thing must be some expression
7347          involving template parameters.  */
7348       if (!fn && !TREE_TYPE (t))
7349         return error_mark_node;
7350       break;
7351
7352     case MODOP_EXPR:
7353     case CAST_EXPR:
7354     case REINTERPRET_CAST_EXPR:
7355     case CONST_CAST_EXPR:
7356     case STATIC_CAST_EXPR:
7357     case DYNAMIC_CAST_EXPR:
7358     case ARROW_EXPR:
7359     case DOTSTAR_EXPR:
7360     case TYPEID_EXPR:
7361     case PSEUDO_DTOR_EXPR:
7362       if (!fn)
7363         return error_mark_node;
7364       break;
7365
7366     default:
7367       break;
7368     }
7369
7370   /* We didn't find any template parameters we liked.  */
7371   return NULL_TREE;
7372 }
7373
7374 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7375    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7376    call FN with the parameter and the DATA.
7377    If FN returns nonzero, the iteration is terminated, and
7378    for_each_template_parm returns 1.  Otherwise, the iteration
7379    continues.  If FN never returns a nonzero value, the value
7380    returned by for_each_template_parm is 0.  If FN is NULL, it is
7381    considered to be the function which always returns 1.
7382
7383    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7384    parameters that occur in non-deduced contexts.  When false, only
7385    visits those template parameters that can be deduced.  */
7386
7387 static int
7388 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7389                         struct pointer_set_t *visited,
7390                         bool include_nondeduced_p)
7391 {
7392   struct pair_fn_data pfd;
7393   int result;
7394
7395   /* Set up.  */
7396   pfd.fn = fn;
7397   pfd.data = data;
7398   pfd.include_nondeduced_p = include_nondeduced_p;
7399
7400   /* Walk the tree.  (Conceptually, we would like to walk without
7401      duplicates, but for_each_template_parm_r recursively calls
7402      for_each_template_parm, so we would need to reorganize a fair
7403      bit to use walk_tree_without_duplicates, so we keep our own
7404      visited list.)  */
7405   if (visited)
7406     pfd.visited = visited;
7407   else
7408     pfd.visited = pointer_set_create ();
7409   result = cp_walk_tree (&t,
7410                          for_each_template_parm_r,
7411                          &pfd,
7412                          pfd.visited) != NULL_TREE;
7413
7414   /* Clean up.  */
7415   if (!visited)
7416     {
7417       pointer_set_destroy (pfd.visited);
7418       pfd.visited = 0;
7419     }
7420
7421   return result;
7422 }
7423
7424 /* Returns true if T depends on any template parameter.  */
7425
7426 int
7427 uses_template_parms (tree t)
7428 {
7429   bool dependent_p;
7430   int saved_processing_template_decl;
7431
7432   saved_processing_template_decl = processing_template_decl;
7433   if (!saved_processing_template_decl)
7434     processing_template_decl = 1;
7435   if (TYPE_P (t))
7436     dependent_p = dependent_type_p (t);
7437   else if (TREE_CODE (t) == TREE_VEC)
7438     dependent_p = any_dependent_template_arguments_p (t);
7439   else if (TREE_CODE (t) == TREE_LIST)
7440     dependent_p = (uses_template_parms (TREE_VALUE (t))
7441                    || uses_template_parms (TREE_CHAIN (t)));
7442   else if (TREE_CODE (t) == TYPE_DECL)
7443     dependent_p = dependent_type_p (TREE_TYPE (t));
7444   else if (DECL_P (t)
7445            || EXPR_P (t)
7446            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7447            || TREE_CODE (t) == OVERLOAD
7448            || TREE_CODE (t) == BASELINK
7449            || TREE_CODE (t) == IDENTIFIER_NODE
7450            || TREE_CODE (t) == TRAIT_EXPR
7451            || TREE_CODE (t) == CONSTRUCTOR
7452            || CONSTANT_CLASS_P (t))
7453     dependent_p = (type_dependent_expression_p (t)
7454                    || value_dependent_expression_p (t));
7455   else
7456     {
7457       gcc_assert (t == error_mark_node);
7458       dependent_p = false;
7459     }
7460
7461   processing_template_decl = saved_processing_template_decl;
7462
7463   return dependent_p;
7464 }
7465
7466 /* Returns true if T depends on any template parameter with level LEVEL.  */
7467
7468 int
7469 uses_template_parms_level (tree t, int level)
7470 {
7471   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7472                                  /*include_nondeduced_p=*/true);
7473 }
7474
7475 static int tinst_depth;
7476 extern int max_tinst_depth;
7477 #ifdef GATHER_STATISTICS
7478 int depth_reached;
7479 #endif
7480 static int tinst_level_tick;
7481 static int last_template_error_tick;
7482
7483 /* We're starting to instantiate D; record the template instantiation context
7484    for diagnostics and to restore it later.  */
7485
7486 int
7487 push_tinst_level (tree d)
7488 {
7489   struct tinst_level *new_level;
7490
7491   if (tinst_depth >= max_tinst_depth)
7492     {
7493       last_template_error_tick = tinst_level_tick;
7494       if (TREE_CODE (d) == TREE_LIST)
7495         error ("template instantiation depth exceeds maximum of %d (use "
7496                "-ftemplate-depth= to increase the maximum) substituting %qS",
7497                max_tinst_depth, d);
7498       else
7499         error ("template instantiation depth exceeds maximum of %d (use "
7500                "-ftemplate-depth= to increase the maximum) instantiating %qD",
7501                max_tinst_depth, d);
7502
7503       print_instantiation_context ();
7504
7505       return 0;
7506     }
7507
7508   new_level = ggc_alloc_tinst_level ();
7509   new_level->decl = d;
7510   new_level->locus = input_location;
7511   new_level->in_system_header_p = in_system_header;
7512   new_level->next = current_tinst_level;
7513   current_tinst_level = new_level;
7514
7515   ++tinst_depth;
7516 #ifdef GATHER_STATISTICS
7517   if (tinst_depth > depth_reached)
7518     depth_reached = tinst_depth;
7519 #endif
7520
7521   ++tinst_level_tick;
7522   return 1;
7523 }
7524
7525 /* We're done instantiating this template; return to the instantiation
7526    context.  */
7527
7528 void
7529 pop_tinst_level (void)
7530 {
7531   /* Restore the filename and line number stashed away when we started
7532      this instantiation.  */
7533   input_location = current_tinst_level->locus;
7534   current_tinst_level = current_tinst_level->next;
7535   --tinst_depth;
7536   ++tinst_level_tick;
7537 }
7538
7539 /* We're instantiating a deferred template; restore the template
7540    instantiation context in which the instantiation was requested, which
7541    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7542
7543 static tree
7544 reopen_tinst_level (struct tinst_level *level)
7545 {
7546   struct tinst_level *t;
7547
7548   tinst_depth = 0;
7549   for (t = level; t; t = t->next)
7550     ++tinst_depth;
7551
7552   current_tinst_level = level;
7553   pop_tinst_level ();
7554   return level->decl;
7555 }
7556
7557 /* Returns the TINST_LEVEL which gives the original instantiation
7558    context.  */
7559
7560 struct tinst_level *
7561 outermost_tinst_level (void)
7562 {
7563   struct tinst_level *level = current_tinst_level;
7564   if (level)
7565     while (level->next)
7566       level = level->next;
7567   return level;
7568 }
7569
7570 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7571
7572 bool
7573 parameter_of_template_p (tree parm, tree templ)
7574 {
7575   tree parms;
7576   int i;
7577
7578   if (!parm || !templ)
7579     return false;
7580
7581   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7582   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7583
7584   parms = DECL_TEMPLATE_PARMS (templ);
7585   parms = INNERMOST_TEMPLATE_PARMS (parms);
7586
7587   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7588     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7589       return true;
7590
7591   return false;
7592 }
7593
7594 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7595    vector of template arguments, as for tsubst.
7596
7597    Returns an appropriate tsubst'd friend declaration.  */
7598
7599 static tree
7600 tsubst_friend_function (tree decl, tree args)
7601 {
7602   tree new_friend;
7603
7604   if (TREE_CODE (decl) == FUNCTION_DECL
7605       && DECL_TEMPLATE_INSTANTIATION (decl)
7606       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7607     /* This was a friend declared with an explicit template
7608        argument list, e.g.:
7609
7610        friend void f<>(T);
7611
7612        to indicate that f was a template instantiation, not a new
7613        function declaration.  Now, we have to figure out what
7614        instantiation of what template.  */
7615     {
7616       tree template_id, arglist, fns;
7617       tree new_args;
7618       tree tmpl;
7619       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7620
7621       /* Friend functions are looked up in the containing namespace scope.
7622          We must enter that scope, to avoid finding member functions of the
7623          current class with same name.  */
7624       push_nested_namespace (ns);
7625       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7626                          tf_warning_or_error, NULL_TREE,
7627                          /*integral_constant_expression_p=*/false);
7628       pop_nested_namespace (ns);
7629       arglist = tsubst (DECL_TI_ARGS (decl), args,
7630                         tf_warning_or_error, NULL_TREE);
7631       template_id = lookup_template_function (fns, arglist);
7632
7633       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7634       tmpl = determine_specialization (template_id, new_friend,
7635                                        &new_args,
7636                                        /*need_member_template=*/0,
7637                                        TREE_VEC_LENGTH (args),
7638                                        tsk_none);
7639       return instantiate_template (tmpl, new_args, tf_error);
7640     }
7641
7642   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7643
7644   /* The NEW_FRIEND will look like an instantiation, to the
7645      compiler, but is not an instantiation from the point of view of
7646      the language.  For example, we might have had:
7647
7648      template <class T> struct S {
7649        template <class U> friend void f(T, U);
7650      };
7651
7652      Then, in S<int>, template <class U> void f(int, U) is not an
7653      instantiation of anything.  */
7654   if (new_friend == error_mark_node)
7655     return error_mark_node;
7656
7657   DECL_USE_TEMPLATE (new_friend) = 0;
7658   if (TREE_CODE (decl) == TEMPLATE_DECL)
7659     {
7660       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7661       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7662         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7663     }
7664
7665   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7666      is not a template instantiation and should not be mangled like
7667      one.  Therefore, we forget the mangling here; we'll recompute it
7668      later if we need it.  */
7669   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7670     {
7671       SET_DECL_RTL (new_friend, NULL);
7672       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7673     }
7674
7675   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7676     {
7677       tree old_decl;
7678       tree new_friend_template_info;
7679       tree new_friend_result_template_info;
7680       tree ns;
7681       int  new_friend_is_defn;
7682
7683       /* We must save some information from NEW_FRIEND before calling
7684          duplicate decls since that function will free NEW_FRIEND if
7685          possible.  */
7686       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7687       new_friend_is_defn =
7688             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7689                            (template_for_substitution (new_friend)))
7690              != NULL_TREE);
7691       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7692         {
7693           /* This declaration is a `primary' template.  */
7694           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7695
7696           new_friend_result_template_info
7697             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7698         }
7699       else
7700         new_friend_result_template_info = NULL_TREE;
7701
7702       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7703       if (new_friend_is_defn)
7704         DECL_INITIAL (new_friend) = error_mark_node;
7705
7706       /* Inside pushdecl_namespace_level, we will push into the
7707          current namespace. However, the friend function should go
7708          into the namespace of the template.  */
7709       ns = decl_namespace_context (new_friend);
7710       push_nested_namespace (ns);
7711       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7712       pop_nested_namespace (ns);
7713
7714       if (old_decl == error_mark_node)
7715         return error_mark_node;
7716
7717       if (old_decl != new_friend)
7718         {
7719           /* This new friend declaration matched an existing
7720              declaration.  For example, given:
7721
7722                template <class T> void f(T);
7723                template <class U> class C {
7724                  template <class T> friend void f(T) {}
7725                };
7726
7727              the friend declaration actually provides the definition
7728              of `f', once C has been instantiated for some type.  So,
7729              old_decl will be the out-of-class template declaration,
7730              while new_friend is the in-class definition.
7731
7732              But, if `f' was called before this point, the
7733              instantiation of `f' will have DECL_TI_ARGS corresponding
7734              to `T' but not to `U', references to which might appear
7735              in the definition of `f'.  Previously, the most general
7736              template for an instantiation of `f' was the out-of-class
7737              version; now it is the in-class version.  Therefore, we
7738              run through all specialization of `f', adding to their
7739              DECL_TI_ARGS appropriately.  In particular, they need a
7740              new set of outer arguments, corresponding to the
7741              arguments for this class instantiation.
7742
7743              The same situation can arise with something like this:
7744
7745                friend void f(int);
7746                template <class T> class C {
7747                  friend void f(T) {}
7748                };
7749
7750              when `C<int>' is instantiated.  Now, `f(int)' is defined
7751              in the class.  */
7752
7753           if (!new_friend_is_defn)
7754             /* On the other hand, if the in-class declaration does
7755                *not* provide a definition, then we don't want to alter
7756                existing definitions.  We can just leave everything
7757                alone.  */
7758             ;
7759           else
7760             {
7761               tree new_template = TI_TEMPLATE (new_friend_template_info);
7762               tree new_args = TI_ARGS (new_friend_template_info);
7763
7764               /* Overwrite whatever template info was there before, if
7765                  any, with the new template information pertaining to
7766                  the declaration.  */
7767               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7768
7769               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7770                 {
7771                   /* We should have called reregister_specialization in
7772                      duplicate_decls.  */
7773                   gcc_assert (retrieve_specialization (new_template,
7774                                                        new_args, 0)
7775                               == old_decl);
7776
7777                   /* Instantiate it if the global has already been used.  */
7778                   if (DECL_ODR_USED (old_decl))
7779                     instantiate_decl (old_decl, /*defer_ok=*/true,
7780                                       /*expl_inst_class_mem_p=*/false);
7781                 }
7782               else
7783                 {
7784                   tree t;
7785
7786                   /* Indicate that the old function template is a partial
7787                      instantiation.  */
7788                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7789                     = new_friend_result_template_info;
7790
7791                   gcc_assert (new_template
7792                               == most_general_template (new_template));
7793                   gcc_assert (new_template != old_decl);
7794
7795                   /* Reassign any specializations already in the hash table
7796                      to the new more general template, and add the
7797                      additional template args.  */
7798                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7799                        t != NULL_TREE;
7800                        t = TREE_CHAIN (t))
7801                     {
7802                       tree spec = TREE_VALUE (t);
7803                       spec_entry elt;
7804
7805                       elt.tmpl = old_decl;
7806                       elt.args = DECL_TI_ARGS (spec);
7807                       elt.spec = NULL_TREE;
7808
7809                       htab_remove_elt (decl_specializations, &elt);
7810
7811                       DECL_TI_ARGS (spec)
7812                         = add_outermost_template_args (new_args,
7813                                                        DECL_TI_ARGS (spec));
7814
7815                       register_specialization
7816                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7817
7818                     }
7819                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7820                 }
7821             }
7822
7823           /* The information from NEW_FRIEND has been merged into OLD_DECL
7824              by duplicate_decls.  */
7825           new_friend = old_decl;
7826         }
7827     }
7828   else
7829     {
7830       tree context = DECL_CONTEXT (new_friend);
7831       bool dependent_p;
7832
7833       /* In the code
7834            template <class T> class C {
7835              template <class U> friend void C1<U>::f (); // case 1
7836              friend void C2<T>::f ();                    // case 2
7837            };
7838          we only need to make sure CONTEXT is a complete type for
7839          case 2.  To distinguish between the two cases, we note that
7840          CONTEXT of case 1 remains dependent type after tsubst while
7841          this isn't true for case 2.  */
7842       ++processing_template_decl;
7843       dependent_p = dependent_type_p (context);
7844       --processing_template_decl;
7845
7846       if (!dependent_p
7847           && !complete_type_or_else (context, NULL_TREE))
7848         return error_mark_node;
7849
7850       if (COMPLETE_TYPE_P (context))
7851         {
7852           /* Check to see that the declaration is really present, and,
7853              possibly obtain an improved declaration.  */
7854           tree fn = check_classfn (context,
7855                                    new_friend, NULL_TREE);
7856
7857           if (fn)
7858             new_friend = fn;
7859         }
7860     }
7861
7862   return new_friend;
7863 }
7864
7865 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7866    template arguments, as for tsubst.
7867
7868    Returns an appropriate tsubst'd friend type or error_mark_node on
7869    failure.  */
7870
7871 static tree
7872 tsubst_friend_class (tree friend_tmpl, tree args)
7873 {
7874   tree friend_type;
7875   tree tmpl;
7876   tree context;
7877
7878   context = CP_DECL_CONTEXT (friend_tmpl);
7879
7880   if (context != global_namespace)
7881     {
7882       if (TREE_CODE (context) == NAMESPACE_DECL)
7883         push_nested_namespace (context);
7884       else
7885         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7886     }
7887
7888   /* Look for a class template declaration.  We look for hidden names
7889      because two friend declarations of the same template are the
7890      same.  For example, in:
7891
7892        struct A { 
7893          template <typename> friend class F;
7894        };
7895        template <typename> struct B { 
7896          template <typename> friend class F;
7897        };
7898
7899      both F templates are the same.  */
7900   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7901                            /*block_p=*/true, 0, 
7902                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7903
7904   /* But, if we don't find one, it might be because we're in a
7905      situation like this:
7906
7907        template <class T>
7908        struct S {
7909          template <class U>
7910          friend struct S;
7911        };
7912
7913      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7914      for `S<int>', not the TEMPLATE_DECL.  */
7915   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7916     {
7917       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7918       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7919     }
7920
7921   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7922     {
7923       /* The friend template has already been declared.  Just
7924          check to see that the declarations match, and install any new
7925          default parameters.  We must tsubst the default parameters,
7926          of course.  We only need the innermost template parameters
7927          because that is all that redeclare_class_template will look
7928          at.  */
7929       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7930           > TMPL_ARGS_DEPTH (args))
7931         {
7932           tree parms;
7933           location_t saved_input_location;
7934           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7935                                          args, tf_warning_or_error);
7936
7937           saved_input_location = input_location;
7938           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7939           redeclare_class_template (TREE_TYPE (tmpl), parms);
7940           input_location = saved_input_location;
7941           
7942         }
7943
7944       friend_type = TREE_TYPE (tmpl);
7945     }
7946   else
7947     {
7948       /* The friend template has not already been declared.  In this
7949          case, the instantiation of the template class will cause the
7950          injection of this template into the global scope.  */
7951       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7952       if (tmpl == error_mark_node)
7953         return error_mark_node;
7954
7955       /* The new TMPL is not an instantiation of anything, so we
7956          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7957          the new type because that is supposed to be the corresponding
7958          template decl, i.e., TMPL.  */
7959       DECL_USE_TEMPLATE (tmpl) = 0;
7960       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7961       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7962       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7963         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7964
7965       /* Inject this template into the global scope.  */
7966       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7967     }
7968
7969   if (context != global_namespace)
7970     {
7971       if (TREE_CODE (context) == NAMESPACE_DECL)
7972         pop_nested_namespace (context);
7973       else
7974         pop_nested_class ();
7975     }
7976
7977   return friend_type;
7978 }
7979
7980 /* Returns zero if TYPE cannot be completed later due to circularity.
7981    Otherwise returns one.  */
7982
7983 static int
7984 can_complete_type_without_circularity (tree type)
7985 {
7986   if (type == NULL_TREE || type == error_mark_node)
7987     return 0;
7988   else if (COMPLETE_TYPE_P (type))
7989     return 1;
7990   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7991     return can_complete_type_without_circularity (TREE_TYPE (type));
7992   else if (CLASS_TYPE_P (type)
7993            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7994     return 0;
7995   else
7996     return 1;
7997 }
7998
7999 /* Apply any attributes which had to be deferred until instantiation
8000    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
8001    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
8002
8003 static void
8004 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
8005                                 tree args, tsubst_flags_t complain, tree in_decl)
8006 {
8007   tree last_dep = NULL_TREE;
8008   tree t;
8009   tree *p;
8010
8011   for (t = attributes; t; t = TREE_CHAIN (t))
8012     if (ATTR_IS_DEPENDENT (t))
8013       {
8014         last_dep = t;
8015         attributes = copy_list (attributes);
8016         break;
8017       }
8018
8019   if (DECL_P (*decl_p))
8020     {
8021       if (TREE_TYPE (*decl_p) == error_mark_node)
8022         return;
8023       p = &DECL_ATTRIBUTES (*decl_p);
8024     }
8025   else
8026     p = &TYPE_ATTRIBUTES (*decl_p);
8027
8028   if (last_dep)
8029     {
8030       tree late_attrs = NULL_TREE;
8031       tree *q = &late_attrs;
8032
8033       for (*p = attributes; *p; )
8034         {
8035           t = *p;
8036           if (ATTR_IS_DEPENDENT (t))
8037             {
8038               *p = TREE_CHAIN (t);
8039               TREE_CHAIN (t) = NULL_TREE;
8040               /* If the first attribute argument is an identifier, don't
8041                  pass it through tsubst.  Attributes like mode, format,
8042                  cleanup and several target specific attributes expect it
8043                  unmodified.  */
8044               if (TREE_VALUE (t)
8045                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
8046                   && TREE_VALUE (TREE_VALUE (t))
8047                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
8048                       == IDENTIFIER_NODE))
8049                 {
8050                   tree chain
8051                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
8052                                    in_decl,
8053                                    /*integral_constant_expression_p=*/false);
8054                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
8055                     TREE_VALUE (t)
8056                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
8057                                    chain);
8058                 }
8059               else
8060                 TREE_VALUE (t)
8061                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
8062                                  /*integral_constant_expression_p=*/false);
8063               *q = t;
8064               q = &TREE_CHAIN (t);
8065             }
8066           else
8067             p = &TREE_CHAIN (t);
8068         }
8069
8070       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
8071     }
8072 }
8073
8074 /* Perform (or defer) access check for typedefs that were referenced
8075    from within the template TMPL code.
8076    This is a subroutine of instantiate_template and instantiate_class_template.
8077    TMPL is the template to consider and TARGS is the list of arguments of
8078    that template.  */
8079
8080 static void
8081 perform_typedefs_access_check (tree tmpl, tree targs)
8082 {
8083   location_t saved_location;
8084   int i;
8085   qualified_typedef_usage_t *iter;
8086
8087   if (!tmpl
8088       || (!CLASS_TYPE_P (tmpl)
8089           && TREE_CODE (tmpl) != FUNCTION_DECL))
8090     return;
8091
8092   saved_location = input_location;
8093   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
8094                     get_types_needing_access_check (tmpl),
8095                     i, iter)
8096     {
8097       tree type_decl = iter->typedef_decl;
8098       tree type_scope = iter->context;
8099
8100       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
8101         continue;
8102
8103       if (uses_template_parms (type_decl))
8104         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
8105       if (uses_template_parms (type_scope))
8106         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
8107
8108       /* Make access check error messages point to the location
8109          of the use of the typedef.  */
8110       input_location = iter->locus;
8111       perform_or_defer_access_check (TYPE_BINFO (type_scope),
8112                                      type_decl, type_decl);
8113     }
8114     input_location = saved_location;
8115 }
8116
8117 static tree
8118 instantiate_class_template_1 (tree type)
8119 {
8120   tree templ, args, pattern, t, member;
8121   tree typedecl;
8122   tree pbinfo;
8123   tree base_list;
8124   unsigned int saved_maximum_field_alignment;
8125
8126   if (type == error_mark_node)
8127     return error_mark_node;
8128
8129   if (COMPLETE_OR_OPEN_TYPE_P (type)
8130       || uses_template_parms (type))
8131     return type;
8132
8133   /* Figure out which template is being instantiated.  */
8134   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
8135   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
8136
8137   /* Determine what specialization of the original template to
8138      instantiate.  */
8139   t = most_specialized_class (type, templ, tf_warning_or_error);
8140   if (t == error_mark_node)
8141     {
8142       TYPE_BEING_DEFINED (type) = 1;
8143       return error_mark_node;
8144     }
8145   else if (t)
8146     {
8147       /* This TYPE is actually an instantiation of a partial
8148          specialization.  We replace the innermost set of ARGS with
8149          the arguments appropriate for substitution.  For example,
8150          given:
8151
8152            template <class T> struct S {};
8153            template <class T> struct S<T*> {};
8154
8155          and supposing that we are instantiating S<int*>, ARGS will
8156          presently be {int*} -- but we need {int}.  */
8157       pattern = TREE_TYPE (t);
8158       args = TREE_PURPOSE (t);
8159     }
8160   else
8161     {
8162       pattern = TREE_TYPE (templ);
8163       args = CLASSTYPE_TI_ARGS (type);
8164     }
8165
8166   /* If the template we're instantiating is incomplete, then clearly
8167      there's nothing we can do.  */
8168   if (!COMPLETE_TYPE_P (pattern))
8169     return type;
8170
8171   /* If we've recursively instantiated too many templates, stop.  */
8172   if (! push_tinst_level (type))
8173     return type;
8174
8175   /* Now we're really doing the instantiation.  Mark the type as in
8176      the process of being defined.  */
8177   TYPE_BEING_DEFINED (type) = 1;
8178
8179   /* We may be in the middle of deferred access check.  Disable
8180      it now.  */
8181   push_deferring_access_checks (dk_no_deferred);
8182
8183   push_to_top_level ();
8184   /* Use #pragma pack from the template context.  */
8185   saved_maximum_field_alignment = maximum_field_alignment;
8186   maximum_field_alignment = TYPE_PRECISION (pattern);
8187
8188   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
8189
8190   /* Set the input location to the most specialized template definition.
8191      This is needed if tsubsting causes an error.  */
8192   typedecl = TYPE_MAIN_DECL (pattern);
8193   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
8194     DECL_SOURCE_LOCATION (typedecl);
8195
8196   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
8197   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
8198   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
8199   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
8200   TYPE_HAS_COPY_ASSIGN (type) = TYPE_HAS_COPY_ASSIGN (pattern);
8201   TYPE_HAS_CONST_COPY_ASSIGN (type) = TYPE_HAS_CONST_COPY_ASSIGN (pattern);
8202   TYPE_HAS_COPY_CTOR (type) = TYPE_HAS_COPY_CTOR (pattern);
8203   TYPE_HAS_CONST_COPY_CTOR (type) = TYPE_HAS_CONST_COPY_CTOR (pattern);
8204   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
8205   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
8206   TYPE_PACKED (type) = TYPE_PACKED (pattern);
8207   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
8208   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
8209   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
8210   if (ANON_AGGR_TYPE_P (pattern))
8211     SET_ANON_AGGR_TYPE_P (type);
8212   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
8213     {
8214       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
8215       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
8216     }
8217   CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
8218
8219   pbinfo = TYPE_BINFO (pattern);
8220
8221   /* We should never instantiate a nested class before its enclosing
8222      class; we need to look up the nested class by name before we can
8223      instantiate it, and that lookup should instantiate the enclosing
8224      class.  */
8225   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
8226               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
8227
8228   base_list = NULL_TREE;
8229   if (BINFO_N_BASE_BINFOS (pbinfo))
8230     {
8231       tree pbase_binfo;
8232       tree pushed_scope;
8233       int i;
8234
8235       /* We must enter the scope containing the type, as that is where
8236          the accessibility of types named in dependent bases are
8237          looked up from.  */
8238       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
8239
8240       /* Substitute into each of the bases to determine the actual
8241          basetypes.  */
8242       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
8243         {
8244           tree base;
8245           tree access = BINFO_BASE_ACCESS (pbinfo, i);
8246           tree expanded_bases = NULL_TREE;
8247           int idx, len = 1;
8248
8249           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
8250             {
8251               expanded_bases = 
8252                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
8253                                        args, tf_error, NULL_TREE);
8254               if (expanded_bases == error_mark_node)
8255                 continue;
8256
8257               len = TREE_VEC_LENGTH (expanded_bases);
8258             }
8259
8260           for (idx = 0; idx < len; idx++)
8261             {
8262               if (expanded_bases)
8263                 /* Extract the already-expanded base class.  */
8264                 base = TREE_VEC_ELT (expanded_bases, idx);
8265               else
8266                 /* Substitute to figure out the base class.  */
8267                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
8268                                NULL_TREE);
8269
8270               if (base == error_mark_node)
8271                 continue;
8272
8273               base_list = tree_cons (access, base, base_list);
8274               if (BINFO_VIRTUAL_P (pbase_binfo))
8275                 TREE_TYPE (base_list) = integer_type_node;
8276             }
8277         }
8278
8279       /* The list is now in reverse order; correct that.  */
8280       base_list = nreverse (base_list);
8281
8282       if (pushed_scope)
8283         pop_scope (pushed_scope);
8284     }
8285   /* Now call xref_basetypes to set up all the base-class
8286      information.  */
8287   xref_basetypes (type, base_list);
8288
8289   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
8290                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
8291                                   args, tf_error, NULL_TREE);
8292   fixup_attribute_variants (type);
8293
8294   /* Now that our base classes are set up, enter the scope of the
8295      class, so that name lookups into base classes, etc. will work
8296      correctly.  This is precisely analogous to what we do in
8297      begin_class_definition when defining an ordinary non-template
8298      class, except we also need to push the enclosing classes.  */
8299   push_nested_class (type);
8300
8301   /* Now members are processed in the order of declaration.  */
8302   for (member = CLASSTYPE_DECL_LIST (pattern);
8303        member; member = TREE_CHAIN (member))
8304     {
8305       tree t = TREE_VALUE (member);
8306
8307       if (TREE_PURPOSE (member))
8308         {
8309           if (TYPE_P (t))
8310             {
8311               /* Build new CLASSTYPE_NESTED_UTDS.  */
8312
8313               tree newtag;
8314               bool class_template_p;
8315
8316               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
8317                                   && TYPE_LANG_SPECIFIC (t)
8318                                   && CLASSTYPE_IS_TEMPLATE (t));
8319               /* If the member is a class template, then -- even after
8320                  substitution -- there may be dependent types in the
8321                  template argument list for the class.  We increment
8322                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
8323                  that function will assume that no types are dependent
8324                  when outside of a template.  */
8325               if (class_template_p)
8326                 ++processing_template_decl;
8327               newtag = tsubst (t, args, tf_error, NULL_TREE);
8328               if (class_template_p)
8329                 --processing_template_decl;
8330               if (newtag == error_mark_node)
8331                 continue;
8332
8333               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8334                 {
8335                   tree name = TYPE_IDENTIFIER (t);
8336
8337                   if (class_template_p)
8338                     /* Unfortunately, lookup_template_class sets
8339                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8340                        instantiation (i.e., for the type of a member
8341                        template class nested within a template class.)
8342                        This behavior is required for
8343                        maybe_process_partial_specialization to work
8344                        correctly, but is not accurate in this case;
8345                        the TAG is not an instantiation of anything.
8346                        (The corresponding TEMPLATE_DECL is an
8347                        instantiation, but the TYPE is not.) */
8348                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8349
8350                   /* Now, we call pushtag to put this NEWTAG into the scope of
8351                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8352                      pushtag calling push_template_decl.  We don't have to do
8353                      this for enums because it will already have been done in
8354                      tsubst_enum.  */
8355                   if (name)
8356                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8357                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8358                 }
8359             }
8360           else if (TREE_CODE (t) == FUNCTION_DECL
8361                    || DECL_FUNCTION_TEMPLATE_P (t))
8362             {
8363               /* Build new TYPE_METHODS.  */
8364               tree r;
8365
8366               if (TREE_CODE (t) == TEMPLATE_DECL)
8367                 ++processing_template_decl;
8368               r = tsubst (t, args, tf_error, NULL_TREE);
8369               if (TREE_CODE (t) == TEMPLATE_DECL)
8370                 --processing_template_decl;
8371               set_current_access_from_decl (r);
8372               finish_member_declaration (r);
8373             }
8374           else
8375             {
8376               /* Build new TYPE_FIELDS.  */
8377               if (TREE_CODE (t) == STATIC_ASSERT)
8378                 {
8379                   tree condition = 
8380                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8381                                  tf_warning_or_error, NULL_TREE,
8382                                  /*integral_constant_expression_p=*/true);
8383                   finish_static_assert (condition,
8384                                         STATIC_ASSERT_MESSAGE (t), 
8385                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8386                                         /*member_p=*/true);
8387                 }
8388               else if (TREE_CODE (t) != CONST_DECL)
8389                 {
8390                   tree r;
8391
8392                   /* The file and line for this declaration, to
8393                      assist in error message reporting.  Since we
8394                      called push_tinst_level above, we don't need to
8395                      restore these.  */
8396                   input_location = DECL_SOURCE_LOCATION (t);
8397
8398                   if (TREE_CODE (t) == TEMPLATE_DECL)
8399                     ++processing_template_decl;
8400                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8401                   if (TREE_CODE (t) == TEMPLATE_DECL)
8402                     --processing_template_decl;
8403                   if (TREE_CODE (r) == VAR_DECL)
8404                     {
8405                       /* In [temp.inst]:
8406
8407                            [t]he initialization (and any associated
8408                            side-effects) of a static data member does
8409                            not occur unless the static data member is
8410                            itself used in a way that requires the
8411                            definition of the static data member to
8412                            exist.
8413
8414                          Therefore, we do not substitute into the
8415                          initialized for the static data member here.  */
8416                       finish_static_data_member_decl
8417                         (r,
8418                          /*init=*/NULL_TREE,
8419                          /*init_const_expr_p=*/false,
8420                          /*asmspec_tree=*/NULL_TREE,
8421                          /*flags=*/0);
8422                     }
8423                   else if (TREE_CODE (r) == FIELD_DECL)
8424                     {
8425                       /* Determine whether R has a valid type and can be
8426                          completed later.  If R is invalid, then it is
8427                          replaced by error_mark_node so that it will not be
8428                          added to TYPE_FIELDS.  */
8429                       tree rtype = TREE_TYPE (r);
8430                       if (can_complete_type_without_circularity (rtype))
8431                         complete_type (rtype);
8432
8433                       if (!COMPLETE_TYPE_P (rtype))
8434                         {
8435                           cxx_incomplete_type_error (r, rtype);
8436                           r = error_mark_node;
8437                         }
8438                     }
8439
8440                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8441                      such a thing will already have been added to the field
8442                      list by tsubst_enum in finish_member_declaration in the
8443                      CLASSTYPE_NESTED_UTDS case above.  */
8444                   if (!(TREE_CODE (r) == TYPE_DECL
8445                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8446                         && DECL_ARTIFICIAL (r)))
8447                     {
8448                       set_current_access_from_decl (r);
8449                       finish_member_declaration (r);
8450                     }
8451                 }
8452             }
8453         }
8454       else
8455         {
8456           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8457             {
8458               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8459
8460               tree friend_type = t;
8461               bool adjust_processing_template_decl = false;
8462
8463               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8464                 {
8465                   /* template <class T> friend class C;  */
8466                   friend_type = tsubst_friend_class (friend_type, args);
8467                   adjust_processing_template_decl = true;
8468                 }
8469               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8470                 {
8471                   /* template <class T> friend class C::D;  */
8472                   friend_type = tsubst (friend_type, args,
8473                                         tf_warning_or_error, NULL_TREE);
8474                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8475                     friend_type = TREE_TYPE (friend_type);
8476                   adjust_processing_template_decl = true;
8477                 }
8478               else if (TREE_CODE (friend_type) == TYPENAME_TYPE
8479                        || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
8480                 {
8481                   /* This could be either
8482
8483                        friend class T::C;
8484
8485                      when dependent_type_p is false or
8486
8487                        template <class U> friend class T::C;
8488
8489                      otherwise.  */
8490                   friend_type = tsubst (friend_type, args,
8491                                         tf_warning_or_error, NULL_TREE);
8492                   /* Bump processing_template_decl for correct
8493                      dependent_type_p calculation.  */
8494                   ++processing_template_decl;
8495                   if (dependent_type_p (friend_type))
8496                     adjust_processing_template_decl = true;
8497                   --processing_template_decl;
8498                 }
8499               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8500                        && hidden_name_p (TYPE_NAME (friend_type)))
8501                 {
8502                   /* friend class C;
8503
8504                      where C hasn't been declared yet.  Let's lookup name
8505                      from namespace scope directly, bypassing any name that
8506                      come from dependent base class.  */
8507                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8508
8509                   /* The call to xref_tag_from_type does injection for friend
8510                      classes.  */
8511                   push_nested_namespace (ns);
8512                   friend_type =
8513                     xref_tag_from_type (friend_type, NULL_TREE,
8514                                         /*tag_scope=*/ts_current);
8515                   pop_nested_namespace (ns);
8516                 }
8517               else if (uses_template_parms (friend_type))
8518                 /* friend class C<T>;  */
8519                 friend_type = tsubst (friend_type, args,
8520                                       tf_warning_or_error, NULL_TREE);
8521               /* Otherwise it's
8522
8523                    friend class C;
8524
8525                  where C is already declared or
8526
8527                    friend class C<int>;
8528
8529                  We don't have to do anything in these cases.  */
8530
8531               if (adjust_processing_template_decl)
8532                 /* Trick make_friend_class into realizing that the friend
8533                    we're adding is a template, not an ordinary class.  It's
8534                    important that we use make_friend_class since it will
8535                    perform some error-checking and output cross-reference
8536                    information.  */
8537                 ++processing_template_decl;
8538
8539               if (friend_type != error_mark_node)
8540                 make_friend_class (type, friend_type, /*complain=*/false);
8541
8542               if (adjust_processing_template_decl)
8543                 --processing_template_decl;
8544             }
8545           else
8546             {
8547               /* Build new DECL_FRIENDLIST.  */
8548               tree r;
8549
8550               /* The file and line for this declaration, to
8551                  assist in error message reporting.  Since we
8552                  called push_tinst_level above, we don't need to
8553                  restore these.  */
8554               input_location = DECL_SOURCE_LOCATION (t);
8555
8556               if (TREE_CODE (t) == TEMPLATE_DECL)
8557                 {
8558                   ++processing_template_decl;
8559                   push_deferring_access_checks (dk_no_check);
8560                 }
8561
8562               r = tsubst_friend_function (t, args);
8563               add_friend (type, r, /*complain=*/false);
8564               if (TREE_CODE (t) == TEMPLATE_DECL)
8565                 {
8566                   pop_deferring_access_checks ();
8567                   --processing_template_decl;
8568                 }
8569             }
8570         }
8571     }
8572
8573   if (CLASSTYPE_LAMBDA_EXPR (type))
8574     maybe_add_lambda_conv_op (type);
8575
8576   /* Set the file and line number information to whatever is given for
8577      the class itself.  This puts error messages involving generated
8578      implicit functions at a predictable point, and the same point
8579      that would be used for non-template classes.  */
8580   input_location = DECL_SOURCE_LOCATION (typedecl);
8581
8582   unreverse_member_declarations (type);
8583   finish_struct_1 (type);
8584   TYPE_BEING_DEFINED (type) = 0;
8585
8586   /* We don't instantiate default arguments for member functions.  14.7.1:
8587
8588      The implicit instantiation of a class template specialization causes
8589      the implicit instantiation of the declarations, but not of the
8590      definitions or default arguments, of the class member functions,
8591      member classes, static data members and member templates....  */
8592
8593   /* Some typedefs referenced from within the template code need to be access
8594      checked at template instantiation time, i.e now. These types were
8595      added to the template at parsing time. Let's get those and perform
8596      the access checks then.  */
8597   perform_typedefs_access_check (pattern, args);
8598   perform_deferred_access_checks ();
8599   pop_nested_class ();
8600   maximum_field_alignment = saved_maximum_field_alignment;
8601   pop_from_top_level ();
8602   pop_deferring_access_checks ();
8603   pop_tinst_level ();
8604
8605   /* The vtable for a template class can be emitted in any translation
8606      unit in which the class is instantiated.  When there is no key
8607      method, however, finish_struct_1 will already have added TYPE to
8608      the keyed_classes list.  */
8609   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8610     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8611
8612   return type;
8613 }
8614
8615 /* Wrapper for instantiate_class_template_1.  */
8616
8617 tree
8618 instantiate_class_template (tree type)
8619 {
8620   tree ret;
8621   timevar_push (TV_TEMPLATE_INST);
8622   ret = instantiate_class_template_1 (type);
8623   timevar_pop (TV_TEMPLATE_INST);
8624   return ret;
8625 }
8626
8627 static tree
8628 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8629 {
8630   tree r;
8631
8632   if (!t)
8633     r = t;
8634   else if (TYPE_P (t))
8635     r = tsubst (t, args, complain, in_decl);
8636   else
8637     {
8638       if (!(complain & tf_warning))
8639         ++c_inhibit_evaluation_warnings;
8640       r = tsubst_expr (t, args, complain, in_decl,
8641                        /*integral_constant_expression_p=*/true);
8642       if (!(complain & tf_warning))
8643         --c_inhibit_evaluation_warnings;
8644     }
8645   return r;
8646 }
8647
8648 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8649    NONTYPE_ARGUMENT_PACK.  */
8650
8651 static tree
8652 make_fnparm_pack (tree spec_parm)
8653 {
8654   /* Collect all of the extra "packed" parameters into an
8655      argument pack.  */
8656   tree parmvec;
8657   tree parmtypevec;
8658   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8659   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8660   int i, len = list_length (spec_parm);
8661
8662   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8663   parmvec = make_tree_vec (len);
8664   parmtypevec = make_tree_vec (len);
8665   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
8666     {
8667       TREE_VEC_ELT (parmvec, i) = spec_parm;
8668       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8669     }
8670
8671   /* Build the argument packs.  */
8672   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8673   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8674   TREE_TYPE (argpack) = argtypepack;
8675
8676   return argpack;
8677 }        
8678
8679 /* Substitute ARGS into T, which is an pack expansion
8680    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8681    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8682    (if only a partial substitution could be performed) or
8683    ERROR_MARK_NODE if there was an error.  */
8684 tree
8685 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8686                        tree in_decl)
8687 {
8688   tree pattern;
8689   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8690   int i, len = -1;
8691   tree result;
8692   int incomplete = 0;
8693   htab_t saved_local_specializations = NULL;
8694
8695   gcc_assert (PACK_EXPANSION_P (t));
8696   pattern = PACK_EXPANSION_PATTERN (t);
8697
8698   /* Determine the argument packs that will instantiate the parameter
8699      packs used in the expansion expression. While we're at it,
8700      compute the number of arguments to be expanded and make sure it
8701      is consistent.  */
8702   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8703        pack = TREE_CHAIN (pack))
8704     {
8705       tree parm_pack = TREE_VALUE (pack);
8706       tree arg_pack = NULL_TREE;
8707       tree orig_arg = NULL_TREE;
8708
8709       if (TREE_CODE (parm_pack) == PARM_DECL)
8710         {
8711           if (!cp_unevaluated_operand)
8712             arg_pack = retrieve_local_specialization (parm_pack);
8713           else
8714             {
8715               /* We can't rely on local_specializations for a parameter
8716                  name used later in a function declaration (such as in a
8717                  late-specified return type).  Even if it exists, it might
8718                  have the wrong value for a recursive call.  Just make a
8719                  dummy decl, since it's only used for its type.  */
8720               arg_pack = tsubst_decl (parm_pack, args, complain);
8721               if (arg_pack && FUNCTION_PARAMETER_PACK_P (arg_pack))
8722                 /* Partial instantiation of the parm_pack, we can't build
8723                    up an argument pack yet.  */
8724                 arg_pack = NULL_TREE;
8725               else
8726                 arg_pack = make_fnparm_pack (arg_pack);
8727             }
8728         }
8729       else
8730         {
8731           int level, idx, levels;
8732           template_parm_level_and_index (parm_pack, &level, &idx);
8733
8734           levels = TMPL_ARGS_DEPTH (args);
8735           if (level <= levels)
8736             arg_pack = TMPL_ARG (args, level, idx);
8737         }
8738
8739       orig_arg = arg_pack;
8740       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8741         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8742       
8743       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8744         /* This can only happen if we forget to expand an argument
8745            pack somewhere else. Just return an error, silently.  */
8746         {
8747           result = make_tree_vec (1);
8748           TREE_VEC_ELT (result, 0) = error_mark_node;
8749           return result;
8750         }
8751
8752       /* For clarity in the comments below let's use the
8753          representation 'argument_pack<elements>' to denote an
8754          argument pack and its elements.
8755
8756          In the 'if' block below, we want to detect cases where
8757          ARG_PACK is argument_pack<PARM_PACK...>.  I.e, we want to
8758          check if ARG_PACK is an argument pack which sole element is
8759          the expansion of PARM_PACK.  That argument pack is typically
8760          created by template_parm_to_arg when passed a parameter
8761          pack.  */
8762       if (arg_pack
8763           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8764           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8765         {
8766           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8767           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8768           /* So we have an argument_pack<P...>.  We want to test if P
8769              is actually PARM_PACK.  We will not use cp_tree_equal to
8770              test P and PARM_PACK because during type fixup (by
8771              fixup_template_parm) P can be a pre-fixup version of a
8772              type and PARM_PACK be its post-fixup version.
8773              cp_tree_equal would consider them as different even
8774              though we would want to consider them compatible for our
8775              precise purpose here.
8776
8777              Thus we are going to consider that P and PARM_PACK are
8778              compatible if they have the same DECL.  */
8779           if ((/* If ARG_PACK is a type parameter pack named by the
8780                   same DECL as parm_pack ...  */
8781                (TYPE_P (pattern)
8782                 && TYPE_P (parm_pack)
8783                 && TYPE_NAME (pattern) == TYPE_NAME (parm_pack))
8784                /* ... or if ARG_PACK is a non-type parameter
8785                   named by the same DECL as parm_pack ...  */
8786                || (TREE_CODE (pattern) == TEMPLATE_PARM_INDEX
8787                    && TREE_CODE (parm_pack) == PARM_DECL
8788                    && TEMPLATE_PARM_DECL (pattern)
8789                    == TEMPLATE_PARM_DECL (DECL_INITIAL (parm_pack))))
8790               && template_parameter_pack_p (pattern))
8791             /* ... then the argument pack that the parameter maps to
8792                is just an expansion of the parameter itself, such as
8793                one would find in the implicit typedef of a class
8794                inside the class itself.  Consider this parameter
8795                "unsubstituted", so that we will maintain the outer
8796                pack expansion.  */
8797             arg_pack = NULL_TREE;
8798         }
8799           
8800       if (arg_pack)
8801         {
8802           int my_len = 
8803             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8804
8805           /* It's all-or-nothing with incomplete argument packs.  */
8806           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8807             return error_mark_node;
8808           
8809           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8810             incomplete = 1;
8811
8812           if (len < 0)
8813             len = my_len;
8814           else if (len != my_len)
8815             {
8816               if (incomplete)
8817                 /* We got explicit args for some packs but not others;
8818                    do nothing now and try again after deduction.  */
8819                 return t;
8820               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8821                 error ("mismatched argument pack lengths while expanding "
8822                        "%<%T%>",
8823                        pattern);
8824               else
8825                 error ("mismatched argument pack lengths while expanding "
8826                        "%<%E%>",
8827                        pattern);
8828               return error_mark_node;
8829             }
8830
8831           /* Keep track of the parameter packs and their corresponding
8832              argument packs.  */
8833           packs = tree_cons (parm_pack, arg_pack, packs);
8834           TREE_TYPE (packs) = orig_arg;
8835         }
8836       else
8837         /* We can't substitute for this parameter pack.  */
8838         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8839                                          TREE_VALUE (pack),
8840                                          unsubstituted_packs);
8841     }
8842
8843   /* We cannot expand this expansion expression, because we don't have
8844      all of the argument packs we need. Substitute into the pattern
8845      and return a PACK_EXPANSION_*. The caller will need to deal with
8846      that.  */
8847   if (unsubstituted_packs)
8848     {
8849       tree new_pat;
8850       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8851         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8852                                /*integral_constant_expression_p=*/false);
8853       else
8854         new_pat = tsubst (pattern, args, complain, in_decl);
8855       return make_pack_expansion (new_pat);
8856     }
8857
8858   /* We could not find any argument packs that work.  */
8859   if (len < 0)
8860     return error_mark_node;
8861
8862   if (cp_unevaluated_operand)
8863     {
8864       /* We're in a late-specified return type, so create our own local
8865          specializations table; the current table is either NULL or (in the
8866          case of recursive unification) might have bindings that we don't
8867          want to use or alter.  */
8868       saved_local_specializations = local_specializations;
8869       local_specializations = htab_create (37,
8870                                            hash_local_specialization,
8871                                            eq_local_specializations,
8872                                            NULL);
8873     }
8874
8875   /* For each argument in each argument pack, substitute into the
8876      pattern.  */
8877   result = make_tree_vec (len + incomplete);
8878   for (i = 0; i < len + incomplete; ++i)
8879     {
8880       /* For parameter pack, change the substitution of the parameter
8881          pack to the ith argument in its argument pack, then expand
8882          the pattern.  */
8883       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8884         {
8885           tree parm = TREE_PURPOSE (pack);
8886
8887           if (TREE_CODE (parm) == PARM_DECL)
8888             {
8889               /* Select the Ith argument from the pack.  */
8890               tree arg = make_node (ARGUMENT_PACK_SELECT);
8891               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8892               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8893               mark_used (parm);
8894               register_local_specialization (arg, parm);
8895             }
8896           else
8897             {
8898               tree value = parm;
8899               int idx, level;
8900               template_parm_level_and_index (parm, &level, &idx);
8901               
8902               if (i < len) 
8903                 {
8904                   /* Select the Ith argument from the pack. */
8905                   value = make_node (ARGUMENT_PACK_SELECT);
8906                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8907                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8908                 }
8909
8910               /* Update the corresponding argument.  */
8911               TMPL_ARG (args, level, idx) = value;
8912             }
8913         }
8914
8915       /* Substitute into the PATTERN with the altered arguments.  */
8916       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8917         TREE_VEC_ELT (result, i) = 
8918           tsubst_expr (pattern, args, complain, in_decl,
8919                        /*integral_constant_expression_p=*/false);
8920       else
8921         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8922
8923       if (i == len)
8924         /* When we have incomplete argument packs, the last "expanded"
8925            result is itself a pack expansion, which allows us
8926            to deduce more arguments.  */
8927         TREE_VEC_ELT (result, i) = 
8928           make_pack_expansion (TREE_VEC_ELT (result, i));
8929
8930       if (TREE_VEC_ELT (result, i) == error_mark_node)
8931         {
8932           result = error_mark_node;
8933           break;
8934         }
8935     }
8936
8937   /* Update ARGS to restore the substitution from parameter packs to
8938      their argument packs.  */
8939   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8940     {
8941       tree parm = TREE_PURPOSE (pack);
8942
8943       if (TREE_CODE (parm) == PARM_DECL)
8944         register_local_specialization (TREE_TYPE (pack), parm);
8945       else
8946         {
8947           int idx, level;
8948           template_parm_level_and_index (parm, &level, &idx);
8949           
8950           /* Update the corresponding argument.  */
8951           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8952             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8953               TREE_TYPE (pack);
8954           else
8955             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8956         }
8957     }
8958
8959   if (saved_local_specializations)
8960     {
8961       htab_delete (local_specializations);
8962       local_specializations = saved_local_specializations;
8963     }
8964   
8965   return result;
8966 }
8967
8968 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8969    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8970    parameter packs; all parms generated from a function parameter pack will
8971    have the same DECL_PARM_INDEX.  */
8972
8973 tree
8974 get_pattern_parm (tree parm, tree tmpl)
8975 {
8976   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8977   tree patparm;
8978
8979   if (DECL_ARTIFICIAL (parm))
8980     {
8981       for (patparm = DECL_ARGUMENTS (pattern);
8982            patparm; patparm = DECL_CHAIN (patparm))
8983         if (DECL_ARTIFICIAL (patparm)
8984             && DECL_NAME (parm) == DECL_NAME (patparm))
8985           break;
8986     }
8987   else
8988     {
8989       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8990       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8991       gcc_assert (DECL_PARM_INDEX (patparm)
8992                   == DECL_PARM_INDEX (parm));
8993     }
8994
8995   return patparm;
8996 }
8997
8998 /* Substitute ARGS into the vector or list of template arguments T.  */
8999
9000 static tree
9001 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9002 {
9003   tree orig_t = t;
9004   int len, need_new = 0, i, expanded_len_adjust = 0, out;
9005   tree *elts;
9006
9007   if (t == error_mark_node)
9008     return error_mark_node;
9009
9010   len = TREE_VEC_LENGTH (t);
9011   elts = XALLOCAVEC (tree, len);
9012
9013   for (i = 0; i < len; i++)
9014     {
9015       tree orig_arg = TREE_VEC_ELT (t, i);
9016       tree new_arg;
9017
9018       if (TREE_CODE (orig_arg) == TREE_VEC)
9019         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
9020       else if (PACK_EXPANSION_P (orig_arg))
9021         {
9022           /* Substitute into an expansion expression.  */
9023           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
9024
9025           if (TREE_CODE (new_arg) == TREE_VEC)
9026             /* Add to the expanded length adjustment the number of
9027                expanded arguments. We subtract one from this
9028                measurement, because the argument pack expression
9029                itself is already counted as 1 in
9030                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
9031                the argument pack is empty.  */
9032             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
9033         }
9034       else if (ARGUMENT_PACK_P (orig_arg))
9035         {
9036           /* Substitute into each of the arguments.  */
9037           new_arg = TYPE_P (orig_arg)
9038             ? cxx_make_type (TREE_CODE (orig_arg))
9039             : make_node (TREE_CODE (orig_arg));
9040           
9041           SET_ARGUMENT_PACK_ARGS (
9042             new_arg,
9043             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
9044                                   args, complain, in_decl));
9045
9046           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
9047             new_arg = error_mark_node;
9048
9049           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
9050             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
9051                                           complain, in_decl);
9052             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
9053
9054             if (TREE_TYPE (new_arg) == error_mark_node)
9055               new_arg = error_mark_node;
9056           }
9057         }
9058       else
9059         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
9060
9061       if (new_arg == error_mark_node)
9062         return error_mark_node;
9063
9064       elts[i] = new_arg;
9065       if (new_arg != orig_arg)
9066         need_new = 1;
9067     }
9068
9069   if (!need_new)
9070     return t;
9071
9072   /* Make space for the expanded arguments coming from template
9073      argument packs.  */
9074   t = make_tree_vec (len + expanded_len_adjust);
9075   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
9076      arguments for a member template.
9077      In that case each TREE_VEC in ORIG_T represents a level of template
9078      arguments, and ORIG_T won't carry any non defaulted argument count.
9079      It will rather be the nested TREE_VECs that will carry one.
9080      In other words, ORIG_T carries a non defaulted argument count only
9081      if it doesn't contain any nested TREE_VEC.  */
9082   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
9083     {
9084       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
9085       count += expanded_len_adjust;
9086       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
9087     }
9088   for (i = 0, out = 0; i < len; i++)
9089     {
9090       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
9091            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
9092           && TREE_CODE (elts[i]) == TREE_VEC)
9093         {
9094           int idx;
9095
9096           /* Now expand the template argument pack "in place".  */
9097           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
9098             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
9099         }
9100       else
9101         {
9102           TREE_VEC_ELT (t, out) = elts[i];
9103           out++;
9104         }
9105     }
9106
9107   return t;
9108 }
9109
9110 /* Return the result of substituting ARGS into the template parameters
9111    given by PARMS.  If there are m levels of ARGS and m + n levels of
9112    PARMS, then the result will contain n levels of PARMS.  For
9113    example, if PARMS is `template <class T> template <class U>
9114    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
9115    result will be `template <int*, double, class V>'.  */
9116
9117 static tree
9118 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
9119 {
9120   tree r = NULL_TREE;
9121   tree* new_parms;
9122
9123   /* When substituting into a template, we must set
9124      PROCESSING_TEMPLATE_DECL as the template parameters may be
9125      dependent if they are based on one-another, and the dependency
9126      predicates are short-circuit outside of templates.  */
9127   ++processing_template_decl;
9128
9129   for (new_parms = &r;
9130        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
9131        new_parms = &(TREE_CHAIN (*new_parms)),
9132          parms = TREE_CHAIN (parms))
9133     {
9134       tree new_vec =
9135         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
9136       int i;
9137
9138       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
9139         {
9140           tree tuple;
9141
9142           if (parms == error_mark_node)
9143             continue;
9144
9145           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
9146
9147           if (tuple == error_mark_node)
9148             continue;
9149
9150           TREE_VEC_ELT (new_vec, i) =
9151             tsubst_template_parm (tuple, args, complain);
9152         }
9153
9154       *new_parms =
9155         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
9156                              - TMPL_ARGS_DEPTH (args)),
9157                    new_vec, NULL_TREE);
9158     }
9159
9160   --processing_template_decl;
9161
9162   return r;
9163 }
9164
9165 /* Return the result of substituting ARGS into one template parameter
9166    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
9167    parameter and which TREE_PURPOSE is the default argument of the
9168    template parameter.  */
9169
9170 static tree
9171 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
9172 {
9173   tree default_value, parm_decl;
9174
9175   if (args == NULL_TREE
9176       || t == NULL_TREE
9177       || t == error_mark_node)
9178     return t;
9179
9180   gcc_assert (TREE_CODE (t) == TREE_LIST);
9181
9182   default_value = TREE_PURPOSE (t);
9183   parm_decl = TREE_VALUE (t);
9184
9185   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
9186   if (TREE_CODE (parm_decl) == PARM_DECL
9187       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
9188     parm_decl = error_mark_node;
9189   default_value = tsubst_template_arg (default_value, args,
9190                                        complain, NULL_TREE);
9191
9192   return build_tree_list (default_value, parm_decl);
9193 }
9194
9195 /* Substitute the ARGS into the indicated aggregate (or enumeration)
9196    type T.  If T is not an aggregate or enumeration type, it is
9197    handled as if by tsubst.  IN_DECL is as for tsubst.  If
9198    ENTERING_SCOPE is nonzero, T is the context for a template which
9199    we are presently tsubst'ing.  Return the substituted value.  */
9200
9201 static tree
9202 tsubst_aggr_type (tree t,
9203                   tree args,
9204                   tsubst_flags_t complain,
9205                   tree in_decl,
9206                   int entering_scope)
9207 {
9208   if (t == NULL_TREE)
9209     return NULL_TREE;
9210
9211   switch (TREE_CODE (t))
9212     {
9213     case RECORD_TYPE:
9214       if (TYPE_PTRMEMFUNC_P (t))
9215         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
9216
9217       /* Else fall through.  */
9218     case ENUMERAL_TYPE:
9219     case UNION_TYPE:
9220       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
9221         {
9222           tree argvec;
9223           tree context;
9224           tree r;
9225           int saved_unevaluated_operand;
9226           int saved_inhibit_evaluation_warnings;
9227
9228           /* In "sizeof(X<I>)" we need to evaluate "I".  */
9229           saved_unevaluated_operand = cp_unevaluated_operand;
9230           cp_unevaluated_operand = 0;
9231           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9232           c_inhibit_evaluation_warnings = 0;
9233
9234           /* First, determine the context for the type we are looking
9235              up.  */
9236           context = TYPE_CONTEXT (t);
9237           if (context)
9238             {
9239               context = tsubst_aggr_type (context, args, complain,
9240                                           in_decl, /*entering_scope=*/1);
9241               /* If context is a nested class inside a class template,
9242                  it may still need to be instantiated (c++/33959).  */
9243               if (TYPE_P (context))
9244                 context = complete_type (context);
9245             }
9246
9247           /* Then, figure out what arguments are appropriate for the
9248              type we are trying to find.  For example, given:
9249
9250                template <class T> struct S;
9251                template <class T, class U> void f(T, U) { S<U> su; }
9252
9253              and supposing that we are instantiating f<int, double>,
9254              then our ARGS will be {int, double}, but, when looking up
9255              S we only want {double}.  */
9256           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
9257                                          complain, in_decl);
9258           if (argvec == error_mark_node)
9259             r = error_mark_node;
9260           else
9261             {
9262               r = lookup_template_class (t, argvec, in_decl, context,
9263                                          entering_scope, complain);
9264               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
9265             }
9266
9267           cp_unevaluated_operand = saved_unevaluated_operand;
9268           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9269
9270           return r;
9271         }
9272       else
9273         /* This is not a template type, so there's nothing to do.  */
9274         return t;
9275
9276     default:
9277       return tsubst (t, args, complain, in_decl);
9278     }
9279 }
9280
9281 /* Substitute into the default argument ARG (a default argument for
9282    FN), which has the indicated TYPE.  */
9283
9284 tree
9285 tsubst_default_argument (tree fn, tree type, tree arg)
9286 {
9287   tree saved_class_ptr = NULL_TREE;
9288   tree saved_class_ref = NULL_TREE;
9289
9290   /* This can happen in invalid code.  */
9291   if (TREE_CODE (arg) == DEFAULT_ARG)
9292     return arg;
9293
9294   /* This default argument came from a template.  Instantiate the
9295      default argument here, not in tsubst.  In the case of
9296      something like:
9297
9298        template <class T>
9299        struct S {
9300          static T t();
9301          void f(T = t());
9302        };
9303
9304      we must be careful to do name lookup in the scope of S<T>,
9305      rather than in the current class.  */
9306   push_access_scope (fn);
9307   /* The "this" pointer is not valid in a default argument.  */
9308   if (cfun)
9309     {
9310       saved_class_ptr = current_class_ptr;
9311       cp_function_chain->x_current_class_ptr = NULL_TREE;
9312       saved_class_ref = current_class_ref;
9313       cp_function_chain->x_current_class_ref = NULL_TREE;
9314     }
9315
9316   push_deferring_access_checks(dk_no_deferred);
9317   /* The default argument expression may cause implicitly defined
9318      member functions to be synthesized, which will result in garbage
9319      collection.  We must treat this situation as if we were within
9320      the body of function so as to avoid collecting live data on the
9321      stack.  */
9322   ++function_depth;
9323   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
9324                      tf_warning_or_error, NULL_TREE,
9325                      /*integral_constant_expression_p=*/false);
9326   --function_depth;
9327   pop_deferring_access_checks();
9328
9329   /* Restore the "this" pointer.  */
9330   if (cfun)
9331     {
9332       cp_function_chain->x_current_class_ptr = saved_class_ptr;
9333       cp_function_chain->x_current_class_ref = saved_class_ref;
9334     }
9335
9336   /* Make sure the default argument is reasonable.  */
9337   arg = check_default_argument (type, arg);
9338
9339   pop_access_scope (fn);
9340
9341   return arg;
9342 }
9343
9344 /* Substitute into all the default arguments for FN.  */
9345
9346 static void
9347 tsubst_default_arguments (tree fn)
9348 {
9349   tree arg;
9350   tree tmpl_args;
9351
9352   tmpl_args = DECL_TI_ARGS (fn);
9353
9354   /* If this function is not yet instantiated, we certainly don't need
9355      its default arguments.  */
9356   if (uses_template_parms (tmpl_args))
9357     return;
9358   /* Don't do this again for clones.  */
9359   if (DECL_CLONED_FUNCTION_P (fn))
9360     return;
9361
9362   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
9363        arg;
9364        arg = TREE_CHAIN (arg))
9365     if (TREE_PURPOSE (arg))
9366       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
9367                                                     TREE_VALUE (arg),
9368                                                     TREE_PURPOSE (arg));
9369 }
9370
9371 /* Substitute the ARGS into the T, which is a _DECL.  Return the
9372    result of the substitution.  Issue error and warning messages under
9373    control of COMPLAIN.  */
9374
9375 static tree
9376 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
9377 {
9378 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
9379   location_t saved_loc;
9380   tree r = NULL_TREE;
9381   tree in_decl = t;
9382   hashval_t hash = 0;
9383
9384   /* Set the filename and linenumber to improve error-reporting.  */
9385   saved_loc = input_location;
9386   input_location = DECL_SOURCE_LOCATION (t);
9387
9388   switch (TREE_CODE (t))
9389     {
9390     case TEMPLATE_DECL:
9391       {
9392         /* We can get here when processing a member function template,
9393            member class template, or template template parameter.  */
9394         tree decl = DECL_TEMPLATE_RESULT (t);
9395         tree spec;
9396         tree tmpl_args;
9397         tree full_args;
9398
9399         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9400           {
9401             /* Template template parameter is treated here.  */
9402             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9403             if (new_type == error_mark_node)
9404               RETURN (error_mark_node);
9405
9406             r = copy_decl (t);
9407             DECL_CHAIN (r) = NULL_TREE;
9408             TREE_TYPE (r) = new_type;
9409             DECL_TEMPLATE_RESULT (r)
9410               = build_decl (DECL_SOURCE_LOCATION (decl),
9411                             TYPE_DECL, DECL_NAME (decl), new_type);
9412             DECL_TEMPLATE_PARMS (r)
9413               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9414                                        complain);
9415             TYPE_NAME (new_type) = r;
9416             break;
9417           }
9418
9419         /* We might already have an instance of this template.
9420            The ARGS are for the surrounding class type, so the
9421            full args contain the tsubst'd args for the context,
9422            plus the innermost args from the template decl.  */
9423         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
9424           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
9425           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
9426         /* Because this is a template, the arguments will still be
9427            dependent, even after substitution.  If
9428            PROCESSING_TEMPLATE_DECL is not set, the dependency
9429            predicates will short-circuit.  */
9430         ++processing_template_decl;
9431         full_args = tsubst_template_args (tmpl_args, args,
9432                                           complain, in_decl);
9433         --processing_template_decl;
9434         if (full_args == error_mark_node)
9435           RETURN (error_mark_node);
9436
9437         /* If this is a default template template argument,
9438            tsubst might not have changed anything.  */
9439         if (full_args == tmpl_args)
9440           RETURN (t);
9441
9442         hash = hash_tmpl_and_args (t, full_args);
9443         spec = retrieve_specialization (t, full_args, hash);
9444         if (spec != NULL_TREE)
9445           {
9446             r = spec;
9447             break;
9448           }
9449
9450         /* Make a new template decl.  It will be similar to the
9451            original, but will record the current template arguments.
9452            We also create a new function declaration, which is just
9453            like the old one, but points to this new template, rather
9454            than the old one.  */
9455         r = copy_decl (t);
9456         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9457         DECL_CHAIN (r) = NULL_TREE;
9458
9459         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9460
9461         if (TREE_CODE (decl) == TYPE_DECL)
9462           {
9463             tree new_type;
9464             ++processing_template_decl;
9465             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9466             --processing_template_decl;
9467             if (new_type == error_mark_node)
9468               RETURN (error_mark_node);
9469
9470             TREE_TYPE (r) = new_type;
9471             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9472             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9473             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9474             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9475           }
9476         else
9477           {
9478             tree new_decl;
9479             ++processing_template_decl;
9480             new_decl = tsubst (decl, args, complain, in_decl);
9481             --processing_template_decl;
9482             if (new_decl == error_mark_node)
9483               RETURN (error_mark_node);
9484
9485             DECL_TEMPLATE_RESULT (r) = new_decl;
9486             DECL_TI_TEMPLATE (new_decl) = r;
9487             TREE_TYPE (r) = TREE_TYPE (new_decl);
9488             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9489             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9490           }
9491
9492         SET_DECL_IMPLICIT_INSTANTIATION (r);
9493         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9494         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9495
9496         /* The template parameters for this new template are all the
9497            template parameters for the old template, except the
9498            outermost level of parameters.  */
9499         DECL_TEMPLATE_PARMS (r)
9500           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9501                                    complain);
9502
9503         if (PRIMARY_TEMPLATE_P (t))
9504           DECL_PRIMARY_TEMPLATE (r) = r;
9505
9506         if (TREE_CODE (decl) != TYPE_DECL)
9507           /* Record this non-type partial instantiation.  */
9508           register_specialization (r, t,
9509                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9510                                    false, hash);
9511       }
9512       break;
9513
9514     case FUNCTION_DECL:
9515       {
9516         tree ctx;
9517         tree argvec = NULL_TREE;
9518         tree *friends;
9519         tree gen_tmpl;
9520         tree type;
9521         int member;
9522         int args_depth;
9523         int parms_depth;
9524
9525         /* Nobody should be tsubst'ing into non-template functions.  */
9526         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9527
9528         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9529           {
9530             tree spec;
9531             bool dependent_p;
9532
9533             /* If T is not dependent, just return it.  We have to
9534                increment PROCESSING_TEMPLATE_DECL because
9535                value_dependent_expression_p assumes that nothing is
9536                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9537             ++processing_template_decl;
9538             dependent_p = value_dependent_expression_p (t);
9539             --processing_template_decl;
9540             if (!dependent_p)
9541               RETURN (t);
9542
9543             /* Calculate the most general template of which R is a
9544                specialization, and the complete set of arguments used to
9545                specialize R.  */
9546             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9547             argvec = tsubst_template_args (DECL_TI_ARGS
9548                                           (DECL_TEMPLATE_RESULT
9549                                                  (DECL_TI_TEMPLATE (t))),
9550                                            args, complain, in_decl);
9551
9552             /* Check to see if we already have this specialization.  */
9553             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9554             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9555
9556             if (spec)
9557               {
9558                 r = spec;
9559                 break;
9560               }
9561
9562             /* We can see more levels of arguments than parameters if
9563                there was a specialization of a member template, like
9564                this:
9565
9566                  template <class T> struct S { template <class U> void f(); }
9567                  template <> template <class U> void S<int>::f(U);
9568
9569                Here, we'll be substituting into the specialization,
9570                because that's where we can find the code we actually
9571                want to generate, but we'll have enough arguments for
9572                the most general template.
9573
9574                We also deal with the peculiar case:
9575
9576                  template <class T> struct S {
9577                    template <class U> friend void f();
9578                  };
9579                  template <class U> void f() {}
9580                  template S<int>;
9581                  template void f<double>();
9582
9583                Here, the ARGS for the instantiation of will be {int,
9584                double}.  But, we only need as many ARGS as there are
9585                levels of template parameters in CODE_PATTERN.  We are
9586                careful not to get fooled into reducing the ARGS in
9587                situations like:
9588
9589                  template <class T> struct S { template <class U> void f(U); }
9590                  template <class T> template <> void S<T>::f(int) {}
9591
9592                which we can spot because the pattern will be a
9593                specialization in this case.  */
9594             args_depth = TMPL_ARGS_DEPTH (args);
9595             parms_depth =
9596               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9597             if (args_depth > parms_depth
9598                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9599               args = get_innermost_template_args (args, parms_depth);
9600           }
9601         else
9602           {
9603             /* This special case arises when we have something like this:
9604
9605                  template <class T> struct S {
9606                    friend void f<int>(int, double);
9607                  };
9608
9609                Here, the DECL_TI_TEMPLATE for the friend declaration
9610                will be an IDENTIFIER_NODE.  We are being called from
9611                tsubst_friend_function, and we want only to create a
9612                new decl (R) with appropriate types so that we can call
9613                determine_specialization.  */
9614             gen_tmpl = NULL_TREE;
9615           }
9616
9617         if (DECL_CLASS_SCOPE_P (t))
9618           {
9619             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9620               member = 2;
9621             else
9622               member = 1;
9623             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9624                                     complain, t, /*entering_scope=*/1);
9625           }
9626         else
9627           {
9628             member = 0;
9629             ctx = DECL_CONTEXT (t);
9630           }
9631         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9632         if (type == error_mark_node)
9633           RETURN (error_mark_node);
9634
9635         /* We do NOT check for matching decls pushed separately at this
9636            point, as they may not represent instantiations of this
9637            template, and in any case are considered separate under the
9638            discrete model.  */
9639         r = copy_decl (t);
9640         DECL_USE_TEMPLATE (r) = 0;
9641         TREE_TYPE (r) = type;
9642         /* Clear out the mangled name and RTL for the instantiation.  */
9643         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9644         SET_DECL_RTL (r, NULL);
9645         /* Leave DECL_INITIAL set on deleted instantiations.  */
9646         if (!DECL_DELETED_FN (r))
9647           DECL_INITIAL (r) = NULL_TREE;
9648         DECL_CONTEXT (r) = ctx;
9649
9650         if (member && DECL_CONV_FN_P (r))
9651           /* Type-conversion operator.  Reconstruct the name, in
9652              case it's the name of one of the template's parameters.  */
9653           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9654
9655         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9656                                      complain, t);
9657         DECL_RESULT (r) = NULL_TREE;
9658
9659         TREE_STATIC (r) = 0;
9660         TREE_PUBLIC (r) = TREE_PUBLIC (t);
9661         DECL_EXTERNAL (r) = 1;
9662         /* If this is an instantiation of a function with internal
9663            linkage, we already know what object file linkage will be
9664            assigned to the instantiation.  */
9665         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9666         DECL_DEFER_OUTPUT (r) = 0;
9667         DECL_CHAIN (r) = NULL_TREE;
9668         DECL_PENDING_INLINE_INFO (r) = 0;
9669         DECL_PENDING_INLINE_P (r) = 0;
9670         DECL_SAVED_TREE (r) = NULL_TREE;
9671         DECL_STRUCT_FUNCTION (r) = NULL;
9672         TREE_USED (r) = 0;
9673         /* We'll re-clone as appropriate in instantiate_template.  */
9674         DECL_CLONED_FUNCTION (r) = NULL_TREE;
9675
9676         /* If we aren't complaining now, return on error before we register
9677            the specialization so that we'll complain eventually.  */
9678         if ((complain & tf_error) == 0
9679             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9680             && !grok_op_properties (r, /*complain=*/false))
9681           RETURN (error_mark_node);
9682
9683         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9684            this in the special friend case mentioned above where
9685            GEN_TMPL is NULL.  */
9686         if (gen_tmpl)
9687           {
9688             DECL_TEMPLATE_INFO (r)
9689               = build_template_info (gen_tmpl, argvec);
9690             SET_DECL_IMPLICIT_INSTANTIATION (r);
9691             register_specialization (r, gen_tmpl, argvec, false, hash);
9692
9693             /* We're not supposed to instantiate default arguments
9694                until they are called, for a template.  But, for a
9695                declaration like:
9696
9697                  template <class T> void f ()
9698                  { extern void g(int i = T()); }
9699
9700                we should do the substitution when the template is
9701                instantiated.  We handle the member function case in
9702                instantiate_class_template since the default arguments
9703                might refer to other members of the class.  */
9704             if (!member
9705                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9706                 && !uses_template_parms (argvec))
9707               tsubst_default_arguments (r);
9708           }
9709         else
9710           DECL_TEMPLATE_INFO (r) = NULL_TREE;
9711
9712         /* Copy the list of befriending classes.  */
9713         for (friends = &DECL_BEFRIENDING_CLASSES (r);
9714              *friends;
9715              friends = &TREE_CHAIN (*friends))
9716           {
9717             *friends = copy_node (*friends);
9718             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9719                                             args, complain,
9720                                             in_decl);
9721           }
9722
9723         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9724           {
9725             maybe_retrofit_in_chrg (r);
9726             if (DECL_CONSTRUCTOR_P (r))
9727               grok_ctor_properties (ctx, r);
9728             /* If this is an instantiation of a member template, clone it.
9729                If it isn't, that'll be handled by
9730                clone_constructors_and_destructors.  */
9731             if (PRIMARY_TEMPLATE_P (gen_tmpl))
9732               clone_function_decl (r, /*update_method_vec_p=*/0);
9733           }
9734         else if ((complain & tf_error) != 0
9735                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9736                  && !grok_op_properties (r, /*complain=*/true))
9737           RETURN (error_mark_node);
9738
9739         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9740           SET_DECL_FRIEND_CONTEXT (r,
9741                                    tsubst (DECL_FRIEND_CONTEXT (t),
9742                                             args, complain, in_decl));
9743
9744         /* Possibly limit visibility based on template args.  */
9745         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9746         if (DECL_VISIBILITY_SPECIFIED (t))
9747           {
9748             DECL_VISIBILITY_SPECIFIED (r) = 0;
9749             DECL_ATTRIBUTES (r)
9750               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9751           }
9752         determine_visibility (r);
9753         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9754             && !processing_template_decl)
9755           defaulted_late_check (r);
9756
9757         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9758                                         args, complain, in_decl);
9759       }
9760       break;
9761
9762     case PARM_DECL:
9763       {
9764         tree type = NULL_TREE;
9765         int i, len = 1;
9766         tree expanded_types = NULL_TREE;
9767         tree prev_r = NULL_TREE;
9768         tree first_r = NULL_TREE;
9769
9770         if (FUNCTION_PARAMETER_PACK_P (t))
9771           {
9772             /* If there is a local specialization that isn't a
9773                parameter pack, it means that we're doing a "simple"
9774                substitution from inside tsubst_pack_expansion. Just
9775                return the local specialization (which will be a single
9776                parm).  */
9777             tree spec = retrieve_local_specialization (t);
9778             if (spec 
9779                 && TREE_CODE (spec) == PARM_DECL
9780                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9781               RETURN (spec);
9782
9783             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9784                the parameters in this function parameter pack.  */
9785             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9786                                                     complain, in_decl);
9787             if (TREE_CODE (expanded_types) == TREE_VEC)
9788               {
9789                 len = TREE_VEC_LENGTH (expanded_types);
9790
9791                 /* Zero-length parameter packs are boring. Just substitute
9792                    into the chain.  */
9793                 if (len == 0)
9794                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9795                                   TREE_CHAIN (t)));
9796               }
9797             else
9798               {
9799                 /* All we did was update the type. Make a note of that.  */
9800                 type = expanded_types;
9801                 expanded_types = NULL_TREE;
9802               }
9803           }
9804
9805         /* Loop through all of the parameter's we'll build. When T is
9806            a function parameter pack, LEN is the number of expanded
9807            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9808         r = NULL_TREE;
9809         for (i = 0; i < len; ++i)
9810           {
9811             prev_r = r;
9812             r = copy_node (t);
9813             if (DECL_TEMPLATE_PARM_P (t))
9814               SET_DECL_TEMPLATE_PARM_P (r);
9815
9816             if (expanded_types)
9817               /* We're on the Ith parameter of the function parameter
9818                  pack.  */
9819               {
9820                 /* An argument of a function parameter pack is not a parameter
9821                    pack.  */
9822                 FUNCTION_PARAMETER_PACK_P (r) = false;
9823
9824                 /* Get the Ith type.  */
9825                 type = TREE_VEC_ELT (expanded_types, i);
9826
9827                 if (DECL_NAME (r))
9828                   /* Rename the parameter to include the index.  */
9829                   DECL_NAME (r) =
9830                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9831               }
9832             else if (!type)
9833               /* We're dealing with a normal parameter.  */
9834               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9835
9836             type = type_decays_to (type);
9837             TREE_TYPE (r) = type;
9838             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9839
9840             if (DECL_INITIAL (r))
9841               {
9842                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9843                   DECL_INITIAL (r) = TREE_TYPE (r);
9844                 else
9845                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9846                                              complain, in_decl);
9847               }
9848
9849             DECL_CONTEXT (r) = NULL_TREE;
9850
9851             if (!DECL_TEMPLATE_PARM_P (r))
9852               DECL_ARG_TYPE (r) = type_passed_as (type);
9853
9854             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9855                                             args, complain, in_decl);
9856
9857             /* Keep track of the first new parameter we
9858                generate. That's what will be returned to the
9859                caller.  */
9860             if (!first_r)
9861               first_r = r;
9862
9863             /* Build a proper chain of parameters when substituting
9864                into a function parameter pack.  */
9865             if (prev_r)
9866               DECL_CHAIN (prev_r) = r;
9867           }
9868
9869         if (DECL_CHAIN (t))
9870           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
9871                                    complain, DECL_CHAIN (t));
9872
9873         /* FIRST_R contains the start of the chain we've built.  */
9874         r = first_r;
9875       }
9876       break;
9877
9878     case FIELD_DECL:
9879       {
9880         tree type;
9881
9882         r = copy_decl (t);
9883         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9884         if (type == error_mark_node)
9885           RETURN (error_mark_node);
9886         TREE_TYPE (r) = type;
9887         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9888
9889         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9890         DECL_INITIAL (r)
9891           = tsubst_expr (DECL_INITIAL (t), args,
9892                          complain, in_decl,
9893                          /*integral_constant_expression_p=*/true);
9894         /* We don't have to set DECL_CONTEXT here; it is set by
9895            finish_member_declaration.  */
9896         DECL_CHAIN (r) = NULL_TREE;
9897         if (VOID_TYPE_P (type))
9898           error ("instantiation of %q+D as type %qT", r, type);
9899
9900         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9901                                         args, complain, in_decl);
9902       }
9903       break;
9904
9905     case USING_DECL:
9906       /* We reach here only for member using decls.  */
9907       if (DECL_DEPENDENT_P (t))
9908         {
9909           r = do_class_using_decl
9910             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9911              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9912           if (!r)
9913             r = error_mark_node;
9914           else
9915             {
9916               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9917               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9918             }
9919         }
9920       else
9921         {
9922           r = copy_node (t);
9923           DECL_CHAIN (r) = NULL_TREE;
9924         }
9925       break;
9926
9927     case TYPE_DECL:
9928     case VAR_DECL:
9929       {
9930         tree argvec = NULL_TREE;
9931         tree gen_tmpl = NULL_TREE;
9932         tree spec;
9933         tree tmpl = NULL_TREE;
9934         tree ctx;
9935         tree type = NULL_TREE;
9936         bool local_p;
9937
9938         if (TREE_CODE (t) == TYPE_DECL
9939             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9940           {
9941             /* If this is the canonical decl, we don't have to
9942                mess with instantiations, and often we can't (for
9943                typename, template type parms and such).  Note that
9944                TYPE_NAME is not correct for the above test if
9945                we've copied the type for a typedef.  */
9946             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9947             if (type == error_mark_node)
9948               RETURN (error_mark_node);
9949             r = TYPE_NAME (type);
9950             break;
9951           }
9952
9953         /* Check to see if we already have the specialization we
9954            need.  */
9955         spec = NULL_TREE;
9956         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9957           {
9958             /* T is a static data member or namespace-scope entity.
9959                We have to substitute into namespace-scope variables
9960                (even though such entities are never templates) because
9961                of cases like:
9962                
9963                  template <class T> void f() { extern T t; }
9964
9965                where the entity referenced is not known until
9966                instantiation time.  */
9967             local_p = false;
9968             ctx = DECL_CONTEXT (t);
9969             if (DECL_CLASS_SCOPE_P (t))
9970               {
9971                 ctx = tsubst_aggr_type (ctx, args,
9972                                         complain,
9973                                         in_decl, /*entering_scope=*/1);
9974                 /* If CTX is unchanged, then T is in fact the
9975                    specialization we want.  That situation occurs when
9976                    referencing a static data member within in its own
9977                    class.  We can use pointer equality, rather than
9978                    same_type_p, because DECL_CONTEXT is always
9979                    canonical.  */
9980                 if (ctx == DECL_CONTEXT (t))
9981                   spec = t;
9982               }
9983
9984             if (!spec)
9985               {
9986                 tmpl = DECL_TI_TEMPLATE (t);
9987                 gen_tmpl = most_general_template (tmpl);
9988                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9989                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9990                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9991               }
9992           }
9993         else
9994           {
9995             /* A local variable.  */
9996             local_p = true;
9997             /* Subsequent calls to pushdecl will fill this in.  */
9998             ctx = NULL_TREE;
9999             spec = retrieve_local_specialization (t);
10000           }
10001         /* If we already have the specialization we need, there is
10002            nothing more to do.  */ 
10003         if (spec)
10004           {
10005             r = spec;
10006             break;
10007           }
10008
10009         /* Create a new node for the specialization we need.  */
10010         r = copy_decl (t);
10011         if (type == NULL_TREE)
10012           {
10013             if (is_typedef_decl (t))
10014               type = DECL_ORIGINAL_TYPE (t);
10015             else
10016               type = TREE_TYPE (t);
10017             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
10018               type = strip_array_domain (type);
10019             type = tsubst (type, args, complain, in_decl);
10020           }
10021         if (TREE_CODE (r) == VAR_DECL)
10022           {
10023             /* Even if the original location is out of scope, the
10024                newly substituted one is not.  */
10025             DECL_DEAD_FOR_LOCAL (r) = 0;
10026             DECL_INITIALIZED_P (r) = 0;
10027             DECL_TEMPLATE_INSTANTIATED (r) = 0;
10028             if (type == error_mark_node)
10029               RETURN (error_mark_node);
10030             if (TREE_CODE (type) == FUNCTION_TYPE)
10031               {
10032                 /* It may seem that this case cannot occur, since:
10033
10034                      typedef void f();
10035                      void g() { f x; }
10036
10037                    declares a function, not a variable.  However:
10038       
10039                      typedef void f();
10040                      template <typename T> void g() { T t; }
10041                      template void g<f>();
10042
10043                    is an attempt to declare a variable with function
10044                    type.  */
10045                 error ("variable %qD has function type",
10046                        /* R is not yet sufficiently initialized, so we
10047                           just use its name.  */
10048                        DECL_NAME (r));
10049                 RETURN (error_mark_node);
10050               }
10051             type = complete_type (type);
10052             /* Wait until cp_finish_decl to set this again, to handle
10053                circular dependency (template/instantiate6.C). */
10054             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
10055             type = check_var_type (DECL_NAME (r), type);
10056
10057             if (DECL_HAS_VALUE_EXPR_P (t))
10058               {
10059                 tree ve = DECL_VALUE_EXPR (t);
10060                 ve = tsubst_expr (ve, args, complain, in_decl,
10061                                   /*constant_expression_p=*/false);
10062                 SET_DECL_VALUE_EXPR (r, ve);
10063               }
10064           }
10065         else if (DECL_SELF_REFERENCE_P (t))
10066           SET_DECL_SELF_REFERENCE_P (r);
10067         TREE_TYPE (r) = type;
10068         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10069         DECL_CONTEXT (r) = ctx;
10070         /* Clear out the mangled name and RTL for the instantiation.  */
10071         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10072         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10073           SET_DECL_RTL (r, NULL);
10074         /* The initializer must not be expanded until it is required;
10075            see [temp.inst].  */
10076         DECL_INITIAL (r) = NULL_TREE;
10077         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10078           SET_DECL_RTL (r, NULL);
10079         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
10080         if (TREE_CODE (r) == VAR_DECL)
10081           {
10082             /* Possibly limit visibility based on template args.  */
10083             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10084             if (DECL_VISIBILITY_SPECIFIED (t))
10085               {
10086                 DECL_VISIBILITY_SPECIFIED (r) = 0;
10087                 DECL_ATTRIBUTES (r)
10088                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10089               }
10090             determine_visibility (r);
10091           }
10092
10093         if (!local_p)
10094           {
10095             /* A static data member declaration is always marked
10096                external when it is declared in-class, even if an
10097                initializer is present.  We mimic the non-template
10098                processing here.  */
10099             DECL_EXTERNAL (r) = 1;
10100
10101             register_specialization (r, gen_tmpl, argvec, false, hash);
10102             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
10103             SET_DECL_IMPLICIT_INSTANTIATION (r);
10104           }
10105         else if (cp_unevaluated_operand)
10106           {
10107             /* We're substituting this var in a decltype outside of its
10108                scope, such as for a lambda return type.  Don't add it to
10109                local_specializations, do perform auto deduction.  */
10110             tree auto_node = type_uses_auto (type);
10111             tree init
10112               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
10113                              /*constant_expression_p=*/false);
10114
10115             if (auto_node && init)
10116               {
10117                 init = resolve_nondeduced_context (init);
10118                 if (describable_type (init))
10119                   {
10120                     type = do_auto_deduction (type, init, auto_node);
10121                     TREE_TYPE (r) = type;
10122                   }
10123               }
10124           }
10125         else
10126           register_local_specialization (r, t);
10127
10128         DECL_CHAIN (r) = NULL_TREE;
10129
10130         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
10131                                         /*flags=*/0,
10132                                         args, complain, in_decl);
10133
10134         /* Preserve a typedef that names a type.  */
10135         if (is_typedef_decl (r))
10136           {
10137             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
10138             set_underlying_type (r);
10139           }
10140
10141         layout_decl (r, 0);
10142       }
10143       break;
10144
10145     default:
10146       gcc_unreachable ();
10147     }
10148 #undef RETURN
10149
10150  out:
10151   /* Restore the file and line information.  */
10152   input_location = saved_loc;
10153
10154   return r;
10155 }
10156
10157 /* Substitute into the ARG_TYPES of a function type.  */
10158
10159 static tree
10160 tsubst_arg_types (tree arg_types,
10161                   tree args,
10162                   tsubst_flags_t complain,
10163                   tree in_decl)
10164 {
10165   tree remaining_arg_types;
10166   tree type = NULL_TREE;
10167   int i = 1;
10168   tree expanded_args = NULL_TREE;
10169   tree default_arg;
10170
10171   if (!arg_types || arg_types == void_list_node)
10172     return arg_types;
10173
10174   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
10175                                           args, complain, in_decl);
10176   if (remaining_arg_types == error_mark_node)
10177     return error_mark_node;
10178
10179   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
10180     {
10181       /* For a pack expansion, perform substitution on the
10182          entire expression. Later on, we'll handle the arguments
10183          one-by-one.  */
10184       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
10185                                             args, complain, in_decl);
10186
10187       if (TREE_CODE (expanded_args) == TREE_VEC)
10188         /* So that we'll spin through the parameters, one by one.  */
10189         i = TREE_VEC_LENGTH (expanded_args);
10190       else
10191         {
10192           /* We only partially substituted into the parameter
10193              pack. Our type is TYPE_PACK_EXPANSION.  */
10194           type = expanded_args;
10195           expanded_args = NULL_TREE;
10196         }
10197     }
10198
10199   while (i > 0) {
10200     --i;
10201     
10202     if (expanded_args)
10203       type = TREE_VEC_ELT (expanded_args, i);
10204     else if (!type)
10205       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
10206
10207     if (type == error_mark_node)
10208       return error_mark_node;
10209     if (VOID_TYPE_P (type))
10210       {
10211         if (complain & tf_error)
10212           {
10213             error ("invalid parameter type %qT", type);
10214             if (in_decl)
10215               error ("in declaration %q+D", in_decl);
10216           }
10217         return error_mark_node;
10218     }
10219     
10220     /* Do array-to-pointer, function-to-pointer conversion, and ignore
10221        top-level qualifiers as required.  */
10222     type = TYPE_MAIN_VARIANT (type_decays_to (type));
10223
10224     /* We do not substitute into default arguments here.  The standard
10225        mandates that they be instantiated only when needed, which is
10226        done in build_over_call.  */
10227     default_arg = TREE_PURPOSE (arg_types);
10228
10229     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
10230       {
10231         /* We've instantiated a template before its default arguments
10232            have been parsed.  This can happen for a nested template
10233            class, and is not an error unless we require the default
10234            argument in a call of this function.  */
10235         remaining_arg_types = 
10236           tree_cons (default_arg, type, remaining_arg_types);
10237         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
10238                        remaining_arg_types);
10239       }
10240     else
10241       remaining_arg_types = 
10242         hash_tree_cons (default_arg, type, remaining_arg_types);
10243   }
10244         
10245   return remaining_arg_types;
10246 }
10247
10248 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
10249    *not* handle the exception-specification for FNTYPE, because the
10250    initial substitution of explicitly provided template parameters
10251    during argument deduction forbids substitution into the
10252    exception-specification:
10253
10254      [temp.deduct]
10255
10256      All references in the function type of the function template to  the
10257      corresponding template parameters are replaced by the specified tem-
10258      plate argument values.  If a substitution in a template parameter or
10259      in  the function type of the function template results in an invalid
10260      type, type deduction fails.  [Note: The equivalent  substitution  in
10261      exception specifications is done only when the function is instanti-
10262      ated, at which point a program is  ill-formed  if  the  substitution
10263      results in an invalid type.]  */
10264
10265 static tree
10266 tsubst_function_type (tree t,
10267                       tree args,
10268                       tsubst_flags_t complain,
10269                       tree in_decl)
10270 {
10271   tree return_type;
10272   tree arg_types;
10273   tree fntype;
10274
10275   /* The TYPE_CONTEXT is not used for function/method types.  */
10276   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
10277
10278   /* Substitute the return type.  */
10279   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10280   if (return_type == error_mark_node)
10281     return error_mark_node;
10282   /* The standard does not presently indicate that creation of a
10283      function type with an invalid return type is a deduction failure.
10284      However, that is clearly analogous to creating an array of "void"
10285      or a reference to a reference.  This is core issue #486.  */
10286   if (TREE_CODE (return_type) == ARRAY_TYPE
10287       || TREE_CODE (return_type) == FUNCTION_TYPE)
10288     {
10289       if (complain & tf_error)
10290         {
10291           if (TREE_CODE (return_type) == ARRAY_TYPE)
10292             error ("function returning an array");
10293           else
10294             error ("function returning a function");
10295         }
10296       return error_mark_node;
10297     }
10298
10299   /* Substitute the argument types.  */
10300   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
10301                                 complain, in_decl);
10302   if (arg_types == error_mark_node)
10303     return error_mark_node;
10304
10305   /* Construct a new type node and return it.  */
10306   if (TREE_CODE (t) == FUNCTION_TYPE)
10307     {
10308       fntype = build_function_type (return_type, arg_types);
10309       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
10310     }
10311   else
10312     {
10313       tree r = TREE_TYPE (TREE_VALUE (arg_types));
10314       if (! MAYBE_CLASS_TYPE_P (r))
10315         {
10316           /* [temp.deduct]
10317
10318              Type deduction may fail for any of the following
10319              reasons:
10320
10321              -- Attempting to create "pointer to member of T" when T
10322              is not a class type.  */
10323           if (complain & tf_error)
10324             error ("creating pointer to member function of non-class type %qT",
10325                       r);
10326           return error_mark_node;
10327         }
10328
10329       fntype = build_method_type_directly (r, return_type,
10330                                            TREE_CHAIN (arg_types));
10331     }
10332   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
10333
10334   return fntype;
10335 }
10336
10337 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
10338    ARGS into that specification, and return the substituted
10339    specification.  If there is no specification, return NULL_TREE.  */
10340
10341 static tree
10342 tsubst_exception_specification (tree fntype,
10343                                 tree args,
10344                                 tsubst_flags_t complain,
10345                                 tree in_decl)
10346 {
10347   tree specs;
10348   tree new_specs;
10349
10350   specs = TYPE_RAISES_EXCEPTIONS (fntype);
10351   new_specs = NULL_TREE;
10352   if (specs && TREE_PURPOSE (specs))
10353     {
10354       /* A noexcept-specifier.  */
10355       new_specs = tsubst_copy_and_build
10356         (TREE_PURPOSE (specs), args, complain, in_decl, /*function_p=*/false,
10357          /*integral_constant_expression_p=*/true);
10358       new_specs = build_noexcept_spec (new_specs, complain);
10359     }
10360   else if (specs)
10361     {
10362       if (! TREE_VALUE (specs))
10363         new_specs = specs;
10364       else
10365         while (specs)
10366           {
10367             tree spec;
10368             int i, len = 1;
10369             tree expanded_specs = NULL_TREE;
10370
10371             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
10372               {
10373                 /* Expand the pack expansion type.  */
10374                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
10375                                                        args, complain,
10376                                                        in_decl);
10377
10378                 if (expanded_specs == error_mark_node)
10379                   return error_mark_node;
10380                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
10381                   len = TREE_VEC_LENGTH (expanded_specs);
10382                 else
10383                   {
10384                     /* We're substituting into a member template, so
10385                        we got a TYPE_PACK_EXPANSION back.  Add that
10386                        expansion and move on.  */
10387                     gcc_assert (TREE_CODE (expanded_specs) 
10388                                 == TYPE_PACK_EXPANSION);
10389                     new_specs = add_exception_specifier (new_specs,
10390                                                          expanded_specs,
10391                                                          complain);
10392                     specs = TREE_CHAIN (specs);
10393                     continue;
10394                   }
10395               }
10396
10397             for (i = 0; i < len; ++i)
10398               {
10399                 if (expanded_specs)
10400                   spec = TREE_VEC_ELT (expanded_specs, i);
10401                 else
10402                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
10403                 if (spec == error_mark_node)
10404                   return spec;
10405                 new_specs = add_exception_specifier (new_specs, spec, 
10406                                                      complain);
10407               }
10408
10409             specs = TREE_CHAIN (specs);
10410           }
10411     }
10412   return new_specs;
10413 }
10414
10415 /* Take the tree structure T and replace template parameters used
10416    therein with the argument vector ARGS.  IN_DECL is an associated
10417    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
10418    Issue error and warning messages under control of COMPLAIN.  Note
10419    that we must be relatively non-tolerant of extensions here, in
10420    order to preserve conformance; if we allow substitutions that
10421    should not be allowed, we may allow argument deductions that should
10422    not succeed, and therefore report ambiguous overload situations
10423    where there are none.  In theory, we could allow the substitution,
10424    but indicate that it should have failed, and allow our caller to
10425    make sure that the right thing happens, but we don't try to do this
10426    yet.
10427
10428    This function is used for dealing with types, decls and the like;
10429    for expressions, use tsubst_expr or tsubst_copy.  */
10430
10431 tree
10432 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10433 {
10434   enum tree_code code;
10435   tree type, r;
10436
10437   if (t == NULL_TREE || t == error_mark_node
10438       || t == integer_type_node
10439       || t == void_type_node
10440       || t == char_type_node
10441       || t == unknown_type_node
10442       || TREE_CODE (t) == NAMESPACE_DECL
10443       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
10444     return t;
10445
10446   if (DECL_P (t))
10447     return tsubst_decl (t, args, complain);
10448
10449   if (args == NULL_TREE)
10450     return t;
10451
10452   code = TREE_CODE (t);
10453
10454   if (code == IDENTIFIER_NODE)
10455     type = IDENTIFIER_TYPE_VALUE (t);
10456   else
10457     type = TREE_TYPE (t);
10458
10459   gcc_assert (type != unknown_type_node);
10460
10461   /* Reuse typedefs.  We need to do this to handle dependent attributes,
10462      such as attribute aligned.  */
10463   if (TYPE_P (t)
10464       && typedef_variant_p (t))
10465     {
10466       tree decl = TYPE_NAME (t);
10467       
10468       if (DECL_CLASS_SCOPE_P (decl)
10469           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
10470           && uses_template_parms (DECL_CONTEXT (decl)))
10471         {
10472           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10473           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
10474           r = retrieve_specialization (tmpl, gen_args, 0);
10475         }
10476       else if (DECL_FUNCTION_SCOPE_P (decl)
10477                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10478                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10479         r = retrieve_local_specialization (decl);
10480       else
10481         /* The typedef is from a non-template context.  */
10482         return t;
10483
10484       if (r)
10485         {
10486           r = TREE_TYPE (r);
10487           r = cp_build_qualified_type_real
10488             (r, cp_type_quals (t) | cp_type_quals (r),
10489              complain | tf_ignore_bad_quals);
10490           return r;
10491         }
10492       /* Else we must be instantiating the typedef, so fall through.  */
10493     }
10494
10495   if (type
10496       && code != TYPENAME_TYPE
10497       && code != TEMPLATE_TYPE_PARM
10498       && code != IDENTIFIER_NODE
10499       && code != FUNCTION_TYPE
10500       && code != METHOD_TYPE)
10501     type = tsubst (type, args, complain, in_decl);
10502   if (type == error_mark_node)
10503     return error_mark_node;
10504
10505   switch (code)
10506     {
10507     case RECORD_TYPE:
10508     case UNION_TYPE:
10509     case ENUMERAL_TYPE:
10510       return tsubst_aggr_type (t, args, complain, in_decl,
10511                                /*entering_scope=*/0);
10512
10513     case ERROR_MARK:
10514     case IDENTIFIER_NODE:
10515     case VOID_TYPE:
10516     case REAL_TYPE:
10517     case COMPLEX_TYPE:
10518     case VECTOR_TYPE:
10519     case BOOLEAN_TYPE:
10520     case NULLPTR_TYPE:
10521     case LANG_TYPE:
10522       return t;
10523
10524     case INTEGER_TYPE:
10525       if (t == integer_type_node)
10526         return t;
10527
10528       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10529           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10530         return t;
10531
10532       {
10533         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10534
10535         max = tsubst_expr (omax, args, complain, in_decl,
10536                            /*integral_constant_expression_p=*/false);
10537
10538         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10539            needed.  */
10540         if (TREE_CODE (max) == NOP_EXPR
10541             && TREE_SIDE_EFFECTS (omax)
10542             && !TREE_TYPE (max))
10543           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10544
10545         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10546            with TREE_SIDE_EFFECTS that indicates this is not an integral
10547            constant expression.  */
10548         if (processing_template_decl
10549             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10550           {
10551             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10552             TREE_SIDE_EFFECTS (max) = 1;
10553           }
10554
10555         return compute_array_index_type (NULL_TREE, max, complain);
10556       }
10557
10558     case TEMPLATE_TYPE_PARM:
10559     case TEMPLATE_TEMPLATE_PARM:
10560     case BOUND_TEMPLATE_TEMPLATE_PARM:
10561     case TEMPLATE_PARM_INDEX:
10562       {
10563         int idx;
10564         int level;
10565         int levels;
10566         tree arg = NULL_TREE;
10567
10568         r = NULL_TREE;
10569
10570         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10571         template_parm_level_and_index (t, &level, &idx); 
10572
10573         levels = TMPL_ARGS_DEPTH (args);
10574         if (level <= levels)
10575           {
10576             arg = TMPL_ARG (args, level, idx);
10577
10578             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10579               /* See through ARGUMENT_PACK_SELECT arguments. */
10580               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10581           }
10582
10583         if (arg == error_mark_node)
10584           return error_mark_node;
10585         else if (arg != NULL_TREE)
10586           {
10587             if (ARGUMENT_PACK_P (arg))
10588               /* If ARG is an argument pack, we don't actually want to
10589                  perform a substitution here, because substitutions
10590                  for argument packs are only done
10591                  element-by-element. We can get to this point when
10592                  substituting the type of a non-type template
10593                  parameter pack, when that type actually contains
10594                  template parameter packs from an outer template, e.g.,
10595
10596                  template<typename... Types> struct A {
10597                    template<Types... Values> struct B { };
10598                  };  */
10599               return t;
10600
10601             if (code == TEMPLATE_TYPE_PARM)
10602               {
10603                 int quals;
10604                 gcc_assert (TYPE_P (arg));
10605
10606                 quals = cp_type_quals (arg) | cp_type_quals (t);
10607                   
10608                 return cp_build_qualified_type_real
10609                   (arg, quals, complain | tf_ignore_bad_quals);
10610               }
10611             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10612               {
10613                 /* We are processing a type constructed from a
10614                    template template parameter.  */
10615                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10616                                       args, complain, in_decl);
10617                 if (argvec == error_mark_node)
10618                   return error_mark_node;
10619
10620                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10621                    are resolving nested-types in the signature of a
10622                    member function templates.  Otherwise ARG is a
10623                    TEMPLATE_DECL and is the real template to be
10624                    instantiated.  */
10625                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10626                   arg = TYPE_NAME (arg);
10627
10628                 r = lookup_template_class (arg,
10629                                            argvec, in_decl,
10630                                            DECL_CONTEXT (arg),
10631                                             /*entering_scope=*/0,
10632                                            complain);
10633                 return cp_build_qualified_type_real
10634                   (r, cp_type_quals (t), complain);
10635               }
10636             else
10637               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10638               return unshare_expr (arg);
10639           }
10640
10641         if (level == 1)
10642           /* This can happen during the attempted tsubst'ing in
10643              unify.  This means that we don't yet have any information
10644              about the template parameter in question.  */
10645           return t;
10646
10647         /* If we get here, we must have been looking at a parm for a
10648            more deeply nested template.  Make a new version of this
10649            template parameter, but with a lower level.  */
10650         switch (code)
10651           {
10652           case TEMPLATE_TYPE_PARM:
10653           case TEMPLATE_TEMPLATE_PARM:
10654           case BOUND_TEMPLATE_TEMPLATE_PARM:
10655             if (cp_type_quals (t))
10656               {
10657                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10658                 r = cp_build_qualified_type_real
10659                   (r, cp_type_quals (t),
10660                    complain | (code == TEMPLATE_TYPE_PARM
10661                                ? tf_ignore_bad_quals : 0));
10662               }
10663             else
10664               {
10665                 r = copy_type (t);
10666                 TEMPLATE_TYPE_PARM_INDEX (r)
10667                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10668                                                 r, levels, args, complain);
10669                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10670                 TYPE_MAIN_VARIANT (r) = r;
10671                 TYPE_POINTER_TO (r) = NULL_TREE;
10672                 TYPE_REFERENCE_TO (r) = NULL_TREE;
10673
10674                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10675                   /* We have reduced the level of the template
10676                      template parameter, but not the levels of its
10677                      template parameters, so canonical_type_parameter
10678                      will not be able to find the canonical template
10679                      template parameter for this level. Thus, we
10680                      require structural equality checking to compare
10681                      TEMPLATE_TEMPLATE_PARMs. */
10682                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10683                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10684                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10685                 else
10686                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
10687
10688                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10689                   {
10690                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10691                                           complain, in_decl);
10692                     if (argvec == error_mark_node)
10693                       return error_mark_node;
10694
10695                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10696                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10697                   }
10698               }
10699             break;
10700
10701           case TEMPLATE_PARM_INDEX:
10702             r = reduce_template_parm_level (t, type, levels, args, complain);
10703             break;
10704
10705           default:
10706             gcc_unreachable ();
10707           }
10708
10709         return r;
10710       }
10711
10712     case TREE_LIST:
10713       {
10714         tree purpose, value, chain;
10715
10716         if (t == void_list_node)
10717           return t;
10718
10719         purpose = TREE_PURPOSE (t);
10720         if (purpose)
10721           {
10722             purpose = tsubst (purpose, args, complain, in_decl);
10723             if (purpose == error_mark_node)
10724               return error_mark_node;
10725           }
10726         value = TREE_VALUE (t);
10727         if (value)
10728           {
10729             value = tsubst (value, args, complain, in_decl);
10730             if (value == error_mark_node)
10731               return error_mark_node;
10732           }
10733         chain = TREE_CHAIN (t);
10734         if (chain && chain != void_type_node)
10735           {
10736             chain = tsubst (chain, args, complain, in_decl);
10737             if (chain == error_mark_node)
10738               return error_mark_node;
10739           }
10740         if (purpose == TREE_PURPOSE (t)
10741             && value == TREE_VALUE (t)
10742             && chain == TREE_CHAIN (t))
10743           return t;
10744         return hash_tree_cons (purpose, value, chain);
10745       }
10746
10747     case TREE_BINFO:
10748       /* We should never be tsubsting a binfo.  */
10749       gcc_unreachable ();
10750
10751     case TREE_VEC:
10752       /* A vector of template arguments.  */
10753       gcc_assert (!type);
10754       return tsubst_template_args (t, args, complain, in_decl);
10755
10756     case POINTER_TYPE:
10757     case REFERENCE_TYPE:
10758       {
10759         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10760           return t;
10761
10762         /* [temp.deduct]
10763
10764            Type deduction may fail for any of the following
10765            reasons:
10766
10767            -- Attempting to create a pointer to reference type.
10768            -- Attempting to create a reference to a reference type or
10769               a reference to void.
10770
10771           Core issue 106 says that creating a reference to a reference
10772           during instantiation is no longer a cause for failure. We
10773           only enforce this check in strict C++98 mode.  */
10774         if ((TREE_CODE (type) == REFERENCE_TYPE
10775              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10776             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10777           {
10778             static location_t last_loc;
10779
10780             /* We keep track of the last time we issued this error
10781                message to avoid spewing a ton of messages during a
10782                single bad template instantiation.  */
10783             if (complain & tf_error
10784                 && last_loc != input_location)
10785               {
10786                 if (TREE_CODE (type) == VOID_TYPE)
10787                   error ("forming reference to void");
10788                else if (code == POINTER_TYPE)
10789                  error ("forming pointer to reference type %qT", type);
10790                else
10791                   error ("forming reference to reference type %qT", type);
10792                 last_loc = input_location;
10793               }
10794
10795             return error_mark_node;
10796           }
10797         else if (code == POINTER_TYPE)
10798           {
10799             r = build_pointer_type (type);
10800             if (TREE_CODE (type) == METHOD_TYPE)
10801               r = build_ptrmemfunc_type (r);
10802           }
10803         else if (TREE_CODE (type) == REFERENCE_TYPE)
10804           /* In C++0x, during template argument substitution, when there is an
10805              attempt to create a reference to a reference type, reference
10806              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10807
10808              "If a template-argument for a template-parameter T names a type
10809              that is a reference to a type A, an attempt to create the type
10810              'lvalue reference to cv T' creates the type 'lvalue reference to
10811              A,' while an attempt to create the type type rvalue reference to
10812              cv T' creates the type T"
10813           */
10814           r = cp_build_reference_type
10815               (TREE_TYPE (type),
10816                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10817         else
10818           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10819         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
10820
10821         if (r != error_mark_node)
10822           /* Will this ever be needed for TYPE_..._TO values?  */
10823           layout_type (r);
10824
10825         return r;
10826       }
10827     case OFFSET_TYPE:
10828       {
10829         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10830         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10831           {
10832             /* [temp.deduct]
10833
10834                Type deduction may fail for any of the following
10835                reasons:
10836
10837                -- Attempting to create "pointer to member of T" when T
10838                   is not a class type.  */
10839             if (complain & tf_error)
10840               error ("creating pointer to member of non-class type %qT", r);
10841             return error_mark_node;
10842           }
10843         if (TREE_CODE (type) == REFERENCE_TYPE)
10844           {
10845             if (complain & tf_error)
10846               error ("creating pointer to member reference type %qT", type);
10847             return error_mark_node;
10848           }
10849         if (TREE_CODE (type) == VOID_TYPE)
10850           {
10851             if (complain & tf_error)
10852               error ("creating pointer to member of type void");
10853             return error_mark_node;
10854           }
10855         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10856         if (TREE_CODE (type) == FUNCTION_TYPE)
10857           {
10858             /* The type of the implicit object parameter gets its
10859                cv-qualifiers from the FUNCTION_TYPE. */
10860             tree memptr;
10861             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
10862             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10863             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10864                                                  complain);
10865           }
10866         else
10867           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10868                                                cp_type_quals (t),
10869                                                complain);
10870       }
10871     case FUNCTION_TYPE:
10872     case METHOD_TYPE:
10873       {
10874         tree fntype;
10875         tree specs;
10876         fntype = tsubst_function_type (t, args, complain, in_decl);
10877         if (fntype == error_mark_node)
10878           return error_mark_node;
10879
10880         /* Substitute the exception specification.  */
10881         specs = tsubst_exception_specification (t, args, complain,
10882                                                 in_decl);
10883         if (specs == error_mark_node)
10884           return error_mark_node;
10885         if (specs)
10886           fntype = build_exception_variant (fntype, specs);
10887         return fntype;
10888       }
10889     case ARRAY_TYPE:
10890       {
10891         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10892         if (domain == error_mark_node)
10893           return error_mark_node;
10894
10895         /* As an optimization, we avoid regenerating the array type if
10896            it will obviously be the same as T.  */
10897         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10898           return t;
10899
10900         /* These checks should match the ones in grokdeclarator.
10901
10902            [temp.deduct]
10903
10904            The deduction may fail for any of the following reasons:
10905
10906            -- Attempting to create an array with an element type that
10907               is void, a function type, or a reference type, or [DR337]
10908               an abstract class type.  */
10909         if (TREE_CODE (type) == VOID_TYPE
10910             || TREE_CODE (type) == FUNCTION_TYPE
10911             || TREE_CODE (type) == REFERENCE_TYPE)
10912           {
10913             if (complain & tf_error)
10914               error ("creating array of %qT", type);
10915             return error_mark_node;
10916           }
10917         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10918           {
10919             if (complain & tf_error)
10920               error ("creating array of %qT, which is an abstract class type",
10921                      type);
10922             return error_mark_node;
10923           }
10924
10925         r = build_cplus_array_type (type, domain);
10926
10927         if (TYPE_USER_ALIGN (t))
10928           {
10929             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10930             TYPE_USER_ALIGN (r) = 1;
10931           }
10932
10933         return r;
10934       }
10935
10936     case TYPENAME_TYPE:
10937       {
10938         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10939                                      in_decl, /*entering_scope=*/1);
10940         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10941                               complain, in_decl);
10942
10943         if (ctx == error_mark_node || f == error_mark_node)
10944           return error_mark_node;
10945
10946         if (!MAYBE_CLASS_TYPE_P (ctx))
10947           {
10948             if (complain & tf_error)
10949               error ("%qT is not a class, struct, or union type", ctx);
10950             return error_mark_node;
10951           }
10952         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10953           {
10954             /* Normally, make_typename_type does not require that the CTX
10955                have complete type in order to allow things like:
10956
10957                  template <class T> struct S { typename S<T>::X Y; };
10958
10959                But, such constructs have already been resolved by this
10960                point, so here CTX really should have complete type, unless
10961                it's a partial instantiation.  */
10962             ctx = complete_type (ctx);
10963             if (!COMPLETE_TYPE_P (ctx))
10964               {
10965                 if (complain & tf_error)
10966                   cxx_incomplete_type_error (NULL_TREE, ctx);
10967                 return error_mark_node;
10968               }
10969           }
10970
10971         f = make_typename_type (ctx, f, typename_type,
10972                                 (complain & tf_error) | tf_keep_type_decl);
10973         if (f == error_mark_node)
10974           return f;
10975         if (TREE_CODE (f) == TYPE_DECL)
10976           {
10977             complain |= tf_ignore_bad_quals;
10978             f = TREE_TYPE (f);
10979           }
10980
10981         if (TREE_CODE (f) != TYPENAME_TYPE)
10982           {
10983             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10984               {
10985                 if (complain & tf_error)
10986                   error ("%qT resolves to %qT, which is not an enumeration type",
10987                          t, f);
10988                 else
10989                   return error_mark_node;
10990               }
10991             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10992               {
10993                 if (complain & tf_error)
10994                   error ("%qT resolves to %qT, which is is not a class type",
10995                          t, f);
10996                 else
10997                   return error_mark_node;
10998               }
10999           }
11000
11001         return cp_build_qualified_type_real
11002           (f, cp_type_quals (f) | cp_type_quals (t), complain);
11003       }
11004
11005     case UNBOUND_CLASS_TEMPLATE:
11006       {
11007         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11008                                      in_decl, /*entering_scope=*/1);
11009         tree name = TYPE_IDENTIFIER (t);
11010         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
11011
11012         if (ctx == error_mark_node || name == error_mark_node)
11013           return error_mark_node;
11014
11015         if (parm_list)
11016           parm_list = tsubst_template_parms (parm_list, args, complain);
11017         return make_unbound_class_template (ctx, name, parm_list, complain);
11018       }
11019
11020     case TYPEOF_TYPE:
11021       {
11022         tree type;
11023
11024         ++cp_unevaluated_operand;
11025         ++c_inhibit_evaluation_warnings;
11026
11027         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
11028                             complain, in_decl,
11029                             /*integral_constant_expression_p=*/false);
11030
11031         --cp_unevaluated_operand;
11032         --c_inhibit_evaluation_warnings;
11033
11034         type = finish_typeof (type);
11035         return cp_build_qualified_type_real (type,
11036                                              cp_type_quals (t)
11037                                              | cp_type_quals (type),
11038                                              complain);
11039       }
11040
11041     case DECLTYPE_TYPE:
11042       {
11043         tree type;
11044
11045         ++cp_unevaluated_operand;
11046         ++c_inhibit_evaluation_warnings;
11047
11048         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
11049                             complain, in_decl,
11050                             /*integral_constant_expression_p=*/false);
11051
11052         --cp_unevaluated_operand;
11053         --c_inhibit_evaluation_warnings;
11054
11055         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
11056           type = lambda_capture_field_type (type);
11057         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
11058           type = lambda_return_type (type);
11059         else
11060           type = finish_decltype_type
11061             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t), complain);
11062         return cp_build_qualified_type_real (type,
11063                                              cp_type_quals (t)
11064                                              | cp_type_quals (type),
11065                                              complain);
11066       }
11067
11068     case UNDERLYING_TYPE:
11069       {
11070         tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
11071                             complain, in_decl);
11072         return finish_underlying_type (type);
11073       }
11074
11075     case TYPE_ARGUMENT_PACK:
11076     case NONTYPE_ARGUMENT_PACK:
11077       {
11078         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
11079         tree packed_out = 
11080           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
11081                                 args,
11082                                 complain,
11083                                 in_decl);
11084         SET_ARGUMENT_PACK_ARGS (r, packed_out);
11085
11086         /* For template nontype argument packs, also substitute into
11087            the type.  */
11088         if (code == NONTYPE_ARGUMENT_PACK)
11089           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
11090
11091         return r;
11092       }
11093       break;
11094
11095     case INTEGER_CST:
11096     case REAL_CST:
11097     case STRING_CST:
11098     case PLUS_EXPR:
11099     case MINUS_EXPR:
11100     case NEGATE_EXPR:
11101     case NOP_EXPR:
11102     case INDIRECT_REF:
11103     case ADDR_EXPR:
11104     case CALL_EXPR:
11105     case ARRAY_REF:
11106     case SCOPE_REF:
11107       /* We should use one of the expression tsubsts for these codes.  */
11108       gcc_unreachable ();
11109
11110     default:
11111       sorry ("use of %qs in template", tree_code_name [(int) code]);
11112       return error_mark_node;
11113     }
11114 }
11115
11116 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
11117    type of the expression on the left-hand side of the "." or "->"
11118    operator.  */
11119
11120 static tree
11121 tsubst_baselink (tree baselink, tree object_type,
11122                  tree args, tsubst_flags_t complain, tree in_decl)
11123 {
11124     tree name;
11125     tree qualifying_scope;
11126     tree fns;
11127     tree optype;
11128     tree template_args = 0;
11129     bool template_id_p = false;
11130
11131     /* A baselink indicates a function from a base class.  Both the
11132        BASELINK_ACCESS_BINFO and the base class referenced may
11133        indicate bases of the template class, rather than the
11134        instantiated class.  In addition, lookups that were not
11135        ambiguous before may be ambiguous now.  Therefore, we perform
11136        the lookup again.  */
11137     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
11138     qualifying_scope = tsubst (qualifying_scope, args,
11139                                complain, in_decl);
11140     fns = BASELINK_FUNCTIONS (baselink);
11141     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
11142     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11143       {
11144         template_id_p = true;
11145         template_args = TREE_OPERAND (fns, 1);
11146         fns = TREE_OPERAND (fns, 0);
11147         if (template_args)
11148           template_args = tsubst_template_args (template_args, args,
11149                                                 complain, in_decl);
11150       }
11151     name = DECL_NAME (get_first_fn (fns));
11152     if (IDENTIFIER_TYPENAME_P (name))
11153       name = mangle_conv_op_name_for_type (optype);
11154     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
11155     if (!baselink)
11156       return error_mark_node;
11157
11158     /* If lookup found a single function, mark it as used at this
11159        point.  (If it lookup found multiple functions the one selected
11160        later by overload resolution will be marked as used at that
11161        point.)  */
11162     if (BASELINK_P (baselink))
11163       fns = BASELINK_FUNCTIONS (baselink);
11164     if (!template_id_p && !really_overloaded_fn (fns))
11165       mark_used (OVL_CURRENT (fns));
11166
11167     /* Add back the template arguments, if present.  */
11168     if (BASELINK_P (baselink) && template_id_p)
11169       BASELINK_FUNCTIONS (baselink)
11170         = build_nt (TEMPLATE_ID_EXPR,
11171                     BASELINK_FUNCTIONS (baselink),
11172                     template_args);
11173     /* Update the conversion operator type.  */
11174     BASELINK_OPTYPE (baselink) = optype;
11175
11176     if (!object_type)
11177       object_type = current_class_type;
11178     return adjust_result_of_qualified_name_lookup (baselink,
11179                                                    qualifying_scope,
11180                                                    object_type);
11181 }
11182
11183 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
11184    true if the qualified-id will be a postfix-expression in-and-of
11185    itself; false if more of the postfix-expression follows the
11186    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
11187    of "&".  */
11188
11189 static tree
11190 tsubst_qualified_id (tree qualified_id, tree args,
11191                      tsubst_flags_t complain, tree in_decl,
11192                      bool done, bool address_p)
11193 {
11194   tree expr;
11195   tree scope;
11196   tree name;
11197   bool is_template;
11198   tree template_args;
11199
11200   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
11201
11202   /* Figure out what name to look up.  */
11203   name = TREE_OPERAND (qualified_id, 1);
11204   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
11205     {
11206       is_template = true;
11207       template_args = TREE_OPERAND (name, 1);
11208       if (template_args)
11209         template_args = tsubst_template_args (template_args, args,
11210                                               complain, in_decl);
11211       name = TREE_OPERAND (name, 0);
11212     }
11213   else
11214     {
11215       is_template = false;
11216       template_args = NULL_TREE;
11217     }
11218
11219   /* Substitute into the qualifying scope.  When there are no ARGS, we
11220      are just trying to simplify a non-dependent expression.  In that
11221      case the qualifying scope may be dependent, and, in any case,
11222      substituting will not help.  */
11223   scope = TREE_OPERAND (qualified_id, 0);
11224   if (args)
11225     {
11226       scope = tsubst (scope, args, complain, in_decl);
11227       expr = tsubst_copy (name, args, complain, in_decl);
11228     }
11229   else
11230     expr = name;
11231
11232   if (dependent_scope_p (scope))
11233     return build_qualified_name (NULL_TREE, scope, expr,
11234                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
11235
11236   if (!BASELINK_P (name) && !DECL_P (expr))
11237     {
11238       if (TREE_CODE (expr) == BIT_NOT_EXPR)
11239         {
11240           /* A BIT_NOT_EXPR is used to represent a destructor.  */
11241           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
11242             {
11243               error ("qualifying type %qT does not match destructor name ~%qT",
11244                      scope, TREE_OPERAND (expr, 0));
11245               expr = error_mark_node;
11246             }
11247           else
11248             expr = lookup_qualified_name (scope, complete_dtor_identifier,
11249                                           /*is_type_p=*/0, false);
11250         }
11251       else
11252         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
11253       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
11254                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
11255         {
11256           if (complain & tf_error)
11257             {
11258               error ("dependent-name %qE is parsed as a non-type, but "
11259                      "instantiation yields a type", qualified_id);
11260               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
11261             }
11262           return error_mark_node;
11263         }
11264     }
11265
11266   if (DECL_P (expr))
11267     {
11268       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
11269                                            scope);
11270       /* Remember that there was a reference to this entity.  */
11271       mark_used (expr);
11272     }
11273
11274   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
11275     {
11276       if (complain & tf_error)
11277         qualified_name_lookup_error (scope,
11278                                      TREE_OPERAND (qualified_id, 1),
11279                                      expr, input_location);
11280       return error_mark_node;
11281     }
11282
11283   if (is_template)
11284     expr = lookup_template_function (expr, template_args);
11285
11286   if (expr == error_mark_node && complain & tf_error)
11287     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
11288                                  expr, input_location);
11289   else if (TYPE_P (scope))
11290     {
11291       expr = (adjust_result_of_qualified_name_lookup
11292               (expr, scope, current_class_type));
11293       expr = (finish_qualified_id_expr
11294               (scope, expr, done, address_p,
11295                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
11296                /*template_arg_p=*/false));
11297     }
11298
11299   /* Expressions do not generally have reference type.  */
11300   if (TREE_CODE (expr) != SCOPE_REF
11301       /* However, if we're about to form a pointer-to-member, we just
11302          want the referenced member referenced.  */
11303       && TREE_CODE (expr) != OFFSET_REF)
11304     expr = convert_from_reference (expr);
11305
11306   return expr;
11307 }
11308
11309 /* Like tsubst, but deals with expressions.  This function just replaces
11310    template parms; to finish processing the resultant expression, use
11311    tsubst_expr.  */
11312
11313 static tree
11314 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11315 {
11316   enum tree_code code;
11317   tree r;
11318
11319   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
11320     return t;
11321
11322   code = TREE_CODE (t);
11323
11324   switch (code)
11325     {
11326     case PARM_DECL:
11327       r = retrieve_local_specialization (t);
11328
11329       if (r == NULL)
11330         {
11331           tree c;
11332           /* This can happen for a parameter name used later in a function
11333              declaration (such as in a late-specified return type).  Just
11334              make a dummy decl, since it's only used for its type.  */
11335           gcc_assert (cp_unevaluated_operand != 0);
11336           /* We copy T because want to tsubst the PARM_DECL only,
11337              not the following PARM_DECLs that are chained to T.  */
11338           c = copy_node (t);
11339           r = tsubst_decl (c, args, complain);
11340           /* Give it the template pattern as its context; its true context
11341              hasn't been instantiated yet and this is good enough for
11342              mangling.  */
11343           DECL_CONTEXT (r) = DECL_CONTEXT (t);
11344         }
11345       
11346       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
11347         r = ARGUMENT_PACK_SELECT_ARG (r);
11348       mark_used (r);
11349       return r;
11350
11351     case CONST_DECL:
11352       {
11353         tree enum_type;
11354         tree v;
11355
11356         if (DECL_TEMPLATE_PARM_P (t))
11357           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
11358         /* There is no need to substitute into namespace-scope
11359            enumerators.  */
11360         if (DECL_NAMESPACE_SCOPE_P (t))
11361           return t;
11362         /* If ARGS is NULL, then T is known to be non-dependent.  */
11363         if (args == NULL_TREE)
11364           return integral_constant_value (t);
11365
11366         /* Unfortunately, we cannot just call lookup_name here.
11367            Consider:
11368
11369              template <int I> int f() {
11370              enum E { a = I };
11371              struct S { void g() { E e = a; } };
11372              };
11373
11374            When we instantiate f<7>::S::g(), say, lookup_name is not
11375            clever enough to find f<7>::a.  */
11376         enum_type
11377           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
11378                               /*entering_scope=*/0);
11379
11380         for (v = TYPE_VALUES (enum_type);
11381              v != NULL_TREE;
11382              v = TREE_CHAIN (v))
11383           if (TREE_PURPOSE (v) == DECL_NAME (t))
11384             return TREE_VALUE (v);
11385
11386           /* We didn't find the name.  That should never happen; if
11387              name-lookup found it during preliminary parsing, we
11388              should find it again here during instantiation.  */
11389         gcc_unreachable ();
11390       }
11391       return t;
11392
11393     case FIELD_DECL:
11394       if (DECL_CONTEXT (t))
11395         {
11396           tree ctx;
11397
11398           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
11399                                   /*entering_scope=*/1);
11400           if (ctx != DECL_CONTEXT (t))
11401             {
11402               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
11403               if (!r)
11404                 {
11405                   if (complain & tf_error)
11406                     error ("using invalid field %qD", t);
11407                   return error_mark_node;
11408                 }
11409               return r;
11410             }
11411         }
11412
11413       return t;
11414
11415     case VAR_DECL:
11416     case FUNCTION_DECL:
11417       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11418           || local_variable_p (t))
11419         t = tsubst (t, args, complain, in_decl);
11420       mark_used (t);
11421       return t;
11422
11423     case OVERLOAD:
11424       /* An OVERLOAD will always be a non-dependent overload set; an
11425          overload set from function scope will just be represented with an
11426          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
11427       gcc_assert (!uses_template_parms (t));
11428       return t;
11429
11430     case BASELINK:
11431       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11432
11433     case TEMPLATE_DECL:
11434       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11435         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11436                        args, complain, in_decl);
11437       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11438         return tsubst (t, args, complain, in_decl);
11439       else if (DECL_CLASS_SCOPE_P (t)
11440                && uses_template_parms (DECL_CONTEXT (t)))
11441         {
11442           /* Template template argument like the following example need
11443              special treatment:
11444
11445                template <template <class> class TT> struct C {};
11446                template <class T> struct D {
11447                  template <class U> struct E {};
11448                  C<E> c;                                // #1
11449                };
11450                D<int> d;                                // #2
11451
11452              We are processing the template argument `E' in #1 for
11453              the template instantiation #2.  Originally, `E' is a
11454              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11455              have to substitute this with one having context `D<int>'.  */
11456
11457           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11458           return lookup_field (context, DECL_NAME(t), 0, false);
11459         }
11460       else
11461         /* Ordinary template template argument.  */
11462         return t;
11463
11464     case CAST_EXPR:
11465     case REINTERPRET_CAST_EXPR:
11466     case CONST_CAST_EXPR:
11467     case STATIC_CAST_EXPR:
11468     case DYNAMIC_CAST_EXPR:
11469     case NOP_EXPR:
11470       return build1
11471         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11472          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11473
11474     case SIZEOF_EXPR:
11475       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11476         {
11477
11478           tree expanded;
11479           int len = 0;
11480
11481           ++cp_unevaluated_operand;
11482           ++c_inhibit_evaluation_warnings;
11483           /* We only want to compute the number of arguments.  */
11484           expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11485                                             complain, in_decl);
11486           --cp_unevaluated_operand;
11487           --c_inhibit_evaluation_warnings;
11488
11489           if (TREE_CODE (expanded) == TREE_VEC)
11490             len = TREE_VEC_LENGTH (expanded);
11491
11492           if (expanded == error_mark_node)
11493             return error_mark_node;
11494           else if (PACK_EXPANSION_P (expanded)
11495                    || (TREE_CODE (expanded) == TREE_VEC
11496                        && len > 0
11497                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11498             {
11499               if (TREE_CODE (expanded) == TREE_VEC)
11500                 expanded = TREE_VEC_ELT (expanded, len - 1);
11501
11502               if (TYPE_P (expanded))
11503                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11504                                                    complain & tf_error);
11505               else
11506                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11507                                                    complain & tf_error);
11508             }
11509           else
11510             return build_int_cst (size_type_node, len);
11511         }
11512       /* Fall through */
11513
11514     case INDIRECT_REF:
11515     case NEGATE_EXPR:
11516     case TRUTH_NOT_EXPR:
11517     case BIT_NOT_EXPR:
11518     case ADDR_EXPR:
11519     case UNARY_PLUS_EXPR:      /* Unary + */
11520     case ALIGNOF_EXPR:
11521     case AT_ENCODE_EXPR:
11522     case ARROW_EXPR:
11523     case THROW_EXPR:
11524     case TYPEID_EXPR:
11525     case REALPART_EXPR:
11526     case IMAGPART_EXPR:
11527       return build1
11528         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11529          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11530
11531     case COMPONENT_REF:
11532       {
11533         tree object;
11534         tree name;
11535
11536         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11537         name = TREE_OPERAND (t, 1);
11538         if (TREE_CODE (name) == BIT_NOT_EXPR)
11539           {
11540             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11541                                 complain, in_decl);
11542             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11543           }
11544         else if (TREE_CODE (name) == SCOPE_REF
11545                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11546           {
11547             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11548                                      complain, in_decl);
11549             name = TREE_OPERAND (name, 1);
11550             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11551                                 complain, in_decl);
11552             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11553             name = build_qualified_name (/*type=*/NULL_TREE,
11554                                          base, name,
11555                                          /*template_p=*/false);
11556           }
11557         else if (TREE_CODE (name) == BASELINK)
11558           name = tsubst_baselink (name,
11559                                   non_reference (TREE_TYPE (object)),
11560                                   args, complain,
11561                                   in_decl);
11562         else
11563           name = tsubst_copy (name, args, complain, in_decl);
11564         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11565       }
11566
11567     case PLUS_EXPR:
11568     case MINUS_EXPR:
11569     case MULT_EXPR:
11570     case TRUNC_DIV_EXPR:
11571     case CEIL_DIV_EXPR:
11572     case FLOOR_DIV_EXPR:
11573     case ROUND_DIV_EXPR:
11574     case EXACT_DIV_EXPR:
11575     case BIT_AND_EXPR:
11576     case BIT_IOR_EXPR:
11577     case BIT_XOR_EXPR:
11578     case TRUNC_MOD_EXPR:
11579     case FLOOR_MOD_EXPR:
11580     case TRUTH_ANDIF_EXPR:
11581     case TRUTH_ORIF_EXPR:
11582     case TRUTH_AND_EXPR:
11583     case TRUTH_OR_EXPR:
11584     case RSHIFT_EXPR:
11585     case LSHIFT_EXPR:
11586     case RROTATE_EXPR:
11587     case LROTATE_EXPR:
11588     case EQ_EXPR:
11589     case NE_EXPR:
11590     case MAX_EXPR:
11591     case MIN_EXPR:
11592     case LE_EXPR:
11593     case GE_EXPR:
11594     case LT_EXPR:
11595     case GT_EXPR:
11596     case COMPOUND_EXPR:
11597     case DOTSTAR_EXPR:
11598     case MEMBER_REF:
11599     case PREDECREMENT_EXPR:
11600     case PREINCREMENT_EXPR:
11601     case POSTDECREMENT_EXPR:
11602     case POSTINCREMENT_EXPR:
11603       return build_nt
11604         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11605          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11606
11607     case SCOPE_REF:
11608       return build_qualified_name (/*type=*/NULL_TREE,
11609                                    tsubst_copy (TREE_OPERAND (t, 0),
11610                                                 args, complain, in_decl),
11611                                    tsubst_copy (TREE_OPERAND (t, 1),
11612                                                 args, complain, in_decl),
11613                                    QUALIFIED_NAME_IS_TEMPLATE (t));
11614
11615     case ARRAY_REF:
11616       return build_nt
11617         (ARRAY_REF,
11618          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11619          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11620          NULL_TREE, NULL_TREE);
11621
11622     case CALL_EXPR:
11623       {
11624         int n = VL_EXP_OPERAND_LENGTH (t);
11625         tree result = build_vl_exp (CALL_EXPR, n);
11626         int i;
11627         for (i = 0; i < n; i++)
11628           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11629                                              complain, in_decl);
11630         return result;
11631       }
11632
11633     case COND_EXPR:
11634     case MODOP_EXPR:
11635     case PSEUDO_DTOR_EXPR:
11636       {
11637         r = build_nt
11638           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11639            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11640            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11641         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11642         return r;
11643       }
11644
11645     case NEW_EXPR:
11646       {
11647         r = build_nt
11648         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11649          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11650          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11651         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11652         return r;
11653       }
11654
11655     case DELETE_EXPR:
11656       {
11657         r = build_nt
11658         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11659          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11660         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11661         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11662         return r;
11663       }
11664
11665     case TEMPLATE_ID_EXPR:
11666       {
11667         /* Substituted template arguments */
11668         tree fn = TREE_OPERAND (t, 0);
11669         tree targs = TREE_OPERAND (t, 1);
11670
11671         fn = tsubst_copy (fn, args, complain, in_decl);
11672         if (targs)
11673           targs = tsubst_template_args (targs, args, complain, in_decl);
11674
11675         return lookup_template_function (fn, targs);
11676       }
11677
11678     case TREE_LIST:
11679       {
11680         tree purpose, value, chain;
11681
11682         if (t == void_list_node)
11683           return t;
11684
11685         purpose = TREE_PURPOSE (t);
11686         if (purpose)
11687           purpose = tsubst_copy (purpose, args, complain, in_decl);
11688         value = TREE_VALUE (t);
11689         if (value)
11690           value = tsubst_copy (value, args, complain, in_decl);
11691         chain = TREE_CHAIN (t);
11692         if (chain && chain != void_type_node)
11693           chain = tsubst_copy (chain, args, complain, in_decl);
11694         if (purpose == TREE_PURPOSE (t)
11695             && value == TREE_VALUE (t)
11696             && chain == TREE_CHAIN (t))
11697           return t;
11698         return tree_cons (purpose, value, chain);
11699       }
11700
11701     case RECORD_TYPE:
11702     case UNION_TYPE:
11703     case ENUMERAL_TYPE:
11704     case INTEGER_TYPE:
11705     case TEMPLATE_TYPE_PARM:
11706     case TEMPLATE_TEMPLATE_PARM:
11707     case BOUND_TEMPLATE_TEMPLATE_PARM:
11708     case TEMPLATE_PARM_INDEX:
11709     case POINTER_TYPE:
11710     case REFERENCE_TYPE:
11711     case OFFSET_TYPE:
11712     case FUNCTION_TYPE:
11713     case METHOD_TYPE:
11714     case ARRAY_TYPE:
11715     case TYPENAME_TYPE:
11716     case UNBOUND_CLASS_TEMPLATE:
11717     case TYPEOF_TYPE:
11718     case DECLTYPE_TYPE:
11719     case TYPE_DECL:
11720       return tsubst (t, args, complain, in_decl);
11721
11722     case IDENTIFIER_NODE:
11723       if (IDENTIFIER_TYPENAME_P (t))
11724         {
11725           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11726           return mangle_conv_op_name_for_type (new_type);
11727         }
11728       else
11729         return t;
11730
11731     case CONSTRUCTOR:
11732       /* This is handled by tsubst_copy_and_build.  */
11733       gcc_unreachable ();
11734
11735     case VA_ARG_EXPR:
11736       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11737                                           in_decl),
11738                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11739
11740     case CLEANUP_POINT_EXPR:
11741       /* We shouldn't have built any of these during initial template
11742          generation.  Instead, they should be built during instantiation
11743          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11744       gcc_unreachable ();
11745
11746     case OFFSET_REF:
11747       r = build2
11748         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11749          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11750          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11751       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
11752       mark_used (TREE_OPERAND (r, 1));
11753       return r;
11754
11755     case EXPR_PACK_EXPANSION:
11756       error ("invalid use of pack expansion expression");
11757       return error_mark_node;
11758
11759     case NONTYPE_ARGUMENT_PACK:
11760       error ("use %<...%> to expand argument pack");
11761       return error_mark_node;
11762
11763     case INTEGER_CST:
11764     case REAL_CST:
11765     case STRING_CST:
11766     case COMPLEX_CST:
11767       {
11768         /* Instantiate any typedefs in the type.  */
11769         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11770         r = fold_convert (type, t);
11771         gcc_assert (TREE_CODE (r) == code);
11772         return r;
11773       }
11774
11775     case PTRMEM_CST:
11776       /* These can sometimes show up in a partial instantiation, but never
11777          involve template parms.  */
11778       gcc_assert (!uses_template_parms (t));
11779       return t;
11780
11781     default:
11782       /* We shouldn't get here, but keep going if !ENABLE_CHECKING.  */
11783       gcc_checking_assert (false);
11784       return t;
11785     }
11786 }
11787
11788 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11789
11790 static tree
11791 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11792                     tree in_decl)
11793 {
11794   tree new_clauses = NULL, nc, oc;
11795
11796   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11797     {
11798       nc = copy_node (oc);
11799       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11800       new_clauses = nc;
11801
11802       switch (OMP_CLAUSE_CODE (nc))
11803         {
11804         case OMP_CLAUSE_LASTPRIVATE:
11805           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11806             {
11807               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11808               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11809                            in_decl, /*integral_constant_expression_p=*/false);
11810               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11811                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11812             }
11813           /* FALLTHRU */
11814         case OMP_CLAUSE_PRIVATE:
11815         case OMP_CLAUSE_SHARED:
11816         case OMP_CLAUSE_FIRSTPRIVATE:
11817         case OMP_CLAUSE_REDUCTION:
11818         case OMP_CLAUSE_COPYIN:
11819         case OMP_CLAUSE_COPYPRIVATE:
11820         case OMP_CLAUSE_IF:
11821         case OMP_CLAUSE_NUM_THREADS:
11822         case OMP_CLAUSE_SCHEDULE:
11823         case OMP_CLAUSE_COLLAPSE:
11824           OMP_CLAUSE_OPERAND (nc, 0)
11825             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11826                            in_decl, /*integral_constant_expression_p=*/false);
11827           break;
11828         case OMP_CLAUSE_NOWAIT:
11829         case OMP_CLAUSE_ORDERED:
11830         case OMP_CLAUSE_DEFAULT:
11831         case OMP_CLAUSE_UNTIED:
11832           break;
11833         default:
11834           gcc_unreachable ();
11835         }
11836     }
11837
11838   return finish_omp_clauses (nreverse (new_clauses));
11839 }
11840
11841 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11842
11843 static tree
11844 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11845                           tree in_decl)
11846 {
11847 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11848
11849   tree purpose, value, chain;
11850
11851   if (t == NULL)
11852     return t;
11853
11854   if (TREE_CODE (t) != TREE_LIST)
11855     return tsubst_copy_and_build (t, args, complain, in_decl,
11856                                   /*function_p=*/false,
11857                                   /*integral_constant_expression_p=*/false);
11858
11859   if (t == void_list_node)
11860     return t;
11861
11862   purpose = TREE_PURPOSE (t);
11863   if (purpose)
11864     purpose = RECUR (purpose);
11865   value = TREE_VALUE (t);
11866   if (value && TREE_CODE (value) != LABEL_DECL)
11867     value = RECUR (value);
11868   chain = TREE_CHAIN (t);
11869   if (chain && chain != void_type_node)
11870     chain = RECUR (chain);
11871   return tree_cons (purpose, value, chain);
11872 #undef RECUR
11873 }
11874
11875 /* Substitute one OMP_FOR iterator.  */
11876
11877 static void
11878 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11879                          tree condv, tree incrv, tree *clauses,
11880                          tree args, tsubst_flags_t complain, tree in_decl,
11881                          bool integral_constant_expression_p)
11882 {
11883 #define RECUR(NODE)                             \
11884   tsubst_expr ((NODE), args, complain, in_decl, \
11885                integral_constant_expression_p)
11886   tree decl, init, cond, incr, auto_node;
11887
11888   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11889   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11890   decl = RECUR (TREE_OPERAND (init, 0));
11891   init = TREE_OPERAND (init, 1);
11892   auto_node = type_uses_auto (TREE_TYPE (decl));
11893   if (auto_node && init)
11894     {
11895       tree init_expr = init;
11896       if (TREE_CODE (init_expr) == DECL_EXPR)
11897         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11898       init_expr = RECUR (init_expr);
11899       TREE_TYPE (decl)
11900         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11901     }
11902   gcc_assert (!type_dependent_expression_p (decl));
11903
11904   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11905     {
11906       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11907       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11908       if (TREE_CODE (incr) == MODIFY_EXPR)
11909         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11910                                     RECUR (TREE_OPERAND (incr, 1)),
11911                                     complain);
11912       else
11913         incr = RECUR (incr);
11914       TREE_VEC_ELT (declv, i) = decl;
11915       TREE_VEC_ELT (initv, i) = init;
11916       TREE_VEC_ELT (condv, i) = cond;
11917       TREE_VEC_ELT (incrv, i) = incr;
11918       return;
11919     }
11920
11921   if (init && TREE_CODE (init) != DECL_EXPR)
11922     {
11923       tree c;
11924       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11925         {
11926           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11927                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11928               && OMP_CLAUSE_DECL (c) == decl)
11929             break;
11930           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11931                    && OMP_CLAUSE_DECL (c) == decl)
11932             error ("iteration variable %qD should not be firstprivate", decl);
11933           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11934                    && OMP_CLAUSE_DECL (c) == decl)
11935             error ("iteration variable %qD should not be reduction", decl);
11936         }
11937       if (c == NULL)
11938         {
11939           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11940           OMP_CLAUSE_DECL (c) = decl;
11941           c = finish_omp_clauses (c);
11942           if (c)
11943             {
11944               OMP_CLAUSE_CHAIN (c) = *clauses;
11945               *clauses = c;
11946             }
11947         }
11948     }
11949   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11950   if (COMPARISON_CLASS_P (cond))
11951     cond = build2 (TREE_CODE (cond), boolean_type_node,
11952                    RECUR (TREE_OPERAND (cond, 0)),
11953                    RECUR (TREE_OPERAND (cond, 1)));
11954   else
11955     cond = RECUR (cond);
11956   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11957   switch (TREE_CODE (incr))
11958     {
11959     case PREINCREMENT_EXPR:
11960     case PREDECREMENT_EXPR:
11961     case POSTINCREMENT_EXPR:
11962     case POSTDECREMENT_EXPR:
11963       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11964                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11965       break;
11966     case MODIFY_EXPR:
11967       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11968           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11969         {
11970           tree rhs = TREE_OPERAND (incr, 1);
11971           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11972                          RECUR (TREE_OPERAND (incr, 0)),
11973                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11974                                  RECUR (TREE_OPERAND (rhs, 0)),
11975                                  RECUR (TREE_OPERAND (rhs, 1))));
11976         }
11977       else
11978         incr = RECUR (incr);
11979       break;
11980     case MODOP_EXPR:
11981       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11982           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11983         {
11984           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11985           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11986                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11987                                  TREE_TYPE (decl), lhs,
11988                                  RECUR (TREE_OPERAND (incr, 2))));
11989         }
11990       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11991                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11992                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11993         {
11994           tree rhs = TREE_OPERAND (incr, 2);
11995           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11996                          RECUR (TREE_OPERAND (incr, 0)),
11997                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11998                                  RECUR (TREE_OPERAND (rhs, 0)),
11999                                  RECUR (TREE_OPERAND (rhs, 1))));
12000         }
12001       else
12002         incr = RECUR (incr);
12003       break;
12004     default:
12005       incr = RECUR (incr);
12006       break;
12007     }
12008
12009   TREE_VEC_ELT (declv, i) = decl;
12010   TREE_VEC_ELT (initv, i) = init;
12011   TREE_VEC_ELT (condv, i) = cond;
12012   TREE_VEC_ELT (incrv, i) = incr;
12013 #undef RECUR
12014 }
12015
12016 /* Like tsubst_copy for expressions, etc. but also does semantic
12017    processing.  */
12018
12019 static tree
12020 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
12021              bool integral_constant_expression_p)
12022 {
12023 #define RECUR(NODE)                             \
12024   tsubst_expr ((NODE), args, complain, in_decl, \
12025                integral_constant_expression_p)
12026
12027   tree stmt, tmp;
12028
12029   if (t == NULL_TREE || t == error_mark_node)
12030     return t;
12031
12032   if (EXPR_HAS_LOCATION (t))
12033     input_location = EXPR_LOCATION (t);
12034   if (STATEMENT_CODE_P (TREE_CODE (t)))
12035     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
12036
12037   switch (TREE_CODE (t))
12038     {
12039     case STATEMENT_LIST:
12040       {
12041         tree_stmt_iterator i;
12042         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
12043           RECUR (tsi_stmt (i));
12044         break;
12045       }
12046
12047     case CTOR_INITIALIZER:
12048       finish_mem_initializers (tsubst_initializer_list
12049                                (TREE_OPERAND (t, 0), args));
12050       break;
12051
12052     case RETURN_EXPR:
12053       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
12054       break;
12055
12056     case EXPR_STMT:
12057       tmp = RECUR (EXPR_STMT_EXPR (t));
12058       if (EXPR_STMT_STMT_EXPR_RESULT (t))
12059         finish_stmt_expr_expr (tmp, cur_stmt_expr);
12060       else
12061         finish_expr_stmt (tmp);
12062       break;
12063
12064     case USING_STMT:
12065       do_using_directive (USING_STMT_NAMESPACE (t));
12066       break;
12067
12068     case DECL_EXPR:
12069       {
12070         tree decl, pattern_decl;
12071         tree init;
12072
12073         pattern_decl = decl = DECL_EXPR_DECL (t);
12074         if (TREE_CODE (decl) == LABEL_DECL)
12075           finish_label_decl (DECL_NAME (decl));
12076         else if (TREE_CODE (decl) == USING_DECL)
12077           {
12078             tree scope = USING_DECL_SCOPE (decl);
12079             tree name = DECL_NAME (decl);
12080             tree decl;
12081
12082             scope = tsubst (scope, args, complain, in_decl);
12083             decl = lookup_qualified_name (scope, name,
12084                                           /*is_type_p=*/false,
12085                                           /*complain=*/false);
12086             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
12087               qualified_name_lookup_error (scope, name, decl, input_location);
12088             else
12089               do_local_using_decl (decl, scope, name);
12090           }
12091         else
12092           {
12093             init = DECL_INITIAL (decl);
12094             decl = tsubst (decl, args, complain, in_decl);
12095             if (decl != error_mark_node)
12096               {
12097                 /* By marking the declaration as instantiated, we avoid
12098                    trying to instantiate it.  Since instantiate_decl can't
12099                    handle local variables, and since we've already done
12100                    all that needs to be done, that's the right thing to
12101                    do.  */
12102                 if (TREE_CODE (decl) == VAR_DECL)
12103                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12104                 if (TREE_CODE (decl) == VAR_DECL
12105                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12106                   /* Anonymous aggregates are a special case.  */
12107                   finish_anon_union (decl);
12108                 else
12109                   {
12110                     int const_init = false;
12111                     maybe_push_decl (decl);
12112                     if (TREE_CODE (decl) == VAR_DECL
12113                         && DECL_PRETTY_FUNCTION_P (decl))
12114                       {
12115                         /* For __PRETTY_FUNCTION__ we have to adjust the
12116                            initializer.  */
12117                         const char *const name
12118                           = cxx_printable_name (current_function_decl, 2);
12119                         init = cp_fname_init (name, &TREE_TYPE (decl));
12120                       }
12121                     else
12122                       {
12123                         tree t = RECUR (init);
12124
12125                         if (init && !t)
12126                           {
12127                             /* If we had an initializer but it
12128                                instantiated to nothing,
12129                                value-initialize the object.  This will
12130                                only occur when the initializer was a
12131                                pack expansion where the parameter packs
12132                                used in that expansion were of length
12133                                zero.  */
12134                             init = build_value_init (TREE_TYPE (decl),
12135                                                      complain);
12136                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
12137                               init = get_target_expr_sfinae (init, complain);
12138                           }
12139                         else
12140                           init = t;
12141                       }
12142
12143                     if (TREE_CODE (decl) == VAR_DECL)
12144                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
12145                                     (pattern_decl));
12146                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
12147                   }
12148               }
12149           }
12150
12151         /* A DECL_EXPR can also be used as an expression, in the condition
12152            clause of an if/for/while construct.  */
12153         return decl;
12154       }
12155
12156     case FOR_STMT:
12157       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12158       RECUR (FOR_INIT_STMT (t));
12159       finish_for_init_stmt (stmt);
12160       tmp = RECUR (FOR_COND (t));
12161       finish_for_cond (tmp, stmt);
12162       tmp = RECUR (FOR_EXPR (t));
12163       finish_for_expr (tmp, stmt);
12164       RECUR (FOR_BODY (t));
12165       finish_for_stmt (stmt);
12166       break;
12167
12168     case RANGE_FOR_STMT:
12169       {
12170         tree decl, expr;
12171         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12172         decl = RANGE_FOR_DECL (t);
12173         decl = tsubst (decl, args, complain, in_decl);
12174         maybe_push_decl (decl);
12175         expr = RECUR (RANGE_FOR_EXPR (t));
12176         stmt = cp_convert_range_for (stmt, decl, expr);
12177         RECUR (RANGE_FOR_BODY (t));
12178         finish_for_stmt (stmt);
12179       }
12180       break;
12181
12182     case WHILE_STMT:
12183       stmt = begin_while_stmt ();
12184       tmp = RECUR (WHILE_COND (t));
12185       finish_while_stmt_cond (tmp, stmt);
12186       RECUR (WHILE_BODY (t));
12187       finish_while_stmt (stmt);
12188       break;
12189
12190     case DO_STMT:
12191       stmt = begin_do_stmt ();
12192       RECUR (DO_BODY (t));
12193       finish_do_body (stmt);
12194       tmp = RECUR (DO_COND (t));
12195       finish_do_stmt (tmp, stmt);
12196       break;
12197
12198     case IF_STMT:
12199       stmt = begin_if_stmt ();
12200       tmp = RECUR (IF_COND (t));
12201       finish_if_stmt_cond (tmp, stmt);
12202       RECUR (THEN_CLAUSE (t));
12203       finish_then_clause (stmt);
12204
12205       if (ELSE_CLAUSE (t))
12206         {
12207           begin_else_clause (stmt);
12208           RECUR (ELSE_CLAUSE (t));
12209           finish_else_clause (stmt);
12210         }
12211
12212       finish_if_stmt (stmt);
12213       break;
12214
12215     case BIND_EXPR:
12216       if (BIND_EXPR_BODY_BLOCK (t))
12217         stmt = begin_function_body ();
12218       else
12219         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
12220                                     ? BCS_TRY_BLOCK : 0);
12221
12222       RECUR (BIND_EXPR_BODY (t));
12223
12224       if (BIND_EXPR_BODY_BLOCK (t))
12225         finish_function_body (stmt);
12226       else
12227         finish_compound_stmt (stmt);
12228       break;
12229
12230     case BREAK_STMT:
12231       finish_break_stmt ();
12232       break;
12233
12234     case CONTINUE_STMT:
12235       finish_continue_stmt ();
12236       break;
12237
12238     case SWITCH_STMT:
12239       stmt = begin_switch_stmt ();
12240       tmp = RECUR (SWITCH_STMT_COND (t));
12241       finish_switch_cond (tmp, stmt);
12242       RECUR (SWITCH_STMT_BODY (t));
12243       finish_switch_stmt (stmt);
12244       break;
12245
12246     case CASE_LABEL_EXPR:
12247       finish_case_label (EXPR_LOCATION (t),
12248                          RECUR (CASE_LOW (t)),
12249                          RECUR (CASE_HIGH (t)));
12250       break;
12251
12252     case LABEL_EXPR:
12253       {
12254         tree decl = LABEL_EXPR_LABEL (t);
12255         tree label;
12256
12257         label = finish_label_stmt (DECL_NAME (decl));
12258         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
12259           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
12260       }
12261       break;
12262
12263     case GOTO_EXPR:
12264       tmp = GOTO_DESTINATION (t);
12265       if (TREE_CODE (tmp) != LABEL_DECL)
12266         /* Computed goto's must be tsubst'd into.  On the other hand,
12267            non-computed gotos must not be; the identifier in question
12268            will have no binding.  */
12269         tmp = RECUR (tmp);
12270       else
12271         tmp = DECL_NAME (tmp);
12272       finish_goto_stmt (tmp);
12273       break;
12274
12275     case ASM_EXPR:
12276       tmp = finish_asm_stmt
12277         (ASM_VOLATILE_P (t),
12278          RECUR (ASM_STRING (t)),
12279          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
12280          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
12281          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
12282          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
12283       {
12284         tree asm_expr = tmp;
12285         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
12286           asm_expr = TREE_OPERAND (asm_expr, 0);
12287         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
12288       }
12289       break;
12290
12291     case TRY_BLOCK:
12292       if (CLEANUP_P (t))
12293         {
12294           stmt = begin_try_block ();
12295           RECUR (TRY_STMTS (t));
12296           finish_cleanup_try_block (stmt);
12297           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
12298         }
12299       else
12300         {
12301           tree compound_stmt = NULL_TREE;
12302
12303           if (FN_TRY_BLOCK_P (t))
12304             stmt = begin_function_try_block (&compound_stmt);
12305           else
12306             stmt = begin_try_block ();
12307
12308           RECUR (TRY_STMTS (t));
12309
12310           if (FN_TRY_BLOCK_P (t))
12311             finish_function_try_block (stmt);
12312           else
12313             finish_try_block (stmt);
12314
12315           RECUR (TRY_HANDLERS (t));
12316           if (FN_TRY_BLOCK_P (t))
12317             finish_function_handler_sequence (stmt, compound_stmt);
12318           else
12319             finish_handler_sequence (stmt);
12320         }
12321       break;
12322
12323     case HANDLER:
12324       {
12325         tree decl = HANDLER_PARMS (t);
12326
12327         if (decl)
12328           {
12329             decl = tsubst (decl, args, complain, in_decl);
12330             /* Prevent instantiate_decl from trying to instantiate
12331                this variable.  We've already done all that needs to be
12332                done.  */
12333             if (decl != error_mark_node)
12334               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12335           }
12336         stmt = begin_handler ();
12337         finish_handler_parms (decl, stmt);
12338         RECUR (HANDLER_BODY (t));
12339         finish_handler (stmt);
12340       }
12341       break;
12342
12343     case TAG_DEFN:
12344       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12345       break;
12346
12347     case STATIC_ASSERT:
12348       {
12349         tree condition = 
12350           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
12351                        args,
12352                        complain, in_decl,
12353                        /*integral_constant_expression_p=*/true);
12354         finish_static_assert (condition,
12355                               STATIC_ASSERT_MESSAGE (t),
12356                               STATIC_ASSERT_SOURCE_LOCATION (t),
12357                               /*member_p=*/false);
12358       }
12359       break;
12360
12361     case OMP_PARALLEL:
12362       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
12363                                 args, complain, in_decl);
12364       stmt = begin_omp_parallel ();
12365       RECUR (OMP_PARALLEL_BODY (t));
12366       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
12367         = OMP_PARALLEL_COMBINED (t);
12368       break;
12369
12370     case OMP_TASK:
12371       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
12372                                 args, complain, in_decl);
12373       stmt = begin_omp_task ();
12374       RECUR (OMP_TASK_BODY (t));
12375       finish_omp_task (tmp, stmt);
12376       break;
12377
12378     case OMP_FOR:
12379       {
12380         tree clauses, body, pre_body;
12381         tree declv, initv, condv, incrv;
12382         int i;
12383
12384         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
12385                                       args, complain, in_decl);
12386         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12387         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12388         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12389         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12390
12391         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
12392           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
12393                                    &clauses, args, complain, in_decl,
12394                                    integral_constant_expression_p);
12395
12396         stmt = begin_omp_structured_block ();
12397
12398         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
12399           if (TREE_VEC_ELT (initv, i) == NULL
12400               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
12401             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
12402           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
12403             {
12404               tree init = RECUR (TREE_VEC_ELT (initv, i));
12405               gcc_assert (init == TREE_VEC_ELT (declv, i));
12406               TREE_VEC_ELT (initv, i) = NULL_TREE;
12407             }
12408           else
12409             {
12410               tree decl_expr = TREE_VEC_ELT (initv, i);
12411               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
12412               gcc_assert (init != NULL);
12413               TREE_VEC_ELT (initv, i) = RECUR (init);
12414               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
12415               RECUR (decl_expr);
12416               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
12417             }
12418
12419         pre_body = push_stmt_list ();
12420         RECUR (OMP_FOR_PRE_BODY (t));
12421         pre_body = pop_stmt_list (pre_body);
12422
12423         body = push_stmt_list ();
12424         RECUR (OMP_FOR_BODY (t));
12425         body = pop_stmt_list (body);
12426
12427         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
12428                             body, pre_body, clauses);
12429
12430         add_stmt (finish_omp_structured_block (stmt));
12431       }
12432       break;
12433
12434     case OMP_SECTIONS:
12435     case OMP_SINGLE:
12436       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
12437       stmt = push_stmt_list ();
12438       RECUR (OMP_BODY (t));
12439       stmt = pop_stmt_list (stmt);
12440
12441       t = copy_node (t);
12442       OMP_BODY (t) = stmt;
12443       OMP_CLAUSES (t) = tmp;
12444       add_stmt (t);
12445       break;
12446
12447     case OMP_SECTION:
12448     case OMP_CRITICAL:
12449     case OMP_MASTER:
12450     case OMP_ORDERED:
12451       stmt = push_stmt_list ();
12452       RECUR (OMP_BODY (t));
12453       stmt = pop_stmt_list (stmt);
12454
12455       t = copy_node (t);
12456       OMP_BODY (t) = stmt;
12457       add_stmt (t);
12458       break;
12459
12460     case OMP_ATOMIC:
12461       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
12462       {
12463         tree op1 = TREE_OPERAND (t, 1);
12464         tree lhs = RECUR (TREE_OPERAND (op1, 0));
12465         tree rhs = RECUR (TREE_OPERAND (op1, 1));
12466         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
12467       }
12468       break;
12469
12470     case EXPR_PACK_EXPANSION:
12471       error ("invalid use of pack expansion expression");
12472       return error_mark_node;
12473
12474     case NONTYPE_ARGUMENT_PACK:
12475       error ("use %<...%> to expand argument pack");
12476       return error_mark_node;
12477
12478     default:
12479       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
12480
12481       return tsubst_copy_and_build (t, args, complain, in_decl,
12482                                     /*function_p=*/false,
12483                                     integral_constant_expression_p);
12484     }
12485
12486   return NULL_TREE;
12487 #undef RECUR
12488 }
12489
12490 /* T is a postfix-expression that is not being used in a function
12491    call.  Return the substituted version of T.  */
12492
12493 static tree
12494 tsubst_non_call_postfix_expression (tree t, tree args,
12495                                     tsubst_flags_t complain,
12496                                     tree in_decl)
12497 {
12498   if (TREE_CODE (t) == SCOPE_REF)
12499     t = tsubst_qualified_id (t, args, complain, in_decl,
12500                              /*done=*/false, /*address_p=*/false);
12501   else
12502     t = tsubst_copy_and_build (t, args, complain, in_decl,
12503                                /*function_p=*/false,
12504                                /*integral_constant_expression_p=*/false);
12505
12506   return t;
12507 }
12508
12509 /* Like tsubst but deals with expressions and performs semantic
12510    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12511
12512 tree
12513 tsubst_copy_and_build (tree t,
12514                        tree args,
12515                        tsubst_flags_t complain,
12516                        tree in_decl,
12517                        bool function_p,
12518                        bool integral_constant_expression_p)
12519 {
12520 #define RECUR(NODE)                                             \
12521   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
12522                          /*function_p=*/false,                  \
12523                          integral_constant_expression_p)
12524
12525   tree op1;
12526
12527   if (t == NULL_TREE || t == error_mark_node)
12528     return t;
12529
12530   switch (TREE_CODE (t))
12531     {
12532     case USING_DECL:
12533       t = DECL_NAME (t);
12534       /* Fall through.  */
12535     case IDENTIFIER_NODE:
12536       {
12537         tree decl;
12538         cp_id_kind idk;
12539         bool non_integral_constant_expression_p;
12540         const char *error_msg;
12541
12542         if (IDENTIFIER_TYPENAME_P (t))
12543           {
12544             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12545             t = mangle_conv_op_name_for_type (new_type);
12546           }
12547
12548         /* Look up the name.  */
12549         decl = lookup_name (t);
12550
12551         /* By convention, expressions use ERROR_MARK_NODE to indicate
12552            failure, not NULL_TREE.  */
12553         if (decl == NULL_TREE)
12554           decl = error_mark_node;
12555
12556         decl = finish_id_expression (t, decl, NULL_TREE,
12557                                      &idk,
12558                                      integral_constant_expression_p,
12559                                      /*allow_non_integral_constant_expression_p=*/false,
12560                                      &non_integral_constant_expression_p,
12561                                      /*template_p=*/false,
12562                                      /*done=*/true,
12563                                      /*address_p=*/false,
12564                                      /*template_arg_p=*/false,
12565                                      &error_msg,
12566                                      input_location);
12567         if (error_msg)
12568           error (error_msg);
12569         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
12570           decl = unqualified_name_lookup_error (decl);
12571         return decl;
12572       }
12573
12574     case TEMPLATE_ID_EXPR:
12575       {
12576         tree object;
12577         tree templ = RECUR (TREE_OPERAND (t, 0));
12578         tree targs = TREE_OPERAND (t, 1);
12579
12580         if (targs)
12581           targs = tsubst_template_args (targs, args, complain, in_decl);
12582
12583         if (TREE_CODE (templ) == COMPONENT_REF)
12584           {
12585             object = TREE_OPERAND (templ, 0);
12586             templ = TREE_OPERAND (templ, 1);
12587           }
12588         else
12589           object = NULL_TREE;
12590         templ = lookup_template_function (templ, targs);
12591
12592         if (object)
12593           return build3 (COMPONENT_REF, TREE_TYPE (templ),
12594                          object, templ, NULL_TREE);
12595         else
12596           return baselink_for_fns (templ);
12597       }
12598
12599     case INDIRECT_REF:
12600       {
12601         tree r = RECUR (TREE_OPERAND (t, 0));
12602
12603         if (REFERENCE_REF_P (t))
12604           {
12605             /* A type conversion to reference type will be enclosed in
12606                such an indirect ref, but the substitution of the cast
12607                will have also added such an indirect ref.  */
12608             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
12609               r = convert_from_reference (r);
12610           }
12611         else
12612           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
12613         return r;
12614       }
12615
12616     case NOP_EXPR:
12617       return build_nop
12618         (tsubst (TREE_TYPE (t), args, complain, in_decl),
12619          RECUR (TREE_OPERAND (t, 0)));
12620
12621     case CAST_EXPR:
12622     case REINTERPRET_CAST_EXPR:
12623     case CONST_CAST_EXPR:
12624     case DYNAMIC_CAST_EXPR:
12625     case STATIC_CAST_EXPR:
12626       {
12627         tree type;
12628         tree op;
12629
12630         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12631         if (integral_constant_expression_p
12632             && !cast_valid_in_integral_constant_expression_p (type))
12633           {
12634             if (complain & tf_error)
12635               error ("a cast to a type other than an integral or "
12636                      "enumeration type cannot appear in a constant-expression");
12637             return error_mark_node; 
12638           }
12639
12640         op = RECUR (TREE_OPERAND (t, 0));
12641
12642         switch (TREE_CODE (t))
12643           {
12644           case CAST_EXPR:
12645             return build_functional_cast (type, op, complain);
12646           case REINTERPRET_CAST_EXPR:
12647             return build_reinterpret_cast (type, op, complain);
12648           case CONST_CAST_EXPR:
12649             return build_const_cast (type, op, complain);
12650           case DYNAMIC_CAST_EXPR:
12651             return build_dynamic_cast (type, op, complain);
12652           case STATIC_CAST_EXPR:
12653             return build_static_cast (type, op, complain);
12654           default:
12655             gcc_unreachable ();
12656           }
12657       }
12658
12659     case POSTDECREMENT_EXPR:
12660     case POSTINCREMENT_EXPR:
12661       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12662                                                 args, complain, in_decl);
12663       return build_x_unary_op (TREE_CODE (t), op1, complain);
12664
12665     case PREDECREMENT_EXPR:
12666     case PREINCREMENT_EXPR:
12667     case NEGATE_EXPR:
12668     case BIT_NOT_EXPR:
12669     case ABS_EXPR:
12670     case TRUTH_NOT_EXPR:
12671     case UNARY_PLUS_EXPR:  /* Unary + */
12672     case REALPART_EXPR:
12673     case IMAGPART_EXPR:
12674       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12675                                complain);
12676
12677     case ADDR_EXPR:
12678       op1 = TREE_OPERAND (t, 0);
12679       if (TREE_CODE (op1) == LABEL_DECL)
12680         return finish_label_address_expr (DECL_NAME (op1),
12681                                           EXPR_LOCATION (op1));
12682       if (TREE_CODE (op1) == SCOPE_REF)
12683         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12684                                    /*done=*/true, /*address_p=*/true);
12685       else
12686         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12687                                                   in_decl);
12688       return build_x_unary_op (ADDR_EXPR, op1, complain);
12689
12690     case PLUS_EXPR:
12691     case MINUS_EXPR:
12692     case MULT_EXPR:
12693     case TRUNC_DIV_EXPR:
12694     case CEIL_DIV_EXPR:
12695     case FLOOR_DIV_EXPR:
12696     case ROUND_DIV_EXPR:
12697     case EXACT_DIV_EXPR:
12698     case BIT_AND_EXPR:
12699     case BIT_IOR_EXPR:
12700     case BIT_XOR_EXPR:
12701     case TRUNC_MOD_EXPR:
12702     case FLOOR_MOD_EXPR:
12703     case TRUTH_ANDIF_EXPR:
12704     case TRUTH_ORIF_EXPR:
12705     case TRUTH_AND_EXPR:
12706     case TRUTH_OR_EXPR:
12707     case RSHIFT_EXPR:
12708     case LSHIFT_EXPR:
12709     case RROTATE_EXPR:
12710     case LROTATE_EXPR:
12711     case EQ_EXPR:
12712     case NE_EXPR:
12713     case MAX_EXPR:
12714     case MIN_EXPR:
12715     case LE_EXPR:
12716     case GE_EXPR:
12717     case LT_EXPR:
12718     case GT_EXPR:
12719     case MEMBER_REF:
12720     case DOTSTAR_EXPR:
12721       return build_x_binary_op
12722         (TREE_CODE (t),
12723          RECUR (TREE_OPERAND (t, 0)),
12724          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12725           ? ERROR_MARK
12726           : TREE_CODE (TREE_OPERAND (t, 0))),
12727          RECUR (TREE_OPERAND (t, 1)),
12728          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12729           ? ERROR_MARK
12730           : TREE_CODE (TREE_OPERAND (t, 1))),
12731          /*overloaded_p=*/NULL,
12732          complain);
12733
12734     case SCOPE_REF:
12735       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12736                                   /*address_p=*/false);
12737     case ARRAY_REF:
12738       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12739                                                 args, complain, in_decl);
12740       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12741
12742     case SIZEOF_EXPR:
12743       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12744         return tsubst_copy (t, args, complain, in_decl);
12745       /* Fall through */
12746       
12747     case ALIGNOF_EXPR:
12748       op1 = TREE_OPERAND (t, 0);
12749       if (!args)
12750         {
12751           /* When there are no ARGS, we are trying to evaluate a
12752              non-dependent expression from the parser.  Trying to do
12753              the substitutions may not work.  */
12754           if (!TYPE_P (op1))
12755             op1 = TREE_TYPE (op1);
12756         }
12757       else
12758         {
12759           ++cp_unevaluated_operand;
12760           ++c_inhibit_evaluation_warnings;
12761           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12762                                        /*function_p=*/false,
12763                                        /*integral_constant_expression_p=*/false);
12764           --cp_unevaluated_operand;
12765           --c_inhibit_evaluation_warnings;
12766         }
12767       if (TYPE_P (op1))
12768         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
12769                                            complain & tf_error);
12770       else
12771         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
12772                                            complain & tf_error);
12773
12774     case AT_ENCODE_EXPR:
12775       {
12776         op1 = TREE_OPERAND (t, 0);
12777         ++cp_unevaluated_operand;
12778         ++c_inhibit_evaluation_warnings;
12779         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12780                                      /*function_p=*/false,
12781                                      /*integral_constant_expression_p=*/false);
12782         --cp_unevaluated_operand;
12783         --c_inhibit_evaluation_warnings;
12784         return objc_build_encode_expr (op1);
12785       }
12786
12787     case NOEXCEPT_EXPR:
12788       op1 = TREE_OPERAND (t, 0);
12789       ++cp_unevaluated_operand;
12790       ++c_inhibit_evaluation_warnings;
12791       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12792                                    /*function_p=*/false,
12793                                    /*integral_constant_expression_p=*/false);
12794       --cp_unevaluated_operand;
12795       --c_inhibit_evaluation_warnings;
12796       return finish_noexcept_expr (op1, complain);
12797
12798     case MODOP_EXPR:
12799       {
12800         tree r = build_x_modify_expr
12801           (RECUR (TREE_OPERAND (t, 0)),
12802            TREE_CODE (TREE_OPERAND (t, 1)),
12803            RECUR (TREE_OPERAND (t, 2)),
12804            complain);
12805         /* TREE_NO_WARNING must be set if either the expression was
12806            parenthesized or it uses an operator such as >>= rather
12807            than plain assignment.  In the former case, it was already
12808            set and must be copied.  In the latter case,
12809            build_x_modify_expr sets it and it must not be reset
12810            here.  */
12811         if (TREE_NO_WARNING (t))
12812           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12813         return r;
12814       }
12815
12816     case ARROW_EXPR:
12817       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12818                                                 args, complain, in_decl);
12819       /* Remember that there was a reference to this entity.  */
12820       if (DECL_P (op1))
12821         mark_used (op1);
12822       return build_x_arrow (op1);
12823
12824     case NEW_EXPR:
12825       {
12826         tree placement = RECUR (TREE_OPERAND (t, 0));
12827         tree init = RECUR (TREE_OPERAND (t, 3));
12828         VEC(tree,gc) *placement_vec;
12829         VEC(tree,gc) *init_vec;
12830         tree ret;
12831
12832         if (placement == NULL_TREE)
12833           placement_vec = NULL;
12834         else
12835           {
12836             placement_vec = make_tree_vector ();
12837             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12838               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12839           }
12840
12841         /* If there was an initializer in the original tree, but it
12842            instantiated to an empty list, then we should pass a
12843            non-NULL empty vector to tell build_new that it was an
12844            empty initializer() rather than no initializer.  This can
12845            only happen when the initializer is a pack expansion whose
12846            parameter packs are of length zero.  */
12847         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12848           init_vec = NULL;
12849         else
12850           {
12851             init_vec = make_tree_vector ();
12852             if (init == void_zero_node)
12853               gcc_assert (init_vec != NULL);
12854             else
12855               {
12856                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12857                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12858               }
12859           }
12860
12861         ret = build_new (&placement_vec,
12862                          tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
12863                          RECUR (TREE_OPERAND (t, 2)),
12864                          &init_vec,
12865                          NEW_EXPR_USE_GLOBAL (t),
12866                          complain);
12867
12868         if (placement_vec != NULL)
12869           release_tree_vector (placement_vec);
12870         if (init_vec != NULL)
12871           release_tree_vector (init_vec);
12872
12873         return ret;
12874       }
12875
12876     case DELETE_EXPR:
12877      return delete_sanity
12878        (RECUR (TREE_OPERAND (t, 0)),
12879         RECUR (TREE_OPERAND (t, 1)),
12880         DELETE_EXPR_USE_VEC (t),
12881         DELETE_EXPR_USE_GLOBAL (t),
12882         complain);
12883
12884     case COMPOUND_EXPR:
12885       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12886                                     RECUR (TREE_OPERAND (t, 1)),
12887                                     complain);
12888
12889     case CALL_EXPR:
12890       {
12891         tree function;
12892         VEC(tree,gc) *call_args;
12893         unsigned int nargs, i;
12894         bool qualified_p;
12895         bool koenig_p;
12896         tree ret;
12897
12898         function = CALL_EXPR_FN (t);
12899         /* When we parsed the expression,  we determined whether or
12900            not Koenig lookup should be performed.  */
12901         koenig_p = KOENIG_LOOKUP_P (t);
12902         if (TREE_CODE (function) == SCOPE_REF)
12903           {
12904             qualified_p = true;
12905             function = tsubst_qualified_id (function, args, complain, in_decl,
12906                                             /*done=*/false,
12907                                             /*address_p=*/false);
12908           }
12909         else if (koenig_p && TREE_CODE (function) == IDENTIFIER_NODE)
12910           {
12911             /* Do nothing; calling tsubst_copy_and_build on an identifier
12912                would incorrectly perform unqualified lookup again.
12913
12914                Note that we can also have an IDENTIFIER_NODE if the earlier
12915                unqualified lookup found a member function; in that case
12916                koenig_p will be false and we do want to do the lookup
12917                again to find the instantiated member function.
12918
12919                FIXME but doing that causes c++/15272, so we need to stop
12920                using IDENTIFIER_NODE in that situation.  */
12921             qualified_p = false;
12922           }
12923         else
12924           {
12925             if (TREE_CODE (function) == COMPONENT_REF)
12926               {
12927                 tree op = TREE_OPERAND (function, 1);
12928
12929                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12930                                || (BASELINK_P (op)
12931                                    && BASELINK_QUALIFIED_P (op)));
12932               }
12933             else
12934               qualified_p = false;
12935
12936             function = tsubst_copy_and_build (function, args, complain,
12937                                               in_decl,
12938                                               !qualified_p,
12939                                               integral_constant_expression_p);
12940
12941             if (BASELINK_P (function))
12942               qualified_p = true;
12943           }
12944
12945         nargs = call_expr_nargs (t);
12946         call_args = make_tree_vector ();
12947         for (i = 0; i < nargs; ++i)
12948           {
12949             tree arg = CALL_EXPR_ARG (t, i);
12950
12951             if (!PACK_EXPANSION_P (arg))
12952               VEC_safe_push (tree, gc, call_args,
12953                              RECUR (CALL_EXPR_ARG (t, i)));
12954             else
12955               {
12956                 /* Expand the pack expansion and push each entry onto
12957                    CALL_ARGS.  */
12958                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12959                 if (TREE_CODE (arg) == TREE_VEC)
12960                   {
12961                     unsigned int len, j;
12962
12963                     len = TREE_VEC_LENGTH (arg);
12964                     for (j = 0; j < len; ++j)
12965                       {
12966                         tree value = TREE_VEC_ELT (arg, j);
12967                         if (value != NULL_TREE)
12968                           value = convert_from_reference (value);
12969                         VEC_safe_push (tree, gc, call_args, value);
12970                       }
12971                   }
12972                 else
12973                   {
12974                     /* A partial substitution.  Add one entry.  */
12975                     VEC_safe_push (tree, gc, call_args, arg);
12976                   }
12977               }
12978           }
12979
12980         /* We do not perform argument-dependent lookup if normal
12981            lookup finds a non-function, in accordance with the
12982            expected resolution of DR 218.  */
12983         if (koenig_p
12984             && ((is_overloaded_fn (function)
12985                  /* If lookup found a member function, the Koenig lookup is
12986                     not appropriate, even if an unqualified-name was used
12987                     to denote the function.  */
12988                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12989                 || TREE_CODE (function) == IDENTIFIER_NODE)
12990             /* Only do this when substitution turns a dependent call
12991                into a non-dependent call.  */
12992             && type_dependent_expression_p_push (t)
12993             && !any_type_dependent_arguments_p (call_args))
12994           function = perform_koenig_lookup (function, call_args, false,
12995                                             tf_none);
12996
12997         if (TREE_CODE (function) == IDENTIFIER_NODE
12998             && !any_type_dependent_arguments_p (call_args))
12999           {
13000             if (koenig_p && (complain & tf_warning_or_error))
13001               {
13002                 /* For backwards compatibility and good diagnostics, try
13003                    the unqualified lookup again if we aren't in SFINAE
13004                    context.  */
13005                 tree unq = (tsubst_copy_and_build
13006                             (function, args, complain, in_decl, true,
13007                              integral_constant_expression_p));
13008                 if (unq != function)
13009                   {
13010                     tree fn = unq;
13011                     if (TREE_CODE (fn) == COMPONENT_REF)
13012                       fn = TREE_OPERAND (fn, 1);
13013                     if (is_overloaded_fn (fn))
13014                       fn = get_first_fn (fn);
13015                     permerror (EXPR_LOC_OR_HERE (t),
13016                                "%qD was not declared in this scope, "
13017                                "and no declarations were found by "
13018                                "argument-dependent lookup at the point "
13019                                "of instantiation", function);
13020                     if (DECL_CLASS_SCOPE_P (fn))
13021                       {
13022                         inform (EXPR_LOC_OR_HERE (t),
13023                                 "declarations in dependent base %qT are "
13024                                 "not found by unqualified lookup",
13025                                 DECL_CLASS_CONTEXT (fn));
13026                         if (current_class_ptr)
13027                           inform (EXPR_LOC_OR_HERE (t),
13028                                   "use %<this->%D%> instead", function);
13029                         else
13030                           inform (EXPR_LOC_OR_HERE (t),
13031                                   "use %<%T::%D%> instead",
13032                                   current_class_name, function);
13033                       }
13034                     else
13035                       inform (0, "%q+D declared here, later in the "
13036                                 "translation unit", fn);
13037                     function = unq;
13038                   }
13039               }
13040             if (TREE_CODE (function) == IDENTIFIER_NODE)
13041               {
13042                 unqualified_name_lookup_error (function);
13043                 release_tree_vector (call_args);
13044                 return error_mark_node;
13045               }
13046           }
13047
13048         /* Remember that there was a reference to this entity.  */
13049         if (DECL_P (function))
13050           mark_used (function);
13051
13052         if (TREE_CODE (function) == OFFSET_REF)
13053           ret = build_offset_ref_call_from_tree (function, &call_args);
13054         else if (TREE_CODE (function) == COMPONENT_REF)
13055           {
13056             tree instance = TREE_OPERAND (function, 0);
13057             tree fn = TREE_OPERAND (function, 1);
13058
13059             if (processing_template_decl
13060                 && (type_dependent_expression_p (instance)
13061                     || (!BASELINK_P (fn)
13062                         && TREE_CODE (fn) != FIELD_DECL)
13063                     || type_dependent_expression_p (fn)
13064                     || any_type_dependent_arguments_p (call_args)))
13065               ret = build_nt_call_vec (function, call_args);
13066             else if (!BASELINK_P (fn))
13067               ret = finish_call_expr (function, &call_args,
13068                                        /*disallow_virtual=*/false,
13069                                        /*koenig_p=*/false,
13070                                        complain);
13071             else
13072               ret = (build_new_method_call
13073                       (instance, fn,
13074                        &call_args, NULL_TREE,
13075                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
13076                        /*fn_p=*/NULL,
13077                        complain));
13078           }
13079         else
13080           ret = finish_call_expr (function, &call_args,
13081                                   /*disallow_virtual=*/qualified_p,
13082                                   koenig_p,
13083                                   complain);
13084
13085         release_tree_vector (call_args);
13086
13087         return ret;
13088       }
13089
13090     case COND_EXPR:
13091       return build_x_conditional_expr
13092         (RECUR (TREE_OPERAND (t, 0)),
13093          RECUR (TREE_OPERAND (t, 1)),
13094          RECUR (TREE_OPERAND (t, 2)),
13095          complain);
13096
13097     case PSEUDO_DTOR_EXPR:
13098       return finish_pseudo_destructor_expr
13099         (RECUR (TREE_OPERAND (t, 0)),
13100          RECUR (TREE_OPERAND (t, 1)),
13101          tsubst (TREE_OPERAND (t, 2), args, complain, in_decl));
13102
13103     case TREE_LIST:
13104       {
13105         tree purpose, value, chain;
13106
13107         if (t == void_list_node)
13108           return t;
13109
13110         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
13111             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
13112           {
13113             /* We have pack expansions, so expand those and
13114                create a new list out of it.  */
13115             tree purposevec = NULL_TREE;
13116             tree valuevec = NULL_TREE;
13117             tree chain;
13118             int i, len = -1;
13119
13120             /* Expand the argument expressions.  */
13121             if (TREE_PURPOSE (t))
13122               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
13123                                                  complain, in_decl);
13124             if (TREE_VALUE (t))
13125               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
13126                                                complain, in_decl);
13127
13128             /* Build the rest of the list.  */
13129             chain = TREE_CHAIN (t);
13130             if (chain && chain != void_type_node)
13131               chain = RECUR (chain);
13132
13133             /* Determine the number of arguments.  */
13134             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
13135               {
13136                 len = TREE_VEC_LENGTH (purposevec);
13137                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
13138               }
13139             else if (TREE_CODE (valuevec) == TREE_VEC)
13140               len = TREE_VEC_LENGTH (valuevec);
13141             else
13142               {
13143                 /* Since we only performed a partial substitution into
13144                    the argument pack, we only return a single list
13145                    node.  */
13146                 if (purposevec == TREE_PURPOSE (t)
13147                     && valuevec == TREE_VALUE (t)
13148                     && chain == TREE_CHAIN (t))
13149                   return t;
13150
13151                 return tree_cons (purposevec, valuevec, chain);
13152               }
13153             
13154             /* Convert the argument vectors into a TREE_LIST */
13155             i = len;
13156             while (i > 0)
13157               {
13158                 /* Grab the Ith values.  */
13159                 i--;
13160                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
13161                                      : NULL_TREE;
13162                 value 
13163                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
13164                              : NULL_TREE;
13165
13166                 /* Build the list (backwards).  */
13167                 chain = tree_cons (purpose, value, chain);
13168               }
13169
13170             return chain;
13171           }
13172
13173         purpose = TREE_PURPOSE (t);
13174         if (purpose)
13175           purpose = RECUR (purpose);
13176         value = TREE_VALUE (t);
13177         if (value)
13178           value = RECUR (value);
13179         chain = TREE_CHAIN (t);
13180         if (chain && chain != void_type_node)
13181           chain = RECUR (chain);
13182         if (purpose == TREE_PURPOSE (t)
13183             && value == TREE_VALUE (t)
13184             && chain == TREE_CHAIN (t))
13185           return t;
13186         return tree_cons (purpose, value, chain);
13187       }
13188
13189     case COMPONENT_REF:
13190       {
13191         tree object;
13192         tree object_type;
13193         tree member;
13194
13195         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13196                                                      args, complain, in_decl);
13197         /* Remember that there was a reference to this entity.  */
13198         if (DECL_P (object))
13199           mark_used (object);
13200         object_type = TREE_TYPE (object);
13201
13202         member = TREE_OPERAND (t, 1);
13203         if (BASELINK_P (member))
13204           member = tsubst_baselink (member,
13205                                     non_reference (TREE_TYPE (object)),
13206                                     args, complain, in_decl);
13207         else
13208           member = tsubst_copy (member, args, complain, in_decl);
13209         if (member == error_mark_node)
13210           return error_mark_node;
13211
13212         if (object_type && !CLASS_TYPE_P (object_type))
13213           {
13214             if (SCALAR_TYPE_P (object_type))
13215               {
13216                 tree s = NULL_TREE;
13217                 tree dtor = member;
13218
13219                 if (TREE_CODE (dtor) == SCOPE_REF)
13220                   {
13221                     s = TREE_OPERAND (dtor, 0);
13222                     dtor = TREE_OPERAND (dtor, 1);
13223                   }
13224                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
13225                   {
13226                     dtor = TREE_OPERAND (dtor, 0);
13227                     if (TYPE_P (dtor))
13228                       return finish_pseudo_destructor_expr (object, s, dtor);
13229                   }
13230               }
13231           }
13232         else if (TREE_CODE (member) == SCOPE_REF
13233                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
13234           {
13235             tree tmpl;
13236             tree args;
13237
13238             /* Lookup the template functions now that we know what the
13239                scope is.  */
13240             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
13241             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
13242             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
13243                                             /*is_type_p=*/false,
13244                                             /*complain=*/false);
13245             if (BASELINK_P (member))
13246               {
13247                 BASELINK_FUNCTIONS (member)
13248                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
13249                               args);
13250                 member = (adjust_result_of_qualified_name_lookup
13251                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
13252                            object_type));
13253               }
13254             else
13255               {
13256                 qualified_name_lookup_error (object_type, tmpl, member,
13257                                              input_location);
13258                 return error_mark_node;
13259               }
13260           }
13261         else if (TREE_CODE (member) == SCOPE_REF
13262                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
13263                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
13264           {
13265             if (complain & tf_error)
13266               {
13267                 if (TYPE_P (TREE_OPERAND (member, 0)))
13268                   error ("%qT is not a class or namespace",
13269                          TREE_OPERAND (member, 0));
13270                 else
13271                   error ("%qD is not a class or namespace",
13272                          TREE_OPERAND (member, 0));
13273               }
13274             return error_mark_node;
13275           }
13276         else if (TREE_CODE (member) == FIELD_DECL)
13277           return finish_non_static_data_member (member, object, NULL_TREE);
13278
13279         return finish_class_member_access_expr (object, member,
13280                                                 /*template_p=*/false,
13281                                                 complain);
13282       }
13283
13284     case THROW_EXPR:
13285       return build_throw
13286         (RECUR (TREE_OPERAND (t, 0)));
13287
13288     case CONSTRUCTOR:
13289       {
13290         VEC(constructor_elt,gc) *n;
13291         constructor_elt *ce;
13292         unsigned HOST_WIDE_INT idx;
13293         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13294         bool process_index_p;
13295         int newlen;
13296         bool need_copy_p = false;
13297         tree r;
13298
13299         if (type == error_mark_node)
13300           return error_mark_node;
13301
13302         /* digest_init will do the wrong thing if we let it.  */
13303         if (type && TYPE_PTRMEMFUNC_P (type))
13304           return t;
13305
13306         /* We do not want to process the index of aggregate
13307            initializers as they are identifier nodes which will be
13308            looked up by digest_init.  */
13309         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
13310
13311         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
13312         newlen = VEC_length (constructor_elt, n);
13313         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
13314           {
13315             if (ce->index && process_index_p)
13316               ce->index = RECUR (ce->index);
13317
13318             if (PACK_EXPANSION_P (ce->value))
13319               {
13320                 /* Substitute into the pack expansion.  */
13321                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
13322                                                   in_decl);
13323
13324                 if (ce->value == error_mark_node
13325                     || PACK_EXPANSION_P (ce->value))
13326                   ;
13327                 else if (TREE_VEC_LENGTH (ce->value) == 1)
13328                   /* Just move the argument into place.  */
13329                   ce->value = TREE_VEC_ELT (ce->value, 0);
13330                 else
13331                   {
13332                     /* Update the length of the final CONSTRUCTOR
13333                        arguments vector, and note that we will need to
13334                        copy.*/
13335                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
13336                     need_copy_p = true;
13337                   }
13338               }
13339             else
13340               ce->value = RECUR (ce->value);
13341           }
13342
13343         if (need_copy_p)
13344           {
13345             VEC(constructor_elt,gc) *old_n = n;
13346
13347             n = VEC_alloc (constructor_elt, gc, newlen);
13348             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
13349               {
13350                 if (TREE_CODE (ce->value) == TREE_VEC)
13351                   {
13352                     int i, len = TREE_VEC_LENGTH (ce->value);
13353                     for (i = 0; i < len; ++i)
13354                       CONSTRUCTOR_APPEND_ELT (n, 0,
13355                                               TREE_VEC_ELT (ce->value, i));
13356                   }
13357                 else
13358                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
13359               }
13360           }
13361
13362         r = build_constructor (init_list_type_node, n);
13363         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
13364
13365         if (TREE_HAS_CONSTRUCTOR (t))
13366           return finish_compound_literal (type, r, complain);
13367
13368         TREE_TYPE (r) = type;
13369         return r;
13370       }
13371
13372     case TYPEID_EXPR:
13373       {
13374         tree operand_0 = TREE_OPERAND (t, 0);
13375         if (TYPE_P (operand_0))
13376           {
13377             operand_0 = tsubst (operand_0, args, complain, in_decl);
13378             return get_typeid (operand_0);
13379           }
13380         else
13381           {
13382             operand_0 = RECUR (operand_0);
13383             return build_typeid (operand_0);
13384           }
13385       }
13386
13387     case VAR_DECL:
13388       if (!args)
13389         return t;
13390       /* Fall through */
13391
13392     case PARM_DECL:
13393       {
13394         tree r = tsubst_copy (t, args, complain, in_decl);
13395
13396         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
13397           /* If the original type was a reference, we'll be wrapped in
13398              the appropriate INDIRECT_REF.  */
13399           r = convert_from_reference (r);
13400         return r;
13401       }
13402
13403     case VA_ARG_EXPR:
13404       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
13405                              tsubst (TREE_TYPE (t), args, complain, in_decl));
13406
13407     case OFFSETOF_EXPR:
13408       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
13409
13410     case TRAIT_EXPR:
13411       {
13412         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
13413                                   complain, in_decl);
13414
13415         tree type2 = TRAIT_EXPR_TYPE2 (t);
13416         if (type2)
13417           type2 = tsubst_copy (type2, args, complain, in_decl);
13418         
13419         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
13420       }
13421
13422     case STMT_EXPR:
13423       {
13424         tree old_stmt_expr = cur_stmt_expr;
13425         tree stmt_expr = begin_stmt_expr ();
13426
13427         cur_stmt_expr = stmt_expr;
13428         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
13429                      integral_constant_expression_p);
13430         stmt_expr = finish_stmt_expr (stmt_expr, false);
13431         cur_stmt_expr = old_stmt_expr;
13432
13433         /* If the resulting list of expression statement is empty,
13434            fold it further into void_zero_node.  */
13435         if (empty_expr_stmt_p (stmt_expr))
13436           stmt_expr = void_zero_node;
13437
13438         return stmt_expr;
13439       }
13440
13441     case CONST_DECL:
13442       t = tsubst_copy (t, args, complain, in_decl);
13443       /* As in finish_id_expression, we resolve enumeration constants
13444          to their underlying values.  */
13445       if (TREE_CODE (t) == CONST_DECL)
13446         {
13447           used_types_insert (TREE_TYPE (t));
13448           return DECL_INITIAL (t);
13449         }
13450       return t;
13451
13452     case LAMBDA_EXPR:
13453       {
13454         tree r = build_lambda_expr ();
13455
13456         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
13457         TREE_TYPE (r) = type;
13458         CLASSTYPE_LAMBDA_EXPR (type) = r;
13459
13460         LAMBDA_EXPR_LOCATION (r)
13461           = LAMBDA_EXPR_LOCATION (t);
13462         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
13463           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
13464         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
13465         LAMBDA_EXPR_DISCRIMINATOR (r)
13466           = (LAMBDA_EXPR_DISCRIMINATOR (t));
13467         LAMBDA_EXPR_CAPTURE_LIST (r)
13468           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
13469         LAMBDA_EXPR_THIS_CAPTURE (r)
13470           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
13471         LAMBDA_EXPR_EXTRA_SCOPE (r)
13472           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
13473
13474         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
13475         determine_visibility (TYPE_NAME (type));
13476         /* Now that we know visibility, instantiate the type so we have a
13477            declaration of the op() for later calls to lambda_function.  */
13478         complete_type (type);
13479
13480         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
13481         if (type)
13482           apply_lambda_return_type (r, type);
13483
13484         return build_lambda_object (r);
13485       }
13486
13487     case TARGET_EXPR:
13488       /* We can get here for a constant initializer of non-dependent type.
13489          FIXME stop folding in cp_parser_initializer_clause.  */
13490       gcc_assert (TREE_CONSTANT (t));
13491       {
13492         tree r = get_target_expr (RECUR (TARGET_EXPR_INITIAL (t)));
13493         TREE_CONSTANT (r) = true;
13494         return r;
13495       }
13496
13497     default:
13498       /* Handle Objective-C++ constructs, if appropriate.  */
13499       {
13500         tree subst
13501           = objcp_tsubst_copy_and_build (t, args, complain,
13502                                          in_decl, /*function_p=*/false);
13503         if (subst)
13504           return subst;
13505       }
13506       return tsubst_copy (t, args, complain, in_decl);
13507     }
13508
13509 #undef RECUR
13510 }
13511
13512 /* Verify that the instantiated ARGS are valid. For type arguments,
13513    make sure that the type's linkage is ok. For non-type arguments,
13514    make sure they are constants if they are integral or enumerations.
13515    Emit an error under control of COMPLAIN, and return TRUE on error.  */
13516
13517 static bool
13518 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
13519 {
13520   if (ARGUMENT_PACK_P (t))
13521     {
13522       tree vec = ARGUMENT_PACK_ARGS (t);
13523       int len = TREE_VEC_LENGTH (vec);
13524       bool result = false;
13525       int i;
13526
13527       for (i = 0; i < len; ++i)
13528         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
13529           result = true;
13530       return result;
13531     }
13532   else if (TYPE_P (t))
13533     {
13534       /* [basic.link]: A name with no linkage (notably, the name
13535          of a class or enumeration declared in a local scope)
13536          shall not be used to declare an entity with linkage.
13537          This implies that names with no linkage cannot be used as
13538          template arguments
13539
13540          DR 757 relaxes this restriction for C++0x.  */
13541       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
13542                  : no_linkage_check (t, /*relaxed_p=*/false));
13543
13544       if (nt)
13545         {
13546           /* DR 488 makes use of a type with no linkage cause
13547              type deduction to fail.  */
13548           if (complain & tf_error)
13549             {
13550               if (TYPE_ANONYMOUS_P (nt))
13551                 error ("%qT is/uses anonymous type", t);
13552               else
13553                 error ("template argument for %qD uses local type %qT",
13554                        tmpl, t);
13555             }
13556           return true;
13557         }
13558       /* In order to avoid all sorts of complications, we do not
13559          allow variably-modified types as template arguments.  */
13560       else if (variably_modified_type_p (t, NULL_TREE))
13561         {
13562           if (complain & tf_error)
13563             error ("%qT is a variably modified type", t);
13564           return true;
13565         }
13566     }
13567   /* A non-type argument of integral or enumerated type must be a
13568      constant.  */
13569   else if (TREE_TYPE (t)
13570            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
13571            && !TREE_CONSTANT (t))
13572     {
13573       if (complain & tf_error)
13574         error ("integral expression %qE is not constant", t);
13575       return true;
13576     }
13577   return false;
13578 }
13579
13580 static bool
13581 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
13582 {
13583   int ix, len = DECL_NTPARMS (tmpl);
13584   bool result = false;
13585
13586   for (ix = 0; ix != len; ix++)
13587     {
13588       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
13589         result = true;
13590     }
13591   if (result && (complain & tf_error))
13592     error ("  trying to instantiate %qD", tmpl);
13593   return result;
13594 }
13595
13596 /* In C++0x, it's possible to have a function template whose type depends
13597    on itself recursively.  This is most obvious with decltype, but can also
13598    occur with enumeration scope (c++/48969).  So we need to catch infinite
13599    recursion and reject the substitution at deduction time; this function
13600    will return error_mark_node for any repeated substitution.
13601
13602    This also catches excessive recursion such as when f<N> depends on
13603    f<N-1> across all integers, and returns error_mark_node for all the
13604    substitutions back up to the initial one.
13605
13606    This is, of course, not reentrant.  */
13607
13608 static tree
13609 deduction_tsubst_fntype (tree fn, tree targs)
13610 {
13611   static bool excessive_deduction_depth;
13612   static int deduction_depth;
13613   location_t save_loc = input_location;
13614   struct pending_template *old_last_pend = last_pending_template;
13615
13616   tree fntype = TREE_TYPE (fn);
13617   tree tinst;
13618   tree r;
13619
13620   if (excessive_deduction_depth)
13621     return error_mark_node;
13622
13623   tinst = build_tree_list (fn, targs);
13624   if (!push_tinst_level (tinst))
13625     {
13626       excessive_deduction_depth = true;
13627       ggc_free (tinst);
13628       return error_mark_node;
13629     }
13630
13631   input_location = DECL_SOURCE_LOCATION (fn);
13632   ++deduction_depth;
13633   push_deduction_access_scope (fn);
13634   r = tsubst (fntype, targs, tf_none, NULL_TREE);
13635   pop_deduction_access_scope (fn);
13636   --deduction_depth;
13637   input_location = save_loc;
13638
13639   if (excessive_deduction_depth)
13640     {
13641       r = error_mark_node;
13642       if (deduction_depth == 0)
13643         /* Reset once we're all the way out.  */
13644         excessive_deduction_depth = false;
13645     }
13646
13647   pop_tinst_level ();
13648   /* We can't free this if a pending_template entry is pointing at it.  */
13649   if (last_pending_template == old_last_pend)
13650     ggc_free (tinst);
13651   return r;
13652 }
13653
13654 /* Instantiate the indicated variable or function template TMPL with
13655    the template arguments in TARG_PTR.  */
13656
13657 static tree
13658 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
13659 {
13660   tree targ_ptr = orig_args;
13661   tree fndecl;
13662   tree gen_tmpl;
13663   tree spec;
13664   HOST_WIDE_INT saved_processing_template_decl;
13665
13666   if (tmpl == error_mark_node)
13667     return error_mark_node;
13668
13669   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
13670
13671   /* If this function is a clone, handle it specially.  */
13672   if (DECL_CLONED_FUNCTION_P (tmpl))
13673     {
13674       tree spec;
13675       tree clone;
13676
13677       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
13678          DECL_CLONED_FUNCTION.  */
13679       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
13680                                    targ_ptr, complain);
13681       if (spec == error_mark_node)
13682         return error_mark_node;
13683
13684       /* Look for the clone.  */
13685       FOR_EACH_CLONE (clone, spec)
13686         if (DECL_NAME (clone) == DECL_NAME (tmpl))
13687           return clone;
13688       /* We should always have found the clone by now.  */
13689       gcc_unreachable ();
13690       return NULL_TREE;
13691     }
13692
13693   /* Check to see if we already have this specialization.  */
13694   gen_tmpl = most_general_template (tmpl);
13695   if (tmpl != gen_tmpl)
13696     /* The TMPL is a partial instantiation.  To get a full set of
13697        arguments we must add the arguments used to perform the
13698        partial instantiation.  */
13699     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
13700                                             targ_ptr);
13701
13702   /* It would be nice to avoid hashing here and then again in tsubst_decl,
13703      but it doesn't seem to be on the hot path.  */
13704   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
13705
13706   gcc_assert (tmpl == gen_tmpl
13707               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
13708                   == spec)
13709               || fndecl == NULL_TREE);
13710
13711   if (spec != NULL_TREE)
13712     return spec;
13713
13714   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
13715                                complain))
13716     return error_mark_node;
13717
13718   /* We are building a FUNCTION_DECL, during which the access of its
13719      parameters and return types have to be checked.  However this
13720      FUNCTION_DECL which is the desired context for access checking
13721      is not built yet.  We solve this chicken-and-egg problem by
13722      deferring all checks until we have the FUNCTION_DECL.  */
13723   push_deferring_access_checks (dk_deferred);
13724
13725   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
13726      (because, for example, we have encountered a non-dependent
13727      function call in the body of a template function and must now
13728      determine which of several overloaded functions will be called),
13729      within the instantiation itself we are not processing a
13730      template.  */  
13731   saved_processing_template_decl = processing_template_decl;
13732   processing_template_decl = 0;
13733   /* Substitute template parameters to obtain the specialization.  */
13734   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
13735                    targ_ptr, complain, gen_tmpl);
13736   processing_template_decl = saved_processing_template_decl;
13737   if (fndecl == error_mark_node)
13738     return error_mark_node;
13739
13740   /* Now we know the specialization, compute access previously
13741      deferred.  */
13742   push_access_scope (fndecl);
13743
13744   /* Some typedefs referenced from within the template code need to be access
13745      checked at template instantiation time, i.e now. These types were
13746      added to the template at parsing time. Let's get those and perfom
13747      the acces checks then.  */
13748   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
13749   perform_deferred_access_checks ();
13750   pop_access_scope (fndecl);
13751   pop_deferring_access_checks ();
13752
13753   /* The DECL_TI_TEMPLATE should always be the immediate parent
13754      template, not the most general template.  */
13755   DECL_TI_TEMPLATE (fndecl) = tmpl;
13756
13757   /* If we've just instantiated the main entry point for a function,
13758      instantiate all the alternate entry points as well.  We do this
13759      by cloning the instantiation of the main entry point, not by
13760      instantiating the template clones.  */
13761   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
13762     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
13763
13764   return fndecl;
13765 }
13766
13767 /* Wrapper for instantiate_template_1.  */
13768
13769 tree
13770 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
13771 {
13772   tree ret;
13773   timevar_push (TV_TEMPLATE_INST);
13774   ret = instantiate_template_1 (tmpl, orig_args,  complain);
13775   timevar_pop (TV_TEMPLATE_INST);
13776   return ret;
13777 }
13778
13779 /* We're going to do deduction substitution on the type of TMPL, a function
13780    template.  In C++11 mode, push into that access scope.  In C++03 mode,
13781    disable access checking.  */
13782
13783 static void
13784 push_deduction_access_scope (tree tmpl)
13785 {
13786   if (cxx_dialect >= cxx0x)
13787     push_access_scope (DECL_TEMPLATE_RESULT (tmpl));
13788   else
13789     push_deferring_access_checks (dk_no_check);
13790 }
13791
13792 /* And pop back out.  */
13793
13794 static void
13795 pop_deduction_access_scope (tree tmpl)
13796 {
13797   if (cxx_dialect >= cxx0x)
13798     pop_access_scope (DECL_TEMPLATE_RESULT (tmpl));
13799   else
13800     pop_deferring_access_checks ();
13801 }
13802
13803 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
13804    NARGS elements of the arguments that are being used when calling
13805    it.  TARGS is a vector into which the deduced template arguments
13806    are placed.
13807
13808    Return zero for success, 2 for an incomplete match that doesn't resolve
13809    all the types, and 1 for complete failure.  An error message will be
13810    printed only for an incomplete match.
13811
13812    If FN is a conversion operator, or we are trying to produce a specific
13813    specialization, RETURN_TYPE is the return type desired.
13814
13815    The EXPLICIT_TARGS are explicit template arguments provided via a
13816    template-id.
13817
13818    The parameter STRICT is one of:
13819
13820    DEDUCE_CALL:
13821      We are deducing arguments for a function call, as in
13822      [temp.deduct.call].
13823
13824    DEDUCE_CONV:
13825      We are deducing arguments for a conversion function, as in
13826      [temp.deduct.conv].
13827
13828    DEDUCE_EXACT:
13829      We are deducing arguments when doing an explicit instantiation
13830      as in [temp.explicit], when determining an explicit specialization
13831      as in [temp.expl.spec], or when taking the address of a function
13832      template, as in [temp.deduct.funcaddr].  */
13833
13834 int
13835 fn_type_unification (tree fn,
13836                      tree explicit_targs,
13837                      tree targs,
13838                      const tree *args,
13839                      unsigned int nargs,
13840                      tree return_type,
13841                      unification_kind_t strict,
13842                      int flags)
13843 {
13844   tree parms;
13845   tree fntype;
13846   int result;
13847   bool incomplete_argument_packs_p = false;
13848
13849   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13850
13851   fntype = TREE_TYPE (fn);
13852   if (explicit_targs)
13853     {
13854       /* [temp.deduct]
13855
13856          The specified template arguments must match the template
13857          parameters in kind (i.e., type, nontype, template), and there
13858          must not be more arguments than there are parameters;
13859          otherwise type deduction fails.
13860
13861          Nontype arguments must match the types of the corresponding
13862          nontype template parameters, or must be convertible to the
13863          types of the corresponding nontype parameters as specified in
13864          _temp.arg.nontype_, otherwise type deduction fails.
13865
13866          All references in the function type of the function template
13867          to the corresponding template parameters are replaced by the
13868          specified template argument values.  If a substitution in a
13869          template parameter or in the function type of the function
13870          template results in an invalid type, type deduction fails.  */
13871       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13872       int i, len = TREE_VEC_LENGTH (tparms);
13873       tree converted_args;
13874       bool incomplete = false;
13875
13876       if (explicit_targs == error_mark_node)
13877         return 1;
13878
13879       converted_args
13880         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13881                                   /*require_all_args=*/false,
13882                                   /*use_default_args=*/false));
13883       if (converted_args == error_mark_node)
13884         return 1;
13885
13886       /* Substitute the explicit args into the function type.  This is
13887          necessary so that, for instance, explicitly declared function
13888          arguments can match null pointed constants.  If we were given
13889          an incomplete set of explicit args, we must not do semantic
13890          processing during substitution as we could create partial
13891          instantiations.  */
13892       for (i = 0; i < len; i++)
13893         {
13894           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13895           bool parameter_pack = false;
13896
13897           /* Dig out the actual parm.  */
13898           if (TREE_CODE (parm) == TYPE_DECL
13899               || TREE_CODE (parm) == TEMPLATE_DECL)
13900             {
13901               parm = TREE_TYPE (parm);
13902               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13903             }
13904           else if (TREE_CODE (parm) == PARM_DECL)
13905             {
13906               parm = DECL_INITIAL (parm);
13907               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13908             }
13909
13910           if (parameter_pack)
13911             {
13912               int level, idx;
13913               tree targ;
13914               template_parm_level_and_index (parm, &level, &idx);
13915
13916               /* Mark the argument pack as "incomplete". We could
13917                  still deduce more arguments during unification.
13918                  We remove this mark in type_unification_real.  */
13919               targ = TMPL_ARG (converted_args, level, idx);
13920               if (targ)
13921                 {
13922                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13923                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
13924                     = ARGUMENT_PACK_ARGS (targ);
13925                 }
13926
13927               /* We have some incomplete argument packs.  */
13928               incomplete_argument_packs_p = true;
13929             }
13930         }
13931
13932       if (incomplete_argument_packs_p)
13933         /* Any substitution is guaranteed to be incomplete if there
13934            are incomplete argument packs, because we can still deduce
13935            more arguments.  */
13936         incomplete = 1;
13937       else
13938         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
13939
13940       processing_template_decl += incomplete;
13941       fntype = deduction_tsubst_fntype (fn, converted_args);
13942       processing_template_decl -= incomplete;
13943
13944       if (fntype == error_mark_node)
13945         return 1;
13946
13947       /* Place the explicitly specified arguments in TARGS.  */
13948       for (i = NUM_TMPL_ARGS (converted_args); i--;)
13949         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
13950     }
13951
13952   /* Never do unification on the 'this' parameter.  */
13953   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
13954
13955   if (return_type)
13956     {
13957       tree *new_args;
13958
13959       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
13960       new_args = XALLOCAVEC (tree, nargs + 1);
13961       new_args[0] = return_type;
13962       memcpy (new_args + 1, args, nargs * sizeof (tree));
13963       args = new_args;
13964       ++nargs;
13965     }
13966
13967   /* We allow incomplete unification without an error message here
13968      because the standard doesn't seem to explicitly prohibit it.  Our
13969      callers must be ready to deal with unification failures in any
13970      event.  */
13971   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
13972                                   targs, parms, args, nargs, /*subr=*/0,
13973                                   strict, flags);
13974
13975   /* Now that we have bindings for all of the template arguments,
13976      ensure that the arguments deduced for the template template
13977      parameters have compatible template parameter lists.  We cannot
13978      check this property before we have deduced all template
13979      arguments, because the template parameter types of a template
13980      template parameter might depend on prior template parameters
13981      deduced after the template template parameter.  The following
13982      ill-formed example illustrates this issue:
13983
13984        template<typename T, template<T> class C> void f(C<5>, T);
13985
13986        template<int N> struct X {};
13987
13988        void g() {
13989          f(X<5>(), 5l); // error: template argument deduction fails
13990        }
13991
13992      The template parameter list of 'C' depends on the template type
13993      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13994      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13995      time that we deduce 'C'.  */
13996   if (result == 0
13997       && !template_template_parm_bindings_ok_p 
13998            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13999     return 1;
14000
14001   if (result == 0)
14002     /* All is well so far.  Now, check:
14003
14004        [temp.deduct]
14005
14006        When all template arguments have been deduced, all uses of
14007        template parameters in nondeduced contexts are replaced with
14008        the corresponding deduced argument values.  If the
14009        substitution results in an invalid type, as described above,
14010        type deduction fails.  */
14011     {
14012       tree substed = deduction_tsubst_fntype (fn, targs);
14013       if (substed == error_mark_node)
14014         return 1;
14015
14016       /* If we're looking for an exact match, check that what we got
14017          is indeed an exact match.  It might not be if some template
14018          parameters are used in non-deduced contexts.  */
14019       if (strict == DEDUCE_EXACT)
14020         {
14021           unsigned int i;
14022
14023           tree sarg
14024             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
14025           if (return_type)
14026             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
14027           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
14028             if (!same_type_p (args[i], TREE_VALUE (sarg)))
14029               return 1;
14030         }
14031     }
14032
14033   return result;
14034 }
14035
14036 /* Adjust types before performing type deduction, as described in
14037    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
14038    sections are symmetric.  PARM is the type of a function parameter
14039    or the return type of the conversion function.  ARG is the type of
14040    the argument passed to the call, or the type of the value
14041    initialized with the result of the conversion function.
14042    ARG_EXPR is the original argument expression, which may be null.  */
14043
14044 static int
14045 maybe_adjust_types_for_deduction (unification_kind_t strict,
14046                                   tree* parm,
14047                                   tree* arg,
14048                                   tree arg_expr)
14049 {
14050   int result = 0;
14051
14052   switch (strict)
14053     {
14054     case DEDUCE_CALL:
14055       break;
14056
14057     case DEDUCE_CONV:
14058       {
14059         /* Swap PARM and ARG throughout the remainder of this
14060            function; the handling is precisely symmetric since PARM
14061            will initialize ARG rather than vice versa.  */
14062         tree* temp = parm;
14063         parm = arg;
14064         arg = temp;
14065         break;
14066       }
14067
14068     case DEDUCE_EXACT:
14069       /* Core issue #873: Do the DR606 thing (see below) for these cases,
14070          too, but here handle it by stripping the reference from PARM
14071          rather than by adding it to ARG.  */
14072       if (TREE_CODE (*parm) == REFERENCE_TYPE
14073           && TYPE_REF_IS_RVALUE (*parm)
14074           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14075           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14076           && TREE_CODE (*arg) == REFERENCE_TYPE
14077           && !TYPE_REF_IS_RVALUE (*arg))
14078         *parm = TREE_TYPE (*parm);
14079       /* Nothing else to do in this case.  */
14080       return 0;
14081
14082     default:
14083       gcc_unreachable ();
14084     }
14085
14086   if (TREE_CODE (*parm) != REFERENCE_TYPE)
14087     {
14088       /* [temp.deduct.call]
14089
14090          If P is not a reference type:
14091
14092          --If A is an array type, the pointer type produced by the
14093          array-to-pointer standard conversion (_conv.array_) is
14094          used in place of A for type deduction; otherwise,
14095
14096          --If A is a function type, the pointer type produced by
14097          the function-to-pointer standard conversion
14098          (_conv.func_) is used in place of A for type deduction;
14099          otherwise,
14100
14101          --If A is a cv-qualified type, the top level
14102          cv-qualifiers of A's type are ignored for type
14103          deduction.  */
14104       if (TREE_CODE (*arg) == ARRAY_TYPE)
14105         *arg = build_pointer_type (TREE_TYPE (*arg));
14106       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
14107         *arg = build_pointer_type (*arg);
14108       else
14109         *arg = TYPE_MAIN_VARIANT (*arg);
14110     }
14111
14112   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
14113      of the form T&&, where T is a template parameter, and the argument
14114      is an lvalue, T is deduced as A& */
14115   if (TREE_CODE (*parm) == REFERENCE_TYPE
14116       && TYPE_REF_IS_RVALUE (*parm)
14117       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14118       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14119       && (arg_expr ? real_lvalue_p (arg_expr)
14120           /* try_one_overload doesn't provide an arg_expr, but
14121              functions are always lvalues.  */
14122           : TREE_CODE (*arg) == FUNCTION_TYPE))
14123     *arg = build_reference_type (*arg);
14124
14125   /* [temp.deduct.call]
14126
14127      If P is a cv-qualified type, the top level cv-qualifiers
14128      of P's type are ignored for type deduction.  If P is a
14129      reference type, the type referred to by P is used for
14130      type deduction.  */
14131   *parm = TYPE_MAIN_VARIANT (*parm);
14132   if (TREE_CODE (*parm) == REFERENCE_TYPE)
14133     {
14134       *parm = TREE_TYPE (*parm);
14135       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14136     }
14137
14138   /* DR 322. For conversion deduction, remove a reference type on parm
14139      too (which has been swapped into ARG).  */
14140   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
14141     *arg = TREE_TYPE (*arg);
14142
14143   return result;
14144 }
14145
14146 /* Most parms like fn_type_unification.
14147
14148    If SUBR is 1, we're being called recursively (to unify the
14149    arguments of a function or method parameter of a function
14150    template). */
14151
14152 static int
14153 type_unification_real (tree tparms,
14154                        tree targs,
14155                        tree xparms,
14156                        const tree *xargs,
14157                        unsigned int xnargs,
14158                        int subr,
14159                        unification_kind_t strict,
14160                        int flags)
14161 {
14162   tree parm, arg, arg_expr;
14163   int i;
14164   int ntparms = TREE_VEC_LENGTH (tparms);
14165   int sub_strict;
14166   int saw_undeduced = 0;
14167   tree parms;
14168   const tree *args;
14169   unsigned int nargs;
14170   unsigned int ia;
14171
14172   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
14173   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
14174   gcc_assert (ntparms > 0);
14175
14176   /* Reset the number of non-defaulted template arguments contained
14177      in TARGS.  */
14178   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
14179
14180   switch (strict)
14181     {
14182     case DEDUCE_CALL:
14183       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
14184                     | UNIFY_ALLOW_DERIVED);
14185       break;
14186
14187     case DEDUCE_CONV:
14188       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14189       break;
14190
14191     case DEDUCE_EXACT:
14192       sub_strict = UNIFY_ALLOW_NONE;
14193       break;
14194
14195     default:
14196       gcc_unreachable ();
14197     }
14198
14199  again:
14200   parms = xparms;
14201   args = xargs;
14202   nargs = xnargs;
14203
14204   ia = 0;
14205   while (parms && parms != void_list_node
14206          && ia < nargs)
14207     {
14208       parm = TREE_VALUE (parms);
14209
14210       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
14211           && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
14212         /* For a function parameter pack that occurs at the end of the
14213            parameter-declaration-list, the type A of each remaining
14214            argument of the call is compared with the type P of the
14215            declarator-id of the function parameter pack.  */
14216         break;
14217
14218       parms = TREE_CHAIN (parms);
14219
14220       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
14221         /* For a function parameter pack that does not occur at the
14222            end of the parameter-declaration-list, the type of the
14223            parameter pack is a non-deduced context.  */
14224         continue;
14225
14226       arg = args[ia];
14227       ++ia;
14228       arg_expr = NULL;
14229
14230       if (arg == error_mark_node)
14231         return 1;
14232       if (arg == unknown_type_node)
14233         /* We can't deduce anything from this, but we might get all the
14234            template args from other function args.  */
14235         continue;
14236
14237       /* Conversions will be performed on a function argument that
14238          corresponds with a function parameter that contains only
14239          non-deducible template parameters and explicitly specified
14240          template parameters.  */
14241       if (!uses_template_parms (parm))
14242         {
14243           tree type;
14244
14245           if (!TYPE_P (arg))
14246             type = TREE_TYPE (arg);
14247           else
14248             type = arg;
14249
14250           if (same_type_p (parm, type))
14251             continue;
14252           if (strict != DEDUCE_EXACT
14253               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
14254                                   flags))
14255             continue;
14256
14257           return 1;
14258         }
14259
14260       if (!TYPE_P (arg))
14261         {
14262           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14263           if (type_unknown_p (arg))
14264             {
14265               /* [temp.deduct.type] 
14266
14267                  A template-argument can be deduced from a pointer to
14268                  function or pointer to member function argument if
14269                  the set of overloaded functions does not contain
14270                  function templates and at most one of a set of
14271                  overloaded functions provides a unique match.  */
14272               if (resolve_overloaded_unification
14273                   (tparms, targs, parm, arg, strict, sub_strict))
14274                 continue;
14275
14276               return 1;
14277             }
14278           arg_expr = arg;
14279           arg = unlowered_expr_type (arg);
14280           if (arg == error_mark_node)
14281             return 1;
14282         }
14283
14284       {
14285         int arg_strict = sub_strict;
14286
14287         if (!subr)
14288           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
14289                                                           arg_expr);
14290
14291         if (arg == init_list_type_node && arg_expr)
14292           arg = arg_expr;
14293         if (unify (tparms, targs, parm, arg, arg_strict))
14294           return 1;
14295       }
14296     }
14297
14298
14299   if (parms 
14300       && parms != void_list_node
14301       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
14302     {
14303       /* Unify the remaining arguments with the pack expansion type.  */
14304       tree argvec;
14305       tree parmvec = make_tree_vec (1);
14306
14307       /* Allocate a TREE_VEC and copy in all of the arguments */ 
14308       argvec = make_tree_vec (nargs - ia);
14309       for (i = 0; ia < nargs; ++ia, ++i)
14310         TREE_VEC_ELT (argvec, i) = args[ia];
14311
14312       /* Copy the parameter into parmvec.  */
14313       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
14314       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
14315                                 /*call_args_p=*/true, /*subr=*/subr))
14316         return 1;
14317
14318       /* Advance to the end of the list of parameters.  */
14319       parms = TREE_CHAIN (parms);
14320     }
14321
14322   /* Fail if we've reached the end of the parm list, and more args
14323      are present, and the parm list isn't variadic.  */
14324   if (ia < nargs && parms == void_list_node)
14325     return 1;
14326   /* Fail if parms are left and they don't have default values.  */
14327   if (parms && parms != void_list_node
14328       && TREE_PURPOSE (parms) == NULL_TREE)
14329     return 1;
14330
14331   if (!subr)
14332     {
14333       /* Check to see if we need another pass before we start clearing
14334          ARGUMENT_PACK_INCOMPLETE_P.  */
14335       for (i = 0; i < ntparms; i++)
14336         {
14337           tree targ = TREE_VEC_ELT (targs, i);
14338           tree tparm = TREE_VEC_ELT (tparms, i);
14339
14340           if (targ || tparm == error_mark_node)
14341             continue;
14342           tparm = TREE_VALUE (tparm);
14343
14344           /* If this is an undeduced nontype parameter that depends on
14345              a type parameter, try another pass; its type may have been
14346              deduced from a later argument than the one from which
14347              this parameter can be deduced.  */
14348           if (TREE_CODE (tparm) == PARM_DECL
14349               && uses_template_parms (TREE_TYPE (tparm))
14350               && !saw_undeduced++)
14351             goto again;
14352         }
14353
14354       for (i = 0; i < ntparms; i++)
14355         {
14356           tree targ = TREE_VEC_ELT (targs, i);
14357           tree tparm = TREE_VEC_ELT (tparms, i);
14358
14359           /* Clear the "incomplete" flags on all argument packs now so that
14360              substituting them into later default arguments works.  */
14361           if (targ && ARGUMENT_PACK_P (targ))
14362             {
14363               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
14364               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
14365             }
14366
14367           if (targ || tparm == error_mark_node)
14368             continue;
14369           tparm = TREE_VALUE (tparm);
14370
14371           /* Core issue #226 (C++0x) [temp.deduct]:
14372
14373              If a template argument has not been deduced, its
14374              default template argument, if any, is used. 
14375
14376              When we are in C++98 mode, TREE_PURPOSE will either
14377              be NULL_TREE or ERROR_MARK_NODE, so we do not need
14378              to explicitly check cxx_dialect here.  */
14379           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
14380             {
14381               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14382               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
14383               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
14384               arg = convert_template_argument (parm, arg, targs, tf_none,
14385                                                i, NULL_TREE);
14386               if (arg == error_mark_node)
14387                 return 1;
14388               else
14389                 {
14390                   TREE_VEC_ELT (targs, i) = arg;
14391                   /* The position of the first default template argument,
14392                      is also the number of non-defaulted arguments in TARGS.
14393                      Record that.  */
14394                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14395                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
14396                   continue;
14397                 }
14398             }
14399
14400           /* If the type parameter is a parameter pack, then it will
14401              be deduced to an empty parameter pack.  */
14402           if (template_parameter_pack_p (tparm))
14403             {
14404               tree arg;
14405
14406               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
14407                 {
14408                   arg = make_node (NONTYPE_ARGUMENT_PACK);
14409                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
14410                   TREE_CONSTANT (arg) = 1;
14411                 }
14412               else
14413                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
14414
14415               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
14416
14417               TREE_VEC_ELT (targs, i) = arg;
14418               continue;
14419             }
14420
14421           return 2;
14422         }
14423     }
14424 #ifdef ENABLE_CHECKING
14425   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14426     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
14427 #endif
14428
14429   return 0;
14430 }
14431
14432 /* Subroutine of type_unification_real.  Args are like the variables
14433    at the call site.  ARG is an overloaded function (or template-id);
14434    we try deducing template args from each of the overloads, and if
14435    only one succeeds, we go with that.  Modifies TARGS and returns
14436    true on success.  */
14437
14438 static bool
14439 resolve_overloaded_unification (tree tparms,
14440                                 tree targs,
14441                                 tree parm,
14442                                 tree arg,
14443                                 unification_kind_t strict,
14444                                 int sub_strict)
14445 {
14446   tree tempargs = copy_node (targs);
14447   int good = 0;
14448   tree goodfn = NULL_TREE;
14449   bool addr_p;
14450
14451   if (TREE_CODE (arg) == ADDR_EXPR)
14452     {
14453       arg = TREE_OPERAND (arg, 0);
14454       addr_p = true;
14455     }
14456   else
14457     addr_p = false;
14458
14459   if (TREE_CODE (arg) == COMPONENT_REF)
14460     /* Handle `&x' where `x' is some static or non-static member
14461        function name.  */
14462     arg = TREE_OPERAND (arg, 1);
14463
14464   if (TREE_CODE (arg) == OFFSET_REF)
14465     arg = TREE_OPERAND (arg, 1);
14466
14467   /* Strip baselink information.  */
14468   if (BASELINK_P (arg))
14469     arg = BASELINK_FUNCTIONS (arg);
14470
14471   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
14472     {
14473       /* If we got some explicit template args, we need to plug them into
14474          the affected templates before we try to unify, in case the
14475          explicit args will completely resolve the templates in question.  */
14476
14477       tree expl_subargs = TREE_OPERAND (arg, 1);
14478       arg = TREE_OPERAND (arg, 0);
14479
14480       for (; arg; arg = OVL_NEXT (arg))
14481         {
14482           tree fn = OVL_CURRENT (arg);
14483           tree subargs, elem;
14484
14485           if (TREE_CODE (fn) != TEMPLATE_DECL)
14486             continue;
14487
14488           ++processing_template_decl;
14489           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
14490                                   expl_subargs, /*check_ret=*/false);
14491           if (subargs)
14492             {
14493               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
14494               if (try_one_overload (tparms, targs, tempargs, parm,
14495                                     elem, strict, sub_strict, addr_p)
14496                   && (!goodfn || !decls_match (goodfn, elem)))
14497                 {
14498                   goodfn = elem;
14499                   ++good;
14500                 }
14501             }
14502           --processing_template_decl;
14503         }
14504     }
14505   else if (TREE_CODE (arg) != OVERLOAD
14506            && TREE_CODE (arg) != FUNCTION_DECL)
14507     /* If ARG is, for example, "(0, &f)" then its type will be unknown
14508        -- but the deduction does not succeed because the expression is
14509        not just the function on its own.  */
14510     return false;
14511   else
14512     for (; arg; arg = OVL_NEXT (arg))
14513       if (try_one_overload (tparms, targs, tempargs, parm,
14514                             TREE_TYPE (OVL_CURRENT (arg)),
14515                             strict, sub_strict, addr_p)
14516           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
14517         {
14518           goodfn = OVL_CURRENT (arg);
14519           ++good;
14520         }
14521
14522   /* [temp.deduct.type] A template-argument can be deduced from a pointer
14523      to function or pointer to member function argument if the set of
14524      overloaded functions does not contain function templates and at most
14525      one of a set of overloaded functions provides a unique match.
14526
14527      So if we found multiple possibilities, we return success but don't
14528      deduce anything.  */
14529
14530   if (good == 1)
14531     {
14532       int i = TREE_VEC_LENGTH (targs);
14533       for (; i--; )
14534         if (TREE_VEC_ELT (tempargs, i))
14535           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
14536     }
14537   if (good)
14538     return true;
14539
14540   return false;
14541 }
14542
14543 /* Core DR 115: In contexts where deduction is done and fails, or in
14544    contexts where deduction is not done, if a template argument list is
14545    specified and it, along with any default template arguments, identifies
14546    a single function template specialization, then the template-id is an
14547    lvalue for the function template specialization.  */
14548
14549 tree
14550 resolve_nondeduced_context (tree orig_expr)
14551 {
14552   tree expr, offset, baselink;
14553   bool addr;
14554
14555   if (!type_unknown_p (orig_expr))
14556     return orig_expr;
14557
14558   expr = orig_expr;
14559   addr = false;
14560   offset = NULL_TREE;
14561   baselink = NULL_TREE;
14562
14563   if (TREE_CODE (expr) == ADDR_EXPR)
14564     {
14565       expr = TREE_OPERAND (expr, 0);
14566       addr = true;
14567     }
14568   if (TREE_CODE (expr) == OFFSET_REF)
14569     {
14570       offset = expr;
14571       expr = TREE_OPERAND (expr, 1);
14572     }
14573   if (TREE_CODE (expr) == BASELINK)
14574     {
14575       baselink = expr;
14576       expr = BASELINK_FUNCTIONS (expr);
14577     }
14578
14579   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
14580     {
14581       int good = 0;
14582       tree goodfn = NULL_TREE;
14583
14584       /* If we got some explicit template args, we need to plug them into
14585          the affected templates before we try to unify, in case the
14586          explicit args will completely resolve the templates in question.  */
14587
14588       tree expl_subargs = TREE_OPERAND (expr, 1);
14589       tree arg = TREE_OPERAND (expr, 0);
14590       tree badfn = NULL_TREE;
14591       tree badargs = NULL_TREE;
14592
14593       for (; arg; arg = OVL_NEXT (arg))
14594         {
14595           tree fn = OVL_CURRENT (arg);
14596           tree subargs, elem;
14597
14598           if (TREE_CODE (fn) != TEMPLATE_DECL)
14599             continue;
14600
14601           ++processing_template_decl;
14602           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
14603                                   expl_subargs, /*check_ret=*/false);
14604           if (subargs && !any_dependent_template_arguments_p (subargs))
14605             {
14606               elem = instantiate_template (fn, subargs, tf_none);
14607               if (elem == error_mark_node)
14608                 {
14609                   badfn = fn;
14610                   badargs = subargs;
14611                 }
14612               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
14613                 {
14614                   goodfn = elem;
14615                   ++good;
14616                 }
14617             }
14618           --processing_template_decl;
14619         }
14620       if (good == 1)
14621         {
14622           expr = goodfn;
14623           if (baselink)
14624             expr = build_baselink (BASELINK_BINFO (baselink),
14625                                    BASELINK_ACCESS_BINFO (baselink),
14626                                    expr, BASELINK_OPTYPE (baselink));
14627           if (offset)
14628             {
14629               tree base
14630                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
14631               expr = build_offset_ref (base, expr, addr);
14632             }
14633           if (addr)
14634             expr = cp_build_addr_expr (expr, tf_warning_or_error);
14635           return expr;
14636         }
14637       else if (good == 0 && badargs)
14638         /* There were no good options and at least one bad one, so let the
14639            user know what the problem is.  */
14640         instantiate_template (badfn, badargs, tf_warning_or_error);
14641     }
14642   return orig_expr;
14643 }
14644
14645 /* Subroutine of resolve_overloaded_unification; does deduction for a single
14646    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
14647    different overloads deduce different arguments for a given parm.
14648    ADDR_P is true if the expression for which deduction is being
14649    performed was of the form "& fn" rather than simply "fn".
14650
14651    Returns 1 on success.  */
14652
14653 static int
14654 try_one_overload (tree tparms,
14655                   tree orig_targs,
14656                   tree targs,
14657                   tree parm,
14658                   tree arg,
14659                   unification_kind_t strict,
14660                   int sub_strict,
14661                   bool addr_p)
14662 {
14663   int nargs;
14664   tree tempargs;
14665   int i;
14666
14667   /* [temp.deduct.type] A template-argument can be deduced from a pointer
14668      to function or pointer to member function argument if the set of
14669      overloaded functions does not contain function templates and at most
14670      one of a set of overloaded functions provides a unique match.
14671
14672      So if this is a template, just return success.  */
14673
14674   if (uses_template_parms (arg))
14675     return 1;
14676
14677   if (TREE_CODE (arg) == METHOD_TYPE)
14678     arg = build_ptrmemfunc_type (build_pointer_type (arg));
14679   else if (addr_p)
14680     arg = build_pointer_type (arg);
14681
14682   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
14683
14684   /* We don't copy orig_targs for this because if we have already deduced
14685      some template args from previous args, unify would complain when we
14686      try to deduce a template parameter for the same argument, even though
14687      there isn't really a conflict.  */
14688   nargs = TREE_VEC_LENGTH (targs);
14689   tempargs = make_tree_vec (nargs);
14690
14691   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
14692     return 0;
14693
14694   /* First make sure we didn't deduce anything that conflicts with
14695      explicitly specified args.  */
14696   for (i = nargs; i--; )
14697     {
14698       tree elt = TREE_VEC_ELT (tempargs, i);
14699       tree oldelt = TREE_VEC_ELT (orig_targs, i);
14700
14701       if (!elt)
14702         /*NOP*/;
14703       else if (uses_template_parms (elt))
14704         /* Since we're unifying against ourselves, we will fill in
14705            template args used in the function parm list with our own
14706            template parms.  Discard them.  */
14707         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
14708       else if (oldelt && !template_args_equal (oldelt, elt))
14709         return 0;
14710     }
14711
14712   for (i = nargs; i--; )
14713     {
14714       tree elt = TREE_VEC_ELT (tempargs, i);
14715
14716       if (elt)
14717         TREE_VEC_ELT (targs, i) = elt;
14718     }
14719
14720   return 1;
14721 }
14722
14723 /* PARM is a template class (perhaps with unbound template
14724    parameters).  ARG is a fully instantiated type.  If ARG can be
14725    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
14726    TARGS are as for unify.  */
14727
14728 static tree
14729 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
14730 {
14731   tree copy_of_targs;
14732
14733   if (!CLASSTYPE_TEMPLATE_INFO (arg)
14734       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
14735           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
14736     return NULL_TREE;
14737
14738   /* We need to make a new template argument vector for the call to
14739      unify.  If we used TARGS, we'd clutter it up with the result of
14740      the attempted unification, even if this class didn't work out.
14741      We also don't want to commit ourselves to all the unifications
14742      we've already done, since unification is supposed to be done on
14743      an argument-by-argument basis.  In other words, consider the
14744      following pathological case:
14745
14746        template <int I, int J, int K>
14747        struct S {};
14748
14749        template <int I, int J>
14750        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
14751
14752        template <int I, int J, int K>
14753        void f(S<I, J, K>, S<I, I, I>);
14754
14755        void g() {
14756          S<0, 0, 0> s0;
14757          S<0, 1, 2> s2;
14758
14759          f(s0, s2);
14760        }
14761
14762      Now, by the time we consider the unification involving `s2', we
14763      already know that we must have `f<0, 0, 0>'.  But, even though
14764      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
14765      because there are two ways to unify base classes of S<0, 1, 2>
14766      with S<I, I, I>.  If we kept the already deduced knowledge, we
14767      would reject the possibility I=1.  */
14768   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
14769
14770   /* If unification failed, we're done.  */
14771   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
14772              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
14773     return NULL_TREE;
14774
14775   return arg;
14776 }
14777
14778 /* Given a template type PARM and a class type ARG, find the unique
14779    base type in ARG that is an instance of PARM.  We do not examine
14780    ARG itself; only its base-classes.  If there is not exactly one
14781    appropriate base class, return NULL_TREE.  PARM may be the type of
14782    a partial specialization, as well as a plain template type.  Used
14783    by unify.  */
14784
14785 static tree
14786 get_template_base (tree tparms, tree targs, tree parm, tree arg)
14787 {
14788   tree rval = NULL_TREE;
14789   tree binfo;
14790
14791   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
14792
14793   binfo = TYPE_BINFO (complete_type (arg));
14794   if (!binfo)
14795     /* The type could not be completed.  */
14796     return NULL_TREE;
14797
14798   /* Walk in inheritance graph order.  The search order is not
14799      important, and this avoids multiple walks of virtual bases.  */
14800   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
14801     {
14802       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
14803
14804       if (r)
14805         {
14806           /* If there is more than one satisfactory baseclass, then:
14807
14808                [temp.deduct.call]
14809
14810               If they yield more than one possible deduced A, the type
14811               deduction fails.
14812
14813              applies.  */
14814           if (rval && !same_type_p (r, rval))
14815             return NULL_TREE;
14816
14817           rval = r;
14818         }
14819     }
14820
14821   return rval;
14822 }
14823
14824 /* Returns the level of DECL, which declares a template parameter.  */
14825
14826 static int
14827 template_decl_level (tree decl)
14828 {
14829   switch (TREE_CODE (decl))
14830     {
14831     case TYPE_DECL:
14832     case TEMPLATE_DECL:
14833       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
14834
14835     case PARM_DECL:
14836       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
14837
14838     default:
14839       gcc_unreachable ();
14840     }
14841   return 0;
14842 }
14843
14844 /* Decide whether ARG can be unified with PARM, considering only the
14845    cv-qualifiers of each type, given STRICT as documented for unify.
14846    Returns nonzero iff the unification is OK on that basis.  */
14847
14848 static int
14849 check_cv_quals_for_unify (int strict, tree arg, tree parm)
14850 {
14851   int arg_quals = cp_type_quals (arg);
14852   int parm_quals = cp_type_quals (parm);
14853
14854   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14855       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14856     {
14857       /*  Although a CVR qualifier is ignored when being applied to a
14858           substituted template parameter ([8.3.2]/1 for example), that
14859           does not allow us to unify "const T" with "int&" because both
14860           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
14861           It is ok when we're allowing additional CV qualifiers
14862           at the outer level [14.8.2.1]/3,1st bullet.  */
14863       if ((TREE_CODE (arg) == REFERENCE_TYPE
14864            || TREE_CODE (arg) == FUNCTION_TYPE
14865            || TREE_CODE (arg) == METHOD_TYPE)
14866           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14867         return 0;
14868
14869       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14870           && (parm_quals & TYPE_QUAL_RESTRICT))
14871         return 0;
14872     }
14873
14874   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14875       && (arg_quals & parm_quals) != parm_quals)
14876     return 0;
14877
14878   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14879       && (parm_quals & arg_quals) != arg_quals)
14880     return 0;
14881
14882   return 1;
14883 }
14884
14885 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
14886 void 
14887 template_parm_level_and_index (tree parm, int* level, int* index)
14888 {
14889   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14890       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14891       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14892     {
14893       *index = TEMPLATE_TYPE_IDX (parm);
14894       *level = TEMPLATE_TYPE_LEVEL (parm);
14895     }
14896   else
14897     {
14898       *index = TEMPLATE_PARM_IDX (parm);
14899       *level = TEMPLATE_PARM_LEVEL (parm);
14900     }
14901 }
14902
14903 /* Unifies the remaining arguments in PACKED_ARGS with the pack
14904    expansion at the end of PACKED_PARMS. Returns 0 if the type
14905    deduction succeeds, 1 otherwise. STRICT is the same as in
14906    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14907    call argument list. We'll need to adjust the arguments to make them
14908    types. SUBR tells us if this is from a recursive call to
14909    type_unification_real.  */
14910 int
14911 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
14912                       tree packed_args, int strict, bool call_args_p,
14913                       bool subr)
14914 {
14915   tree parm 
14916     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14917   tree pattern = PACK_EXPANSION_PATTERN (parm);
14918   tree pack, packs = NULL_TREE;
14919   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14920   int len = TREE_VEC_LENGTH (packed_args);
14921
14922   /* Determine the parameter packs we will be deducing from the
14923      pattern, and record their current deductions.  */
14924   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
14925        pack; pack = TREE_CHAIN (pack))
14926     {
14927       tree parm_pack = TREE_VALUE (pack);
14928       int idx, level;
14929
14930       /* Determine the index and level of this parameter pack.  */
14931       template_parm_level_and_index (parm_pack, &level, &idx);
14932
14933       /* Keep track of the parameter packs and their corresponding
14934          argument packs.  */
14935       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
14936       TREE_TYPE (packs) = make_tree_vec (len - start);
14937     }
14938   
14939   /* Loop through all of the arguments that have not yet been
14940      unified and unify each with the pattern.  */
14941   for (i = start; i < len; i++)
14942     {
14943       tree parm = pattern;
14944
14945       /* For each parameter pack, clear out the deduced value so that
14946          we can deduce it again.  */
14947       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14948         {
14949           int idx, level;
14950           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14951
14952           TMPL_ARG (targs, level, idx) = NULL_TREE;
14953         }
14954
14955       /* Unify the pattern with the current argument.  */
14956       {
14957         tree arg = TREE_VEC_ELT (packed_args, i);
14958         tree arg_expr = NULL_TREE;
14959         int arg_strict = strict;
14960         bool skip_arg_p = false;
14961
14962         if (call_args_p)
14963           {
14964             int sub_strict;
14965
14966             /* This mirrors what we do in type_unification_real.  */
14967             switch (strict)
14968               {
14969               case DEDUCE_CALL:
14970                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
14971                               | UNIFY_ALLOW_MORE_CV_QUAL
14972                               | UNIFY_ALLOW_DERIVED);
14973                 break;
14974                 
14975               case DEDUCE_CONV:
14976                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14977                 break;
14978                 
14979               case DEDUCE_EXACT:
14980                 sub_strict = UNIFY_ALLOW_NONE;
14981                 break;
14982                 
14983               default:
14984                 gcc_unreachable ();
14985               }
14986
14987             if (!TYPE_P (arg))
14988               {
14989                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14990                 if (type_unknown_p (arg))
14991                   {
14992                     /* [temp.deduct.type] A template-argument can be
14993                        deduced from a pointer to function or pointer
14994                        to member function argument if the set of
14995                        overloaded functions does not contain function
14996                        templates and at most one of a set of
14997                        overloaded functions provides a unique
14998                        match.  */
14999
15000                     if (resolve_overloaded_unification
15001                         (tparms, targs, parm, arg,
15002                          (unification_kind_t) strict,
15003                          sub_strict)
15004                         != 0)
15005                       return 1;
15006                     skip_arg_p = true;
15007                   }
15008
15009                 if (!skip_arg_p)
15010                   {
15011                     arg_expr = arg;
15012                     arg = unlowered_expr_type (arg);
15013                     if (arg == error_mark_node)
15014                       return 1;
15015                   }
15016               }
15017       
15018             arg_strict = sub_strict;
15019
15020             if (!subr)
15021               arg_strict |= 
15022                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
15023                                                   &parm, &arg, arg_expr);
15024           }
15025
15026         if (!skip_arg_p)
15027           {
15028             /* For deduction from an init-list we need the actual list.  */
15029             if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
15030               arg = arg_expr;
15031             if (unify (tparms, targs, parm, arg, arg_strict))
15032               return 1;
15033           }
15034       }
15035
15036       /* For each parameter pack, collect the deduced value.  */
15037       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15038         {
15039           int idx, level;
15040           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15041
15042           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
15043             TMPL_ARG (targs, level, idx);
15044         }
15045     }
15046
15047   /* Verify that the results of unification with the parameter packs
15048      produce results consistent with what we've seen before, and make
15049      the deduced argument packs available.  */
15050   for (pack = packs; pack; pack = TREE_CHAIN (pack))
15051     {
15052       tree old_pack = TREE_VALUE (pack);
15053       tree new_args = TREE_TYPE (pack);
15054       int i, len = TREE_VEC_LENGTH (new_args);
15055       int idx, level;
15056       bool nondeduced_p = false;
15057
15058       /* By default keep the original deduced argument pack.
15059          If necessary, more specific code is going to update the
15060          resulting deduced argument later down in this function.  */
15061       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15062       TMPL_ARG (targs, level, idx) = old_pack;
15063
15064       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
15065          actually deduce anything.  */
15066       for (i = 0; i < len && !nondeduced_p; ++i)
15067         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
15068           nondeduced_p = true;
15069       if (nondeduced_p)
15070         continue;
15071
15072       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
15073         {
15074           /* Prepend the explicit arguments onto NEW_ARGS.  */
15075           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15076           tree old_args = new_args;
15077           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
15078           int len = explicit_len + TREE_VEC_LENGTH (old_args);
15079
15080           /* Copy the explicit arguments.  */
15081           new_args = make_tree_vec (len);
15082           for (i = 0; i < explicit_len; i++)
15083             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
15084
15085           /* Copy the deduced arguments.  */
15086           for (; i < len; i++)
15087             TREE_VEC_ELT (new_args, i) =
15088               TREE_VEC_ELT (old_args, i - explicit_len);
15089         }
15090
15091       if (!old_pack)
15092         {
15093           tree result;
15094           /* Build the deduced *_ARGUMENT_PACK.  */
15095           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
15096             {
15097               result = make_node (NONTYPE_ARGUMENT_PACK);
15098               TREE_TYPE (result) = 
15099                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
15100               TREE_CONSTANT (result) = 1;
15101             }
15102           else
15103             result = cxx_make_type (TYPE_ARGUMENT_PACK);
15104
15105           SET_ARGUMENT_PACK_ARGS (result, new_args);
15106
15107           /* Note the deduced argument packs for this parameter
15108              pack.  */
15109           TMPL_ARG (targs, level, idx) = result;
15110         }
15111       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
15112                && (ARGUMENT_PACK_ARGS (old_pack) 
15113                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
15114         {
15115           /* We only had the explicitly-provided arguments before, but
15116              now we have a complete set of arguments.  */
15117           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15118
15119           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
15120           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
15121           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
15122         }
15123       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
15124                                     new_args))
15125         /* Inconsistent unification of this parameter pack.  */
15126         return 1;
15127     }
15128
15129   return 0;
15130 }
15131
15132 /* Deduce the value of template parameters.  TPARMS is the (innermost)
15133    set of template parameters to a template.  TARGS is the bindings
15134    for those template parameters, as determined thus far; TARGS may
15135    include template arguments for outer levels of template parameters
15136    as well.  PARM is a parameter to a template function, or a
15137    subcomponent of that parameter; ARG is the corresponding argument.
15138    This function attempts to match PARM with ARG in a manner
15139    consistent with the existing assignments in TARGS.  If more values
15140    are deduced, then TARGS is updated.
15141
15142    Returns 0 if the type deduction succeeds, 1 otherwise.  The
15143    parameter STRICT is a bitwise or of the following flags:
15144
15145      UNIFY_ALLOW_NONE:
15146        Require an exact match between PARM and ARG.
15147      UNIFY_ALLOW_MORE_CV_QUAL:
15148        Allow the deduced ARG to be more cv-qualified (by qualification
15149        conversion) than ARG.
15150      UNIFY_ALLOW_LESS_CV_QUAL:
15151        Allow the deduced ARG to be less cv-qualified than ARG.
15152      UNIFY_ALLOW_DERIVED:
15153        Allow the deduced ARG to be a template base class of ARG,
15154        or a pointer to a template base class of the type pointed to by
15155        ARG.
15156      UNIFY_ALLOW_INTEGER:
15157        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
15158        case for more information.
15159      UNIFY_ALLOW_OUTER_LEVEL:
15160        This is the outermost level of a deduction. Used to determine validity
15161        of qualification conversions. A valid qualification conversion must
15162        have const qualified pointers leading up to the inner type which
15163        requires additional CV quals, except at the outer level, where const
15164        is not required [conv.qual]. It would be normal to set this flag in
15165        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
15166      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
15167        This is the outermost level of a deduction, and PARM can be more CV
15168        qualified at this point.
15169      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
15170        This is the outermost level of a deduction, and PARM can be less CV
15171        qualified at this point.  */
15172
15173 static int
15174 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
15175 {
15176   int idx;
15177   tree targ;
15178   tree tparm;
15179   int strict_in = strict;
15180
15181   /* I don't think this will do the right thing with respect to types.
15182      But the only case I've seen it in so far has been array bounds, where
15183      signedness is the only information lost, and I think that will be
15184      okay.  */
15185   while (TREE_CODE (parm) == NOP_EXPR)
15186     parm = TREE_OPERAND (parm, 0);
15187
15188   if (arg == error_mark_node)
15189     return 1;
15190   if (arg == unknown_type_node
15191       || arg == init_list_type_node)
15192     /* We can't deduce anything from this, but we might get all the
15193        template args from other function args.  */
15194     return 0;
15195
15196   /* If PARM uses template parameters, then we can't bail out here,
15197      even if ARG == PARM, since we won't record unifications for the
15198      template parameters.  We might need them if we're trying to
15199      figure out which of two things is more specialized.  */
15200   if (arg == parm && !uses_template_parms (parm))
15201     return 0;
15202
15203   /* Handle init lists early, so the rest of the function can assume
15204      we're dealing with a type. */
15205   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
15206     {
15207       tree elt, elttype;
15208       unsigned i;
15209       tree orig_parm = parm;
15210
15211       /* Replace T with std::initializer_list<T> for deduction.  */
15212       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15213           && flag_deduce_init_list)
15214         parm = listify (parm);
15215
15216       if (!is_std_init_list (parm))
15217         /* We can only deduce from an initializer list argument if the
15218            parameter is std::initializer_list; otherwise this is a
15219            non-deduced context. */
15220         return 0;
15221
15222       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
15223
15224       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
15225         {
15226           int elt_strict = strict;
15227
15228           if (elt == error_mark_node)
15229             return 1;
15230
15231           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
15232             {
15233               tree type = TREE_TYPE (elt);
15234               /* It should only be possible to get here for a call.  */
15235               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
15236               elt_strict |= maybe_adjust_types_for_deduction
15237                 (DEDUCE_CALL, &elttype, &type, elt);
15238               elt = type;
15239             }
15240
15241           if (unify (tparms, targs, elttype, elt, elt_strict))
15242             return 1;
15243         }
15244
15245       /* If the std::initializer_list<T> deduction worked, replace the
15246          deduced A with std::initializer_list<A>.  */
15247       if (orig_parm != parm)
15248         {
15249           idx = TEMPLATE_TYPE_IDX (orig_parm);
15250           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15251           targ = listify (targ);
15252           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
15253         }
15254       return 0;
15255     }
15256
15257   /* Immediately reject some pairs that won't unify because of
15258      cv-qualification mismatches.  */
15259   if (TREE_CODE (arg) == TREE_CODE (parm)
15260       && TYPE_P (arg)
15261       /* It is the elements of the array which hold the cv quals of an array
15262          type, and the elements might be template type parms. We'll check
15263          when we recurse.  */
15264       && TREE_CODE (arg) != ARRAY_TYPE
15265       /* We check the cv-qualifiers when unifying with template type
15266          parameters below.  We want to allow ARG `const T' to unify with
15267          PARM `T' for example, when computing which of two templates
15268          is more specialized, for example.  */
15269       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
15270       && !check_cv_quals_for_unify (strict_in, arg, parm))
15271     return 1;
15272
15273   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
15274       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
15275     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
15276   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
15277   strict &= ~UNIFY_ALLOW_DERIVED;
15278   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
15279   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
15280
15281   switch (TREE_CODE (parm))
15282     {
15283     case TYPENAME_TYPE:
15284     case SCOPE_REF:
15285     case UNBOUND_CLASS_TEMPLATE:
15286       /* In a type which contains a nested-name-specifier, template
15287          argument values cannot be deduced for template parameters used
15288          within the nested-name-specifier.  */
15289       return 0;
15290
15291     case TEMPLATE_TYPE_PARM:
15292     case TEMPLATE_TEMPLATE_PARM:
15293     case BOUND_TEMPLATE_TEMPLATE_PARM:
15294       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15295       if (tparm == error_mark_node)
15296         return 1;
15297
15298       if (TEMPLATE_TYPE_LEVEL (parm)
15299           != template_decl_level (tparm))
15300         /* The PARM is not one we're trying to unify.  Just check
15301            to see if it matches ARG.  */
15302         return (TREE_CODE (arg) == TREE_CODE (parm)
15303                 && same_type_p (parm, arg)) ? 0 : 1;
15304       idx = TEMPLATE_TYPE_IDX (parm);
15305       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15306       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
15307
15308       /* Check for mixed types and values.  */
15309       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15310            && TREE_CODE (tparm) != TYPE_DECL)
15311           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15312               && TREE_CODE (tparm) != TEMPLATE_DECL))
15313         return 1;
15314
15315       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15316         {
15317           /* ARG must be constructed from a template class or a template
15318              template parameter.  */
15319           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
15320               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
15321             return 1;
15322
15323           {
15324             tree parmvec = TYPE_TI_ARGS (parm);
15325             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
15326             tree full_argvec = add_to_template_args (targs, argvec);
15327             tree parm_parms 
15328               = DECL_INNERMOST_TEMPLATE_PARMS
15329                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
15330             int i, len;
15331             int parm_variadic_p = 0;
15332
15333             /* The resolution to DR150 makes clear that default
15334                arguments for an N-argument may not be used to bind T
15335                to a template template parameter with fewer than N
15336                parameters.  It is not safe to permit the binding of
15337                default arguments as an extension, as that may change
15338                the meaning of a conforming program.  Consider:
15339
15340                   struct Dense { static const unsigned int dim = 1; };
15341
15342                   template <template <typename> class View,
15343                             typename Block>
15344                   void operator+(float, View<Block> const&);
15345
15346                   template <typename Block,
15347                             unsigned int Dim = Block::dim>
15348                   struct Lvalue_proxy { operator float() const; };
15349
15350                   void
15351                   test_1d (void) {
15352                     Lvalue_proxy<Dense> p;
15353                     float b;
15354                     b + p;
15355                   }
15356
15357               Here, if Lvalue_proxy is permitted to bind to View, then
15358               the global operator+ will be used; if they are not, the
15359               Lvalue_proxy will be converted to float.  */
15360             if (coerce_template_parms (parm_parms,
15361                                        full_argvec,
15362                                        TYPE_TI_TEMPLATE (parm),
15363                                        tf_none,
15364                                        /*require_all_args=*/true,
15365                                        /*use_default_args=*/false)
15366                 == error_mark_node)
15367               return 1;
15368
15369             /* Deduce arguments T, i from TT<T> or TT<i>.
15370                We check each element of PARMVEC and ARGVEC individually
15371                rather than the whole TREE_VEC since they can have
15372                different number of elements.  */
15373
15374             parmvec = expand_template_argument_pack (parmvec);
15375             argvec = expand_template_argument_pack (argvec);
15376
15377             len = TREE_VEC_LENGTH (parmvec);
15378
15379             /* Check if the parameters end in a pack, making them
15380                variadic.  */
15381             if (len > 0
15382                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
15383               parm_variadic_p = 1;
15384             
15385             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
15386               return 1;
15387
15388              for (i = 0; i < len - parm_variadic_p; ++i)
15389               {
15390                 if (unify (tparms, targs,
15391                            TREE_VEC_ELT (parmvec, i),
15392                            TREE_VEC_ELT (argvec, i),
15393                            UNIFY_ALLOW_NONE))
15394                   return 1;
15395               }
15396
15397             if (parm_variadic_p
15398                 && unify_pack_expansion (tparms, targs,
15399                                          parmvec, argvec,
15400                                          UNIFY_ALLOW_NONE,
15401                                          /*call_args_p=*/false,
15402                                          /*subr=*/false))
15403               return 1;
15404           }
15405           arg = TYPE_TI_TEMPLATE (arg);
15406
15407           /* Fall through to deduce template name.  */
15408         }
15409
15410       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15411           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15412         {
15413           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
15414
15415           /* Simple cases: Value already set, does match or doesn't.  */
15416           if (targ != NULL_TREE && template_args_equal (targ, arg))
15417             return 0;
15418           else if (targ)
15419             return 1;
15420         }
15421       else
15422         {
15423           /* If PARM is `const T' and ARG is only `int', we don't have
15424              a match unless we are allowing additional qualification.
15425              If ARG is `const int' and PARM is just `T' that's OK;
15426              that binds `const int' to `T'.  */
15427           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
15428                                          arg, parm))
15429             return 1;
15430
15431           /* Consider the case where ARG is `const volatile int' and
15432              PARM is `const T'.  Then, T should be `volatile int'.  */
15433           arg = cp_build_qualified_type_real
15434             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
15435           if (arg == error_mark_node)
15436             return 1;
15437
15438           /* Simple cases: Value already set, does match or doesn't.  */
15439           if (targ != NULL_TREE && same_type_p (targ, arg))
15440             return 0;
15441           else if (targ)
15442             return 1;
15443
15444           /* Make sure that ARG is not a variable-sized array.  (Note
15445              that were talking about variable-sized arrays (like
15446              `int[n]'), rather than arrays of unknown size (like
15447              `int[]').)  We'll get very confused by such a type since
15448              the bound of the array will not be computable in an
15449              instantiation.  Besides, such types are not allowed in
15450              ISO C++, so we can do as we please here.  */
15451           if (variably_modified_type_p (arg, NULL_TREE))
15452             return 1;
15453
15454           /* Strip typedefs as in convert_template_argument.  */
15455           arg = strip_typedefs (arg);
15456         }
15457
15458       /* If ARG is a parameter pack or an expansion, we cannot unify
15459          against it unless PARM is also a parameter pack.  */
15460       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
15461           && !template_parameter_pack_p (parm))
15462         return 1;
15463
15464       /* If the argument deduction results is a METHOD_TYPE,
15465          then there is a problem.
15466          METHOD_TYPE doesn't map to any real C++ type the result of
15467          the deduction can not be of that type.  */
15468       if (TREE_CODE (arg) == METHOD_TYPE)
15469         return 1;
15470
15471       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
15472       return 0;
15473
15474     case TEMPLATE_PARM_INDEX:
15475       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15476       if (tparm == error_mark_node)
15477         return 1;
15478
15479       if (TEMPLATE_PARM_LEVEL (parm)
15480           != template_decl_level (tparm))
15481         /* The PARM is not one we're trying to unify.  Just check
15482            to see if it matches ARG.  */
15483         return !(TREE_CODE (arg) == TREE_CODE (parm)
15484                  && cp_tree_equal (parm, arg));
15485
15486       idx = TEMPLATE_PARM_IDX (parm);
15487       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15488
15489       if (targ)
15490         return !cp_tree_equal (targ, arg);
15491
15492       /* [temp.deduct.type] If, in the declaration of a function template
15493          with a non-type template-parameter, the non-type
15494          template-parameter is used in an expression in the function
15495          parameter-list and, if the corresponding template-argument is
15496          deduced, the template-argument type shall match the type of the
15497          template-parameter exactly, except that a template-argument
15498          deduced from an array bound may be of any integral type.
15499          The non-type parameter might use already deduced type parameters.  */
15500       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
15501       if (!TREE_TYPE (arg))
15502         /* Template-parameter dependent expression.  Just accept it for now.
15503            It will later be processed in convert_template_argument.  */
15504         ;
15505       else if (same_type_p (TREE_TYPE (arg), tparm))
15506         /* OK */;
15507       else if ((strict & UNIFY_ALLOW_INTEGER)
15508                && (TREE_CODE (tparm) == INTEGER_TYPE
15509                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
15510         /* Convert the ARG to the type of PARM; the deduced non-type
15511            template argument must exactly match the types of the
15512            corresponding parameter.  */
15513         arg = fold (build_nop (tparm, arg));
15514       else if (uses_template_parms (tparm))
15515         /* We haven't deduced the type of this parameter yet.  Try again
15516            later.  */
15517         return 0;
15518       else
15519         return 1;
15520
15521       /* If ARG is a parameter pack or an expansion, we cannot unify
15522          against it unless PARM is also a parameter pack.  */
15523       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
15524           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
15525         return 1;
15526
15527       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
15528       return 0;
15529
15530     case PTRMEM_CST:
15531      {
15532         /* A pointer-to-member constant can be unified only with
15533          another constant.  */
15534       if (TREE_CODE (arg) != PTRMEM_CST)
15535         return 1;
15536
15537       /* Just unify the class member. It would be useless (and possibly
15538          wrong, depending on the strict flags) to unify also
15539          PTRMEM_CST_CLASS, because we want to be sure that both parm and
15540          arg refer to the same variable, even if through different
15541          classes. For instance:
15542
15543          struct A { int x; };
15544          struct B : A { };
15545
15546          Unification of &A::x and &B::x must succeed.  */
15547       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
15548                     PTRMEM_CST_MEMBER (arg), strict);
15549      }
15550
15551     case POINTER_TYPE:
15552       {
15553         if (TREE_CODE (arg) != POINTER_TYPE)
15554           return 1;
15555
15556         /* [temp.deduct.call]
15557
15558            A can be another pointer or pointer to member type that can
15559            be converted to the deduced A via a qualification
15560            conversion (_conv.qual_).
15561
15562            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
15563            This will allow for additional cv-qualification of the
15564            pointed-to types if appropriate.  */
15565
15566         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
15567           /* The derived-to-base conversion only persists through one
15568              level of pointers.  */
15569           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
15570
15571         return unify (tparms, targs, TREE_TYPE (parm),
15572                       TREE_TYPE (arg), strict);
15573       }
15574
15575     case REFERENCE_TYPE:
15576       if (TREE_CODE (arg) != REFERENCE_TYPE)
15577         return 1;
15578       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15579                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
15580
15581     case ARRAY_TYPE:
15582       if (TREE_CODE (arg) != ARRAY_TYPE)
15583         return 1;
15584       if ((TYPE_DOMAIN (parm) == NULL_TREE)
15585           != (TYPE_DOMAIN (arg) == NULL_TREE))
15586         return 1;
15587       if (TYPE_DOMAIN (parm) != NULL_TREE)
15588         {
15589           tree parm_max;
15590           tree arg_max;
15591           bool parm_cst;
15592           bool arg_cst;
15593
15594           /* Our representation of array types uses "N - 1" as the
15595              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
15596              not an integer constant.  We cannot unify arbitrarily
15597              complex expressions, so we eliminate the MINUS_EXPRs
15598              here.  */
15599           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
15600           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
15601           if (!parm_cst)
15602             {
15603               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
15604               parm_max = TREE_OPERAND (parm_max, 0);
15605             }
15606           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
15607           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
15608           if (!arg_cst)
15609             {
15610               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
15611                  trying to unify the type of a variable with the type
15612                  of a template parameter.  For example:
15613
15614                    template <unsigned int N>
15615                    void f (char (&) [N]);
15616                    int g(); 
15617                    void h(int i) {
15618                      char a[g(i)];
15619                      f(a); 
15620                    }
15621
15622                 Here, the type of the ARG will be "int [g(i)]", and
15623                 may be a SAVE_EXPR, etc.  */
15624               if (TREE_CODE (arg_max) != MINUS_EXPR)
15625                 return 1;
15626               arg_max = TREE_OPERAND (arg_max, 0);
15627             }
15628
15629           /* If only one of the bounds used a MINUS_EXPR, compensate
15630              by adding one to the other bound.  */
15631           if (parm_cst && !arg_cst)
15632             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
15633                                     integer_type_node,
15634                                     parm_max,
15635                                     integer_one_node);
15636           else if (arg_cst && !parm_cst)
15637             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
15638                                    integer_type_node,
15639                                    arg_max,
15640                                    integer_one_node);
15641
15642           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
15643             return 1;
15644         }
15645       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15646                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
15647
15648     case REAL_TYPE:
15649     case COMPLEX_TYPE:
15650     case VECTOR_TYPE:
15651     case INTEGER_TYPE:
15652     case BOOLEAN_TYPE:
15653     case ENUMERAL_TYPE:
15654     case VOID_TYPE:
15655       if (TREE_CODE (arg) != TREE_CODE (parm))
15656         return 1;
15657
15658       /* We have already checked cv-qualification at the top of the
15659          function.  */
15660       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
15661         return 1;
15662
15663       /* As far as unification is concerned, this wins.  Later checks
15664          will invalidate it if necessary.  */
15665       return 0;
15666
15667       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
15668       /* Type INTEGER_CST can come from ordinary constant template args.  */
15669     case INTEGER_CST:
15670       while (TREE_CODE (arg) == NOP_EXPR)
15671         arg = TREE_OPERAND (arg, 0);
15672
15673       if (TREE_CODE (arg) != INTEGER_CST)
15674         return 1;
15675       return !tree_int_cst_equal (parm, arg);
15676
15677     case TREE_VEC:
15678       {
15679         int i;
15680         if (TREE_CODE (arg) != TREE_VEC)
15681           return 1;
15682         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
15683           return 1;
15684         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
15685           if (unify (tparms, targs,
15686                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
15687                      UNIFY_ALLOW_NONE))
15688             return 1;
15689         return 0;
15690       }
15691
15692     case RECORD_TYPE:
15693     case UNION_TYPE:
15694       if (TREE_CODE (arg) != TREE_CODE (parm))
15695         return 1;
15696
15697       if (TYPE_PTRMEMFUNC_P (parm))
15698         {
15699           if (!TYPE_PTRMEMFUNC_P (arg))
15700             return 1;
15701
15702           return unify (tparms, targs,
15703                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
15704                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
15705                         strict);
15706         }
15707
15708       if (CLASSTYPE_TEMPLATE_INFO (parm))
15709         {
15710           tree t = NULL_TREE;
15711
15712           if (strict_in & UNIFY_ALLOW_DERIVED)
15713             {
15714               /* First, we try to unify the PARM and ARG directly.  */
15715               t = try_class_unification (tparms, targs,
15716                                          parm, arg);
15717
15718               if (!t)
15719                 {
15720                   /* Fallback to the special case allowed in
15721                      [temp.deduct.call]:
15722
15723                        If P is a class, and P has the form
15724                        template-id, then A can be a derived class of
15725                        the deduced A.  Likewise, if P is a pointer to
15726                        a class of the form template-id, A can be a
15727                        pointer to a derived class pointed to by the
15728                        deduced A.  */
15729                   t = get_template_base (tparms, targs, parm, arg);
15730
15731                   if (!t)
15732                     return 1;
15733                 }
15734             }
15735           else if (CLASSTYPE_TEMPLATE_INFO (arg)
15736                    && (CLASSTYPE_TI_TEMPLATE (parm)
15737                        == CLASSTYPE_TI_TEMPLATE (arg)))
15738             /* Perhaps PARM is something like S<U> and ARG is S<int>.
15739                Then, we should unify `int' and `U'.  */
15740             t = arg;
15741           else
15742             /* There's no chance of unification succeeding.  */
15743             return 1;
15744
15745           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
15746                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
15747         }
15748       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
15749         return 1;
15750       return 0;
15751
15752     case METHOD_TYPE:
15753     case FUNCTION_TYPE:
15754       {
15755         unsigned int nargs;
15756         tree *args;
15757         tree a;
15758         unsigned int i;
15759
15760         if (TREE_CODE (arg) != TREE_CODE (parm))
15761           return 1;
15762
15763         /* CV qualifications for methods can never be deduced, they must
15764            match exactly.  We need to check them explicitly here,
15765            because type_unification_real treats them as any other
15766            cv-qualified parameter.  */
15767         if (TREE_CODE (parm) == METHOD_TYPE
15768             && (!check_cv_quals_for_unify
15769                 (UNIFY_ALLOW_NONE,
15770                  class_of_this_parm (arg),
15771                  class_of_this_parm (parm))))
15772           return 1;
15773
15774         if (unify (tparms, targs, TREE_TYPE (parm),
15775                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
15776           return 1;
15777
15778         nargs = list_length (TYPE_ARG_TYPES (arg));
15779         args = XALLOCAVEC (tree, nargs);
15780         for (a = TYPE_ARG_TYPES (arg), i = 0;
15781              a != NULL_TREE && a != void_list_node;
15782              a = TREE_CHAIN (a), ++i)
15783           args[i] = TREE_VALUE (a);
15784         nargs = i;
15785
15786         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
15787                                       args, nargs, 1, DEDUCE_EXACT,
15788                                       LOOKUP_NORMAL);
15789       }
15790
15791     case OFFSET_TYPE:
15792       /* Unify a pointer to member with a pointer to member function, which
15793          deduces the type of the member as a function type. */
15794       if (TYPE_PTRMEMFUNC_P (arg))
15795         {
15796           tree method_type;
15797           tree fntype;
15798
15799           /* Check top-level cv qualifiers */
15800           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
15801             return 1;
15802
15803           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15804                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
15805             return 1;
15806
15807           /* Determine the type of the function we are unifying against. */
15808           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
15809           fntype =
15810             build_function_type (TREE_TYPE (method_type),
15811                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
15812
15813           /* Extract the cv-qualifiers of the member function from the
15814              implicit object parameter and place them on the function
15815              type to be restored later. */
15816           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
15817           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
15818         }
15819
15820       if (TREE_CODE (arg) != OFFSET_TYPE)
15821         return 1;
15822       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15823                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
15824         return 1;
15825       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15826                     strict);
15827
15828     case CONST_DECL:
15829       if (DECL_TEMPLATE_PARM_P (parm))
15830         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
15831       if (arg != integral_constant_value (parm))
15832         return 1;
15833       return 0;
15834
15835     case FIELD_DECL:
15836     case TEMPLATE_DECL:
15837       /* Matched cases are handled by the ARG == PARM test above.  */
15838       return 1;
15839
15840     case VAR_DECL:
15841       /* A non-type template parameter that is a variable should be a
15842          an integral constant, in which case, it whould have been
15843          folded into its (constant) value. So we should not be getting
15844          a variable here.  */
15845       gcc_unreachable ();
15846
15847     case TYPE_ARGUMENT_PACK:
15848     case NONTYPE_ARGUMENT_PACK:
15849       {
15850         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
15851         tree packed_args = ARGUMENT_PACK_ARGS (arg);
15852         int i, len = TREE_VEC_LENGTH (packed_parms);
15853         int argslen = TREE_VEC_LENGTH (packed_args);
15854         int parm_variadic_p = 0;
15855
15856         for (i = 0; i < len; ++i)
15857           {
15858             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
15859               {
15860                 if (i == len - 1)
15861                   /* We can unify against something with a trailing
15862                      parameter pack.  */
15863                   parm_variadic_p = 1;
15864                 else
15865                   /* Since there is something following the pack
15866                      expansion, we cannot unify this template argument
15867                      list.  */
15868                   return 0;
15869               }
15870           }
15871           
15872
15873         /* If we don't have enough arguments to satisfy the parameters
15874            (not counting the pack expression at the end), or we have
15875            too many arguments for a parameter list that doesn't end in
15876            a pack expression, we can't unify.  */
15877         if (argslen < (len - parm_variadic_p)
15878             || (argslen > len && !parm_variadic_p))
15879           return 1;
15880
15881         /* Unify all of the parameters that precede the (optional)
15882            pack expression.  */
15883         for (i = 0; i < len - parm_variadic_p; ++i)
15884           {
15885             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15886                        TREE_VEC_ELT (packed_args, i), strict))
15887               return 1;
15888           }
15889
15890         if (parm_variadic_p)
15891           return unify_pack_expansion (tparms, targs, 
15892                                        packed_parms, packed_args,
15893                                        strict, /*call_args_p=*/false,
15894                                        /*subr=*/false);
15895         return 0;
15896       }
15897
15898       break;
15899
15900     case TYPEOF_TYPE:
15901     case DECLTYPE_TYPE:
15902     case UNDERLYING_TYPE:
15903       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
15904          or UNDERLYING_TYPE nodes.  */
15905       return 0;
15906
15907     case ERROR_MARK:
15908       /* Unification fails if we hit an error node.  */
15909       return 1;
15910
15911     default:
15912       /* An unresolved overload is a nondeduced context.  */
15913       if (type_unknown_p (parm))
15914         return 0;
15915       gcc_assert (EXPR_P (parm));
15916
15917       /* We must be looking at an expression.  This can happen with
15918          something like:
15919
15920            template <int I>
15921            void foo(S<I>, S<I + 2>);
15922
15923          This is a "nondeduced context":
15924
15925            [deduct.type]
15926
15927            The nondeduced contexts are:
15928
15929            --A type that is a template-id in which one or more of
15930              the template-arguments is an expression that references
15931              a template-parameter.
15932
15933          In these cases, we assume deduction succeeded, but don't
15934          actually infer any unifications.  */
15935
15936       if (!uses_template_parms (parm)
15937           && !template_args_equal (parm, arg))
15938         return 1;
15939       else
15940         return 0;
15941     }
15942 }
15943 \f
15944 /* Note that DECL can be defined in this translation unit, if
15945    required.  */
15946
15947 static void
15948 mark_definable (tree decl)
15949 {
15950   tree clone;
15951   DECL_NOT_REALLY_EXTERN (decl) = 1;
15952   FOR_EACH_CLONE (clone, decl)
15953     DECL_NOT_REALLY_EXTERN (clone) = 1;
15954 }
15955
15956 /* Called if RESULT is explicitly instantiated, or is a member of an
15957    explicitly instantiated class.  */
15958
15959 void
15960 mark_decl_instantiated (tree result, int extern_p)
15961 {
15962   SET_DECL_EXPLICIT_INSTANTIATION (result);
15963
15964   /* If this entity has already been written out, it's too late to
15965      make any modifications.  */
15966   if (TREE_ASM_WRITTEN (result))
15967     return;
15968
15969   if (TREE_CODE (result) != FUNCTION_DECL)
15970     /* The TREE_PUBLIC flag for function declarations will have been
15971        set correctly by tsubst.  */
15972     TREE_PUBLIC (result) = 1;
15973
15974   /* This might have been set by an earlier implicit instantiation.  */
15975   DECL_COMDAT (result) = 0;
15976
15977   if (extern_p)
15978     DECL_NOT_REALLY_EXTERN (result) = 0;
15979   else
15980     {
15981       mark_definable (result);
15982       /* Always make artificials weak.  */
15983       if (DECL_ARTIFICIAL (result) && flag_weak)
15984         comdat_linkage (result);
15985       /* For WIN32 we also want to put explicit instantiations in
15986          linkonce sections.  */
15987       else if (TREE_PUBLIC (result))
15988         maybe_make_one_only (result);
15989     }
15990
15991   /* If EXTERN_P, then this function will not be emitted -- unless
15992      followed by an explicit instantiation, at which point its linkage
15993      will be adjusted.  If !EXTERN_P, then this function will be
15994      emitted here.  In neither circumstance do we want
15995      import_export_decl to adjust the linkage.  */
15996   DECL_INTERFACE_KNOWN (result) = 1;
15997 }
15998
15999 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
16000    important template arguments.  If any are missing, we check whether
16001    they're important by using error_mark_node for substituting into any
16002    args that were used for partial ordering (the ones between ARGS and END)
16003    and seeing if it bubbles up.  */
16004
16005 static bool
16006 check_undeduced_parms (tree targs, tree args, tree end)
16007 {
16008   bool found = false;
16009   int i;
16010   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
16011     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
16012       {
16013         found = true;
16014         TREE_VEC_ELT (targs, i) = error_mark_node;
16015       }
16016   if (found)
16017     {
16018       for (; args != end; args = TREE_CHAIN (args))
16019         {
16020           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
16021           if (substed == error_mark_node)
16022             return true;
16023         }
16024     }
16025   return false;
16026 }
16027
16028 /* Given two function templates PAT1 and PAT2, return:
16029
16030    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
16031    -1 if PAT2 is more specialized than PAT1.
16032    0 if neither is more specialized.
16033
16034    LEN indicates the number of parameters we should consider
16035    (defaulted parameters should not be considered).
16036
16037    The 1998 std underspecified function template partial ordering, and
16038    DR214 addresses the issue.  We take pairs of arguments, one from
16039    each of the templates, and deduce them against each other.  One of
16040    the templates will be more specialized if all the *other*
16041    template's arguments deduce against its arguments and at least one
16042    of its arguments *does* *not* deduce against the other template's
16043    corresponding argument.  Deduction is done as for class templates.
16044    The arguments used in deduction have reference and top level cv
16045    qualifiers removed.  Iff both arguments were originally reference
16046    types *and* deduction succeeds in both directions, the template
16047    with the more cv-qualified argument wins for that pairing (if
16048    neither is more cv-qualified, they both are equal).  Unlike regular
16049    deduction, after all the arguments have been deduced in this way,
16050    we do *not* verify the deduced template argument values can be
16051    substituted into non-deduced contexts.
16052
16053    The logic can be a bit confusing here, because we look at deduce1 and
16054    targs1 to see if pat2 is at least as specialized, and vice versa; if we
16055    can find template arguments for pat1 to make arg1 look like arg2, that
16056    means that arg2 is at least as specialized as arg1.  */
16057
16058 int
16059 more_specialized_fn (tree pat1, tree pat2, int len)
16060 {
16061   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
16062   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
16063   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
16064   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
16065   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
16066   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
16067   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
16068   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
16069   tree origs1, origs2;
16070   bool lose1 = false;
16071   bool lose2 = false;
16072
16073   /* Remove the this parameter from non-static member functions.  If
16074      one is a non-static member function and the other is not a static
16075      member function, remove the first parameter from that function
16076      also.  This situation occurs for operator functions where we
16077      locate both a member function (with this pointer) and non-member
16078      operator (with explicit first operand).  */
16079   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
16080     {
16081       len--; /* LEN is the number of significant arguments for DECL1 */
16082       args1 = TREE_CHAIN (args1);
16083       if (!DECL_STATIC_FUNCTION_P (decl2))
16084         args2 = TREE_CHAIN (args2);
16085     }
16086   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
16087     {
16088       args2 = TREE_CHAIN (args2);
16089       if (!DECL_STATIC_FUNCTION_P (decl1))
16090         {
16091           len--;
16092           args1 = TREE_CHAIN (args1);
16093         }
16094     }
16095
16096   /* If only one is a conversion operator, they are unordered.  */
16097   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
16098     return 0;
16099
16100   /* Consider the return type for a conversion function */
16101   if (DECL_CONV_FN_P (decl1))
16102     {
16103       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
16104       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
16105       len++;
16106     }
16107
16108   processing_template_decl++;
16109
16110   origs1 = args1;
16111   origs2 = args2;
16112
16113   while (len--
16114          /* Stop when an ellipsis is seen.  */
16115          && args1 != NULL_TREE && args2 != NULL_TREE)
16116     {
16117       tree arg1 = TREE_VALUE (args1);
16118       tree arg2 = TREE_VALUE (args2);
16119       int deduce1, deduce2;
16120       int quals1 = -1;
16121       int quals2 = -1;
16122
16123       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16124           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16125         {
16126           /* When both arguments are pack expansions, we need only
16127              unify the patterns themselves.  */
16128           arg1 = PACK_EXPANSION_PATTERN (arg1);
16129           arg2 = PACK_EXPANSION_PATTERN (arg2);
16130
16131           /* This is the last comparison we need to do.  */
16132           len = 0;
16133         }
16134
16135       if (TREE_CODE (arg1) == REFERENCE_TYPE)
16136         {
16137           arg1 = TREE_TYPE (arg1);
16138           quals1 = cp_type_quals (arg1);
16139         }
16140
16141       if (TREE_CODE (arg2) == REFERENCE_TYPE)
16142         {
16143           arg2 = TREE_TYPE (arg2);
16144           quals2 = cp_type_quals (arg2);
16145         }
16146
16147       if ((quals1 < 0) != (quals2 < 0))
16148         {
16149           /* Only of the args is a reference, see if we should apply
16150              array/function pointer decay to it.  This is not part of
16151              DR214, but is, IMHO, consistent with the deduction rules
16152              for the function call itself, and with our earlier
16153              implementation of the underspecified partial ordering
16154              rules.  (nathan).  */
16155           if (quals1 >= 0)
16156             {
16157               switch (TREE_CODE (arg1))
16158                 {
16159                 case ARRAY_TYPE:
16160                   arg1 = TREE_TYPE (arg1);
16161                   /* FALLTHROUGH. */
16162                 case FUNCTION_TYPE:
16163                   arg1 = build_pointer_type (arg1);
16164                   break;
16165
16166                 default:
16167                   break;
16168                 }
16169             }
16170           else
16171             {
16172               switch (TREE_CODE (arg2))
16173                 {
16174                 case ARRAY_TYPE:
16175                   arg2 = TREE_TYPE (arg2);
16176                   /* FALLTHROUGH. */
16177                 case FUNCTION_TYPE:
16178                   arg2 = build_pointer_type (arg2);
16179                   break;
16180
16181                 default:
16182                   break;
16183                 }
16184             }
16185         }
16186
16187       arg1 = TYPE_MAIN_VARIANT (arg1);
16188       arg2 = TYPE_MAIN_VARIANT (arg2);
16189
16190       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
16191         {
16192           int i, len2 = list_length (args2);
16193           tree parmvec = make_tree_vec (1);
16194           tree argvec = make_tree_vec (len2);
16195           tree ta = args2;
16196
16197           /* Setup the parameter vector, which contains only ARG1.  */
16198           TREE_VEC_ELT (parmvec, 0) = arg1;
16199
16200           /* Setup the argument vector, which contains the remaining
16201              arguments.  */
16202           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
16203             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16204
16205           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
16206                                            argvec, UNIFY_ALLOW_NONE, 
16207                                            /*call_args_p=*/false, 
16208                                            /*subr=*/0);
16209
16210           /* We cannot deduce in the other direction, because ARG1 is
16211              a pack expansion but ARG2 is not.  */
16212           deduce2 = 0;
16213         }
16214       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16215         {
16216           int i, len1 = list_length (args1);
16217           tree parmvec = make_tree_vec (1);
16218           tree argvec = make_tree_vec (len1);
16219           tree ta = args1;
16220
16221           /* Setup the parameter vector, which contains only ARG1.  */
16222           TREE_VEC_ELT (parmvec, 0) = arg2;
16223
16224           /* Setup the argument vector, which contains the remaining
16225              arguments.  */
16226           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
16227             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16228
16229           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
16230                                            argvec, UNIFY_ALLOW_NONE, 
16231                                            /*call_args_p=*/false, 
16232                                            /*subr=*/0);
16233
16234           /* We cannot deduce in the other direction, because ARG2 is
16235              a pack expansion but ARG1 is not.*/
16236           deduce1 = 0;
16237         }
16238
16239       else
16240         {
16241           /* The normal case, where neither argument is a pack
16242              expansion.  */
16243           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
16244           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
16245         }
16246
16247       /* If we couldn't deduce arguments for tparms1 to make arg1 match
16248          arg2, then arg2 is not as specialized as arg1.  */
16249       if (!deduce1)
16250         lose2 = true;
16251       if (!deduce2)
16252         lose1 = true;
16253
16254       /* "If, for a given type, deduction succeeds in both directions
16255          (i.e., the types are identical after the transformations above)
16256          and if the type from the argument template is more cv-qualified
16257          than the type from the parameter template (as described above)
16258          that type is considered to be more specialized than the other. If
16259          neither type is more cv-qualified than the other then neither type
16260          is more specialized than the other."  */
16261
16262       if (deduce1 && deduce2
16263           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
16264         {
16265           if ((quals1 & quals2) == quals2)
16266             lose2 = true;
16267           if ((quals1 & quals2) == quals1)
16268             lose1 = true;
16269         }
16270
16271       if (lose1 && lose2)
16272         /* We've failed to deduce something in either direction.
16273            These must be unordered.  */
16274         break;
16275
16276       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16277           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16278         /* We have already processed all of the arguments in our
16279            handing of the pack expansion type.  */
16280         len = 0;
16281
16282       args1 = TREE_CHAIN (args1);
16283       args2 = TREE_CHAIN (args2);
16284     }
16285
16286   /* "In most cases, all template parameters must have values in order for
16287      deduction to succeed, but for partial ordering purposes a template
16288      parameter may remain without a value provided it is not used in the
16289      types being used for partial ordering."
16290
16291      Thus, if we are missing any of the targs1 we need to substitute into
16292      origs1, then pat2 is not as specialized as pat1.  This can happen when
16293      there is a nondeduced context.  */
16294   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
16295     lose2 = true;
16296   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
16297     lose1 = true;
16298
16299   processing_template_decl--;
16300
16301   /* All things being equal, if the next argument is a pack expansion
16302      for one function but not for the other, prefer the
16303      non-variadic function.  FIXME this is bogus; see c++/41958.  */
16304   if (lose1 == lose2
16305       && args1 && TREE_VALUE (args1)
16306       && args2 && TREE_VALUE (args2))
16307     {
16308       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
16309       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
16310     }
16311
16312   if (lose1 == lose2)
16313     return 0;
16314   else if (!lose1)
16315     return 1;
16316   else
16317     return -1;
16318 }
16319
16320 /* Determine which of two partial specializations is more specialized.
16321
16322    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
16323    to the first partial specialization.  The TREE_VALUE is the
16324    innermost set of template parameters for the partial
16325    specialization.  PAT2 is similar, but for the second template.
16326
16327    Return 1 if the first partial specialization is more specialized;
16328    -1 if the second is more specialized; 0 if neither is more
16329    specialized.
16330
16331    See [temp.class.order] for information about determining which of
16332    two templates is more specialized.  */
16333
16334 static int
16335 more_specialized_class (tree pat1, tree pat2)
16336 {
16337   tree targs;
16338   tree tmpl1, tmpl2;
16339   int winner = 0;
16340   bool any_deductions = false;
16341
16342   tmpl1 = TREE_TYPE (pat1);
16343   tmpl2 = TREE_TYPE (pat2);
16344
16345   /* Just like what happens for functions, if we are ordering between
16346      different class template specializations, we may encounter dependent
16347      types in the arguments, and we need our dependency check functions
16348      to behave correctly.  */
16349   ++processing_template_decl;
16350   targs = get_class_bindings (TREE_VALUE (pat1),
16351                               CLASSTYPE_TI_ARGS (tmpl1),
16352                               CLASSTYPE_TI_ARGS (tmpl2));
16353   if (targs)
16354     {
16355       --winner;
16356       any_deductions = true;
16357     }
16358
16359   targs = get_class_bindings (TREE_VALUE (pat2),
16360                               CLASSTYPE_TI_ARGS (tmpl2),
16361                               CLASSTYPE_TI_ARGS (tmpl1));
16362   if (targs)
16363     {
16364       ++winner;
16365       any_deductions = true;
16366     }
16367   --processing_template_decl;
16368
16369   /* In the case of a tie where at least one of the class templates
16370      has a parameter pack at the end, the template with the most
16371      non-packed parameters wins.  */
16372   if (winner == 0
16373       && any_deductions
16374       && (template_args_variadic_p (TREE_PURPOSE (pat1))
16375           || template_args_variadic_p (TREE_PURPOSE (pat2))))
16376     {
16377       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
16378       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
16379       int len1 = TREE_VEC_LENGTH (args1);
16380       int len2 = TREE_VEC_LENGTH (args2);
16381
16382       /* We don't count the pack expansion at the end.  */
16383       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
16384         --len1;
16385       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
16386         --len2;
16387
16388       if (len1 > len2)
16389         return 1;
16390       else if (len1 < len2)
16391         return -1;
16392     }
16393
16394   return winner;
16395 }
16396
16397 /* Return the template arguments that will produce the function signature
16398    DECL from the function template FN, with the explicit template
16399    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
16400    also match.  Return NULL_TREE if no satisfactory arguments could be
16401    found.  */
16402
16403 static tree
16404 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
16405 {
16406   int ntparms = DECL_NTPARMS (fn);
16407   tree targs = make_tree_vec (ntparms);
16408   tree decl_type;
16409   tree decl_arg_types;
16410   tree *args;
16411   unsigned int nargs, ix;
16412   tree arg;
16413
16414   /* Substitute the explicit template arguments into the type of DECL.
16415      The call to fn_type_unification will handle substitution into the
16416      FN.  */
16417   decl_type = TREE_TYPE (decl);
16418   if (explicit_args && uses_template_parms (decl_type))
16419     {
16420       tree tmpl;
16421       tree converted_args;
16422
16423       if (DECL_TEMPLATE_INFO (decl))
16424         tmpl = DECL_TI_TEMPLATE (decl);
16425       else
16426         /* We can get here for some invalid specializations.  */
16427         return NULL_TREE;
16428
16429       converted_args
16430         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16431                                  explicit_args, NULL_TREE,
16432                                  tf_none,
16433                                  /*require_all_args=*/false,
16434                                  /*use_default_args=*/false);
16435       if (converted_args == error_mark_node)
16436         return NULL_TREE;
16437
16438       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
16439       if (decl_type == error_mark_node)
16440         return NULL_TREE;
16441     }
16442
16443   /* Never do unification on the 'this' parameter.  */
16444   decl_arg_types = skip_artificial_parms_for (decl, 
16445                                               TYPE_ARG_TYPES (decl_type));
16446
16447   nargs = list_length (decl_arg_types);
16448   args = XALLOCAVEC (tree, nargs);
16449   for (arg = decl_arg_types, ix = 0;
16450        arg != NULL_TREE && arg != void_list_node;
16451        arg = TREE_CHAIN (arg), ++ix)
16452     args[ix] = TREE_VALUE (arg);
16453
16454   if (fn_type_unification (fn, explicit_args, targs,
16455                            args, ix,
16456                            (check_rettype || DECL_CONV_FN_P (fn)
16457                             ? TREE_TYPE (decl_type) : NULL_TREE),
16458                            DEDUCE_EXACT, LOOKUP_NORMAL))
16459     return NULL_TREE;
16460
16461   return targs;
16462 }
16463
16464 /* Return the innermost template arguments that, when applied to a
16465    template specialization whose innermost template parameters are
16466    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
16467    ARGS.
16468
16469    For example, suppose we have:
16470
16471      template <class T, class U> struct S {};
16472      template <class T> struct S<T*, int> {};
16473
16474    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
16475    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
16476    int}.  The resulting vector will be {double}, indicating that `T'
16477    is bound to `double'.  */
16478
16479 static tree
16480 get_class_bindings (tree tparms, tree spec_args, tree args)
16481 {
16482   int i, ntparms = TREE_VEC_LENGTH (tparms);
16483   tree deduced_args;
16484   tree innermost_deduced_args;
16485
16486   innermost_deduced_args = make_tree_vec (ntparms);
16487   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
16488     {
16489       deduced_args = copy_node (args);
16490       SET_TMPL_ARGS_LEVEL (deduced_args,
16491                            TMPL_ARGS_DEPTH (deduced_args),
16492                            innermost_deduced_args);
16493     }
16494   else
16495     deduced_args = innermost_deduced_args;
16496
16497   if (unify (tparms, deduced_args,
16498              INNERMOST_TEMPLATE_ARGS (spec_args),
16499              INNERMOST_TEMPLATE_ARGS (args),
16500              UNIFY_ALLOW_NONE))
16501     return NULL_TREE;
16502
16503   for (i =  0; i < ntparms; ++i)
16504     if (! TREE_VEC_ELT (innermost_deduced_args, i))
16505       return NULL_TREE;
16506
16507   /* Verify that nondeduced template arguments agree with the type
16508      obtained from argument deduction.
16509
16510      For example:
16511
16512        struct A { typedef int X; };
16513        template <class T, class U> struct C {};
16514        template <class T> struct C<T, typename T::X> {};
16515
16516      Then with the instantiation `C<A, int>', we can deduce that
16517      `T' is `A' but unify () does not check whether `typename T::X'
16518      is `int'.  */
16519   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
16520   if (spec_args == error_mark_node
16521       /* We only need to check the innermost arguments; the other
16522          arguments will always agree.  */
16523       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
16524                               INNERMOST_TEMPLATE_ARGS (args)))
16525     return NULL_TREE;
16526
16527   /* Now that we have bindings for all of the template arguments,
16528      ensure that the arguments deduced for the template template
16529      parameters have compatible template parameter lists.  See the use
16530      of template_template_parm_bindings_ok_p in fn_type_unification
16531      for more information.  */
16532   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
16533     return NULL_TREE;
16534
16535   return deduced_args;
16536 }
16537
16538 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
16539    Return the TREE_LIST node with the most specialized template, if
16540    any.  If there is no most specialized template, the error_mark_node
16541    is returned.
16542
16543    Note that this function does not look at, or modify, the
16544    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
16545    returned is one of the elements of INSTANTIATIONS, callers may
16546    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
16547    and retrieve it from the value returned.  */
16548
16549 tree
16550 most_specialized_instantiation (tree templates)
16551 {
16552   tree fn, champ;
16553
16554   ++processing_template_decl;
16555
16556   champ = templates;
16557   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
16558     {
16559       int fate = 0;
16560
16561       if (get_bindings (TREE_VALUE (champ),
16562                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
16563                         NULL_TREE, /*check_ret=*/false))
16564         fate--;
16565
16566       if (get_bindings (TREE_VALUE (fn),
16567                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
16568                         NULL_TREE, /*check_ret=*/false))
16569         fate++;
16570
16571       if (fate == -1)
16572         champ = fn;
16573       else if (!fate)
16574         {
16575           /* Equally specialized, move to next function.  If there
16576              is no next function, nothing's most specialized.  */
16577           fn = TREE_CHAIN (fn);
16578           champ = fn;
16579           if (!fn)
16580             break;
16581         }
16582     }
16583
16584   if (champ)
16585     /* Now verify that champ is better than everything earlier in the
16586        instantiation list.  */
16587     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
16588       if (get_bindings (TREE_VALUE (champ),
16589                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
16590                         NULL_TREE, /*check_ret=*/false)
16591           || !get_bindings (TREE_VALUE (fn),
16592                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
16593                             NULL_TREE, /*check_ret=*/false))
16594         {
16595           champ = NULL_TREE;
16596           break;
16597         }
16598
16599   processing_template_decl--;
16600
16601   if (!champ)
16602     return error_mark_node;
16603
16604   return champ;
16605 }
16606
16607 /* If DECL is a specialization of some template, return the most
16608    general such template.  Otherwise, returns NULL_TREE.
16609
16610    For example, given:
16611
16612      template <class T> struct S { template <class U> void f(U); };
16613
16614    if TMPL is `template <class U> void S<int>::f(U)' this will return
16615    the full template.  This function will not trace past partial
16616    specializations, however.  For example, given in addition:
16617
16618      template <class T> struct S<T*> { template <class U> void f(U); };
16619
16620    if TMPL is `template <class U> void S<int*>::f(U)' this will return
16621    `template <class T> template <class U> S<T*>::f(U)'.  */
16622
16623 tree
16624 most_general_template (tree decl)
16625 {
16626   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
16627      an immediate specialization.  */
16628   if (TREE_CODE (decl) == FUNCTION_DECL)
16629     {
16630       if (DECL_TEMPLATE_INFO (decl)) {
16631         decl = DECL_TI_TEMPLATE (decl);
16632
16633         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
16634            template friend.  */
16635         if (TREE_CODE (decl) != TEMPLATE_DECL)
16636           return NULL_TREE;
16637       } else
16638         return NULL_TREE;
16639     }
16640
16641   /* Look for more and more general templates.  */
16642   while (DECL_TEMPLATE_INFO (decl))
16643     {
16644       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
16645          (See cp-tree.h for details.)  */
16646       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
16647         break;
16648
16649       if (CLASS_TYPE_P (TREE_TYPE (decl))
16650           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
16651         break;
16652
16653       /* Stop if we run into an explicitly specialized class template.  */
16654       if (!DECL_NAMESPACE_SCOPE_P (decl)
16655           && DECL_CONTEXT (decl)
16656           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
16657         break;
16658
16659       decl = DECL_TI_TEMPLATE (decl);
16660     }
16661
16662   return decl;
16663 }
16664
16665 /* Return the most specialized of the class template partial
16666    specializations of TMPL which can produce TYPE, a specialization of
16667    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
16668    a _TYPE node corresponding to the partial specialization, while the
16669    TREE_PURPOSE is the set of template arguments that must be
16670    substituted into the TREE_TYPE in order to generate TYPE.
16671
16672    If the choice of partial specialization is ambiguous, a diagnostic
16673    is issued, and the error_mark_node is returned.  If there are no
16674    partial specializations of TMPL matching TYPE, then NULL_TREE is
16675    returned.  */
16676
16677 static tree
16678 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
16679 {
16680   tree list = NULL_TREE;
16681   tree t;
16682   tree champ;
16683   int fate;
16684   bool ambiguous_p;
16685   tree args;
16686   tree outer_args = NULL_TREE;
16687
16688   tmpl = most_general_template (tmpl);
16689   args = CLASSTYPE_TI_ARGS (type);
16690
16691   /* For determining which partial specialization to use, only the
16692      innermost args are interesting.  */
16693   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
16694     {
16695       outer_args = strip_innermost_template_args (args, 1);
16696       args = INNERMOST_TEMPLATE_ARGS (args);
16697     }
16698
16699   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
16700     {
16701       tree partial_spec_args;
16702       tree spec_args;
16703       tree parms = TREE_VALUE (t);
16704
16705       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
16706
16707       ++processing_template_decl;
16708
16709       if (outer_args)
16710         {
16711           int i;
16712
16713           /* Discard the outer levels of args, and then substitute in the
16714              template args from the enclosing class.  */
16715           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
16716           partial_spec_args = tsubst_template_args
16717             (partial_spec_args, outer_args, tf_none, NULL_TREE);
16718
16719           /* PARMS already refers to just the innermost parms, but the
16720              template parms in partial_spec_args had their levels lowered
16721              by tsubst, so we need to do the same for the parm list.  We
16722              can't just tsubst the TREE_VEC itself, as tsubst wants to
16723              treat a TREE_VEC as an argument vector.  */
16724           parms = copy_node (parms);
16725           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
16726             TREE_VEC_ELT (parms, i) =
16727               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
16728
16729         }
16730
16731       partial_spec_args =
16732           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16733                                  add_to_template_args (outer_args,
16734                                                        partial_spec_args),
16735                                  tmpl, tf_none,
16736                                  /*require_all_args=*/true,
16737                                  /*use_default_args=*/true);
16738
16739       --processing_template_decl;
16740
16741       if (partial_spec_args == error_mark_node)
16742         return error_mark_node;
16743
16744       spec_args = get_class_bindings (parms,
16745                                       partial_spec_args,
16746                                       args);
16747       if (spec_args)
16748         {
16749           if (outer_args)
16750             spec_args = add_to_template_args (outer_args, spec_args);
16751           list = tree_cons (spec_args, TREE_VALUE (t), list);
16752           TREE_TYPE (list) = TREE_TYPE (t);
16753         }
16754     }
16755
16756   if (! list)
16757     return NULL_TREE;
16758
16759   ambiguous_p = false;
16760   t = list;
16761   champ = t;
16762   t = TREE_CHAIN (t);
16763   for (; t; t = TREE_CHAIN (t))
16764     {
16765       fate = more_specialized_class (champ, t);
16766       if (fate == 1)
16767         ;
16768       else
16769         {
16770           if (fate == 0)
16771             {
16772               t = TREE_CHAIN (t);
16773               if (! t)
16774                 {
16775                   ambiguous_p = true;
16776                   break;
16777                 }
16778             }
16779           champ = t;
16780         }
16781     }
16782
16783   if (!ambiguous_p)
16784     for (t = list; t && t != champ; t = TREE_CHAIN (t))
16785       {
16786         fate = more_specialized_class (champ, t);
16787         if (fate != 1)
16788           {
16789             ambiguous_p = true;
16790             break;
16791           }
16792       }
16793
16794   if (ambiguous_p)
16795     {
16796       const char *str;
16797       char *spaces = NULL;
16798       if (!(complain & tf_error))
16799         return error_mark_node;
16800       error ("ambiguous class template instantiation for %q#T", type);
16801       str = ngettext ("candidate is:", "candidates are:", list_length (list));
16802       for (t = list; t; t = TREE_CHAIN (t))
16803         {
16804           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
16805           spaces = spaces ? spaces : get_spaces (str);
16806         }
16807       free (spaces);
16808       return error_mark_node;
16809     }
16810
16811   return champ;
16812 }
16813
16814 /* Explicitly instantiate DECL.  */
16815
16816 void
16817 do_decl_instantiation (tree decl, tree storage)
16818 {
16819   tree result = NULL_TREE;
16820   int extern_p = 0;
16821
16822   if (!decl || decl == error_mark_node)
16823     /* An error occurred, for which grokdeclarator has already issued
16824        an appropriate message.  */
16825     return;
16826   else if (! DECL_LANG_SPECIFIC (decl))
16827     {
16828       error ("explicit instantiation of non-template %q#D", decl);
16829       return;
16830     }
16831   else if (TREE_CODE (decl) == VAR_DECL)
16832     {
16833       /* There is an asymmetry here in the way VAR_DECLs and
16834          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
16835          the latter, the DECL we get back will be marked as a
16836          template instantiation, and the appropriate
16837          DECL_TEMPLATE_INFO will be set up.  This does not happen for
16838          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
16839          should handle VAR_DECLs as it currently handles
16840          FUNCTION_DECLs.  */
16841       if (!DECL_CLASS_SCOPE_P (decl))
16842         {
16843           error ("%qD is not a static data member of a class template", decl);
16844           return;
16845         }
16846       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
16847       if (!result || TREE_CODE (result) != VAR_DECL)
16848         {
16849           error ("no matching template for %qD found", decl);
16850           return;
16851         }
16852       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
16853         {
16854           error ("type %qT for explicit instantiation %qD does not match "
16855                  "declared type %qT", TREE_TYPE (result), decl,
16856                  TREE_TYPE (decl));
16857           return;
16858         }
16859     }
16860   else if (TREE_CODE (decl) != FUNCTION_DECL)
16861     {
16862       error ("explicit instantiation of %q#D", decl);
16863       return;
16864     }
16865   else
16866     result = decl;
16867
16868   /* Check for various error cases.  Note that if the explicit
16869      instantiation is valid the RESULT will currently be marked as an
16870      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
16871      until we get here.  */
16872
16873   if (DECL_TEMPLATE_SPECIALIZATION (result))
16874     {
16875       /* DR 259 [temp.spec].
16876
16877          Both an explicit instantiation and a declaration of an explicit
16878          specialization shall not appear in a program unless the explicit
16879          instantiation follows a declaration of the explicit specialization.
16880
16881          For a given set of template parameters, if an explicit
16882          instantiation of a template appears after a declaration of an
16883          explicit specialization for that template, the explicit
16884          instantiation has no effect.  */
16885       return;
16886     }
16887   else if (DECL_EXPLICIT_INSTANTIATION (result))
16888     {
16889       /* [temp.spec]
16890
16891          No program shall explicitly instantiate any template more
16892          than once.
16893
16894          We check DECL_NOT_REALLY_EXTERN so as not to complain when
16895          the first instantiation was `extern' and the second is not,
16896          and EXTERN_P for the opposite case.  */
16897       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16898         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16899       /* If an "extern" explicit instantiation follows an ordinary
16900          explicit instantiation, the template is instantiated.  */
16901       if (extern_p)
16902         return;
16903     }
16904   else if (!DECL_IMPLICIT_INSTANTIATION (result))
16905     {
16906       error ("no matching template for %qD found", result);
16907       return;
16908     }
16909   else if (!DECL_TEMPLATE_INFO (result))
16910     {
16911       permerror (input_location, "explicit instantiation of non-template %q#D", result);
16912       return;
16913     }
16914
16915   if (storage == NULL_TREE)
16916     ;
16917   else if (storage == ridpointers[(int) RID_EXTERN])
16918     {
16919       if (!in_system_header && (cxx_dialect == cxx98))
16920         pedwarn (input_location, OPT_pedantic, 
16921                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16922                  "instantiations");
16923       extern_p = 1;
16924     }
16925   else
16926     error ("storage class %qD applied to template instantiation", storage);
16927
16928   check_explicit_instantiation_namespace (result);
16929   mark_decl_instantiated (result, extern_p);
16930   if (! extern_p)
16931     instantiate_decl (result, /*defer_ok=*/1,
16932                       /*expl_inst_class_mem_p=*/false);
16933 }
16934
16935 static void
16936 mark_class_instantiated (tree t, int extern_p)
16937 {
16938   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
16939   SET_CLASSTYPE_INTERFACE_KNOWN (t);
16940   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
16941   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
16942   if (! extern_p)
16943     {
16944       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
16945       rest_of_type_compilation (t, 1);
16946     }
16947 }
16948
16949 /* Called from do_type_instantiation through binding_table_foreach to
16950    do recursive instantiation for the type bound in ENTRY.  */
16951 static void
16952 bt_instantiate_type_proc (binding_entry entry, void *data)
16953 {
16954   tree storage = *(tree *) data;
16955
16956   if (MAYBE_CLASS_TYPE_P (entry->type)
16957       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
16958     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
16959 }
16960
16961 /* Called from do_type_instantiation to instantiate a member
16962    (a member function or a static member variable) of an
16963    explicitly instantiated class template.  */
16964 static void
16965 instantiate_class_member (tree decl, int extern_p)
16966 {
16967   mark_decl_instantiated (decl, extern_p);
16968   if (! extern_p)
16969     instantiate_decl (decl, /*defer_ok=*/1,
16970                       /*expl_inst_class_mem_p=*/true);
16971 }
16972
16973 /* Perform an explicit instantiation of template class T.  STORAGE, if
16974    non-null, is the RID for extern, inline or static.  COMPLAIN is
16975    nonzero if this is called from the parser, zero if called recursively,
16976    since the standard is unclear (as detailed below).  */
16977
16978 void
16979 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
16980 {
16981   int extern_p = 0;
16982   int nomem_p = 0;
16983   int static_p = 0;
16984   int previous_instantiation_extern_p = 0;
16985
16986   if (TREE_CODE (t) == TYPE_DECL)
16987     t = TREE_TYPE (t);
16988
16989   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
16990     {
16991       error ("explicit instantiation of non-template type %qT", t);
16992       return;
16993     }
16994
16995   complete_type (t);
16996
16997   if (!COMPLETE_TYPE_P (t))
16998     {
16999       if (complain & tf_error)
17000         error ("explicit instantiation of %q#T before definition of template",
17001                t);
17002       return;
17003     }
17004
17005   if (storage != NULL_TREE)
17006     {
17007       if (!in_system_header)
17008         {
17009           if (storage == ridpointers[(int) RID_EXTERN])
17010             {
17011               if (cxx_dialect == cxx98)
17012                 pedwarn (input_location, OPT_pedantic, 
17013                          "ISO C++ 1998 forbids the use of %<extern%> on "
17014                          "explicit instantiations");
17015             }
17016           else
17017             pedwarn (input_location, OPT_pedantic, 
17018                      "ISO C++ forbids the use of %qE"
17019                      " on explicit instantiations", storage);
17020         }
17021
17022       if (storage == ridpointers[(int) RID_INLINE])
17023         nomem_p = 1;
17024       else if (storage == ridpointers[(int) RID_EXTERN])
17025         extern_p = 1;
17026       else if (storage == ridpointers[(int) RID_STATIC])
17027         static_p = 1;
17028       else
17029         {
17030           error ("storage class %qD applied to template instantiation",
17031                  storage);
17032           extern_p = 0;
17033         }
17034     }
17035
17036   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
17037     {
17038       /* DR 259 [temp.spec].
17039
17040          Both an explicit instantiation and a declaration of an explicit
17041          specialization shall not appear in a program unless the explicit
17042          instantiation follows a declaration of the explicit specialization.
17043
17044          For a given set of template parameters, if an explicit
17045          instantiation of a template appears after a declaration of an
17046          explicit specialization for that template, the explicit
17047          instantiation has no effect.  */
17048       return;
17049     }
17050   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
17051     {
17052       /* [temp.spec]
17053
17054          No program shall explicitly instantiate any template more
17055          than once.
17056
17057          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
17058          instantiation was `extern'.  If EXTERN_P then the second is.
17059          These cases are OK.  */
17060       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
17061
17062       if (!previous_instantiation_extern_p && !extern_p
17063           && (complain & tf_error))
17064         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
17065
17066       /* If we've already instantiated the template, just return now.  */
17067       if (!CLASSTYPE_INTERFACE_ONLY (t))
17068         return;
17069     }
17070
17071   check_explicit_instantiation_namespace (TYPE_NAME (t));
17072   mark_class_instantiated (t, extern_p);
17073
17074   if (nomem_p)
17075     return;
17076
17077   {
17078     tree tmp;
17079
17080     /* In contrast to implicit instantiation, where only the
17081        declarations, and not the definitions, of members are
17082        instantiated, we have here:
17083
17084          [temp.explicit]
17085
17086          The explicit instantiation of a class template specialization
17087          implies the instantiation of all of its members not
17088          previously explicitly specialized in the translation unit
17089          containing the explicit instantiation.
17090
17091        Of course, we can't instantiate member template classes, since
17092        we don't have any arguments for them.  Note that the standard
17093        is unclear on whether the instantiation of the members are
17094        *explicit* instantiations or not.  However, the most natural
17095        interpretation is that it should be an explicit instantiation.  */
17096
17097     if (! static_p)
17098       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
17099         if (TREE_CODE (tmp) == FUNCTION_DECL
17100             && DECL_TEMPLATE_INSTANTIATION (tmp))
17101           instantiate_class_member (tmp, extern_p);
17102
17103     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
17104       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
17105         instantiate_class_member (tmp, extern_p);
17106
17107     if (CLASSTYPE_NESTED_UTDS (t))
17108       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
17109                              bt_instantiate_type_proc, &storage);
17110   }
17111 }
17112
17113 /* Given a function DECL, which is a specialization of TMPL, modify
17114    DECL to be a re-instantiation of TMPL with the same template
17115    arguments.  TMPL should be the template into which tsubst'ing
17116    should occur for DECL, not the most general template.
17117
17118    One reason for doing this is a scenario like this:
17119
17120      template <class T>
17121      void f(const T&, int i);
17122
17123      void g() { f(3, 7); }
17124
17125      template <class T>
17126      void f(const T& t, const int i) { }
17127
17128    Note that when the template is first instantiated, with
17129    instantiate_template, the resulting DECL will have no name for the
17130    first parameter, and the wrong type for the second.  So, when we go
17131    to instantiate the DECL, we regenerate it.  */
17132
17133 static void
17134 regenerate_decl_from_template (tree decl, tree tmpl)
17135 {
17136   /* The arguments used to instantiate DECL, from the most general
17137      template.  */
17138   tree args;
17139   tree code_pattern;
17140
17141   args = DECL_TI_ARGS (decl);
17142   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
17143
17144   /* Make sure that we can see identifiers, and compute access
17145      correctly.  */
17146   push_access_scope (decl);
17147
17148   if (TREE_CODE (decl) == FUNCTION_DECL)
17149     {
17150       tree decl_parm;
17151       tree pattern_parm;
17152       tree specs;
17153       int args_depth;
17154       int parms_depth;
17155
17156       args_depth = TMPL_ARGS_DEPTH (args);
17157       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
17158       if (args_depth > parms_depth)
17159         args = get_innermost_template_args (args, parms_depth);
17160
17161       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
17162                                               args, tf_error, NULL_TREE);
17163       if (specs)
17164         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
17165                                                     specs);
17166
17167       /* Merge parameter declarations.  */
17168       decl_parm = skip_artificial_parms_for (decl,
17169                                              DECL_ARGUMENTS (decl));
17170       pattern_parm
17171         = skip_artificial_parms_for (code_pattern,
17172                                      DECL_ARGUMENTS (code_pattern));
17173       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
17174         {
17175           tree parm_type;
17176           tree attributes;
17177           
17178           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17179             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
17180           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
17181                               NULL_TREE);
17182           parm_type = type_decays_to (parm_type);
17183           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17184             TREE_TYPE (decl_parm) = parm_type;
17185           attributes = DECL_ATTRIBUTES (pattern_parm);
17186           if (DECL_ATTRIBUTES (decl_parm) != attributes)
17187             {
17188               DECL_ATTRIBUTES (decl_parm) = attributes;
17189               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17190             }
17191           decl_parm = DECL_CHAIN (decl_parm);
17192           pattern_parm = DECL_CHAIN (pattern_parm);
17193         }
17194       /* Merge any parameters that match with the function parameter
17195          pack.  */
17196       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
17197         {
17198           int i, len;
17199           tree expanded_types;
17200           /* Expand the TYPE_PACK_EXPANSION that provides the types for
17201              the parameters in this function parameter pack.  */
17202           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
17203                                                  args, tf_error, NULL_TREE);
17204           len = TREE_VEC_LENGTH (expanded_types);
17205           for (i = 0; i < len; i++)
17206             {
17207               tree parm_type;
17208               tree attributes;
17209           
17210               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17211                 /* Rename the parameter to include the index.  */
17212                 DECL_NAME (decl_parm) = 
17213                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
17214               parm_type = TREE_VEC_ELT (expanded_types, i);
17215               parm_type = type_decays_to (parm_type);
17216               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17217                 TREE_TYPE (decl_parm) = parm_type;
17218               attributes = DECL_ATTRIBUTES (pattern_parm);
17219               if (DECL_ATTRIBUTES (decl_parm) != attributes)
17220                 {
17221                   DECL_ATTRIBUTES (decl_parm) = attributes;
17222                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17223                 }
17224               decl_parm = DECL_CHAIN (decl_parm);
17225             }
17226         }
17227       /* Merge additional specifiers from the CODE_PATTERN.  */
17228       if (DECL_DECLARED_INLINE_P (code_pattern)
17229           && !DECL_DECLARED_INLINE_P (decl))
17230         DECL_DECLARED_INLINE_P (decl) = 1;
17231     }
17232   else if (TREE_CODE (decl) == VAR_DECL)
17233     {
17234       DECL_INITIAL (decl) =
17235         tsubst_expr (DECL_INITIAL (code_pattern), args,
17236                      tf_error, DECL_TI_TEMPLATE (decl),
17237                      /*integral_constant_expression_p=*/false);
17238       if (VAR_HAD_UNKNOWN_BOUND (decl))
17239         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
17240                                    tf_error, DECL_TI_TEMPLATE (decl));
17241     }
17242   else
17243     gcc_unreachable ();
17244
17245   pop_access_scope (decl);
17246 }
17247
17248 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
17249    substituted to get DECL.  */
17250
17251 tree
17252 template_for_substitution (tree decl)
17253 {
17254   tree tmpl = DECL_TI_TEMPLATE (decl);
17255
17256   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
17257      for the instantiation.  This is not always the most general
17258      template.  Consider, for example:
17259
17260         template <class T>
17261         struct S { template <class U> void f();
17262                    template <> void f<int>(); };
17263
17264      and an instantiation of S<double>::f<int>.  We want TD to be the
17265      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
17266   while (/* An instantiation cannot have a definition, so we need a
17267             more general template.  */
17268          DECL_TEMPLATE_INSTANTIATION (tmpl)
17269            /* We must also deal with friend templates.  Given:
17270
17271                 template <class T> struct S {
17272                   template <class U> friend void f() {};
17273                 };
17274
17275               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
17276               so far as the language is concerned, but that's still
17277               where we get the pattern for the instantiation from.  On
17278               other hand, if the definition comes outside the class, say:
17279
17280                 template <class T> struct S {
17281                   template <class U> friend void f();
17282                 };
17283                 template <class U> friend void f() {}
17284
17285               we don't need to look any further.  That's what the check for
17286               DECL_INITIAL is for.  */
17287           || (TREE_CODE (decl) == FUNCTION_DECL
17288               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
17289               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
17290     {
17291       /* The present template, TD, should not be a definition.  If it
17292          were a definition, we should be using it!  Note that we
17293          cannot restructure the loop to just keep going until we find
17294          a template with a definition, since that might go too far if
17295          a specialization was declared, but not defined.  */
17296       gcc_assert (TREE_CODE (decl) != VAR_DECL
17297                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
17298
17299       /* Fetch the more general template.  */
17300       tmpl = DECL_TI_TEMPLATE (tmpl);
17301     }
17302
17303   return tmpl;
17304 }
17305
17306 /* Returns true if we need to instantiate this template instance even if we
17307    know we aren't going to emit it..  */
17308
17309 bool
17310 always_instantiate_p (tree decl)
17311 {
17312   /* We always instantiate inline functions so that we can inline them.  An
17313      explicit instantiation declaration prohibits implicit instantiation of
17314      non-inline functions.  With high levels of optimization, we would
17315      normally inline non-inline functions -- but we're not allowed to do
17316      that for "extern template" functions.  Therefore, we check
17317      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
17318   return ((TREE_CODE (decl) == FUNCTION_DECL
17319            && DECL_DECLARED_INLINE_P (decl))
17320           /* And we need to instantiate static data members so that
17321              their initializers are available in integral constant
17322              expressions.  */
17323           || (TREE_CODE (decl) == VAR_DECL
17324               && decl_maybe_constant_var_p (decl)));
17325 }
17326
17327 /* Produce the definition of D, a _DECL generated from a template.  If
17328    DEFER_OK is nonzero, then we don't have to actually do the
17329    instantiation now; we just have to do it sometime.  Normally it is
17330    an error if this is an explicit instantiation but D is undefined.
17331    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
17332    explicitly instantiated class template.  */
17333
17334 tree
17335 instantiate_decl (tree d, int defer_ok,
17336                   bool expl_inst_class_mem_p)
17337 {
17338   tree tmpl = DECL_TI_TEMPLATE (d);
17339   tree gen_args;
17340   tree args;
17341   tree td;
17342   tree code_pattern;
17343   tree spec;
17344   tree gen_tmpl;
17345   bool pattern_defined;
17346   int need_push;
17347   location_t saved_loc = input_location;
17348   bool external_p;
17349
17350   /* This function should only be used to instantiate templates for
17351      functions and static member variables.  */
17352   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
17353               || TREE_CODE (d) == VAR_DECL);
17354
17355   /* Variables are never deferred; if instantiation is required, they
17356      are instantiated right away.  That allows for better code in the
17357      case that an expression refers to the value of the variable --
17358      if the variable has a constant value the referring expression can
17359      take advantage of that fact.  */
17360   if (TREE_CODE (d) == VAR_DECL
17361       || DECL_DECLARED_CONSTEXPR_P (d))
17362     defer_ok = 0;
17363
17364   /* Don't instantiate cloned functions.  Instead, instantiate the
17365      functions they cloned.  */
17366   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
17367     d = DECL_CLONED_FUNCTION (d);
17368
17369   if (DECL_TEMPLATE_INSTANTIATED (d)
17370       || DECL_TEMPLATE_SPECIALIZATION (d))
17371     /* D has already been instantiated or explicitly specialized, so
17372        there's nothing for us to do here.
17373
17374        It might seem reasonable to check whether or not D is an explicit
17375        instantiation, and, if so, stop here.  But when an explicit
17376        instantiation is deferred until the end of the compilation,
17377        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
17378        the instantiation.  */
17379     return d;
17380
17381   /* Check to see whether we know that this template will be
17382      instantiated in some other file, as with "extern template"
17383      extension.  */
17384   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
17385
17386   /* In general, we do not instantiate such templates.  */
17387   if (external_p && !always_instantiate_p (d))
17388     return d;
17389
17390   gen_tmpl = most_general_template (tmpl);
17391   gen_args = DECL_TI_ARGS (d);
17392
17393   if (tmpl != gen_tmpl)
17394     /* We should already have the extra args.  */
17395     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
17396                 == TMPL_ARGS_DEPTH (gen_args));
17397   /* And what's in the hash table should match D.  */
17398   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
17399               || spec == NULL_TREE);
17400
17401   /* This needs to happen before any tsubsting.  */
17402   if (! push_tinst_level (d))
17403     return d;
17404
17405   timevar_push (TV_TEMPLATE_INST);
17406
17407   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
17408      for the instantiation.  */
17409   td = template_for_substitution (d);
17410   code_pattern = DECL_TEMPLATE_RESULT (td);
17411
17412   /* We should never be trying to instantiate a member of a class
17413      template or partial specialization.  */
17414   gcc_assert (d != code_pattern);
17415
17416   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
17417       || DECL_TEMPLATE_SPECIALIZATION (td))
17418     /* In the case of a friend template whose definition is provided
17419        outside the class, we may have too many arguments.  Drop the
17420        ones we don't need.  The same is true for specializations.  */
17421     args = get_innermost_template_args
17422       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
17423   else
17424     args = gen_args;
17425
17426   if (TREE_CODE (d) == FUNCTION_DECL)
17427     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE
17428                        || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern));
17429   else
17430     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
17431
17432   /* We may be in the middle of deferred access check.  Disable it now.  */
17433   push_deferring_access_checks (dk_no_deferred);
17434
17435   /* Unless an explicit instantiation directive has already determined
17436      the linkage of D, remember that a definition is available for
17437      this entity.  */
17438   if (pattern_defined
17439       && !DECL_INTERFACE_KNOWN (d)
17440       && !DECL_NOT_REALLY_EXTERN (d))
17441     mark_definable (d);
17442
17443   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
17444   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
17445   input_location = DECL_SOURCE_LOCATION (d);
17446
17447   /* If D is a member of an explicitly instantiated class template,
17448      and no definition is available, treat it like an implicit
17449      instantiation.  */
17450   if (!pattern_defined && expl_inst_class_mem_p
17451       && DECL_EXPLICIT_INSTANTIATION (d))
17452     {
17453       /* Leave linkage flags alone on instantiations with anonymous
17454          visibility.  */
17455       if (TREE_PUBLIC (d))
17456         {
17457           DECL_NOT_REALLY_EXTERN (d) = 0;
17458           DECL_INTERFACE_KNOWN (d) = 0;
17459         }
17460       SET_DECL_IMPLICIT_INSTANTIATION (d);
17461     }
17462
17463   /* Recheck the substitutions to obtain any warning messages
17464      about ignoring cv qualifiers.  Don't do this for artificial decls,
17465      as it breaks the context-sensitive substitution for lambda op(). */
17466   if (!defer_ok && !DECL_ARTIFICIAL (d))
17467     {
17468       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
17469       tree type = TREE_TYPE (gen);
17470
17471       /* Make sure that we can see identifiers, and compute access
17472          correctly.  D is already the target FUNCTION_DECL with the
17473          right context.  */
17474       push_access_scope (d);
17475
17476       if (TREE_CODE (gen) == FUNCTION_DECL)
17477         {
17478           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
17479           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
17480                                           d);
17481           /* Don't simply tsubst the function type, as that will give
17482              duplicate warnings about poor parameter qualifications.
17483              The function arguments are the same as the decl_arguments
17484              without the top level cv qualifiers.  */
17485           type = TREE_TYPE (type);
17486         }
17487       tsubst (type, gen_args, tf_warning_or_error, d);
17488
17489       pop_access_scope (d);
17490     }
17491
17492   /* Defer all other templates, unless we have been explicitly
17493      forbidden from doing so.  */
17494   if (/* If there is no definition, we cannot instantiate the
17495          template.  */
17496       ! pattern_defined
17497       /* If it's OK to postpone instantiation, do so.  */
17498       || defer_ok
17499       /* If this is a static data member that will be defined
17500          elsewhere, we don't want to instantiate the entire data
17501          member, but we do want to instantiate the initializer so that
17502          we can substitute that elsewhere.  */
17503       || (external_p && TREE_CODE (d) == VAR_DECL))
17504     {
17505       /* The definition of the static data member is now required so
17506          we must substitute the initializer.  */
17507       if (TREE_CODE (d) == VAR_DECL
17508           && !DECL_INITIAL (d)
17509           && DECL_INITIAL (code_pattern))
17510         {
17511           tree ns;
17512           tree init;
17513           bool const_init = false;
17514
17515           ns = decl_namespace_context (d);
17516           push_nested_namespace (ns);
17517           push_nested_class (DECL_CONTEXT (d));
17518           init = tsubst_expr (DECL_INITIAL (code_pattern),
17519                               args,
17520                               tf_warning_or_error, NULL_TREE,
17521                               /*integral_constant_expression_p=*/false);
17522           /* Make sure the initializer is still constant, in case of
17523              circular dependency (template/instantiate6.C). */
17524           const_init
17525             = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
17526           cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
17527                           /*asmspec_tree=*/NULL_TREE,
17528                           LOOKUP_ONLYCONVERTING);
17529           pop_nested_class ();
17530           pop_nested_namespace (ns);
17531         }
17532
17533       /* We restore the source position here because it's used by
17534          add_pending_template.  */
17535       input_location = saved_loc;
17536
17537       if (at_eof && !pattern_defined
17538           && DECL_EXPLICIT_INSTANTIATION (d)
17539           && DECL_NOT_REALLY_EXTERN (d))
17540         /* [temp.explicit]
17541
17542            The definition of a non-exported function template, a
17543            non-exported member function template, or a non-exported
17544            member function or static data member of a class template
17545            shall be present in every translation unit in which it is
17546            explicitly instantiated.  */
17547         permerror (input_location,  "explicit instantiation of %qD "
17548                    "but no definition available", d);
17549
17550       /* If we're in unevaluated context, we just wanted to get the
17551          constant value; this isn't an odr use, so don't queue
17552          a full instantiation.  */
17553       if (cp_unevaluated_operand != 0)
17554         goto out;
17555       /* ??? Historically, we have instantiated inline functions, even
17556          when marked as "extern template".  */
17557       if (!(external_p && TREE_CODE (d) == VAR_DECL))
17558         add_pending_template (d);
17559       goto out;
17560     }
17561   /* Tell the repository that D is available in this translation unit
17562      -- and see if it is supposed to be instantiated here.  */
17563   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
17564     {
17565       /* In a PCH file, despite the fact that the repository hasn't
17566          requested instantiation in the PCH it is still possible that
17567          an instantiation will be required in a file that includes the
17568          PCH.  */
17569       if (pch_file)
17570         add_pending_template (d);
17571       /* Instantiate inline functions so that the inliner can do its
17572          job, even though we'll not be emitting a copy of this
17573          function.  */
17574       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
17575         goto out;
17576     }
17577
17578   need_push = !cfun || !global_bindings_p ();
17579   if (need_push)
17580     push_to_top_level ();
17581
17582   /* Mark D as instantiated so that recursive calls to
17583      instantiate_decl do not try to instantiate it again.  */
17584   DECL_TEMPLATE_INSTANTIATED (d) = 1;
17585
17586   /* Regenerate the declaration in case the template has been modified
17587      by a subsequent redeclaration.  */
17588   regenerate_decl_from_template (d, td);
17589
17590   /* We already set the file and line above.  Reset them now in case
17591      they changed as a result of calling regenerate_decl_from_template.  */
17592   input_location = DECL_SOURCE_LOCATION (d);
17593
17594   if (TREE_CODE (d) == VAR_DECL)
17595     {
17596       tree init;
17597       bool const_init = false;
17598
17599       /* Clear out DECL_RTL; whatever was there before may not be right
17600          since we've reset the type of the declaration.  */
17601       SET_DECL_RTL (d, NULL);
17602       DECL_IN_AGGR_P (d) = 0;
17603
17604       /* The initializer is placed in DECL_INITIAL by
17605          regenerate_decl_from_template so we don't need to
17606          push/pop_access_scope again here.  Pull it out so that
17607          cp_finish_decl can process it.  */
17608       init = DECL_INITIAL (d);
17609       DECL_INITIAL (d) = NULL_TREE;
17610       DECL_INITIALIZED_P (d) = 0;
17611
17612       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
17613          initializer.  That function will defer actual emission until
17614          we have a chance to determine linkage.  */
17615       DECL_EXTERNAL (d) = 0;
17616
17617       /* Enter the scope of D so that access-checking works correctly.  */
17618       push_nested_class (DECL_CONTEXT (d));
17619       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
17620       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
17621       pop_nested_class ();
17622     }
17623   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
17624     synthesize_method (d);
17625   else if (TREE_CODE (d) == FUNCTION_DECL)
17626     {
17627       htab_t saved_local_specializations;
17628       tree subst_decl;
17629       tree tmpl_parm;
17630       tree spec_parm;
17631
17632       /* Save away the current list, in case we are instantiating one
17633          template from within the body of another.  */
17634       saved_local_specializations = local_specializations;
17635
17636       /* Set up the list of local specializations.  */
17637       local_specializations = htab_create (37,
17638                                            hash_local_specialization,
17639                                            eq_local_specializations,
17640                                            NULL);
17641
17642       /* Set up context.  */
17643       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
17644
17645       /* Create substitution entries for the parameters.  */
17646       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
17647       tmpl_parm = DECL_ARGUMENTS (subst_decl);
17648       spec_parm = DECL_ARGUMENTS (d);
17649       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
17650         {
17651           register_local_specialization (spec_parm, tmpl_parm);
17652           spec_parm = skip_artificial_parms_for (d, spec_parm);
17653           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
17654         }
17655       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
17656         {
17657           register_local_specialization (spec_parm, tmpl_parm);
17658           tmpl_parm = DECL_CHAIN (tmpl_parm);
17659           spec_parm = DECL_CHAIN (spec_parm);
17660         }
17661       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
17662         {
17663           /* Register the (value) argument pack as a specialization of
17664              TMPL_PARM, then move on.  */
17665           tree argpack = make_fnparm_pack (spec_parm);
17666           register_local_specialization (argpack, tmpl_parm);
17667           tmpl_parm = DECL_CHAIN (tmpl_parm);
17668           spec_parm = NULL_TREE;
17669         }
17670       gcc_assert (!spec_parm);
17671
17672       /* Substitute into the body of the function.  */
17673       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
17674                    tf_warning_or_error, tmpl,
17675                    /*integral_constant_expression_p=*/false);
17676
17677       /* Set the current input_location to the end of the function
17678          so that finish_function knows where we are.  */
17679       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
17680
17681       /* We don't need the local specializations any more.  */
17682       htab_delete (local_specializations);
17683       local_specializations = saved_local_specializations;
17684
17685       /* Finish the function.  */
17686       d = finish_function (0);
17687       expand_or_defer_fn (d);
17688     }
17689
17690   /* We're not deferring instantiation any more.  */
17691   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
17692
17693   if (need_push)
17694     pop_from_top_level ();
17695
17696 out:
17697   input_location = saved_loc;
17698   pop_deferring_access_checks ();
17699   pop_tinst_level ();
17700
17701   timevar_pop (TV_TEMPLATE_INST);
17702
17703   return d;
17704 }
17705
17706 /* Run through the list of templates that we wish we could
17707    instantiate, and instantiate any we can.  RETRIES is the
17708    number of times we retry pending template instantiation.  */
17709
17710 void
17711 instantiate_pending_templates (int retries)
17712 {
17713   int reconsider;
17714   location_t saved_loc = input_location;
17715
17716   /* Instantiating templates may trigger vtable generation.  This in turn
17717      may require further template instantiations.  We place a limit here
17718      to avoid infinite loop.  */
17719   if (pending_templates && retries >= max_tinst_depth)
17720     {
17721       tree decl = pending_templates->tinst->decl;
17722
17723       error ("template instantiation depth exceeds maximum of %d"
17724              " instantiating %q+D, possibly from virtual table generation"
17725              " (use -ftemplate-depth= to increase the maximum)",
17726              max_tinst_depth, decl);
17727       if (TREE_CODE (decl) == FUNCTION_DECL)
17728         /* Pretend that we defined it.  */
17729         DECL_INITIAL (decl) = error_mark_node;
17730       return;
17731     }
17732
17733   do
17734     {
17735       struct pending_template **t = &pending_templates;
17736       struct pending_template *last = NULL;
17737       reconsider = 0;
17738       while (*t)
17739         {
17740           tree instantiation = reopen_tinst_level ((*t)->tinst);
17741           bool complete = false;
17742
17743           if (TYPE_P (instantiation))
17744             {
17745               tree fn;
17746
17747               if (!COMPLETE_TYPE_P (instantiation))
17748                 {
17749                   instantiate_class_template (instantiation);
17750                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
17751                     for (fn = TYPE_METHODS (instantiation);
17752                          fn;
17753                          fn = TREE_CHAIN (fn))
17754                       if (! DECL_ARTIFICIAL (fn))
17755                         instantiate_decl (fn,
17756                                           /*defer_ok=*/0,
17757                                           /*expl_inst_class_mem_p=*/false);
17758                   if (COMPLETE_TYPE_P (instantiation))
17759                     reconsider = 1;
17760                 }
17761
17762               complete = COMPLETE_TYPE_P (instantiation);
17763             }
17764           else
17765             {
17766               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
17767                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
17768                 {
17769                   instantiation
17770                     = instantiate_decl (instantiation,
17771                                         /*defer_ok=*/0,
17772                                         /*expl_inst_class_mem_p=*/false);
17773                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
17774                     reconsider = 1;
17775                 }
17776
17777               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
17778                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
17779             }
17780
17781           if (complete)
17782             /* If INSTANTIATION has been instantiated, then we don't
17783                need to consider it again in the future.  */
17784             *t = (*t)->next;
17785           else
17786             {
17787               last = *t;
17788               t = &(*t)->next;
17789             }
17790           tinst_depth = 0;
17791           current_tinst_level = NULL;
17792         }
17793       last_pending_template = last;
17794     }
17795   while (reconsider);
17796
17797   input_location = saved_loc;
17798 }
17799
17800 /* Substitute ARGVEC into T, which is a list of initializers for
17801    either base class or a non-static data member.  The TREE_PURPOSEs
17802    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
17803    instantiate_decl.  */
17804
17805 static tree
17806 tsubst_initializer_list (tree t, tree argvec)
17807 {
17808   tree inits = NULL_TREE;
17809
17810   for (; t; t = TREE_CHAIN (t))
17811     {
17812       tree decl;
17813       tree init;
17814       tree expanded_bases = NULL_TREE;
17815       tree expanded_arguments = NULL_TREE;
17816       int i, len = 1;
17817
17818       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
17819         {
17820           tree expr;
17821           tree arg;
17822
17823           /* Expand the base class expansion type into separate base
17824              classes.  */
17825           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
17826                                                  tf_warning_or_error,
17827                                                  NULL_TREE);
17828           if (expanded_bases == error_mark_node)
17829             continue;
17830           
17831           /* We'll be building separate TREE_LISTs of arguments for
17832              each base.  */
17833           len = TREE_VEC_LENGTH (expanded_bases);
17834           expanded_arguments = make_tree_vec (len);
17835           for (i = 0; i < len; i++)
17836             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
17837
17838           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
17839              expand each argument in the TREE_VALUE of t.  */
17840           expr = make_node (EXPR_PACK_EXPANSION);
17841           PACK_EXPANSION_PARAMETER_PACKS (expr) =
17842             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
17843
17844           if (TREE_VALUE (t) == void_type_node)
17845             /* VOID_TYPE_NODE is used to indicate
17846                value-initialization.  */
17847             {
17848               for (i = 0; i < len; i++)
17849                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
17850             }
17851           else
17852             {
17853               /* Substitute parameter packs into each argument in the
17854                  TREE_LIST.  */
17855               in_base_initializer = 1;
17856               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
17857                 {
17858                   tree expanded_exprs;
17859
17860                   /* Expand the argument.  */
17861                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
17862                   expanded_exprs 
17863                     = tsubst_pack_expansion (expr, argvec,
17864                                              tf_warning_or_error,
17865                                              NULL_TREE);
17866                   if (expanded_exprs == error_mark_node)
17867                     continue;
17868
17869                   /* Prepend each of the expanded expressions to the
17870                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
17871                   for (i = 0; i < len; i++)
17872                     {
17873                       TREE_VEC_ELT (expanded_arguments, i) = 
17874                         tree_cons (NULL_TREE, 
17875                                    TREE_VEC_ELT (expanded_exprs, i),
17876                                    TREE_VEC_ELT (expanded_arguments, i));
17877                     }
17878                 }
17879               in_base_initializer = 0;
17880
17881               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
17882                  since we built them backwards.  */
17883               for (i = 0; i < len; i++)
17884                 {
17885                   TREE_VEC_ELT (expanded_arguments, i) = 
17886                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
17887                 }
17888             }
17889         }
17890
17891       for (i = 0; i < len; ++i)
17892         {
17893           if (expanded_bases)
17894             {
17895               decl = TREE_VEC_ELT (expanded_bases, i);
17896               decl = expand_member_init (decl);
17897               init = TREE_VEC_ELT (expanded_arguments, i);
17898             }
17899           else
17900             {
17901               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
17902                                   tf_warning_or_error, NULL_TREE);
17903
17904               decl = expand_member_init (decl);
17905               if (decl && !DECL_P (decl))
17906                 in_base_initializer = 1;
17907
17908               init = TREE_VALUE (t);
17909               if (init != void_type_node)
17910                 init = tsubst_expr (init, argvec,
17911                                     tf_warning_or_error, NULL_TREE,
17912                                     /*integral_constant_expression_p=*/false);
17913               in_base_initializer = 0;
17914             }
17915
17916           if (decl)
17917             {
17918               init = build_tree_list (decl, init);
17919               TREE_CHAIN (init) = inits;
17920               inits = init;
17921             }
17922         }
17923     }
17924   return inits;
17925 }
17926
17927 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
17928
17929 static void
17930 set_current_access_from_decl (tree decl)
17931 {
17932   if (TREE_PRIVATE (decl))
17933     current_access_specifier = access_private_node;
17934   else if (TREE_PROTECTED (decl))
17935     current_access_specifier = access_protected_node;
17936   else
17937     current_access_specifier = access_public_node;
17938 }
17939
17940 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
17941    is the instantiation (which should have been created with
17942    start_enum) and ARGS are the template arguments to use.  */
17943
17944 static void
17945 tsubst_enum (tree tag, tree newtag, tree args)
17946 {
17947   tree e;
17948
17949   if (SCOPED_ENUM_P (newtag))
17950     begin_scope (sk_scoped_enum, newtag);
17951
17952   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
17953     {
17954       tree value;
17955       tree decl;
17956
17957       decl = TREE_VALUE (e);
17958       /* Note that in a template enum, the TREE_VALUE is the
17959          CONST_DECL, not the corresponding INTEGER_CST.  */
17960       value = tsubst_expr (DECL_INITIAL (decl),
17961                            args, tf_warning_or_error, NULL_TREE,
17962                            /*integral_constant_expression_p=*/true);
17963
17964       /* Give this enumeration constant the correct access.  */
17965       set_current_access_from_decl (decl);
17966
17967       /* Actually build the enumerator itself.  */
17968       build_enumerator
17969         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
17970     }
17971
17972   if (SCOPED_ENUM_P (newtag))
17973     finish_scope ();
17974
17975   finish_enum_value_list (newtag);
17976   finish_enum (newtag);
17977
17978   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
17979     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
17980 }
17981
17982 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
17983    its type -- but without substituting the innermost set of template
17984    arguments.  So, innermost set of template parameters will appear in
17985    the type.  */
17986
17987 tree
17988 get_mostly_instantiated_function_type (tree decl)
17989 {
17990   tree fn_type;
17991   tree tmpl;
17992   tree targs;
17993   tree tparms;
17994   int parm_depth;
17995
17996   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
17997   targs = DECL_TI_ARGS (decl);
17998   tparms = DECL_TEMPLATE_PARMS (tmpl);
17999   parm_depth = TMPL_PARMS_DEPTH (tparms);
18000
18001   /* There should be as many levels of arguments as there are levels
18002      of parameters.  */
18003   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
18004
18005   fn_type = TREE_TYPE (tmpl);
18006
18007   if (parm_depth == 1)
18008     /* No substitution is necessary.  */
18009     ;
18010   else
18011     {
18012       int i;
18013       tree partial_args;
18014
18015       /* Replace the innermost level of the TARGS with NULL_TREEs to
18016          let tsubst know not to substitute for those parameters.  */
18017       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
18018       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
18019         SET_TMPL_ARGS_LEVEL (partial_args, i,
18020                              TMPL_ARGS_LEVEL (targs, i));
18021       SET_TMPL_ARGS_LEVEL (partial_args,
18022                            TMPL_ARGS_DEPTH (targs),
18023                            make_tree_vec (DECL_NTPARMS (tmpl)));
18024
18025       /* Make sure that we can see identifiers, and compute access
18026          correctly.  */
18027       push_access_scope (decl);
18028
18029       ++processing_template_decl;
18030       /* Now, do the (partial) substitution to figure out the
18031          appropriate function type.  */
18032       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
18033       --processing_template_decl;
18034
18035       /* Substitute into the template parameters to obtain the real
18036          innermost set of parameters.  This step is important if the
18037          innermost set of template parameters contains value
18038          parameters whose types depend on outer template parameters.  */
18039       TREE_VEC_LENGTH (partial_args)--;
18040       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
18041
18042       pop_access_scope (decl);
18043     }
18044
18045   return fn_type;
18046 }
18047
18048 /* Return truthvalue if we're processing a template different from
18049    the last one involved in diagnostics.  */
18050 int
18051 problematic_instantiation_changed (void)
18052 {
18053   return last_template_error_tick != tinst_level_tick;
18054 }
18055
18056 /* Remember current template involved in diagnostics.  */
18057 void
18058 record_last_problematic_instantiation (void)
18059 {
18060   last_template_error_tick = tinst_level_tick;
18061 }
18062
18063 struct tinst_level *
18064 current_instantiation (void)
18065 {
18066   return current_tinst_level;
18067 }
18068
18069 /* [temp.param] Check that template non-type parm TYPE is of an allowable
18070    type. Return zero for ok, nonzero for disallowed. Issue error and
18071    warning messages under control of COMPLAIN.  */
18072
18073 static int
18074 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
18075 {
18076   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
18077     return 0;
18078   else if (POINTER_TYPE_P (type))
18079     return 0;
18080   else if (TYPE_PTR_TO_MEMBER_P (type))
18081     return 0;
18082   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
18083     return 0;
18084   else if (TREE_CODE (type) == TYPENAME_TYPE)
18085     return 0;
18086   else if (TREE_CODE (type) == DECLTYPE_TYPE)
18087     return 0;
18088
18089   if (complain & tf_error)
18090     error ("%q#T is not a valid type for a template constant parameter", type);
18091   return 1;
18092 }
18093
18094 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
18095    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
18096
18097 static bool
18098 dependent_type_p_r (tree type)
18099 {
18100   tree scope;
18101
18102   /* [temp.dep.type]
18103
18104      A type is dependent if it is:
18105
18106      -- a template parameter. Template template parameters are types
18107         for us (since TYPE_P holds true for them) so we handle
18108         them here.  */
18109   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18110       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
18111     return true;
18112   /* -- a qualified-id with a nested-name-specifier which contains a
18113         class-name that names a dependent type or whose unqualified-id
18114         names a dependent type.  */
18115   if (TREE_CODE (type) == TYPENAME_TYPE)
18116     return true;
18117   /* -- a cv-qualified type where the cv-unqualified type is
18118         dependent.  */
18119   type = TYPE_MAIN_VARIANT (type);
18120   /* -- a compound type constructed from any dependent type.  */
18121   if (TYPE_PTR_TO_MEMBER_P (type))
18122     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
18123             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
18124                                            (type)));
18125   else if (TREE_CODE (type) == POINTER_TYPE
18126            || TREE_CODE (type) == REFERENCE_TYPE)
18127     return dependent_type_p (TREE_TYPE (type));
18128   else if (TREE_CODE (type) == FUNCTION_TYPE
18129            || TREE_CODE (type) == METHOD_TYPE)
18130     {
18131       tree arg_type;
18132
18133       if (dependent_type_p (TREE_TYPE (type)))
18134         return true;
18135       for (arg_type = TYPE_ARG_TYPES (type);
18136            arg_type;
18137            arg_type = TREE_CHAIN (arg_type))
18138         if (dependent_type_p (TREE_VALUE (arg_type)))
18139           return true;
18140       return false;
18141     }
18142   /* -- an array type constructed from any dependent type or whose
18143         size is specified by a constant expression that is
18144         value-dependent.
18145
18146         We checked for type- and value-dependence of the bounds in
18147         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
18148   if (TREE_CODE (type) == ARRAY_TYPE)
18149     {
18150       if (TYPE_DOMAIN (type)
18151           && dependent_type_p (TYPE_DOMAIN (type)))
18152         return true;
18153       return dependent_type_p (TREE_TYPE (type));
18154     }
18155
18156   /* -- a template-id in which either the template name is a template
18157      parameter ...  */
18158   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
18159     return true;
18160   /* ... or any of the template arguments is a dependent type or
18161         an expression that is type-dependent or value-dependent.  */
18162   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
18163            && (any_dependent_template_arguments_p
18164                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
18165     return true;
18166
18167   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
18168      dependent; if the argument of the `typeof' expression is not
18169      type-dependent, then it should already been have resolved.  */
18170   if (TREE_CODE (type) == TYPEOF_TYPE
18171       || TREE_CODE (type) == DECLTYPE_TYPE
18172       || TREE_CODE (type) == UNDERLYING_TYPE)
18173     return true;
18174
18175   /* A template argument pack is dependent if any of its packed
18176      arguments are.  */
18177   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
18178     {
18179       tree args = ARGUMENT_PACK_ARGS (type);
18180       int i, len = TREE_VEC_LENGTH (args);
18181       for (i = 0; i < len; ++i)
18182         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
18183           return true;
18184     }
18185
18186   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
18187      be template parameters.  */
18188   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
18189     return true;
18190
18191   /* The standard does not specifically mention types that are local
18192      to template functions or local classes, but they should be
18193      considered dependent too.  For example:
18194
18195        template <int I> void f() {
18196          enum E { a = I };
18197          S<sizeof (E)> s;
18198        }
18199
18200      The size of `E' cannot be known until the value of `I' has been
18201      determined.  Therefore, `E' must be considered dependent.  */
18202   scope = TYPE_CONTEXT (type);
18203   if (scope && TYPE_P (scope))
18204     return dependent_type_p (scope);
18205   /* Don't use type_dependent_expression_p here, as it can lead
18206      to infinite recursion trying to determine whether a lambda
18207      nested in a lambda is dependent (c++/47687).  */
18208   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
18209            && DECL_LANG_SPECIFIC (scope)
18210            && DECL_TEMPLATE_INFO (scope)
18211            && (any_dependent_template_arguments_p
18212                (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
18213     return true;
18214
18215   /* Other types are non-dependent.  */
18216   return false;
18217 }
18218
18219 /* Returns TRUE if TYPE is dependent, in the sense of
18220    [temp.dep.type].  Note that a NULL type is considered dependent.  */
18221
18222 bool
18223 dependent_type_p (tree type)
18224 {
18225   /* If there are no template parameters in scope, then there can't be
18226      any dependent types.  */
18227   if (!processing_template_decl)
18228     {
18229       /* If we are not processing a template, then nobody should be
18230          providing us with a dependent type.  */
18231       gcc_assert (type);
18232       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
18233       return false;
18234     }
18235
18236   /* If the type is NULL, we have not computed a type for the entity
18237      in question; in that case, the type is dependent.  */
18238   if (!type)
18239     return true;
18240
18241   /* Erroneous types can be considered non-dependent.  */
18242   if (type == error_mark_node)
18243     return false;
18244
18245   /* If we have not already computed the appropriate value for TYPE,
18246      do so now.  */
18247   if (!TYPE_DEPENDENT_P_VALID (type))
18248     {
18249       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
18250       TYPE_DEPENDENT_P_VALID (type) = 1;
18251     }
18252
18253   return TYPE_DEPENDENT_P (type);
18254 }
18255
18256 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
18257    lookup.  In other words, a dependent type that is not the current
18258    instantiation.  */
18259
18260 bool
18261 dependent_scope_p (tree scope)
18262 {
18263   return (scope && TYPE_P (scope) && dependent_type_p (scope)
18264           && !currently_open_class (scope));
18265 }
18266
18267 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
18268    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
18269    expression.  */
18270
18271 /* Note that this predicate is not appropriate for general expressions;
18272    only constant expressions (that satisfy potential_constant_expression)
18273    can be tested for value dependence.
18274
18275    We should really also have a predicate for "instantiation-dependent".
18276
18277    fold_non_dependent_expr: fold if constant and not type-dependent and not value-dependent.
18278      (what about instantiation-dependent constant-expressions?)
18279    is_late_template_attribute: defer if instantiation-dependent.
18280    compute_array_index_type: proceed if constant and not t- or v-dependent
18281      if instantiation-dependent, need to remember full expression
18282    uses_template_parms: FIXME - need to audit callers
18283    tsubst_decl [function_decl]: Why is this using value_dependent_expression_p?
18284    dependent_type_p [array_type]: dependent if index type is dependent
18285      (or non-constant?)
18286    static_assert - instantiation-dependent */
18287
18288 bool
18289 value_dependent_expression_p (tree expression)
18290 {
18291   if (!processing_template_decl)
18292     return false;
18293
18294   /* A name declared with a dependent type.  */
18295   if (DECL_P (expression) && type_dependent_expression_p (expression))
18296     return true;
18297
18298   switch (TREE_CODE (expression))
18299     {
18300     case IDENTIFIER_NODE:
18301       /* A name that has not been looked up -- must be dependent.  */
18302       return true;
18303
18304     case TEMPLATE_PARM_INDEX:
18305       /* A non-type template parm.  */
18306       return true;
18307
18308     case CONST_DECL:
18309       /* A non-type template parm.  */
18310       if (DECL_TEMPLATE_PARM_P (expression))
18311         return true;
18312       return value_dependent_expression_p (DECL_INITIAL (expression));
18313
18314     case VAR_DECL:
18315        /* A constant with literal type and is initialized
18316           with an expression that is value-dependent.  */
18317       if (DECL_INITIAL (expression)
18318           && decl_constant_var_p (expression)
18319           && value_dependent_expression_p (DECL_INITIAL (expression)))
18320         return true;
18321       return false;
18322
18323     case DYNAMIC_CAST_EXPR:
18324     case STATIC_CAST_EXPR:
18325     case CONST_CAST_EXPR:
18326     case REINTERPRET_CAST_EXPR:
18327     case CAST_EXPR:
18328       /* These expressions are value-dependent if the type to which
18329          the cast occurs is dependent or the expression being casted
18330          is value-dependent.  */
18331       {
18332         tree type = TREE_TYPE (expression);
18333
18334         if (dependent_type_p (type))
18335           return true;
18336
18337         /* A functional cast has a list of operands.  */
18338         expression = TREE_OPERAND (expression, 0);
18339         if (!expression)
18340           {
18341             /* If there are no operands, it must be an expression such
18342                as "int()". This should not happen for aggregate types
18343                because it would form non-constant expressions.  */
18344             gcc_assert (cxx_dialect >= cxx0x
18345                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
18346
18347             return false;
18348           }
18349
18350         if (TREE_CODE (expression) == TREE_LIST)
18351           return any_value_dependent_elements_p (expression);
18352
18353         return value_dependent_expression_p (expression);
18354       }
18355
18356     case SIZEOF_EXPR:
18357     case ALIGNOF_EXPR:
18358     case TYPEID_EXPR:
18359       /* A `sizeof' expression is value-dependent if the operand is
18360          type-dependent or is a pack expansion.  */
18361       expression = TREE_OPERAND (expression, 0);
18362       if (PACK_EXPANSION_P (expression))
18363         return true;
18364       else if (TYPE_P (expression))
18365         return dependent_type_p (expression);
18366       return type_dependent_expression_p (expression);
18367
18368     case AT_ENCODE_EXPR:
18369       /* An 'encode' expression is value-dependent if the operand is
18370          type-dependent.  */
18371       expression = TREE_OPERAND (expression, 0);
18372       return dependent_type_p (expression);
18373
18374     case NOEXCEPT_EXPR:
18375       expression = TREE_OPERAND (expression, 0);
18376       return type_dependent_expression_p (expression);
18377
18378     case SCOPE_REF:
18379       {
18380         tree name = TREE_OPERAND (expression, 1);
18381         return value_dependent_expression_p (name);
18382       }
18383
18384     case COMPONENT_REF:
18385       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
18386               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
18387
18388     case NONTYPE_ARGUMENT_PACK:
18389       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
18390          is value-dependent.  */
18391       {
18392         tree values = ARGUMENT_PACK_ARGS (expression);
18393         int i, len = TREE_VEC_LENGTH (values);
18394         
18395         for (i = 0; i < len; ++i)
18396           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
18397             return true;
18398         
18399         return false;
18400       }
18401
18402     case TRAIT_EXPR:
18403       {
18404         tree type2 = TRAIT_EXPR_TYPE2 (expression);
18405         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
18406                 || (type2 ? dependent_type_p (type2) : false));
18407       }
18408
18409     case MODOP_EXPR:
18410       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
18411               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
18412
18413     case ARRAY_REF:
18414       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
18415               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
18416
18417     case ADDR_EXPR:
18418       {
18419         tree op = TREE_OPERAND (expression, 0);
18420         return (value_dependent_expression_p (op)
18421                 || has_value_dependent_address (op));
18422       }
18423
18424     case CALL_EXPR:
18425       {
18426         tree fn = get_callee_fndecl (expression);
18427         int i, nargs;
18428         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
18429           return true;
18430         nargs = call_expr_nargs (expression);
18431         for (i = 0; i < nargs; ++i)
18432           {
18433             tree op = CALL_EXPR_ARG (expression, i);
18434             /* In a call to a constexpr member function, look through the
18435                implicit ADDR_EXPR on the object argument so that it doesn't
18436                cause the call to be considered value-dependent.  We also
18437                look through it in potential_constant_expression.  */
18438             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
18439                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
18440                 && TREE_CODE (op) == ADDR_EXPR)
18441               op = TREE_OPERAND (op, 0);
18442             if (value_dependent_expression_p (op))
18443               return true;
18444           }
18445         return false;
18446       }
18447
18448     case TEMPLATE_ID_EXPR:
18449       /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
18450          type-dependent.  */
18451       return type_dependent_expression_p (expression);
18452
18453     case CONSTRUCTOR:
18454       {
18455         unsigned ix;
18456         tree val;
18457         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
18458           if (value_dependent_expression_p (val))
18459             return true;
18460         return false;
18461       }
18462
18463     default:
18464       /* A constant expression is value-dependent if any subexpression is
18465          value-dependent.  */
18466       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
18467         {
18468         case tcc_reference:
18469         case tcc_unary:
18470         case tcc_comparison:
18471         case tcc_binary:
18472         case tcc_expression:
18473         case tcc_vl_exp:
18474           {
18475             int i, len = cp_tree_operand_length (expression);
18476
18477             for (i = 0; i < len; i++)
18478               {
18479                 tree t = TREE_OPERAND (expression, i);
18480
18481                 /* In some cases, some of the operands may be missing.l
18482                    (For example, in the case of PREDECREMENT_EXPR, the
18483                    amount to increment by may be missing.)  That doesn't
18484                    make the expression dependent.  */
18485                 if (t && value_dependent_expression_p (t))
18486                   return true;
18487               }
18488           }
18489           break;
18490         default:
18491           break;
18492         }
18493       break;
18494     }
18495
18496   /* The expression is not value-dependent.  */
18497   return false;
18498 }
18499
18500 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
18501    [temp.dep.expr].  Note that an expression with no type is
18502    considered dependent.  Other parts of the compiler arrange for an
18503    expression with type-dependent subexpressions to have no type, so
18504    this function doesn't have to be fully recursive.  */
18505
18506 bool
18507 type_dependent_expression_p (tree expression)
18508 {
18509   if (!processing_template_decl)
18510     return false;
18511
18512   if (expression == error_mark_node)
18513     return false;
18514
18515   /* An unresolved name is always dependent.  */
18516   if (TREE_CODE (expression) == IDENTIFIER_NODE
18517       || TREE_CODE (expression) == USING_DECL)
18518     return true;
18519
18520   /* Some expression forms are never type-dependent.  */
18521   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
18522       || TREE_CODE (expression) == SIZEOF_EXPR
18523       || TREE_CODE (expression) == ALIGNOF_EXPR
18524       || TREE_CODE (expression) == AT_ENCODE_EXPR
18525       || TREE_CODE (expression) == NOEXCEPT_EXPR
18526       || TREE_CODE (expression) == TRAIT_EXPR
18527       || TREE_CODE (expression) == TYPEID_EXPR
18528       || TREE_CODE (expression) == DELETE_EXPR
18529       || TREE_CODE (expression) == VEC_DELETE_EXPR
18530       || TREE_CODE (expression) == THROW_EXPR)
18531     return false;
18532
18533   /* The types of these expressions depends only on the type to which
18534      the cast occurs.  */
18535   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
18536       || TREE_CODE (expression) == STATIC_CAST_EXPR
18537       || TREE_CODE (expression) == CONST_CAST_EXPR
18538       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
18539       || TREE_CODE (expression) == CAST_EXPR)
18540     return dependent_type_p (TREE_TYPE (expression));
18541
18542   /* The types of these expressions depends only on the type created
18543      by the expression.  */
18544   if (TREE_CODE (expression) == NEW_EXPR
18545       || TREE_CODE (expression) == VEC_NEW_EXPR)
18546     {
18547       /* For NEW_EXPR tree nodes created inside a template, either
18548          the object type itself or a TREE_LIST may appear as the
18549          operand 1.  */
18550       tree type = TREE_OPERAND (expression, 1);
18551       if (TREE_CODE (type) == TREE_LIST)
18552         /* This is an array type.  We need to check array dimensions
18553            as well.  */
18554         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
18555                || value_dependent_expression_p
18556                     (TREE_OPERAND (TREE_VALUE (type), 1));
18557       else
18558         return dependent_type_p (type);
18559     }
18560
18561   if (TREE_CODE (expression) == SCOPE_REF)
18562     {
18563       tree scope = TREE_OPERAND (expression, 0);
18564       tree name = TREE_OPERAND (expression, 1);
18565
18566       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
18567          contains an identifier associated by name lookup with one or more
18568          declarations declared with a dependent type, or...a
18569          nested-name-specifier or qualified-id that names a member of an
18570          unknown specialization.  */
18571       return (type_dependent_expression_p (name)
18572               || dependent_scope_p (scope));
18573     }
18574
18575   if (TREE_CODE (expression) == FUNCTION_DECL
18576       && DECL_LANG_SPECIFIC (expression)
18577       && DECL_TEMPLATE_INFO (expression)
18578       && (any_dependent_template_arguments_p
18579           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
18580     return true;
18581
18582   if (TREE_CODE (expression) == TEMPLATE_DECL
18583       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
18584     return false;
18585
18586   if (TREE_CODE (expression) == STMT_EXPR)
18587     expression = stmt_expr_value_expr (expression);
18588
18589   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
18590     {
18591       tree elt;
18592       unsigned i;
18593
18594       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
18595         {
18596           if (type_dependent_expression_p (elt))
18597             return true;
18598         }
18599       return false;
18600     }
18601
18602   /* A static data member of the current instantiation with incomplete
18603      array type is type-dependent, as the definition and specializations
18604      can have different bounds.  */
18605   if (TREE_CODE (expression) == VAR_DECL
18606       && DECL_CLASS_SCOPE_P (expression)
18607       && dependent_type_p (DECL_CONTEXT (expression))
18608       && VAR_HAD_UNKNOWN_BOUND (expression))
18609     return true;
18610
18611   if (TREE_TYPE (expression) == unknown_type_node)
18612     {
18613       if (TREE_CODE (expression) == ADDR_EXPR)
18614         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
18615       if (TREE_CODE (expression) == COMPONENT_REF
18616           || TREE_CODE (expression) == OFFSET_REF)
18617         {
18618           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
18619             return true;
18620           expression = TREE_OPERAND (expression, 1);
18621           if (TREE_CODE (expression) == IDENTIFIER_NODE)
18622             return false;
18623         }
18624       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
18625       if (TREE_CODE (expression) == SCOPE_REF)
18626         return false;
18627
18628       if (TREE_CODE (expression) == BASELINK)
18629         expression = BASELINK_FUNCTIONS (expression);
18630
18631       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
18632         {
18633           if (any_dependent_template_arguments_p
18634               (TREE_OPERAND (expression, 1)))
18635             return true;
18636           expression = TREE_OPERAND (expression, 0);
18637         }
18638       gcc_assert (TREE_CODE (expression) == OVERLOAD
18639                   || TREE_CODE (expression) == FUNCTION_DECL);
18640
18641       while (expression)
18642         {
18643           if (type_dependent_expression_p (OVL_CURRENT (expression)))
18644             return true;
18645           expression = OVL_NEXT (expression);
18646         }
18647       return false;
18648     }
18649
18650   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
18651
18652   return (dependent_type_p (TREE_TYPE (expression)));
18653 }
18654
18655 /* Like type_dependent_expression_p, but it also works while not processing
18656    a template definition, i.e. during substitution or mangling.  */
18657
18658 bool
18659 type_dependent_expression_p_push (tree expr)
18660 {
18661   bool b;
18662   ++processing_template_decl;
18663   b = type_dependent_expression_p (expr);
18664   --processing_template_decl;
18665   return b;
18666 }
18667
18668 /* Returns TRUE if ARGS contains a type-dependent expression.  */
18669
18670 bool
18671 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
18672 {
18673   unsigned int i;
18674   tree arg;
18675
18676   FOR_EACH_VEC_ELT (tree, args, i, arg)
18677     {
18678       if (type_dependent_expression_p (arg))
18679         return true;
18680     }
18681   return false;
18682 }
18683
18684 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
18685    expressions) contains any type-dependent expressions.  */
18686
18687 bool
18688 any_type_dependent_elements_p (const_tree list)
18689 {
18690   for (; list; list = TREE_CHAIN (list))
18691     if (value_dependent_expression_p (TREE_VALUE (list)))
18692       return true;
18693
18694   return false;
18695 }
18696
18697 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
18698    expressions) contains any value-dependent expressions.  */
18699
18700 bool
18701 any_value_dependent_elements_p (const_tree list)
18702 {
18703   for (; list; list = TREE_CHAIN (list))
18704     if (value_dependent_expression_p (TREE_VALUE (list)))
18705       return true;
18706
18707   return false;
18708 }
18709
18710 /* Returns TRUE if the ARG (a template argument) is dependent.  */
18711
18712 bool
18713 dependent_template_arg_p (tree arg)
18714 {
18715   if (!processing_template_decl)
18716     return false;
18717
18718   /* Assume a template argument that was wrongly written by the user
18719      is dependent. This is consistent with what
18720      any_dependent_template_arguments_p [that calls this function]
18721      does.  */
18722   if (arg == error_mark_node)
18723     return true;
18724
18725   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
18726     arg = ARGUMENT_PACK_SELECT_ARG (arg);
18727
18728   if (TREE_CODE (arg) == TEMPLATE_DECL
18729       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
18730     return dependent_template_p (arg);
18731   else if (ARGUMENT_PACK_P (arg))
18732     {
18733       tree args = ARGUMENT_PACK_ARGS (arg);
18734       int i, len = TREE_VEC_LENGTH (args);
18735       for (i = 0; i < len; ++i)
18736         {
18737           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
18738             return true;
18739         }
18740
18741       return false;
18742     }
18743   else if (TYPE_P (arg))
18744     return dependent_type_p (arg);
18745   else
18746     return (type_dependent_expression_p (arg)
18747             || value_dependent_expression_p (arg));
18748 }
18749
18750 /* Returns true if ARGS (a collection of template arguments) contains
18751    any types that require structural equality testing.  */
18752
18753 bool
18754 any_template_arguments_need_structural_equality_p (tree args)
18755 {
18756   int i;
18757   int j;
18758
18759   if (!args)
18760     return false;
18761   if (args == error_mark_node)
18762     return true;
18763
18764   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
18765     {
18766       tree level = TMPL_ARGS_LEVEL (args, i + 1);
18767       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
18768         {
18769           tree arg = TREE_VEC_ELT (level, j);
18770           tree packed_args = NULL_TREE;
18771           int k, len = 1;
18772
18773           if (ARGUMENT_PACK_P (arg))
18774             {
18775               /* Look inside the argument pack.  */
18776               packed_args = ARGUMENT_PACK_ARGS (arg);
18777               len = TREE_VEC_LENGTH (packed_args);
18778             }
18779
18780           for (k = 0; k < len; ++k)
18781             {
18782               if (packed_args)
18783                 arg = TREE_VEC_ELT (packed_args, k);
18784
18785               if (error_operand_p (arg))
18786                 return true;
18787               else if (TREE_CODE (arg) == TEMPLATE_DECL
18788                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
18789                 continue;
18790               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
18791                 return true;
18792               else if (!TYPE_P (arg) && TREE_TYPE (arg)
18793                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
18794                 return true;
18795             }
18796         }
18797     }
18798
18799   return false;
18800 }
18801
18802 /* Returns true if ARGS (a collection of template arguments) contains
18803    any dependent arguments.  */
18804
18805 bool
18806 any_dependent_template_arguments_p (const_tree args)
18807 {
18808   int i;
18809   int j;
18810
18811   if (!args)
18812     return false;
18813   if (args == error_mark_node)
18814     return true;
18815
18816   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
18817     {
18818       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
18819       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
18820         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
18821           return true;
18822     }
18823
18824   return false;
18825 }
18826
18827 /* Returns TRUE if the template TMPL is dependent.  */
18828
18829 bool
18830 dependent_template_p (tree tmpl)
18831 {
18832   if (TREE_CODE (tmpl) == OVERLOAD)
18833     {
18834       while (tmpl)
18835         {
18836           if (dependent_template_p (OVL_CURRENT (tmpl)))
18837             return true;
18838           tmpl = OVL_NEXT (tmpl);
18839         }
18840       return false;
18841     }
18842
18843   /* Template template parameters are dependent.  */
18844   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
18845       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
18846     return true;
18847   /* So are names that have not been looked up.  */
18848   if (TREE_CODE (tmpl) == SCOPE_REF
18849       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
18850     return true;
18851   /* So are member templates of dependent classes.  */
18852   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
18853     return dependent_type_p (DECL_CONTEXT (tmpl));
18854   return false;
18855 }
18856
18857 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
18858
18859 bool
18860 dependent_template_id_p (tree tmpl, tree args)
18861 {
18862   return (dependent_template_p (tmpl)
18863           || any_dependent_template_arguments_p (args));
18864 }
18865
18866 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
18867    is dependent.  */
18868
18869 bool
18870 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
18871 {
18872   int i;
18873
18874   if (!processing_template_decl)
18875     return false;
18876
18877   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
18878     {
18879       tree decl = TREE_VEC_ELT (declv, i);
18880       tree init = TREE_VEC_ELT (initv, i);
18881       tree cond = TREE_VEC_ELT (condv, i);
18882       tree incr = TREE_VEC_ELT (incrv, i);
18883
18884       if (type_dependent_expression_p (decl))
18885         return true;
18886
18887       if (init && type_dependent_expression_p (init))
18888         return true;
18889
18890       if (type_dependent_expression_p (cond))
18891         return true;
18892
18893       if (COMPARISON_CLASS_P (cond)
18894           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
18895               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
18896         return true;
18897
18898       if (TREE_CODE (incr) == MODOP_EXPR)
18899         {
18900           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
18901               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
18902             return true;
18903         }
18904       else if (type_dependent_expression_p (incr))
18905         return true;
18906       else if (TREE_CODE (incr) == MODIFY_EXPR)
18907         {
18908           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
18909             return true;
18910           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
18911             {
18912               tree t = TREE_OPERAND (incr, 1);
18913               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
18914                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
18915                 return true;
18916             }
18917         }
18918     }
18919
18920   return false;
18921 }
18922
18923 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
18924    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
18925    no such TYPE can be found.  Note that this function peers inside
18926    uninstantiated templates and therefore should be used only in
18927    extremely limited situations.  ONLY_CURRENT_P restricts this
18928    peering to the currently open classes hierarchy (which is required
18929    when comparing types).  */
18930
18931 tree
18932 resolve_typename_type (tree type, bool only_current_p)
18933 {
18934   tree scope;
18935   tree name;
18936   tree decl;
18937   int quals;
18938   tree pushed_scope;
18939   tree result;
18940
18941   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
18942
18943   scope = TYPE_CONTEXT (type);
18944   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
18945      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
18946      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
18947      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
18948      identifier  of the TYPENAME_TYPE anymore.
18949      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
18950      TYPENAME_TYPE instead, we avoid messing up with a possible
18951      typedef variant case.  */
18952   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
18953
18954   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
18955      it first before we can figure out what NAME refers to.  */
18956   if (TREE_CODE (scope) == TYPENAME_TYPE)
18957     scope = resolve_typename_type (scope, only_current_p);
18958   /* If we don't know what SCOPE refers to, then we cannot resolve the
18959      TYPENAME_TYPE.  */
18960   if (TREE_CODE (scope) == TYPENAME_TYPE)
18961     return type;
18962   /* If the SCOPE is a template type parameter, we have no way of
18963      resolving the name.  */
18964   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
18965     return type;
18966   /* If the SCOPE is not the current instantiation, there's no reason
18967      to look inside it.  */
18968   if (only_current_p && !currently_open_class (scope))
18969     return type;
18970   /* If this is a typedef, we don't want to look inside (c++/11987).  */
18971   if (typedef_variant_p (type))
18972     return type;
18973   /* If SCOPE isn't the template itself, it will not have a valid
18974      TYPE_FIELDS list.  */
18975   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
18976     /* scope is either the template itself or a compatible instantiation
18977        like X<T>, so look up the name in the original template.  */
18978     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
18979   else
18980     /* scope is a partial instantiation, so we can't do the lookup or we
18981        will lose the template arguments.  */
18982     return type;
18983   /* Enter the SCOPE so that name lookup will be resolved as if we
18984      were in the class definition.  In particular, SCOPE will no
18985      longer be considered a dependent type.  */
18986   pushed_scope = push_scope (scope);
18987   /* Look up the declaration.  */
18988   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
18989
18990   result = NULL_TREE;
18991   
18992   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
18993      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
18994   if (!decl)
18995     /*nop*/;
18996   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
18997            && TREE_CODE (decl) == TYPE_DECL)
18998     {
18999       result = TREE_TYPE (decl);
19000       if (result == error_mark_node)
19001         result = NULL_TREE;
19002     }
19003   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
19004            && DECL_CLASS_TEMPLATE_P (decl))
19005     {
19006       tree tmpl;
19007       tree args;
19008       /* Obtain the template and the arguments.  */
19009       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
19010       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
19011       /* Instantiate the template.  */
19012       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
19013                                       /*entering_scope=*/0,
19014                                       tf_error | tf_user);
19015       if (result == error_mark_node)
19016         result = NULL_TREE;
19017     }
19018   
19019   /* Leave the SCOPE.  */
19020   if (pushed_scope)
19021     pop_scope (pushed_scope);
19022
19023   /* If we failed to resolve it, return the original typename.  */
19024   if (!result)
19025     return type;
19026   
19027   /* If lookup found a typename type, resolve that too.  */
19028   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
19029     {
19030       /* Ill-formed programs can cause infinite recursion here, so we
19031          must catch that.  */
19032       TYPENAME_IS_RESOLVING_P (type) = 1;
19033       result = resolve_typename_type (result, only_current_p);
19034       TYPENAME_IS_RESOLVING_P (type) = 0;
19035     }
19036   
19037   /* Qualify the resulting type.  */
19038   quals = cp_type_quals (type);
19039   if (quals)
19040     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
19041
19042   return result;
19043 }
19044
19045 /* EXPR is an expression which is not type-dependent.  Return a proxy
19046    for EXPR that can be used to compute the types of larger
19047    expressions containing EXPR.  */
19048
19049 tree
19050 build_non_dependent_expr (tree expr)
19051 {
19052   tree inner_expr;
19053
19054 #ifdef ENABLE_CHECKING
19055   /* Try to get a constant value for all non-type-dependent expressions in
19056       order to expose bugs in *_dependent_expression_p and constexpr.  */
19057   if (cxx_dialect >= cxx0x)
19058     maybe_constant_value (fold_non_dependent_expr (expr));
19059 #endif
19060
19061   /* Preserve OVERLOADs; the functions must be available to resolve
19062      types.  */
19063   inner_expr = expr;
19064   if (TREE_CODE (inner_expr) == STMT_EXPR)
19065     inner_expr = stmt_expr_value_expr (inner_expr);
19066   if (TREE_CODE (inner_expr) == ADDR_EXPR)
19067     inner_expr = TREE_OPERAND (inner_expr, 0);
19068   if (TREE_CODE (inner_expr) == COMPONENT_REF)
19069     inner_expr = TREE_OPERAND (inner_expr, 1);
19070   if (is_overloaded_fn (inner_expr)
19071       || TREE_CODE (inner_expr) == OFFSET_REF)
19072     return expr;
19073   /* There is no need to return a proxy for a variable.  */
19074   if (TREE_CODE (expr) == VAR_DECL)
19075     return expr;
19076   /* Preserve string constants; conversions from string constants to
19077      "char *" are allowed, even though normally a "const char *"
19078      cannot be used to initialize a "char *".  */
19079   if (TREE_CODE (expr) == STRING_CST)
19080     return expr;
19081   /* Preserve arithmetic constants, as an optimization -- there is no
19082      reason to create a new node.  */
19083   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
19084     return expr;
19085   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
19086      There is at least one place where we want to know that a
19087      particular expression is a throw-expression: when checking a ?:
19088      expression, there are special rules if the second or third
19089      argument is a throw-expression.  */
19090   if (TREE_CODE (expr) == THROW_EXPR)
19091     return expr;
19092
19093   if (TREE_CODE (expr) == COND_EXPR)
19094     return build3 (COND_EXPR,
19095                    TREE_TYPE (expr),
19096                    TREE_OPERAND (expr, 0),
19097                    (TREE_OPERAND (expr, 1)
19098                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
19099                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
19100                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
19101   if (TREE_CODE (expr) == COMPOUND_EXPR
19102       && !COMPOUND_EXPR_OVERLOADED (expr))
19103     return build2 (COMPOUND_EXPR,
19104                    TREE_TYPE (expr),
19105                    TREE_OPERAND (expr, 0),
19106                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
19107
19108   /* If the type is unknown, it can't really be non-dependent */
19109   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
19110
19111   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
19112   return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
19113 }
19114
19115 /* ARGS is a vector of expressions as arguments to a function call.
19116    Replace the arguments with equivalent non-dependent expressions.
19117    This modifies ARGS in place.  */
19118
19119 void
19120 make_args_non_dependent (VEC(tree,gc) *args)
19121 {
19122   unsigned int ix;
19123   tree arg;
19124
19125   FOR_EACH_VEC_ELT (tree, args, ix, arg)
19126     {
19127       tree newarg = build_non_dependent_expr (arg);
19128       if (newarg != arg)
19129         VEC_replace (tree, args, ix, newarg);
19130     }
19131 }
19132
19133 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
19134    with a level one deeper than the actual template parms.  */
19135
19136 tree
19137 make_auto (void)
19138 {
19139   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
19140   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
19141                                TYPE_DECL, get_identifier ("auto"), au);
19142   TYPE_STUB_DECL (au) = TYPE_NAME (au);
19143   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
19144     (0, processing_template_decl + 1, processing_template_decl + 1,
19145      0, TYPE_NAME (au), NULL_TREE);
19146   TYPE_CANONICAL (au) = canonical_type_parameter (au);
19147   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
19148   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
19149
19150   return au;
19151 }
19152
19153 /* Given type ARG, return std::initializer_list<ARG>.  */
19154
19155 static tree
19156 listify (tree arg)
19157 {
19158   tree std_init_list = namespace_binding
19159     (get_identifier ("initializer_list"), std_node);
19160   tree argvec;
19161   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
19162     {    
19163       error ("deducing from brace-enclosed initializer list requires "
19164              "#include <initializer_list>");
19165       return error_mark_node;
19166     }
19167   argvec = make_tree_vec (1);
19168   TREE_VEC_ELT (argvec, 0) = arg;
19169   return lookup_template_class (std_init_list, argvec, NULL_TREE,
19170                                 NULL_TREE, 0, tf_warning_or_error);
19171 }
19172
19173 /* Replace auto in TYPE with std::initializer_list<auto>.  */
19174
19175 static tree
19176 listify_autos (tree type, tree auto_node)
19177 {
19178   tree init_auto = listify (auto_node);
19179   tree argvec = make_tree_vec (1);
19180   TREE_VEC_ELT (argvec, 0) = init_auto;
19181   if (processing_template_decl)
19182     argvec = add_to_template_args (current_template_args (), argvec);
19183   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19184 }
19185
19186 /* walk_tree helper for do_auto_deduction.  */
19187
19188 static tree
19189 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
19190                  void *type)
19191 {
19192   /* Is this a variable with the type we're looking for?  */
19193   if (DECL_P (*tp)
19194       && TREE_TYPE (*tp) == type)
19195     return *tp;
19196   else
19197     return NULL_TREE;
19198 }
19199
19200 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
19201    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
19202
19203 tree
19204 do_auto_deduction (tree type, tree init, tree auto_node)
19205 {
19206   tree parms, tparms, targs;
19207   tree args[1];
19208   tree decl;
19209   int val;
19210
19211   /* The name of the object being declared shall not appear in the
19212      initializer expression.  */
19213   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
19214   if (decl)
19215     {
19216       error ("variable %q#D with %<auto%> type used in its own "
19217              "initializer", decl);
19218       return error_mark_node;
19219     }
19220
19221   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
19222      with either a new invented type template parameter U or, if the
19223      initializer is a braced-init-list (8.5.4), with
19224      std::initializer_list<U>.  */
19225   if (BRACE_ENCLOSED_INITIALIZER_P (init))
19226     type = listify_autos (type, auto_node);
19227
19228   init = resolve_nondeduced_context (init);
19229
19230   parms = build_tree_list (NULL_TREE, type);
19231   args[0] = init;
19232   tparms = make_tree_vec (1);
19233   targs = make_tree_vec (1);
19234   TREE_VEC_ELT (tparms, 0)
19235     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
19236   val = type_unification_real (tparms, targs, parms, args, 1, 0,
19237                                DEDUCE_CALL, LOOKUP_NORMAL);
19238   if (val > 0)
19239     {
19240       if (type && type != error_mark_node)
19241         /* If type is error_mark_node a diagnostic must have been
19242            emitted by now.  Also, having a mention to '<type error>'
19243            in the diagnostic is not really useful to the user.  */
19244         error ("unable to deduce %qT from %qE", type, init);
19245       return error_mark_node;
19246     }
19247
19248   /* If the list of declarators contains more than one declarator, the type
19249      of each declared variable is determined as described above. If the
19250      type deduced for the template parameter U is not the same in each
19251      deduction, the program is ill-formed.  */
19252   if (TREE_TYPE (auto_node)
19253       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
19254     {
19255       error ("inconsistent deduction for %qT: %qT and then %qT",
19256              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
19257       return error_mark_node;
19258     }
19259   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
19260
19261   if (processing_template_decl)
19262     targs = add_to_template_args (current_template_args (), targs);
19263   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
19264 }
19265
19266 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
19267    result.  */
19268
19269 tree
19270 splice_late_return_type (tree type, tree late_return_type)
19271 {
19272   tree argvec;
19273
19274   if (late_return_type == NULL_TREE)
19275     return type;
19276   argvec = make_tree_vec (1);
19277   TREE_VEC_ELT (argvec, 0) = late_return_type;
19278   if (processing_template_parmlist)
19279     /* For a late-specified return type in a template type-parameter, we
19280        need to add a dummy argument level for its parmlist.  */
19281     argvec = add_to_template_args
19282       (make_tree_vec (processing_template_parmlist), argvec);
19283   if (current_template_parms)
19284     argvec = add_to_template_args (current_template_args (), argvec);
19285   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19286 }
19287
19288 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
19289
19290 bool
19291 is_auto (const_tree type)
19292 {
19293   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
19294       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
19295     return true;
19296   else
19297     return false;
19298 }
19299
19300 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
19301    appear as a type-specifier for the declaration in question, we don't
19302    have to look through the whole type.  */
19303
19304 tree
19305 type_uses_auto (tree type)
19306 {
19307   enum tree_code code;
19308   if (is_auto (type))
19309     return type;
19310
19311   code = TREE_CODE (type);
19312
19313   if (code == POINTER_TYPE || code == REFERENCE_TYPE
19314       || code == OFFSET_TYPE || code == FUNCTION_TYPE
19315       || code == METHOD_TYPE || code == ARRAY_TYPE)
19316     return type_uses_auto (TREE_TYPE (type));
19317
19318   if (TYPE_PTRMEMFUNC_P (type))
19319     return type_uses_auto (TREE_TYPE (TREE_TYPE
19320                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
19321
19322   return NULL_TREE;
19323 }
19324
19325 /* For a given template T, return the vector of typedefs referenced
19326    in T for which access check is needed at T instantiation time.
19327    T is either  a FUNCTION_DECL or a RECORD_TYPE.
19328    Those typedefs were added to T by the function
19329    append_type_to_template_for_access_check.  */
19330
19331 VEC(qualified_typedef_usage_t,gc)*
19332 get_types_needing_access_check (tree t)
19333 {
19334   tree ti;
19335   VEC(qualified_typedef_usage_t,gc) *result = NULL;
19336
19337   if (!t || t == error_mark_node)
19338     return NULL;
19339
19340   if (!(ti = get_template_info (t)))
19341     return NULL;
19342
19343   if (CLASS_TYPE_P (t)
19344       || TREE_CODE (t) == FUNCTION_DECL)
19345     {
19346       if (!TI_TEMPLATE (ti))
19347         return NULL;
19348
19349       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
19350     }
19351
19352   return result;
19353 }
19354
19355 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
19356    tied to T. That list of typedefs will be access checked at
19357    T instantiation time.
19358    T is either a FUNCTION_DECL or a RECORD_TYPE.
19359    TYPE_DECL is a TYPE_DECL node representing a typedef.
19360    SCOPE is the scope through which TYPE_DECL is accessed.
19361    LOCATION is the location of the usage point of TYPE_DECL.
19362
19363    This function is a subroutine of
19364    append_type_to_template_for_access_check.  */
19365
19366 static void
19367 append_type_to_template_for_access_check_1 (tree t,
19368                                             tree type_decl,
19369                                             tree scope,
19370                                             location_t location)
19371 {
19372   qualified_typedef_usage_t typedef_usage;
19373   tree ti;
19374
19375   if (!t || t == error_mark_node)
19376     return;
19377
19378   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
19379                || CLASS_TYPE_P (t))
19380               && type_decl
19381               && TREE_CODE (type_decl) == TYPE_DECL
19382               && scope);
19383
19384   if (!(ti = get_template_info (t)))
19385     return;
19386
19387   gcc_assert (TI_TEMPLATE (ti));
19388
19389   typedef_usage.typedef_decl = type_decl;
19390   typedef_usage.context = scope;
19391   typedef_usage.locus = location;
19392
19393   VEC_safe_push (qualified_typedef_usage_t, gc,
19394                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
19395                  &typedef_usage);
19396 }
19397
19398 /* Append TYPE_DECL to the template TEMPL.
19399    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
19400    At TEMPL instanciation time, TYPE_DECL will be checked to see
19401    if it can be accessed through SCOPE.
19402    LOCATION is the location of the usage point of TYPE_DECL.
19403
19404    e.g. consider the following code snippet:
19405
19406      class C
19407      {
19408        typedef int myint;
19409      };
19410
19411      template<class U> struct S
19412      {
19413        C::myint mi; // <-- usage point of the typedef C::myint
19414      };
19415
19416      S<char> s;
19417
19418    At S<char> instantiation time, we need to check the access of C::myint
19419    In other words, we need to check the access of the myint typedef through
19420    the C scope. For that purpose, this function will add the myint typedef
19421    and the scope C through which its being accessed to a list of typedefs
19422    tied to the template S. That list will be walked at template instantiation
19423    time and access check performed on each typedefs it contains.
19424    Note that this particular code snippet should yield an error because
19425    myint is private to C.  */
19426
19427 void
19428 append_type_to_template_for_access_check (tree templ,
19429                                           tree type_decl,
19430                                           tree scope,
19431                                           location_t location)
19432 {
19433   qualified_typedef_usage_t *iter;
19434   int i;
19435
19436   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
19437
19438   /* Make sure we don't append the type to the template twice.  */
19439   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
19440                     get_types_needing_access_check (templ),
19441                     i, iter)
19442     if (iter->typedef_decl == type_decl && scope == iter->context)
19443       return;
19444
19445   append_type_to_template_for_access_check_1 (templ, type_decl,
19446                                               scope, location);
19447 }
19448
19449 /* Set up the hash tables for template instantiations.  */
19450
19451 void
19452 init_template_processing (void)
19453 {
19454   decl_specializations = htab_create_ggc (37,
19455                                           hash_specialization,
19456                                           eq_specializations,
19457                                           ggc_free);
19458   type_specializations = htab_create_ggc (37,
19459                                           hash_specialization,
19460                                           eq_specializations,
19461                                           ggc_free);
19462 }
19463
19464 /* Print stats about the template hash tables for -fstats.  */
19465
19466 void
19467 print_template_statistics (void)
19468 {
19469   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
19470            "%f collisions\n", (long) htab_size (decl_specializations),
19471            (long) htab_elements (decl_specializations),
19472            htab_collisions (decl_specializations));
19473   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
19474            "%f collisions\n", (long) htab_size (type_specializations),
19475            (long) htab_elements (type_specializations),
19476            htab_collisions (type_specializations));
19477 }
19478
19479 #include "gt-cp-pt.h"