OSDN Git Service

* cp-tree.h (TYPE_HAS_ASSIGN_REF): Rename to TYPE_HAS_COPY_ASSIGN.
[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
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 "cp-objcp-common.h"
40 #include "tree-inline.h"
41 #include "decl.h"
42 #include "output.h"
43 #include "toplev.h"
44 #include "timevar.h"
45 #include "tree-iterator.h"
46 #include "vecprim.h"
47
48 /* The type of functions taking a tree, and some additional data, and
49    returning an int.  */
50 typedef int (*tree_fn_t) (tree, void*);
51
52 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
53    instantiations have been deferred, either because their definitions
54    were not yet available, or because we were putting off doing the work.  */
55 struct GTY (()) pending_template {
56   struct pending_template *next;
57   struct tinst_level *tinst;
58 };
59
60 static GTY(()) struct pending_template *pending_templates;
61 static GTY(()) struct pending_template *last_pending_template;
62
63 int processing_template_parmlist;
64 static int template_header_count;
65
66 static GTY(()) tree saved_trees;
67 static VEC(int,heap) *inline_parm_levels;
68
69 static GTY(()) struct tinst_level *current_tinst_level;
70
71 static GTY(()) tree saved_access_scope;
72
73 /* Live only within one (recursive) call to tsubst_expr.  We use
74    this to pass the statement expression node from the STMT_EXPR
75    to the EXPR_STMT that is its result.  */
76 static tree cur_stmt_expr;
77
78 /* A map from local variable declarations in the body of the template
79    presently being instantiated to the corresponding instantiated
80    local variables.  */
81 static htab_t local_specializations;
82
83 typedef struct GTY(()) spec_entry
84 {
85   tree tmpl;
86   tree args;
87   tree spec;
88 } spec_entry;
89
90 static GTY ((param_is (spec_entry)))
91   htab_t decl_specializations;
92
93 static GTY ((param_is (spec_entry)))
94   htab_t type_specializations;
95
96 /* Contains canonical template parameter types. The vector is indexed by
97    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
98    TREE_LIST, whose TREE_VALUEs contain the canonical template
99    parameters of various types and levels.  */
100 static GTY(()) VEC(tree,gc) *canonical_template_parms;
101
102 #define UNIFY_ALLOW_NONE 0
103 #define UNIFY_ALLOW_MORE_CV_QUAL 1
104 #define UNIFY_ALLOW_LESS_CV_QUAL 2
105 #define UNIFY_ALLOW_DERIVED 4
106 #define UNIFY_ALLOW_INTEGER 8
107 #define UNIFY_ALLOW_OUTER_LEVEL 16
108 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
109 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
110
111 static void push_access_scope (tree);
112 static void pop_access_scope (tree);
113 static bool resolve_overloaded_unification (tree, tree, tree, tree,
114                                             unification_kind_t, int);
115 static int try_one_overload (tree, tree, tree, tree, tree,
116                              unification_kind_t, int, bool);
117 static int unify (tree, tree, tree, tree, int);
118 static void add_pending_template (tree);
119 static tree reopen_tinst_level (struct tinst_level *);
120 static tree tsubst_initializer_list (tree, tree);
121 static tree get_class_bindings (tree, tree, tree);
122 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
123                                    bool, bool);
124 static void tsubst_enum (tree, tree, tree);
125 static tree add_to_template_args (tree, tree);
126 static tree add_outermost_template_args (tree, tree);
127 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
128 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
129                                              tree);
130 static int type_unification_real (tree, tree, tree, const tree *,
131                                   unsigned int, int, unification_kind_t, int);
132 static void note_template_header (int);
133 static tree convert_nontype_argument_function (tree, tree);
134 static tree convert_nontype_argument (tree, tree);
135 static tree convert_template_argument (tree, tree, tree,
136                                        tsubst_flags_t, int, tree);
137 static int for_each_template_parm (tree, tree_fn_t, void*,
138                                    struct pointer_set_t*, bool);
139 static tree expand_template_argument_pack (tree);
140 static tree build_template_parm_index (int, int, int, tree, tree);
141 static bool inline_needs_template_parms (tree);
142 static void push_inline_template_parms_recursive (tree, int);
143 static tree retrieve_local_specialization (tree);
144 static void register_local_specialization (tree, tree);
145 static hashval_t hash_specialization (const void *p);
146 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
147 static int mark_template_parm (tree, void *);
148 static int template_parm_this_level_p (tree, void *);
149 static tree tsubst_friend_function (tree, tree);
150 static tree tsubst_friend_class (tree, tree);
151 static int can_complete_type_without_circularity (tree);
152 static tree get_bindings (tree, tree, tree, bool);
153 static int template_decl_level (tree);
154 static int check_cv_quals_for_unify (int, tree, tree);
155 static void template_parm_level_and_index (tree, int*, int*);
156 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
157 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
158 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
159 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
160 static void regenerate_decl_from_template (tree, tree);
161 static tree most_specialized_class (tree, tree);
162 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
163 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
164 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
165 static bool check_specialization_scope (void);
166 static tree process_partial_specialization (tree);
167 static void set_current_access_from_decl (tree);
168 static tree get_template_base (tree, tree, tree, tree);
169 static tree try_class_unification (tree, tree, tree, tree);
170 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
171                                            tree, tree);
172 static bool template_template_parm_bindings_ok_p (tree, tree);
173 static int template_args_equal (tree, tree);
174 static void tsubst_default_arguments (tree);
175 static tree for_each_template_parm_r (tree *, int *, void *);
176 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
177 static void copy_default_args_to_explicit_spec (tree);
178 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
179 static int eq_local_specializations (const void *, const void *);
180 static bool dependent_template_arg_p (tree);
181 static bool any_template_arguments_need_structural_equality_p (tree);
182 static bool dependent_type_p_r (tree);
183 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
184 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
185 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
186 static tree tsubst_decl (tree, tree, tsubst_flags_t);
187 static void perform_typedefs_access_check (tree tmpl, tree targs);
188 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
189                                                         location_t);
190 static hashval_t iterative_hash_template_arg (tree arg, hashval_t val);
191 static tree listify (tree);
192 static tree listify_autos (tree, tree);
193
194 /* Make the current scope suitable for access checking when we are
195    processing T.  T can be FUNCTION_DECL for instantiated function
196    template, or VAR_DECL for static member variable (need by
197    instantiate_decl).  */
198
199 static void
200 push_access_scope (tree t)
201 {
202   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
203               || TREE_CODE (t) == VAR_DECL);
204
205   if (DECL_FRIEND_CONTEXT (t))
206     push_nested_class (DECL_FRIEND_CONTEXT (t));
207   else if (DECL_CLASS_SCOPE_P (t))
208     push_nested_class (DECL_CONTEXT (t));
209   else
210     push_to_top_level ();
211
212   if (TREE_CODE (t) == FUNCTION_DECL)
213     {
214       saved_access_scope = tree_cons
215         (NULL_TREE, current_function_decl, saved_access_scope);
216       current_function_decl = t;
217     }
218 }
219
220 /* Restore the scope set up by push_access_scope.  T is the node we
221    are processing.  */
222
223 static void
224 pop_access_scope (tree t)
225 {
226   if (TREE_CODE (t) == FUNCTION_DECL)
227     {
228       current_function_decl = TREE_VALUE (saved_access_scope);
229       saved_access_scope = TREE_CHAIN (saved_access_scope);
230     }
231
232   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
233     pop_nested_class ();
234   else
235     pop_from_top_level ();
236 }
237
238 /* Do any processing required when DECL (a member template
239    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
240    to DECL, unless it is a specialization, in which case the DECL
241    itself is returned.  */
242
243 tree
244 finish_member_template_decl (tree decl)
245 {
246   if (decl == error_mark_node)
247     return error_mark_node;
248
249   gcc_assert (DECL_P (decl));
250
251   if (TREE_CODE (decl) == TYPE_DECL)
252     {
253       tree type;
254
255       type = TREE_TYPE (decl);
256       if (type == error_mark_node)
257         return error_mark_node;
258       if (MAYBE_CLASS_TYPE_P (type)
259           && CLASSTYPE_TEMPLATE_INFO (type)
260           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
261         {
262           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
263           check_member_template (tmpl);
264           return tmpl;
265         }
266       return NULL_TREE;
267     }
268   else if (TREE_CODE (decl) == FIELD_DECL)
269     error ("data member %qD cannot be a member template", decl);
270   else if (DECL_TEMPLATE_INFO (decl))
271     {
272       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
273         {
274           check_member_template (DECL_TI_TEMPLATE (decl));
275           return DECL_TI_TEMPLATE (decl);
276         }
277       else
278         return decl;
279     }
280   else
281     error ("invalid member template declaration %qD", decl);
282
283   return error_mark_node;
284 }
285
286 /* Create a template info node.  */
287
288 tree
289 build_template_info (tree template_decl, tree template_args)
290 {
291   tree result = make_node (TEMPLATE_INFO);
292   TI_TEMPLATE (result) = template_decl;
293   TI_ARGS (result) = template_args;
294   return result;
295 }
296
297 /* Return the template info node corresponding to T, whatever T is.  */
298
299 tree
300 get_template_info (const_tree t)
301 {
302   tree tinfo = NULL_TREE;
303
304   if (!t || t == error_mark_node)
305     return NULL;
306
307   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
308     tinfo = DECL_TEMPLATE_INFO (t);
309
310   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
311     t = TREE_TYPE (t);
312
313   if (TAGGED_TYPE_P (t))
314     tinfo = TYPE_TEMPLATE_INFO (t);
315   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
316     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
317
318   return tinfo;
319 }
320
321 /* Returns the template nesting level of the indicated class TYPE.
322
323    For example, in:
324      template <class T>
325      struct A
326      {
327        template <class U>
328        struct B {};
329      };
330
331    A<T>::B<U> has depth two, while A<T> has depth one.
332    Both A<T>::B<int> and A<int>::B<U> have depth one, if
333    they are instantiations, not specializations.
334
335    This function is guaranteed to return 0 if passed NULL_TREE so
336    that, for example, `template_class_depth (current_class_type)' is
337    always safe.  */
338
339 int
340 template_class_depth (tree type)
341 {
342   int depth;
343
344   for (depth = 0;
345        type && TREE_CODE (type) != NAMESPACE_DECL;
346        type = (TREE_CODE (type) == FUNCTION_DECL)
347          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
348     {
349       tree tinfo = get_template_info (type);
350
351       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
352           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
353         ++depth;
354     }
355
356   return depth;
357 }
358
359 /* Subroutine of maybe_begin_member_template_processing.
360    Returns true if processing DECL needs us to push template parms.  */
361
362 static bool
363 inline_needs_template_parms (tree decl)
364 {
365   if (! DECL_TEMPLATE_INFO (decl))
366     return false;
367
368   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
369           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
370 }
371
372 /* Subroutine of maybe_begin_member_template_processing.
373    Push the template parms in PARMS, starting from LEVELS steps into the
374    chain, and ending at the beginning, since template parms are listed
375    innermost first.  */
376
377 static void
378 push_inline_template_parms_recursive (tree parmlist, int levels)
379 {
380   tree parms = TREE_VALUE (parmlist);
381   int i;
382
383   if (levels > 1)
384     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
385
386   ++processing_template_decl;
387   current_template_parms
388     = tree_cons (size_int (processing_template_decl),
389                  parms, current_template_parms);
390   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
391
392   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
393                NULL);
394   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
395     {
396       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
397
398       if (parm == error_mark_node)
399         continue;
400
401       gcc_assert (DECL_P (parm));
402
403       switch (TREE_CODE (parm))
404         {
405         case TYPE_DECL:
406         case TEMPLATE_DECL:
407           pushdecl (parm);
408           break;
409
410         case PARM_DECL:
411           {
412             /* Make a CONST_DECL as is done in process_template_parm.
413                It is ugly that we recreate this here; the original
414                version built in process_template_parm is no longer
415                available.  */
416             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
417                                     CONST_DECL, DECL_NAME (parm),
418                                     TREE_TYPE (parm));
419             DECL_ARTIFICIAL (decl) = 1;
420             TREE_CONSTANT (decl) = 1;
421             TREE_READONLY (decl) = 1;
422             DECL_INITIAL (decl) = DECL_INITIAL (parm);
423             SET_DECL_TEMPLATE_PARM_P (decl);
424             pushdecl (decl);
425           }
426           break;
427
428         default:
429           gcc_unreachable ();
430         }
431     }
432 }
433
434 /* Restore the template parameter context for a member template or
435    a friend template defined in a class definition.  */
436
437 void
438 maybe_begin_member_template_processing (tree decl)
439 {
440   tree parms;
441   int levels = 0;
442
443   if (inline_needs_template_parms (decl))
444     {
445       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
446       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
447
448       if (DECL_TEMPLATE_SPECIALIZATION (decl))
449         {
450           --levels;
451           parms = TREE_CHAIN (parms);
452         }
453
454       push_inline_template_parms_recursive (parms, levels);
455     }
456
457   /* Remember how many levels of template parameters we pushed so that
458      we can pop them later.  */
459   VEC_safe_push (int, heap, inline_parm_levels, levels);
460 }
461
462 /* Undo the effects of maybe_begin_member_template_processing.  */
463
464 void
465 maybe_end_member_template_processing (void)
466 {
467   int i;
468   int last;
469
470   if (VEC_length (int, inline_parm_levels) == 0)
471     return;
472
473   last = VEC_pop (int, inline_parm_levels);
474   for (i = 0; i < last; ++i)
475     {
476       --processing_template_decl;
477       current_template_parms = TREE_CHAIN (current_template_parms);
478       poplevel (0, 0, 0);
479     }
480 }
481
482 /* Return a new template argument vector which contains all of ARGS,
483    but has as its innermost set of arguments the EXTRA_ARGS.  */
484
485 static tree
486 add_to_template_args (tree args, tree extra_args)
487 {
488   tree new_args;
489   int extra_depth;
490   int i;
491   int j;
492
493   if (args == NULL_TREE)
494     return extra_args;
495
496   extra_depth = TMPL_ARGS_DEPTH (extra_args);
497   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
498
499   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
500     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
501
502   for (j = 1; j <= extra_depth; ++j, ++i)
503     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
504
505   return new_args;
506 }
507
508 /* Like add_to_template_args, but only the outermost ARGS are added to
509    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
510    (EXTRA_ARGS) levels are added.  This function is used to combine
511    the template arguments from a partial instantiation with the
512    template arguments used to attain the full instantiation from the
513    partial instantiation.  */
514
515 static tree
516 add_outermost_template_args (tree args, tree extra_args)
517 {
518   tree new_args;
519
520   /* If there are more levels of EXTRA_ARGS than there are ARGS,
521      something very fishy is going on.  */
522   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
523
524   /* If *all* the new arguments will be the EXTRA_ARGS, just return
525      them.  */
526   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
527     return extra_args;
528
529   /* For the moment, we make ARGS look like it contains fewer levels.  */
530   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
531
532   new_args = add_to_template_args (args, extra_args);
533
534   /* Now, we restore ARGS to its full dimensions.  */
535   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
536
537   return new_args;
538 }
539
540 /* Return the N levels of innermost template arguments from the ARGS.  */
541
542 tree
543 get_innermost_template_args (tree args, int n)
544 {
545   tree new_args;
546   int extra_levels;
547   int i;
548
549   gcc_assert (n >= 0);
550
551   /* If N is 1, just return the innermost set of template arguments.  */
552   if (n == 1)
553     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
554
555   /* If we're not removing anything, just return the arguments we were
556      given.  */
557   extra_levels = TMPL_ARGS_DEPTH (args) - n;
558   gcc_assert (extra_levels >= 0);
559   if (extra_levels == 0)
560     return args;
561
562   /* Make a new set of arguments, not containing the outer arguments.  */
563   new_args = make_tree_vec (n);
564   for (i = 1; i <= n; ++i)
565     SET_TMPL_ARGS_LEVEL (new_args, i,
566                          TMPL_ARGS_LEVEL (args, i + extra_levels));
567
568   return new_args;
569 }
570
571 /* The inverse of get_innermost_template_args: Return all but the innermost
572    EXTRA_LEVELS levels of template arguments from the ARGS.  */
573
574 static tree
575 strip_innermost_template_args (tree args, int extra_levels)
576 {
577   tree new_args;
578   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
579   int i;
580
581   gcc_assert (n >= 0);
582
583   /* If N is 1, just return the outermost set of template arguments.  */
584   if (n == 1)
585     return TMPL_ARGS_LEVEL (args, 1);
586
587   /* If we're not removing anything, just return the arguments we were
588      given.  */
589   gcc_assert (extra_levels >= 0);
590   if (extra_levels == 0)
591     return args;
592
593   /* Make a new set of arguments, not containing the inner arguments.  */
594   new_args = make_tree_vec (n);
595   for (i = 1; i <= n; ++i)
596     SET_TMPL_ARGS_LEVEL (new_args, i,
597                          TMPL_ARGS_LEVEL (args, i));
598
599   return new_args;
600 }
601
602 /* We've got a template header coming up; push to a new level for storing
603    the parms.  */
604
605 void
606 begin_template_parm_list (void)
607 {
608   /* We use a non-tag-transparent scope here, which causes pushtag to
609      put tags in this scope, rather than in the enclosing class or
610      namespace scope.  This is the right thing, since we want
611      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
612      global template class, push_template_decl handles putting the
613      TEMPLATE_DECL into top-level scope.  For a nested template class,
614      e.g.:
615
616        template <class T> struct S1 {
617          template <class T> struct S2 {};
618        };
619
620      pushtag contains special code to call pushdecl_with_scope on the
621      TEMPLATE_DECL for S2.  */
622   begin_scope (sk_template_parms, NULL);
623   ++processing_template_decl;
624   ++processing_template_parmlist;
625   note_template_header (0);
626 }
627
628 /* This routine is called when a specialization is declared.  If it is
629    invalid to declare a specialization here, an error is reported and
630    false is returned, otherwise this routine will return true.  */
631
632 static bool
633 check_specialization_scope (void)
634 {
635   tree scope = current_scope ();
636
637   /* [temp.expl.spec]
638
639      An explicit specialization shall be declared in the namespace of
640      which the template is a member, or, for member templates, in the
641      namespace of which the enclosing class or enclosing class
642      template is a member.  An explicit specialization of a member
643      function, member class or static data member of a class template
644      shall be declared in the namespace of which the class template
645      is a member.  */
646   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
647     {
648       error ("explicit specialization in non-namespace scope %qD", scope);
649       return false;
650     }
651
652   /* [temp.expl.spec]
653
654      In an explicit specialization declaration for a member of a class
655      template or a member template that appears in namespace scope,
656      the member template and some of its enclosing class templates may
657      remain unspecialized, except that the declaration shall not
658      explicitly specialize a class member template if its enclosing
659      class templates are not explicitly specialized as well.  */
660   if (current_template_parms)
661     {
662       error ("enclosing class templates are not explicitly specialized");
663       return false;
664     }
665
666   return true;
667 }
668
669 /* We've just seen template <>.  */
670
671 bool
672 begin_specialization (void)
673 {
674   begin_scope (sk_template_spec, NULL);
675   note_template_header (1);
676   return check_specialization_scope ();
677 }
678
679 /* Called at then end of processing a declaration preceded by
680    template<>.  */
681
682 void
683 end_specialization (void)
684 {
685   finish_scope ();
686   reset_specialization ();
687 }
688
689 /* Any template <>'s that we have seen thus far are not referring to a
690    function specialization.  */
691
692 void
693 reset_specialization (void)
694 {
695   processing_specialization = 0;
696   template_header_count = 0;
697 }
698
699 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
700    it was of the form template <>.  */
701
702 static void
703 note_template_header (int specialization)
704 {
705   processing_specialization = specialization;
706   template_header_count++;
707 }
708
709 /* We're beginning an explicit instantiation.  */
710
711 void
712 begin_explicit_instantiation (void)
713 {
714   gcc_assert (!processing_explicit_instantiation);
715   processing_explicit_instantiation = true;
716 }
717
718
719 void
720 end_explicit_instantiation (void)
721 {
722   gcc_assert (processing_explicit_instantiation);
723   processing_explicit_instantiation = false;
724 }
725
726 /* An explicit specialization or partial specialization TMPL is being
727    declared.  Check that the namespace in which the specialization is
728    occurring is permissible.  Returns false iff it is invalid to
729    specialize TMPL in the current namespace.  */
730
731 static bool
732 check_specialization_namespace (tree tmpl)
733 {
734   tree tpl_ns = decl_namespace_context (tmpl);
735
736   /* [tmpl.expl.spec]
737
738      An explicit specialization shall be declared in the namespace of
739      which the template is a member, or, for member templates, in the
740      namespace of which the enclosing class or enclosing class
741      template is a member.  An explicit specialization of a member
742      function, member class or static data member of a class template
743      shall be declared in the namespace of which the class template is
744      a member.  */
745   if (current_scope() != DECL_CONTEXT (tmpl)
746       && !at_namespace_scope_p ())
747     {
748       error ("specialization of %qD must appear at namespace scope", tmpl);
749       return false;
750     }
751   if (is_associated_namespace (current_namespace, tpl_ns))
752     /* Same or super-using namespace.  */
753     return true;
754   else
755     {
756       permerror (input_location, "specialization of %qD in different namespace", tmpl);
757       permerror (input_location, "  from definition of %q+#D", tmpl);
758       return false;
759     }
760 }
761
762 /* SPEC is an explicit instantiation.  Check that it is valid to
763    perform this explicit instantiation in the current namespace.  */
764
765 static void
766 check_explicit_instantiation_namespace (tree spec)
767 {
768   tree ns;
769
770   /* DR 275: An explicit instantiation shall appear in an enclosing
771      namespace of its template.  */
772   ns = decl_namespace_context (spec);
773   if (!is_ancestor (current_namespace, ns))
774     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
775                "(which does not enclose namespace %qD)",
776                spec, current_namespace, ns);
777 }
778
779 /* The TYPE is being declared.  If it is a template type, that means it
780    is a partial specialization.  Do appropriate error-checking.  */
781
782 tree
783 maybe_process_partial_specialization (tree type)
784 {
785   tree context;
786
787   if (type == error_mark_node)
788     return error_mark_node;
789
790   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
791     {
792       error ("name of class shadows template template parameter %qD",
793              TYPE_NAME (type));
794       return error_mark_node;
795     }
796
797   context = TYPE_CONTEXT (type);
798
799   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
800     {
801       /* This is for ordinary explicit specialization and partial
802          specialization of a template class such as:
803
804            template <> class C<int>;
805
806          or:
807
808            template <class T> class C<T*>;
809
810          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
811
812       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
813           && !COMPLETE_TYPE_P (type))
814         {
815           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
816           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
817           if (processing_template_decl)
818             {
819               if (push_template_decl (TYPE_MAIN_DECL (type))
820                   == error_mark_node)
821                 return error_mark_node;
822             }
823         }
824       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
825         error ("specialization of %qT after instantiation", type);
826     }
827   else if (CLASS_TYPE_P (type)
828            && !CLASSTYPE_USE_TEMPLATE (type)
829            && CLASSTYPE_TEMPLATE_INFO (type)
830            && context && CLASS_TYPE_P (context)
831            && CLASSTYPE_TEMPLATE_INFO (context))
832     {
833       /* This is for an explicit specialization of member class
834          template according to [temp.expl.spec/18]:
835
836            template <> template <class U> class C<int>::D;
837
838          The context `C<int>' must be an implicit instantiation.
839          Otherwise this is just a member class template declared
840          earlier like:
841
842            template <> class C<int> { template <class U> class D; };
843            template <> template <class U> class C<int>::D;
844
845          In the first case, `C<int>::D' is a specialization of `C<T>::D'
846          while in the second case, `C<int>::D' is a primary template
847          and `C<T>::D' may not exist.  */
848
849       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
850           && !COMPLETE_TYPE_P (type))
851         {
852           tree t;
853           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
854
855           if (current_namespace
856               != decl_namespace_context (tmpl))
857             {
858               permerror (input_location, "specializing %q#T in different namespace", type);
859               permerror (input_location, "  from definition of %q+#D", tmpl);
860             }
861
862           /* Check for invalid specialization after instantiation:
863
864                template <> template <> class C<int>::D<int>;
865                template <> template <class U> class C<int>::D;  */
866
867           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
868                t; t = TREE_CHAIN (t))
869             {
870               tree inst = TREE_VALUE (t);
871               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
872                 {
873                   /* We already have a full specialization of this partial
874                      instantiation.  Reassign it to the new member
875                      specialization template.  */
876                   spec_entry elt;
877                   spec_entry **slot;
878
879                   elt.tmpl = most_general_template (tmpl);
880                   elt.args = CLASSTYPE_TI_ARGS (inst);
881                   elt.spec = inst;
882
883                   htab_remove_elt (type_specializations, &elt);
884
885                   elt.tmpl = tmpl;
886                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
887
888                   slot = (spec_entry **)
889                     htab_find_slot (type_specializations, &elt, INSERT);
890                   *slot = ggc_alloc_spec_entry ();
891                   **slot = elt;
892                 }
893               else if (COMPLETE_OR_OPEN_TYPE_P (inst))
894                 /* But if we've had an implicit instantiation, that's a
895                    problem ([temp.expl.spec]/6).  */
896                 error ("specialization %qT after instantiation %qT",
897                        type, inst);
898             }
899
900           /* Mark TYPE as a specialization.  And as a result, we only
901              have one level of template argument for the innermost
902              class template.  */
903           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
904           CLASSTYPE_TI_ARGS (type)
905             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
906         }
907     }
908   else if (processing_specialization)
909     {
910       error ("explicit specialization of non-template %qT", type);
911       return error_mark_node;
912     }
913
914   return type;
915 }
916
917 /* Returns nonzero if we can optimize the retrieval of specializations
918    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
919    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
920
921 static inline bool
922 optimize_specialization_lookup_p (tree tmpl)
923 {
924   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
925           && DECL_CLASS_SCOPE_P (tmpl)
926           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
927              parameter.  */
928           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
929           /* The optimized lookup depends on the fact that the
930              template arguments for the member function template apply
931              purely to the containing class, which is not true if the
932              containing class is an explicit or partial
933              specialization.  */
934           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
935           && !DECL_MEMBER_TEMPLATE_P (tmpl)
936           && !DECL_CONV_FN_P (tmpl)
937           /* It is possible to have a template that is not a member
938              template and is not a member of a template class:
939
940              template <typename T>
941              struct S { friend A::f(); };
942
943              Here, the friend function is a template, but the context does
944              not have template information.  The optimized lookup relies
945              on having ARGS be the template arguments for both the class
946              and the function template.  */
947           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
948 }
949
950 /* Retrieve the specialization (in the sense of [temp.spec] - a
951    specialization is either an instantiation or an explicit
952    specialization) of TMPL for the given template ARGS.  If there is
953    no such specialization, return NULL_TREE.  The ARGS are a vector of
954    arguments, or a vector of vectors of arguments, in the case of
955    templates with more than one level of parameters.
956
957    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
958    then we search for a partial specialization matching ARGS.  This
959    parameter is ignored if TMPL is not a class template.  */
960
961 static tree
962 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
963 {
964   if (args == error_mark_node)
965     return NULL_TREE;
966
967   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
968
969   /* There should be as many levels of arguments as there are
970      levels of parameters.  */
971   gcc_assert (TMPL_ARGS_DEPTH (args)
972               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
973
974   if (optimize_specialization_lookup_p (tmpl))
975     {
976       tree class_template;
977       tree class_specialization;
978       VEC(tree,gc) *methods;
979       tree fns;
980       int idx;
981
982       /* The template arguments actually apply to the containing
983          class.  Find the class specialization with those
984          arguments.  */
985       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
986       class_specialization
987         = retrieve_specialization (class_template, args, 0);
988       if (!class_specialization)
989         return NULL_TREE;
990       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
991          for the specialization.  */
992       idx = class_method_index_for_fn (class_specialization, tmpl);
993       if (idx == -1)
994         return NULL_TREE;
995       /* Iterate through the methods with the indicated name, looking
996          for the one that has an instance of TMPL.  */
997       methods = CLASSTYPE_METHOD_VEC (class_specialization);
998       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
999         {
1000           tree fn = OVL_CURRENT (fns);
1001           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1002               /* using-declarations can add base methods to the method vec,
1003                  and we don't want those here.  */
1004               && DECL_CONTEXT (fn) == class_specialization)
1005             return fn;
1006         }
1007       return NULL_TREE;
1008     }
1009   else
1010     {
1011       spec_entry *found;
1012       spec_entry elt;
1013       htab_t specializations;
1014
1015       elt.tmpl = tmpl;
1016       elt.args = args;
1017       elt.spec = NULL_TREE;
1018
1019       if (DECL_CLASS_TEMPLATE_P (tmpl))
1020         specializations = type_specializations;
1021       else
1022         specializations = decl_specializations;
1023
1024       if (hash == 0)
1025         hash = hash_specialization (&elt);
1026       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1027       if (found)
1028         return found->spec;
1029     }
1030
1031   return NULL_TREE;
1032 }
1033
1034 /* Like retrieve_specialization, but for local declarations.  */
1035
1036 static tree
1037 retrieve_local_specialization (tree tmpl)
1038 {
1039   tree spec;
1040
1041   if (local_specializations == NULL)
1042     return NULL_TREE;
1043
1044   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1045                                      htab_hash_pointer (tmpl));
1046   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1047 }
1048
1049 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1050
1051 int
1052 is_specialization_of (tree decl, tree tmpl)
1053 {
1054   tree t;
1055
1056   if (TREE_CODE (decl) == FUNCTION_DECL)
1057     {
1058       for (t = decl;
1059            t != NULL_TREE;
1060            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1061         if (t == tmpl)
1062           return 1;
1063     }
1064   else
1065     {
1066       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1067
1068       for (t = TREE_TYPE (decl);
1069            t != NULL_TREE;
1070            t = CLASSTYPE_USE_TEMPLATE (t)
1071              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1072         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1073           return 1;
1074     }
1075
1076   return 0;
1077 }
1078
1079 /* Returns nonzero iff DECL is a specialization of friend declaration
1080    FRIEND_DECL according to [temp.friend].  */
1081
1082 bool
1083 is_specialization_of_friend (tree decl, tree friend_decl)
1084 {
1085   bool need_template = true;
1086   int template_depth;
1087
1088   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1089               || TREE_CODE (decl) == TYPE_DECL);
1090
1091   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1092      of a template class, we want to check if DECL is a specialization
1093      if this.  */
1094   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1095       && DECL_TEMPLATE_INFO (friend_decl)
1096       && !DECL_USE_TEMPLATE (friend_decl))
1097     {
1098       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1099       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1100       need_template = false;
1101     }
1102   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1103            && !PRIMARY_TEMPLATE_P (friend_decl))
1104     need_template = false;
1105
1106   /* There is nothing to do if this is not a template friend.  */
1107   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1108     return false;
1109
1110   if (is_specialization_of (decl, friend_decl))
1111     return true;
1112
1113   /* [temp.friend/6]
1114      A member of a class template may be declared to be a friend of a
1115      non-template class.  In this case, the corresponding member of
1116      every specialization of the class template is a friend of the
1117      class granting friendship.
1118
1119      For example, given a template friend declaration
1120
1121        template <class T> friend void A<T>::f();
1122
1123      the member function below is considered a friend
1124
1125        template <> struct A<int> {
1126          void f();
1127        };
1128
1129      For this type of template friend, TEMPLATE_DEPTH below will be
1130      nonzero.  To determine if DECL is a friend of FRIEND, we first
1131      check if the enclosing class is a specialization of another.  */
1132
1133   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1134   if (template_depth
1135       && DECL_CLASS_SCOPE_P (decl)
1136       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1137                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1138     {
1139       /* Next, we check the members themselves.  In order to handle
1140          a few tricky cases, such as when FRIEND_DECL's are
1141
1142            template <class T> friend void A<T>::g(T t);
1143            template <class T> template <T t> friend void A<T>::h();
1144
1145          and DECL's are
1146
1147            void A<int>::g(int);
1148            template <int> void A<int>::h();
1149
1150          we need to figure out ARGS, the template arguments from
1151          the context of DECL.  This is required for template substitution
1152          of `T' in the function parameter of `g' and template parameter
1153          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1154
1155       tree context = DECL_CONTEXT (decl);
1156       tree args = NULL_TREE;
1157       int current_depth = 0;
1158
1159       while (current_depth < template_depth)
1160         {
1161           if (CLASSTYPE_TEMPLATE_INFO (context))
1162             {
1163               if (current_depth == 0)
1164                 args = TYPE_TI_ARGS (context);
1165               else
1166                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1167               current_depth++;
1168             }
1169           context = TYPE_CONTEXT (context);
1170         }
1171
1172       if (TREE_CODE (decl) == FUNCTION_DECL)
1173         {
1174           bool is_template;
1175           tree friend_type;
1176           tree decl_type;
1177           tree friend_args_type;
1178           tree decl_args_type;
1179
1180           /* Make sure that both DECL and FRIEND_DECL are templates or
1181              non-templates.  */
1182           is_template = DECL_TEMPLATE_INFO (decl)
1183                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1184           if (need_template ^ is_template)
1185             return false;
1186           else if (is_template)
1187             {
1188               /* If both are templates, check template parameter list.  */
1189               tree friend_parms
1190                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1191                                          args, tf_none);
1192               if (!comp_template_parms
1193                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1194                       friend_parms))
1195                 return false;
1196
1197               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1198             }
1199           else
1200             decl_type = TREE_TYPE (decl);
1201
1202           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1203                                               tf_none, NULL_TREE);
1204           if (friend_type == error_mark_node)
1205             return false;
1206
1207           /* Check if return types match.  */
1208           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1209             return false;
1210
1211           /* Check if function parameter types match, ignoring the
1212              `this' parameter.  */
1213           friend_args_type = TYPE_ARG_TYPES (friend_type);
1214           decl_args_type = TYPE_ARG_TYPES (decl_type);
1215           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1216             friend_args_type = TREE_CHAIN (friend_args_type);
1217           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1218             decl_args_type = TREE_CHAIN (decl_args_type);
1219
1220           return compparms (decl_args_type, friend_args_type);
1221         }
1222       else
1223         {
1224           /* DECL is a TYPE_DECL */
1225           bool is_template;
1226           tree decl_type = TREE_TYPE (decl);
1227
1228           /* Make sure that both DECL and FRIEND_DECL are templates or
1229              non-templates.  */
1230           is_template
1231             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1232               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1233
1234           if (need_template ^ is_template)
1235             return false;
1236           else if (is_template)
1237             {
1238               tree friend_parms;
1239               /* If both are templates, check the name of the two
1240                  TEMPLATE_DECL's first because is_friend didn't.  */
1241               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1242                   != DECL_NAME (friend_decl))
1243                 return false;
1244
1245               /* Now check template parameter list.  */
1246               friend_parms
1247                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1248                                          args, tf_none);
1249               return comp_template_parms
1250                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1251                  friend_parms);
1252             }
1253           else
1254             return (DECL_NAME (decl)
1255                     == DECL_NAME (friend_decl));
1256         }
1257     }
1258   return false;
1259 }
1260
1261 /* Register the specialization SPEC as a specialization of TMPL with
1262    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1263    is actually just a friend declaration.  Returns SPEC, or an
1264    equivalent prior declaration, if available.  */
1265
1266 static tree
1267 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1268                          hashval_t hash)
1269 {
1270   tree fn;
1271   spec_entry **slot = NULL;
1272   spec_entry elt;
1273
1274   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1275
1276   if (TREE_CODE (spec) == FUNCTION_DECL
1277       && uses_template_parms (DECL_TI_ARGS (spec)))
1278     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1279        register it; we want the corresponding TEMPLATE_DECL instead.
1280        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1281        the more obvious `uses_template_parms (spec)' to avoid problems
1282        with default function arguments.  In particular, given
1283        something like this:
1284
1285           template <class T> void f(T t1, T t = T())
1286
1287        the default argument expression is not substituted for in an
1288        instantiation unless and until it is actually needed.  */
1289     return spec;
1290
1291   if (optimize_specialization_lookup_p (tmpl))
1292     /* We don't put these specializations in the hash table, but we might
1293        want to give an error about a mismatch.  */
1294     fn = retrieve_specialization (tmpl, args, 0);
1295   else
1296     {
1297       elt.tmpl = tmpl;
1298       elt.args = args;
1299       elt.spec = spec;
1300
1301       if (hash == 0)
1302         hash = hash_specialization (&elt);
1303
1304       slot = (spec_entry **)
1305         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1306       if (*slot)
1307         fn = (*slot)->spec;
1308       else
1309         fn = NULL_TREE;
1310     }
1311
1312   /* We can sometimes try to re-register a specialization that we've
1313      already got.  In particular, regenerate_decl_from_template calls
1314      duplicate_decls which will update the specialization list.  But,
1315      we'll still get called again here anyhow.  It's more convenient
1316      to simply allow this than to try to prevent it.  */
1317   if (fn == spec)
1318     return spec;
1319   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1320     {
1321       if (DECL_TEMPLATE_INSTANTIATION (fn))
1322         {
1323           if (DECL_ODR_USED (fn)
1324               || DECL_EXPLICIT_INSTANTIATION (fn))
1325             {
1326               error ("specialization of %qD after instantiation",
1327                      fn);
1328               return error_mark_node;
1329             }
1330           else
1331             {
1332               tree clone;
1333               /* This situation should occur only if the first
1334                  specialization is an implicit instantiation, the
1335                  second is an explicit specialization, and the
1336                  implicit instantiation has not yet been used.  That
1337                  situation can occur if we have implicitly
1338                  instantiated a member function and then specialized
1339                  it later.
1340
1341                  We can also wind up here if a friend declaration that
1342                  looked like an instantiation turns out to be a
1343                  specialization:
1344
1345                    template <class T> void foo(T);
1346                    class S { friend void foo<>(int) };
1347                    template <> void foo(int);
1348
1349                  We transform the existing DECL in place so that any
1350                  pointers to it become pointers to the updated
1351                  declaration.
1352
1353                  If there was a definition for the template, but not
1354                  for the specialization, we want this to look as if
1355                  there were no definition, and vice versa.  */
1356               DECL_INITIAL (fn) = NULL_TREE;
1357               duplicate_decls (spec, fn, is_friend);
1358               /* The call to duplicate_decls will have applied
1359                  [temp.expl.spec]:
1360
1361                    An explicit specialization of a function template
1362                    is inline only if it is explicitly declared to be,
1363                    and independently of whether its function template
1364                    is.
1365
1366                 to the primary function; now copy the inline bits to
1367                 the various clones.  */
1368               FOR_EACH_CLONE (clone, fn)
1369                 {
1370                   DECL_DECLARED_INLINE_P (clone)
1371                     = DECL_DECLARED_INLINE_P (fn);
1372                   DECL_SOURCE_LOCATION (clone)
1373                     = DECL_SOURCE_LOCATION (fn);
1374                 }
1375               check_specialization_namespace (fn);
1376
1377               return fn;
1378             }
1379         }
1380       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1381         {
1382           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1383             /* Dup decl failed, but this is a new definition. Set the
1384                line number so any errors match this new
1385                definition.  */
1386             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1387
1388           return fn;
1389         }
1390     }
1391   else if (fn)
1392     return duplicate_decls (spec, fn, is_friend);
1393
1394   /* A specialization must be declared in the same namespace as the
1395      template it is specializing.  */
1396   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1397       && !check_specialization_namespace (tmpl))
1398     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1399
1400   if (!optimize_specialization_lookup_p (tmpl))
1401     {
1402       gcc_assert (tmpl && args && spec);
1403       *slot = ggc_alloc_spec_entry ();
1404       **slot = elt;
1405       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1406           && PRIMARY_TEMPLATE_P (tmpl)
1407           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1408         /* TMPL is a forward declaration of a template function; keep a list
1409            of all specializations in case we need to reassign them to a friend
1410            template later in tsubst_friend_function.  */
1411         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1412           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1413     }
1414
1415   return spec;
1416 }
1417
1418 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1419    TMPL and ARGS members, ignores SPEC.  */
1420
1421 static int
1422 eq_specializations (const void *p1, const void *p2)
1423 {
1424   const spec_entry *e1 = (const spec_entry *)p1;
1425   const spec_entry *e2 = (const spec_entry *)p2;
1426
1427   return (e1->tmpl == e2->tmpl
1428           && comp_template_args (e1->args, e2->args));
1429 }
1430
1431 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1432
1433 static hashval_t
1434 hash_tmpl_and_args (tree tmpl, tree args)
1435 {
1436   hashval_t val = DECL_UID (tmpl);
1437   return iterative_hash_template_arg (args, val);
1438 }
1439
1440 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1441    ignoring SPEC.  */
1442
1443 static hashval_t
1444 hash_specialization (const void *p)
1445 {
1446   const spec_entry *e = (const spec_entry *)p;
1447   return hash_tmpl_and_args (e->tmpl, e->args);
1448 }
1449
1450 /* Recursively calculate a hash value for a template argument ARG, for use
1451    in the hash tables of template specializations.  */
1452
1453 static hashval_t
1454 iterative_hash_template_arg (tree arg, hashval_t val)
1455 {
1456   unsigned HOST_WIDE_INT i;
1457   enum tree_code code;
1458   char tclass;
1459
1460   if (arg == NULL_TREE)
1461     return iterative_hash_object (arg, val);
1462
1463   if (!TYPE_P (arg))
1464     STRIP_NOPS (arg);
1465
1466   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1467     /* We can get one of these when re-hashing a previous entry in the middle
1468        of substituting into a pack expansion.  Just look through it.  */
1469     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1470
1471   code = TREE_CODE (arg);
1472   tclass = TREE_CODE_CLASS (code);
1473
1474   val = iterative_hash_object (code, val);
1475
1476   switch (code)
1477     {
1478     case ERROR_MARK:
1479       return val;
1480
1481     case IDENTIFIER_NODE:
1482       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1483
1484     case TREE_VEC:
1485       {
1486         int i, len = TREE_VEC_LENGTH (arg);
1487         for (i = 0; i < len; ++i)
1488           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1489         return val;
1490       }
1491
1492     case TYPE_PACK_EXPANSION:
1493     case EXPR_PACK_EXPANSION:
1494       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1495
1496     case TYPE_ARGUMENT_PACK:
1497     case NONTYPE_ARGUMENT_PACK:
1498       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1499
1500     case TREE_LIST:
1501       for (; arg; arg = TREE_CHAIN (arg))
1502         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1503       return val;
1504
1505     case OVERLOAD:
1506       for (; arg; arg = OVL_CHAIN (arg))
1507         val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1508       return val;
1509
1510     case CONSTRUCTOR:
1511       {
1512         tree field, value;
1513         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1514           {
1515             val = iterative_hash_template_arg (field, val);
1516             val = iterative_hash_template_arg (value, val);
1517           }
1518         return val;
1519       }
1520
1521     case PARM_DECL:
1522       if (!DECL_ARTIFICIAL (arg))
1523         val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1524       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1525
1526     case TARGET_EXPR:
1527       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1528
1529     case PTRMEM_CST:
1530       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1531       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1532
1533     case TEMPLATE_PARM_INDEX:
1534       val = iterative_hash_template_arg
1535         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1536       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1537       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1538
1539     case TRAIT_EXPR:
1540       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1541       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1542       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1543
1544     case BASELINK:
1545       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1546                                          val);
1547       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1548                                           val);
1549
1550     case MODOP_EXPR:
1551       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1552       code = TREE_CODE (TREE_OPERAND (arg, 1));
1553       val = iterative_hash_object (code, val);
1554       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1555
1556     case ARRAY_TYPE:
1557       /* layout_type sets structural equality for arrays of
1558          incomplete type, so we can't rely on the canonical type
1559          for hashing.  */
1560       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1561       return iterative_hash_template_arg (TYPE_DOMAIN (arg), val);
1562
1563     case LAMBDA_EXPR:
1564       /* A lambda can't appear in a template arg, but don't crash on
1565          erroneous input.  */
1566       gcc_assert (seen_error ());
1567       return val;
1568
1569     default:
1570       switch (tclass)
1571         {
1572         case tcc_type:
1573           if (TYPE_CANONICAL (arg))
1574             return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1575                                           val);
1576           else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1577             return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1578           /* Otherwise just compare the types during lookup.  */
1579           return val;
1580
1581         case tcc_declaration:
1582         case tcc_constant:
1583           return iterative_hash_expr (arg, val);
1584
1585         default:
1586           gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1587           {
1588             unsigned n = TREE_OPERAND_LENGTH (arg);
1589             for (i = 0; i < n; ++i)
1590               val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1591             return val;
1592           }
1593         }
1594     }
1595   gcc_unreachable ();
1596   return 0;
1597 }
1598
1599 /* Unregister the specialization SPEC as a specialization of TMPL.
1600    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1601    if the SPEC was listed as a specialization of TMPL.
1602
1603    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1604
1605 bool
1606 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1607 {
1608   spec_entry **slot;
1609   spec_entry elt;
1610
1611   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1612   elt.args = TI_ARGS (tinfo);
1613   elt.spec = NULL_TREE;
1614
1615   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1616   if (*slot)
1617     {
1618       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1619       gcc_assert (new_spec != NULL_TREE);
1620       (*slot)->spec = new_spec;
1621       return 1;
1622     }
1623
1624   return 0;
1625 }
1626
1627 /* Compare an entry in the local specializations hash table P1 (which
1628    is really a pointer to a TREE_LIST) with P2 (which is really a
1629    DECL).  */
1630
1631 static int
1632 eq_local_specializations (const void *p1, const void *p2)
1633 {
1634   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1635 }
1636
1637 /* Hash P1, an entry in the local specializations table.  */
1638
1639 static hashval_t
1640 hash_local_specialization (const void* p1)
1641 {
1642   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1643 }
1644
1645 /* Like register_specialization, but for local declarations.  We are
1646    registering SPEC, an instantiation of TMPL.  */
1647
1648 static void
1649 register_local_specialization (tree spec, tree tmpl)
1650 {
1651   void **slot;
1652
1653   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1654                                    htab_hash_pointer (tmpl), INSERT);
1655   *slot = build_tree_list (spec, tmpl);
1656 }
1657
1658 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1659    specialized class.  */
1660
1661 bool
1662 explicit_class_specialization_p (tree type)
1663 {
1664   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1665     return false;
1666   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1667 }
1668
1669 /* Print the list of functions at FNS, going through all the overloads
1670    for each element of the list.  Alternatively, FNS can not be a
1671    TREE_LIST, in which case it will be printed together with all the
1672    overloads.
1673
1674    MORE and *STR should respectively be FALSE and NULL when the function
1675    is called from the outside.  They are used internally on recursive
1676    calls.  print_candidates manages the two parameters and leaves NULL
1677    in *STR when it ends.  */
1678
1679 static void
1680 print_candidates_1 (tree fns, bool more, const char **str)
1681 {
1682   tree fn, fn2;
1683   char *spaces = NULL;
1684
1685   for (fn = fns; fn; fn = OVL_NEXT (fn))
1686     if (TREE_CODE (fn) == TREE_LIST)
1687       {
1688         gcc_assert (!OVL_NEXT (fn) && !is_overloaded_fn (fn));
1689         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1690           print_candidates_1 (TREE_VALUE (fn2),
1691                               TREE_CHAIN (fn2) || more, str);
1692       }
1693     else
1694       {
1695         if (!*str)
1696           {
1697             /* Pick the prefix string.  */
1698             if (!more && !OVL_NEXT (fns))
1699               {
1700                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1701                 continue;
1702               }
1703
1704             *str = _("candidates are:");
1705             spaces = get_spaces (*str);
1706           }
1707         error ("%s %+#D", *str, OVL_CURRENT (fn));
1708         *str = spaces ? spaces : *str;
1709       }
1710
1711   if (!more)
1712     {
1713       free (spaces);
1714       *str = NULL;
1715     }
1716 }
1717
1718 /* Print the list of candidate FNS in an error message.  */
1719
1720 void
1721 print_candidates (tree fns)
1722 {
1723   const char *str = NULL;
1724   print_candidates_1 (fns, false, &str);
1725   gcc_assert (str == NULL);
1726 }
1727
1728 /* Returns the template (one of the functions given by TEMPLATE_ID)
1729    which can be specialized to match the indicated DECL with the
1730    explicit template args given in TEMPLATE_ID.  The DECL may be
1731    NULL_TREE if none is available.  In that case, the functions in
1732    TEMPLATE_ID are non-members.
1733
1734    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1735    specialization of a member template.
1736
1737    The TEMPLATE_COUNT is the number of references to qualifying
1738    template classes that appeared in the name of the function. See
1739    check_explicit_specialization for a more accurate description.
1740
1741    TSK indicates what kind of template declaration (if any) is being
1742    declared.  TSK_TEMPLATE indicates that the declaration given by
1743    DECL, though a FUNCTION_DECL, has template parameters, and is
1744    therefore a template function.
1745
1746    The template args (those explicitly specified and those deduced)
1747    are output in a newly created vector *TARGS_OUT.
1748
1749    If it is impossible to determine the result, an error message is
1750    issued.  The error_mark_node is returned to indicate failure.  */
1751
1752 static tree
1753 determine_specialization (tree template_id,
1754                           tree decl,
1755                           tree* targs_out,
1756                           int need_member_template,
1757                           int template_count,
1758                           tmpl_spec_kind tsk)
1759 {
1760   tree fns;
1761   tree targs;
1762   tree explicit_targs;
1763   tree candidates = NULL_TREE;
1764   /* A TREE_LIST of templates of which DECL may be a specialization.
1765      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1766      corresponding TREE_PURPOSE is the set of template arguments that,
1767      when used to instantiate the template, would produce a function
1768      with the signature of DECL.  */
1769   tree templates = NULL_TREE;
1770   int header_count;
1771   struct cp_binding_level *b;
1772
1773   *targs_out = NULL_TREE;
1774
1775   if (template_id == error_mark_node || decl == error_mark_node)
1776     return error_mark_node;
1777
1778   fns = TREE_OPERAND (template_id, 0);
1779   explicit_targs = TREE_OPERAND (template_id, 1);
1780
1781   if (fns == error_mark_node)
1782     return error_mark_node;
1783
1784   /* Check for baselinks.  */
1785   if (BASELINK_P (fns))
1786     fns = BASELINK_FUNCTIONS (fns);
1787
1788   if (!is_overloaded_fn (fns))
1789     {
1790       error ("%qD is not a function template", fns);
1791       return error_mark_node;
1792     }
1793
1794   /* Count the number of template headers specified for this
1795      specialization.  */
1796   header_count = 0;
1797   for (b = current_binding_level;
1798        b->kind == sk_template_parms;
1799        b = b->level_chain)
1800     ++header_count;
1801
1802   for (; fns; fns = OVL_NEXT (fns))
1803     {
1804       tree fn = OVL_CURRENT (fns);
1805
1806       if (TREE_CODE (fn) == TEMPLATE_DECL)
1807         {
1808           tree decl_arg_types;
1809           tree fn_arg_types;
1810
1811           /* In case of explicit specialization, we need to check if
1812              the number of template headers appearing in the specialization
1813              is correct. This is usually done in check_explicit_specialization,
1814              but the check done there cannot be exhaustive when specializing
1815              member functions. Consider the following code:
1816
1817              template <> void A<int>::f(int);
1818              template <> template <> void A<int>::f(int);
1819
1820              Assuming that A<int> is not itself an explicit specialization
1821              already, the first line specializes "f" which is a non-template
1822              member function, whilst the second line specializes "f" which
1823              is a template member function. So both lines are syntactically
1824              correct, and check_explicit_specialization does not reject
1825              them.
1826
1827              Here, we can do better, as we are matching the specialization
1828              against the declarations. We count the number of template
1829              headers, and we check if they match TEMPLATE_COUNT + 1
1830              (TEMPLATE_COUNT is the number of qualifying template classes,
1831              plus there must be another header for the member template
1832              itself).
1833
1834              Notice that if header_count is zero, this is not a
1835              specialization but rather a template instantiation, so there
1836              is no check we can perform here.  */
1837           if (header_count && header_count != template_count + 1)
1838             continue;
1839
1840           /* Check that the number of template arguments at the
1841              innermost level for DECL is the same as for FN.  */
1842           if (current_binding_level->kind == sk_template_parms
1843               && !current_binding_level->explicit_spec_p
1844               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1845                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1846                                       (current_template_parms))))
1847             continue;
1848
1849           /* DECL might be a specialization of FN.  */
1850           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1851           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1852
1853           /* For a non-static member function, we need to make sure
1854              that the const qualification is the same.  Since
1855              get_bindings does not try to merge the "this" parameter,
1856              we must do the comparison explicitly.  */
1857           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1858               && !same_type_p (TREE_VALUE (fn_arg_types),
1859                                TREE_VALUE (decl_arg_types)))
1860             continue;
1861
1862           /* Skip the "this" parameter and, for constructors of
1863              classes with virtual bases, the VTT parameter.  A
1864              full specialization of a constructor will have a VTT
1865              parameter, but a template never will.  */ 
1866           decl_arg_types 
1867             = skip_artificial_parms_for (decl, decl_arg_types);
1868           fn_arg_types 
1869             = skip_artificial_parms_for (fn, fn_arg_types);
1870
1871           /* Check that the number of function parameters matches.
1872              For example,
1873                template <class T> void f(int i = 0);
1874                template <> void f<int>();
1875              The specialization f<int> is invalid but is not caught
1876              by get_bindings below.  */
1877           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1878             continue;
1879
1880           /* Function templates cannot be specializations; there are
1881              no partial specializations of functions.  Therefore, if
1882              the type of DECL does not match FN, there is no
1883              match.  */
1884           if (tsk == tsk_template)
1885             {
1886               if (compparms (fn_arg_types, decl_arg_types))
1887                 candidates = tree_cons (NULL_TREE, fn, candidates);
1888               continue;
1889             }
1890
1891           /* See whether this function might be a specialization of this
1892              template.  */
1893           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1894
1895           if (!targs)
1896             /* We cannot deduce template arguments that when used to
1897                specialize TMPL will produce DECL.  */
1898             continue;
1899
1900           /* Save this template, and the arguments deduced.  */
1901           templates = tree_cons (targs, fn, templates);
1902         }
1903       else if (need_member_template)
1904         /* FN is an ordinary member function, and we need a
1905            specialization of a member template.  */
1906         ;
1907       else if (TREE_CODE (fn) != FUNCTION_DECL)
1908         /* We can get IDENTIFIER_NODEs here in certain erroneous
1909            cases.  */
1910         ;
1911       else if (!DECL_FUNCTION_MEMBER_P (fn))
1912         /* This is just an ordinary non-member function.  Nothing can
1913            be a specialization of that.  */
1914         ;
1915       else if (DECL_ARTIFICIAL (fn))
1916         /* Cannot specialize functions that are created implicitly.  */
1917         ;
1918       else
1919         {
1920           tree decl_arg_types;
1921
1922           /* This is an ordinary member function.  However, since
1923              we're here, we can assume it's enclosing class is a
1924              template class.  For example,
1925
1926                template <typename T> struct S { void f(); };
1927                template <> void S<int>::f() {}
1928
1929              Here, S<int>::f is a non-template, but S<int> is a
1930              template class.  If FN has the same type as DECL, we
1931              might be in business.  */
1932
1933           if (!DECL_TEMPLATE_INFO (fn))
1934             /* Its enclosing class is an explicit specialization
1935                of a template class.  This is not a candidate.  */
1936             continue;
1937
1938           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1939                             TREE_TYPE (TREE_TYPE (fn))))
1940             /* The return types differ.  */
1941             continue;
1942
1943           /* Adjust the type of DECL in case FN is a static member.  */
1944           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1945           if (DECL_STATIC_FUNCTION_P (fn)
1946               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1947             decl_arg_types = TREE_CHAIN (decl_arg_types);
1948
1949           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1950                          decl_arg_types))
1951             /* They match!  */
1952             candidates = tree_cons (NULL_TREE, fn, candidates);
1953         }
1954     }
1955
1956   if (templates && TREE_CHAIN (templates))
1957     {
1958       /* We have:
1959
1960            [temp.expl.spec]
1961
1962            It is possible for a specialization with a given function
1963            signature to be instantiated from more than one function
1964            template.  In such cases, explicit specification of the
1965            template arguments must be used to uniquely identify the
1966            function template specialization being specialized.
1967
1968          Note that here, there's no suggestion that we're supposed to
1969          determine which of the candidate templates is most
1970          specialized.  However, we, also have:
1971
1972            [temp.func.order]
1973
1974            Partial ordering of overloaded function template
1975            declarations is used in the following contexts to select
1976            the function template to which a function template
1977            specialization refers:
1978
1979            -- when an explicit specialization refers to a function
1980               template.
1981
1982          So, we do use the partial ordering rules, at least for now.
1983          This extension can only serve to make invalid programs valid,
1984          so it's safe.  And, there is strong anecdotal evidence that
1985          the committee intended the partial ordering rules to apply;
1986          the EDG front end has that behavior, and John Spicer claims
1987          that the committee simply forgot to delete the wording in
1988          [temp.expl.spec].  */
1989       tree tmpl = most_specialized_instantiation (templates);
1990       if (tmpl != error_mark_node)
1991         {
1992           templates = tmpl;
1993           TREE_CHAIN (templates) = NULL_TREE;
1994         }
1995     }
1996
1997   if (templates == NULL_TREE && candidates == NULL_TREE)
1998     {
1999       error ("template-id %qD for %q+D does not match any template "
2000              "declaration", template_id, decl);
2001       if (header_count && header_count != template_count + 1)
2002         inform (input_location, "saw %d %<template<>%>, need %d for "
2003                 "specializing a member function template",
2004                 header_count, template_count + 1);
2005       return error_mark_node;
2006     }
2007   else if ((templates && TREE_CHAIN (templates))
2008            || (candidates && TREE_CHAIN (candidates))
2009            || (templates && candidates))
2010     {
2011       error ("ambiguous template specialization %qD for %q+D",
2012              template_id, decl);
2013       candidates = chainon (candidates, templates);
2014       print_candidates (candidates);
2015       return error_mark_node;
2016     }
2017
2018   /* We have one, and exactly one, match.  */
2019   if (candidates)
2020     {
2021       tree fn = TREE_VALUE (candidates);
2022       *targs_out = copy_node (DECL_TI_ARGS (fn));
2023       /* DECL is a re-declaration or partial instantiation of a template
2024          function.  */
2025       if (TREE_CODE (fn) == TEMPLATE_DECL)
2026         return fn;
2027       /* It was a specialization of an ordinary member function in a
2028          template class.  */
2029       return DECL_TI_TEMPLATE (fn);
2030     }
2031
2032   /* It was a specialization of a template.  */
2033   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2034   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2035     {
2036       *targs_out = copy_node (targs);
2037       SET_TMPL_ARGS_LEVEL (*targs_out,
2038                            TMPL_ARGS_DEPTH (*targs_out),
2039                            TREE_PURPOSE (templates));
2040     }
2041   else
2042     *targs_out = TREE_PURPOSE (templates);
2043   return TREE_VALUE (templates);
2044 }
2045
2046 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2047    but with the default argument values filled in from those in the
2048    TMPL_TYPES.  */
2049
2050 static tree
2051 copy_default_args_to_explicit_spec_1 (tree spec_types,
2052                                       tree tmpl_types)
2053 {
2054   tree new_spec_types;
2055
2056   if (!spec_types)
2057     return NULL_TREE;
2058
2059   if (spec_types == void_list_node)
2060     return void_list_node;
2061
2062   /* Substitute into the rest of the list.  */
2063   new_spec_types =
2064     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2065                                           TREE_CHAIN (tmpl_types));
2066
2067   /* Add the default argument for this parameter.  */
2068   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2069                          TREE_VALUE (spec_types),
2070                          new_spec_types);
2071 }
2072
2073 /* DECL is an explicit specialization.  Replicate default arguments
2074    from the template it specializes.  (That way, code like:
2075
2076      template <class T> void f(T = 3);
2077      template <> void f(double);
2078      void g () { f (); }
2079
2080    works, as required.)  An alternative approach would be to look up
2081    the correct default arguments at the call-site, but this approach
2082    is consistent with how implicit instantiations are handled.  */
2083
2084 static void
2085 copy_default_args_to_explicit_spec (tree decl)
2086 {
2087   tree tmpl;
2088   tree spec_types;
2089   tree tmpl_types;
2090   tree new_spec_types;
2091   tree old_type;
2092   tree new_type;
2093   tree t;
2094   tree object_type = NULL_TREE;
2095   tree in_charge = NULL_TREE;
2096   tree vtt = NULL_TREE;
2097
2098   /* See if there's anything we need to do.  */
2099   tmpl = DECL_TI_TEMPLATE (decl);
2100   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2101   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2102     if (TREE_PURPOSE (t))
2103       break;
2104   if (!t)
2105     return;
2106
2107   old_type = TREE_TYPE (decl);
2108   spec_types = TYPE_ARG_TYPES (old_type);
2109
2110   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2111     {
2112       /* Remove the this pointer, but remember the object's type for
2113          CV quals.  */
2114       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2115       spec_types = TREE_CHAIN (spec_types);
2116       tmpl_types = TREE_CHAIN (tmpl_types);
2117
2118       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2119         {
2120           /* DECL may contain more parameters than TMPL due to the extra
2121              in-charge parameter in constructors and destructors.  */
2122           in_charge = spec_types;
2123           spec_types = TREE_CHAIN (spec_types);
2124         }
2125       if (DECL_HAS_VTT_PARM_P (decl))
2126         {
2127           vtt = spec_types;
2128           spec_types = TREE_CHAIN (spec_types);
2129         }
2130     }
2131
2132   /* Compute the merged default arguments.  */
2133   new_spec_types =
2134     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2135
2136   /* Compute the new FUNCTION_TYPE.  */
2137   if (object_type)
2138     {
2139       if (vtt)
2140         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2141                                          TREE_VALUE (vtt),
2142                                          new_spec_types);
2143
2144       if (in_charge)
2145         /* Put the in-charge parameter back.  */
2146         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2147                                          TREE_VALUE (in_charge),
2148                                          new_spec_types);
2149
2150       new_type = build_method_type_directly (object_type,
2151                                              TREE_TYPE (old_type),
2152                                              new_spec_types);
2153     }
2154   else
2155     new_type = build_function_type (TREE_TYPE (old_type),
2156                                     new_spec_types);
2157   new_type = cp_build_type_attribute_variant (new_type,
2158                                               TYPE_ATTRIBUTES (old_type));
2159   new_type = build_exception_variant (new_type,
2160                                       TYPE_RAISES_EXCEPTIONS (old_type));
2161   TREE_TYPE (decl) = new_type;
2162 }
2163
2164 /* Check to see if the function just declared, as indicated in
2165    DECLARATOR, and in DECL, is a specialization of a function
2166    template.  We may also discover that the declaration is an explicit
2167    instantiation at this point.
2168
2169    Returns DECL, or an equivalent declaration that should be used
2170    instead if all goes well.  Issues an error message if something is
2171    amiss.  Returns error_mark_node if the error is not easily
2172    recoverable.
2173
2174    FLAGS is a bitmask consisting of the following flags:
2175
2176    2: The function has a definition.
2177    4: The function is a friend.
2178
2179    The TEMPLATE_COUNT is the number of references to qualifying
2180    template classes that appeared in the name of the function.  For
2181    example, in
2182
2183      template <class T> struct S { void f(); };
2184      void S<int>::f();
2185
2186    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2187    classes are not counted in the TEMPLATE_COUNT, so that in
2188
2189      template <class T> struct S {};
2190      template <> struct S<int> { void f(); }
2191      template <> void S<int>::f();
2192
2193    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2194    invalid; there should be no template <>.)
2195
2196    If the function is a specialization, it is marked as such via
2197    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2198    is set up correctly, and it is added to the list of specializations
2199    for that template.  */
2200
2201 tree
2202 check_explicit_specialization (tree declarator,
2203                                tree decl,
2204                                int template_count,
2205                                int flags)
2206 {
2207   int have_def = flags & 2;
2208   int is_friend = flags & 4;
2209   int specialization = 0;
2210   int explicit_instantiation = 0;
2211   int member_specialization = 0;
2212   tree ctype = DECL_CLASS_CONTEXT (decl);
2213   tree dname = DECL_NAME (decl);
2214   tmpl_spec_kind tsk;
2215
2216   if (is_friend)
2217     {
2218       if (!processing_specialization)
2219         tsk = tsk_none;
2220       else
2221         tsk = tsk_excessive_parms;
2222     }
2223   else
2224     tsk = current_tmpl_spec_kind (template_count);
2225
2226   switch (tsk)
2227     {
2228     case tsk_none:
2229       if (processing_specialization)
2230         {
2231           specialization = 1;
2232           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2233         }
2234       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2235         {
2236           if (is_friend)
2237             /* This could be something like:
2238
2239                template <class T> void f(T);
2240                class S { friend void f<>(int); }  */
2241             specialization = 1;
2242           else
2243             {
2244               /* This case handles bogus declarations like template <>
2245                  template <class T> void f<int>(); */
2246
2247               error ("template-id %qD in declaration of primary template",
2248                      declarator);
2249               return decl;
2250             }
2251         }
2252       break;
2253
2254     case tsk_invalid_member_spec:
2255       /* The error has already been reported in
2256          check_specialization_scope.  */
2257       return error_mark_node;
2258
2259     case tsk_invalid_expl_inst:
2260       error ("template parameter list used in explicit instantiation");
2261
2262       /* Fall through.  */
2263
2264     case tsk_expl_inst:
2265       if (have_def)
2266         error ("definition provided for explicit instantiation");
2267
2268       explicit_instantiation = 1;
2269       break;
2270
2271     case tsk_excessive_parms:
2272     case tsk_insufficient_parms:
2273       if (tsk == tsk_excessive_parms)
2274         error ("too many template parameter lists in declaration of %qD",
2275                decl);
2276       else if (template_header_count)
2277         error("too few template parameter lists in declaration of %qD", decl);
2278       else
2279         error("explicit specialization of %qD must be introduced by "
2280               "%<template <>%>", decl);
2281
2282       /* Fall through.  */
2283     case tsk_expl_spec:
2284       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2285       if (ctype)
2286         member_specialization = 1;
2287       else
2288         specialization = 1;
2289       break;
2290
2291     case tsk_template:
2292       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2293         {
2294           /* This case handles bogus declarations like template <>
2295              template <class T> void f<int>(); */
2296
2297           if (uses_template_parms (declarator))
2298             error ("function template partial specialization %qD "
2299                    "is not allowed", declarator);
2300           else
2301             error ("template-id %qD in declaration of primary template",
2302                    declarator);
2303           return decl;
2304         }
2305
2306       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2307         /* This is a specialization of a member template, without
2308            specialization the containing class.  Something like:
2309
2310              template <class T> struct S {
2311                template <class U> void f (U);
2312              };
2313              template <> template <class U> void S<int>::f(U) {}
2314
2315            That's a specialization -- but of the entire template.  */
2316         specialization = 1;
2317       break;
2318
2319     default:
2320       gcc_unreachable ();
2321     }
2322
2323   if (specialization || member_specialization)
2324     {
2325       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2326       for (; t; t = TREE_CHAIN (t))
2327         if (TREE_PURPOSE (t))
2328           {
2329             permerror (input_location, 
2330                        "default argument specified in explicit specialization");
2331             break;
2332           }
2333     }
2334
2335   if (specialization || member_specialization || explicit_instantiation)
2336     {
2337       tree tmpl = NULL_TREE;
2338       tree targs = NULL_TREE;
2339
2340       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2341       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2342         {
2343           tree fns;
2344
2345           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2346           if (ctype)
2347             fns = dname;
2348           else
2349             {
2350               /* If there is no class context, the explicit instantiation
2351                  must be at namespace scope.  */
2352               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2353
2354               /* Find the namespace binding, using the declaration
2355                  context.  */
2356               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2357                                            false, true);
2358               if (fns == error_mark_node || !is_overloaded_fn (fns))
2359                 {
2360                   error ("%qD is not a template function", dname);
2361                   fns = error_mark_node;
2362                 }
2363               else
2364                 {
2365                   tree fn = OVL_CURRENT (fns);
2366                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2367                                                 CP_DECL_CONTEXT (fn)))
2368                     error ("%qD is not declared in %qD",
2369                            decl, current_namespace);
2370                 }
2371             }
2372
2373           declarator = lookup_template_function (fns, NULL_TREE);
2374         }
2375
2376       if (declarator == error_mark_node)
2377         return error_mark_node;
2378
2379       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2380         {
2381           if (!explicit_instantiation)
2382             /* A specialization in class scope.  This is invalid,
2383                but the error will already have been flagged by
2384                check_specialization_scope.  */
2385             return error_mark_node;
2386           else
2387             {
2388               /* It's not valid to write an explicit instantiation in
2389                  class scope, e.g.:
2390
2391                    class C { template void f(); }
2392
2393                    This case is caught by the parser.  However, on
2394                    something like:
2395
2396                    template class C { void f(); };
2397
2398                    (which is invalid) we can get here.  The error will be
2399                    issued later.  */
2400               ;
2401             }
2402
2403           return decl;
2404         }
2405       else if (ctype != NULL_TREE
2406                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2407                    IDENTIFIER_NODE))
2408         {
2409           /* Find the list of functions in ctype that have the same
2410              name as the declared function.  */
2411           tree name = TREE_OPERAND (declarator, 0);
2412           tree fns = NULL_TREE;
2413           int idx;
2414
2415           if (constructor_name_p (name, ctype))
2416             {
2417               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2418
2419               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2420                   : !CLASSTYPE_DESTRUCTORS (ctype))
2421                 {
2422                   /* From [temp.expl.spec]:
2423
2424                      If such an explicit specialization for the member
2425                      of a class template names an implicitly-declared
2426                      special member function (clause _special_), the
2427                      program is ill-formed.
2428
2429                      Similar language is found in [temp.explicit].  */
2430                   error ("specialization of implicitly-declared special member function");
2431                   return error_mark_node;
2432                 }
2433
2434               name = is_constructor ? ctor_identifier : dtor_identifier;
2435             }
2436
2437           if (!DECL_CONV_FN_P (decl))
2438             {
2439               idx = lookup_fnfields_1 (ctype, name);
2440               if (idx >= 0)
2441                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2442             }
2443           else
2444             {
2445               VEC(tree,gc) *methods;
2446               tree ovl;
2447
2448               /* For a type-conversion operator, we cannot do a
2449                  name-based lookup.  We might be looking for `operator
2450                  int' which will be a specialization of `operator T'.
2451                  So, we find *all* the conversion operators, and then
2452                  select from them.  */
2453               fns = NULL_TREE;
2454
2455               methods = CLASSTYPE_METHOD_VEC (ctype);
2456               if (methods)
2457                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2458                      VEC_iterate (tree, methods, idx, ovl);
2459                      ++idx)
2460                   {
2461                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2462                       /* There are no more conversion functions.  */
2463                       break;
2464
2465                     /* Glue all these conversion functions together
2466                        with those we already have.  */
2467                     for (; ovl; ovl = OVL_NEXT (ovl))
2468                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2469                   }
2470             }
2471
2472           if (fns == NULL_TREE)
2473             {
2474               error ("no member function %qD declared in %qT", name, ctype);
2475               return error_mark_node;
2476             }
2477           else
2478             TREE_OPERAND (declarator, 0) = fns;
2479         }
2480
2481       /* Figure out what exactly is being specialized at this point.
2482          Note that for an explicit instantiation, even one for a
2483          member function, we cannot tell apriori whether the
2484          instantiation is for a member template, or just a member
2485          function of a template class.  Even if a member template is
2486          being instantiated, the member template arguments may be
2487          elided if they can be deduced from the rest of the
2488          declaration.  */
2489       tmpl = determine_specialization (declarator, decl,
2490                                        &targs,
2491                                        member_specialization,
2492                                        template_count,
2493                                        tsk);
2494
2495       if (!tmpl || tmpl == error_mark_node)
2496         /* We couldn't figure out what this declaration was
2497            specializing.  */
2498         return error_mark_node;
2499       else
2500         {
2501           tree gen_tmpl = most_general_template (tmpl);
2502
2503           if (explicit_instantiation)
2504             {
2505               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2506                  is done by do_decl_instantiation later.  */
2507
2508               int arg_depth = TMPL_ARGS_DEPTH (targs);
2509               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2510
2511               if (arg_depth > parm_depth)
2512                 {
2513                   /* If TMPL is not the most general template (for
2514                      example, if TMPL is a friend template that is
2515                      injected into namespace scope), then there will
2516                      be too many levels of TARGS.  Remove some of them
2517                      here.  */
2518                   int i;
2519                   tree new_targs;
2520
2521                   new_targs = make_tree_vec (parm_depth);
2522                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2523                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2524                       = TREE_VEC_ELT (targs, i);
2525                   targs = new_targs;
2526                 }
2527
2528               return instantiate_template (tmpl, targs, tf_error);
2529             }
2530
2531           /* If we thought that the DECL was a member function, but it
2532              turns out to be specializing a static member function,
2533              make DECL a static member function as well.  */
2534           if (DECL_STATIC_FUNCTION_P (tmpl)
2535               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2536             revert_static_member_fn (decl);
2537
2538           /* If this is a specialization of a member template of a
2539              template class, we want to return the TEMPLATE_DECL, not
2540              the specialization of it.  */
2541           if (tsk == tsk_template)
2542             {
2543               tree result = DECL_TEMPLATE_RESULT (tmpl);
2544               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2545               DECL_INITIAL (result) = NULL_TREE;
2546               if (have_def)
2547                 {
2548                   tree parm;
2549                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2550                   DECL_SOURCE_LOCATION (result)
2551                     = DECL_SOURCE_LOCATION (decl);
2552                   /* We want to use the argument list specified in the
2553                      definition, not in the original declaration.  */
2554                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2555                   for (parm = DECL_ARGUMENTS (result); parm;
2556                        parm = TREE_CHAIN (parm))
2557                     DECL_CONTEXT (parm) = result;
2558                 }
2559               return register_specialization (tmpl, gen_tmpl, targs,
2560                                               is_friend, 0);
2561             }
2562
2563           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2564           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2565
2566           /* Inherit default function arguments from the template
2567              DECL is specializing.  */
2568           copy_default_args_to_explicit_spec (decl);
2569
2570           /* This specialization has the same protection as the
2571              template it specializes.  */
2572           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2573           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2574
2575           /* 7.1.1-1 [dcl.stc]
2576
2577              A storage-class-specifier shall not be specified in an
2578              explicit specialization...
2579
2580              The parser rejects these, so unless action is taken here,
2581              explicit function specializations will always appear with
2582              global linkage.
2583
2584              The action recommended by the C++ CWG in response to C++
2585              defect report 605 is to make the storage class and linkage
2586              of the explicit specialization match the templated function:
2587
2588              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2589            */
2590           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2591             {
2592               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2593               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2594
2595               /* This specialization has the same linkage and visibility as
2596                  the function template it specializes.  */
2597               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2598               if (! TREE_PUBLIC (decl))
2599                 {
2600                   DECL_INTERFACE_KNOWN (decl) = 1;
2601                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2602                 }
2603               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2604               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2605                 {
2606                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2607                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2608                 }
2609             }
2610
2611           /* If DECL is a friend declaration, declared using an
2612              unqualified name, the namespace associated with DECL may
2613              have been set incorrectly.  For example, in:
2614
2615                template <typename T> void f(T);
2616                namespace N {
2617                  struct S { friend void f<int>(int); }
2618                }
2619
2620              we will have set the DECL_CONTEXT for the friend
2621              declaration to N, rather than to the global namespace.  */
2622           if (DECL_NAMESPACE_SCOPE_P (decl))
2623             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2624
2625           if (is_friend && !have_def)
2626             /* This is not really a declaration of a specialization.
2627                It's just the name of an instantiation.  But, it's not
2628                a request for an instantiation, either.  */
2629             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2630           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2631             /* This is indeed a specialization.  In case of constructors
2632                and destructors, we need in-charge and not-in-charge
2633                versions in V3 ABI.  */
2634             clone_function_decl (decl, /*update_method_vec_p=*/0);
2635
2636           /* Register this specialization so that we can find it
2637              again.  */
2638           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2639         }
2640     }
2641
2642   return decl;
2643 }
2644
2645 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2646    parameters.  These are represented in the same format used for
2647    DECL_TEMPLATE_PARMS.  */
2648
2649 int
2650 comp_template_parms (const_tree parms1, const_tree parms2)
2651 {
2652   const_tree p1;
2653   const_tree p2;
2654
2655   if (parms1 == parms2)
2656     return 1;
2657
2658   for (p1 = parms1, p2 = parms2;
2659        p1 != NULL_TREE && p2 != NULL_TREE;
2660        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2661     {
2662       tree t1 = TREE_VALUE (p1);
2663       tree t2 = TREE_VALUE (p2);
2664       int i;
2665
2666       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2667       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2668
2669       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2670         return 0;
2671
2672       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2673         {
2674           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2675           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2676
2677           /* If either of the template parameters are invalid, assume
2678              they match for the sake of error recovery. */
2679           if (parm1 == error_mark_node || parm2 == error_mark_node)
2680             return 1;
2681
2682           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2683             return 0;
2684
2685           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2686               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2687                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2688             continue;
2689           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2690             return 0;
2691         }
2692     }
2693
2694   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2695     /* One set of parameters has more parameters lists than the
2696        other.  */
2697     return 0;
2698
2699   return 1;
2700 }
2701
2702 /* Determine whether PARM is a parameter pack.  */
2703
2704 bool 
2705 template_parameter_pack_p (const_tree parm)
2706 {
2707   /* Determine if we have a non-type template parameter pack.  */
2708   if (TREE_CODE (parm) == PARM_DECL)
2709     return (DECL_TEMPLATE_PARM_P (parm) 
2710             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2711
2712   /* If this is a list of template parameters, we could get a
2713      TYPE_DECL or a TEMPLATE_DECL.  */ 
2714   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2715     parm = TREE_TYPE (parm);
2716
2717   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2718            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2719           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2720 }
2721
2722 /* Determine if T is a function parameter pack.  */
2723
2724 bool
2725 function_parameter_pack_p (const_tree t)
2726 {
2727   if (t && TREE_CODE (t) == PARM_DECL)
2728     return FUNCTION_PARAMETER_PACK_P (t);
2729   return false;
2730 }
2731
2732 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2733    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2734
2735 tree
2736 get_function_template_decl (const_tree primary_func_tmpl_inst)
2737 {
2738   if (! primary_func_tmpl_inst
2739       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2740       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2741     return NULL;
2742
2743   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2744 }
2745
2746 /* Return true iff the function parameter PARAM_DECL was expanded
2747    from the function parameter pack PACK.  */
2748
2749 bool
2750 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2751 {
2752   if (DECL_ARTIFICIAL (param_decl)
2753       || !function_parameter_pack_p (pack))
2754     return false;
2755
2756   /* The parameter pack and its pack arguments have the same
2757      DECL_PARM_INDEX.  */
2758   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2759 }
2760
2761 /* Determine whether ARGS describes a variadic template args list,
2762    i.e., one that is terminated by a template argument pack.  */
2763
2764 static bool 
2765 template_args_variadic_p (tree args)
2766 {
2767   int nargs;
2768   tree last_parm;
2769
2770   if (args == NULL_TREE)
2771     return false;
2772
2773   args = INNERMOST_TEMPLATE_ARGS (args);
2774   nargs = TREE_VEC_LENGTH (args);
2775
2776   if (nargs == 0)
2777     return false;
2778
2779   last_parm = TREE_VEC_ELT (args, nargs - 1);
2780
2781   return ARGUMENT_PACK_P (last_parm);
2782 }
2783
2784 /* Generate a new name for the parameter pack name NAME (an
2785    IDENTIFIER_NODE) that incorporates its */
2786
2787 static tree
2788 make_ith_pack_parameter_name (tree name, int i)
2789 {
2790   /* Munge the name to include the parameter index.  */
2791 #define NUMBUF_LEN 128
2792   char numbuf[NUMBUF_LEN];
2793   char* newname;
2794   int newname_len;
2795
2796   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2797   newname_len = IDENTIFIER_LENGTH (name)
2798                 + strlen (numbuf) + 2;
2799   newname = (char*)alloca (newname_len);
2800   snprintf (newname, newname_len,
2801             "%s#%i", IDENTIFIER_POINTER (name), i);
2802   return get_identifier (newname);
2803 }
2804
2805 /* Return true if T is a primary function
2806    or class template instantiation.  */
2807
2808 bool
2809 primary_template_instantiation_p (const_tree t)
2810 {
2811   if (!t)
2812     return false;
2813
2814   if (TREE_CODE (t) == FUNCTION_DECL)
2815     return DECL_LANG_SPECIFIC (t)
2816            && DECL_TEMPLATE_INSTANTIATION (t)
2817            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2818   else if (CLASS_TYPE_P (t))
2819     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2820            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2821   return false;
2822 }
2823
2824 /* Return true if PARM is a template template parameter.  */
2825
2826 bool
2827 template_template_parameter_p (const_tree parm)
2828 {
2829   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2830 }
2831
2832 /* Return the template parameters of T if T is a
2833    primary template instantiation, NULL otherwise.  */
2834
2835 tree
2836 get_primary_template_innermost_parameters (const_tree t)
2837 {
2838   tree parms = NULL, template_info = NULL;
2839
2840   if ((template_info = get_template_info (t))
2841       && primary_template_instantiation_p (t))
2842     parms = INNERMOST_TEMPLATE_PARMS
2843         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2844
2845   return parms;
2846 }
2847
2848 /* Return the template parameters of the LEVELth level from the full list
2849    of template parameters PARMS.  */
2850
2851 tree
2852 get_template_parms_at_level (tree parms, int level)
2853 {
2854   tree p;
2855   if (!parms
2856       || TREE_CODE (parms) != TREE_LIST
2857       || level > TMPL_PARMS_DEPTH (parms))
2858     return NULL_TREE;
2859
2860   for (p = parms; p; p = TREE_CHAIN (p))
2861     if (TMPL_PARMS_DEPTH (p) == level)
2862       return p;
2863
2864   return NULL_TREE;
2865 }
2866
2867 /* Returns the template arguments of T if T is a template instantiation,
2868    NULL otherwise.  */
2869
2870 tree
2871 get_template_innermost_arguments (const_tree t)
2872 {
2873   tree args = NULL, template_info = NULL;
2874
2875   if ((template_info = get_template_info (t))
2876       && TI_ARGS (template_info))
2877     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2878
2879   return args;
2880 }
2881
2882 /* Return the argument pack elements of T if T is a template argument pack,
2883    NULL otherwise.  */
2884
2885 tree
2886 get_template_argument_pack_elems (const_tree t)
2887 {
2888   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2889       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2890     return NULL;
2891
2892   return ARGUMENT_PACK_ARGS (t);
2893 }
2894
2895 /* Structure used to track the progress of find_parameter_packs_r.  */
2896 struct find_parameter_pack_data 
2897 {
2898   /* TREE_LIST that will contain all of the parameter packs found by
2899      the traversal.  */
2900   tree* parameter_packs;
2901
2902   /* Set of AST nodes that have been visited by the traversal.  */
2903   struct pointer_set_t *visited;
2904 };
2905
2906 /* Identifies all of the argument packs that occur in a template
2907    argument and appends them to the TREE_LIST inside DATA, which is a
2908    find_parameter_pack_data structure. This is a subroutine of
2909    make_pack_expansion and uses_parameter_packs.  */
2910 static tree
2911 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2912 {
2913   tree t = *tp;
2914   struct find_parameter_pack_data* ppd = 
2915     (struct find_parameter_pack_data*)data;
2916   bool parameter_pack_p = false;
2917
2918   /* Identify whether this is a parameter pack or not.  */
2919   switch (TREE_CODE (t))
2920     {
2921     case TEMPLATE_PARM_INDEX:
2922       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2923         parameter_pack_p = true;
2924       break;
2925
2926     case TEMPLATE_TYPE_PARM:
2927     case TEMPLATE_TEMPLATE_PARM:
2928       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2929         parameter_pack_p = true;
2930       break;
2931
2932     case PARM_DECL:
2933       if (FUNCTION_PARAMETER_PACK_P (t))
2934         {
2935           /* We don't want to walk into the type of a PARM_DECL,
2936              because we don't want to see the type parameter pack.  */
2937           *walk_subtrees = 0;
2938           parameter_pack_p = true;
2939         }
2940       break;
2941
2942     default:
2943       /* Not a parameter pack.  */
2944       break;
2945     }
2946
2947   if (parameter_pack_p)
2948     {
2949       /* Add this parameter pack to the list.  */
2950       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2951     }
2952
2953   if (TYPE_P (t))
2954     cp_walk_tree (&TYPE_CONTEXT (t), 
2955                   &find_parameter_packs_r, ppd, ppd->visited);
2956
2957   /* This switch statement will return immediately if we don't find a
2958      parameter pack.  */
2959   switch (TREE_CODE (t)) 
2960     {
2961     case TEMPLATE_PARM_INDEX:
2962       return NULL_TREE;
2963
2964     case BOUND_TEMPLATE_TEMPLATE_PARM:
2965       /* Check the template itself.  */
2966       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2967                     &find_parameter_packs_r, ppd, ppd->visited);
2968       /* Check the template arguments.  */
2969       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2970                     ppd->visited);
2971       *walk_subtrees = 0;
2972       return NULL_TREE;
2973
2974     case TEMPLATE_TYPE_PARM:
2975     case TEMPLATE_TEMPLATE_PARM:
2976       return NULL_TREE;
2977
2978     case PARM_DECL:
2979       return NULL_TREE;
2980
2981     case RECORD_TYPE:
2982       if (TYPE_PTRMEMFUNC_P (t))
2983         return NULL_TREE;
2984       /* Fall through.  */
2985
2986     case UNION_TYPE:
2987     case ENUMERAL_TYPE:
2988       if (TYPE_TEMPLATE_INFO (t))
2989         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
2990                       &find_parameter_packs_r, ppd, ppd->visited);
2991
2992       *walk_subtrees = 0;
2993       return NULL_TREE;
2994
2995     case TEMPLATE_DECL:
2996       cp_walk_tree (&TREE_TYPE (t),
2997                     &find_parameter_packs_r, ppd, ppd->visited);
2998       return NULL_TREE;
2999  
3000     case TYPENAME_TYPE:
3001       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3002                    ppd, ppd->visited);
3003       *walk_subtrees = 0;
3004       return NULL_TREE;
3005       
3006     case TYPE_PACK_EXPANSION:
3007     case EXPR_PACK_EXPANSION:
3008       *walk_subtrees = 0;
3009       return NULL_TREE;
3010
3011     case INTEGER_TYPE:
3012       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3013                     ppd, ppd->visited);
3014       *walk_subtrees = 0;
3015       return NULL_TREE;
3016
3017     case IDENTIFIER_NODE:
3018       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3019                     ppd->visited);
3020       *walk_subtrees = 0;
3021       return NULL_TREE;
3022
3023     default:
3024       return NULL_TREE;
3025     }
3026
3027   return NULL_TREE;
3028 }
3029
3030 /* Determines if the expression or type T uses any parameter packs.  */
3031 bool
3032 uses_parameter_packs (tree t)
3033 {
3034   tree parameter_packs = NULL_TREE;
3035   struct find_parameter_pack_data ppd;
3036   ppd.parameter_packs = &parameter_packs;
3037   ppd.visited = pointer_set_create ();
3038   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3039   pointer_set_destroy (ppd.visited);
3040   return parameter_packs != NULL_TREE;
3041 }
3042
3043 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3044    representation a base-class initializer into a parameter pack
3045    expansion. If all goes well, the resulting node will be an
3046    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3047    respectively.  */
3048 tree 
3049 make_pack_expansion (tree arg)
3050 {
3051   tree result;
3052   tree parameter_packs = NULL_TREE;
3053   bool for_types = false;
3054   struct find_parameter_pack_data ppd;
3055
3056   if (!arg || arg == error_mark_node)
3057     return arg;
3058
3059   if (TREE_CODE (arg) == TREE_LIST)
3060     {
3061       /* The only time we will see a TREE_LIST here is for a base
3062          class initializer.  In this case, the TREE_PURPOSE will be a
3063          _TYPE node (representing the base class expansion we're
3064          initializing) and the TREE_VALUE will be a TREE_LIST
3065          containing the initialization arguments. 
3066
3067          The resulting expansion looks somewhat different from most
3068          expansions. Rather than returning just one _EXPANSION, we
3069          return a TREE_LIST whose TREE_PURPOSE is a
3070          TYPE_PACK_EXPANSION containing the bases that will be
3071          initialized.  The TREE_VALUE will be identical to the
3072          original TREE_VALUE, which is a list of arguments that will
3073          be passed to each base.  We do not introduce any new pack
3074          expansion nodes into the TREE_VALUE (although it is possible
3075          that some already exist), because the TREE_PURPOSE and
3076          TREE_VALUE all need to be expanded together with the same
3077          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3078          resulting TREE_PURPOSE will mention the parameter packs in
3079          both the bases and the arguments to the bases.  */
3080       tree purpose;
3081       tree value;
3082       tree parameter_packs = NULL_TREE;
3083
3084       /* Determine which parameter packs will be used by the base
3085          class expansion.  */
3086       ppd.visited = pointer_set_create ();
3087       ppd.parameter_packs = &parameter_packs;
3088       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3089                     &ppd, ppd.visited);
3090
3091       if (parameter_packs == NULL_TREE)
3092         {
3093           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3094           pointer_set_destroy (ppd.visited);
3095           return error_mark_node;
3096         }
3097
3098       if (TREE_VALUE (arg) != void_type_node)
3099         {
3100           /* Collect the sets of parameter packs used in each of the
3101              initialization arguments.  */
3102           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3103             {
3104               /* Determine which parameter packs will be expanded in this
3105                  argument.  */
3106               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3107                             &ppd, ppd.visited);
3108             }
3109         }
3110
3111       pointer_set_destroy (ppd.visited);
3112
3113       /* Create the pack expansion type for the base type.  */
3114       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3115       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3116       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3117
3118       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3119          they will rarely be compared to anything.  */
3120       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3121
3122       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3123     }
3124
3125   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3126     for_types = true;
3127
3128   /* Build the PACK_EXPANSION_* node.  */
3129   result = for_types
3130      ? cxx_make_type (TYPE_PACK_EXPANSION)
3131      : make_node (EXPR_PACK_EXPANSION);
3132   SET_PACK_EXPANSION_PATTERN (result, arg);
3133   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3134     {
3135       /* Propagate type and const-expression information.  */
3136       TREE_TYPE (result) = TREE_TYPE (arg);
3137       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3138     }
3139   else
3140     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3141        they will rarely be compared to anything.  */
3142     SET_TYPE_STRUCTURAL_EQUALITY (result);
3143
3144   /* Determine which parameter packs will be expanded.  */
3145   ppd.parameter_packs = &parameter_packs;
3146   ppd.visited = pointer_set_create ();
3147   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3148   pointer_set_destroy (ppd.visited);
3149
3150   /* Make sure we found some parameter packs.  */
3151   if (parameter_packs == NULL_TREE)
3152     {
3153       if (TYPE_P (arg))
3154         error ("expansion pattern %<%T%> contains no argument packs", arg);
3155       else
3156         error ("expansion pattern %<%E%> contains no argument packs", arg);
3157       return error_mark_node;
3158     }
3159   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3160
3161   return result;
3162 }
3163
3164 /* Checks T for any "bare" parameter packs, which have not yet been
3165    expanded, and issues an error if any are found. This operation can
3166    only be done on full expressions or types (e.g., an expression
3167    statement, "if" condition, etc.), because we could have expressions like:
3168
3169      foo(f(g(h(args)))...)
3170
3171    where "args" is a parameter pack. check_for_bare_parameter_packs
3172    should not be called for the subexpressions args, h(args),
3173    g(h(args)), or f(g(h(args))), because we would produce erroneous
3174    error messages. 
3175
3176    Returns TRUE and emits an error if there were bare parameter packs,
3177    returns FALSE otherwise.  */
3178 bool 
3179 check_for_bare_parameter_packs (tree t)
3180 {
3181   tree parameter_packs = NULL_TREE;
3182   struct find_parameter_pack_data ppd;
3183
3184   if (!processing_template_decl || !t || t == error_mark_node)
3185     return false;
3186
3187   if (TREE_CODE (t) == TYPE_DECL)
3188     t = TREE_TYPE (t);
3189
3190   ppd.parameter_packs = &parameter_packs;
3191   ppd.visited = pointer_set_create ();
3192   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3193   pointer_set_destroy (ppd.visited);
3194
3195   if (parameter_packs) 
3196     {
3197       error ("parameter packs not expanded with %<...%>:");
3198       while (parameter_packs)
3199         {
3200           tree pack = TREE_VALUE (parameter_packs);
3201           tree name = NULL_TREE;
3202
3203           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3204               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3205             name = TYPE_NAME (pack);
3206           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3207             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3208           else
3209             name = DECL_NAME (pack);
3210
3211           if (name)
3212             inform (input_location, "        %qD", name);
3213           else
3214             inform (input_location, "        <anonymous>");
3215
3216           parameter_packs = TREE_CHAIN (parameter_packs);
3217         }
3218
3219       return true;
3220     }
3221
3222   return false;
3223 }
3224
3225 /* Expand any parameter packs that occur in the template arguments in
3226    ARGS.  */
3227 tree
3228 expand_template_argument_pack (tree args)
3229 {
3230   tree result_args = NULL_TREE;
3231   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3232   int num_result_args = -1;
3233   int non_default_args_count = -1;
3234
3235   /* First, determine if we need to expand anything, and the number of
3236      slots we'll need.  */
3237   for (in_arg = 0; in_arg < nargs; ++in_arg)
3238     {
3239       tree arg = TREE_VEC_ELT (args, in_arg);
3240       if (arg == NULL_TREE)
3241         return args;
3242       if (ARGUMENT_PACK_P (arg))
3243         {
3244           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3245           if (num_result_args < 0)
3246             num_result_args = in_arg + num_packed;
3247           else
3248             num_result_args += num_packed;
3249         }
3250       else
3251         {
3252           if (num_result_args >= 0)
3253             num_result_args++;
3254         }
3255     }
3256
3257   /* If no expansion is necessary, we're done.  */
3258   if (num_result_args < 0)
3259     return args;
3260
3261   /* Expand arguments.  */
3262   result_args = make_tree_vec (num_result_args);
3263   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3264     non_default_args_count =
3265       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3266   for (in_arg = 0; in_arg < nargs; ++in_arg)
3267     {
3268       tree arg = TREE_VEC_ELT (args, in_arg);
3269       if (ARGUMENT_PACK_P (arg))
3270         {
3271           tree packed = ARGUMENT_PACK_ARGS (arg);
3272           int i, num_packed = TREE_VEC_LENGTH (packed);
3273           for (i = 0; i < num_packed; ++i, ++out_arg)
3274             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3275           if (non_default_args_count > 0)
3276             non_default_args_count += num_packed;
3277         }
3278       else
3279         {
3280           TREE_VEC_ELT (result_args, out_arg) = arg;
3281           ++out_arg;
3282         }
3283     }
3284   if (non_default_args_count >= 0)
3285     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3286   return result_args;
3287 }
3288
3289 /* Checks if DECL shadows a template parameter.
3290
3291    [temp.local]: A template-parameter shall not be redeclared within its
3292    scope (including nested scopes).
3293
3294    Emits an error and returns TRUE if the DECL shadows a parameter,
3295    returns FALSE otherwise.  */
3296
3297 bool
3298 check_template_shadow (tree decl)
3299 {
3300   tree olddecl;
3301
3302   /* If we're not in a template, we can't possibly shadow a template
3303      parameter.  */
3304   if (!current_template_parms)
3305     return true;
3306
3307   /* Figure out what we're shadowing.  */
3308   if (TREE_CODE (decl) == OVERLOAD)
3309     decl = OVL_CURRENT (decl);
3310   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3311
3312   /* If there's no previous binding for this name, we're not shadowing
3313      anything, let alone a template parameter.  */
3314   if (!olddecl)
3315     return true;
3316
3317   /* If we're not shadowing a template parameter, we're done.  Note
3318      that OLDDECL might be an OVERLOAD (or perhaps even an
3319      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3320      node.  */
3321   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3322     return true;
3323
3324   /* We check for decl != olddecl to avoid bogus errors for using a
3325      name inside a class.  We check TPFI to avoid duplicate errors for
3326      inline member templates.  */
3327   if (decl == olddecl
3328       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3329     return true;
3330
3331   error ("declaration of %q+#D", decl);
3332   error (" shadows template parm %q+#D", olddecl);
3333   return false;
3334 }
3335
3336 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3337    ORIG_LEVEL, DECL, and TYPE.  */
3338
3339 static tree
3340 build_template_parm_index (int index,
3341                            int level,
3342                            int orig_level,
3343                            tree decl,
3344                            tree type)
3345 {
3346   tree t = make_node (TEMPLATE_PARM_INDEX);
3347   TEMPLATE_PARM_IDX (t) = index;
3348   TEMPLATE_PARM_LEVEL (t) = level;
3349   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3350   TEMPLATE_PARM_DECL (t) = decl;
3351   TREE_TYPE (t) = type;
3352   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3353   TREE_READONLY (t) = TREE_READONLY (decl);
3354
3355   return t;
3356 }
3357
3358 /* Find the canonical type parameter for the given template type
3359    parameter.  Returns the canonical type parameter, which may be TYPE
3360    if no such parameter existed.  */
3361 static tree
3362 canonical_type_parameter (tree type)
3363 {
3364   tree list;
3365   int idx = TEMPLATE_TYPE_IDX (type);
3366   if (!canonical_template_parms)
3367     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3368
3369   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3370     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3371
3372   list = VEC_index (tree, canonical_template_parms, idx);
3373   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3374     list = TREE_CHAIN (list);
3375
3376   if (list)
3377     return TREE_VALUE (list);
3378   else
3379     {
3380       VEC_replace(tree, canonical_template_parms, idx,
3381                   tree_cons (NULL_TREE, type, 
3382                              VEC_index (tree, canonical_template_parms, idx)));
3383       return type;
3384     }
3385 }
3386
3387 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3388    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3389    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3390    new one is created.  */
3391
3392 static tree
3393 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3394                             tsubst_flags_t complain)
3395 {
3396   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3397       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3398           != TEMPLATE_PARM_LEVEL (index) - levels)
3399       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3400     {
3401       tree orig_decl = TEMPLATE_PARM_DECL (index);
3402       tree decl, t;
3403
3404       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3405                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3406       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3407       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3408       DECL_ARTIFICIAL (decl) = 1;
3409       SET_DECL_TEMPLATE_PARM_P (decl);
3410
3411       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3412                                      TEMPLATE_PARM_LEVEL (index) - levels,
3413                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3414                                      decl, type);
3415       TEMPLATE_PARM_DESCENDANTS (index) = t;
3416       TEMPLATE_PARM_PARAMETER_PACK (t) 
3417         = TEMPLATE_PARM_PARAMETER_PACK (index);
3418
3419         /* Template template parameters need this.  */
3420       if (TREE_CODE (decl) == TEMPLATE_DECL)
3421         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3422           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3423            args, complain);
3424     }
3425
3426   return TEMPLATE_PARM_DESCENDANTS (index);
3427 }
3428
3429 /* Process information from new template parameter PARM and append it to the
3430    LIST being built.  This new parameter is a non-type parameter iff
3431    IS_NON_TYPE is true. This new parameter is a parameter
3432    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3433    PARM_LOC.  */
3434
3435 tree
3436 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3437                        bool is_parameter_pack)
3438 {
3439   tree decl = 0;
3440   tree defval;
3441   tree err_parm_list;
3442   int idx = 0;
3443
3444   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3445   defval = TREE_PURPOSE (parm);
3446
3447   if (list)
3448     {
3449       tree p = tree_last (list);
3450
3451       if (p && TREE_VALUE (p) != error_mark_node)
3452         {
3453           p = TREE_VALUE (p);
3454           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3455             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3456           else
3457             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3458         }
3459
3460       ++idx;
3461     }
3462   else
3463     idx = 0;
3464
3465   if (is_non_type)
3466     {
3467       parm = TREE_VALUE (parm);
3468
3469       SET_DECL_TEMPLATE_PARM_P (parm);
3470
3471       if (TREE_TYPE (parm) == error_mark_node)
3472         {
3473           err_parm_list = build_tree_list (defval, parm);
3474           TREE_VALUE (err_parm_list) = error_mark_node;
3475            return chainon (list, err_parm_list);
3476         }
3477       else
3478       {
3479         /* [temp.param]
3480
3481            The top-level cv-qualifiers on the template-parameter are
3482            ignored when determining its type.  */
3483         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3484         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3485           {
3486             err_parm_list = build_tree_list (defval, parm);
3487             TREE_VALUE (err_parm_list) = error_mark_node;
3488              return chainon (list, err_parm_list);
3489           }
3490
3491         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3492           {
3493             /* This template parameter is not a parameter pack, but it
3494                should be. Complain about "bare" parameter packs.  */
3495             check_for_bare_parameter_packs (TREE_TYPE (parm));
3496             
3497             /* Recover by calling this a parameter pack.  */
3498             is_parameter_pack = true;
3499           }
3500       }
3501
3502       /* A template parameter is not modifiable.  */
3503       TREE_CONSTANT (parm) = 1;
3504       TREE_READONLY (parm) = 1;
3505       decl = build_decl (parm_loc,
3506                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3507       TREE_CONSTANT (decl) = 1;
3508       TREE_READONLY (decl) = 1;
3509       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3510         = build_template_parm_index (idx, processing_template_decl,
3511                                      processing_template_decl,
3512                                      decl, TREE_TYPE (parm));
3513
3514       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3515         = is_parameter_pack;
3516     }
3517   else
3518     {
3519       tree t;
3520       parm = TREE_VALUE (TREE_VALUE (parm));
3521
3522       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3523         {
3524           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3525           /* This is for distinguishing between real templates and template
3526              template parameters */
3527           TREE_TYPE (parm) = t;
3528           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3529           decl = parm;
3530         }
3531       else
3532         {
3533           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3534           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3535           decl = build_decl (parm_loc,
3536                              TYPE_DECL, parm, t);
3537         }
3538
3539       TYPE_NAME (t) = decl;
3540       TYPE_STUB_DECL (t) = decl;
3541       parm = decl;
3542       TEMPLATE_TYPE_PARM_INDEX (t)
3543         = build_template_parm_index (idx, processing_template_decl,
3544                                      processing_template_decl,
3545                                      decl, TREE_TYPE (parm));
3546       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3547       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3548     }
3549   DECL_ARTIFICIAL (decl) = 1;
3550   SET_DECL_TEMPLATE_PARM_P (decl);
3551   pushdecl (decl);
3552   parm = build_tree_list (defval, parm);
3553   return chainon (list, parm);
3554 }
3555
3556 /* The end of a template parameter list has been reached.  Process the
3557    tree list into a parameter vector, converting each parameter into a more
3558    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3559    as PARM_DECLs.  */
3560
3561 tree
3562 end_template_parm_list (tree parms)
3563 {
3564   int nparms;
3565   tree parm, next;
3566   tree saved_parmlist = make_tree_vec (list_length (parms));
3567
3568   current_template_parms
3569     = tree_cons (size_int (processing_template_decl),
3570                  saved_parmlist, current_template_parms);
3571
3572   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3573     {
3574       next = TREE_CHAIN (parm);
3575       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3576       TREE_CHAIN (parm) = NULL_TREE;
3577       if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL)
3578         TEMPLATE_TYPE_PARM_SIBLING_PARMS (TREE_TYPE (TREE_VALUE (parm))) =
3579               current_template_parms;
3580     }
3581
3582   --processing_template_parmlist;
3583
3584   return saved_parmlist;
3585 }
3586
3587 /* end_template_decl is called after a template declaration is seen.  */
3588
3589 void
3590 end_template_decl (void)
3591 {
3592   reset_specialization ();
3593
3594   if (! processing_template_decl)
3595     return;
3596
3597   /* This matches the pushlevel in begin_template_parm_list.  */
3598   finish_scope ();
3599
3600   --processing_template_decl;
3601   current_template_parms = TREE_CHAIN (current_template_parms);
3602 }
3603
3604 /* Within the declaration of a template, return all levels of template
3605    parameters that apply.  The template parameters are represented as
3606    a TREE_VEC, in the form documented in cp-tree.h for template
3607    arguments.  */
3608
3609 static tree
3610 current_template_args (void)
3611 {
3612   tree header;
3613   tree args = NULL_TREE;
3614   int length = TMPL_PARMS_DEPTH (current_template_parms);
3615   int l = length;
3616
3617   /* If there is only one level of template parameters, we do not
3618      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3619      TREE_VEC containing the arguments.  */
3620   if (length > 1)
3621     args = make_tree_vec (length);
3622
3623   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3624     {
3625       tree a = copy_node (TREE_VALUE (header));
3626       int i;
3627
3628       TREE_TYPE (a) = NULL_TREE;
3629       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3630         {
3631           tree t = TREE_VEC_ELT (a, i);
3632
3633           /* T will be a list if we are called from within a
3634              begin/end_template_parm_list pair, but a vector directly
3635              if within a begin/end_member_template_processing pair.  */
3636           if (TREE_CODE (t) == TREE_LIST)
3637             {
3638               t = TREE_VALUE (t);
3639
3640               if (!error_operand_p (t))
3641                 {
3642                   if (TREE_CODE (t) == TYPE_DECL
3643                       || TREE_CODE (t) == TEMPLATE_DECL)
3644                     {
3645                       t = TREE_TYPE (t);
3646                       
3647                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3648                         {
3649                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3650                              with a single element, which expands T.  */
3651                           tree vec = make_tree_vec (1);
3652 #ifdef ENABLE_CHECKING
3653                           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3654                                 (vec, TREE_VEC_LENGTH (vec));
3655 #endif
3656                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3657                           
3658                           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3659                           SET_ARGUMENT_PACK_ARGS (t, vec);
3660                         }
3661                     }
3662                   else
3663                     {
3664                       t = DECL_INITIAL (t);
3665                       
3666                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3667                         {
3668                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3669                              with a single element, which expands T.  */
3670                           tree vec = make_tree_vec (1);
3671                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3672 #ifdef ENABLE_CHECKING
3673                           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3674                                 (vec, TREE_VEC_LENGTH (vec));
3675 #endif
3676                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3677                           
3678                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3679                           SET_ARGUMENT_PACK_ARGS (t, vec);
3680                           TREE_TYPE (t) = type;
3681                         }
3682                     }
3683                   TREE_VEC_ELT (a, i) = t;
3684                 }
3685             }
3686         }
3687
3688 #ifdef ENABLE_CHECKING
3689       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
3690 #endif
3691
3692       if (length > 1)
3693         TREE_VEC_ELT (args, --l) = a;
3694       else
3695         args = a;
3696     }
3697
3698   return args;
3699 }
3700
3701 /* Update the declared TYPE by doing any lookups which were thought to be
3702    dependent, but are not now that we know the SCOPE of the declarator.  */
3703
3704 tree
3705 maybe_update_decl_type (tree orig_type, tree scope)
3706 {
3707   tree type = orig_type;
3708
3709   if (type == NULL_TREE)
3710     return type;
3711
3712   if (TREE_CODE (orig_type) == TYPE_DECL)
3713     type = TREE_TYPE (type);
3714
3715   if (scope && TYPE_P (scope) && dependent_type_p (scope)
3716       && dependent_type_p (type)
3717       /* Don't bother building up the args in this case.  */
3718       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
3719     {
3720       /* tsubst in the args corresponding to the template parameters,
3721          including auto if present.  Most things will be unchanged, but
3722          make_typename_type and tsubst_qualified_id will resolve
3723          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
3724       tree args = current_template_args ();
3725       tree auto_node = type_uses_auto (type);
3726       tree pushed;
3727       if (auto_node)
3728         {
3729           tree auto_vec = make_tree_vec (1);
3730           TREE_VEC_ELT (auto_vec, 0) = auto_node;
3731           args = add_to_template_args (args, auto_vec);
3732         }
3733       pushed = push_scope (scope);
3734       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
3735       if (pushed)
3736         pop_scope (scope);
3737     }
3738
3739   if (type == error_mark_node)
3740     return orig_type;
3741
3742   if (TREE_CODE (orig_type) == TYPE_DECL)
3743     {
3744       if (same_type_p (type, TREE_TYPE (orig_type)))
3745         type = orig_type;
3746       else
3747         type = TYPE_NAME (type);
3748     }
3749   return type;
3750 }
3751
3752 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3753    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3754    a member template.  Used by push_template_decl below.  */
3755
3756 static tree
3757 build_template_decl (tree decl, tree parms, bool member_template_p)
3758 {
3759   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3760   DECL_TEMPLATE_PARMS (tmpl) = parms;
3761   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3762   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3763
3764   return tmpl;
3765 }
3766
3767 struct template_parm_data
3768 {
3769   /* The level of the template parameters we are currently
3770      processing.  */
3771   int level;
3772
3773   /* The index of the specialization argument we are currently
3774      processing.  */
3775   int current_arg;
3776
3777   /* An array whose size is the number of template parameters.  The
3778      elements are nonzero if the parameter has been used in any one
3779      of the arguments processed so far.  */
3780   int* parms;
3781
3782   /* An array whose size is the number of template arguments.  The
3783      elements are nonzero if the argument makes use of template
3784      parameters of this level.  */
3785   int* arg_uses_template_parms;
3786 };
3787
3788 /* Subroutine of push_template_decl used to see if each template
3789    parameter in a partial specialization is used in the explicit
3790    argument list.  If T is of the LEVEL given in DATA (which is
3791    treated as a template_parm_data*), then DATA->PARMS is marked
3792    appropriately.  */
3793
3794 static int
3795 mark_template_parm (tree t, void* data)
3796 {
3797   int level;
3798   int idx;
3799   struct template_parm_data* tpd = (struct template_parm_data*) data;
3800
3801   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3802     {
3803       level = TEMPLATE_PARM_LEVEL (t);
3804       idx = TEMPLATE_PARM_IDX (t);
3805     }
3806   else
3807     {
3808       level = TEMPLATE_TYPE_LEVEL (t);
3809       idx = TEMPLATE_TYPE_IDX (t);
3810     }
3811
3812   if (level == tpd->level)
3813     {
3814       tpd->parms[idx] = 1;
3815       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3816     }
3817
3818   /* Return zero so that for_each_template_parm will continue the
3819      traversal of the tree; we want to mark *every* template parm.  */
3820   return 0;
3821 }
3822
3823 /* Process the partial specialization DECL.  */
3824
3825 static tree
3826 process_partial_specialization (tree decl)
3827 {
3828   tree type = TREE_TYPE (decl);
3829   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3830   tree specargs = CLASSTYPE_TI_ARGS (type);
3831   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3832   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3833   tree inner_parms;
3834   int nargs = TREE_VEC_LENGTH (inner_args);
3835   int ntparms;
3836   int  i;
3837   bool did_error_intro = false;
3838   struct template_parm_data tpd;
3839   struct template_parm_data tpd2;
3840
3841   gcc_assert (current_template_parms);
3842
3843   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3844   ntparms = TREE_VEC_LENGTH (inner_parms);
3845
3846   /* We check that each of the template parameters given in the
3847      partial specialization is used in the argument list to the
3848      specialization.  For example:
3849
3850        template <class T> struct S;
3851        template <class T> struct S<T*>;
3852
3853      The second declaration is OK because `T*' uses the template
3854      parameter T, whereas
3855
3856        template <class T> struct S<int>;
3857
3858      is no good.  Even trickier is:
3859
3860        template <class T>
3861        struct S1
3862        {
3863           template <class U>
3864           struct S2;
3865           template <class U>
3866           struct S2<T>;
3867        };
3868
3869      The S2<T> declaration is actually invalid; it is a
3870      full-specialization.  Of course,
3871
3872           template <class U>
3873           struct S2<T (*)(U)>;
3874
3875      or some such would have been OK.  */
3876   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3877   tpd.parms = XALLOCAVEC (int, ntparms);
3878   memset (tpd.parms, 0, sizeof (int) * ntparms);
3879
3880   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
3881   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3882   for (i = 0; i < nargs; ++i)
3883     {
3884       tpd.current_arg = i;
3885       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3886                               &mark_template_parm,
3887                               &tpd,
3888                               NULL,
3889                               /*include_nondeduced_p=*/false);
3890     }
3891   for (i = 0; i < ntparms; ++i)
3892     if (tpd.parms[i] == 0)
3893       {
3894         /* One of the template parms was not used in the
3895            specialization.  */
3896         if (!did_error_intro)
3897           {
3898             error ("template parameters not used in partial specialization:");
3899             did_error_intro = true;
3900           }
3901
3902         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3903       }
3904
3905   if (did_error_intro)
3906     return error_mark_node;
3907
3908   /* [temp.class.spec]
3909
3910      The argument list of the specialization shall not be identical to
3911      the implicit argument list of the primary template.  */
3912   if (comp_template_args
3913       (inner_args,
3914        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3915                                                    (maintmpl)))))
3916     error ("partial specialization %qT does not specialize any template arguments", type);
3917
3918   /* [temp.class.spec]
3919
3920      A partially specialized non-type argument expression shall not
3921      involve template parameters of the partial specialization except
3922      when the argument expression is a simple identifier.
3923
3924      The type of a template parameter corresponding to a specialized
3925      non-type argument shall not be dependent on a parameter of the
3926      specialization. 
3927
3928      Also, we verify that pack expansions only occur at the
3929      end of the argument list.  */
3930   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3931   tpd2.parms = 0;
3932   for (i = 0; i < nargs; ++i)
3933     {
3934       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3935       tree arg = TREE_VEC_ELT (inner_args, i);
3936       tree packed_args = NULL_TREE;
3937       int j, len = 1;
3938
3939       if (ARGUMENT_PACK_P (arg))
3940         {
3941           /* Extract the arguments from the argument pack. We'll be
3942              iterating over these in the following loop.  */
3943           packed_args = ARGUMENT_PACK_ARGS (arg);
3944           len = TREE_VEC_LENGTH (packed_args);
3945         }
3946
3947       for (j = 0; j < len; j++)
3948         {
3949           if (packed_args)
3950             /* Get the Jth argument in the parameter pack.  */
3951             arg = TREE_VEC_ELT (packed_args, j);
3952
3953           if (PACK_EXPANSION_P (arg))
3954             {
3955               /* Pack expansions must come at the end of the
3956                  argument list.  */
3957               if ((packed_args && j < len - 1)
3958                   || (!packed_args && i < nargs - 1))
3959                 {
3960                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3961                     error ("parameter pack argument %qE must be at the "
3962                            "end of the template argument list", arg);
3963                   else
3964                     error ("parameter pack argument %qT must be at the "
3965                            "end of the template argument list", arg);
3966                 }
3967             }
3968
3969           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3970             /* We only care about the pattern.  */
3971             arg = PACK_EXPANSION_PATTERN (arg);
3972
3973           if (/* These first two lines are the `non-type' bit.  */
3974               !TYPE_P (arg)
3975               && TREE_CODE (arg) != TEMPLATE_DECL
3976               /* This next line is the `argument expression is not just a
3977                  simple identifier' condition and also the `specialized
3978                  non-type argument' bit.  */
3979               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3980             {
3981               if ((!packed_args && tpd.arg_uses_template_parms[i])
3982                   || (packed_args && uses_template_parms (arg)))
3983                 error ("template argument %qE involves template parameter(s)",
3984                        arg);
3985               else 
3986                 {
3987                   /* Look at the corresponding template parameter,
3988                      marking which template parameters its type depends
3989                      upon.  */
3990                   tree type = TREE_TYPE (parm);
3991
3992                   if (!tpd2.parms)
3993                     {
3994                       /* We haven't yet initialized TPD2.  Do so now.  */
3995                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
3996                       /* The number of parameters here is the number in the
3997                          main template, which, as checked in the assertion
3998                          above, is NARGS.  */
3999                       tpd2.parms = XALLOCAVEC (int, nargs);
4000                       tpd2.level = 
4001                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4002                     }
4003
4004                   /* Mark the template parameters.  But this time, we're
4005                      looking for the template parameters of the main
4006                      template, not in the specialization.  */
4007                   tpd2.current_arg = i;
4008                   tpd2.arg_uses_template_parms[i] = 0;
4009                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4010                   for_each_template_parm (type,
4011                                           &mark_template_parm,
4012                                           &tpd2,
4013                                           NULL,
4014                                           /*include_nondeduced_p=*/false);
4015
4016                   if (tpd2.arg_uses_template_parms [i])
4017                     {
4018                       /* The type depended on some template parameters.
4019                          If they are fully specialized in the
4020                          specialization, that's OK.  */
4021                       int j;
4022                       int count = 0;
4023                       for (j = 0; j < nargs; ++j)
4024                         if (tpd2.parms[j] != 0
4025                             && tpd.arg_uses_template_parms [j])
4026                           ++count;
4027                       if (count != 0)
4028                         error_n (input_location, count,
4029                                  "type %qT of template argument %qE depends "
4030                                  "on a template parameter",
4031                                  "type %qT of template argument %qE depends "
4032                                  "on template parameters",
4033                                  type,
4034                                  arg);
4035                     }
4036                 }
4037             }
4038         }
4039     }
4040
4041   /* We should only get here once.  */
4042   gcc_assert (!COMPLETE_TYPE_P (type));
4043
4044   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4045     = tree_cons (specargs, inner_parms,
4046                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4047   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4048   return decl;
4049 }
4050
4051 /* Check that a template declaration's use of default arguments and
4052    parameter packs is not invalid.  Here, PARMS are the template
4053    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4054    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4055    specialization.
4056    
4057
4058    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4059    declaration (but not a definition); 1 indicates a declaration, 2
4060    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4061    emitted for extraneous default arguments.
4062
4063    Returns TRUE if there were no errors found, FALSE otherwise. */
4064
4065 bool
4066 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4067                          int is_partial, int is_friend_decl)
4068 {
4069   const char *msg;
4070   int last_level_to_check;
4071   tree parm_level;
4072   bool no_errors = true;
4073
4074   /* [temp.param]
4075
4076      A default template-argument shall not be specified in a
4077      function template declaration or a function template definition, nor
4078      in the template-parameter-list of the definition of a member of a
4079      class template.  */
4080
4081   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4082     /* You can't have a function template declaration in a local
4083        scope, nor you can you define a member of a class template in a
4084        local scope.  */
4085     return true;
4086
4087   if (current_class_type
4088       && !TYPE_BEING_DEFINED (current_class_type)
4089       && DECL_LANG_SPECIFIC (decl)
4090       && DECL_DECLARES_FUNCTION_P (decl)
4091       /* If this is either a friend defined in the scope of the class
4092          or a member function.  */
4093       && (DECL_FUNCTION_MEMBER_P (decl)
4094           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4095           : DECL_FRIEND_CONTEXT (decl)
4096           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4097           : false)
4098       /* And, if it was a member function, it really was defined in
4099          the scope of the class.  */
4100       && (!DECL_FUNCTION_MEMBER_P (decl)
4101           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4102     /* We already checked these parameters when the template was
4103        declared, so there's no need to do it again now.  This function
4104        was defined in class scope, but we're processing it's body now
4105        that the class is complete.  */
4106     return true;
4107
4108   /* Core issue 226 (C++0x only): the following only applies to class
4109      templates.  */
4110   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4111     {
4112       /* [temp.param]
4113
4114          If a template-parameter has a default template-argument, all
4115          subsequent template-parameters shall have a default
4116          template-argument supplied.  */
4117       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4118         {
4119           tree inner_parms = TREE_VALUE (parm_level);
4120           int ntparms = TREE_VEC_LENGTH (inner_parms);
4121           int seen_def_arg_p = 0;
4122           int i;
4123
4124           for (i = 0; i < ntparms; ++i)
4125             {
4126               tree parm = TREE_VEC_ELT (inner_parms, i);
4127
4128               if (parm == error_mark_node)
4129                 continue;
4130
4131               if (TREE_PURPOSE (parm))
4132                 seen_def_arg_p = 1;
4133               else if (seen_def_arg_p
4134                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4135                 {
4136                   error ("no default argument for %qD", TREE_VALUE (parm));
4137                   /* For better subsequent error-recovery, we indicate that
4138                      there should have been a default argument.  */
4139                   TREE_PURPOSE (parm) = error_mark_node;
4140                   no_errors = false;
4141                 }
4142               else if (is_primary
4143                        && !is_partial
4144                        && !is_friend_decl
4145                        /* Don't complain about an enclosing partial
4146                           specialization.  */
4147                        && parm_level == parms
4148                        && TREE_CODE (decl) == TYPE_DECL
4149                        && i < ntparms - 1
4150                        && template_parameter_pack_p (TREE_VALUE (parm)))
4151                 {
4152                   /* A primary class template can only have one
4153                      parameter pack, at the end of the template
4154                      parameter list.  */
4155
4156                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4157                     error ("parameter pack %qE must be at the end of the"
4158                            " template parameter list", TREE_VALUE (parm));
4159                   else
4160                     error ("parameter pack %qT must be at the end of the"
4161                            " template parameter list", 
4162                            TREE_TYPE (TREE_VALUE (parm)));
4163
4164                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4165                     = error_mark_node;
4166                   no_errors = false;
4167                 }
4168             }
4169         }
4170     }
4171
4172   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4173       || is_partial 
4174       || !is_primary
4175       || is_friend_decl)
4176     /* For an ordinary class template, default template arguments are
4177        allowed at the innermost level, e.g.:
4178          template <class T = int>
4179          struct S {};
4180        but, in a partial specialization, they're not allowed even
4181        there, as we have in [temp.class.spec]:
4182
4183          The template parameter list of a specialization shall not
4184          contain default template argument values.
4185
4186        So, for a partial specialization, or for a function template
4187        (in C++98/C++03), we look at all of them.  */
4188     ;
4189   else
4190     /* But, for a primary class template that is not a partial
4191        specialization we look at all template parameters except the
4192        innermost ones.  */
4193     parms = TREE_CHAIN (parms);
4194
4195   /* Figure out what error message to issue.  */
4196   if (is_friend_decl == 2)
4197     msg = G_("default template arguments may not be used in function template "
4198              "friend re-declaration");
4199   else if (is_friend_decl)
4200     msg = G_("default template arguments may not be used in function template "
4201              "friend declarations");
4202   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4203     msg = G_("default template arguments may not be used in function templates "
4204              "without -std=c++0x or -std=gnu++0x");
4205   else if (is_partial)
4206     msg = G_("default template arguments may not be used in "
4207              "partial specializations");
4208   else
4209     msg = G_("default argument for template parameter for class enclosing %qD");
4210
4211   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4212     /* If we're inside a class definition, there's no need to
4213        examine the parameters to the class itself.  On the one
4214        hand, they will be checked when the class is defined, and,
4215        on the other, default arguments are valid in things like:
4216          template <class T = double>
4217          struct S { template <class U> void f(U); };
4218        Here the default argument for `S' has no bearing on the
4219        declaration of `f'.  */
4220     last_level_to_check = template_class_depth (current_class_type) + 1;
4221   else
4222     /* Check everything.  */
4223     last_level_to_check = 0;
4224
4225   for (parm_level = parms;
4226        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4227        parm_level = TREE_CHAIN (parm_level))
4228     {
4229       tree inner_parms = TREE_VALUE (parm_level);
4230       int i;
4231       int ntparms;
4232
4233       ntparms = TREE_VEC_LENGTH (inner_parms);
4234       for (i = 0; i < ntparms; ++i)
4235         {
4236           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4237             continue;
4238
4239           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4240             {
4241               if (msg)
4242                 {
4243                   no_errors = false;
4244                   if (is_friend_decl == 2)
4245                     return no_errors;
4246
4247                   error (msg, decl);
4248                   msg = 0;
4249                 }
4250
4251               /* Clear out the default argument so that we are not
4252                  confused later.  */
4253               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4254             }
4255         }
4256
4257       /* At this point, if we're still interested in issuing messages,
4258          they must apply to classes surrounding the object declared.  */
4259       if (msg)
4260         msg = G_("default argument for template parameter for class "
4261                  "enclosing %qD");
4262     }
4263
4264   return no_errors;
4265 }
4266
4267 /* Worker for push_template_decl_real, called via
4268    for_each_template_parm.  DATA is really an int, indicating the
4269    level of the parameters we are interested in.  If T is a template
4270    parameter of that level, return nonzero.  */
4271
4272 static int
4273 template_parm_this_level_p (tree t, void* data)
4274 {
4275   int this_level = *(int *)data;
4276   int level;
4277
4278   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4279     level = TEMPLATE_PARM_LEVEL (t);
4280   else
4281     level = TEMPLATE_TYPE_LEVEL (t);
4282   return level == this_level;
4283 }
4284
4285 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4286    parameters given by current_template_args, or reuses a
4287    previously existing one, if appropriate.  Returns the DECL, or an
4288    equivalent one, if it is replaced via a call to duplicate_decls.
4289
4290    If IS_FRIEND is true, DECL is a friend declaration.  */
4291
4292 tree
4293 push_template_decl_real (tree decl, bool is_friend)
4294 {
4295   tree tmpl;
4296   tree args;
4297   tree info;
4298   tree ctx;
4299   int primary;
4300   int is_partial;
4301   int new_template_p = 0;
4302   /* True if the template is a member template, in the sense of
4303      [temp.mem].  */
4304   bool member_template_p = false;
4305
4306   if (decl == error_mark_node || !current_template_parms)
4307     return error_mark_node;
4308
4309   /* See if this is a partial specialization.  */
4310   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4311                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4312                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4313
4314   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4315     is_friend = true;
4316
4317   if (is_friend)
4318     /* For a friend, we want the context of the friend function, not
4319        the type of which it is a friend.  */
4320     ctx = DECL_CONTEXT (decl);
4321   else if (CP_DECL_CONTEXT (decl)
4322            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4323     /* In the case of a virtual function, we want the class in which
4324        it is defined.  */
4325     ctx = CP_DECL_CONTEXT (decl);
4326   else
4327     /* Otherwise, if we're currently defining some class, the DECL
4328        is assumed to be a member of the class.  */
4329     ctx = current_scope ();
4330
4331   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4332     ctx = NULL_TREE;
4333
4334   if (!DECL_CONTEXT (decl))
4335     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4336
4337   /* See if this is a primary template.  */
4338   if (is_friend && ctx)
4339     /* A friend template that specifies a class context, i.e.
4340          template <typename T> friend void A<T>::f();
4341        is not primary.  */
4342     primary = 0;
4343   else
4344     primary = template_parm_scope_p ();
4345
4346   if (primary)
4347     {
4348       if (DECL_CLASS_SCOPE_P (decl))
4349         member_template_p = true;
4350       if (TREE_CODE (decl) == TYPE_DECL
4351           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4352         {
4353           error ("template class without a name");
4354           return error_mark_node;
4355         }
4356       else if (TREE_CODE (decl) == FUNCTION_DECL)
4357         {
4358           if (DECL_DESTRUCTOR_P (decl))
4359             {
4360               /* [temp.mem]
4361
4362                  A destructor shall not be a member template.  */
4363               error ("destructor %qD declared as member template", decl);
4364               return error_mark_node;
4365             }
4366           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4367               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4368                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4369                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4370                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4371                       == void_list_node)))
4372             {
4373               /* [basic.stc.dynamic.allocation]
4374
4375                  An allocation function can be a function
4376                  template. ... Template allocation functions shall
4377                  have two or more parameters.  */
4378               error ("invalid template declaration of %qD", decl);
4379               return error_mark_node;
4380             }
4381         }
4382       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4383                && CLASS_TYPE_P (TREE_TYPE (decl)))
4384         /* OK */;
4385       else
4386         {
4387           error ("template declaration of %q#D", decl);
4388           return error_mark_node;
4389         }
4390     }
4391
4392   /* Check to see that the rules regarding the use of default
4393      arguments are not being violated.  */
4394   check_default_tmpl_args (decl, current_template_parms,
4395                            primary, is_partial, /*is_friend_decl=*/0);
4396
4397   /* Ensure that there are no parameter packs in the type of this
4398      declaration that have not been expanded.  */
4399   if (TREE_CODE (decl) == FUNCTION_DECL)
4400     {
4401       /* Check each of the arguments individually to see if there are
4402          any bare parameter packs.  */
4403       tree type = TREE_TYPE (decl);
4404       tree arg = DECL_ARGUMENTS (decl);
4405       tree argtype = TYPE_ARG_TYPES (type);
4406
4407       while (arg && argtype)
4408         {
4409           if (!FUNCTION_PARAMETER_PACK_P (arg)
4410               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4411             {
4412             /* This is a PARM_DECL that contains unexpanded parameter
4413                packs. We have already complained about this in the
4414                check_for_bare_parameter_packs call, so just replace
4415                these types with ERROR_MARK_NODE.  */
4416               TREE_TYPE (arg) = error_mark_node;
4417               TREE_VALUE (argtype) = error_mark_node;
4418             }
4419
4420           arg = TREE_CHAIN (arg);
4421           argtype = TREE_CHAIN (argtype);
4422         }
4423
4424       /* Check for bare parameter packs in the return type and the
4425          exception specifiers.  */
4426       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4427         /* Errors were already issued, set return type to int
4428            as the frontend doesn't expect error_mark_node as
4429            the return type.  */
4430         TREE_TYPE (type) = integer_type_node;
4431       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4432         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4433     }
4434   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4435     {
4436       TREE_TYPE (decl) = error_mark_node;
4437       return error_mark_node;
4438     }
4439
4440   if (is_partial)
4441     return process_partial_specialization (decl);
4442
4443   args = current_template_args ();
4444
4445   if (!ctx
4446       || TREE_CODE (ctx) == FUNCTION_DECL
4447       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4448       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4449     {
4450       if (DECL_LANG_SPECIFIC (decl)
4451           && DECL_TEMPLATE_INFO (decl)
4452           && DECL_TI_TEMPLATE (decl))
4453         tmpl = DECL_TI_TEMPLATE (decl);
4454       /* If DECL is a TYPE_DECL for a class-template, then there won't
4455          be DECL_LANG_SPECIFIC.  The information equivalent to
4456          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4457       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4458                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4459                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4460         {
4461           /* Since a template declaration already existed for this
4462              class-type, we must be redeclaring it here.  Make sure
4463              that the redeclaration is valid.  */
4464           redeclare_class_template (TREE_TYPE (decl),
4465                                     current_template_parms);
4466           /* We don't need to create a new TEMPLATE_DECL; just use the
4467              one we already had.  */
4468           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4469         }
4470       else
4471         {
4472           tmpl = build_template_decl (decl, current_template_parms,
4473                                       member_template_p);
4474           new_template_p = 1;
4475
4476           if (DECL_LANG_SPECIFIC (decl)
4477               && DECL_TEMPLATE_SPECIALIZATION (decl))
4478             {
4479               /* A specialization of a member template of a template
4480                  class.  */
4481               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4482               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4483               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4484             }
4485         }
4486     }
4487   else
4488     {
4489       tree a, t, current, parms;
4490       int i;
4491       tree tinfo = get_template_info (decl);
4492
4493       if (!tinfo)
4494         {
4495           error ("template definition of non-template %q#D", decl);
4496           return error_mark_node;
4497         }
4498
4499       tmpl = TI_TEMPLATE (tinfo);
4500
4501       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4502           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4503           && DECL_TEMPLATE_SPECIALIZATION (decl)
4504           && DECL_MEMBER_TEMPLATE_P (tmpl))
4505         {
4506           tree new_tmpl;
4507
4508           /* The declaration is a specialization of a member
4509              template, declared outside the class.  Therefore, the
4510              innermost template arguments will be NULL, so we
4511              replace them with the arguments determined by the
4512              earlier call to check_explicit_specialization.  */
4513           args = DECL_TI_ARGS (decl);
4514
4515           new_tmpl
4516             = build_template_decl (decl, current_template_parms,
4517                                    member_template_p);
4518           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4519           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4520           DECL_TI_TEMPLATE (decl) = new_tmpl;
4521           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4522           DECL_TEMPLATE_INFO (new_tmpl)
4523             = build_template_info (tmpl, args);
4524
4525           register_specialization (new_tmpl,
4526                                    most_general_template (tmpl),
4527                                    args,
4528                                    is_friend, 0);
4529           return decl;
4530         }
4531
4532       /* Make sure the template headers we got make sense.  */
4533
4534       parms = DECL_TEMPLATE_PARMS (tmpl);
4535       i = TMPL_PARMS_DEPTH (parms);
4536       if (TMPL_ARGS_DEPTH (args) != i)
4537         {
4538           error ("expected %d levels of template parms for %q#D, got %d",
4539                  i, decl, TMPL_ARGS_DEPTH (args));
4540         }
4541       else
4542         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4543           {
4544             a = TMPL_ARGS_LEVEL (args, i);
4545             t = INNERMOST_TEMPLATE_PARMS (parms);
4546
4547             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4548               {
4549                 if (current == decl)
4550                   error ("got %d template parameters for %q#D",
4551                          TREE_VEC_LENGTH (a), decl);
4552                 else
4553                   error ("got %d template parameters for %q#T",
4554                          TREE_VEC_LENGTH (a), current);
4555                 error ("  but %d required", TREE_VEC_LENGTH (t));
4556                 return error_mark_node;
4557               }
4558
4559             if (current == decl)
4560               current = ctx;
4561             else if (current == NULL_TREE)
4562               /* Can happen in erroneous input.  */
4563               break;
4564             else
4565               current = (TYPE_P (current)
4566                          ? TYPE_CONTEXT (current)
4567                          : DECL_CONTEXT (current));
4568           }
4569
4570       /* Check that the parms are used in the appropriate qualifying scopes
4571          in the declarator.  */
4572       if (!comp_template_args
4573           (TI_ARGS (tinfo),
4574            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4575         {
4576           error ("\
4577 template arguments to %qD do not match original template %qD",
4578                  decl, DECL_TEMPLATE_RESULT (tmpl));
4579           if (!uses_template_parms (TI_ARGS (tinfo)))
4580             inform (input_location, "use template<> for an explicit specialization");
4581           /* Avoid crash in import_export_decl.  */
4582           DECL_INTERFACE_KNOWN (decl) = 1;
4583           return error_mark_node;
4584         }
4585     }
4586
4587   DECL_TEMPLATE_RESULT (tmpl) = decl;
4588   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4589
4590   /* Push template declarations for global functions and types.  Note
4591      that we do not try to push a global template friend declared in a
4592      template class; such a thing may well depend on the template
4593      parameters of the class.  */
4594   if (new_template_p && !ctx
4595       && !(is_friend && template_class_depth (current_class_type) > 0))
4596     {
4597       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4598       if (tmpl == error_mark_node)
4599         return error_mark_node;
4600
4601       /* Hide template friend classes that haven't been declared yet.  */
4602       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4603         {
4604           DECL_ANTICIPATED (tmpl) = 1;
4605           DECL_FRIEND_P (tmpl) = 1;
4606         }
4607     }
4608
4609   if (primary)
4610     {
4611       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4612       int i;
4613
4614       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4615       if (DECL_CONV_FN_P (tmpl))
4616         {
4617           int depth = TMPL_PARMS_DEPTH (parms);
4618
4619           /* It is a conversion operator. See if the type converted to
4620              depends on innermost template operands.  */
4621
4622           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4623                                          depth))
4624             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4625         }
4626
4627       /* Give template template parms a DECL_CONTEXT of the template
4628          for which they are a parameter.  */
4629       parms = INNERMOST_TEMPLATE_PARMS (parms);
4630       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4631         {
4632           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4633           if (TREE_CODE (parm) == TEMPLATE_DECL)
4634             DECL_CONTEXT (parm) = tmpl;
4635         }
4636     }
4637
4638   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4639      back to its most general template.  If TMPL is a specialization,
4640      ARGS may only have the innermost set of arguments.  Add the missing
4641      argument levels if necessary.  */
4642   if (DECL_TEMPLATE_INFO (tmpl))
4643     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4644
4645   info = build_template_info (tmpl, args);
4646
4647   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4648     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4649   else if (DECL_LANG_SPECIFIC (decl))
4650     DECL_TEMPLATE_INFO (decl) = info;
4651
4652   return DECL_TEMPLATE_RESULT (tmpl);
4653 }
4654
4655 tree
4656 push_template_decl (tree decl)
4657 {
4658   return push_template_decl_real (decl, false);
4659 }
4660
4661 /* Called when a class template TYPE is redeclared with the indicated
4662    template PARMS, e.g.:
4663
4664      template <class T> struct S;
4665      template <class T> struct S {};  */
4666
4667 bool
4668 redeclare_class_template (tree type, tree parms)
4669 {
4670   tree tmpl;
4671   tree tmpl_parms;
4672   int i;
4673
4674   if (!TYPE_TEMPLATE_INFO (type))
4675     {
4676       error ("%qT is not a template type", type);
4677       return false;
4678     }
4679
4680   tmpl = TYPE_TI_TEMPLATE (type);
4681   if (!PRIMARY_TEMPLATE_P (tmpl))
4682     /* The type is nested in some template class.  Nothing to worry
4683        about here; there are no new template parameters for the nested
4684        type.  */
4685     return true;
4686
4687   if (!parms)
4688     {
4689       error ("template specifiers not specified in declaration of %qD",
4690              tmpl);
4691       return false;
4692     }
4693
4694   parms = INNERMOST_TEMPLATE_PARMS (parms);
4695   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4696
4697   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4698     {
4699       error_n (input_location, TREE_VEC_LENGTH (parms),
4700                "redeclared with %d template parameter",
4701                "redeclared with %d template parameters",
4702                TREE_VEC_LENGTH (parms));
4703       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
4704                 "previous declaration %q+D used %d template parameter",
4705                 "previous declaration %q+D used %d template parameters",
4706                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
4707       return false;
4708     }
4709
4710   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4711     {
4712       tree tmpl_parm;
4713       tree parm;
4714       tree tmpl_default;
4715       tree parm_default;
4716
4717       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4718           || TREE_VEC_ELT (parms, i) == error_mark_node)
4719         continue;
4720
4721       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4722       if (tmpl_parm == error_mark_node)
4723         return false;
4724
4725       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4726       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4727       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4728
4729       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4730          TEMPLATE_DECL.  */
4731       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4732           || (TREE_CODE (tmpl_parm) != TYPE_DECL
4733               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4734           || (TREE_CODE (tmpl_parm) != PARM_DECL
4735               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4736                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4737           || (TREE_CODE (tmpl_parm) == PARM_DECL
4738               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4739                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
4740         {
4741           error ("template parameter %q+#D", tmpl_parm);
4742           error ("redeclared here as %q#D", parm);
4743           return false;
4744         }
4745
4746       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4747         {
4748           /* We have in [temp.param]:
4749
4750              A template-parameter may not be given default arguments
4751              by two different declarations in the same scope.  */
4752           error_at (input_location, "redefinition of default argument for %q#D", parm);
4753           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4754                   "original definition appeared here");
4755           return false;
4756         }
4757
4758       if (parm_default != NULL_TREE)
4759         /* Update the previous template parameters (which are the ones
4760            that will really count) with the new default value.  */
4761         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4762       else if (tmpl_default != NULL_TREE)
4763         /* Update the new parameters, too; they'll be used as the
4764            parameters for any members.  */
4765         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4766     }
4767
4768     return true;
4769 }
4770
4771 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4772    (possibly simplified) expression.  */
4773
4774 tree
4775 fold_non_dependent_expr (tree expr)
4776 {
4777   if (expr == NULL_TREE)
4778     return NULL_TREE;
4779
4780   /* If we're in a template, but EXPR isn't value dependent, simplify
4781      it.  We're supposed to treat:
4782
4783        template <typename T> void f(T[1 + 1]);
4784        template <typename T> void f(T[2]);
4785
4786      as two declarations of the same function, for example.  */
4787   if (processing_template_decl
4788       && !type_dependent_expression_p (expr)
4789       && !value_dependent_expression_p (expr))
4790     {
4791       HOST_WIDE_INT saved_processing_template_decl;
4792
4793       saved_processing_template_decl = processing_template_decl;
4794       processing_template_decl = 0;
4795       expr = tsubst_copy_and_build (expr,
4796                                     /*args=*/NULL_TREE,
4797                                     tf_error,
4798                                     /*in_decl=*/NULL_TREE,
4799                                     /*function_p=*/false,
4800                                     /*integral_constant_expression_p=*/true);
4801       processing_template_decl = saved_processing_template_decl;
4802     }
4803   return expr;
4804 }
4805
4806 /* EXPR is an expression which is used in a constant-expression context.
4807    For instance, it could be a VAR_DECL with a constant initializer.
4808    Extract the innermost constant expression.
4809
4810    This is basically a more powerful version of
4811    integral_constant_value, which can be used also in templates where
4812    initializers can maintain a syntactic rather than semantic form
4813    (even if they are non-dependent, for access-checking purposes).  */
4814
4815 static tree
4816 fold_decl_constant_value (tree expr)
4817 {
4818   tree const_expr = expr;
4819   do
4820     {
4821       expr = fold_non_dependent_expr (const_expr);
4822       const_expr = integral_constant_value (expr);
4823     }
4824   while (expr != const_expr);
4825
4826   return expr;
4827 }
4828
4829 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4830    must be a function or a pointer-to-function type, as specified
4831    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4832    and check that the resulting function has external linkage.  */
4833
4834 static tree
4835 convert_nontype_argument_function (tree type, tree expr)
4836 {
4837   tree fns = expr;
4838   tree fn, fn_no_ptr;
4839
4840   fn = instantiate_type (type, fns, tf_none);
4841   if (fn == error_mark_node)
4842     return error_mark_node;
4843
4844   fn_no_ptr = fn;
4845   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4846     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4847   if (TREE_CODE (fn_no_ptr) == BASELINK)
4848     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4849  
4850   /* [temp.arg.nontype]/1
4851
4852      A template-argument for a non-type, non-template template-parameter
4853      shall be one of:
4854      [...]
4855      -- the address of an object or function with external linkage.  */
4856   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4857     {
4858       error ("%qE is not a valid template argument for type %qT "
4859              "because function %qD has not external linkage",
4860              expr, type, fn_no_ptr);
4861       return NULL_TREE;
4862     }
4863
4864   return fn;
4865 }
4866
4867 /* Subroutine of convert_nontype_argument.
4868    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4869    Emit an error otherwise.  */
4870
4871 static bool
4872 check_valid_ptrmem_cst_expr (tree type, tree expr)
4873 {
4874   STRIP_NOPS (expr);
4875   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4876     return true;
4877   error ("%qE is not a valid template argument for type %qT",
4878          expr, type);
4879   error ("it must be a pointer-to-member of the form `&X::Y'");
4880   return false;
4881 }
4882
4883 /* Returns TRUE iff the address of OP is value-dependent.
4884
4885    14.6.2.4 [temp.dep.temp]:
4886    A non-integral non-type template-argument is dependent if its type is
4887    dependent or it has either of the following forms
4888      qualified-id
4889      & qualified-id
4890    and contains a nested-name-specifier which specifies a class-name that
4891    names a dependent type.
4892
4893    We generalize this to just say that the address of a member of a
4894    dependent class is value-dependent; the above doesn't cover the
4895    address of a static data member named with an unqualified-id.  */
4896
4897 static bool
4898 has_value_dependent_address (tree op)
4899 {
4900   /* We could use get_inner_reference here, but there's no need;
4901      this is only relevant for template non-type arguments, which
4902      can only be expressed as &id-expression.  */
4903   if (DECL_P (op))
4904     {
4905       tree ctx = CP_DECL_CONTEXT (op);
4906       if (TYPE_P (ctx) && dependent_type_p (ctx))
4907         return true;
4908     }
4909
4910   return false;
4911 }
4912
4913 /* Attempt to convert the non-type template parameter EXPR to the
4914    indicated TYPE.  If the conversion is successful, return the
4915    converted value.  If the conversion is unsuccessful, return
4916    NULL_TREE if we issued an error message, or error_mark_node if we
4917    did not.  We issue error messages for out-and-out bad template
4918    parameters, but not simply because the conversion failed, since we
4919    might be just trying to do argument deduction.  Both TYPE and EXPR
4920    must be non-dependent.
4921
4922    The conversion follows the special rules described in
4923    [temp.arg.nontype], and it is much more strict than an implicit
4924    conversion.
4925
4926    This function is called twice for each template argument (see
4927    lookup_template_class for a more accurate description of this
4928    problem). This means that we need to handle expressions which
4929    are not valid in a C++ source, but can be created from the
4930    first call (for instance, casts to perform conversions). These
4931    hacks can go away after we fix the double coercion problem.  */
4932
4933 static tree
4934 convert_nontype_argument (tree type, tree expr)
4935 {
4936   tree expr_type;
4937
4938   /* Detect immediately string literals as invalid non-type argument.
4939      This special-case is not needed for correctness (we would easily
4940      catch this later), but only to provide better diagnostic for this
4941      common user mistake. As suggested by DR 100, we do not mention
4942      linkage issues in the diagnostic as this is not the point.  */
4943   if (TREE_CODE (expr) == STRING_CST)
4944     {
4945       error ("%qE is not a valid template argument for type %qT "
4946              "because string literals can never be used in this context",
4947              expr, type);
4948       return NULL_TREE;
4949     }
4950
4951   /* Add the ADDR_EXPR now for the benefit of
4952      value_dependent_expression_p.  */
4953   if (TYPE_PTROBV_P (type))
4954     expr = decay_conversion (expr);
4955
4956   /* If we are in a template, EXPR may be non-dependent, but still
4957      have a syntactic, rather than semantic, form.  For example, EXPR
4958      might be a SCOPE_REF, rather than the VAR_DECL to which the
4959      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4960      so that access checking can be performed when the template is
4961      instantiated -- but here we need the resolved form so that we can
4962      convert the argument.  */
4963   if (TYPE_REF_OBJ_P (type)
4964       && has_value_dependent_address (expr))
4965     /* If we want the address and it's value-dependent, don't fold.  */;
4966   else
4967     expr = fold_non_dependent_expr (expr);
4968   if (error_operand_p (expr))
4969     return error_mark_node;
4970   expr_type = TREE_TYPE (expr);
4971   if (TREE_CODE (type) == REFERENCE_TYPE)
4972     expr = mark_lvalue_use (expr);
4973   else
4974     expr = mark_rvalue_use (expr);
4975
4976   /* HACK: Due to double coercion, we can get a
4977      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4978      which is the tree that we built on the first call (see
4979      below when coercing to reference to object or to reference to
4980      function). We just strip everything and get to the arg.
4981      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4982      for examples.  */
4983   if (TREE_CODE (expr) == NOP_EXPR)
4984     {
4985       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4986         {
4987           /* ??? Maybe we could use convert_from_reference here, but we
4988              would need to relax its constraints because the NOP_EXPR
4989              could actually change the type to something more cv-qualified,
4990              and this is not folded by convert_from_reference.  */
4991           tree addr = TREE_OPERAND (expr, 0);
4992           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4993           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4994           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4995           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4996                       (TREE_TYPE (expr_type),
4997                        TREE_TYPE (TREE_TYPE (addr))));
4998
4999           expr = TREE_OPERAND (addr, 0);
5000           expr_type = TREE_TYPE (expr);
5001         }
5002
5003       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5004          parameter is a pointer to object, through decay and
5005          qualification conversion. Let's strip everything.  */
5006       else if (TYPE_PTROBV_P (type))
5007         {
5008           STRIP_NOPS (expr);
5009           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5010           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5011           /* Skip the ADDR_EXPR only if it is part of the decay for
5012              an array. Otherwise, it is part of the original argument
5013              in the source code.  */
5014           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5015             expr = TREE_OPERAND (expr, 0);
5016           expr_type = TREE_TYPE (expr);
5017         }
5018     }
5019
5020   /* [temp.arg.nontype]/5, bullet 1
5021
5022      For a non-type template-parameter of integral or enumeration type,
5023      integral promotions (_conv.prom_) and integral conversions
5024      (_conv.integral_) are applied.  */
5025   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5026     {
5027       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
5028         return error_mark_node;
5029
5030       expr = fold_decl_constant_value (expr);
5031       /* Notice that there are constant expressions like '4 % 0' which
5032          do not fold into integer constants.  */
5033       if (TREE_CODE (expr) != INTEGER_CST)
5034         {
5035           error ("%qE is not a valid template argument for type %qT "
5036                  "because it is a non-constant expression", expr, type);
5037           return NULL_TREE;
5038         }
5039
5040       /* At this point, an implicit conversion does what we want,
5041          because we already know that the expression is of integral
5042          type.  */
5043       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
5044       if (expr == error_mark_node)
5045         return error_mark_node;
5046
5047       /* Conversion was allowed: fold it to a bare integer constant.  */
5048       expr = fold (expr);
5049     }
5050   /* [temp.arg.nontype]/5, bullet 2
5051
5052      For a non-type template-parameter of type pointer to object,
5053      qualification conversions (_conv.qual_) and the array-to-pointer
5054      conversion (_conv.array_) are applied.  */
5055   else if (TYPE_PTROBV_P (type))
5056     {
5057       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5058
5059          A template-argument for a non-type, non-template template-parameter
5060          shall be one of: [...]
5061
5062          -- the name of a non-type template-parameter;
5063          -- the address of an object or function with external linkage, [...]
5064             expressed as "& id-expression" where the & is optional if the name
5065             refers to a function or array, or if the corresponding
5066             template-parameter is a reference.
5067
5068         Here, we do not care about functions, as they are invalid anyway
5069         for a parameter of type pointer-to-object.  */
5070
5071       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5072         /* Non-type template parameters are OK.  */
5073         ;
5074       else if (TREE_CODE (expr) != ADDR_EXPR
5075                && TREE_CODE (expr_type) != ARRAY_TYPE)
5076         {
5077           if (TREE_CODE (expr) == VAR_DECL)
5078             {
5079               error ("%qD is not a valid template argument "
5080                      "because %qD is a variable, not the address of "
5081                      "a variable",
5082                      expr, expr);
5083               return NULL_TREE;
5084             }
5085           /* Other values, like integer constants, might be valid
5086              non-type arguments of some other type.  */
5087           return error_mark_node;
5088         }
5089       else
5090         {
5091           tree decl;
5092
5093           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5094                   ? TREE_OPERAND (expr, 0) : expr);
5095           if (TREE_CODE (decl) != VAR_DECL)
5096             {
5097               error ("%qE is not a valid template argument of type %qT "
5098                      "because %qE is not a variable",
5099                      expr, type, decl);
5100               return NULL_TREE;
5101             }
5102           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5103             {
5104               error ("%qE is not a valid template argument of type %qT "
5105                      "because %qD does not have external linkage",
5106                      expr, type, decl);
5107               return NULL_TREE;
5108             }
5109         }
5110
5111       expr = decay_conversion (expr);
5112       if (expr == error_mark_node)
5113         return error_mark_node;
5114
5115       expr = perform_qualification_conversions (type, expr);
5116       if (expr == error_mark_node)
5117         return error_mark_node;
5118     }
5119   /* [temp.arg.nontype]/5, bullet 3
5120
5121      For a non-type template-parameter of type reference to object, no
5122      conversions apply. The type referred to by the reference may be more
5123      cv-qualified than the (otherwise identical) type of the
5124      template-argument. The template-parameter is bound directly to the
5125      template-argument, which must be an lvalue.  */
5126   else if (TYPE_REF_OBJ_P (type))
5127     {
5128       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5129                                                       expr_type))
5130         return error_mark_node;
5131
5132       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5133         {
5134           error ("%qE is not a valid template argument for type %qT "
5135                  "because of conflicts in cv-qualification", expr, type);
5136           return NULL_TREE;
5137         }
5138
5139       if (!real_lvalue_p (expr))
5140         {
5141           error ("%qE is not a valid template argument for type %qT "
5142                  "because it is not an lvalue", expr, type);
5143           return NULL_TREE;
5144         }
5145
5146       /* [temp.arg.nontype]/1
5147
5148          A template-argument for a non-type, non-template template-parameter
5149          shall be one of: [...]
5150
5151          -- the address of an object or function with external linkage.  */
5152       if (TREE_CODE (expr) == INDIRECT_REF
5153           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5154         {
5155           expr = TREE_OPERAND (expr, 0);
5156           if (DECL_P (expr))
5157             {
5158               error ("%q#D is not a valid template argument for type %qT "
5159                      "because a reference variable does not have a constant "
5160                      "address", expr, type);
5161               return NULL_TREE;
5162             }
5163         }
5164
5165       if (!DECL_P (expr))
5166         {
5167           error ("%qE is not a valid template argument for type %qT "
5168                  "because it is not an object with external linkage",
5169                  expr, type);
5170           return NULL_TREE;
5171         }
5172
5173       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5174         {
5175           error ("%qE is not a valid template argument for type %qT "
5176                  "because object %qD has not external linkage",
5177                  expr, type, expr);
5178           return NULL_TREE;
5179         }
5180
5181       expr = build_nop (type, build_address (expr));
5182     }
5183   /* [temp.arg.nontype]/5, bullet 4
5184
5185      For a non-type template-parameter of type pointer to function, only
5186      the function-to-pointer conversion (_conv.func_) is applied. If the
5187      template-argument represents a set of overloaded functions (or a
5188      pointer to such), the matching function is selected from the set
5189      (_over.over_).  */
5190   else if (TYPE_PTRFN_P (type))
5191     {
5192       /* If the argument is a template-id, we might not have enough
5193          context information to decay the pointer.  */
5194       if (!type_unknown_p (expr_type))
5195         {
5196           expr = decay_conversion (expr);
5197           if (expr == error_mark_node)
5198             return error_mark_node;
5199         }
5200
5201       expr = convert_nontype_argument_function (type, expr);
5202       if (!expr || expr == error_mark_node)
5203         return expr;
5204
5205       if (TREE_CODE (expr) != ADDR_EXPR)
5206         {
5207           error ("%qE is not a valid template argument for type %qT", expr, type);
5208           error ("it must be the address of a function with external linkage");
5209           return NULL_TREE;
5210         }
5211     }
5212   /* [temp.arg.nontype]/5, bullet 5
5213
5214      For a non-type template-parameter of type reference to function, no
5215      conversions apply. If the template-argument represents a set of
5216      overloaded functions, the matching function is selected from the set
5217      (_over.over_).  */
5218   else if (TYPE_REFFN_P (type))
5219     {
5220       if (TREE_CODE (expr) == ADDR_EXPR)
5221         {
5222           error ("%qE is not a valid template argument for type %qT "
5223                  "because it is a pointer", expr, type);
5224           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5225           return NULL_TREE;
5226         }
5227
5228       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5229       if (!expr || expr == error_mark_node)
5230         return expr;
5231
5232       expr = build_nop (type, build_address (expr));
5233     }
5234   /* [temp.arg.nontype]/5, bullet 6
5235
5236      For a non-type template-parameter of type pointer to member function,
5237      no conversions apply. If the template-argument represents a set of
5238      overloaded member functions, the matching member function is selected
5239      from the set (_over.over_).  */
5240   else if (TYPE_PTRMEMFUNC_P (type))
5241     {
5242       expr = instantiate_type (type, expr, tf_none);
5243       if (expr == error_mark_node)
5244         return error_mark_node;
5245
5246       /* [temp.arg.nontype] bullet 1 says the pointer to member
5247          expression must be a pointer-to-member constant.  */
5248       if (!check_valid_ptrmem_cst_expr (type, expr))
5249         return error_mark_node;
5250
5251       /* There is no way to disable standard conversions in
5252          resolve_address_of_overloaded_function (called by
5253          instantiate_type). It is possible that the call succeeded by
5254          converting &B::I to &D::I (where B is a base of D), so we need
5255          to reject this conversion here.
5256
5257          Actually, even if there was a way to disable standard conversions,
5258          it would still be better to reject them here so that we can
5259          provide a superior diagnostic.  */
5260       if (!same_type_p (TREE_TYPE (expr), type))
5261         {
5262           error ("%qE is not a valid template argument for type %qT "
5263                  "because it is of type %qT", expr, type,
5264                  TREE_TYPE (expr));
5265           /* If we are just one standard conversion off, explain.  */
5266           if (can_convert (type, TREE_TYPE (expr)))
5267             inform (input_location,
5268                     "standard conversions are not allowed in this context");
5269           return NULL_TREE;
5270         }
5271     }
5272   /* [temp.arg.nontype]/5, bullet 7
5273
5274      For a non-type template-parameter of type pointer to data member,
5275      qualification conversions (_conv.qual_) are applied.  */
5276   else if (TYPE_PTRMEM_P (type))
5277     {
5278       /* [temp.arg.nontype] bullet 1 says the pointer to member
5279          expression must be a pointer-to-member constant.  */
5280       if (!check_valid_ptrmem_cst_expr (type, expr))
5281         return error_mark_node;
5282
5283       expr = perform_qualification_conversions (type, expr);
5284       if (expr == error_mark_node)
5285         return expr;
5286     }
5287   /* A template non-type parameter must be one of the above.  */
5288   else
5289     gcc_unreachable ();
5290
5291   /* Sanity check: did we actually convert the argument to the
5292      right type?  */
5293   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5294   return expr;
5295 }
5296
5297 /* Subroutine of coerce_template_template_parms, which returns 1 if
5298    PARM_PARM and ARG_PARM match using the rule for the template
5299    parameters of template template parameters. Both PARM and ARG are
5300    template parameters; the rest of the arguments are the same as for
5301    coerce_template_template_parms.
5302  */
5303 static int
5304 coerce_template_template_parm (tree parm,
5305                               tree arg,
5306                               tsubst_flags_t complain,
5307                               tree in_decl,
5308                               tree outer_args)
5309 {
5310   if (arg == NULL_TREE || arg == error_mark_node
5311       || parm == NULL_TREE || parm == error_mark_node)
5312     return 0;
5313   
5314   if (TREE_CODE (arg) != TREE_CODE (parm))
5315     return 0;
5316   
5317   switch (TREE_CODE (parm))
5318     {
5319     case TEMPLATE_DECL:
5320       /* We encounter instantiations of templates like
5321          template <template <template <class> class> class TT>
5322          class C;  */
5323       {
5324         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5325         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5326         
5327         if (!coerce_template_template_parms
5328             (parmparm, argparm, complain, in_decl, outer_args))
5329           return 0;
5330       }
5331       /* Fall through.  */
5332       
5333     case TYPE_DECL:
5334       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5335           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5336         /* Argument is a parameter pack but parameter is not.  */
5337         return 0;
5338       break;
5339       
5340     case PARM_DECL:
5341       /* The tsubst call is used to handle cases such as
5342          
5343            template <int> class C {};
5344            template <class T, template <T> class TT> class D {};
5345            D<int, C> d;
5346
5347          i.e. the parameter list of TT depends on earlier parameters.  */
5348       if (!uses_template_parms (TREE_TYPE (arg))
5349           && !same_type_p
5350                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5351                  TREE_TYPE (arg)))
5352         return 0;
5353       
5354       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5355           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5356         /* Argument is a parameter pack but parameter is not.  */
5357         return 0;
5358       
5359       break;
5360
5361     default:
5362       gcc_unreachable ();
5363     }
5364
5365   return 1;
5366 }
5367
5368
5369 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5370    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5371    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5372    or PARM_DECL.
5373
5374    Consider the example:
5375      template <class T> class A;
5376      template<template <class U> class TT> class B;
5377
5378    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5379    the parameters to A, and OUTER_ARGS contains A.  */
5380
5381 static int
5382 coerce_template_template_parms (tree parm_parms,
5383                                 tree arg_parms,
5384                                 tsubst_flags_t complain,
5385                                 tree in_decl,
5386                                 tree outer_args)
5387 {
5388   int nparms, nargs, i;
5389   tree parm, arg;
5390   int variadic_p = 0;
5391
5392   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5393   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5394
5395   nparms = TREE_VEC_LENGTH (parm_parms);
5396   nargs = TREE_VEC_LENGTH (arg_parms);
5397
5398   /* Determine whether we have a parameter pack at the end of the
5399      template template parameter's template parameter list.  */
5400   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5401     {
5402       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5403       
5404       if (parm == error_mark_node)
5405         return 0;
5406
5407       switch (TREE_CODE (parm))
5408         {
5409         case TEMPLATE_DECL:
5410         case TYPE_DECL:
5411           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5412             variadic_p = 1;
5413           break;
5414           
5415         case PARM_DECL:
5416           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5417             variadic_p = 1;
5418           break;
5419           
5420         default:
5421           gcc_unreachable ();
5422         }
5423     }
5424  
5425   if (nargs != nparms
5426       && !(variadic_p && nargs >= nparms - 1))
5427     return 0;
5428
5429   /* Check all of the template parameters except the parameter pack at
5430      the end (if any).  */
5431   for (i = 0; i < nparms - variadic_p; ++i)
5432     {
5433       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5434           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5435         continue;
5436
5437       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5438       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5439
5440       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5441                                           outer_args))
5442         return 0;
5443
5444     }
5445
5446   if (variadic_p)
5447     {
5448       /* Check each of the template parameters in the template
5449          argument against the template parameter pack at the end of
5450          the template template parameter.  */
5451       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5452         return 0;
5453
5454       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5455
5456       for (; i < nargs; ++i)
5457         {
5458           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5459             continue;
5460  
5461           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5462  
5463           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5464                                               outer_args))
5465             return 0;
5466         }
5467     }
5468
5469   return 1;
5470 }
5471
5472 /* Verifies that the deduced template arguments (in TARGS) for the
5473    template template parameters (in TPARMS) represent valid bindings,
5474    by comparing the template parameter list of each template argument
5475    to the template parameter list of its corresponding template
5476    template parameter, in accordance with DR150. This
5477    routine can only be called after all template arguments have been
5478    deduced. It will return TRUE if all of the template template
5479    parameter bindings are okay, FALSE otherwise.  */
5480 bool 
5481 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5482 {
5483   int i, ntparms = TREE_VEC_LENGTH (tparms);
5484   bool ret = true;
5485
5486   /* We're dealing with template parms in this process.  */
5487   ++processing_template_decl;
5488
5489   targs = INNERMOST_TEMPLATE_ARGS (targs);
5490
5491   for (i = 0; i < ntparms; ++i)
5492     {
5493       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5494       tree targ = TREE_VEC_ELT (targs, i);
5495
5496       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5497         {
5498           tree packed_args = NULL_TREE;
5499           int idx, len = 1;
5500
5501           if (ARGUMENT_PACK_P (targ))
5502             {
5503               /* Look inside the argument pack.  */
5504               packed_args = ARGUMENT_PACK_ARGS (targ);
5505               len = TREE_VEC_LENGTH (packed_args);
5506             }
5507
5508           for (idx = 0; idx < len; ++idx)
5509             {
5510               tree targ_parms = NULL_TREE;
5511
5512               if (packed_args)
5513                 /* Extract the next argument from the argument
5514                    pack.  */
5515                 targ = TREE_VEC_ELT (packed_args, idx);
5516
5517               if (PACK_EXPANSION_P (targ))
5518                 /* Look at the pattern of the pack expansion.  */
5519                 targ = PACK_EXPANSION_PATTERN (targ);
5520
5521               /* Extract the template parameters from the template
5522                  argument.  */
5523               if (TREE_CODE (targ) == TEMPLATE_DECL)
5524                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5525               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5526                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5527
5528               /* Verify that we can coerce the template template
5529                  parameters from the template argument to the template
5530                  parameter.  This requires an exact match.  */
5531               if (targ_parms
5532                   && !coerce_template_template_parms
5533                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5534                         targ_parms,
5535                         tf_none,
5536                         tparm,
5537                         targs))
5538                 {
5539                   ret = false;
5540                   goto out;
5541                 }
5542             }
5543         }
5544     }
5545
5546  out:
5547
5548   --processing_template_decl;
5549   return ret;
5550 }
5551
5552 /* Convert the indicated template ARG as necessary to match the
5553    indicated template PARM.  Returns the converted ARG, or
5554    error_mark_node if the conversion was unsuccessful.  Error and
5555    warning messages are issued under control of COMPLAIN.  This
5556    conversion is for the Ith parameter in the parameter list.  ARGS is
5557    the full set of template arguments deduced so far.  */
5558
5559 static tree
5560 convert_template_argument (tree parm,
5561                            tree arg,
5562                            tree args,
5563                            tsubst_flags_t complain,
5564                            int i,
5565                            tree in_decl)
5566 {
5567   tree orig_arg;
5568   tree val;
5569   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5570
5571   if (TREE_CODE (arg) == TREE_LIST
5572       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5573     {
5574       /* The template argument was the name of some
5575          member function.  That's usually
5576          invalid, but static members are OK.  In any
5577          case, grab the underlying fields/functions
5578          and issue an error later if required.  */
5579       orig_arg = TREE_VALUE (arg);
5580       TREE_TYPE (arg) = unknown_type_node;
5581     }
5582
5583   orig_arg = arg;
5584
5585   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5586   requires_type = (TREE_CODE (parm) == TYPE_DECL
5587                    || requires_tmpl_type);
5588
5589   /* When determining whether an argument pack expansion is a template,
5590      look at the pattern.  */
5591   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5592     arg = PACK_EXPANSION_PATTERN (arg);
5593
5594   /* Deal with an injected-class-name used as a template template arg.  */
5595   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5596     {
5597       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5598       if (TREE_CODE (t) == TEMPLATE_DECL)
5599         {
5600           if (complain & tf_warning_or_error)
5601             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5602                      " used as template template argument", TYPE_NAME (arg));
5603           else if (flag_pedantic_errors)
5604             t = arg;
5605
5606           arg = t;
5607         }
5608     }
5609
5610   is_tmpl_type = 
5611     ((TREE_CODE (arg) == TEMPLATE_DECL
5612       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5613      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5614      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5615
5616   if (is_tmpl_type
5617       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5618           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5619     arg = TYPE_STUB_DECL (arg);
5620
5621   is_type = TYPE_P (arg) || is_tmpl_type;
5622
5623   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5624       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5625     {
5626       permerror (input_location, "to refer to a type member of a template parameter, "
5627                  "use %<typename %E%>", orig_arg);
5628
5629       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5630                                      TREE_OPERAND (arg, 1),
5631                                      typename_type,
5632                                      complain & tf_error);
5633       arg = orig_arg;
5634       is_type = 1;
5635     }
5636   if (is_type != requires_type)
5637     {
5638       if (in_decl)
5639         {
5640           if (complain & tf_error)
5641             {
5642               error ("type/value mismatch at argument %d in template "
5643                      "parameter list for %qD",
5644                      i + 1, in_decl);
5645               if (is_type)
5646                 error ("  expected a constant of type %qT, got %qT",
5647                        TREE_TYPE (parm),
5648                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5649               else if (requires_tmpl_type)
5650                 error ("  expected a class template, got %qE", orig_arg);
5651               else
5652                 error ("  expected a type, got %qE", orig_arg);
5653             }
5654         }
5655       return error_mark_node;
5656     }
5657   if (is_tmpl_type ^ requires_tmpl_type)
5658     {
5659       if (in_decl && (complain & tf_error))
5660         {
5661           error ("type/value mismatch at argument %d in template "
5662                  "parameter list for %qD",
5663                  i + 1, in_decl);
5664           if (is_tmpl_type)
5665             error ("  expected a type, got %qT", DECL_NAME (arg));
5666           else
5667             error ("  expected a class template, got %qT", orig_arg);
5668         }
5669       return error_mark_node;
5670     }
5671
5672   if (is_type)
5673     {
5674       if (requires_tmpl_type)
5675         {
5676           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5677             /* The number of argument required is not known yet.
5678                Just accept it for now.  */
5679             val = TREE_TYPE (arg);
5680           else
5681             {
5682               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5683               tree argparm;
5684
5685               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5686
5687               if (coerce_template_template_parms (parmparm, argparm,
5688                                                   complain, in_decl,
5689                                                   args))
5690                 {
5691                   val = arg;
5692
5693                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5694                      TEMPLATE_DECL.  */
5695                   if (val != error_mark_node)
5696                     {
5697                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5698                         val = TREE_TYPE (val);
5699                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
5700                         val = make_pack_expansion (val);
5701                     }
5702                 }
5703               else
5704                 {
5705                   if (in_decl && (complain & tf_error))
5706                     {
5707                       error ("type/value mismatch at argument %d in "
5708                              "template parameter list for %qD",
5709                              i + 1, in_decl);
5710                       error ("  expected a template of type %qD, got %qT",
5711                              parm, orig_arg);
5712                     }
5713
5714                   val = error_mark_node;
5715                 }
5716             }
5717         }
5718       else
5719         val = orig_arg;
5720       /* We only form one instance of each template specialization.
5721          Therefore, if we use a non-canonical variant (i.e., a
5722          typedef), any future messages referring to the type will use
5723          the typedef, which is confusing if those future uses do not
5724          themselves also use the typedef.  */
5725       if (TYPE_P (val))
5726         val = strip_typedefs (val);
5727     }
5728   else
5729     {
5730       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5731
5732       if (invalid_nontype_parm_type_p (t, complain))
5733         return error_mark_node;
5734
5735       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5736         {
5737           if (same_type_p (t, TREE_TYPE (orig_arg)))
5738             val = orig_arg;
5739           else
5740             {
5741               /* Not sure if this is reachable, but it doesn't hurt
5742                  to be robust.  */
5743               error ("type mismatch in nontype parameter pack");
5744               val = error_mark_node;
5745             }
5746         }
5747       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5748         /* We used to call digest_init here.  However, digest_init
5749            will report errors, which we don't want when complain
5750            is zero.  More importantly, digest_init will try too
5751            hard to convert things: for example, `0' should not be
5752            converted to pointer type at this point according to
5753            the standard.  Accepting this is not merely an
5754            extension, since deciding whether or not these
5755            conversions can occur is part of determining which
5756            function template to call, or whether a given explicit
5757            argument specification is valid.  */
5758         val = convert_nontype_argument (t, orig_arg);
5759       else
5760         val = orig_arg;
5761
5762       if (val == NULL_TREE)
5763         val = error_mark_node;
5764       else if (val == error_mark_node && (complain & tf_error))
5765         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5766
5767       if (TREE_CODE (val) == SCOPE_REF)
5768         {
5769           /* Strip typedefs from the SCOPE_REF.  */
5770           tree type = strip_typedefs (TREE_TYPE (val));
5771           tree scope = strip_typedefs (TREE_OPERAND (val, 0));
5772           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
5773                                       QUALIFIED_NAME_IS_TEMPLATE (val));
5774         }
5775     }
5776
5777   return val;
5778 }
5779
5780 /* Coerces the remaining template arguments in INNER_ARGS (from
5781    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5782    Returns the coerced argument pack. PARM_IDX is the position of this
5783    parameter in the template parameter list. ARGS is the original
5784    template argument list.  */
5785 static tree
5786 coerce_template_parameter_pack (tree parms,
5787                                 int parm_idx,
5788                                 tree args,
5789                                 tree inner_args,
5790                                 int arg_idx,
5791                                 tree new_args,
5792                                 int* lost,
5793                                 tree in_decl,
5794                                 tsubst_flags_t complain)
5795 {
5796   tree parm = TREE_VEC_ELT (parms, parm_idx);
5797   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5798   tree packed_args;
5799   tree argument_pack;
5800   tree packed_types = NULL_TREE;
5801
5802   if (arg_idx > nargs)
5803     arg_idx = nargs;
5804
5805   packed_args = make_tree_vec (nargs - arg_idx);
5806
5807   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5808       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5809     {
5810       /* When the template parameter is a non-type template
5811          parameter pack whose type uses parameter packs, we need
5812          to look at each of the template arguments
5813          separately. Build a vector of the types for these
5814          non-type template parameters in PACKED_TYPES.  */
5815       tree expansion 
5816         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5817       packed_types = tsubst_pack_expansion (expansion, args,
5818                                             complain, in_decl);
5819
5820       if (packed_types == error_mark_node)
5821         return error_mark_node;
5822
5823       /* Check that we have the right number of arguments.  */
5824       if (arg_idx < nargs
5825           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5826           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5827         {
5828           int needed_parms 
5829             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5830           error ("wrong number of template arguments (%d, should be %d)",
5831                  nargs, needed_parms);
5832           return error_mark_node;
5833         }
5834
5835       /* If we aren't able to check the actual arguments now
5836          (because they haven't been expanded yet), we can at least
5837          verify that all of the types used for the non-type
5838          template parameter pack are, in fact, valid for non-type
5839          template parameters.  */
5840       if (arg_idx < nargs 
5841           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5842         {
5843           int j, len = TREE_VEC_LENGTH (packed_types);
5844           for (j = 0; j < len; ++j)
5845             {
5846               tree t = TREE_VEC_ELT (packed_types, j);
5847               if (invalid_nontype_parm_type_p (t, complain))
5848                 return error_mark_node;
5849             }
5850         }
5851     }
5852
5853   /* Convert the remaining arguments, which will be a part of the
5854      parameter pack "parm".  */
5855   for (; arg_idx < nargs; ++arg_idx)
5856     {
5857       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5858       tree actual_parm = TREE_VALUE (parm);
5859
5860       if (packed_types && !PACK_EXPANSION_P (arg))
5861         {
5862           /* When we have a vector of types (corresponding to the
5863              non-type template parameter pack that uses parameter
5864              packs in its type, as mention above), and the
5865              argument is not an expansion (which expands to a
5866              currently unknown number of arguments), clone the
5867              parm and give it the next type in PACKED_TYPES.  */
5868           actual_parm = copy_node (actual_parm);
5869           TREE_TYPE (actual_parm) = 
5870             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5871         }
5872
5873       if (arg != error_mark_node)
5874         arg = convert_template_argument (actual_parm, 
5875                                          arg, new_args, complain, parm_idx,
5876                                          in_decl);
5877       if (arg == error_mark_node)
5878         (*lost)++;
5879       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5880     }
5881
5882   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5883       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5884     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5885   else
5886     {
5887       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5888       TREE_TYPE (argument_pack) 
5889         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5890       TREE_CONSTANT (argument_pack) = 1;
5891     }
5892
5893   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5894 #ifdef ENABLE_CHECKING
5895   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
5896                                        TREE_VEC_LENGTH (packed_args));
5897 #endif
5898   return argument_pack;
5899 }
5900
5901 /* Convert all template arguments to their appropriate types, and
5902    return a vector containing the innermost resulting template
5903    arguments.  If any error occurs, return error_mark_node. Error and
5904    warning messages are issued under control of COMPLAIN.
5905
5906    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5907    for arguments not specified in ARGS.  Otherwise, if
5908    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5909    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5910    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5911    ARGS.  */
5912
5913 static tree
5914 coerce_template_parms (tree parms,
5915                        tree args,
5916                        tree in_decl,
5917                        tsubst_flags_t complain,
5918                        bool require_all_args,
5919                        bool use_default_args)
5920 {
5921   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5922   tree inner_args;
5923   tree new_args;
5924   tree new_inner_args;
5925   int saved_unevaluated_operand;
5926   int saved_inhibit_evaluation_warnings;
5927
5928   /* When used as a boolean value, indicates whether this is a
5929      variadic template parameter list. Since it's an int, we can also
5930      subtract it from nparms to get the number of non-variadic
5931      parameters.  */
5932   int variadic_p = 0;
5933
5934   nparms = TREE_VEC_LENGTH (parms);
5935
5936   /* Determine if there are any parameter packs.  */
5937   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5938     {
5939       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5940       if (template_parameter_pack_p (tparm))
5941         ++variadic_p;
5942     }
5943
5944   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5945   /* If there are 0 or 1 parameter packs, we need to expand any argument
5946      packs so that we can deduce a parameter pack from some non-packed args
5947      followed by an argument pack, as in variadic85.C.  If there are more
5948      than that, we need to leave argument packs intact so the arguments are
5949      assigned to the right parameter packs.  This should only happen when
5950      dealing with a nested class inside a partial specialization of a class
5951      template, as in variadic92.C.  */
5952   if (variadic_p <= 1)
5953     inner_args = expand_template_argument_pack (inner_args);
5954
5955   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5956   if ((nargs > nparms && !variadic_p)
5957       || (nargs < nparms - variadic_p
5958           && require_all_args
5959           && (!use_default_args
5960               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5961                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5962     {
5963       if (complain & tf_error)
5964         {
5965           if (variadic_p)
5966             {
5967               --nparms;
5968               error ("wrong number of template arguments "
5969                      "(%d, should be %d or more)", nargs, nparms);
5970             }
5971           else
5972              error ("wrong number of template arguments "
5973                     "(%d, should be %d)", nargs, nparms);
5974
5975           if (in_decl)
5976             error ("provided for %q+D", in_decl);
5977         }
5978
5979       return error_mark_node;
5980     }
5981
5982   /* We need to evaluate the template arguments, even though this
5983      template-id may be nested within a "sizeof".  */
5984   saved_unevaluated_operand = cp_unevaluated_operand;
5985   cp_unevaluated_operand = 0;
5986   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5987   c_inhibit_evaluation_warnings = 0;
5988   new_inner_args = make_tree_vec (nparms);
5989   new_args = add_outermost_template_args (args, new_inner_args);
5990   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5991     {
5992       tree arg;
5993       tree parm;
5994
5995       /* Get the Ith template parameter.  */
5996       parm = TREE_VEC_ELT (parms, parm_idx);
5997  
5998       if (parm == error_mark_node)
5999       {
6000         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6001         continue;
6002       }
6003
6004       /* Calculate the next argument.  */
6005       if (arg_idx < nargs)
6006         arg = TREE_VEC_ELT (inner_args, arg_idx);
6007       else
6008         arg = NULL_TREE;
6009
6010       if (template_parameter_pack_p (TREE_VALUE (parm))
6011           && !(arg && ARGUMENT_PACK_P (arg)))
6012         {
6013           /* All remaining arguments will be placed in the
6014              template parameter pack PARM.  */
6015           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6016                                                 inner_args, arg_idx,
6017                                                 new_args, &lost,
6018                                                 in_decl, complain);
6019
6020           /* Store this argument.  */
6021           if (arg == error_mark_node)
6022             lost++;
6023           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6024
6025           /* We are done with all of the arguments.  */
6026           arg_idx = nargs;
6027           
6028           continue;
6029         }
6030       else if (arg)
6031         {
6032           if (PACK_EXPANSION_P (arg))
6033             {
6034               if (complain & tf_error)
6035                 {
6036                   /* FIXME this restriction was removed by N2555; see
6037                      bug 35722.  */
6038                   /* If ARG is a pack expansion, but PARM is not a
6039                      template parameter pack (if it were, we would have
6040                      handled it above), we're trying to expand into a
6041                      fixed-length argument list.  */
6042                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
6043                     sorry ("cannot expand %<%E%> into a fixed-length "
6044                            "argument list", arg);
6045                   else
6046                     sorry ("cannot expand %<%T%> into a fixed-length "
6047                            "argument list", arg);
6048                 }
6049               return error_mark_node;
6050             }
6051         }
6052       else if (require_all_args)
6053         {
6054           /* There must be a default arg in this case.  */
6055           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6056                                      complain, in_decl);
6057           /* The position of the first default template argument,
6058              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6059              Record that.  */
6060           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6061             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6062         }
6063       else
6064         break;
6065
6066       if (arg == error_mark_node)
6067         {
6068           if (complain & tf_error)
6069             error ("template argument %d is invalid", arg_idx + 1);
6070         }
6071       else if (!arg)
6072         /* This only occurs if there was an error in the template
6073            parameter list itself (which we would already have
6074            reported) that we are trying to recover from, e.g., a class
6075            template with a parameter list such as
6076            template<typename..., typename>.  */
6077         return error_mark_node;
6078       else
6079         arg = convert_template_argument (TREE_VALUE (parm),
6080                                          arg, new_args, complain, 
6081                                          parm_idx, in_decl);
6082
6083       if (arg == error_mark_node)
6084         lost++;
6085       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6086     }
6087   cp_unevaluated_operand = saved_unevaluated_operand;
6088   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6089
6090   if (lost)
6091     return error_mark_node;
6092
6093 #ifdef ENABLE_CHECKING
6094   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6095     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6096                                          TREE_VEC_LENGTH (new_inner_args));
6097 #endif
6098
6099   return new_inner_args;
6100 }
6101
6102 /* Returns 1 if template args OT and NT are equivalent.  */
6103
6104 static int
6105 template_args_equal (tree ot, tree nt)
6106 {
6107   if (nt == ot)
6108     return 1;
6109
6110   if (TREE_CODE (nt) == TREE_VEC)
6111     /* For member templates */
6112     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6113   else if (PACK_EXPANSION_P (ot))
6114     return PACK_EXPANSION_P (nt) 
6115       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6116                               PACK_EXPANSION_PATTERN (nt));
6117   else if (ARGUMENT_PACK_P (ot))
6118     {
6119       int i, len;
6120       tree opack, npack;
6121
6122       if (!ARGUMENT_PACK_P (nt))
6123         return 0;
6124
6125       opack = ARGUMENT_PACK_ARGS (ot);
6126       npack = ARGUMENT_PACK_ARGS (nt);
6127       len = TREE_VEC_LENGTH (opack);
6128       if (TREE_VEC_LENGTH (npack) != len)
6129         return 0;
6130       for (i = 0; i < len; ++i)
6131         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6132                                   TREE_VEC_ELT (npack, i)))
6133           return 0;
6134       return 1;
6135     }
6136   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6137     {
6138       /* We get here probably because we are in the middle of substituting
6139          into the pattern of a pack expansion. In that case the
6140          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6141          interested in. So we want to use the initial pack argument for
6142          the comparison.  */
6143       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6144       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6145         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6146       return template_args_equal (ot, nt);
6147     }
6148   else if (TYPE_P (nt))
6149     return TYPE_P (ot) && same_type_p (ot, nt);
6150   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6151     return 0;
6152   else
6153     return cp_tree_equal (ot, nt);
6154 }
6155
6156 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6157    of template arguments.  Returns 0 otherwise.  */
6158
6159 int
6160 comp_template_args (tree oldargs, tree newargs)
6161 {
6162   int i;
6163
6164   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6165     return 0;
6166
6167   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6168     {
6169       tree nt = TREE_VEC_ELT (newargs, i);
6170       tree ot = TREE_VEC_ELT (oldargs, i);
6171
6172       if (! template_args_equal (ot, nt))
6173         return 0;
6174     }
6175   return 1;
6176 }
6177
6178 static void
6179 add_pending_template (tree d)
6180 {
6181   tree ti = (TYPE_P (d)
6182              ? CLASSTYPE_TEMPLATE_INFO (d)
6183              : DECL_TEMPLATE_INFO (d));
6184   struct pending_template *pt;
6185   int level;
6186
6187   if (TI_PENDING_TEMPLATE_FLAG (ti))
6188     return;
6189
6190   /* We are called both from instantiate_decl, where we've already had a
6191      tinst_level pushed, and instantiate_template, where we haven't.
6192      Compensate.  */
6193   level = !current_tinst_level || current_tinst_level->decl != d;
6194
6195   if (level)
6196     push_tinst_level (d);
6197
6198   pt = ggc_alloc_pending_template ();
6199   pt->next = NULL;
6200   pt->tinst = current_tinst_level;
6201   if (last_pending_template)
6202     last_pending_template->next = pt;
6203   else
6204     pending_templates = pt;
6205
6206   last_pending_template = pt;
6207
6208   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6209
6210   if (level)
6211     pop_tinst_level ();
6212 }
6213
6214
6215 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6216    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6217    documentation for TEMPLATE_ID_EXPR.  */
6218
6219 tree
6220 lookup_template_function (tree fns, tree arglist)
6221 {
6222   tree type;
6223
6224   if (fns == error_mark_node || arglist == error_mark_node)
6225     return error_mark_node;
6226
6227   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6228   gcc_assert (fns && (is_overloaded_fn (fns)
6229                       || TREE_CODE (fns) == IDENTIFIER_NODE));
6230
6231   if (BASELINK_P (fns))
6232     {
6233       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6234                                          unknown_type_node,
6235                                          BASELINK_FUNCTIONS (fns),
6236                                          arglist);
6237       return fns;
6238     }
6239
6240   type = TREE_TYPE (fns);
6241   if (TREE_CODE (fns) == OVERLOAD || !type)
6242     type = unknown_type_node;
6243
6244   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6245 }
6246
6247 /* Within the scope of a template class S<T>, the name S gets bound
6248    (in build_self_reference) to a TYPE_DECL for the class, not a
6249    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6250    or one of its enclosing classes, and that type is a template,
6251    return the associated TEMPLATE_DECL.  Otherwise, the original
6252    DECL is returned.
6253
6254    Also handle the case when DECL is a TREE_LIST of ambiguous
6255    injected-class-names from different bases.  */
6256
6257 tree
6258 maybe_get_template_decl_from_type_decl (tree decl)
6259 {
6260   if (decl == NULL_TREE)
6261     return decl;
6262
6263   /* DR 176: A lookup that finds an injected-class-name (10.2
6264      [class.member.lookup]) can result in an ambiguity in certain cases
6265      (for example, if it is found in more than one base class). If all of
6266      the injected-class-names that are found refer to specializations of
6267      the same class template, and if the name is followed by a
6268      template-argument-list, the reference refers to the class template
6269      itself and not a specialization thereof, and is not ambiguous.  */
6270   if (TREE_CODE (decl) == TREE_LIST)
6271     {
6272       tree t, tmpl = NULL_TREE;
6273       for (t = decl; t; t = TREE_CHAIN (t))
6274         {
6275           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6276           if (!tmpl)
6277             tmpl = elt;
6278           else if (tmpl != elt)
6279             break;
6280         }
6281       if (tmpl && t == NULL_TREE)
6282         return tmpl;
6283       else
6284         return decl;
6285     }
6286
6287   return (decl != NULL_TREE
6288           && DECL_SELF_REFERENCE_P (decl)
6289           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6290     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6291 }
6292
6293 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6294    parameters, find the desired type.
6295
6296    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6297
6298    IN_DECL, if non-NULL, is the template declaration we are trying to
6299    instantiate.
6300
6301    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6302    the class we are looking up.
6303
6304    Issue error and warning messages under control of COMPLAIN.
6305
6306    If the template class is really a local class in a template
6307    function, then the FUNCTION_CONTEXT is the function in which it is
6308    being instantiated.
6309
6310    ??? Note that this function is currently called *twice* for each
6311    template-id: the first time from the parser, while creating the
6312    incomplete type (finish_template_type), and the second type during the
6313    real instantiation (instantiate_template_class). This is surely something
6314    that we want to avoid. It also causes some problems with argument
6315    coercion (see convert_nontype_argument for more information on this).  */
6316
6317 tree
6318 lookup_template_class (tree d1,
6319                        tree arglist,
6320                        tree in_decl,
6321                        tree context,
6322                        int entering_scope,
6323                        tsubst_flags_t complain)
6324 {
6325   tree templ = NULL_TREE, parmlist;
6326   tree t;
6327   spec_entry **slot;
6328   spec_entry *entry;
6329   spec_entry elt;
6330   hashval_t hash;
6331
6332   timevar_push (TV_NAME_LOOKUP);
6333
6334   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6335     {
6336       tree value = innermost_non_namespace_value (d1);
6337       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6338         templ = value;
6339       else
6340         {
6341           if (context)
6342             push_decl_namespace (context);
6343           templ = lookup_name (d1);
6344           templ = maybe_get_template_decl_from_type_decl (templ);
6345           if (context)
6346             pop_decl_namespace ();
6347         }
6348       if (templ)
6349         context = DECL_CONTEXT (templ);
6350     }
6351   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6352     {
6353       tree type = TREE_TYPE (d1);
6354
6355       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6356          an implicit typename for the second A.  Deal with it.  */
6357       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6358         type = TREE_TYPE (type);
6359
6360       if (CLASSTYPE_TEMPLATE_INFO (type))
6361         {
6362           templ = CLASSTYPE_TI_TEMPLATE (type);
6363           d1 = DECL_NAME (templ);
6364         }
6365     }
6366   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6367            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6368     {
6369       templ = TYPE_TI_TEMPLATE (d1);
6370       d1 = DECL_NAME (templ);
6371     }
6372   else if (TREE_CODE (d1) == TEMPLATE_DECL
6373            && DECL_TEMPLATE_RESULT (d1)
6374            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6375     {
6376       templ = d1;
6377       d1 = DECL_NAME (templ);
6378       context = DECL_CONTEXT (templ);
6379     }
6380
6381   /* Issue an error message if we didn't find a template.  */
6382   if (! templ)
6383     {
6384       if (complain & tf_error)
6385         error ("%qT is not a template", d1);
6386       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6387     }
6388
6389   if (TREE_CODE (templ) != TEMPLATE_DECL
6390          /* Make sure it's a user visible template, if it was named by
6391             the user.  */
6392       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6393           && !PRIMARY_TEMPLATE_P (templ)))
6394     {
6395       if (complain & tf_error)
6396         {
6397           error ("non-template type %qT used as a template", d1);
6398           if (in_decl)
6399             error ("for template declaration %q+D", in_decl);
6400         }
6401       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6402     }
6403
6404   complain &= ~tf_user;
6405
6406   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6407     {
6408       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6409          template arguments */
6410
6411       tree parm;
6412       tree arglist2;
6413       tree outer;
6414
6415       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6416
6417       /* Consider an example where a template template parameter declared as
6418
6419            template <class T, class U = std::allocator<T> > class TT
6420
6421          The template parameter level of T and U are one level larger than
6422          of TT.  To proper process the default argument of U, say when an
6423          instantiation `TT<int>' is seen, we need to build the full
6424          arguments containing {int} as the innermost level.  Outer levels,
6425          available when not appearing as default template argument, can be
6426          obtained from the arguments of the enclosing template.
6427
6428          Suppose that TT is later substituted with std::vector.  The above
6429          instantiation is `TT<int, std::allocator<T> >' with TT at
6430          level 1, and T at level 2, while the template arguments at level 1
6431          becomes {std::vector} and the inner level 2 is {int}.  */
6432
6433       outer = DECL_CONTEXT (templ);
6434       if (outer)
6435         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6436       else if (current_template_parms)
6437         /* This is an argument of the current template, so we haven't set
6438            DECL_CONTEXT yet.  */
6439         outer = current_template_args ();
6440
6441       if (outer)
6442         arglist = add_to_template_args (outer, arglist);
6443
6444       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6445                                         complain,
6446                                         /*require_all_args=*/true,
6447                                         /*use_default_args=*/true);
6448       if (arglist2 == error_mark_node
6449           || (!uses_template_parms (arglist2)
6450               && check_instantiated_args (templ, arglist2, complain)))
6451         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6452
6453       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6454       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6455     }
6456   else
6457     {
6458       tree template_type = TREE_TYPE (templ);
6459       tree gen_tmpl;
6460       tree type_decl;
6461       tree found = NULL_TREE;
6462       int arg_depth;
6463       int parm_depth;
6464       int is_dependent_type;
6465       int use_partial_inst_tmpl = false;
6466
6467       gen_tmpl = most_general_template (templ);
6468       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6469       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6470       arg_depth = TMPL_ARGS_DEPTH (arglist);
6471
6472       if (arg_depth == 1 && parm_depth > 1)
6473         {
6474           /* We've been given an incomplete set of template arguments.
6475              For example, given:
6476
6477                template <class T> struct S1 {
6478                  template <class U> struct S2 {};
6479                  template <class U> struct S2<U*> {};
6480                 };
6481
6482              we will be called with an ARGLIST of `U*', but the
6483              TEMPLATE will be `template <class T> template
6484              <class U> struct S1<T>::S2'.  We must fill in the missing
6485              arguments.  */
6486           arglist
6487             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6488                                            arglist);
6489           arg_depth = TMPL_ARGS_DEPTH (arglist);
6490         }
6491
6492       /* Now we should have enough arguments.  */
6493       gcc_assert (parm_depth == arg_depth);
6494
6495       /* From here on, we're only interested in the most general
6496          template.  */
6497
6498       /* Calculate the BOUND_ARGS.  These will be the args that are
6499          actually tsubst'd into the definition to create the
6500          instantiation.  */
6501       if (parm_depth > 1)
6502         {
6503           /* We have multiple levels of arguments to coerce, at once.  */
6504           int i;
6505           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6506
6507           tree bound_args = make_tree_vec (parm_depth);
6508
6509           for (i = saved_depth,
6510                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6511                i > 0 && t != NULL_TREE;
6512                --i, t = TREE_CHAIN (t))
6513             {
6514               tree a = coerce_template_parms (TREE_VALUE (t),
6515                                               arglist, gen_tmpl,
6516                                               complain,
6517                                               /*require_all_args=*/true,
6518                                               /*use_default_args=*/true);
6519
6520               /* Don't process further if one of the levels fails.  */
6521               if (a == error_mark_node)
6522                 {
6523                   /* Restore the ARGLIST to its full size.  */
6524                   TREE_VEC_LENGTH (arglist) = saved_depth;
6525                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6526                 }
6527
6528               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6529
6530               /* We temporarily reduce the length of the ARGLIST so
6531                  that coerce_template_parms will see only the arguments
6532                  corresponding to the template parameters it is
6533                  examining.  */
6534               TREE_VEC_LENGTH (arglist)--;
6535             }
6536
6537           /* Restore the ARGLIST to its full size.  */
6538           TREE_VEC_LENGTH (arglist) = saved_depth;
6539
6540           arglist = bound_args;
6541         }
6542       else
6543         arglist
6544           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6545                                    INNERMOST_TEMPLATE_ARGS (arglist),
6546                                    gen_tmpl,
6547                                    complain,
6548                                    /*require_all_args=*/true,
6549                                    /*use_default_args=*/true);
6550
6551       if (arglist == error_mark_node)
6552         /* We were unable to bind the arguments.  */
6553         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6554
6555       /* In the scope of a template class, explicit references to the
6556          template class refer to the type of the template, not any
6557          instantiation of it.  For example, in:
6558
6559            template <class T> class C { void f(C<T>); }
6560
6561          the `C<T>' is just the same as `C'.  Outside of the
6562          class, however, such a reference is an instantiation.  */
6563       if ((entering_scope
6564            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6565            || currently_open_class (template_type))
6566           /* comp_template_args is expensive, check it last.  */
6567           && comp_template_args (TYPE_TI_ARGS (template_type),
6568                                  arglist))
6569         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6570
6571       /* If we already have this specialization, return it.  */
6572       elt.tmpl = gen_tmpl;
6573       elt.args = arglist;
6574       hash = hash_specialization (&elt);
6575       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6576                                                   &elt, hash);
6577
6578       if (entry)
6579         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6580
6581       is_dependent_type = uses_template_parms (arglist);
6582
6583       /* If the deduced arguments are invalid, then the binding
6584          failed.  */
6585       if (!is_dependent_type
6586           && check_instantiated_args (gen_tmpl,
6587                                       INNERMOST_TEMPLATE_ARGS (arglist),
6588                                       complain))
6589         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6590
6591       if (!is_dependent_type
6592           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6593           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6594           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6595         {
6596           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6597                                       DECL_NAME (gen_tmpl),
6598                                       /*tag_scope=*/ts_global);
6599           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6600         }
6601
6602       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6603                         complain, in_decl);
6604       if (!context)
6605         context = global_namespace;
6606
6607       /* Create the type.  */
6608       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6609         {
6610           if (!is_dependent_type)
6611             {
6612               set_current_access_from_decl (TYPE_NAME (template_type));
6613               t = start_enum (TYPE_IDENTIFIER (template_type),
6614                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6615                                       arglist, complain, in_decl),
6616                               SCOPED_ENUM_P (template_type));
6617             }
6618           else
6619             {
6620               /* We don't want to call start_enum for this type, since
6621                  the values for the enumeration constants may involve
6622                  template parameters.  And, no one should be interested
6623                  in the enumeration constants for such a type.  */
6624               t = cxx_make_type (ENUMERAL_TYPE);
6625               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6626             }
6627         }
6628       else
6629         {
6630           t = make_class_type (TREE_CODE (template_type));
6631           CLASSTYPE_DECLARED_CLASS (t)
6632             = CLASSTYPE_DECLARED_CLASS (template_type);
6633           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6634           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6635
6636           /* A local class.  Make sure the decl gets registered properly.  */
6637           if (context == current_function_decl)
6638             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6639
6640           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6641             /* This instantiation is another name for the primary
6642                template type. Set the TYPE_CANONICAL field
6643                appropriately. */
6644             TYPE_CANONICAL (t) = template_type;
6645           else if (any_template_arguments_need_structural_equality_p (arglist))
6646             /* Some of the template arguments require structural
6647                equality testing, so this template class requires
6648                structural equality testing. */
6649             SET_TYPE_STRUCTURAL_EQUALITY (t);
6650         }
6651
6652       /* If we called start_enum or pushtag above, this information
6653          will already be set up.  */
6654       if (!TYPE_NAME (t))
6655         {
6656           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6657
6658           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6659           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6660           DECL_SOURCE_LOCATION (type_decl)
6661             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6662         }
6663       else
6664         type_decl = TYPE_NAME (t);
6665
6666       TREE_PRIVATE (type_decl)
6667         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6668       TREE_PROTECTED (type_decl)
6669         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6670       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6671         {
6672           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6673           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6674         }
6675
6676       /* Let's consider the explicit specialization of a member
6677          of a class template specialization that is implicitely instantiated,
6678          e.g.:
6679              template<class T>
6680              struct S
6681              {
6682                template<class U> struct M {}; //#0
6683              };
6684
6685              template<>
6686              template<>
6687              struct S<int>::M<char> //#1
6688              {
6689                int i;
6690              };
6691         [temp.expl.spec]/4 says this is valid.
6692
6693         In this case, when we write:
6694         S<int>::M<char> m;
6695
6696         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
6697         the one of #0.
6698
6699         When we encounter #1, we want to store the partial instantiation
6700         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
6701
6702         For all cases other than this "explicit specialization of member of a
6703         class template", we just want to store the most general template into
6704         the CLASSTYPE_TI_TEMPLATE of M.
6705
6706         This case of "explicit specialization of member of a class template"
6707         only happens when:
6708         1/ the enclosing class is an instantiation of, and therefore not
6709         the same as, the context of the most general template, and
6710         2/ we aren't looking at the partial instantiation itself, i.e.
6711         the innermost arguments are not the same as the innermost parms of
6712         the most general template.
6713
6714         So it's only when 1/ and 2/ happens that we want to use the partial
6715         instantiation of the member template in lieu of its most general
6716         template.  */
6717
6718       if (PRIMARY_TEMPLATE_P (gen_tmpl)
6719           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
6720           /* the enclosing class must be an instantiation...  */
6721           && CLASS_TYPE_P (context)
6722           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
6723         {
6724           tree partial_inst_args;
6725           TREE_VEC_LENGTH (arglist)--;
6726           ++processing_template_decl;
6727           partial_inst_args =
6728             tsubst (INNERMOST_TEMPLATE_ARGS
6729                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
6730                     arglist, complain, NULL_TREE);
6731           --processing_template_decl;
6732           TREE_VEC_LENGTH (arglist)++;
6733           use_partial_inst_tmpl =
6734             /*...and we must not be looking at the partial instantiation
6735              itself. */
6736             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
6737                                  partial_inst_args);
6738         }
6739
6740       if (!use_partial_inst_tmpl)
6741         /* This case is easy; there are no member templates involved.  */
6742         found = gen_tmpl;
6743       else
6744         {
6745           /* This is a full instantiation of a member template.  Find
6746              the partial instantiation of which this is an instance.  */
6747
6748           /* Temporarily reduce by one the number of levels in the ARGLIST
6749              so as to avoid comparing the last set of arguments.  */
6750           TREE_VEC_LENGTH (arglist)--;
6751           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6752           TREE_VEC_LENGTH (arglist)++;
6753           found = CLASSTYPE_TI_TEMPLATE (found);
6754         }
6755
6756       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
6757
6758       elt.spec = t;
6759       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6760                                                        &elt, hash, INSERT);
6761       *slot = ggc_alloc_spec_entry ();
6762       **slot = elt;
6763
6764       /* Note this use of the partial instantiation so we can check it
6765          later in maybe_process_partial_specialization.  */
6766       DECL_TEMPLATE_INSTANTIATIONS (templ)
6767         = tree_cons (arglist, t,
6768                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6769
6770       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
6771         /* Now that the type has been registered on the instantiations
6772            list, we set up the enumerators.  Because the enumeration
6773            constants may involve the enumeration type itself, we make
6774            sure to register the type first, and then create the
6775            constants.  That way, doing tsubst_expr for the enumeration
6776            constants won't result in recursive calls here; we'll find
6777            the instantiation and exit above.  */
6778         tsubst_enum (template_type, t, arglist);
6779
6780       if (is_dependent_type)
6781         /* If the type makes use of template parameters, the
6782            code that generates debugging information will crash.  */
6783         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6784
6785       /* Possibly limit visibility based on template args.  */
6786       TREE_PUBLIC (type_decl) = 1;
6787       determine_visibility (type_decl);
6788
6789       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6790     }
6791   timevar_pop (TV_NAME_LOOKUP);
6792 }
6793 \f
6794 struct pair_fn_data
6795 {
6796   tree_fn_t fn;
6797   void *data;
6798   /* True when we should also visit template parameters that occur in
6799      non-deduced contexts.  */
6800   bool include_nondeduced_p;
6801   struct pointer_set_t *visited;
6802 };
6803
6804 /* Called from for_each_template_parm via walk_tree.  */
6805
6806 static tree
6807 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6808 {
6809   tree t = *tp;
6810   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6811   tree_fn_t fn = pfd->fn;
6812   void *data = pfd->data;
6813
6814   if (TYPE_P (t)
6815       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6816       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6817                                  pfd->include_nondeduced_p))
6818     return error_mark_node;
6819
6820   switch (TREE_CODE (t))
6821     {
6822     case RECORD_TYPE:
6823       if (TYPE_PTRMEMFUNC_P (t))
6824         break;
6825       /* Fall through.  */
6826
6827     case UNION_TYPE:
6828     case ENUMERAL_TYPE:
6829       if (!TYPE_TEMPLATE_INFO (t))
6830         *walk_subtrees = 0;
6831       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
6832                                        fn, data, pfd->visited, 
6833                                        pfd->include_nondeduced_p))
6834         return error_mark_node;
6835       break;
6836
6837     case INTEGER_TYPE:
6838       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6839                                   fn, data, pfd->visited, 
6840                                   pfd->include_nondeduced_p)
6841           || for_each_template_parm (TYPE_MAX_VALUE (t),
6842                                      fn, data, pfd->visited,
6843                                      pfd->include_nondeduced_p))
6844         return error_mark_node;
6845       break;
6846
6847     case METHOD_TYPE:
6848       /* Since we're not going to walk subtrees, we have to do this
6849          explicitly here.  */
6850       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6851                                   pfd->visited, pfd->include_nondeduced_p))
6852         return error_mark_node;
6853       /* Fall through.  */
6854
6855     case FUNCTION_TYPE:
6856       /* Check the return type.  */
6857       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6858                                   pfd->include_nondeduced_p))
6859         return error_mark_node;
6860
6861       /* Check the parameter types.  Since default arguments are not
6862          instantiated until they are needed, the TYPE_ARG_TYPES may
6863          contain expressions that involve template parameters.  But,
6864          no-one should be looking at them yet.  And, once they're
6865          instantiated, they don't contain template parameters, so
6866          there's no point in looking at them then, either.  */
6867       {
6868         tree parm;
6869
6870         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6871           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6872                                       pfd->visited, pfd->include_nondeduced_p))
6873             return error_mark_node;
6874
6875         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6876            want walk_tree walking into them itself.  */
6877         *walk_subtrees = 0;
6878       }
6879       break;
6880
6881     case TYPEOF_TYPE:
6882       if (pfd->include_nondeduced_p
6883           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6884                                      pfd->visited, 
6885                                      pfd->include_nondeduced_p))
6886         return error_mark_node;
6887       break;
6888
6889     case FUNCTION_DECL:
6890     case VAR_DECL:
6891       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6892           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6893                                      pfd->visited, pfd->include_nondeduced_p))
6894         return error_mark_node;
6895       /* Fall through.  */
6896
6897     case PARM_DECL:
6898     case CONST_DECL:
6899       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6900           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6901                                      pfd->visited, pfd->include_nondeduced_p))
6902         return error_mark_node;
6903       if (DECL_CONTEXT (t)
6904           && pfd->include_nondeduced_p
6905           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6906                                      pfd->visited, pfd->include_nondeduced_p))
6907         return error_mark_node;
6908       break;
6909
6910     case BOUND_TEMPLATE_TEMPLATE_PARM:
6911       /* Record template parameters such as `T' inside `TT<T>'.  */
6912       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6913                                   pfd->include_nondeduced_p))
6914         return error_mark_node;
6915       /* Fall through.  */
6916
6917     case TEMPLATE_TEMPLATE_PARM:
6918     case TEMPLATE_TYPE_PARM:
6919     case TEMPLATE_PARM_INDEX:
6920       if (fn && (*fn)(t, data))
6921         return error_mark_node;
6922       else if (!fn)
6923         return error_mark_node;
6924       break;
6925
6926     case TEMPLATE_DECL:
6927       /* A template template parameter is encountered.  */
6928       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6929           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6930                                      pfd->include_nondeduced_p))
6931         return error_mark_node;
6932
6933       /* Already substituted template template parameter */
6934       *walk_subtrees = 0;
6935       break;
6936
6937     case TYPENAME_TYPE:
6938       if (!fn
6939           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6940                                      data, pfd->visited, 
6941                                      pfd->include_nondeduced_p))
6942         return error_mark_node;
6943       break;
6944
6945     case CONSTRUCTOR:
6946       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6947           && pfd->include_nondeduced_p
6948           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6949                                      (TREE_TYPE (t)), fn, data,
6950                                      pfd->visited, pfd->include_nondeduced_p))
6951         return error_mark_node;
6952       break;
6953
6954     case INDIRECT_REF:
6955     case COMPONENT_REF:
6956       /* If there's no type, then this thing must be some expression
6957          involving template parameters.  */
6958       if (!fn && !TREE_TYPE (t))
6959         return error_mark_node;
6960       break;
6961
6962     case MODOP_EXPR:
6963     case CAST_EXPR:
6964     case REINTERPRET_CAST_EXPR:
6965     case CONST_CAST_EXPR:
6966     case STATIC_CAST_EXPR:
6967     case DYNAMIC_CAST_EXPR:
6968     case ARROW_EXPR:
6969     case DOTSTAR_EXPR:
6970     case TYPEID_EXPR:
6971     case PSEUDO_DTOR_EXPR:
6972       if (!fn)
6973         return error_mark_node;
6974       break;
6975
6976     default:
6977       break;
6978     }
6979
6980   /* We didn't find any template parameters we liked.  */
6981   return NULL_TREE;
6982 }
6983
6984 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6985    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6986    call FN with the parameter and the DATA.
6987    If FN returns nonzero, the iteration is terminated, and
6988    for_each_template_parm returns 1.  Otherwise, the iteration
6989    continues.  If FN never returns a nonzero value, the value
6990    returned by for_each_template_parm is 0.  If FN is NULL, it is
6991    considered to be the function which always returns 1.
6992
6993    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6994    parameters that occur in non-deduced contexts.  When false, only
6995    visits those template parameters that can be deduced.  */
6996
6997 static int
6998 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6999                         struct pointer_set_t *visited,
7000                         bool include_nondeduced_p)
7001 {
7002   struct pair_fn_data pfd;
7003   int result;
7004
7005   /* Set up.  */
7006   pfd.fn = fn;
7007   pfd.data = data;
7008   pfd.include_nondeduced_p = include_nondeduced_p;
7009
7010   /* Walk the tree.  (Conceptually, we would like to walk without
7011      duplicates, but for_each_template_parm_r recursively calls
7012      for_each_template_parm, so we would need to reorganize a fair
7013      bit to use walk_tree_without_duplicates, so we keep our own
7014      visited list.)  */
7015   if (visited)
7016     pfd.visited = visited;
7017   else
7018     pfd.visited = pointer_set_create ();
7019   result = cp_walk_tree (&t,
7020                          for_each_template_parm_r,
7021                          &pfd,
7022                          pfd.visited) != NULL_TREE;
7023
7024   /* Clean up.  */
7025   if (!visited)
7026     {
7027       pointer_set_destroy (pfd.visited);
7028       pfd.visited = 0;
7029     }
7030
7031   return result;
7032 }
7033
7034 /* Returns true if T depends on any template parameter.  */
7035
7036 int
7037 uses_template_parms (tree t)
7038 {
7039   bool dependent_p;
7040   int saved_processing_template_decl;
7041
7042   saved_processing_template_decl = processing_template_decl;
7043   if (!saved_processing_template_decl)
7044     processing_template_decl = 1;
7045   if (TYPE_P (t))
7046     dependent_p = dependent_type_p (t);
7047   else if (TREE_CODE (t) == TREE_VEC)
7048     dependent_p = any_dependent_template_arguments_p (t);
7049   else if (TREE_CODE (t) == TREE_LIST)
7050     dependent_p = (uses_template_parms (TREE_VALUE (t))
7051                    || uses_template_parms (TREE_CHAIN (t)));
7052   else if (TREE_CODE (t) == TYPE_DECL)
7053     dependent_p = dependent_type_p (TREE_TYPE (t));
7054   else if (DECL_P (t)
7055            || EXPR_P (t)
7056            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7057            || TREE_CODE (t) == OVERLOAD
7058            || TREE_CODE (t) == BASELINK
7059            || TREE_CODE (t) == IDENTIFIER_NODE
7060            || TREE_CODE (t) == TRAIT_EXPR
7061            || TREE_CODE (t) == CONSTRUCTOR
7062            || CONSTANT_CLASS_P (t))
7063     dependent_p = (type_dependent_expression_p (t)
7064                    || value_dependent_expression_p (t));
7065   else
7066     {
7067       gcc_assert (t == error_mark_node);
7068       dependent_p = false;
7069     }
7070
7071   processing_template_decl = saved_processing_template_decl;
7072
7073   return dependent_p;
7074 }
7075
7076 /* Returns true if T depends on any template parameter with level LEVEL.  */
7077
7078 int
7079 uses_template_parms_level (tree t, int level)
7080 {
7081   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7082                                  /*include_nondeduced_p=*/true);
7083 }
7084
7085 static int tinst_depth;
7086 extern int max_tinst_depth;
7087 #ifdef GATHER_STATISTICS
7088 int depth_reached;
7089 #endif
7090 static int tinst_level_tick;
7091 static int last_template_error_tick;
7092
7093 /* We're starting to instantiate D; record the template instantiation context
7094    for diagnostics and to restore it later.  */
7095
7096 int
7097 push_tinst_level (tree d)
7098 {
7099   struct tinst_level *new_level;
7100
7101   if (tinst_depth >= max_tinst_depth)
7102     {
7103       /* If the instantiation in question still has unbound template parms,
7104          we don't really care if we can't instantiate it, so just return.
7105          This happens with base instantiation for implicit `typename'.  */
7106       if (uses_template_parms (d))
7107         return 0;
7108
7109       last_template_error_tick = tinst_level_tick;
7110       error ("template instantiation depth exceeds maximum of %d (use "
7111              "-ftemplate-depth= to increase the maximum) instantiating %qD",
7112              max_tinst_depth, d);
7113
7114       print_instantiation_context ();
7115
7116       return 0;
7117     }
7118
7119   new_level = ggc_alloc_tinst_level ();
7120   new_level->decl = d;
7121   new_level->locus = input_location;
7122   new_level->in_system_header_p = in_system_header;
7123   new_level->next = current_tinst_level;
7124   current_tinst_level = new_level;
7125
7126   ++tinst_depth;
7127 #ifdef GATHER_STATISTICS
7128   if (tinst_depth > depth_reached)
7129     depth_reached = tinst_depth;
7130 #endif
7131
7132   ++tinst_level_tick;
7133   return 1;
7134 }
7135
7136 /* We're done instantiating this template; return to the instantiation
7137    context.  */
7138
7139 void
7140 pop_tinst_level (void)
7141 {
7142   /* Restore the filename and line number stashed away when we started
7143      this instantiation.  */
7144   input_location = current_tinst_level->locus;
7145   current_tinst_level = current_tinst_level->next;
7146   --tinst_depth;
7147   ++tinst_level_tick;
7148 }
7149
7150 /* We're instantiating a deferred template; restore the template
7151    instantiation context in which the instantiation was requested, which
7152    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7153
7154 static tree
7155 reopen_tinst_level (struct tinst_level *level)
7156 {
7157   struct tinst_level *t;
7158
7159   tinst_depth = 0;
7160   for (t = level; t; t = t->next)
7161     ++tinst_depth;
7162
7163   current_tinst_level = level;
7164   pop_tinst_level ();
7165   return level->decl;
7166 }
7167
7168 /* Returns the TINST_LEVEL which gives the original instantiation
7169    context.  */
7170
7171 struct tinst_level *
7172 outermost_tinst_level (void)
7173 {
7174   struct tinst_level *level = current_tinst_level;
7175   if (level)
7176     while (level->next)
7177       level = level->next;
7178   return level;
7179 }
7180
7181 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7182
7183 bool
7184 parameter_of_template_p (tree parm, tree templ)
7185 {
7186   tree parms;
7187   int i;
7188
7189   if (!parm || !templ)
7190     return false;
7191
7192   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7193   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7194
7195   parms = DECL_TEMPLATE_PARMS (templ);
7196   parms = INNERMOST_TEMPLATE_PARMS (parms);
7197
7198   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7199     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7200       return true;
7201
7202   return false;
7203 }
7204
7205 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7206    vector of template arguments, as for tsubst.
7207
7208    Returns an appropriate tsubst'd friend declaration.  */
7209
7210 static tree
7211 tsubst_friend_function (tree decl, tree args)
7212 {
7213   tree new_friend;
7214
7215   if (TREE_CODE (decl) == FUNCTION_DECL
7216       && DECL_TEMPLATE_INSTANTIATION (decl)
7217       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7218     /* This was a friend declared with an explicit template
7219        argument list, e.g.:
7220
7221        friend void f<>(T);
7222
7223        to indicate that f was a template instantiation, not a new
7224        function declaration.  Now, we have to figure out what
7225        instantiation of what template.  */
7226     {
7227       tree template_id, arglist, fns;
7228       tree new_args;
7229       tree tmpl;
7230       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7231
7232       /* Friend functions are looked up in the containing namespace scope.
7233          We must enter that scope, to avoid finding member functions of the
7234          current class with same name.  */
7235       push_nested_namespace (ns);
7236       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7237                          tf_warning_or_error, NULL_TREE,
7238                          /*integral_constant_expression_p=*/false);
7239       pop_nested_namespace (ns);
7240       arglist = tsubst (DECL_TI_ARGS (decl), args,
7241                         tf_warning_or_error, NULL_TREE);
7242       template_id = lookup_template_function (fns, arglist);
7243
7244       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7245       tmpl = determine_specialization (template_id, new_friend,
7246                                        &new_args,
7247                                        /*need_member_template=*/0,
7248                                        TREE_VEC_LENGTH (args),
7249                                        tsk_none);
7250       return instantiate_template (tmpl, new_args, tf_error);
7251     }
7252
7253   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7254
7255   /* The NEW_FRIEND will look like an instantiation, to the
7256      compiler, but is not an instantiation from the point of view of
7257      the language.  For example, we might have had:
7258
7259      template <class T> struct S {
7260        template <class U> friend void f(T, U);
7261      };
7262
7263      Then, in S<int>, template <class U> void f(int, U) is not an
7264      instantiation of anything.  */
7265   if (new_friend == error_mark_node)
7266     return error_mark_node;
7267
7268   DECL_USE_TEMPLATE (new_friend) = 0;
7269   if (TREE_CODE (decl) == TEMPLATE_DECL)
7270     {
7271       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7272       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7273         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7274     }
7275
7276   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7277      is not a template instantiation and should not be mangled like
7278      one.  Therefore, we forget the mangling here; we'll recompute it
7279      later if we need it.  */
7280   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7281     {
7282       SET_DECL_RTL (new_friend, NULL);
7283       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7284     }
7285
7286   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7287     {
7288       tree old_decl;
7289       tree new_friend_template_info;
7290       tree new_friend_result_template_info;
7291       tree ns;
7292       int  new_friend_is_defn;
7293
7294       /* We must save some information from NEW_FRIEND before calling
7295          duplicate decls since that function will free NEW_FRIEND if
7296          possible.  */
7297       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7298       new_friend_is_defn =
7299             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7300                            (template_for_substitution (new_friend)))
7301              != NULL_TREE);
7302       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7303         {
7304           /* This declaration is a `primary' template.  */
7305           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7306
7307           new_friend_result_template_info
7308             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7309         }
7310       else
7311         new_friend_result_template_info = NULL_TREE;
7312
7313       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7314       if (new_friend_is_defn)
7315         DECL_INITIAL (new_friend) = error_mark_node;
7316
7317       /* Inside pushdecl_namespace_level, we will push into the
7318          current namespace. However, the friend function should go
7319          into the namespace of the template.  */
7320       ns = decl_namespace_context (new_friend);
7321       push_nested_namespace (ns);
7322       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7323       pop_nested_namespace (ns);
7324
7325       if (old_decl == error_mark_node)
7326         return error_mark_node;
7327
7328       if (old_decl != new_friend)
7329         {
7330           /* This new friend declaration matched an existing
7331              declaration.  For example, given:
7332
7333                template <class T> void f(T);
7334                template <class U> class C {
7335                  template <class T> friend void f(T) {}
7336                };
7337
7338              the friend declaration actually provides the definition
7339              of `f', once C has been instantiated for some type.  So,
7340              old_decl will be the out-of-class template declaration,
7341              while new_friend is the in-class definition.
7342
7343              But, if `f' was called before this point, the
7344              instantiation of `f' will have DECL_TI_ARGS corresponding
7345              to `T' but not to `U', references to which might appear
7346              in the definition of `f'.  Previously, the most general
7347              template for an instantiation of `f' was the out-of-class
7348              version; now it is the in-class version.  Therefore, we
7349              run through all specialization of `f', adding to their
7350              DECL_TI_ARGS appropriately.  In particular, they need a
7351              new set of outer arguments, corresponding to the
7352              arguments for this class instantiation.
7353
7354              The same situation can arise with something like this:
7355
7356                friend void f(int);
7357                template <class T> class C {
7358                  friend void f(T) {}
7359                };
7360
7361              when `C<int>' is instantiated.  Now, `f(int)' is defined
7362              in the class.  */
7363
7364           if (!new_friend_is_defn)
7365             /* On the other hand, if the in-class declaration does
7366                *not* provide a definition, then we don't want to alter
7367                existing definitions.  We can just leave everything
7368                alone.  */
7369             ;
7370           else
7371             {
7372               tree new_template = TI_TEMPLATE (new_friend_template_info);
7373               tree new_args = TI_ARGS (new_friend_template_info);
7374
7375               /* Overwrite whatever template info was there before, if
7376                  any, with the new template information pertaining to
7377                  the declaration.  */
7378               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7379
7380               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7381                 {
7382                   /* We should have called reregister_specialization in
7383                      duplicate_decls.  */
7384                   gcc_assert (retrieve_specialization (new_template,
7385                                                        new_args, 0)
7386                               == old_decl);
7387
7388                   /* Instantiate it if the global has already been used.  */
7389                   if (DECL_ODR_USED (old_decl))
7390                     instantiate_decl (old_decl, /*defer_ok=*/true,
7391                                       /*expl_inst_class_mem_p=*/false);
7392                 }
7393               else
7394                 {
7395                   tree t;
7396
7397                   /* Indicate that the old function template is a partial
7398                      instantiation.  */
7399                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7400                     = new_friend_result_template_info;
7401
7402                   gcc_assert (new_template
7403                               == most_general_template (new_template));
7404                   gcc_assert (new_template != old_decl);
7405
7406                   /* Reassign any specializations already in the hash table
7407                      to the new more general template, and add the
7408                      additional template args.  */
7409                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7410                        t != NULL_TREE;
7411                        t = TREE_CHAIN (t))
7412                     {
7413                       tree spec = TREE_VALUE (t);
7414                       spec_entry elt;
7415
7416                       elt.tmpl = old_decl;
7417                       elt.args = DECL_TI_ARGS (spec);
7418                       elt.spec = NULL_TREE;
7419
7420                       htab_remove_elt (decl_specializations, &elt);
7421
7422                       DECL_TI_ARGS (spec)
7423                         = add_outermost_template_args (new_args,
7424                                                        DECL_TI_ARGS (spec));
7425
7426                       register_specialization
7427                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7428
7429                     }
7430                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7431                 }
7432             }
7433
7434           /* The information from NEW_FRIEND has been merged into OLD_DECL
7435              by duplicate_decls.  */
7436           new_friend = old_decl;
7437         }
7438     }
7439   else
7440     {
7441       tree context = DECL_CONTEXT (new_friend);
7442       bool dependent_p;
7443
7444       /* In the code
7445            template <class T> class C {
7446              template <class U> friend void C1<U>::f (); // case 1
7447              friend void C2<T>::f ();                    // case 2
7448            };
7449          we only need to make sure CONTEXT is a complete type for
7450          case 2.  To distinguish between the two cases, we note that
7451          CONTEXT of case 1 remains dependent type after tsubst while
7452          this isn't true for case 2.  */
7453       ++processing_template_decl;
7454       dependent_p = dependent_type_p (context);
7455       --processing_template_decl;
7456
7457       if (!dependent_p
7458           && !complete_type_or_else (context, NULL_TREE))
7459         return error_mark_node;
7460
7461       if (COMPLETE_TYPE_P (context))
7462         {
7463           /* Check to see that the declaration is really present, and,
7464              possibly obtain an improved declaration.  */
7465           tree fn = check_classfn (context,
7466                                    new_friend, NULL_TREE);
7467
7468           if (fn)
7469             new_friend = fn;
7470         }
7471     }
7472
7473   return new_friend;
7474 }
7475
7476 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7477    template arguments, as for tsubst.
7478
7479    Returns an appropriate tsubst'd friend type or error_mark_node on
7480    failure.  */
7481
7482 static tree
7483 tsubst_friend_class (tree friend_tmpl, tree args)
7484 {
7485   tree friend_type;
7486   tree tmpl;
7487   tree context;
7488
7489   context = DECL_CONTEXT (friend_tmpl);
7490
7491   if (context)
7492     {
7493       if (TREE_CODE (context) == NAMESPACE_DECL)
7494         push_nested_namespace (context);
7495       else
7496         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7497     }
7498
7499   /* Look for a class template declaration.  We look for hidden names
7500      because two friend declarations of the same template are the
7501      same.  For example, in:
7502
7503        struct A { 
7504          template <typename> friend class F;
7505        };
7506        template <typename> struct B { 
7507          template <typename> friend class F;
7508        };
7509
7510      both F templates are the same.  */
7511   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7512                            /*block_p=*/true, 0, 
7513                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7514
7515   /* But, if we don't find one, it might be because we're in a
7516      situation like this:
7517
7518        template <class T>
7519        struct S {
7520          template <class U>
7521          friend struct S;
7522        };
7523
7524      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7525      for `S<int>', not the TEMPLATE_DECL.  */
7526   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7527     {
7528       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7529       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7530     }
7531
7532   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7533     {
7534       /* The friend template has already been declared.  Just
7535          check to see that the declarations match, and install any new
7536          default parameters.  We must tsubst the default parameters,
7537          of course.  We only need the innermost template parameters
7538          because that is all that redeclare_class_template will look
7539          at.  */
7540       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7541           > TMPL_ARGS_DEPTH (args))
7542         {
7543           tree parms;
7544           location_t saved_input_location;
7545           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7546                                          args, tf_warning_or_error);
7547
7548           saved_input_location = input_location;
7549           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7550           redeclare_class_template (TREE_TYPE (tmpl), parms);
7551           input_location = saved_input_location;
7552           
7553         }
7554
7555       friend_type = TREE_TYPE (tmpl);
7556     }
7557   else
7558     {
7559       /* The friend template has not already been declared.  In this
7560          case, the instantiation of the template class will cause the
7561          injection of this template into the global scope.  */
7562       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7563       if (tmpl == error_mark_node)
7564         return error_mark_node;
7565
7566       /* The new TMPL is not an instantiation of anything, so we
7567          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7568          the new type because that is supposed to be the corresponding
7569          template decl, i.e., TMPL.  */
7570       DECL_USE_TEMPLATE (tmpl) = 0;
7571       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7572       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7573       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7574         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7575
7576       /* Inject this template into the global scope.  */
7577       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7578     }
7579
7580   if (context)
7581     {
7582       if (TREE_CODE (context) == NAMESPACE_DECL)
7583         pop_nested_namespace (context);
7584       else
7585         pop_nested_class ();
7586     }
7587
7588   return friend_type;
7589 }
7590
7591 /* Returns zero if TYPE cannot be completed later due to circularity.
7592    Otherwise returns one.  */
7593
7594 static int
7595 can_complete_type_without_circularity (tree type)
7596 {
7597   if (type == NULL_TREE || type == error_mark_node)
7598     return 0;
7599   else if (COMPLETE_TYPE_P (type))
7600     return 1;
7601   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7602     return can_complete_type_without_circularity (TREE_TYPE (type));
7603   else if (CLASS_TYPE_P (type)
7604            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7605     return 0;
7606   else
7607     return 1;
7608 }
7609
7610 /* Apply any attributes which had to be deferred until instantiation
7611    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7612    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7613
7614 static void
7615 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7616                                 tree args, tsubst_flags_t complain, tree in_decl)
7617 {
7618   tree last_dep = NULL_TREE;
7619   tree t;
7620   tree *p;
7621
7622   for (t = attributes; t; t = TREE_CHAIN (t))
7623     if (ATTR_IS_DEPENDENT (t))
7624       {
7625         last_dep = t;
7626         attributes = copy_list (attributes);
7627         break;
7628       }
7629
7630   if (DECL_P (*decl_p))
7631     {
7632       if (TREE_TYPE (*decl_p) == error_mark_node)
7633         return;
7634       p = &DECL_ATTRIBUTES (*decl_p);
7635     }
7636   else
7637     p = &TYPE_ATTRIBUTES (*decl_p);
7638
7639   if (last_dep)
7640     {
7641       tree late_attrs = NULL_TREE;
7642       tree *q = &late_attrs;
7643
7644       for (*p = attributes; *p; )
7645         {
7646           t = *p;
7647           if (ATTR_IS_DEPENDENT (t))
7648             {
7649               *p = TREE_CHAIN (t);
7650               TREE_CHAIN (t) = NULL_TREE;
7651               /* If the first attribute argument is an identifier, don't
7652                  pass it through tsubst.  Attributes like mode, format,
7653                  cleanup and several target specific attributes expect it
7654                  unmodified.  */
7655               if (TREE_VALUE (t)
7656                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7657                   && TREE_VALUE (TREE_VALUE (t))
7658                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7659                       == IDENTIFIER_NODE))
7660                 {
7661                   tree chain
7662                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7663                                    in_decl,
7664                                    /*integral_constant_expression_p=*/false);
7665                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7666                     TREE_VALUE (t)
7667                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7668                                    chain);
7669                 }
7670               else
7671                 TREE_VALUE (t)
7672                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7673                                  /*integral_constant_expression_p=*/false);
7674               *q = t;
7675               q = &TREE_CHAIN (t);
7676             }
7677           else
7678             p = &TREE_CHAIN (t);
7679         }
7680
7681       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7682     }
7683 }
7684
7685 /* Perform (or defer) access check for typedefs that were referenced
7686    from within the template TMPL code.
7687    This is a subroutine of instantiate_template and instantiate_class_template.
7688    TMPL is the template to consider and TARGS is the list of arguments of
7689    that template.  */
7690
7691 static void
7692 perform_typedefs_access_check (tree tmpl, tree targs)
7693 {
7694   location_t saved_location;
7695   int i;
7696   qualified_typedef_usage_t *iter;
7697
7698   if (!tmpl
7699       || (!CLASS_TYPE_P (tmpl)
7700           && TREE_CODE (tmpl) != FUNCTION_DECL))
7701     return;
7702
7703   saved_location = input_location;
7704   for (i = 0;
7705        VEC_iterate (qualified_typedef_usage_t,
7706                     get_types_needing_access_check (tmpl),
7707                     i, iter);
7708         ++i)
7709     {
7710       tree type_decl = iter->typedef_decl;
7711       tree type_scope = iter->context;
7712
7713       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7714         continue;
7715
7716       if (uses_template_parms (type_decl))
7717         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7718       if (uses_template_parms (type_scope))
7719         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7720
7721       /* Make access check error messages point to the location
7722          of the use of the typedef.  */
7723       input_location = iter->locus;
7724       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7725                                      type_decl, type_decl);
7726     }
7727     input_location = saved_location;
7728 }
7729
7730 tree
7731 instantiate_class_template (tree type)
7732 {
7733   tree templ, args, pattern, t, member;
7734   tree typedecl;
7735   tree pbinfo;
7736   tree base_list;
7737   unsigned int saved_maximum_field_alignment;
7738
7739   if (type == error_mark_node)
7740     return error_mark_node;
7741
7742   if (COMPLETE_OR_OPEN_TYPE_P (type)
7743       || uses_template_parms (type))
7744     return type;
7745
7746   /* Figure out which template is being instantiated.  */
7747   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7748   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7749
7750   /* Determine what specialization of the original template to
7751      instantiate.  */
7752   t = most_specialized_class (type, templ);
7753   if (t == error_mark_node)
7754     {
7755       TYPE_BEING_DEFINED (type) = 1;
7756       return error_mark_node;
7757     }
7758   else if (t)
7759     {
7760       /* This TYPE is actually an instantiation of a partial
7761          specialization.  We replace the innermost set of ARGS with
7762          the arguments appropriate for substitution.  For example,
7763          given:
7764
7765            template <class T> struct S {};
7766            template <class T> struct S<T*> {};
7767
7768          and supposing that we are instantiating S<int*>, ARGS will
7769          presently be {int*} -- but we need {int}.  */
7770       pattern = TREE_TYPE (t);
7771       args = TREE_PURPOSE (t);
7772     }
7773   else
7774     {
7775       pattern = TREE_TYPE (templ);
7776       args = CLASSTYPE_TI_ARGS (type);
7777     }
7778
7779   /* If the template we're instantiating is incomplete, then clearly
7780      there's nothing we can do.  */
7781   if (!COMPLETE_TYPE_P (pattern))
7782     return type;
7783
7784   /* If we've recursively instantiated too many templates, stop.  */
7785   if (! push_tinst_level (type))
7786     return type;
7787
7788   /* Now we're really doing the instantiation.  Mark the type as in
7789      the process of being defined.  */
7790   TYPE_BEING_DEFINED (type) = 1;
7791
7792   /* We may be in the middle of deferred access check.  Disable
7793      it now.  */
7794   push_deferring_access_checks (dk_no_deferred);
7795
7796   push_to_top_level ();
7797   /* Use #pragma pack from the template context.  */
7798   saved_maximum_field_alignment = maximum_field_alignment;
7799   maximum_field_alignment = TYPE_PRECISION (pattern);
7800
7801   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7802
7803   /* Set the input location to the most specialized template definition.
7804      This is needed if tsubsting causes an error.  */
7805   typedecl = TYPE_MAIN_DECL (pattern);
7806   input_location = DECL_SOURCE_LOCATION (typedecl);
7807
7808   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7809   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7810   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7811   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7812   TYPE_HAS_COPY_ASSIGN (type) = TYPE_HAS_COPY_ASSIGN (pattern);
7813   TYPE_HAS_CONST_COPY_ASSIGN (type) = TYPE_HAS_CONST_COPY_ASSIGN (pattern);
7814   TYPE_HAS_COPY_CTOR (type) = TYPE_HAS_COPY_CTOR (pattern);
7815   TYPE_HAS_CONST_COPY_CTOR (type) = TYPE_HAS_CONST_COPY_CTOR (pattern);
7816   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7817   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7818   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7819   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7820   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7821   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7822   if (ANON_AGGR_TYPE_P (pattern))
7823     SET_ANON_AGGR_TYPE_P (type);
7824   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7825     {
7826       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7827       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7828     }
7829
7830   pbinfo = TYPE_BINFO (pattern);
7831
7832   /* We should never instantiate a nested class before its enclosing
7833      class; we need to look up the nested class by name before we can
7834      instantiate it, and that lookup should instantiate the enclosing
7835      class.  */
7836   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7837               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
7838
7839   base_list = NULL_TREE;
7840   if (BINFO_N_BASE_BINFOS (pbinfo))
7841     {
7842       tree pbase_binfo;
7843       tree context = TYPE_CONTEXT (type);
7844       tree pushed_scope;
7845       int i;
7846
7847       /* We must enter the scope containing the type, as that is where
7848          the accessibility of types named in dependent bases are
7849          looked up from.  */
7850       pushed_scope = push_scope (context ? context : global_namespace);
7851
7852       /* Substitute into each of the bases to determine the actual
7853          basetypes.  */
7854       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7855         {
7856           tree base;
7857           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7858           tree expanded_bases = NULL_TREE;
7859           int idx, len = 1;
7860
7861           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7862             {
7863               expanded_bases = 
7864                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7865                                        args, tf_error, NULL_TREE);
7866               if (expanded_bases == error_mark_node)
7867                 continue;
7868
7869               len = TREE_VEC_LENGTH (expanded_bases);
7870             }
7871
7872           for (idx = 0; idx < len; idx++)
7873             {
7874               if (expanded_bases)
7875                 /* Extract the already-expanded base class.  */
7876                 base = TREE_VEC_ELT (expanded_bases, idx);
7877               else
7878                 /* Substitute to figure out the base class.  */
7879                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7880                                NULL_TREE);
7881
7882               if (base == error_mark_node)
7883                 continue;
7884
7885               base_list = tree_cons (access, base, base_list);
7886               if (BINFO_VIRTUAL_P (pbase_binfo))
7887                 TREE_TYPE (base_list) = integer_type_node;
7888             }
7889         }
7890
7891       /* The list is now in reverse order; correct that.  */
7892       base_list = nreverse (base_list);
7893
7894       if (pushed_scope)
7895         pop_scope (pushed_scope);
7896     }
7897   /* Now call xref_basetypes to set up all the base-class
7898      information.  */
7899   xref_basetypes (type, base_list);
7900
7901   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7902                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7903                                   args, tf_error, NULL_TREE);
7904
7905   /* Now that our base classes are set up, enter the scope of the
7906      class, so that name lookups into base classes, etc. will work
7907      correctly.  This is precisely analogous to what we do in
7908      begin_class_definition when defining an ordinary non-template
7909      class, except we also need to push the enclosing classes.  */
7910   push_nested_class (type);
7911
7912   /* Now members are processed in the order of declaration.  */
7913   for (member = CLASSTYPE_DECL_LIST (pattern);
7914        member; member = TREE_CHAIN (member))
7915     {
7916       tree t = TREE_VALUE (member);
7917
7918       if (TREE_PURPOSE (member))
7919         {
7920           if (TYPE_P (t))
7921             {
7922               /* Build new CLASSTYPE_NESTED_UTDS.  */
7923
7924               tree newtag;
7925               bool class_template_p;
7926
7927               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7928                                   && TYPE_LANG_SPECIFIC (t)
7929                                   && CLASSTYPE_IS_TEMPLATE (t));
7930               /* If the member is a class template, then -- even after
7931                  substitution -- there may be dependent types in the
7932                  template argument list for the class.  We increment
7933                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7934                  that function will assume that no types are dependent
7935                  when outside of a template.  */
7936               if (class_template_p)
7937                 ++processing_template_decl;
7938               newtag = tsubst (t, args, tf_error, NULL_TREE);
7939               if (class_template_p)
7940                 --processing_template_decl;
7941               if (newtag == error_mark_node)
7942                 continue;
7943
7944               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7945                 {
7946                   tree name = TYPE_IDENTIFIER (t);
7947
7948                   if (class_template_p)
7949                     /* Unfortunately, lookup_template_class sets
7950                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7951                        instantiation (i.e., for the type of a member
7952                        template class nested within a template class.)
7953                        This behavior is required for
7954                        maybe_process_partial_specialization to work
7955                        correctly, but is not accurate in this case;
7956                        the TAG is not an instantiation of anything.
7957                        (The corresponding TEMPLATE_DECL is an
7958                        instantiation, but the TYPE is not.) */
7959                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7960
7961                   /* Now, we call pushtag to put this NEWTAG into the scope of
7962                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7963                      pushtag calling push_template_decl.  We don't have to do
7964                      this for enums because it will already have been done in
7965                      tsubst_enum.  */
7966                   if (name)
7967                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7968                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7969                 }
7970             }
7971           else if (TREE_CODE (t) == FUNCTION_DECL
7972                    || DECL_FUNCTION_TEMPLATE_P (t))
7973             {
7974               /* Build new TYPE_METHODS.  */
7975               tree r;
7976
7977               if (TREE_CODE (t) == TEMPLATE_DECL)
7978                 ++processing_template_decl;
7979               r = tsubst (t, args, tf_error, NULL_TREE);
7980               if (TREE_CODE (t) == TEMPLATE_DECL)
7981                 --processing_template_decl;
7982               set_current_access_from_decl (r);
7983               finish_member_declaration (r);
7984             }
7985           else
7986             {
7987               /* Build new TYPE_FIELDS.  */
7988               if (TREE_CODE (t) == STATIC_ASSERT)
7989                 {
7990                   tree condition = 
7991                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7992                                  tf_warning_or_error, NULL_TREE,
7993                                  /*integral_constant_expression_p=*/true);
7994                   finish_static_assert (condition,
7995                                         STATIC_ASSERT_MESSAGE (t), 
7996                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7997                                         /*member_p=*/true);
7998                 }
7999               else if (TREE_CODE (t) != CONST_DECL)
8000                 {
8001                   tree r;
8002
8003                   /* The file and line for this declaration, to
8004                      assist in error message reporting.  Since we
8005                      called push_tinst_level above, we don't need to
8006                      restore these.  */
8007                   input_location = DECL_SOURCE_LOCATION (t);
8008
8009                   if (TREE_CODE (t) == TEMPLATE_DECL)
8010                     ++processing_template_decl;
8011                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8012                   if (TREE_CODE (t) == TEMPLATE_DECL)
8013                     --processing_template_decl;
8014                   if (TREE_CODE (r) == VAR_DECL)
8015                     {
8016                       /* In [temp.inst]:
8017
8018                            [t]he initialization (and any associated
8019                            side-effects) of a static data member does
8020                            not occur unless the static data member is
8021                            itself used in a way that requires the
8022                            definition of the static data member to
8023                            exist.
8024
8025                          Therefore, we do not substitute into the
8026                          initialized for the static data member here.  */
8027                       finish_static_data_member_decl
8028                         (r,
8029                          /*init=*/NULL_TREE,
8030                          /*init_const_expr_p=*/false,
8031                          /*asmspec_tree=*/NULL_TREE,
8032                          /*flags=*/0);
8033                       if (DECL_INITIALIZED_IN_CLASS_P (r))
8034                         check_static_variable_definition (r, TREE_TYPE (r));
8035                     }
8036                   else if (TREE_CODE (r) == FIELD_DECL)
8037                     {
8038                       /* Determine whether R has a valid type and can be
8039                          completed later.  If R is invalid, then it is
8040                          replaced by error_mark_node so that it will not be
8041                          added to TYPE_FIELDS.  */
8042                       tree rtype = TREE_TYPE (r);
8043                       if (can_complete_type_without_circularity (rtype))
8044                         complete_type (rtype);
8045
8046                       if (!COMPLETE_TYPE_P (rtype))
8047                         {
8048                           cxx_incomplete_type_error (r, rtype);
8049                           r = error_mark_node;
8050                         }
8051                     }
8052
8053                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8054                      such a thing will already have been added to the field
8055                      list by tsubst_enum in finish_member_declaration in the
8056                      CLASSTYPE_NESTED_UTDS case above.  */
8057                   if (!(TREE_CODE (r) == TYPE_DECL
8058                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8059                         && DECL_ARTIFICIAL (r)))
8060                     {
8061                       set_current_access_from_decl (r);
8062                       finish_member_declaration (r);
8063                     }
8064                 }
8065             }
8066         }
8067       else
8068         {
8069           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8070             {
8071               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8072
8073               tree friend_type = t;
8074               bool adjust_processing_template_decl = false;
8075
8076               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8077                 {
8078                   /* template <class T> friend class C;  */
8079                   friend_type = tsubst_friend_class (friend_type, args);
8080                   adjust_processing_template_decl = true;
8081                 }
8082               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8083                 {
8084                   /* template <class T> friend class C::D;  */
8085                   friend_type = tsubst (friend_type, args,
8086                                         tf_warning_or_error, NULL_TREE);
8087                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8088                     friend_type = TREE_TYPE (friend_type);
8089                   adjust_processing_template_decl = true;
8090                 }
8091               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
8092                 {
8093                   /* This could be either
8094
8095                        friend class T::C;
8096
8097                      when dependent_type_p is false or
8098
8099                        template <class U> friend class T::C;
8100
8101                      otherwise.  */
8102                   friend_type = tsubst (friend_type, args,
8103                                         tf_warning_or_error, NULL_TREE);
8104                   /* Bump processing_template_decl for correct
8105                      dependent_type_p calculation.  */
8106                   ++processing_template_decl;
8107                   if (dependent_type_p (friend_type))
8108                     adjust_processing_template_decl = true;
8109                   --processing_template_decl;
8110                 }
8111               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8112                        && hidden_name_p (TYPE_NAME (friend_type)))
8113                 {
8114                   /* friend class C;
8115
8116                      where C hasn't been declared yet.  Let's lookup name
8117                      from namespace scope directly, bypassing any name that
8118                      come from dependent base class.  */
8119                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8120
8121                   /* The call to xref_tag_from_type does injection for friend
8122                      classes.  */
8123                   push_nested_namespace (ns);
8124                   friend_type =
8125                     xref_tag_from_type (friend_type, NULL_TREE,
8126                                         /*tag_scope=*/ts_current);
8127                   pop_nested_namespace (ns);
8128                 }
8129               else if (uses_template_parms (friend_type))
8130                 /* friend class C<T>;  */
8131                 friend_type = tsubst (friend_type, args,
8132                                       tf_warning_or_error, NULL_TREE);
8133               /* Otherwise it's
8134
8135                    friend class C;
8136
8137                  where C is already declared or
8138
8139                    friend class C<int>;
8140
8141                  We don't have to do anything in these cases.  */
8142
8143               if (adjust_processing_template_decl)
8144                 /* Trick make_friend_class into realizing that the friend
8145                    we're adding is a template, not an ordinary class.  It's
8146                    important that we use make_friend_class since it will
8147                    perform some error-checking and output cross-reference
8148                    information.  */
8149                 ++processing_template_decl;
8150
8151               if (friend_type != error_mark_node)
8152                 make_friend_class (type, friend_type, /*complain=*/false);
8153
8154               if (adjust_processing_template_decl)
8155                 --processing_template_decl;
8156             }
8157           else
8158             {
8159               /* Build new DECL_FRIENDLIST.  */
8160               tree r;
8161
8162               /* The file and line for this declaration, to
8163                  assist in error message reporting.  Since we
8164                  called push_tinst_level above, we don't need to
8165                  restore these.  */
8166               input_location = DECL_SOURCE_LOCATION (t);
8167
8168               if (TREE_CODE (t) == TEMPLATE_DECL)
8169                 {
8170                   ++processing_template_decl;
8171                   push_deferring_access_checks (dk_no_check);
8172                 }
8173
8174               r = tsubst_friend_function (t, args);
8175               add_friend (type, r, /*complain=*/false);
8176               if (TREE_CODE (t) == TEMPLATE_DECL)
8177                 {
8178                   pop_deferring_access_checks ();
8179                   --processing_template_decl;
8180                 }
8181             }
8182         }
8183     }
8184
8185   /* Set the file and line number information to whatever is given for
8186      the class itself.  This puts error messages involving generated
8187      implicit functions at a predictable point, and the same point
8188      that would be used for non-template classes.  */
8189   input_location = DECL_SOURCE_LOCATION (typedecl);
8190
8191   unreverse_member_declarations (type);
8192   finish_struct_1 (type);
8193   TYPE_BEING_DEFINED (type) = 0;
8194
8195   /* Now that the class is complete, instantiate default arguments for
8196      any member functions.  We don't do this earlier because the
8197      default arguments may reference members of the class.  */
8198   if (!PRIMARY_TEMPLATE_P (templ))
8199     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
8200       if (TREE_CODE (t) == FUNCTION_DECL
8201           /* Implicitly generated member functions will not have template
8202              information; they are not instantiations, but instead are
8203              created "fresh" for each instantiation.  */
8204           && DECL_TEMPLATE_INFO (t))
8205         tsubst_default_arguments (t);
8206
8207   /* Some typedefs referenced from within the template code need to be access
8208      checked at template instantiation time, i.e now. These types were
8209      added to the template at parsing time. Let's get those and perform
8210      the access checks then.  */
8211   perform_typedefs_access_check (pattern, args);
8212   perform_deferred_access_checks ();
8213   pop_nested_class ();
8214   maximum_field_alignment = saved_maximum_field_alignment;
8215   pop_from_top_level ();
8216   pop_deferring_access_checks ();
8217   pop_tinst_level ();
8218
8219   /* The vtable for a template class can be emitted in any translation
8220      unit in which the class is instantiated.  When there is no key
8221      method, however, finish_struct_1 will already have added TYPE to
8222      the keyed_classes list.  */
8223   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8224     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8225
8226   return type;
8227 }
8228
8229 static tree
8230 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8231 {
8232   tree r;
8233
8234   if (!t)
8235     r = t;
8236   else if (TYPE_P (t))
8237     r = tsubst (t, args, complain, in_decl);
8238   else
8239     {
8240       r = tsubst_expr (t, args, complain, in_decl,
8241                        /*integral_constant_expression_p=*/true);
8242       r = fold_non_dependent_expr (r);
8243     }
8244   return r;
8245 }
8246
8247 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8248    NONTYPE_ARGUMENT_PACK.  */
8249
8250 static tree
8251 make_fnparm_pack (tree spec_parm)
8252 {
8253   /* Collect all of the extra "packed" parameters into an
8254      argument pack.  */
8255   tree parmvec;
8256   tree parmtypevec;
8257   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8258   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8259   int i, len = list_length (spec_parm);
8260
8261   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8262   parmvec = make_tree_vec (len);
8263   parmtypevec = make_tree_vec (len);
8264   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
8265     {
8266       TREE_VEC_ELT (parmvec, i) = spec_parm;
8267       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8268     }
8269
8270   /* Build the argument packs.  */
8271   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8272   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8273   TREE_TYPE (argpack) = argtypepack;
8274
8275   return argpack;
8276 }        
8277
8278 /* Substitute ARGS into T, which is an pack expansion
8279    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8280    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8281    (if only a partial substitution could be performed) or
8282    ERROR_MARK_NODE if there was an error.  */
8283 tree
8284 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8285                        tree in_decl)
8286 {
8287   tree pattern;
8288   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8289   int i, len = -1;
8290   tree result;
8291   int incomplete = 0;
8292   htab_t saved_local_specializations = NULL;
8293
8294   gcc_assert (PACK_EXPANSION_P (t));
8295   pattern = PACK_EXPANSION_PATTERN (t);
8296
8297   /* Determine the argument packs that will instantiate the parameter
8298      packs used in the expansion expression. While we're at it,
8299      compute the number of arguments to be expanded and make sure it
8300      is consistent.  */
8301   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8302        pack = TREE_CHAIN (pack))
8303     {
8304       tree parm_pack = TREE_VALUE (pack);
8305       tree arg_pack = NULL_TREE;
8306       tree orig_arg = NULL_TREE;
8307
8308       if (TREE_CODE (parm_pack) == PARM_DECL)
8309         {
8310           if (!cp_unevaluated_operand)
8311             arg_pack = retrieve_local_specialization (parm_pack);
8312           else
8313             {
8314               /* We can't rely on local_specializations for a parameter
8315                  name used later in a function declaration (such as in a
8316                  late-specified return type).  Even if it exists, it might
8317                  have the wrong value for a recursive call.  Just make a
8318                  dummy decl, since it's only used for its type.  */
8319               arg_pack = tsubst_decl (parm_pack, args, complain);
8320               arg_pack = make_fnparm_pack (arg_pack);
8321             }
8322         }
8323       else
8324         {
8325           int level, idx, levels;
8326           template_parm_level_and_index (parm_pack, &level, &idx);
8327
8328           levels = TMPL_ARGS_DEPTH (args);
8329           if (level <= levels)
8330             arg_pack = TMPL_ARG (args, level, idx);
8331         }
8332
8333       orig_arg = arg_pack;
8334       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8335         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8336       
8337       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8338         /* This can only happen if we forget to expand an argument
8339            pack somewhere else. Just return an error, silently.  */
8340         {
8341           result = make_tree_vec (1);
8342           TREE_VEC_ELT (result, 0) = error_mark_node;
8343           return result;
8344         }
8345
8346       if (arg_pack
8347           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8348           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8349         {
8350           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8351           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8352           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8353               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8354             /* The argument pack that the parameter maps to is just an
8355                expansion of the parameter itself, such as one would
8356                find in the implicit typedef of a class inside the
8357                class itself.  Consider this parameter "unsubstituted",
8358                so that we will maintain the outer pack expansion.  */
8359             arg_pack = NULL_TREE;
8360         }
8361           
8362       if (arg_pack)
8363         {
8364           int my_len = 
8365             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8366
8367           /* It's all-or-nothing with incomplete argument packs.  */
8368           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8369             return error_mark_node;
8370           
8371           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8372             incomplete = 1;
8373
8374           if (len < 0)
8375             len = my_len;
8376           else if (len != my_len)
8377             {
8378               if (incomplete)
8379                 /* We got explicit args for some packs but not others;
8380                    do nothing now and try again after deduction.  */
8381                 return t;
8382               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8383                 error ("mismatched argument pack lengths while expanding "
8384                        "%<%T%>",
8385                        pattern);
8386               else
8387                 error ("mismatched argument pack lengths while expanding "
8388                        "%<%E%>",
8389                        pattern);
8390               return error_mark_node;
8391             }
8392
8393           /* Keep track of the parameter packs and their corresponding
8394              argument packs.  */
8395           packs = tree_cons (parm_pack, arg_pack, packs);
8396           TREE_TYPE (packs) = orig_arg;
8397         }
8398       else
8399         /* We can't substitute for this parameter pack.  */
8400         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8401                                          TREE_VALUE (pack),
8402                                          unsubstituted_packs);
8403     }
8404
8405   /* We cannot expand this expansion expression, because we don't have
8406      all of the argument packs we need. Substitute into the pattern
8407      and return a PACK_EXPANSION_*. The caller will need to deal with
8408      that.  */
8409   if (unsubstituted_packs)
8410     {
8411       tree new_pat;
8412       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8413         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8414                                /*integral_constant_expression_p=*/false);
8415       else
8416         new_pat = tsubst (pattern, args, complain, in_decl);
8417       return make_pack_expansion (new_pat);
8418     }
8419
8420   /* We could not find any argument packs that work.  */
8421   if (len < 0)
8422     return error_mark_node;
8423
8424   if (cp_unevaluated_operand)
8425     {
8426       /* We're in a late-specified return type, so create our own local
8427          specializations table; the current table is either NULL or (in the
8428          case of recursive unification) might have bindings that we don't
8429          want to use or alter.  */
8430       saved_local_specializations = local_specializations;
8431       local_specializations = htab_create (37,
8432                                            hash_local_specialization,
8433                                            eq_local_specializations,
8434                                            NULL);
8435     }
8436
8437   /* For each argument in each argument pack, substitute into the
8438      pattern.  */
8439   result = make_tree_vec (len + incomplete);
8440   for (i = 0; i < len + incomplete; ++i)
8441     {
8442       /* For parameter pack, change the substitution of the parameter
8443          pack to the ith argument in its argument pack, then expand
8444          the pattern.  */
8445       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8446         {
8447           tree parm = TREE_PURPOSE (pack);
8448
8449           if (TREE_CODE (parm) == PARM_DECL)
8450             {
8451               /* Select the Ith argument from the pack.  */
8452               tree arg = make_node (ARGUMENT_PACK_SELECT);
8453               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8454               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8455               mark_used (parm);
8456               register_local_specialization (arg, parm);
8457             }
8458           else
8459             {
8460               tree value = parm;
8461               int idx, level;
8462               template_parm_level_and_index (parm, &level, &idx);
8463               
8464               if (i < len) 
8465                 {
8466                   /* Select the Ith argument from the pack. */
8467                   value = make_node (ARGUMENT_PACK_SELECT);
8468                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8469                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8470                 }
8471
8472               /* Update the corresponding argument.  */
8473               TMPL_ARG (args, level, idx) = value;
8474             }
8475         }
8476
8477       /* Substitute into the PATTERN with the altered arguments.  */
8478       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8479         TREE_VEC_ELT (result, i) = 
8480           tsubst_expr (pattern, args, complain, in_decl,
8481                        /*integral_constant_expression_p=*/false);
8482       else
8483         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8484
8485       if (i == len)
8486         /* When we have incomplete argument packs, the last "expanded"
8487            result is itself a pack expansion, which allows us
8488            to deduce more arguments.  */
8489         TREE_VEC_ELT (result, i) = 
8490           make_pack_expansion (TREE_VEC_ELT (result, i));
8491
8492       if (TREE_VEC_ELT (result, i) == error_mark_node)
8493         {
8494           result = error_mark_node;
8495           break;
8496         }
8497     }
8498
8499   /* Update ARGS to restore the substitution from parameter packs to
8500      their argument packs.  */
8501   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8502     {
8503       tree parm = TREE_PURPOSE (pack);
8504
8505       if (TREE_CODE (parm) == PARM_DECL)
8506         register_local_specialization (TREE_TYPE (pack), parm);
8507       else
8508         {
8509           int idx, level;
8510           template_parm_level_and_index (parm, &level, &idx);
8511           
8512           /* Update the corresponding argument.  */
8513           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8514             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8515               TREE_TYPE (pack);
8516           else
8517             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8518         }
8519     }
8520
8521   if (saved_local_specializations)
8522     {
8523       htab_delete (local_specializations);
8524       local_specializations = saved_local_specializations;
8525     }
8526   
8527   return result;
8528 }
8529
8530 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8531    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8532    parameter packs; all parms generated from a function parameter pack will
8533    have the same DECL_PARM_INDEX.  */
8534
8535 tree
8536 get_pattern_parm (tree parm, tree tmpl)
8537 {
8538   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8539   tree patparm;
8540
8541   if (DECL_ARTIFICIAL (parm))
8542     {
8543       for (patparm = DECL_ARGUMENTS (pattern);
8544            patparm; patparm = TREE_CHAIN (patparm))
8545         if (DECL_ARTIFICIAL (patparm)
8546             && DECL_NAME (parm) == DECL_NAME (patparm))
8547           break;
8548     }
8549   else
8550     {
8551       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8552       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8553       gcc_assert (DECL_PARM_INDEX (patparm)
8554                   == DECL_PARM_INDEX (parm));
8555     }
8556
8557   return patparm;
8558 }
8559
8560 /* Substitute ARGS into the vector or list of template arguments T.  */
8561
8562 static tree
8563 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8564 {
8565   tree orig_t = t;
8566   int len = TREE_VEC_LENGTH (t);
8567   int need_new = 0, i, expanded_len_adjust = 0, out;
8568   tree *elts = XALLOCAVEC (tree, len);
8569
8570   for (i = 0; i < len; i++)
8571     {
8572       tree orig_arg = TREE_VEC_ELT (t, i);
8573       tree new_arg;
8574
8575       if (TREE_CODE (orig_arg) == TREE_VEC)
8576         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8577       else if (PACK_EXPANSION_P (orig_arg))
8578         {
8579           /* Substitute into an expansion expression.  */
8580           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8581
8582           if (TREE_CODE (new_arg) == TREE_VEC)
8583             /* Add to the expanded length adjustment the number of
8584                expanded arguments. We subtract one from this
8585                measurement, because the argument pack expression
8586                itself is already counted as 1 in
8587                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8588                the argument pack is empty.  */
8589             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8590         }
8591       else if (ARGUMENT_PACK_P (orig_arg))
8592         {
8593           /* Substitute into each of the arguments.  */
8594           new_arg = TYPE_P (orig_arg)
8595             ? cxx_make_type (TREE_CODE (orig_arg))
8596             : make_node (TREE_CODE (orig_arg));
8597           
8598           SET_ARGUMENT_PACK_ARGS (
8599             new_arg,
8600             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8601                                   args, complain, in_decl));
8602
8603           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8604             new_arg = error_mark_node;
8605
8606           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8607             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8608                                           complain, in_decl);
8609             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8610
8611             if (TREE_TYPE (new_arg) == error_mark_node)
8612               new_arg = error_mark_node;
8613           }
8614         }
8615       else
8616         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8617
8618       if (new_arg == error_mark_node)
8619         return error_mark_node;
8620
8621       elts[i] = new_arg;
8622       if (new_arg != orig_arg)
8623         need_new = 1;
8624     }
8625
8626   if (!need_new)
8627     return t;
8628
8629   /* Make space for the expanded arguments coming from template
8630      argument packs.  */
8631   t = make_tree_vec (len + expanded_len_adjust);
8632   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
8633      arguments for a member template.
8634      In that case each TREE_VEC in ORIG_T represents a level of template
8635      arguments, and ORIG_T won't carry any non defaulted argument count.
8636      It will rather be the nested TREE_VECs that will carry one.
8637      In other words, ORIG_T carries a non defaulted argument count only
8638      if it doesn't contain any nested TREE_VEC.  */
8639   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
8640     {
8641       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
8642       count += expanded_len_adjust;
8643       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
8644     }
8645   for (i = 0, out = 0; i < len; i++)
8646     {
8647       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8648            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8649           && TREE_CODE (elts[i]) == TREE_VEC)
8650         {
8651           int idx;
8652
8653           /* Now expand the template argument pack "in place".  */
8654           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8655             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8656         }
8657       else
8658         {
8659           TREE_VEC_ELT (t, out) = elts[i];
8660           out++;
8661         }
8662     }
8663
8664   return t;
8665 }
8666
8667 /* Return the result of substituting ARGS into the template parameters
8668    given by PARMS.  If there are m levels of ARGS and m + n levels of
8669    PARMS, then the result will contain n levels of PARMS.  For
8670    example, if PARMS is `template <class T> template <class U>
8671    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8672    result will be `template <int*, double, class V>'.  */
8673
8674 static tree
8675 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8676 {
8677   tree r = NULL_TREE;
8678   tree* new_parms;
8679
8680   /* When substituting into a template, we must set
8681      PROCESSING_TEMPLATE_DECL as the template parameters may be
8682      dependent if they are based on one-another, and the dependency
8683      predicates are short-circuit outside of templates.  */
8684   ++processing_template_decl;
8685
8686   for (new_parms = &r;
8687        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8688        new_parms = &(TREE_CHAIN (*new_parms)),
8689          parms = TREE_CHAIN (parms))
8690     {
8691       tree new_vec =
8692         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8693       int i;
8694
8695       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8696         {
8697           tree tuple;
8698           tree default_value;
8699           tree parm_decl;
8700
8701           if (parms == error_mark_node)
8702             continue;
8703
8704           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8705
8706           if (tuple == error_mark_node)
8707             continue;
8708
8709           default_value = TREE_PURPOSE (tuple);
8710           parm_decl = TREE_VALUE (tuple);
8711
8712           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8713           if (TREE_CODE (parm_decl) == PARM_DECL
8714               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8715             parm_decl = error_mark_node;
8716           default_value = tsubst_template_arg (default_value, args,
8717                                                complain, NULL_TREE);
8718
8719           tuple = build_tree_list (default_value, parm_decl);
8720           TREE_VEC_ELT (new_vec, i) = tuple;
8721         }
8722
8723       *new_parms =
8724         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8725                              - TMPL_ARGS_DEPTH (args)),
8726                    new_vec, NULL_TREE);
8727     }
8728
8729   --processing_template_decl;
8730
8731   return r;
8732 }
8733
8734 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8735    type T.  If T is not an aggregate or enumeration type, it is
8736    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8737    ENTERING_SCOPE is nonzero, T is the context for a template which
8738    we are presently tsubst'ing.  Return the substituted value.  */
8739
8740 static tree
8741 tsubst_aggr_type (tree t,
8742                   tree args,
8743                   tsubst_flags_t complain,
8744                   tree in_decl,
8745                   int entering_scope)
8746 {
8747   if (t == NULL_TREE)
8748     return NULL_TREE;
8749
8750   switch (TREE_CODE (t))
8751     {
8752     case RECORD_TYPE:
8753       if (TYPE_PTRMEMFUNC_P (t))
8754         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8755
8756       /* Else fall through.  */
8757     case ENUMERAL_TYPE:
8758     case UNION_TYPE:
8759       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8760         {
8761           tree argvec;
8762           tree context;
8763           tree r;
8764           int saved_unevaluated_operand;
8765           int saved_inhibit_evaluation_warnings;
8766
8767           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8768           saved_unevaluated_operand = cp_unevaluated_operand;
8769           cp_unevaluated_operand = 0;
8770           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8771           c_inhibit_evaluation_warnings = 0;
8772
8773           /* First, determine the context for the type we are looking
8774              up.  */
8775           context = TYPE_CONTEXT (t);
8776           if (context)
8777             {
8778               context = tsubst_aggr_type (context, args, complain,
8779                                           in_decl, /*entering_scope=*/1);
8780               /* If context is a nested class inside a class template,
8781                  it may still need to be instantiated (c++/33959).  */
8782               if (TYPE_P (context))
8783                 context = complete_type (context);
8784             }
8785
8786           /* Then, figure out what arguments are appropriate for the
8787              type we are trying to find.  For example, given:
8788
8789                template <class T> struct S;
8790                template <class T, class U> void f(T, U) { S<U> su; }
8791
8792              and supposing that we are instantiating f<int, double>,
8793              then our ARGS will be {int, double}, but, when looking up
8794              S we only want {double}.  */
8795           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8796                                          complain, in_decl);
8797           if (argvec == error_mark_node)
8798             r = error_mark_node;
8799           else
8800             {
8801               r = lookup_template_class (t, argvec, in_decl, context,
8802                                          entering_scope, complain);
8803               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
8804             }
8805
8806           cp_unevaluated_operand = saved_unevaluated_operand;
8807           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8808
8809           return r;
8810         }
8811       else
8812         /* This is not a template type, so there's nothing to do.  */
8813         return t;
8814
8815     default:
8816       return tsubst (t, args, complain, in_decl);
8817     }
8818 }
8819
8820 /* Substitute into the default argument ARG (a default argument for
8821    FN), which has the indicated TYPE.  */
8822
8823 tree
8824 tsubst_default_argument (tree fn, tree type, tree arg)
8825 {
8826   tree saved_class_ptr = NULL_TREE;
8827   tree saved_class_ref = NULL_TREE;
8828
8829   /* This default argument came from a template.  Instantiate the
8830      default argument here, not in tsubst.  In the case of
8831      something like:
8832
8833        template <class T>
8834        struct S {
8835          static T t();
8836          void f(T = t());
8837        };
8838
8839      we must be careful to do name lookup in the scope of S<T>,
8840      rather than in the current class.  */
8841   push_access_scope (fn);
8842   /* The "this" pointer is not valid in a default argument.  */
8843   if (cfun)
8844     {
8845       saved_class_ptr = current_class_ptr;
8846       cp_function_chain->x_current_class_ptr = NULL_TREE;
8847       saved_class_ref = current_class_ref;
8848       cp_function_chain->x_current_class_ref = NULL_TREE;
8849     }
8850
8851   push_deferring_access_checks(dk_no_deferred);
8852   /* The default argument expression may cause implicitly defined
8853      member functions to be synthesized, which will result in garbage
8854      collection.  We must treat this situation as if we were within
8855      the body of function so as to avoid collecting live data on the
8856      stack.  */
8857   ++function_depth;
8858   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8859                      tf_warning_or_error, NULL_TREE,
8860                      /*integral_constant_expression_p=*/false);
8861   --function_depth;
8862   pop_deferring_access_checks();
8863
8864   /* Restore the "this" pointer.  */
8865   if (cfun)
8866     {
8867       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8868       cp_function_chain->x_current_class_ref = saved_class_ref;
8869     }
8870
8871   /* Make sure the default argument is reasonable.  */
8872   arg = check_default_argument (type, arg);
8873
8874   pop_access_scope (fn);
8875
8876   return arg;
8877 }
8878
8879 /* Substitute into all the default arguments for FN.  */
8880
8881 static void
8882 tsubst_default_arguments (tree fn)
8883 {
8884   tree arg;
8885   tree tmpl_args;
8886
8887   tmpl_args = DECL_TI_ARGS (fn);
8888
8889   /* If this function is not yet instantiated, we certainly don't need
8890      its default arguments.  */
8891   if (uses_template_parms (tmpl_args))
8892     return;
8893
8894   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8895        arg;
8896        arg = TREE_CHAIN (arg))
8897     if (TREE_PURPOSE (arg))
8898       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8899                                                     TREE_VALUE (arg),
8900                                                     TREE_PURPOSE (arg));
8901 }
8902
8903 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8904    result of the substitution.  Issue error and warning messages under
8905    control of COMPLAIN.  */
8906
8907 static tree
8908 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8909 {
8910 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8911   location_t saved_loc;
8912   tree r = NULL_TREE;
8913   tree in_decl = t;
8914   hashval_t hash = 0;
8915
8916   /* Set the filename and linenumber to improve error-reporting.  */
8917   saved_loc = input_location;
8918   input_location = DECL_SOURCE_LOCATION (t);
8919
8920   switch (TREE_CODE (t))
8921     {
8922     case TEMPLATE_DECL:
8923       {
8924         /* We can get here when processing a member function template,
8925            member class template, or template template parameter.  */
8926         tree decl = DECL_TEMPLATE_RESULT (t);
8927         tree spec;
8928         tree tmpl_args;
8929         tree full_args;
8930
8931         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8932           {
8933             /* Template template parameter is treated here.  */
8934             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8935             if (new_type == error_mark_node)
8936               RETURN (error_mark_node);
8937
8938             r = copy_decl (t);
8939             TREE_CHAIN (r) = NULL_TREE;
8940             TREE_TYPE (r) = new_type;
8941             DECL_TEMPLATE_RESULT (r)
8942               = build_decl (DECL_SOURCE_LOCATION (decl),
8943                             TYPE_DECL, DECL_NAME (decl), new_type);
8944             DECL_TEMPLATE_PARMS (r)
8945               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8946                                        complain);
8947             TYPE_NAME (new_type) = r;
8948             break;
8949           }
8950
8951         /* We might already have an instance of this template.
8952            The ARGS are for the surrounding class type, so the
8953            full args contain the tsubst'd args for the context,
8954            plus the innermost args from the template decl.  */
8955         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8956           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8957           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8958         /* Because this is a template, the arguments will still be
8959            dependent, even after substitution.  If
8960            PROCESSING_TEMPLATE_DECL is not set, the dependency
8961            predicates will short-circuit.  */
8962         ++processing_template_decl;
8963         full_args = tsubst_template_args (tmpl_args, args,
8964                                           complain, in_decl);
8965         --processing_template_decl;
8966         if (full_args == error_mark_node)
8967           RETURN (error_mark_node);
8968
8969         /* If this is a default template template argument,
8970            tsubst might not have changed anything.  */
8971         if (full_args == tmpl_args)
8972           RETURN (t);
8973
8974         hash = hash_tmpl_and_args (t, full_args);
8975         spec = retrieve_specialization (t, full_args, hash);
8976         if (spec != NULL_TREE)
8977           {
8978             r = spec;
8979             break;
8980           }
8981
8982         /* Make a new template decl.  It will be similar to the
8983            original, but will record the current template arguments.
8984            We also create a new function declaration, which is just
8985            like the old one, but points to this new template, rather
8986            than the old one.  */
8987         r = copy_decl (t);
8988         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8989         TREE_CHAIN (r) = NULL_TREE;
8990
8991         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
8992
8993         if (TREE_CODE (decl) == TYPE_DECL)
8994           {
8995             tree new_type;
8996             ++processing_template_decl;
8997             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8998             --processing_template_decl;
8999             if (new_type == error_mark_node)
9000               RETURN (error_mark_node);
9001
9002             TREE_TYPE (r) = new_type;
9003             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9004             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9005             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9006             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9007           }
9008         else
9009           {
9010             tree new_decl;
9011             ++processing_template_decl;
9012             new_decl = tsubst (decl, args, complain, in_decl);
9013             --processing_template_decl;
9014             if (new_decl == error_mark_node)
9015               RETURN (error_mark_node);
9016
9017             DECL_TEMPLATE_RESULT (r) = new_decl;
9018             DECL_TI_TEMPLATE (new_decl) = r;
9019             TREE_TYPE (r) = TREE_TYPE (new_decl);
9020             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9021             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9022           }
9023
9024         SET_DECL_IMPLICIT_INSTANTIATION (r);
9025         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9026         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9027
9028         /* The template parameters for this new template are all the
9029            template parameters for the old template, except the
9030            outermost level of parameters.  */
9031         DECL_TEMPLATE_PARMS (r)
9032           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9033                                    complain);
9034
9035         if (PRIMARY_TEMPLATE_P (t))
9036           DECL_PRIMARY_TEMPLATE (r) = r;
9037
9038         if (TREE_CODE (decl) != TYPE_DECL)
9039           /* Record this non-type partial instantiation.  */
9040           register_specialization (r, t,
9041                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9042                                    false, hash);
9043       }
9044       break;
9045
9046     case FUNCTION_DECL:
9047       {
9048         tree ctx;
9049         tree argvec = NULL_TREE;
9050         tree *friends;
9051         tree gen_tmpl;
9052         tree type;
9053         int member;
9054         int args_depth;
9055         int parms_depth;
9056
9057         /* Nobody should be tsubst'ing into non-template functions.  */
9058         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9059
9060         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9061           {
9062             tree spec;
9063             bool dependent_p;
9064
9065             /* If T is not dependent, just return it.  We have to
9066                increment PROCESSING_TEMPLATE_DECL because
9067                value_dependent_expression_p assumes that nothing is
9068                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9069             ++processing_template_decl;
9070             dependent_p = value_dependent_expression_p (t);
9071             --processing_template_decl;
9072             if (!dependent_p)
9073               RETURN (t);
9074
9075             /* Calculate the most general template of which R is a
9076                specialization, and the complete set of arguments used to
9077                specialize R.  */
9078             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9079             argvec = tsubst_template_args (DECL_TI_ARGS
9080                                           (DECL_TEMPLATE_RESULT
9081                                                  (DECL_TI_TEMPLATE (t))),
9082                                            args, complain, in_decl);
9083
9084             /* Check to see if we already have this specialization.  */
9085             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9086             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9087
9088             if (spec)
9089               {
9090                 r = spec;
9091                 break;
9092               }
9093
9094             /* We can see more levels of arguments than parameters if
9095                there was a specialization of a member template, like
9096                this:
9097
9098                  template <class T> struct S { template <class U> void f(); }
9099                  template <> template <class U> void S<int>::f(U);
9100
9101                Here, we'll be substituting into the specialization,
9102                because that's where we can find the code we actually
9103                want to generate, but we'll have enough arguments for
9104                the most general template.
9105
9106                We also deal with the peculiar case:
9107
9108                  template <class T> struct S {
9109                    template <class U> friend void f();
9110                  };
9111                  template <class U> void f() {}
9112                  template S<int>;
9113                  template void f<double>();
9114
9115                Here, the ARGS for the instantiation of will be {int,
9116                double}.  But, we only need as many ARGS as there are
9117                levels of template parameters in CODE_PATTERN.  We are
9118                careful not to get fooled into reducing the ARGS in
9119                situations like:
9120
9121                  template <class T> struct S { template <class U> void f(U); }
9122                  template <class T> template <> void S<T>::f(int) {}
9123
9124                which we can spot because the pattern will be a
9125                specialization in this case.  */
9126             args_depth = TMPL_ARGS_DEPTH (args);
9127             parms_depth =
9128               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9129             if (args_depth > parms_depth
9130                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9131               args = get_innermost_template_args (args, parms_depth);
9132           }
9133         else
9134           {
9135             /* This special case arises when we have something like this:
9136
9137                  template <class T> struct S {
9138                    friend void f<int>(int, double);
9139                  };
9140
9141                Here, the DECL_TI_TEMPLATE for the friend declaration
9142                will be an IDENTIFIER_NODE.  We are being called from
9143                tsubst_friend_function, and we want only to create a
9144                new decl (R) with appropriate types so that we can call
9145                determine_specialization.  */
9146             gen_tmpl = NULL_TREE;
9147           }
9148
9149         if (DECL_CLASS_SCOPE_P (t))
9150           {
9151             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9152               member = 2;
9153             else
9154               member = 1;
9155             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9156                                     complain, t, /*entering_scope=*/1);
9157           }
9158         else
9159           {
9160             member = 0;
9161             ctx = DECL_CONTEXT (t);
9162           }
9163         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9164         if (type == error_mark_node)
9165           RETURN (error_mark_node);
9166
9167         /* We do NOT check for matching decls pushed separately at this
9168            point, as they may not represent instantiations of this
9169            template, and in any case are considered separate under the
9170            discrete model.  */
9171         r = copy_decl (t);
9172         DECL_USE_TEMPLATE (r) = 0;
9173         TREE_TYPE (r) = type;
9174         /* Clear out the mangled name and RTL for the instantiation.  */
9175         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9176         SET_DECL_RTL (r, NULL);
9177         /* Leave DECL_INITIAL set on deleted instantiations.  */
9178         if (!DECL_DELETED_FN (r))
9179           DECL_INITIAL (r) = NULL_TREE;
9180         DECL_CONTEXT (r) = ctx;
9181
9182         if (member && DECL_CONV_FN_P (r))
9183           /* Type-conversion operator.  Reconstruct the name, in
9184              case it's the name of one of the template's parameters.  */
9185           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9186
9187         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9188                                      complain, t);
9189         DECL_RESULT (r) = NULL_TREE;
9190
9191         TREE_STATIC (r) = 0;
9192         TREE_PUBLIC (r) = TREE_PUBLIC (t);
9193         DECL_EXTERNAL (r) = 1;
9194         /* If this is an instantiation of a function with internal
9195            linkage, we already know what object file linkage will be
9196            assigned to the instantiation.  */
9197         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9198         DECL_DEFER_OUTPUT (r) = 0;
9199         TREE_CHAIN (r) = NULL_TREE;
9200         DECL_PENDING_INLINE_INFO (r) = 0;
9201         DECL_PENDING_INLINE_P (r) = 0;
9202         DECL_SAVED_TREE (r) = NULL_TREE;
9203         DECL_STRUCT_FUNCTION (r) = NULL;
9204         TREE_USED (r) = 0;
9205         /* We'll re-clone as appropriate in instantiate_template.  */
9206         DECL_CLONED_FUNCTION (r) = NULL_TREE;
9207
9208         /* If we aren't complaining now, return on error before we register
9209            the specialization so that we'll complain eventually.  */
9210         if ((complain & tf_error) == 0
9211             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9212             && !grok_op_properties (r, /*complain=*/false))
9213           RETURN (error_mark_node);
9214
9215         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9216            this in the special friend case mentioned above where
9217            GEN_TMPL is NULL.  */
9218         if (gen_tmpl)
9219           {
9220             DECL_TEMPLATE_INFO (r)
9221               = build_template_info (gen_tmpl, argvec);
9222             SET_DECL_IMPLICIT_INSTANTIATION (r);
9223             register_specialization (r, gen_tmpl, argvec, false, hash);
9224
9225             /* We're not supposed to instantiate default arguments
9226                until they are called, for a template.  But, for a
9227                declaration like:
9228
9229                  template <class T> void f ()
9230                  { extern void g(int i = T()); }
9231
9232                we should do the substitution when the template is
9233                instantiated.  We handle the member function case in
9234                instantiate_class_template since the default arguments
9235                might refer to other members of the class.  */
9236             if (!member
9237                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9238                 && !uses_template_parms (argvec))
9239               tsubst_default_arguments (r);
9240           }
9241         else
9242           DECL_TEMPLATE_INFO (r) = NULL_TREE;
9243
9244         /* Copy the list of befriending classes.  */
9245         for (friends = &DECL_BEFRIENDING_CLASSES (r);
9246              *friends;
9247              friends = &TREE_CHAIN (*friends))
9248           {
9249             *friends = copy_node (*friends);
9250             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9251                                             args, complain,
9252                                             in_decl);
9253           }
9254
9255         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9256           {
9257             maybe_retrofit_in_chrg (r);
9258             if (DECL_CONSTRUCTOR_P (r))
9259               grok_ctor_properties (ctx, r);
9260             /* If this is an instantiation of a member template, clone it.
9261                If it isn't, that'll be handled by
9262                clone_constructors_and_destructors.  */
9263             if (PRIMARY_TEMPLATE_P (gen_tmpl))
9264               clone_function_decl (r, /*update_method_vec_p=*/0);
9265           }
9266         else if ((complain & tf_error) != 0
9267                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9268                  && !grok_op_properties (r, /*complain=*/true))
9269           RETURN (error_mark_node);
9270
9271         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9272           SET_DECL_FRIEND_CONTEXT (r,
9273                                    tsubst (DECL_FRIEND_CONTEXT (t),
9274                                             args, complain, in_decl));
9275
9276         /* Possibly limit visibility based on template args.  */
9277         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9278         if (DECL_VISIBILITY_SPECIFIED (t))
9279           {
9280             DECL_VISIBILITY_SPECIFIED (r) = 0;
9281             DECL_ATTRIBUTES (r)
9282               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9283           }
9284         determine_visibility (r);
9285         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9286             && !processing_template_decl)
9287           defaulted_late_check (r);
9288
9289         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9290                                         args, complain, in_decl);
9291       }
9292       break;
9293
9294     case PARM_DECL:
9295       {
9296         tree type = NULL_TREE;
9297         int i, len = 1;
9298         tree expanded_types = NULL_TREE;
9299         tree prev_r = NULL_TREE;
9300         tree first_r = NULL_TREE;
9301
9302         if (FUNCTION_PARAMETER_PACK_P (t))
9303           {
9304             /* If there is a local specialization that isn't a
9305                parameter pack, it means that we're doing a "simple"
9306                substitution from inside tsubst_pack_expansion. Just
9307                return the local specialization (which will be a single
9308                parm).  */
9309             tree spec = retrieve_local_specialization (t);
9310             if (spec 
9311                 && TREE_CODE (spec) == PARM_DECL
9312                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9313               RETURN (spec);
9314
9315             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9316                the parameters in this function parameter pack.  */
9317             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9318                                                     complain, in_decl);
9319             if (TREE_CODE (expanded_types) == TREE_VEC)
9320               {
9321                 len = TREE_VEC_LENGTH (expanded_types);
9322
9323                 /* Zero-length parameter packs are boring. Just substitute
9324                    into the chain.  */
9325                 if (len == 0)
9326                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9327                                   TREE_CHAIN (t)));
9328               }
9329             else
9330               {
9331                 /* All we did was update the type. Make a note of that.  */
9332                 type = expanded_types;
9333                 expanded_types = NULL_TREE;
9334               }
9335           }
9336
9337         /* Loop through all of the parameter's we'll build. When T is
9338            a function parameter pack, LEN is the number of expanded
9339            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9340         r = NULL_TREE;
9341         for (i = 0; i < len; ++i)
9342           {
9343             prev_r = r;
9344             r = copy_node (t);
9345             if (DECL_TEMPLATE_PARM_P (t))
9346               SET_DECL_TEMPLATE_PARM_P (r);
9347
9348             /* An argument of a function parameter pack is not a parameter
9349                pack.  */
9350             FUNCTION_PARAMETER_PACK_P (r) = false;
9351
9352             if (expanded_types)
9353               /* We're on the Ith parameter of the function parameter
9354                  pack.  */
9355               {
9356                 /* Get the Ith type.  */
9357                 type = TREE_VEC_ELT (expanded_types, i);
9358
9359                 if (DECL_NAME (r))
9360                   /* Rename the parameter to include the index.  */
9361                   DECL_NAME (r) =
9362                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9363               }
9364             else if (!type)
9365               /* We're dealing with a normal parameter.  */
9366               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9367
9368             type = type_decays_to (type);
9369             TREE_TYPE (r) = type;
9370             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9371
9372             if (DECL_INITIAL (r))
9373               {
9374                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9375                   DECL_INITIAL (r) = TREE_TYPE (r);
9376                 else
9377                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9378                                              complain, in_decl);
9379               }
9380
9381             DECL_CONTEXT (r) = NULL_TREE;
9382
9383             if (!DECL_TEMPLATE_PARM_P (r))
9384               DECL_ARG_TYPE (r) = type_passed_as (type);
9385
9386             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9387                                             args, complain, in_decl);
9388
9389             /* Keep track of the first new parameter we
9390                generate. That's what will be returned to the
9391                caller.  */
9392             if (!first_r)
9393               first_r = r;
9394
9395             /* Build a proper chain of parameters when substituting
9396                into a function parameter pack.  */
9397             if (prev_r)
9398               TREE_CHAIN (prev_r) = r;
9399           }
9400
9401         if (TREE_CHAIN (t))
9402           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
9403                                    complain, TREE_CHAIN (t));
9404
9405         /* FIRST_R contains the start of the chain we've built.  */
9406         r = first_r;
9407       }
9408       break;
9409
9410     case FIELD_DECL:
9411       {
9412         tree type;
9413
9414         r = copy_decl (t);
9415         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9416         if (type == error_mark_node)
9417           RETURN (error_mark_node);
9418         TREE_TYPE (r) = type;
9419         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9420
9421         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9422         DECL_INITIAL (r)
9423           = tsubst_expr (DECL_INITIAL (t), args,
9424                          complain, in_decl,
9425                          /*integral_constant_expression_p=*/true);
9426         /* We don't have to set DECL_CONTEXT here; it is set by
9427            finish_member_declaration.  */
9428         TREE_CHAIN (r) = NULL_TREE;
9429         if (VOID_TYPE_P (type))
9430           error ("instantiation of %q+D as type %qT", r, type);
9431
9432         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9433                                         args, complain, in_decl);
9434       }
9435       break;
9436
9437     case USING_DECL:
9438       /* We reach here only for member using decls.  */
9439       if (DECL_DEPENDENT_P (t))
9440         {
9441           r = do_class_using_decl
9442             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9443              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9444           if (!r)
9445             r = error_mark_node;
9446           else
9447             {
9448               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9449               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9450             }
9451         }
9452       else
9453         {
9454           r = copy_node (t);
9455           TREE_CHAIN (r) = NULL_TREE;
9456         }
9457       break;
9458
9459     case TYPE_DECL:
9460     case VAR_DECL:
9461       {
9462         tree argvec = NULL_TREE;
9463         tree gen_tmpl = NULL_TREE;
9464         tree spec;
9465         tree tmpl = NULL_TREE;
9466         tree ctx;
9467         tree type = NULL_TREE;
9468         bool local_p;
9469
9470         if (TREE_CODE (t) == TYPE_DECL
9471             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9472           {
9473             /* If this is the canonical decl, we don't have to
9474                mess with instantiations, and often we can't (for
9475                typename, template type parms and such).  Note that
9476                TYPE_NAME is not correct for the above test if
9477                we've copied the type for a typedef.  */
9478             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9479             if (type == error_mark_node)
9480               RETURN (error_mark_node);
9481             r = TYPE_NAME (type);
9482             break;
9483           }
9484
9485         /* Check to see if we already have the specialization we
9486            need.  */
9487         spec = NULL_TREE;
9488         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9489           {
9490             /* T is a static data member or namespace-scope entity.
9491                We have to substitute into namespace-scope variables
9492                (even though such entities are never templates) because
9493                of cases like:
9494                
9495                  template <class T> void f() { extern T t; }
9496
9497                where the entity referenced is not known until
9498                instantiation time.  */
9499             local_p = false;
9500             ctx = DECL_CONTEXT (t);
9501             if (DECL_CLASS_SCOPE_P (t))
9502               {
9503                 ctx = tsubst_aggr_type (ctx, args,
9504                                         complain,
9505                                         in_decl, /*entering_scope=*/1);
9506                 /* If CTX is unchanged, then T is in fact the
9507                    specialization we want.  That situation occurs when
9508                    referencing a static data member within in its own
9509                    class.  We can use pointer equality, rather than
9510                    same_type_p, because DECL_CONTEXT is always
9511                    canonical.  */
9512                 if (ctx == DECL_CONTEXT (t))
9513                   spec = t;
9514               }
9515
9516             if (!spec)
9517               {
9518                 tmpl = DECL_TI_TEMPLATE (t);
9519                 gen_tmpl = most_general_template (tmpl);
9520                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9521                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9522                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9523               }
9524           }
9525         else
9526           {
9527             /* A local variable.  */
9528             local_p = true;
9529             /* Subsequent calls to pushdecl will fill this in.  */
9530             ctx = NULL_TREE;
9531             spec = retrieve_local_specialization (t);
9532           }
9533         /* If we already have the specialization we need, there is
9534            nothing more to do.  */ 
9535         if (spec)
9536           {
9537             r = spec;
9538             break;
9539           }
9540
9541         /* Create a new node for the specialization we need.  */
9542         r = copy_decl (t);
9543         if (type == NULL_TREE)
9544           {
9545             if (is_typedef_decl (t))
9546               type = DECL_ORIGINAL_TYPE (t);
9547             else
9548               type = TREE_TYPE (t);
9549             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
9550               type = strip_array_domain (type);
9551             type = tsubst (type, args, complain, in_decl);
9552           }
9553         if (TREE_CODE (r) == VAR_DECL)
9554           {
9555             /* Even if the original location is out of scope, the
9556                newly substituted one is not.  */
9557             DECL_DEAD_FOR_LOCAL (r) = 0;
9558             DECL_INITIALIZED_P (r) = 0;
9559             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9560             if (type == error_mark_node)
9561               RETURN (error_mark_node);
9562             if (TREE_CODE (type) == FUNCTION_TYPE)
9563               {
9564                 /* It may seem that this case cannot occur, since:
9565
9566                      typedef void f();
9567                      void g() { f x; }
9568
9569                    declares a function, not a variable.  However:
9570       
9571                      typedef void f();
9572                      template <typename T> void g() { T t; }
9573                      template void g<f>();
9574
9575                    is an attempt to declare a variable with function
9576                    type.  */
9577                 error ("variable %qD has function type",
9578                        /* R is not yet sufficiently initialized, so we
9579                           just use its name.  */
9580                        DECL_NAME (r));
9581                 RETURN (error_mark_node);
9582               }
9583             type = complete_type (type);
9584             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9585               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9586             type = check_var_type (DECL_NAME (r), type);
9587
9588             if (DECL_HAS_VALUE_EXPR_P (t))
9589               {
9590                 tree ve = DECL_VALUE_EXPR (t);
9591                 ve = tsubst_expr (ve, args, complain, in_decl,
9592                                   /*constant_expression_p=*/false);
9593                 SET_DECL_VALUE_EXPR (r, ve);
9594               }
9595           }
9596         else if (DECL_SELF_REFERENCE_P (t))
9597           SET_DECL_SELF_REFERENCE_P (r);
9598         TREE_TYPE (r) = type;
9599         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9600         DECL_CONTEXT (r) = ctx;
9601         /* Clear out the mangled name and RTL for the instantiation.  */
9602         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9603         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9604           SET_DECL_RTL (r, NULL);
9605         /* The initializer must not be expanded until it is required;
9606            see [temp.inst].  */
9607         DECL_INITIAL (r) = NULL_TREE;
9608         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9609           SET_DECL_RTL (r, NULL);
9610         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9611         if (TREE_CODE (r) == VAR_DECL)
9612           {
9613             /* Possibly limit visibility based on template args.  */
9614             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9615             if (DECL_VISIBILITY_SPECIFIED (t))
9616               {
9617                 DECL_VISIBILITY_SPECIFIED (r) = 0;
9618                 DECL_ATTRIBUTES (r)
9619                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9620               }
9621             determine_visibility (r);
9622           }
9623
9624         if (!local_p)
9625           {
9626             /* A static data member declaration is always marked
9627                external when it is declared in-class, even if an
9628                initializer is present.  We mimic the non-template
9629                processing here.  */
9630             DECL_EXTERNAL (r) = 1;
9631
9632             register_specialization (r, gen_tmpl, argvec, false, hash);
9633             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
9634             SET_DECL_IMPLICIT_INSTANTIATION (r);
9635           }
9636         else if (cp_unevaluated_operand)
9637           {
9638             /* We're substituting this var in a decltype outside of its
9639                scope, such as for a lambda return type.  Don't add it to
9640                local_specializations, do perform auto deduction.  */
9641             tree auto_node = type_uses_auto (type);
9642             tree init
9643               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9644                              /*constant_expression_p=*/false);
9645
9646             if (auto_node && init && describable_type (init))
9647               {
9648                 type = do_auto_deduction (type, init, auto_node);
9649                 TREE_TYPE (r) = type;
9650               }
9651           }
9652         else
9653           register_local_specialization (r, t);
9654
9655         TREE_CHAIN (r) = NULL_TREE;
9656
9657         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9658                                         /*flags=*/0,
9659                                         args, complain, in_decl);
9660
9661         /* Preserve a typedef that names a type.  */
9662         if (is_typedef_decl (r))
9663           {
9664             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
9665             set_underlying_type (r);
9666           }
9667
9668         layout_decl (r, 0);
9669       }
9670       break;
9671
9672     default:
9673       gcc_unreachable ();
9674     }
9675 #undef RETURN
9676
9677  out:
9678   /* Restore the file and line information.  */
9679   input_location = saved_loc;
9680
9681   return r;
9682 }
9683
9684 /* Substitute into the ARG_TYPES of a function type.  */
9685
9686 static tree
9687 tsubst_arg_types (tree arg_types,
9688                   tree args,
9689                   tsubst_flags_t complain,
9690                   tree in_decl)
9691 {
9692   tree remaining_arg_types;
9693   tree type = NULL_TREE;
9694   int i = 1;
9695   tree expanded_args = NULL_TREE;
9696   tree default_arg;
9697
9698   if (!arg_types || arg_types == void_list_node)
9699     return arg_types;
9700
9701   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9702                                           args, complain, in_decl);
9703   if (remaining_arg_types == error_mark_node)
9704     return error_mark_node;
9705
9706   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9707     {
9708       /* For a pack expansion, perform substitution on the
9709          entire expression. Later on, we'll handle the arguments
9710          one-by-one.  */
9711       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9712                                             args, complain, in_decl);
9713
9714       if (TREE_CODE (expanded_args) == TREE_VEC)
9715         /* So that we'll spin through the parameters, one by one.  */
9716         i = TREE_VEC_LENGTH (expanded_args);
9717       else
9718         {
9719           /* We only partially substituted into the parameter
9720              pack. Our type is TYPE_PACK_EXPANSION.  */
9721           type = expanded_args;
9722           expanded_args = NULL_TREE;
9723         }
9724     }
9725
9726   while (i > 0) {
9727     --i;
9728     
9729     if (expanded_args)
9730       type = TREE_VEC_ELT (expanded_args, i);
9731     else if (!type)
9732       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9733
9734     if (type == error_mark_node)
9735       return error_mark_node;
9736     if (VOID_TYPE_P (type))
9737       {
9738         if (complain & tf_error)
9739           {
9740             error ("invalid parameter type %qT", type);
9741             if (in_decl)
9742               error ("in declaration %q+D", in_decl);
9743           }
9744         return error_mark_node;
9745     }
9746     
9747     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9748        top-level qualifiers as required.  */
9749     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9750
9751     /* We do not substitute into default arguments here.  The standard
9752        mandates that they be instantiated only when needed, which is
9753        done in build_over_call.  */
9754     default_arg = TREE_PURPOSE (arg_types);
9755
9756     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9757       {
9758         /* We've instantiated a template before its default arguments
9759            have been parsed.  This can happen for a nested template
9760            class, and is not an error unless we require the default
9761            argument in a call of this function.  */
9762         remaining_arg_types = 
9763           tree_cons (default_arg, type, remaining_arg_types);
9764         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9765                        remaining_arg_types);
9766       }
9767     else
9768       remaining_arg_types = 
9769         hash_tree_cons (default_arg, type, remaining_arg_types);
9770   }
9771         
9772   return remaining_arg_types;
9773 }
9774
9775 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9776    *not* handle the exception-specification for FNTYPE, because the
9777    initial substitution of explicitly provided template parameters
9778    during argument deduction forbids substitution into the
9779    exception-specification:
9780
9781      [temp.deduct]
9782
9783      All references in the function type of the function template to  the
9784      corresponding template parameters are replaced by the specified tem-
9785      plate argument values.  If a substitution in a template parameter or
9786      in  the function type of the function template results in an invalid
9787      type, type deduction fails.  [Note: The equivalent  substitution  in
9788      exception specifications is done only when the function is instanti-
9789      ated, at which point a program is  ill-formed  if  the  substitution
9790      results in an invalid type.]  */
9791
9792 static tree
9793 tsubst_function_type (tree t,
9794                       tree args,
9795                       tsubst_flags_t complain,
9796                       tree in_decl)
9797 {
9798   tree return_type;
9799   tree arg_types;
9800   tree fntype;
9801
9802   /* The TYPE_CONTEXT is not used for function/method types.  */
9803   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9804
9805   /* Substitute the return type.  */
9806   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9807   if (return_type == error_mark_node)
9808     return error_mark_node;
9809   /* The standard does not presently indicate that creation of a
9810      function type with an invalid return type is a deduction failure.
9811      However, that is clearly analogous to creating an array of "void"
9812      or a reference to a reference.  This is core issue #486.  */
9813   if (TREE_CODE (return_type) == ARRAY_TYPE
9814       || TREE_CODE (return_type) == FUNCTION_TYPE)
9815     {
9816       if (complain & tf_error)
9817         {
9818           if (TREE_CODE (return_type) == ARRAY_TYPE)
9819             error ("function returning an array");
9820           else
9821             error ("function returning a function");
9822         }
9823       return error_mark_node;
9824     }
9825
9826   /* Substitute the argument types.  */
9827   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9828                                 complain, in_decl);
9829   if (arg_types == error_mark_node)
9830     return error_mark_node;
9831
9832   /* Construct a new type node and return it.  */
9833   if (TREE_CODE (t) == FUNCTION_TYPE)
9834     {
9835       fntype = build_function_type (return_type, arg_types);
9836       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
9837     }
9838   else
9839     {
9840       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9841       if (! MAYBE_CLASS_TYPE_P (r))
9842         {
9843           /* [temp.deduct]
9844
9845              Type deduction may fail for any of the following
9846              reasons:
9847
9848              -- Attempting to create "pointer to member of T" when T
9849              is not a class type.  */
9850           if (complain & tf_error)
9851             error ("creating pointer to member function of non-class type %qT",
9852                       r);
9853           return error_mark_node;
9854         }
9855
9856       fntype = build_method_type_directly (r, return_type,
9857                                            TREE_CHAIN (arg_types));
9858     }
9859   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9860
9861   return fntype;
9862 }
9863
9864 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9865    ARGS into that specification, and return the substituted
9866    specification.  If there is no specification, return NULL_TREE.  */
9867
9868 static tree
9869 tsubst_exception_specification (tree fntype,
9870                                 tree args,
9871                                 tsubst_flags_t complain,
9872                                 tree in_decl)
9873 {
9874   tree specs;
9875   tree new_specs;
9876
9877   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9878   new_specs = NULL_TREE;
9879   if (specs && TREE_PURPOSE (specs))
9880     {
9881       /* A noexcept-specifier.  */
9882       new_specs = tsubst_copy_and_build
9883         (TREE_PURPOSE (specs), args, complain, in_decl, /*function_p=*/false,
9884          /*integral_constant_expression_p=*/true);
9885       new_specs = build_noexcept_spec (new_specs, complain);
9886     }
9887   else if (specs)
9888     {
9889       if (! TREE_VALUE (specs))
9890         new_specs = specs;
9891       else
9892         while (specs)
9893           {
9894             tree spec;
9895             int i, len = 1;
9896             tree expanded_specs = NULL_TREE;
9897
9898             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9899               {
9900                 /* Expand the pack expansion type.  */
9901                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9902                                                        args, complain,
9903                                                        in_decl);
9904
9905                 if (expanded_specs == error_mark_node)
9906                   return error_mark_node;
9907                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9908                   len = TREE_VEC_LENGTH (expanded_specs);
9909                 else
9910                   {
9911                     /* We're substituting into a member template, so
9912                        we got a TYPE_PACK_EXPANSION back.  Add that
9913                        expansion and move on.  */
9914                     gcc_assert (TREE_CODE (expanded_specs) 
9915                                 == TYPE_PACK_EXPANSION);
9916                     new_specs = add_exception_specifier (new_specs,
9917                                                          expanded_specs,
9918                                                          complain);
9919                     specs = TREE_CHAIN (specs);
9920                     continue;
9921                   }
9922               }
9923
9924             for (i = 0; i < len; ++i)
9925               {
9926                 if (expanded_specs)
9927                   spec = TREE_VEC_ELT (expanded_specs, i);
9928                 else
9929                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9930                 if (spec == error_mark_node)
9931                   return spec;
9932                 new_specs = add_exception_specifier (new_specs, spec, 
9933                                                      complain);
9934               }
9935
9936             specs = TREE_CHAIN (specs);
9937           }
9938     }
9939   return new_specs;
9940 }
9941
9942 /* Take the tree structure T and replace template parameters used
9943    therein with the argument vector ARGS.  IN_DECL is an associated
9944    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9945    Issue error and warning messages under control of COMPLAIN.  Note
9946    that we must be relatively non-tolerant of extensions here, in
9947    order to preserve conformance; if we allow substitutions that
9948    should not be allowed, we may allow argument deductions that should
9949    not succeed, and therefore report ambiguous overload situations
9950    where there are none.  In theory, we could allow the substitution,
9951    but indicate that it should have failed, and allow our caller to
9952    make sure that the right thing happens, but we don't try to do this
9953    yet.
9954
9955    This function is used for dealing with types, decls and the like;
9956    for expressions, use tsubst_expr or tsubst_copy.  */
9957
9958 tree
9959 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9960 {
9961   tree type, r;
9962
9963   if (t == NULL_TREE || t == error_mark_node
9964       || t == integer_type_node
9965       || t == void_type_node
9966       || t == char_type_node
9967       || t == unknown_type_node
9968       || TREE_CODE (t) == NAMESPACE_DECL)
9969     return t;
9970
9971   if (DECL_P (t))
9972     return tsubst_decl (t, args, complain);
9973
9974   if (args == NULL_TREE)
9975     return t;
9976
9977   if (TREE_CODE (t) == IDENTIFIER_NODE)
9978     type = IDENTIFIER_TYPE_VALUE (t);
9979   else
9980     type = TREE_TYPE (t);
9981
9982   gcc_assert (type != unknown_type_node);
9983
9984   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9985      such as attribute aligned.  */
9986   if (TYPE_P (t)
9987       && TYPE_NAME (t)
9988       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9989     {
9990       tree decl = TYPE_NAME (t);
9991       
9992       if (DECL_CLASS_SCOPE_P (decl)
9993           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9994           && uses_template_parms (DECL_CONTEXT (decl)))
9995         {
9996           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9997           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9998           r = retrieve_specialization (tmpl, gen_args, 0);
9999         }
10000       else if (DECL_FUNCTION_SCOPE_P (decl)
10001                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10002                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10003         r = retrieve_local_specialization (decl);
10004       else
10005         /* The typedef is from a non-template context.  */
10006         return t;
10007
10008       if (r)
10009         {
10010           r = TREE_TYPE (r);
10011           r = cp_build_qualified_type_real
10012             (r, cp_type_quals (t) | cp_type_quals (r),
10013              complain | tf_ignore_bad_quals);
10014           return r;
10015         }
10016       /* Else we must be instantiating the typedef, so fall through.  */
10017     }
10018
10019   if (type
10020       && TREE_CODE (t) != TYPENAME_TYPE
10021       && TREE_CODE (t) != TEMPLATE_TYPE_PARM
10022       && TREE_CODE (t) != IDENTIFIER_NODE
10023       && TREE_CODE (t) != FUNCTION_TYPE
10024       && TREE_CODE (t) != METHOD_TYPE)
10025     type = tsubst (type, args, complain, in_decl);
10026   if (type == error_mark_node)
10027     return error_mark_node;
10028
10029   switch (TREE_CODE (t))
10030     {
10031     case RECORD_TYPE:
10032     case UNION_TYPE:
10033     case ENUMERAL_TYPE:
10034       return tsubst_aggr_type (t, args, complain, in_decl,
10035                                /*entering_scope=*/0);
10036
10037     case ERROR_MARK:
10038     case IDENTIFIER_NODE:
10039     case VOID_TYPE:
10040     case REAL_TYPE:
10041     case COMPLEX_TYPE:
10042     case VECTOR_TYPE:
10043     case BOOLEAN_TYPE:
10044     case INTEGER_CST:
10045     case REAL_CST:
10046     case STRING_CST:
10047       return t;
10048
10049     case INTEGER_TYPE:
10050       if (t == integer_type_node)
10051         return t;
10052
10053       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10054           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10055         return t;
10056
10057       {
10058         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10059
10060         max = tsubst_expr (omax, args, complain, in_decl,
10061                            /*integral_constant_expression_p=*/false);
10062
10063         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10064            needed.  */
10065         if (TREE_CODE (max) == NOP_EXPR
10066             && TREE_SIDE_EFFECTS (omax)
10067             && !TREE_TYPE (max))
10068           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10069
10070         max = fold_decl_constant_value (max);
10071
10072         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10073            with TREE_SIDE_EFFECTS that indicates this is not an integral
10074            constant expression.  */
10075         if (processing_template_decl
10076             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10077           {
10078             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10079             TREE_SIDE_EFFECTS (max) = 1;
10080           }
10081
10082         if (TREE_CODE (max) != INTEGER_CST
10083             && !at_function_scope_p ()
10084             && !TREE_SIDE_EFFECTS (max)
10085             && !value_dependent_expression_p (max))
10086           {
10087             if (complain & tf_error)
10088               error ("array bound is not an integer constant");
10089             return error_mark_node;
10090           }
10091
10092         /* [temp.deduct]
10093
10094            Type deduction may fail for any of the following
10095            reasons:
10096
10097              Attempting to create an array with a size that is
10098              zero or negative.  */
10099         if (integer_zerop (max) && !(complain & tf_error))
10100           /* We must fail if performing argument deduction (as
10101              indicated by the state of complain), so that
10102              another substitution can be found.  */
10103           return error_mark_node;
10104         else if (TREE_CODE (max) == INTEGER_CST
10105                  && INT_CST_LT (max, integer_zero_node))
10106           {
10107             if (complain & tf_error)
10108               error ("creating array with negative size (%qE)", max);
10109
10110             return error_mark_node;
10111           }
10112
10113         return compute_array_index_type (NULL_TREE, max);
10114       }
10115
10116     case TEMPLATE_TYPE_PARM:
10117     case TEMPLATE_TEMPLATE_PARM:
10118     case BOUND_TEMPLATE_TEMPLATE_PARM:
10119     case TEMPLATE_PARM_INDEX:
10120       {
10121         int idx;
10122         int level;
10123         int levels;
10124         tree arg = NULL_TREE;
10125
10126         r = NULL_TREE;
10127
10128         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10129         template_parm_level_and_index (t, &level, &idx); 
10130
10131         levels = TMPL_ARGS_DEPTH (args);
10132         if (level <= levels)
10133           {
10134             arg = TMPL_ARG (args, level, idx);
10135
10136             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10137               /* See through ARGUMENT_PACK_SELECT arguments. */
10138               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10139           }
10140
10141         if (arg == error_mark_node)
10142           return error_mark_node;
10143         else if (arg != NULL_TREE)
10144           {
10145             if (ARGUMENT_PACK_P (arg))
10146               /* If ARG is an argument pack, we don't actually want to
10147                  perform a substitution here, because substitutions
10148                  for argument packs are only done
10149                  element-by-element. We can get to this point when
10150                  substituting the type of a non-type template
10151                  parameter pack, when that type actually contains
10152                  template parameter packs from an outer template, e.g.,
10153
10154                  template<typename... Types> struct A {
10155                    template<Types... Values> struct B { };
10156                  };  */
10157               return t;
10158
10159             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
10160               {
10161                 int quals;
10162                 gcc_assert (TYPE_P (arg));
10163
10164                 quals = cp_type_quals (arg) | cp_type_quals (t);
10165                   
10166                 return cp_build_qualified_type_real
10167                   (arg, quals, complain | tf_ignore_bad_quals);
10168               }
10169             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10170               {
10171                 /* We are processing a type constructed from a
10172                    template template parameter.  */
10173                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10174                                       args, complain, in_decl);
10175                 if (argvec == error_mark_node)
10176                   return error_mark_node;
10177
10178                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10179                    are resolving nested-types in the signature of a
10180                    member function templates.  Otherwise ARG is a
10181                    TEMPLATE_DECL and is the real template to be
10182                    instantiated.  */
10183                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10184                   arg = TYPE_NAME (arg);
10185
10186                 r = lookup_template_class (arg,
10187                                            argvec, in_decl,
10188                                            DECL_CONTEXT (arg),
10189                                             /*entering_scope=*/0,
10190                                            complain);
10191                 return cp_build_qualified_type_real
10192                   (r, cp_type_quals (t), complain);
10193               }
10194             else
10195               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10196               return unshare_expr (arg);
10197           }
10198
10199         if (level == 1)
10200           /* This can happen during the attempted tsubst'ing in
10201              unify.  This means that we don't yet have any information
10202              about the template parameter in question.  */
10203           return t;
10204
10205         /* If we get here, we must have been looking at a parm for a
10206            more deeply nested template.  Make a new version of this
10207            template parameter, but with a lower level.  */
10208         switch (TREE_CODE (t))
10209           {
10210           case TEMPLATE_TYPE_PARM:
10211           case TEMPLATE_TEMPLATE_PARM:
10212           case BOUND_TEMPLATE_TEMPLATE_PARM:
10213             if (cp_type_quals (t))
10214               {
10215                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10216                 r = cp_build_qualified_type_real
10217                   (r, cp_type_quals (t),
10218                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
10219                                ? tf_ignore_bad_quals : 0));
10220               }
10221             else
10222               {
10223                 r = copy_type (t);
10224                 TEMPLATE_TYPE_PARM_INDEX (r)
10225                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10226                                                 r, levels, args, complain);
10227                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10228                 TYPE_MAIN_VARIANT (r) = r;
10229                 TYPE_POINTER_TO (r) = NULL_TREE;
10230                 TYPE_REFERENCE_TO (r) = NULL_TREE;
10231
10232                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10233                   /* We have reduced the level of the template
10234                      template parameter, but not the levels of its
10235                      template parameters, so canonical_type_parameter
10236                      will not be able to find the canonical template
10237                      template parameter for this level. Thus, we
10238                      require structural equality checking to compare
10239                      TEMPLATE_TEMPLATE_PARMs. */
10240                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10241                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10242                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10243                 else
10244                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
10245
10246                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10247                   {
10248                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10249                                           complain, in_decl);
10250                     if (argvec == error_mark_node)
10251                       return error_mark_node;
10252
10253                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10254                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10255                   }
10256               }
10257             break;
10258
10259           case TEMPLATE_PARM_INDEX:
10260             r = reduce_template_parm_level (t, type, levels, args, complain);
10261             break;
10262
10263           default:
10264             gcc_unreachable ();
10265           }
10266
10267         return r;
10268       }
10269
10270     case TREE_LIST:
10271       {
10272         tree purpose, value, chain;
10273
10274         if (t == void_list_node)
10275           return t;
10276
10277         purpose = TREE_PURPOSE (t);
10278         if (purpose)
10279           {
10280             purpose = tsubst (purpose, args, complain, in_decl);
10281             if (purpose == error_mark_node)
10282               return error_mark_node;
10283           }
10284         value = TREE_VALUE (t);
10285         if (value)
10286           {
10287             value = tsubst (value, args, complain, in_decl);
10288             if (value == error_mark_node)
10289               return error_mark_node;
10290           }
10291         chain = TREE_CHAIN (t);
10292         if (chain && chain != void_type_node)
10293           {
10294             chain = tsubst (chain, args, complain, in_decl);
10295             if (chain == error_mark_node)
10296               return error_mark_node;
10297           }
10298         if (purpose == TREE_PURPOSE (t)
10299             && value == TREE_VALUE (t)
10300             && chain == TREE_CHAIN (t))
10301           return t;
10302         return hash_tree_cons (purpose, value, chain);
10303       }
10304
10305     case TREE_BINFO:
10306       /* We should never be tsubsting a binfo.  */
10307       gcc_unreachable ();
10308
10309     case TREE_VEC:
10310       /* A vector of template arguments.  */
10311       gcc_assert (!type);
10312       return tsubst_template_args (t, args, complain, in_decl);
10313
10314     case POINTER_TYPE:
10315     case REFERENCE_TYPE:
10316       {
10317         enum tree_code code;
10318
10319         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10320           return t;
10321
10322         code = TREE_CODE (t);
10323
10324
10325         /* [temp.deduct]
10326
10327            Type deduction may fail for any of the following
10328            reasons:
10329
10330            -- Attempting to create a pointer to reference type.
10331            -- Attempting to create a reference to a reference type or
10332               a reference to void.
10333
10334           Core issue 106 says that creating a reference to a reference
10335           during instantiation is no longer a cause for failure. We
10336           only enforce this check in strict C++98 mode.  */
10337         if ((TREE_CODE (type) == REFERENCE_TYPE
10338              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10339             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10340           {
10341             static location_t last_loc;
10342
10343             /* We keep track of the last time we issued this error
10344                message to avoid spewing a ton of messages during a
10345                single bad template instantiation.  */
10346             if (complain & tf_error
10347                 && last_loc != input_location)
10348               {
10349                 if (TREE_CODE (type) == VOID_TYPE)
10350                   error ("forming reference to void");
10351                else if (code == POINTER_TYPE)
10352                  error ("forming pointer to reference type %qT", type);
10353                else
10354                   error ("forming reference to reference type %qT", type);
10355                 last_loc = input_location;
10356               }
10357
10358             return error_mark_node;
10359           }
10360         else if (code == POINTER_TYPE)
10361           {
10362             r = build_pointer_type (type);
10363             if (TREE_CODE (type) == METHOD_TYPE)
10364               r = build_ptrmemfunc_type (r);
10365           }
10366         else if (TREE_CODE (type) == REFERENCE_TYPE)
10367           /* In C++0x, during template argument substitution, when there is an
10368              attempt to create a reference to a reference type, reference
10369              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10370
10371              "If a template-argument for a template-parameter T names a type
10372              that is a reference to a type A, an attempt to create the type
10373              'lvalue reference to cv T' creates the type 'lvalue reference to
10374              A,' while an attempt to create the type type rvalue reference to
10375              cv T' creates the type T"
10376           */
10377           r = cp_build_reference_type
10378               (TREE_TYPE (type),
10379                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10380         else
10381           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10382         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
10383
10384         if (r != error_mark_node)
10385           /* Will this ever be needed for TYPE_..._TO values?  */
10386           layout_type (r);
10387
10388         return r;
10389       }
10390     case OFFSET_TYPE:
10391       {
10392         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10393         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10394           {
10395             /* [temp.deduct]
10396
10397                Type deduction may fail for any of the following
10398                reasons:
10399
10400                -- Attempting to create "pointer to member of T" when T
10401                   is not a class type.  */
10402             if (complain & tf_error)
10403               error ("creating pointer to member of non-class type %qT", r);
10404             return error_mark_node;
10405           }
10406         if (TREE_CODE (type) == REFERENCE_TYPE)
10407           {
10408             if (complain & tf_error)
10409               error ("creating pointer to member reference type %qT", type);
10410             return error_mark_node;
10411           }
10412         if (TREE_CODE (type) == VOID_TYPE)
10413           {
10414             if (complain & tf_error)
10415               error ("creating pointer to member of type void");
10416             return error_mark_node;
10417           }
10418         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10419         if (TREE_CODE (type) == FUNCTION_TYPE)
10420           {
10421             /* The type of the implicit object parameter gets its
10422                cv-qualifiers from the FUNCTION_TYPE. */
10423             tree memptr;
10424             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
10425             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10426             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10427                                                  complain);
10428           }
10429         else
10430           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10431                                                cp_type_quals (t),
10432                                                complain);
10433       }
10434     case FUNCTION_TYPE:
10435     case METHOD_TYPE:
10436       {
10437         tree fntype;
10438         tree specs;
10439         fntype = tsubst_function_type (t, args, complain, in_decl);
10440         if (fntype == error_mark_node)
10441           return error_mark_node;
10442
10443         /* Substitute the exception specification.  */
10444         specs = tsubst_exception_specification (t, args, complain,
10445                                                 in_decl);
10446         if (specs == error_mark_node)
10447           return error_mark_node;
10448         if (specs)
10449           fntype = build_exception_variant (fntype, specs);
10450         return fntype;
10451       }
10452     case ARRAY_TYPE:
10453       {
10454         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10455         if (domain == error_mark_node)
10456           return error_mark_node;
10457
10458         /* As an optimization, we avoid regenerating the array type if
10459            it will obviously be the same as T.  */
10460         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10461           return t;
10462
10463         /* These checks should match the ones in grokdeclarator.
10464
10465            [temp.deduct]
10466
10467            The deduction may fail for any of the following reasons:
10468
10469            -- Attempting to create an array with an element type that
10470               is void, a function type, or a reference type, or [DR337]
10471               an abstract class type.  */
10472         if (TREE_CODE (type) == VOID_TYPE
10473             || TREE_CODE (type) == FUNCTION_TYPE
10474             || TREE_CODE (type) == REFERENCE_TYPE)
10475           {
10476             if (complain & tf_error)
10477               error ("creating array of %qT", type);
10478             return error_mark_node;
10479           }
10480         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10481           {
10482             if (complain & tf_error)
10483               error ("creating array of %qT, which is an abstract class type",
10484                      type);
10485             return error_mark_node;
10486           }
10487
10488         r = build_cplus_array_type (type, domain);
10489
10490         if (TYPE_USER_ALIGN (t))
10491           {
10492             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10493             TYPE_USER_ALIGN (r) = 1;
10494           }
10495
10496         return r;
10497       }
10498
10499     case PLUS_EXPR:
10500     case MINUS_EXPR:
10501       {
10502         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10503         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10504
10505         if (e1 == error_mark_node || e2 == error_mark_node)
10506           return error_mark_node;
10507
10508         return fold_build2_loc (input_location,
10509                             TREE_CODE (t), TREE_TYPE (t), e1, e2);
10510       }
10511
10512     case NEGATE_EXPR:
10513     case NOP_EXPR:
10514       {
10515         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10516         if (e == error_mark_node)
10517           return error_mark_node;
10518
10519         return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
10520       }
10521
10522     case TYPENAME_TYPE:
10523       {
10524         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10525                                      in_decl, /*entering_scope=*/1);
10526         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10527                               complain, in_decl);
10528
10529         if (ctx == error_mark_node || f == error_mark_node)
10530           return error_mark_node;
10531
10532         if (!MAYBE_CLASS_TYPE_P (ctx))
10533           {
10534             if (complain & tf_error)
10535               error ("%qT is not a class, struct, or union type", ctx);
10536             return error_mark_node;
10537           }
10538         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10539           {
10540             /* Normally, make_typename_type does not require that the CTX
10541                have complete type in order to allow things like:
10542
10543                  template <class T> struct S { typename S<T>::X Y; };
10544
10545                But, such constructs have already been resolved by this
10546                point, so here CTX really should have complete type, unless
10547                it's a partial instantiation.  */
10548             if (!(complain & tf_no_class_instantiations))
10549               ctx = complete_type (ctx);
10550             if (!COMPLETE_TYPE_P (ctx))
10551               {
10552                 if (complain & tf_error)
10553                   cxx_incomplete_type_error (NULL_TREE, ctx);
10554                 return error_mark_node;
10555               }
10556           }
10557
10558         f = make_typename_type (ctx, f, typename_type,
10559                                 (complain & tf_error) | tf_keep_type_decl);
10560         if (f == error_mark_node)
10561           return f;
10562         if (TREE_CODE (f) == TYPE_DECL)
10563           {
10564             complain |= tf_ignore_bad_quals;
10565             f = TREE_TYPE (f);
10566           }
10567
10568         if (TREE_CODE (f) != TYPENAME_TYPE)
10569           {
10570             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10571               error ("%qT resolves to %qT, which is not an enumeration type",
10572                      t, f);
10573             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10574               error ("%qT resolves to %qT, which is is not a class type",
10575                      t, f);
10576           }
10577
10578         return cp_build_qualified_type_real
10579           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10580       }
10581
10582     case UNBOUND_CLASS_TEMPLATE:
10583       {
10584         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10585                                      in_decl, /*entering_scope=*/1);
10586         tree name = TYPE_IDENTIFIER (t);
10587         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10588
10589         if (ctx == error_mark_node || name == error_mark_node)
10590           return error_mark_node;
10591
10592         if (parm_list)
10593           parm_list = tsubst_template_parms (parm_list, args, complain);
10594         return make_unbound_class_template (ctx, name, parm_list, complain);
10595       }
10596
10597     case INDIRECT_REF:
10598     case ADDR_EXPR:
10599     case CALL_EXPR:
10600       gcc_unreachable ();
10601
10602     case ARRAY_REF:
10603       {
10604         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10605         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10606                                /*integral_constant_expression_p=*/false);
10607         if (e1 == error_mark_node || e2 == error_mark_node)
10608           return error_mark_node;
10609
10610         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10611       }
10612
10613     case SCOPE_REF:
10614       {
10615         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10616         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10617         if (e1 == error_mark_node || e2 == error_mark_node)
10618           return error_mark_node;
10619
10620         return build_qualified_name (/*type=*/NULL_TREE,
10621                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10622       }
10623
10624     case TYPEOF_TYPE:
10625       {
10626         tree type;
10627
10628         ++cp_unevaluated_operand;
10629         ++c_inhibit_evaluation_warnings;
10630
10631         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10632                             complain, in_decl,
10633                             /*integral_constant_expression_p=*/false);
10634
10635         --cp_unevaluated_operand;
10636         --c_inhibit_evaluation_warnings;
10637
10638         type = finish_typeof (type);
10639         return cp_build_qualified_type_real (type,
10640                                              cp_type_quals (t)
10641                                              | cp_type_quals (type),
10642                                              complain);
10643       }
10644
10645     case DECLTYPE_TYPE:
10646       {
10647         tree type;
10648
10649         ++cp_unevaluated_operand;
10650         ++c_inhibit_evaluation_warnings;
10651
10652         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10653                             complain, in_decl,
10654                             /*integral_constant_expression_p=*/false);
10655
10656         --cp_unevaluated_operand;
10657         --c_inhibit_evaluation_warnings;
10658
10659         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10660           type = lambda_capture_field_type (type);
10661         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10662           type = lambda_return_type (type);
10663         else
10664           type = finish_decltype_type
10665             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10666         return cp_build_qualified_type_real (type,
10667                                              cp_type_quals (t)
10668                                              | cp_type_quals (type),
10669                                              complain);
10670       }
10671
10672     case TYPE_ARGUMENT_PACK:
10673     case NONTYPE_ARGUMENT_PACK:
10674       {
10675         tree r = TYPE_P (t)
10676           ? cxx_make_type (TREE_CODE (t))
10677           : make_node (TREE_CODE (t));
10678         tree packed_out = 
10679           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10680                                 args,
10681                                 complain,
10682                                 in_decl);
10683         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10684
10685         /* For template nontype argument packs, also substitute into
10686            the type.  */
10687         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10688           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10689
10690         return r;
10691       }
10692       break;
10693
10694     default:
10695       sorry ("use of %qs in template",
10696              tree_code_name [(int) TREE_CODE (t)]);
10697       return error_mark_node;
10698     }
10699 }
10700
10701 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10702    type of the expression on the left-hand side of the "." or "->"
10703    operator.  */
10704
10705 static tree
10706 tsubst_baselink (tree baselink, tree object_type,
10707                  tree args, tsubst_flags_t complain, tree in_decl)
10708 {
10709     tree name;
10710     tree qualifying_scope;
10711     tree fns;
10712     tree optype;
10713     tree template_args = 0;
10714     bool template_id_p = false;
10715
10716     /* A baselink indicates a function from a base class.  Both the
10717        BASELINK_ACCESS_BINFO and the base class referenced may
10718        indicate bases of the template class, rather than the
10719        instantiated class.  In addition, lookups that were not
10720        ambiguous before may be ambiguous now.  Therefore, we perform
10721        the lookup again.  */
10722     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10723     qualifying_scope = tsubst (qualifying_scope, args,
10724                                complain, in_decl);
10725     fns = BASELINK_FUNCTIONS (baselink);
10726     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10727     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10728       {
10729         template_id_p = true;
10730         template_args = TREE_OPERAND (fns, 1);
10731         fns = TREE_OPERAND (fns, 0);
10732         if (template_args)
10733           template_args = tsubst_template_args (template_args, args,
10734                                                 complain, in_decl);
10735       }
10736     name = DECL_NAME (get_first_fn (fns));
10737     if (IDENTIFIER_TYPENAME_P (name))
10738       name = mangle_conv_op_name_for_type (optype);
10739     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10740
10741     /* If lookup found a single function, mark it as used at this
10742        point.  (If it lookup found multiple functions the one selected
10743        later by overload resolution will be marked as used at that
10744        point.)  */
10745     if (BASELINK_P (baselink))
10746       fns = BASELINK_FUNCTIONS (baselink);
10747     if (!template_id_p && !really_overloaded_fn (fns))
10748       mark_used (OVL_CURRENT (fns));
10749
10750     /* Add back the template arguments, if present.  */
10751     if (BASELINK_P (baselink) && template_id_p)
10752       BASELINK_FUNCTIONS (baselink)
10753         = build_nt (TEMPLATE_ID_EXPR,
10754                     BASELINK_FUNCTIONS (baselink),
10755                     template_args);
10756     /* Update the conversion operator type.  */
10757     BASELINK_OPTYPE (baselink) = optype;
10758
10759     if (!object_type)
10760       object_type = current_class_type;
10761     return adjust_result_of_qualified_name_lookup (baselink,
10762                                                    qualifying_scope,
10763                                                    object_type);
10764 }
10765
10766 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10767    true if the qualified-id will be a postfix-expression in-and-of
10768    itself; false if more of the postfix-expression follows the
10769    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10770    of "&".  */
10771
10772 static tree
10773 tsubst_qualified_id (tree qualified_id, tree args,
10774                      tsubst_flags_t complain, tree in_decl,
10775                      bool done, bool address_p)
10776 {
10777   tree expr;
10778   tree scope;
10779   tree name;
10780   bool is_template;
10781   tree template_args;
10782
10783   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10784
10785   /* Figure out what name to look up.  */
10786   name = TREE_OPERAND (qualified_id, 1);
10787   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10788     {
10789       is_template = true;
10790       template_args = TREE_OPERAND (name, 1);
10791       if (template_args)
10792         template_args = tsubst_template_args (template_args, args,
10793                                               complain, in_decl);
10794       name = TREE_OPERAND (name, 0);
10795     }
10796   else
10797     {
10798       is_template = false;
10799       template_args = NULL_TREE;
10800     }
10801
10802   /* Substitute into the qualifying scope.  When there are no ARGS, we
10803      are just trying to simplify a non-dependent expression.  In that
10804      case the qualifying scope may be dependent, and, in any case,
10805      substituting will not help.  */
10806   scope = TREE_OPERAND (qualified_id, 0);
10807   if (args)
10808     {
10809       scope = tsubst (scope, args, complain, in_decl);
10810       expr = tsubst_copy (name, args, complain, in_decl);
10811     }
10812   else
10813     expr = name;
10814
10815   if (dependent_scope_p (scope))
10816     return build_qualified_name (NULL_TREE, scope, expr,
10817                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10818
10819   if (!BASELINK_P (name) && !DECL_P (expr))
10820     {
10821       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10822         {
10823           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10824           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10825             {
10826               error ("qualifying type %qT does not match destructor name ~%qT",
10827                      scope, TREE_OPERAND (expr, 0));
10828               expr = error_mark_node;
10829             }
10830           else
10831             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10832                                           /*is_type_p=*/0, false);
10833         }
10834       else
10835         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10836       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10837                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10838         {
10839           if (complain & tf_error)
10840             {
10841               error ("dependent-name %qE is parsed as a non-type, but "
10842                      "instantiation yields a type", qualified_id);
10843               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10844             }
10845           return error_mark_node;
10846         }
10847     }
10848
10849   if (DECL_P (expr))
10850     {
10851       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10852                                            scope);
10853       /* Remember that there was a reference to this entity.  */
10854       mark_used (expr);
10855     }
10856
10857   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10858     {
10859       if (complain & tf_error)
10860         qualified_name_lookup_error (scope,
10861                                      TREE_OPERAND (qualified_id, 1),
10862                                      expr, input_location);
10863       return error_mark_node;
10864     }
10865
10866   if (is_template)
10867     expr = lookup_template_function (expr, template_args);
10868
10869   if (expr == error_mark_node && complain & tf_error)
10870     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10871                                  expr, input_location);
10872   else if (TYPE_P (scope))
10873     {
10874       expr = (adjust_result_of_qualified_name_lookup
10875               (expr, scope, current_class_type));
10876       expr = (finish_qualified_id_expr
10877               (scope, expr, done, address_p,
10878                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10879                /*template_arg_p=*/false));
10880     }
10881
10882   /* Expressions do not generally have reference type.  */
10883   if (TREE_CODE (expr) != SCOPE_REF
10884       /* However, if we're about to form a pointer-to-member, we just
10885          want the referenced member referenced.  */
10886       && TREE_CODE (expr) != OFFSET_REF)
10887     expr = convert_from_reference (expr);
10888
10889   return expr;
10890 }
10891
10892 /* Like tsubst, but deals with expressions.  This function just replaces
10893    template parms; to finish processing the resultant expression, use
10894    tsubst_expr.  */
10895
10896 static tree
10897 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10898 {
10899   enum tree_code code;
10900   tree r;
10901
10902   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10903     return t;
10904
10905   code = TREE_CODE (t);
10906
10907   switch (code)
10908     {
10909     case PARM_DECL:
10910       r = retrieve_local_specialization (t);
10911
10912       if (r == NULL)
10913         {
10914           tree c;
10915           /* This can happen for a parameter name used later in a function
10916              declaration (such as in a late-specified return type).  Just
10917              make a dummy decl, since it's only used for its type.  */
10918           gcc_assert (cp_unevaluated_operand != 0);
10919           /* We copy T because want to tsubst the PARM_DECL only,
10920              not the following PARM_DECLs that are chained to T.  */
10921           c = copy_node (t);
10922           r = tsubst_decl (c, args, complain);
10923           /* Give it the template pattern as its context; its true context
10924              hasn't been instantiated yet and this is good enough for
10925              mangling.  */
10926           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10927         }
10928       
10929       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10930         r = ARGUMENT_PACK_SELECT_ARG (r);
10931       mark_used (r);
10932       return r;
10933
10934     case CONST_DECL:
10935       {
10936         tree enum_type;
10937         tree v;
10938
10939         if (DECL_TEMPLATE_PARM_P (t))
10940           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10941         /* There is no need to substitute into namespace-scope
10942            enumerators.  */
10943         if (DECL_NAMESPACE_SCOPE_P (t))
10944           return t;
10945         /* If ARGS is NULL, then T is known to be non-dependent.  */
10946         if (args == NULL_TREE)
10947           return integral_constant_value (t);
10948
10949         /* Unfortunately, we cannot just call lookup_name here.
10950            Consider:
10951
10952              template <int I> int f() {
10953              enum E { a = I };
10954              struct S { void g() { E e = a; } };
10955              };
10956
10957            When we instantiate f<7>::S::g(), say, lookup_name is not
10958            clever enough to find f<7>::a.  */
10959         enum_type
10960           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10961                               /*entering_scope=*/0);
10962
10963         for (v = TYPE_VALUES (enum_type);
10964              v != NULL_TREE;
10965              v = TREE_CHAIN (v))
10966           if (TREE_PURPOSE (v) == DECL_NAME (t))
10967             return TREE_VALUE (v);
10968
10969           /* We didn't find the name.  That should never happen; if
10970              name-lookup found it during preliminary parsing, we
10971              should find it again here during instantiation.  */
10972         gcc_unreachable ();
10973       }
10974       return t;
10975
10976     case FIELD_DECL:
10977       if (DECL_CONTEXT (t))
10978         {
10979           tree ctx;
10980
10981           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10982                                   /*entering_scope=*/1);
10983           if (ctx != DECL_CONTEXT (t))
10984             {
10985               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10986               if (!r)
10987                 {
10988                   if (complain & tf_error)
10989                     error ("using invalid field %qD", t);
10990                   return error_mark_node;
10991                 }
10992               return r;
10993             }
10994         }
10995
10996       return t;
10997
10998     case VAR_DECL:
10999     case FUNCTION_DECL:
11000       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11001           || local_variable_p (t))
11002         t = tsubst (t, args, complain, in_decl);
11003       mark_used (t);
11004       return t;
11005
11006     case BASELINK:
11007       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11008
11009     case TEMPLATE_DECL:
11010       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11011         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11012                        args, complain, in_decl);
11013       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11014         return tsubst (t, args, complain, in_decl);
11015       else if (DECL_CLASS_SCOPE_P (t)
11016                && uses_template_parms (DECL_CONTEXT (t)))
11017         {
11018           /* Template template argument like the following example need
11019              special treatment:
11020
11021                template <template <class> class TT> struct C {};
11022                template <class T> struct D {
11023                  template <class U> struct E {};
11024                  C<E> c;                                // #1
11025                };
11026                D<int> d;                                // #2
11027
11028              We are processing the template argument `E' in #1 for
11029              the template instantiation #2.  Originally, `E' is a
11030              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11031              have to substitute this with one having context `D<int>'.  */
11032
11033           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11034           return lookup_field (context, DECL_NAME(t), 0, false);
11035         }
11036       else
11037         /* Ordinary template template argument.  */
11038         return t;
11039
11040     case CAST_EXPR:
11041     case REINTERPRET_CAST_EXPR:
11042     case CONST_CAST_EXPR:
11043     case STATIC_CAST_EXPR:
11044     case DYNAMIC_CAST_EXPR:
11045     case NOP_EXPR:
11046       return build1
11047         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11048          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11049
11050     case SIZEOF_EXPR:
11051       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11052         {
11053           /* We only want to compute the number of arguments.  */
11054           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11055                                                 complain, in_decl);
11056           int len = 0;
11057
11058           if (TREE_CODE (expanded) == TREE_VEC)
11059             len = TREE_VEC_LENGTH (expanded);
11060
11061           if (expanded == error_mark_node)
11062             return error_mark_node;
11063           else if (PACK_EXPANSION_P (expanded)
11064                    || (TREE_CODE (expanded) == TREE_VEC
11065                        && len > 0
11066                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11067             {
11068               if (TREE_CODE (expanded) == TREE_VEC)
11069                 expanded = TREE_VEC_ELT (expanded, len - 1);
11070
11071               if (TYPE_P (expanded))
11072                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11073                                                    complain & tf_error);
11074               else
11075                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11076                                                    complain & tf_error);
11077             }
11078           else
11079             return build_int_cst (size_type_node, len);
11080         }
11081       /* Fall through */
11082
11083     case INDIRECT_REF:
11084     case NEGATE_EXPR:
11085     case TRUTH_NOT_EXPR:
11086     case BIT_NOT_EXPR:
11087     case ADDR_EXPR:
11088     case UNARY_PLUS_EXPR:      /* Unary + */
11089     case ALIGNOF_EXPR:
11090     case ARROW_EXPR:
11091     case THROW_EXPR:
11092     case TYPEID_EXPR:
11093     case REALPART_EXPR:
11094     case IMAGPART_EXPR:
11095       return build1
11096         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11097          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11098
11099     case COMPONENT_REF:
11100       {
11101         tree object;
11102         tree name;
11103
11104         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11105         name = TREE_OPERAND (t, 1);
11106         if (TREE_CODE (name) == BIT_NOT_EXPR)
11107           {
11108             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11109                                 complain, in_decl);
11110             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11111           }
11112         else if (TREE_CODE (name) == SCOPE_REF
11113                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11114           {
11115             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11116                                      complain, in_decl);
11117             name = TREE_OPERAND (name, 1);
11118             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11119                                 complain, in_decl);
11120             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11121             name = build_qualified_name (/*type=*/NULL_TREE,
11122                                          base, name,
11123                                          /*template_p=*/false);
11124           }
11125         else if (TREE_CODE (name) == BASELINK)
11126           name = tsubst_baselink (name,
11127                                   non_reference (TREE_TYPE (object)),
11128                                   args, complain,
11129                                   in_decl);
11130         else
11131           name = tsubst_copy (name, args, complain, in_decl);
11132         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11133       }
11134
11135     case PLUS_EXPR:
11136     case MINUS_EXPR:
11137     case MULT_EXPR:
11138     case TRUNC_DIV_EXPR:
11139     case CEIL_DIV_EXPR:
11140     case FLOOR_DIV_EXPR:
11141     case ROUND_DIV_EXPR:
11142     case EXACT_DIV_EXPR:
11143     case BIT_AND_EXPR:
11144     case BIT_IOR_EXPR:
11145     case BIT_XOR_EXPR:
11146     case TRUNC_MOD_EXPR:
11147     case FLOOR_MOD_EXPR:
11148     case TRUTH_ANDIF_EXPR:
11149     case TRUTH_ORIF_EXPR:
11150     case TRUTH_AND_EXPR:
11151     case TRUTH_OR_EXPR:
11152     case RSHIFT_EXPR:
11153     case LSHIFT_EXPR:
11154     case RROTATE_EXPR:
11155     case LROTATE_EXPR:
11156     case EQ_EXPR:
11157     case NE_EXPR:
11158     case MAX_EXPR:
11159     case MIN_EXPR:
11160     case LE_EXPR:
11161     case GE_EXPR:
11162     case LT_EXPR:
11163     case GT_EXPR:
11164     case COMPOUND_EXPR:
11165     case DOTSTAR_EXPR:
11166     case MEMBER_REF:
11167     case PREDECREMENT_EXPR:
11168     case PREINCREMENT_EXPR:
11169     case POSTDECREMENT_EXPR:
11170     case POSTINCREMENT_EXPR:
11171       return build_nt
11172         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11173          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11174
11175     case SCOPE_REF:
11176       return build_qualified_name (/*type=*/NULL_TREE,
11177                                    tsubst_copy (TREE_OPERAND (t, 0),
11178                                                 args, complain, in_decl),
11179                                    tsubst_copy (TREE_OPERAND (t, 1),
11180                                                 args, complain, in_decl),
11181                                    QUALIFIED_NAME_IS_TEMPLATE (t));
11182
11183     case ARRAY_REF:
11184       return build_nt
11185         (ARRAY_REF,
11186          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11187          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11188          NULL_TREE, NULL_TREE);
11189
11190     case CALL_EXPR:
11191       {
11192         int n = VL_EXP_OPERAND_LENGTH (t);
11193         tree result = build_vl_exp (CALL_EXPR, n);
11194         int i;
11195         for (i = 0; i < n; i++)
11196           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11197                                              complain, in_decl);
11198         return result;
11199       }
11200
11201     case COND_EXPR:
11202     case MODOP_EXPR:
11203     case PSEUDO_DTOR_EXPR:
11204       {
11205         r = build_nt
11206           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11207            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11208            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11209         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11210         return r;
11211       }
11212
11213     case NEW_EXPR:
11214       {
11215         r = build_nt
11216         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11217          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11218          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11219         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11220         return r;
11221       }
11222
11223     case DELETE_EXPR:
11224       {
11225         r = build_nt
11226         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11227          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11228         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11229         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11230         return r;
11231       }
11232
11233     case TEMPLATE_ID_EXPR:
11234       {
11235         /* Substituted template arguments */
11236         tree fn = TREE_OPERAND (t, 0);
11237         tree targs = TREE_OPERAND (t, 1);
11238
11239         fn = tsubst_copy (fn, args, complain, in_decl);
11240         if (targs)
11241           targs = tsubst_template_args (targs, args, complain, in_decl);
11242
11243         return lookup_template_function (fn, targs);
11244       }
11245
11246     case TREE_LIST:
11247       {
11248         tree purpose, value, chain;
11249
11250         if (t == void_list_node)
11251           return t;
11252
11253         purpose = TREE_PURPOSE (t);
11254         if (purpose)
11255           purpose = tsubst_copy (purpose, args, complain, in_decl);
11256         value = TREE_VALUE (t);
11257         if (value)
11258           value = tsubst_copy (value, args, complain, in_decl);
11259         chain = TREE_CHAIN (t);
11260         if (chain && chain != void_type_node)
11261           chain = tsubst_copy (chain, args, complain, in_decl);
11262         if (purpose == TREE_PURPOSE (t)
11263             && value == TREE_VALUE (t)
11264             && chain == TREE_CHAIN (t))
11265           return t;
11266         return tree_cons (purpose, value, chain);
11267       }
11268
11269     case RECORD_TYPE:
11270     case UNION_TYPE:
11271     case ENUMERAL_TYPE:
11272     case INTEGER_TYPE:
11273     case TEMPLATE_TYPE_PARM:
11274     case TEMPLATE_TEMPLATE_PARM:
11275     case BOUND_TEMPLATE_TEMPLATE_PARM:
11276     case TEMPLATE_PARM_INDEX:
11277     case POINTER_TYPE:
11278     case REFERENCE_TYPE:
11279     case OFFSET_TYPE:
11280     case FUNCTION_TYPE:
11281     case METHOD_TYPE:
11282     case ARRAY_TYPE:
11283     case TYPENAME_TYPE:
11284     case UNBOUND_CLASS_TEMPLATE:
11285     case TYPEOF_TYPE:
11286     case DECLTYPE_TYPE:
11287     case TYPE_DECL:
11288       return tsubst (t, args, complain, in_decl);
11289
11290     case IDENTIFIER_NODE:
11291       if (IDENTIFIER_TYPENAME_P (t))
11292         {
11293           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11294           return mangle_conv_op_name_for_type (new_type);
11295         }
11296       else
11297         return t;
11298
11299     case CONSTRUCTOR:
11300       /* This is handled by tsubst_copy_and_build.  */
11301       gcc_unreachable ();
11302
11303     case VA_ARG_EXPR:
11304       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11305                                           in_decl),
11306                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11307
11308     case CLEANUP_POINT_EXPR:
11309       /* We shouldn't have built any of these during initial template
11310          generation.  Instead, they should be built during instantiation
11311          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11312       gcc_unreachable ();
11313
11314     case OFFSET_REF:
11315       mark_used (TREE_OPERAND (t, 1));
11316       return t;
11317
11318     case EXPR_PACK_EXPANSION:
11319       error ("invalid use of pack expansion expression");
11320       return error_mark_node;
11321
11322     case NONTYPE_ARGUMENT_PACK:
11323       error ("use %<...%> to expand argument pack");
11324       return error_mark_node;
11325
11326     default:
11327       return t;
11328     }
11329 }
11330
11331 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11332
11333 static tree
11334 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11335                     tree in_decl)
11336 {
11337   tree new_clauses = NULL, nc, oc;
11338
11339   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11340     {
11341       nc = copy_node (oc);
11342       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11343       new_clauses = nc;
11344
11345       switch (OMP_CLAUSE_CODE (nc))
11346         {
11347         case OMP_CLAUSE_LASTPRIVATE:
11348           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11349             {
11350               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11351               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11352                            in_decl, /*integral_constant_expression_p=*/false);
11353               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11354                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11355             }
11356           /* FALLTHRU */
11357         case OMP_CLAUSE_PRIVATE:
11358         case OMP_CLAUSE_SHARED:
11359         case OMP_CLAUSE_FIRSTPRIVATE:
11360         case OMP_CLAUSE_REDUCTION:
11361         case OMP_CLAUSE_COPYIN:
11362         case OMP_CLAUSE_COPYPRIVATE:
11363         case OMP_CLAUSE_IF:
11364         case OMP_CLAUSE_NUM_THREADS:
11365         case OMP_CLAUSE_SCHEDULE:
11366         case OMP_CLAUSE_COLLAPSE:
11367           OMP_CLAUSE_OPERAND (nc, 0)
11368             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11369                            in_decl, /*integral_constant_expression_p=*/false);
11370           break;
11371         case OMP_CLAUSE_NOWAIT:
11372         case OMP_CLAUSE_ORDERED:
11373         case OMP_CLAUSE_DEFAULT:
11374         case OMP_CLAUSE_UNTIED:
11375           break;
11376         default:
11377           gcc_unreachable ();
11378         }
11379     }
11380
11381   return finish_omp_clauses (nreverse (new_clauses));
11382 }
11383
11384 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11385
11386 static tree
11387 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11388                           tree in_decl)
11389 {
11390 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11391
11392   tree purpose, value, chain;
11393
11394   if (t == NULL)
11395     return t;
11396
11397   if (TREE_CODE (t) != TREE_LIST)
11398     return tsubst_copy_and_build (t, args, complain, in_decl,
11399                                   /*function_p=*/false,
11400                                   /*integral_constant_expression_p=*/false);
11401
11402   if (t == void_list_node)
11403     return t;
11404
11405   purpose = TREE_PURPOSE (t);
11406   if (purpose)
11407     purpose = RECUR (purpose);
11408   value = TREE_VALUE (t);
11409   if (value && TREE_CODE (value) != LABEL_DECL)
11410     value = RECUR (value);
11411   chain = TREE_CHAIN (t);
11412   if (chain && chain != void_type_node)
11413     chain = RECUR (chain);
11414   return tree_cons (purpose, value, chain);
11415 #undef RECUR
11416 }
11417
11418 /* Substitute one OMP_FOR iterator.  */
11419
11420 static void
11421 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11422                          tree condv, tree incrv, tree *clauses,
11423                          tree args, tsubst_flags_t complain, tree in_decl,
11424                          bool integral_constant_expression_p)
11425 {
11426 #define RECUR(NODE)                             \
11427   tsubst_expr ((NODE), args, complain, in_decl, \
11428                integral_constant_expression_p)
11429   tree decl, init, cond, incr, auto_node;
11430
11431   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11432   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11433   decl = RECUR (TREE_OPERAND (init, 0));
11434   init = TREE_OPERAND (init, 1);
11435   auto_node = type_uses_auto (TREE_TYPE (decl));
11436   if (auto_node && init)
11437     {
11438       tree init_expr = init;
11439       if (TREE_CODE (init_expr) == DECL_EXPR)
11440         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11441       init_expr = RECUR (init_expr);
11442       TREE_TYPE (decl)
11443         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11444     }
11445   gcc_assert (!type_dependent_expression_p (decl));
11446
11447   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11448     {
11449       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11450       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11451       if (TREE_CODE (incr) == MODIFY_EXPR)
11452         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11453                                     RECUR (TREE_OPERAND (incr, 1)),
11454                                     complain);
11455       else
11456         incr = RECUR (incr);
11457       TREE_VEC_ELT (declv, i) = decl;
11458       TREE_VEC_ELT (initv, i) = init;
11459       TREE_VEC_ELT (condv, i) = cond;
11460       TREE_VEC_ELT (incrv, i) = incr;
11461       return;
11462     }
11463
11464   if (init && TREE_CODE (init) != DECL_EXPR)
11465     {
11466       tree c;
11467       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11468         {
11469           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11470                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11471               && OMP_CLAUSE_DECL (c) == decl)
11472             break;
11473           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11474                    && OMP_CLAUSE_DECL (c) == decl)
11475             error ("iteration variable %qD should not be firstprivate", decl);
11476           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11477                    && OMP_CLAUSE_DECL (c) == decl)
11478             error ("iteration variable %qD should not be reduction", decl);
11479         }
11480       if (c == NULL)
11481         {
11482           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11483           OMP_CLAUSE_DECL (c) = decl;
11484           c = finish_omp_clauses (c);
11485           if (c)
11486             {
11487               OMP_CLAUSE_CHAIN (c) = *clauses;
11488               *clauses = c;
11489             }
11490         }
11491     }
11492   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11493   if (COMPARISON_CLASS_P (cond))
11494     cond = build2 (TREE_CODE (cond), boolean_type_node,
11495                    RECUR (TREE_OPERAND (cond, 0)),
11496                    RECUR (TREE_OPERAND (cond, 1)));
11497   else
11498     cond = RECUR (cond);
11499   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11500   switch (TREE_CODE (incr))
11501     {
11502     case PREINCREMENT_EXPR:
11503     case PREDECREMENT_EXPR:
11504     case POSTINCREMENT_EXPR:
11505     case POSTDECREMENT_EXPR:
11506       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11507                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11508       break;
11509     case MODIFY_EXPR:
11510       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11511           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11512         {
11513           tree rhs = TREE_OPERAND (incr, 1);
11514           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11515                          RECUR (TREE_OPERAND (incr, 0)),
11516                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11517                                  RECUR (TREE_OPERAND (rhs, 0)),
11518                                  RECUR (TREE_OPERAND (rhs, 1))));
11519         }
11520       else
11521         incr = RECUR (incr);
11522       break;
11523     case MODOP_EXPR:
11524       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11525           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11526         {
11527           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11528           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11529                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11530                                  TREE_TYPE (decl), lhs,
11531                                  RECUR (TREE_OPERAND (incr, 2))));
11532         }
11533       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11534                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11535                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11536         {
11537           tree rhs = TREE_OPERAND (incr, 2);
11538           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11539                          RECUR (TREE_OPERAND (incr, 0)),
11540                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11541                                  RECUR (TREE_OPERAND (rhs, 0)),
11542                                  RECUR (TREE_OPERAND (rhs, 1))));
11543         }
11544       else
11545         incr = RECUR (incr);
11546       break;
11547     default:
11548       incr = RECUR (incr);
11549       break;
11550     }
11551
11552   TREE_VEC_ELT (declv, i) = decl;
11553   TREE_VEC_ELT (initv, i) = init;
11554   TREE_VEC_ELT (condv, i) = cond;
11555   TREE_VEC_ELT (incrv, i) = incr;
11556 #undef RECUR
11557 }
11558
11559 /* Like tsubst_copy for expressions, etc. but also does semantic
11560    processing.  */
11561
11562 static tree
11563 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11564              bool integral_constant_expression_p)
11565 {
11566 #define RECUR(NODE)                             \
11567   tsubst_expr ((NODE), args, complain, in_decl, \
11568                integral_constant_expression_p)
11569
11570   tree stmt, tmp;
11571
11572   if (t == NULL_TREE || t == error_mark_node)
11573     return t;
11574
11575   if (EXPR_HAS_LOCATION (t))
11576     input_location = EXPR_LOCATION (t);
11577   if (STATEMENT_CODE_P (TREE_CODE (t)))
11578     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11579
11580   switch (TREE_CODE (t))
11581     {
11582     case STATEMENT_LIST:
11583       {
11584         tree_stmt_iterator i;
11585         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11586           RECUR (tsi_stmt (i));
11587         break;
11588       }
11589
11590     case CTOR_INITIALIZER:
11591       finish_mem_initializers (tsubst_initializer_list
11592                                (TREE_OPERAND (t, 0), args));
11593       break;
11594
11595     case RETURN_EXPR:
11596       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11597       break;
11598
11599     case EXPR_STMT:
11600       tmp = RECUR (EXPR_STMT_EXPR (t));
11601       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11602         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11603       else
11604         finish_expr_stmt (tmp);
11605       break;
11606
11607     case USING_STMT:
11608       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11609       break;
11610
11611     case DECL_EXPR:
11612       {
11613         tree decl;
11614         tree init;
11615
11616         decl = DECL_EXPR_DECL (t);
11617         if (TREE_CODE (decl) == LABEL_DECL)
11618           finish_label_decl (DECL_NAME (decl));
11619         else if (TREE_CODE (decl) == USING_DECL)
11620           {
11621             tree scope = USING_DECL_SCOPE (decl);
11622             tree name = DECL_NAME (decl);
11623             tree decl;
11624
11625             scope = RECUR (scope);
11626             decl = lookup_qualified_name (scope, name,
11627                                           /*is_type_p=*/false,
11628                                           /*complain=*/false);
11629             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11630               qualified_name_lookup_error (scope, name, decl, input_location);
11631             else
11632               do_local_using_decl (decl, scope, name);
11633           }
11634         else
11635           {
11636             init = DECL_INITIAL (decl);
11637             decl = tsubst (decl, args, complain, in_decl);
11638             if (decl != error_mark_node)
11639               {
11640                 /* By marking the declaration as instantiated, we avoid
11641                    trying to instantiate it.  Since instantiate_decl can't
11642                    handle local variables, and since we've already done
11643                    all that needs to be done, that's the right thing to
11644                    do.  */
11645                 if (TREE_CODE (decl) == VAR_DECL)
11646                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11647                 if (TREE_CODE (decl) == VAR_DECL
11648                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11649                   /* Anonymous aggregates are a special case.  */
11650                   finish_anon_union (decl);
11651                 else
11652                   {
11653                     maybe_push_decl (decl);
11654                     if (TREE_CODE (decl) == VAR_DECL
11655                         && DECL_PRETTY_FUNCTION_P (decl))
11656                       {
11657                         /* For __PRETTY_FUNCTION__ we have to adjust the
11658                            initializer.  */
11659                         const char *const name
11660                           = cxx_printable_name (current_function_decl, 2);
11661                         init = cp_fname_init (name, &TREE_TYPE (decl));
11662                       }
11663                     else
11664                       {
11665                         tree t = RECUR (init);
11666
11667                         if (init && !t)
11668                           /* If we had an initializer but it
11669                              instantiated to nothing,
11670                              value-initialize the object.  This will
11671                              only occur when the initializer was a
11672                              pack expansion where the parameter packs
11673                              used in that expansion were of length
11674                              zero.  */
11675                           init = build_value_init (TREE_TYPE (decl));
11676                         else
11677                           init = t;
11678                       }
11679
11680                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11681                   }
11682               }
11683           }
11684
11685         /* A DECL_EXPR can also be used as an expression, in the condition
11686            clause of an if/for/while construct.  */
11687         return decl;
11688       }
11689
11690     case FOR_STMT:
11691       stmt = begin_for_stmt ();
11692                           RECUR (FOR_INIT_STMT (t));
11693       finish_for_init_stmt (stmt);
11694       tmp = RECUR (FOR_COND (t));
11695       finish_for_cond (tmp, stmt);
11696       tmp = RECUR (FOR_EXPR (t));
11697       finish_for_expr (tmp, stmt);
11698       RECUR (FOR_BODY (t));
11699       finish_for_stmt (stmt);
11700       break;
11701
11702     case WHILE_STMT:
11703       stmt = begin_while_stmt ();
11704       tmp = RECUR (WHILE_COND (t));
11705       finish_while_stmt_cond (tmp, stmt);
11706       RECUR (WHILE_BODY (t));
11707       finish_while_stmt (stmt);
11708       break;
11709
11710     case DO_STMT:
11711       stmt = begin_do_stmt ();
11712       RECUR (DO_BODY (t));
11713       finish_do_body (stmt);
11714       tmp = RECUR (DO_COND (t));
11715       finish_do_stmt (tmp, stmt);
11716       break;
11717
11718     case IF_STMT:
11719       stmt = begin_if_stmt ();
11720       tmp = RECUR (IF_COND (t));
11721       finish_if_stmt_cond (tmp, stmt);
11722       RECUR (THEN_CLAUSE (t));
11723       finish_then_clause (stmt);
11724
11725       if (ELSE_CLAUSE (t))
11726         {
11727           begin_else_clause (stmt);
11728           RECUR (ELSE_CLAUSE (t));
11729           finish_else_clause (stmt);
11730         }
11731
11732       finish_if_stmt (stmt);
11733       break;
11734
11735     case BIND_EXPR:
11736       if (BIND_EXPR_BODY_BLOCK (t))
11737         stmt = begin_function_body ();
11738       else
11739         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11740                                     ? BCS_TRY_BLOCK : 0);
11741
11742       RECUR (BIND_EXPR_BODY (t));
11743
11744       if (BIND_EXPR_BODY_BLOCK (t))
11745         finish_function_body (stmt);
11746       else
11747         finish_compound_stmt (stmt);
11748       break;
11749
11750     case BREAK_STMT:
11751       finish_break_stmt ();
11752       break;
11753
11754     case CONTINUE_STMT:
11755       finish_continue_stmt ();
11756       break;
11757
11758     case SWITCH_STMT:
11759       stmt = begin_switch_stmt ();
11760       tmp = RECUR (SWITCH_STMT_COND (t));
11761       finish_switch_cond (tmp, stmt);
11762       RECUR (SWITCH_STMT_BODY (t));
11763       finish_switch_stmt (stmt);
11764       break;
11765
11766     case CASE_LABEL_EXPR:
11767       finish_case_label (EXPR_LOCATION (t),
11768                          RECUR (CASE_LOW (t)),
11769                          RECUR (CASE_HIGH (t)));
11770       break;
11771
11772     case LABEL_EXPR:
11773       {
11774         tree decl = LABEL_EXPR_LABEL (t);
11775         tree label;
11776
11777         label = finish_label_stmt (DECL_NAME (decl));
11778         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11779           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11780       }
11781       break;
11782
11783     case GOTO_EXPR:
11784       tmp = GOTO_DESTINATION (t);
11785       if (TREE_CODE (tmp) != LABEL_DECL)
11786         /* Computed goto's must be tsubst'd into.  On the other hand,
11787            non-computed gotos must not be; the identifier in question
11788            will have no binding.  */
11789         tmp = RECUR (tmp);
11790       else
11791         tmp = DECL_NAME (tmp);
11792       finish_goto_stmt (tmp);
11793       break;
11794
11795     case ASM_EXPR:
11796       tmp = finish_asm_stmt
11797         (ASM_VOLATILE_P (t),
11798          RECUR (ASM_STRING (t)),
11799          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11800          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11801          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11802          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11803       {
11804         tree asm_expr = tmp;
11805         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11806           asm_expr = TREE_OPERAND (asm_expr, 0);
11807         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11808       }
11809       break;
11810
11811     case TRY_BLOCK:
11812       if (CLEANUP_P (t))
11813         {
11814           stmt = begin_try_block ();
11815           RECUR (TRY_STMTS (t));
11816           finish_cleanup_try_block (stmt);
11817           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11818         }
11819       else
11820         {
11821           tree compound_stmt = NULL_TREE;
11822
11823           if (FN_TRY_BLOCK_P (t))
11824             stmt = begin_function_try_block (&compound_stmt);
11825           else
11826             stmt = begin_try_block ();
11827
11828           RECUR (TRY_STMTS (t));
11829
11830           if (FN_TRY_BLOCK_P (t))
11831             finish_function_try_block (stmt);
11832           else
11833             finish_try_block (stmt);
11834
11835           RECUR (TRY_HANDLERS (t));
11836           if (FN_TRY_BLOCK_P (t))
11837             finish_function_handler_sequence (stmt, compound_stmt);
11838           else
11839             finish_handler_sequence (stmt);
11840         }
11841       break;
11842
11843     case HANDLER:
11844       {
11845         tree decl = HANDLER_PARMS (t);
11846
11847         if (decl)
11848           {
11849             decl = tsubst (decl, args, complain, in_decl);
11850             /* Prevent instantiate_decl from trying to instantiate
11851                this variable.  We've already done all that needs to be
11852                done.  */
11853             if (decl != error_mark_node)
11854               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11855           }
11856         stmt = begin_handler ();
11857         finish_handler_parms (decl, stmt);
11858         RECUR (HANDLER_BODY (t));
11859         finish_handler (stmt);
11860       }
11861       break;
11862
11863     case TAG_DEFN:
11864       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11865       break;
11866
11867     case STATIC_ASSERT:
11868       {
11869         tree condition = 
11870           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11871                        args,
11872                        complain, in_decl,
11873                        /*integral_constant_expression_p=*/true);
11874         finish_static_assert (condition,
11875                               STATIC_ASSERT_MESSAGE (t),
11876                               STATIC_ASSERT_SOURCE_LOCATION (t),
11877                               /*member_p=*/false);
11878       }
11879       break;
11880
11881     case OMP_PARALLEL:
11882       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11883                                 args, complain, in_decl);
11884       stmt = begin_omp_parallel ();
11885       RECUR (OMP_PARALLEL_BODY (t));
11886       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11887         = OMP_PARALLEL_COMBINED (t);
11888       break;
11889
11890     case OMP_TASK:
11891       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11892                                 args, complain, in_decl);
11893       stmt = begin_omp_task ();
11894       RECUR (OMP_TASK_BODY (t));
11895       finish_omp_task (tmp, stmt);
11896       break;
11897
11898     case OMP_FOR:
11899       {
11900         tree clauses, body, pre_body;
11901         tree declv, initv, condv, incrv;
11902         int i;
11903
11904         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11905                                       args, complain, in_decl);
11906         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11907         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11908         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11909         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11910
11911         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11912           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11913                                    &clauses, args, complain, in_decl,
11914                                    integral_constant_expression_p);
11915
11916         stmt = begin_omp_structured_block ();
11917
11918         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11919           if (TREE_VEC_ELT (initv, i) == NULL
11920               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11921             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11922           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11923             {
11924               tree init = RECUR (TREE_VEC_ELT (initv, i));
11925               gcc_assert (init == TREE_VEC_ELT (declv, i));
11926               TREE_VEC_ELT (initv, i) = NULL_TREE;
11927             }
11928           else
11929             {
11930               tree decl_expr = TREE_VEC_ELT (initv, i);
11931               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11932               gcc_assert (init != NULL);
11933               TREE_VEC_ELT (initv, i) = RECUR (init);
11934               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11935               RECUR (decl_expr);
11936               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11937             }
11938
11939         pre_body = push_stmt_list ();
11940         RECUR (OMP_FOR_PRE_BODY (t));
11941         pre_body = pop_stmt_list (pre_body);
11942
11943         body = push_stmt_list ();
11944         RECUR (OMP_FOR_BODY (t));
11945         body = pop_stmt_list (body);
11946
11947         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11948                             body, pre_body, clauses);
11949
11950         add_stmt (finish_omp_structured_block (stmt));
11951       }
11952       break;
11953
11954     case OMP_SECTIONS:
11955     case OMP_SINGLE:
11956       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11957       stmt = push_stmt_list ();
11958       RECUR (OMP_BODY (t));
11959       stmt = pop_stmt_list (stmt);
11960
11961       t = copy_node (t);
11962       OMP_BODY (t) = stmt;
11963       OMP_CLAUSES (t) = tmp;
11964       add_stmt (t);
11965       break;
11966
11967     case OMP_SECTION:
11968     case OMP_CRITICAL:
11969     case OMP_MASTER:
11970     case OMP_ORDERED:
11971       stmt = push_stmt_list ();
11972       RECUR (OMP_BODY (t));
11973       stmt = pop_stmt_list (stmt);
11974
11975       t = copy_node (t);
11976       OMP_BODY (t) = stmt;
11977       add_stmt (t);
11978       break;
11979
11980     case OMP_ATOMIC:
11981       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11982       {
11983         tree op1 = TREE_OPERAND (t, 1);
11984         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11985         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11986         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11987       }
11988       break;
11989
11990     case EXPR_PACK_EXPANSION:
11991       error ("invalid use of pack expansion expression");
11992       return error_mark_node;
11993
11994     case NONTYPE_ARGUMENT_PACK:
11995       error ("use %<...%> to expand argument pack");
11996       return error_mark_node;
11997
11998     default:
11999       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
12000
12001       return tsubst_copy_and_build (t, args, complain, in_decl,
12002                                     /*function_p=*/false,
12003                                     integral_constant_expression_p);
12004     }
12005
12006   return NULL_TREE;
12007 #undef RECUR
12008 }
12009
12010 /* T is a postfix-expression that is not being used in a function
12011    call.  Return the substituted version of T.  */
12012
12013 static tree
12014 tsubst_non_call_postfix_expression (tree t, tree args,
12015                                     tsubst_flags_t complain,
12016                                     tree in_decl)
12017 {
12018   if (TREE_CODE (t) == SCOPE_REF)
12019     t = tsubst_qualified_id (t, args, complain, in_decl,
12020                              /*done=*/false, /*address_p=*/false);
12021   else
12022     t = tsubst_copy_and_build (t, args, complain, in_decl,
12023                                /*function_p=*/false,
12024                                /*integral_constant_expression_p=*/false);
12025
12026   return t;
12027 }
12028
12029 /* Like tsubst but deals with expressions and performs semantic
12030    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12031
12032 tree
12033 tsubst_copy_and_build (tree t,
12034                        tree args,
12035                        tsubst_flags_t complain,
12036                        tree in_decl,
12037                        bool function_p,
12038                        bool integral_constant_expression_p)
12039 {
12040 #define RECUR(NODE)                                             \
12041   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
12042                          /*function_p=*/false,                  \
12043                          integral_constant_expression_p)
12044
12045   tree op1;
12046
12047   if (t == NULL_TREE || t == error_mark_node)
12048     return t;
12049
12050   switch (TREE_CODE (t))
12051     {
12052     case USING_DECL:
12053       t = DECL_NAME (t);
12054       /* Fall through.  */
12055     case IDENTIFIER_NODE:
12056       {
12057         tree decl;
12058         cp_id_kind idk;
12059         bool non_integral_constant_expression_p;
12060         const char *error_msg;
12061
12062         if (IDENTIFIER_TYPENAME_P (t))
12063           {
12064             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12065             t = mangle_conv_op_name_for_type (new_type);
12066           }
12067
12068         /* Look up the name.  */
12069         decl = lookup_name (t);
12070
12071         /* By convention, expressions use ERROR_MARK_NODE to indicate
12072            failure, not NULL_TREE.  */
12073         if (decl == NULL_TREE)
12074           decl = error_mark_node;
12075
12076         decl = finish_id_expression (t, decl, NULL_TREE,
12077                                      &idk,
12078                                      integral_constant_expression_p,
12079                                      /*allow_non_integral_constant_expression_p=*/false,
12080                                      &non_integral_constant_expression_p,
12081                                      /*template_p=*/false,
12082                                      /*done=*/true,
12083                                      /*address_p=*/false,
12084                                      /*template_arg_p=*/false,
12085                                      &error_msg,
12086                                      input_location);
12087         if (error_msg)
12088           error (error_msg);
12089         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
12090           decl = unqualified_name_lookup_error (decl);
12091         return decl;
12092       }
12093
12094     case TEMPLATE_ID_EXPR:
12095       {
12096         tree object;
12097         tree templ = RECUR (TREE_OPERAND (t, 0));
12098         tree targs = TREE_OPERAND (t, 1);
12099
12100         if (targs)
12101           targs = tsubst_template_args (targs, args, complain, in_decl);
12102
12103         if (TREE_CODE (templ) == COMPONENT_REF)
12104           {
12105             object = TREE_OPERAND (templ, 0);
12106             templ = TREE_OPERAND (templ, 1);
12107           }
12108         else
12109           object = NULL_TREE;
12110         templ = lookup_template_function (templ, targs);
12111
12112         if (object)
12113           return build3 (COMPONENT_REF, TREE_TYPE (templ),
12114                          object, templ, NULL_TREE);
12115         else
12116           return baselink_for_fns (templ);
12117       }
12118
12119     case INDIRECT_REF:
12120       {
12121         tree r = RECUR (TREE_OPERAND (t, 0));
12122
12123         if (REFERENCE_REF_P (t))
12124           {
12125             /* A type conversion to reference type will be enclosed in
12126                such an indirect ref, but the substitution of the cast
12127                will have also added such an indirect ref.  */
12128             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
12129               r = convert_from_reference (r);
12130           }
12131         else
12132           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
12133         return r;
12134       }
12135
12136     case NOP_EXPR:
12137       return build_nop
12138         (tsubst (TREE_TYPE (t), args, complain, in_decl),
12139          RECUR (TREE_OPERAND (t, 0)));
12140
12141     case CAST_EXPR:
12142     case REINTERPRET_CAST_EXPR:
12143     case CONST_CAST_EXPR:
12144     case DYNAMIC_CAST_EXPR:
12145     case STATIC_CAST_EXPR:
12146       {
12147         tree type;
12148         tree op;
12149
12150         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12151         if (integral_constant_expression_p
12152             && !cast_valid_in_integral_constant_expression_p (type))
12153           {
12154             if (complain & tf_error)
12155               error ("a cast to a type other than an integral or "
12156                      "enumeration type cannot appear in a constant-expression");
12157             return error_mark_node; 
12158           }
12159
12160         op = RECUR (TREE_OPERAND (t, 0));
12161
12162         switch (TREE_CODE (t))
12163           {
12164           case CAST_EXPR:
12165             return build_functional_cast (type, op, complain);
12166           case REINTERPRET_CAST_EXPR:
12167             return build_reinterpret_cast (type, op, complain);
12168           case CONST_CAST_EXPR:
12169             return build_const_cast (type, op, complain);
12170           case DYNAMIC_CAST_EXPR:
12171             return build_dynamic_cast (type, op, complain);
12172           case STATIC_CAST_EXPR:
12173             return build_static_cast (type, op, complain);
12174           default:
12175             gcc_unreachable ();
12176           }
12177       }
12178
12179     case POSTDECREMENT_EXPR:
12180     case POSTINCREMENT_EXPR:
12181       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12182                                                 args, complain, in_decl);
12183       return build_x_unary_op (TREE_CODE (t), op1, complain);
12184
12185     case PREDECREMENT_EXPR:
12186     case PREINCREMENT_EXPR:
12187     case NEGATE_EXPR:
12188     case BIT_NOT_EXPR:
12189     case ABS_EXPR:
12190     case TRUTH_NOT_EXPR:
12191     case UNARY_PLUS_EXPR:  /* Unary + */
12192     case REALPART_EXPR:
12193     case IMAGPART_EXPR:
12194       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12195                                complain);
12196
12197     case ADDR_EXPR:
12198       op1 = TREE_OPERAND (t, 0);
12199       if (TREE_CODE (op1) == SCOPE_REF)
12200         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12201                                    /*done=*/true, /*address_p=*/true);
12202       else
12203         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12204                                                   in_decl);
12205       if (TREE_CODE (op1) == LABEL_DECL)
12206         return finish_label_address_expr (DECL_NAME (op1),
12207                                           EXPR_LOCATION (op1));
12208       return build_x_unary_op (ADDR_EXPR, op1, complain);
12209
12210     case PLUS_EXPR:
12211     case MINUS_EXPR:
12212     case MULT_EXPR:
12213     case TRUNC_DIV_EXPR:
12214     case CEIL_DIV_EXPR:
12215     case FLOOR_DIV_EXPR:
12216     case ROUND_DIV_EXPR:
12217     case EXACT_DIV_EXPR:
12218     case BIT_AND_EXPR:
12219     case BIT_IOR_EXPR:
12220     case BIT_XOR_EXPR:
12221     case TRUNC_MOD_EXPR:
12222     case FLOOR_MOD_EXPR:
12223     case TRUTH_ANDIF_EXPR:
12224     case TRUTH_ORIF_EXPR:
12225     case TRUTH_AND_EXPR:
12226     case TRUTH_OR_EXPR:
12227     case RSHIFT_EXPR:
12228     case LSHIFT_EXPR:
12229     case RROTATE_EXPR:
12230     case LROTATE_EXPR:
12231     case EQ_EXPR:
12232     case NE_EXPR:
12233     case MAX_EXPR:
12234     case MIN_EXPR:
12235     case LE_EXPR:
12236     case GE_EXPR:
12237     case LT_EXPR:
12238     case GT_EXPR:
12239     case MEMBER_REF:
12240     case DOTSTAR_EXPR:
12241       return build_x_binary_op
12242         (TREE_CODE (t),
12243          RECUR (TREE_OPERAND (t, 0)),
12244          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12245           ? ERROR_MARK
12246           : TREE_CODE (TREE_OPERAND (t, 0))),
12247          RECUR (TREE_OPERAND (t, 1)),
12248          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12249           ? ERROR_MARK
12250           : TREE_CODE (TREE_OPERAND (t, 1))),
12251          /*overloaded_p=*/NULL,
12252          complain);
12253
12254     case SCOPE_REF:
12255       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12256                                   /*address_p=*/false);
12257     case ARRAY_REF:
12258       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12259                                                 args, complain, in_decl);
12260       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12261
12262     case SIZEOF_EXPR:
12263       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12264         return tsubst_copy (t, args, complain, in_decl);
12265       /* Fall through */
12266       
12267     case ALIGNOF_EXPR:
12268       op1 = TREE_OPERAND (t, 0);
12269       if (!args)
12270         {
12271           /* When there are no ARGS, we are trying to evaluate a
12272              non-dependent expression from the parser.  Trying to do
12273              the substitutions may not work.  */
12274           if (!TYPE_P (op1))
12275             op1 = TREE_TYPE (op1);
12276         }
12277       else
12278         {
12279           ++cp_unevaluated_operand;
12280           ++c_inhibit_evaluation_warnings;
12281           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12282                                        /*function_p=*/false,
12283                                        /*integral_constant_expression_p=*/false);
12284           --cp_unevaluated_operand;
12285           --c_inhibit_evaluation_warnings;
12286         }
12287       if (TYPE_P (op1))
12288         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
12289                                            complain & tf_error);
12290       else
12291         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
12292                                            complain & tf_error);
12293
12294     case NOEXCEPT_EXPR:
12295       op1 = TREE_OPERAND (t, 0);
12296       ++cp_unevaluated_operand;
12297       ++c_inhibit_evaluation_warnings;
12298       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12299                                    /*function_p=*/false,
12300                                    /*integral_constant_expression_p=*/false);
12301       --cp_unevaluated_operand;
12302       --c_inhibit_evaluation_warnings;
12303       return finish_noexcept_expr (op1, complain);
12304
12305     case MODOP_EXPR:
12306       {
12307         tree r = build_x_modify_expr
12308           (RECUR (TREE_OPERAND (t, 0)),
12309            TREE_CODE (TREE_OPERAND (t, 1)),
12310            RECUR (TREE_OPERAND (t, 2)),
12311            complain);
12312         /* TREE_NO_WARNING must be set if either the expression was
12313            parenthesized or it uses an operator such as >>= rather
12314            than plain assignment.  In the former case, it was already
12315            set and must be copied.  In the latter case,
12316            build_x_modify_expr sets it and it must not be reset
12317            here.  */
12318         if (TREE_NO_WARNING (t))
12319           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12320         return r;
12321       }
12322
12323     case ARROW_EXPR:
12324       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12325                                                 args, complain, in_decl);
12326       /* Remember that there was a reference to this entity.  */
12327       if (DECL_P (op1))
12328         mark_used (op1);
12329       return build_x_arrow (op1);
12330
12331     case NEW_EXPR:
12332       {
12333         tree placement = RECUR (TREE_OPERAND (t, 0));
12334         tree init = RECUR (TREE_OPERAND (t, 3));
12335         VEC(tree,gc) *placement_vec;
12336         VEC(tree,gc) *init_vec;
12337         tree ret;
12338
12339         if (placement == NULL_TREE)
12340           placement_vec = NULL;
12341         else
12342           {
12343             placement_vec = make_tree_vector ();
12344             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12345               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12346           }
12347
12348         /* If there was an initializer in the original tree, but it
12349            instantiated to an empty list, then we should pass a
12350            non-NULL empty vector to tell build_new that it was an
12351            empty initializer() rather than no initializer.  This can
12352            only happen when the initializer is a pack expansion whose
12353            parameter packs are of length zero.  */
12354         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12355           init_vec = NULL;
12356         else
12357           {
12358             init_vec = make_tree_vector ();
12359             if (init == void_zero_node)
12360               gcc_assert (init_vec != NULL);
12361             else
12362               {
12363                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12364                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12365               }
12366           }
12367
12368         ret = build_new (&placement_vec,
12369                          RECUR (TREE_OPERAND (t, 1)),
12370                          RECUR (TREE_OPERAND (t, 2)),
12371                          &init_vec,
12372                          NEW_EXPR_USE_GLOBAL (t),
12373                          complain);
12374
12375         if (placement_vec != NULL)
12376           release_tree_vector (placement_vec);
12377         if (init_vec != NULL)
12378           release_tree_vector (init_vec);
12379
12380         return ret;
12381       }
12382
12383     case DELETE_EXPR:
12384      return delete_sanity
12385        (RECUR (TREE_OPERAND (t, 0)),
12386         RECUR (TREE_OPERAND (t, 1)),
12387         DELETE_EXPR_USE_VEC (t),
12388         DELETE_EXPR_USE_GLOBAL (t));
12389
12390     case COMPOUND_EXPR:
12391       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12392                                     RECUR (TREE_OPERAND (t, 1)),
12393                                     complain);
12394
12395     case CALL_EXPR:
12396       {
12397         tree function;
12398         VEC(tree,gc) *call_args;
12399         unsigned int nargs, i;
12400         bool qualified_p;
12401         bool koenig_p;
12402         tree ret;
12403
12404         function = CALL_EXPR_FN (t);
12405         /* When we parsed the expression,  we determined whether or
12406            not Koenig lookup should be performed.  */
12407         koenig_p = KOENIG_LOOKUP_P (t);
12408         if (TREE_CODE (function) == SCOPE_REF)
12409           {
12410             qualified_p = true;
12411             function = tsubst_qualified_id (function, args, complain, in_decl,
12412                                             /*done=*/false,
12413                                             /*address_p=*/false);
12414           }
12415         else
12416           {
12417             if (TREE_CODE (function) == COMPONENT_REF)
12418               {
12419                 tree op = TREE_OPERAND (function, 1);
12420
12421                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12422                                || (BASELINK_P (op)
12423                                    && BASELINK_QUALIFIED_P (op)));
12424               }
12425             else
12426               qualified_p = false;
12427
12428             function = tsubst_copy_and_build (function, args, complain,
12429                                               in_decl,
12430                                               !qualified_p,
12431                                               integral_constant_expression_p);
12432
12433             if (BASELINK_P (function))
12434               qualified_p = true;
12435           }
12436
12437         nargs = call_expr_nargs (t);
12438         call_args = make_tree_vector ();
12439         for (i = 0; i < nargs; ++i)
12440           {
12441             tree arg = CALL_EXPR_ARG (t, i);
12442
12443             if (!PACK_EXPANSION_P (arg))
12444               VEC_safe_push (tree, gc, call_args,
12445                              RECUR (CALL_EXPR_ARG (t, i)));
12446             else
12447               {
12448                 /* Expand the pack expansion and push each entry onto
12449                    CALL_ARGS.  */
12450                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12451                 if (TREE_CODE (arg) == TREE_VEC)
12452                   {
12453                     unsigned int len, j;
12454
12455                     len = TREE_VEC_LENGTH (arg);
12456                     for (j = 0; j < len; ++j)
12457                       {
12458                         tree value = TREE_VEC_ELT (arg, j);
12459                         if (value != NULL_TREE)
12460                           value = convert_from_reference (value);
12461                         VEC_safe_push (tree, gc, call_args, value);
12462                       }
12463                   }
12464                 else
12465                   {
12466                     /* A partial substitution.  Add one entry.  */
12467                     VEC_safe_push (tree, gc, call_args, arg);
12468                   }
12469               }
12470           }
12471
12472         /* We do not perform argument-dependent lookup if normal
12473            lookup finds a non-function, in accordance with the
12474            expected resolution of DR 218.  */
12475         if (koenig_p
12476             && ((is_overloaded_fn (function)
12477                  /* If lookup found a member function, the Koenig lookup is
12478                     not appropriate, even if an unqualified-name was used
12479                     to denote the function.  */
12480                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12481                 || TREE_CODE (function) == IDENTIFIER_NODE)
12482             /* Only do this when substitution turns a dependent call
12483                into a non-dependent call.  */
12484             && type_dependent_expression_p_push (t)
12485             && !any_type_dependent_arguments_p (call_args))
12486           function = perform_koenig_lookup (function, call_args);
12487
12488         if (TREE_CODE (function) == IDENTIFIER_NODE)
12489           {
12490             unqualified_name_lookup_error (function);
12491             release_tree_vector (call_args);
12492             return error_mark_node;
12493           }
12494
12495         /* Remember that there was a reference to this entity.  */
12496         if (DECL_P (function))
12497           mark_used (function);
12498
12499         if (TREE_CODE (function) == OFFSET_REF)
12500           ret = build_offset_ref_call_from_tree (function, &call_args);
12501         else if (TREE_CODE (function) == COMPONENT_REF)
12502           {
12503             if (!BASELINK_P (TREE_OPERAND (function, 1)))
12504               ret = finish_call_expr (function, &call_args,
12505                                        /*disallow_virtual=*/false,
12506                                        /*koenig_p=*/false,
12507                                        complain);
12508             else
12509               ret = (build_new_method_call
12510                       (TREE_OPERAND (function, 0),
12511                        TREE_OPERAND (function, 1),
12512                        &call_args, NULL_TREE,
12513                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12514                        /*fn_p=*/NULL,
12515                        complain));
12516           }
12517         else
12518           ret = finish_call_expr (function, &call_args,
12519                                   /*disallow_virtual=*/qualified_p,
12520                                   koenig_p,
12521                                   complain);
12522
12523         release_tree_vector (call_args);
12524
12525         return ret;
12526       }
12527
12528     case COND_EXPR:
12529       return build_x_conditional_expr
12530         (RECUR (TREE_OPERAND (t, 0)),
12531          RECUR (TREE_OPERAND (t, 1)),
12532          RECUR (TREE_OPERAND (t, 2)),
12533          complain);
12534
12535     case PSEUDO_DTOR_EXPR:
12536       return finish_pseudo_destructor_expr
12537         (RECUR (TREE_OPERAND (t, 0)),
12538          RECUR (TREE_OPERAND (t, 1)),
12539          RECUR (TREE_OPERAND (t, 2)));
12540
12541     case TREE_LIST:
12542       {
12543         tree purpose, value, chain;
12544
12545         if (t == void_list_node)
12546           return t;
12547
12548         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12549             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12550           {
12551             /* We have pack expansions, so expand those and
12552                create a new list out of it.  */
12553             tree purposevec = NULL_TREE;
12554             tree valuevec = NULL_TREE;
12555             tree chain;
12556             int i, len = -1;
12557
12558             /* Expand the argument expressions.  */
12559             if (TREE_PURPOSE (t))
12560               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12561                                                  complain, in_decl);
12562             if (TREE_VALUE (t))
12563               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12564                                                complain, in_decl);
12565
12566             /* Build the rest of the list.  */
12567             chain = TREE_CHAIN (t);
12568             if (chain && chain != void_type_node)
12569               chain = RECUR (chain);
12570
12571             /* Determine the number of arguments.  */
12572             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12573               {
12574                 len = TREE_VEC_LENGTH (purposevec);
12575                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12576               }
12577             else if (TREE_CODE (valuevec) == TREE_VEC)
12578               len = TREE_VEC_LENGTH (valuevec);
12579             else
12580               {
12581                 /* Since we only performed a partial substitution into
12582                    the argument pack, we only return a single list
12583                    node.  */
12584                 if (purposevec == TREE_PURPOSE (t)
12585                     && valuevec == TREE_VALUE (t)
12586                     && chain == TREE_CHAIN (t))
12587                   return t;
12588
12589                 return tree_cons (purposevec, valuevec, chain);
12590               }
12591             
12592             /* Convert the argument vectors into a TREE_LIST */
12593             i = len;
12594             while (i > 0)
12595               {
12596                 /* Grab the Ith values.  */
12597                 i--;
12598                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12599                                      : NULL_TREE;
12600                 value 
12601                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12602                              : NULL_TREE;
12603
12604                 /* Build the list (backwards).  */
12605                 chain = tree_cons (purpose, value, chain);
12606               }
12607
12608             return chain;
12609           }
12610
12611         purpose = TREE_PURPOSE (t);
12612         if (purpose)
12613           purpose = RECUR (purpose);
12614         value = TREE_VALUE (t);
12615         if (value)
12616           value = RECUR (value);
12617         chain = TREE_CHAIN (t);
12618         if (chain && chain != void_type_node)
12619           chain = RECUR (chain);
12620         if (purpose == TREE_PURPOSE (t)
12621             && value == TREE_VALUE (t)
12622             && chain == TREE_CHAIN (t))
12623           return t;
12624         return tree_cons (purpose, value, chain);
12625       }
12626
12627     case COMPONENT_REF:
12628       {
12629         tree object;
12630         tree object_type;
12631         tree member;
12632
12633         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12634                                                      args, complain, in_decl);
12635         /* Remember that there was a reference to this entity.  */
12636         if (DECL_P (object))
12637           mark_used (object);
12638         object_type = TREE_TYPE (object);
12639
12640         member = TREE_OPERAND (t, 1);
12641         if (BASELINK_P (member))
12642           member = tsubst_baselink (member,
12643                                     non_reference (TREE_TYPE (object)),
12644                                     args, complain, in_decl);
12645         else
12646           member = tsubst_copy (member, args, complain, in_decl);
12647         if (member == error_mark_node)
12648           return error_mark_node;
12649
12650         if (object_type && !CLASS_TYPE_P (object_type))
12651           {
12652             if (SCALAR_TYPE_P (object_type))
12653               {
12654                 tree s = NULL_TREE;
12655                 tree dtor = member;
12656
12657                 if (TREE_CODE (dtor) == SCOPE_REF)
12658                   {
12659                     s = TREE_OPERAND (dtor, 0);
12660                     dtor = TREE_OPERAND (dtor, 1);
12661                   }
12662                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12663                   {
12664                     dtor = TREE_OPERAND (dtor, 0);
12665                     if (TYPE_P (dtor))
12666                       return finish_pseudo_destructor_expr (object, s, dtor);
12667                   }
12668               }
12669           }
12670         else if (TREE_CODE (member) == SCOPE_REF
12671                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12672           {
12673             tree tmpl;
12674             tree args;
12675
12676             /* Lookup the template functions now that we know what the
12677                scope is.  */
12678             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12679             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12680             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12681                                             /*is_type_p=*/false,
12682                                             /*complain=*/false);
12683             if (BASELINK_P (member))
12684               {
12685                 BASELINK_FUNCTIONS (member)
12686                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12687                               args);
12688                 member = (adjust_result_of_qualified_name_lookup
12689                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12690                            object_type));
12691               }
12692             else
12693               {
12694                 qualified_name_lookup_error (object_type, tmpl, member,
12695                                              input_location);
12696                 return error_mark_node;
12697               }
12698           }
12699         else if (TREE_CODE (member) == SCOPE_REF
12700                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12701                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12702           {
12703             if (complain & tf_error)
12704               {
12705                 if (TYPE_P (TREE_OPERAND (member, 0)))
12706                   error ("%qT is not a class or namespace",
12707                          TREE_OPERAND (member, 0));
12708                 else
12709                   error ("%qD is not a class or namespace",
12710                          TREE_OPERAND (member, 0));
12711               }
12712             return error_mark_node;
12713           }
12714         else if (TREE_CODE (member) == FIELD_DECL)
12715           return finish_non_static_data_member (member, object, NULL_TREE);
12716
12717         return finish_class_member_access_expr (object, member,
12718                                                 /*template_p=*/false,
12719                                                 complain);
12720       }
12721
12722     case THROW_EXPR:
12723       return build_throw
12724         (RECUR (TREE_OPERAND (t, 0)));
12725
12726     case CONSTRUCTOR:
12727       {
12728         VEC(constructor_elt,gc) *n;
12729         constructor_elt *ce;
12730         unsigned HOST_WIDE_INT idx;
12731         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12732         bool process_index_p;
12733         int newlen;
12734         bool need_copy_p = false;
12735         tree r;
12736
12737         if (type == error_mark_node)
12738           return error_mark_node;
12739
12740         /* digest_init will do the wrong thing if we let it.  */
12741         if (type && TYPE_PTRMEMFUNC_P (type))
12742           return t;
12743
12744         /* We do not want to process the index of aggregate
12745            initializers as they are identifier nodes which will be
12746            looked up by digest_init.  */
12747         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12748
12749         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12750         newlen = VEC_length (constructor_elt, n);
12751         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12752           {
12753             if (ce->index && process_index_p)
12754               ce->index = RECUR (ce->index);
12755
12756             if (PACK_EXPANSION_P (ce->value))
12757               {
12758                 /* Substitute into the pack expansion.  */
12759                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12760                                                   in_decl);
12761
12762                 if (ce->value == error_mark_node)
12763                   ;
12764                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12765                   /* Just move the argument into place.  */
12766                   ce->value = TREE_VEC_ELT (ce->value, 0);
12767                 else
12768                   {
12769                     /* Update the length of the final CONSTRUCTOR
12770                        arguments vector, and note that we will need to
12771                        copy.*/
12772                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12773                     need_copy_p = true;
12774                   }
12775               }
12776             else
12777               ce->value = RECUR (ce->value);
12778           }
12779
12780         if (need_copy_p)
12781           {
12782             VEC(constructor_elt,gc) *old_n = n;
12783
12784             n = VEC_alloc (constructor_elt, gc, newlen);
12785             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
12786                  idx++)
12787               {
12788                 if (TREE_CODE (ce->value) == TREE_VEC)
12789                   {
12790                     int i, len = TREE_VEC_LENGTH (ce->value);
12791                     for (i = 0; i < len; ++i)
12792                       CONSTRUCTOR_APPEND_ELT (n, 0,
12793                                               TREE_VEC_ELT (ce->value, i));
12794                   }
12795                 else
12796                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12797               }
12798           }
12799
12800         r = build_constructor (init_list_type_node, n);
12801         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12802
12803         if (TREE_HAS_CONSTRUCTOR (t))
12804           return finish_compound_literal (type, r);
12805
12806         return r;
12807       }
12808
12809     case TYPEID_EXPR:
12810       {
12811         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12812         if (TYPE_P (operand_0))
12813           return get_typeid (operand_0);
12814         return build_typeid (operand_0);
12815       }
12816
12817     case VAR_DECL:
12818       if (!args)
12819         return t;
12820       /* Fall through */
12821
12822     case PARM_DECL:
12823       {
12824         tree r = tsubst_copy (t, args, complain, in_decl);
12825
12826         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12827           /* If the original type was a reference, we'll be wrapped in
12828              the appropriate INDIRECT_REF.  */
12829           r = convert_from_reference (r);
12830         return r;
12831       }
12832
12833     case VA_ARG_EXPR:
12834       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12835                              tsubst_copy (TREE_TYPE (t), args, complain,
12836                                           in_decl));
12837
12838     case OFFSETOF_EXPR:
12839       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12840
12841     case TRAIT_EXPR:
12842       {
12843         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12844                                   complain, in_decl);
12845
12846         tree type2 = TRAIT_EXPR_TYPE2 (t);
12847         if (type2)
12848           type2 = tsubst_copy (type2, args, complain, in_decl);
12849         
12850         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12851       }
12852
12853     case STMT_EXPR:
12854       {
12855         tree old_stmt_expr = cur_stmt_expr;
12856         tree stmt_expr = begin_stmt_expr ();
12857
12858         cur_stmt_expr = stmt_expr;
12859         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12860                      integral_constant_expression_p);
12861         stmt_expr = finish_stmt_expr (stmt_expr, false);
12862         cur_stmt_expr = old_stmt_expr;
12863
12864         /* If the resulting list of expression statement is empty,
12865            fold it further into void_zero_node.  */
12866         if (empty_expr_stmt_p (stmt_expr))
12867           stmt_expr = void_zero_node;
12868
12869         return stmt_expr;
12870       }
12871
12872     case CONST_DECL:
12873       t = tsubst_copy (t, args, complain, in_decl);
12874       /* As in finish_id_expression, we resolve enumeration constants
12875          to their underlying values.  */
12876       if (TREE_CODE (t) == CONST_DECL)
12877         {
12878           used_types_insert (TREE_TYPE (t));
12879           return DECL_INITIAL (t);
12880         }
12881       return t;
12882
12883     case LAMBDA_EXPR:
12884       {
12885         tree r = build_lambda_expr ();
12886
12887         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12888         TREE_TYPE (r) = type;
12889         CLASSTYPE_LAMBDA_EXPR (type) = r;
12890
12891         LAMBDA_EXPR_LOCATION (r)
12892           = LAMBDA_EXPR_LOCATION (t);
12893         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12894           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12895         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12896         LAMBDA_EXPR_DISCRIMINATOR (r)
12897           = (LAMBDA_EXPR_DISCRIMINATOR (t));
12898         LAMBDA_EXPR_CAPTURE_LIST (r)
12899           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12900         LAMBDA_EXPR_THIS_CAPTURE (r)
12901           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12902         LAMBDA_EXPR_EXTRA_SCOPE (r)
12903           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12904
12905         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12906         determine_visibility (TYPE_NAME (type));
12907         /* Now that we know visibility, instantiate the type so we have a
12908            declaration of the op() for later calls to lambda_function.  */
12909         complete_type (type);
12910
12911         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12912         if (type)
12913           apply_lambda_return_type (r, type);
12914
12915         return build_lambda_object (r);
12916       }
12917
12918     default:
12919       /* Handle Objective-C++ constructs, if appropriate.  */
12920       {
12921         tree subst
12922           = objcp_tsubst_copy_and_build (t, args, complain,
12923                                          in_decl, /*function_p=*/false);
12924         if (subst)
12925           return subst;
12926       }
12927       return tsubst_copy (t, args, complain, in_decl);
12928     }
12929
12930 #undef RECUR
12931 }
12932
12933 /* Verify that the instantiated ARGS are valid. For type arguments,
12934    make sure that the type's linkage is ok. For non-type arguments,
12935    make sure they are constants if they are integral or enumerations.
12936    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12937
12938 static bool
12939 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12940 {
12941   if (ARGUMENT_PACK_P (t))
12942     {
12943       tree vec = ARGUMENT_PACK_ARGS (t);
12944       int len = TREE_VEC_LENGTH (vec);
12945       bool result = false;
12946       int i;
12947
12948       for (i = 0; i < len; ++i)
12949         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12950           result = true;
12951       return result;
12952     }
12953   else if (TYPE_P (t))
12954     {
12955       /* [basic.link]: A name with no linkage (notably, the name
12956          of a class or enumeration declared in a local scope)
12957          shall not be used to declare an entity with linkage.
12958          This implies that names with no linkage cannot be used as
12959          template arguments
12960
12961          DR 757 relaxes this restriction for C++0x.  */
12962       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
12963                  : no_linkage_check (t, /*relaxed_p=*/false));
12964
12965       if (nt)
12966         {
12967           /* DR 488 makes use of a type with no linkage cause
12968              type deduction to fail.  */
12969           if (complain & tf_error)
12970             {
12971               if (TYPE_ANONYMOUS_P (nt))
12972                 error ("%qT is/uses anonymous type", t);
12973               else
12974                 error ("template argument for %qD uses local type %qT",
12975                        tmpl, t);
12976             }
12977           return true;
12978         }
12979       /* In order to avoid all sorts of complications, we do not
12980          allow variably-modified types as template arguments.  */
12981       else if (variably_modified_type_p (t, NULL_TREE))
12982         {
12983           if (complain & tf_error)
12984             error ("%qT is a variably modified type", t);
12985           return true;
12986         }
12987     }
12988   /* A non-type argument of integral or enumerated type must be a
12989      constant.  */
12990   else if (TREE_TYPE (t)
12991            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12992            && !TREE_CONSTANT (t))
12993     {
12994       if (complain & tf_error)
12995         error ("integral expression %qE is not constant", t);
12996       return true;
12997     }
12998   return false;
12999 }
13000
13001 static bool
13002 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
13003 {
13004   int ix, len = DECL_NTPARMS (tmpl);
13005   bool result = false;
13006
13007   for (ix = 0; ix != len; ix++)
13008     {
13009       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
13010         result = true;
13011     }
13012   if (result && (complain & tf_error))
13013     error ("  trying to instantiate %qD", tmpl);
13014   return result;
13015 }
13016
13017 /* Instantiate the indicated variable or function template TMPL with
13018    the template arguments in TARG_PTR.  */
13019
13020 tree
13021 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
13022 {
13023   tree targ_ptr = orig_args;
13024   tree fndecl;
13025   tree gen_tmpl;
13026   tree spec;
13027   HOST_WIDE_INT saved_processing_template_decl;
13028
13029   if (tmpl == error_mark_node)
13030     return error_mark_node;
13031
13032   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
13033
13034   /* If this function is a clone, handle it specially.  */
13035   if (DECL_CLONED_FUNCTION_P (tmpl))
13036     {
13037       tree spec;
13038       tree clone;
13039
13040       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
13041          DECL_CLONED_FUNCTION.  */
13042       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
13043                                    targ_ptr, complain);
13044       if (spec == error_mark_node)
13045         return error_mark_node;
13046
13047       /* Look for the clone.  */
13048       FOR_EACH_CLONE (clone, spec)
13049         if (DECL_NAME (clone) == DECL_NAME (tmpl))
13050           return clone;
13051       /* We should always have found the clone by now.  */
13052       gcc_unreachable ();
13053       return NULL_TREE;
13054     }
13055
13056   /* Check to see if we already have this specialization.  */
13057   gen_tmpl = most_general_template (tmpl);
13058   if (tmpl != gen_tmpl)
13059     /* The TMPL is a partial instantiation.  To get a full set of
13060        arguments we must add the arguments used to perform the
13061        partial instantiation.  */
13062     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
13063                                             targ_ptr);
13064
13065   /* It would be nice to avoid hashing here and then again in tsubst_decl,
13066      but it doesn't seem to be on the hot path.  */
13067   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
13068
13069   gcc_assert (tmpl == gen_tmpl
13070               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
13071                   == spec)
13072               || fndecl == NULL_TREE);
13073
13074   if (spec != NULL_TREE)
13075     return spec;
13076
13077   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
13078                                complain))
13079     return error_mark_node;
13080
13081   /* We are building a FUNCTION_DECL, during which the access of its
13082      parameters and return types have to be checked.  However this
13083      FUNCTION_DECL which is the desired context for access checking
13084      is not built yet.  We solve this chicken-and-egg problem by
13085      deferring all checks until we have the FUNCTION_DECL.  */
13086   push_deferring_access_checks (dk_deferred);
13087
13088   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
13089      (because, for example, we have encountered a non-dependent
13090      function call in the body of a template function and must now
13091      determine which of several overloaded functions will be called),
13092      within the instantiation itself we are not processing a
13093      template.  */  
13094   saved_processing_template_decl = processing_template_decl;
13095   processing_template_decl = 0;
13096   /* Substitute template parameters to obtain the specialization.  */
13097   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
13098                    targ_ptr, complain, gen_tmpl);
13099   processing_template_decl = saved_processing_template_decl;
13100   if (fndecl == error_mark_node)
13101     return error_mark_node;
13102
13103   /* Now we know the specialization, compute access previously
13104      deferred.  */
13105   push_access_scope (fndecl);
13106
13107   /* Some typedefs referenced from within the template code need to be access
13108      checked at template instantiation time, i.e now. These types were
13109      added to the template at parsing time. Let's get those and perfom
13110      the acces checks then.  */
13111   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
13112   perform_deferred_access_checks ();
13113   pop_access_scope (fndecl);
13114   pop_deferring_access_checks ();
13115
13116   /* The DECL_TI_TEMPLATE should always be the immediate parent
13117      template, not the most general template.  */
13118   DECL_TI_TEMPLATE (fndecl) = tmpl;
13119
13120   /* If we've just instantiated the main entry point for a function,
13121      instantiate all the alternate entry points as well.  We do this
13122      by cloning the instantiation of the main entry point, not by
13123      instantiating the template clones.  */
13124   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
13125     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
13126
13127   return fndecl;
13128 }
13129
13130 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
13131    NARGS elements of the arguments that are being used when calling
13132    it.  TARGS is a vector into which the deduced template arguments
13133    are placed.
13134
13135    Return zero for success, 2 for an incomplete match that doesn't resolve
13136    all the types, and 1 for complete failure.  An error message will be
13137    printed only for an incomplete match.
13138
13139    If FN is a conversion operator, or we are trying to produce a specific
13140    specialization, RETURN_TYPE is the return type desired.
13141
13142    The EXPLICIT_TARGS are explicit template arguments provided via a
13143    template-id.
13144
13145    The parameter STRICT is one of:
13146
13147    DEDUCE_CALL:
13148      We are deducing arguments for a function call, as in
13149      [temp.deduct.call].
13150
13151    DEDUCE_CONV:
13152      We are deducing arguments for a conversion function, as in
13153      [temp.deduct.conv].
13154
13155    DEDUCE_EXACT:
13156      We are deducing arguments when doing an explicit instantiation
13157      as in [temp.explicit], when determining an explicit specialization
13158      as in [temp.expl.spec], or when taking the address of a function
13159      template, as in [temp.deduct.funcaddr].  */
13160
13161 int
13162 fn_type_unification (tree fn,
13163                      tree explicit_targs,
13164                      tree targs,
13165                      const tree *args,
13166                      unsigned int nargs,
13167                      tree return_type,
13168                      unification_kind_t strict,
13169                      int flags)
13170 {
13171   tree parms;
13172   tree fntype;
13173   int result;
13174   bool incomplete_argument_packs_p = false;
13175
13176   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13177
13178   fntype = TREE_TYPE (fn);
13179   if (explicit_targs)
13180     {
13181       /* [temp.deduct]
13182
13183          The specified template arguments must match the template
13184          parameters in kind (i.e., type, nontype, template), and there
13185          must not be more arguments than there are parameters;
13186          otherwise type deduction fails.
13187
13188          Nontype arguments must match the types of the corresponding
13189          nontype template parameters, or must be convertible to the
13190          types of the corresponding nontype parameters as specified in
13191          _temp.arg.nontype_, otherwise type deduction fails.
13192
13193          All references in the function type of the function template
13194          to the corresponding template parameters are replaced by the
13195          specified template argument values.  If a substitution in a
13196          template parameter or in the function type of the function
13197          template results in an invalid type, type deduction fails.  */
13198       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13199       int i, len = TREE_VEC_LENGTH (tparms);
13200       tree converted_args;
13201       bool incomplete = false;
13202
13203       if (explicit_targs == error_mark_node)
13204         return 1;
13205
13206       converted_args
13207         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13208                                   /*require_all_args=*/false,
13209                                   /*use_default_args=*/false));
13210       if (converted_args == error_mark_node)
13211         return 1;
13212
13213       /* Substitute the explicit args into the function type.  This is
13214          necessary so that, for instance, explicitly declared function
13215          arguments can match null pointed constants.  If we were given
13216          an incomplete set of explicit args, we must not do semantic
13217          processing during substitution as we could create partial
13218          instantiations.  */
13219       for (i = 0; i < len; i++)
13220         {
13221           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13222           bool parameter_pack = false;
13223
13224           /* Dig out the actual parm.  */
13225           if (TREE_CODE (parm) == TYPE_DECL
13226               || TREE_CODE (parm) == TEMPLATE_DECL)
13227             {
13228               parm = TREE_TYPE (parm);
13229               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13230             }
13231           else if (TREE_CODE (parm) == PARM_DECL)
13232             {
13233               parm = DECL_INITIAL (parm);
13234               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13235             }
13236
13237           if (parameter_pack)
13238             {
13239               int level, idx;
13240               tree targ;
13241               template_parm_level_and_index (parm, &level, &idx);
13242
13243               /* Mark the argument pack as "incomplete". We could
13244                  still deduce more arguments during unification.  */
13245               targ = TMPL_ARG (converted_args, level, idx);
13246               if (targ)
13247                 {
13248                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13249                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
13250                     = ARGUMENT_PACK_ARGS (targ);
13251                 }
13252
13253               /* We have some incomplete argument packs.  */
13254               incomplete_argument_packs_p = true;
13255             }
13256         }
13257
13258       if (incomplete_argument_packs_p)
13259         /* Any substitution is guaranteed to be incomplete if there
13260            are incomplete argument packs, because we can still deduce
13261            more arguments.  */
13262         incomplete = 1;
13263       else
13264         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
13265
13266       processing_template_decl += incomplete;
13267       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
13268       processing_template_decl -= incomplete;
13269
13270       if (fntype == error_mark_node)
13271         return 1;
13272
13273       /* Place the explicitly specified arguments in TARGS.  */
13274       for (i = NUM_TMPL_ARGS (converted_args); i--;)
13275         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
13276     }
13277
13278   /* Never do unification on the 'this' parameter.  */
13279   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
13280
13281   if (return_type)
13282     {
13283       tree *new_args;
13284
13285       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
13286       new_args = XALLOCAVEC (tree, nargs + 1);
13287       new_args[0] = return_type;
13288       memcpy (new_args + 1, args, nargs * sizeof (tree));
13289       args = new_args;
13290       ++nargs;
13291     }
13292
13293   /* We allow incomplete unification without an error message here
13294      because the standard doesn't seem to explicitly prohibit it.  Our
13295      callers must be ready to deal with unification failures in any
13296      event.  */
13297   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
13298                                   targs, parms, args, nargs, /*subr=*/0,
13299                                   strict, flags);
13300
13301   if (result == 0 && incomplete_argument_packs_p)
13302     {
13303       int i, len = NUM_TMPL_ARGS (targs);
13304
13305       /* Clear the "incomplete" flags on all argument packs.  */
13306       for (i = 0; i < len; i++)
13307         {
13308           tree arg = TREE_VEC_ELT (targs, i);
13309           if (ARGUMENT_PACK_P (arg))
13310             {
13311               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
13312               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
13313             }
13314         }
13315     }
13316
13317   /* Now that we have bindings for all of the template arguments,
13318      ensure that the arguments deduced for the template template
13319      parameters have compatible template parameter lists.  We cannot
13320      check this property before we have deduced all template
13321      arguments, because the template parameter types of a template
13322      template parameter might depend on prior template parameters
13323      deduced after the template template parameter.  The following
13324      ill-formed example illustrates this issue:
13325
13326        template<typename T, template<T> class C> void f(C<5>, T);
13327
13328        template<int N> struct X {};
13329
13330        void g() {
13331          f(X<5>(), 5l); // error: template argument deduction fails
13332        }
13333
13334      The template parameter list of 'C' depends on the template type
13335      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13336      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13337      time that we deduce 'C'.  */
13338   if (result == 0
13339       && !template_template_parm_bindings_ok_p 
13340            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13341     return 1;
13342
13343   if (result == 0)
13344     /* All is well so far.  Now, check:
13345
13346        [temp.deduct]
13347
13348        When all template arguments have been deduced, all uses of
13349        template parameters in nondeduced contexts are replaced with
13350        the corresponding deduced argument values.  If the
13351        substitution results in an invalid type, as described above,
13352        type deduction fails.  */
13353     {
13354       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13355       if (substed == error_mark_node)
13356         return 1;
13357
13358       /* If we're looking for an exact match, check that what we got
13359          is indeed an exact match.  It might not be if some template
13360          parameters are used in non-deduced contexts.  */
13361       if (strict == DEDUCE_EXACT)
13362         {
13363           unsigned int i;
13364
13365           tree sarg
13366             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13367           if (return_type)
13368             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13369           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13370             if (!same_type_p (args[i], TREE_VALUE (sarg)))
13371               return 1;
13372         }
13373     }
13374
13375   return result;
13376 }
13377
13378 /* Adjust types before performing type deduction, as described in
13379    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13380    sections are symmetric.  PARM is the type of a function parameter
13381    or the return type of the conversion function.  ARG is the type of
13382    the argument passed to the call, or the type of the value
13383    initialized with the result of the conversion function.
13384    ARG_EXPR is the original argument expression, which may be null.  */
13385
13386 static int
13387 maybe_adjust_types_for_deduction (unification_kind_t strict,
13388                                   tree* parm,
13389                                   tree* arg,
13390                                   tree arg_expr)
13391 {
13392   int result = 0;
13393
13394   switch (strict)
13395     {
13396     case DEDUCE_CALL:
13397       break;
13398
13399     case DEDUCE_CONV:
13400       {
13401         /* Swap PARM and ARG throughout the remainder of this
13402            function; the handling is precisely symmetric since PARM
13403            will initialize ARG rather than vice versa.  */
13404         tree* temp = parm;
13405         parm = arg;
13406         arg = temp;
13407         break;
13408       }
13409
13410     case DEDUCE_EXACT:
13411       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13412          too, but here handle it by stripping the reference from PARM
13413          rather than by adding it to ARG.  */
13414       if (TREE_CODE (*parm) == REFERENCE_TYPE
13415           && TYPE_REF_IS_RVALUE (*parm)
13416           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13417           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13418           && TREE_CODE (*arg) == REFERENCE_TYPE
13419           && !TYPE_REF_IS_RVALUE (*arg))
13420         *parm = TREE_TYPE (*parm);
13421       /* Nothing else to do in this case.  */
13422       return 0;
13423
13424     default:
13425       gcc_unreachable ();
13426     }
13427
13428   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13429     {
13430       /* [temp.deduct.call]
13431
13432          If P is not a reference type:
13433
13434          --If A is an array type, the pointer type produced by the
13435          array-to-pointer standard conversion (_conv.array_) is
13436          used in place of A for type deduction; otherwise,
13437
13438          --If A is a function type, the pointer type produced by
13439          the function-to-pointer standard conversion
13440          (_conv.func_) is used in place of A for type deduction;
13441          otherwise,
13442
13443          --If A is a cv-qualified type, the top level
13444          cv-qualifiers of A's type are ignored for type
13445          deduction.  */
13446       if (TREE_CODE (*arg) == ARRAY_TYPE)
13447         *arg = build_pointer_type (TREE_TYPE (*arg));
13448       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13449         *arg = build_pointer_type (*arg);
13450       else
13451         *arg = TYPE_MAIN_VARIANT (*arg);
13452     }
13453
13454   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13455      of the form T&&, where T is a template parameter, and the argument
13456      is an lvalue, T is deduced as A& */
13457   if (TREE_CODE (*parm) == REFERENCE_TYPE
13458       && TYPE_REF_IS_RVALUE (*parm)
13459       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13460       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13461       && arg_expr && real_lvalue_p (arg_expr))
13462     *arg = build_reference_type (*arg);
13463
13464   /* [temp.deduct.call]
13465
13466      If P is a cv-qualified type, the top level cv-qualifiers
13467      of P's type are ignored for type deduction.  If P is a
13468      reference type, the type referred to by P is used for
13469      type deduction.  */
13470   *parm = TYPE_MAIN_VARIANT (*parm);
13471   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13472     {
13473       *parm = TREE_TYPE (*parm);
13474       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13475     }
13476
13477   /* DR 322. For conversion deduction, remove a reference type on parm
13478      too (which has been swapped into ARG).  */
13479   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13480     *arg = TREE_TYPE (*arg);
13481
13482   return result;
13483 }
13484
13485 /* Most parms like fn_type_unification.
13486
13487    If SUBR is 1, we're being called recursively (to unify the
13488    arguments of a function or method parameter of a function
13489    template). */
13490
13491 static int
13492 type_unification_real (tree tparms,
13493                        tree targs,
13494                        tree xparms,
13495                        const tree *xargs,
13496                        unsigned int xnargs,
13497                        int subr,
13498                        unification_kind_t strict,
13499                        int flags)
13500 {
13501   tree parm, arg, arg_expr;
13502   int i;
13503   int ntparms = TREE_VEC_LENGTH (tparms);
13504   int sub_strict;
13505   int saw_undeduced = 0;
13506   tree parms;
13507   const tree *args;
13508   unsigned int nargs;
13509   unsigned int ia;
13510
13511   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13512   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13513   gcc_assert (ntparms > 0);
13514
13515   /* Reset the number of non-defaulted template arguments contained
13516      in in TARGS.  */
13517   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
13518
13519   switch (strict)
13520     {
13521     case DEDUCE_CALL:
13522       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13523                     | UNIFY_ALLOW_DERIVED);
13524       break;
13525
13526     case DEDUCE_CONV:
13527       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13528       break;
13529
13530     case DEDUCE_EXACT:
13531       sub_strict = UNIFY_ALLOW_NONE;
13532       break;
13533
13534     default:
13535       gcc_unreachable ();
13536     }
13537
13538  again:
13539   parms = xparms;
13540   args = xargs;
13541   nargs = xnargs;
13542
13543   ia = 0;
13544   while (parms && parms != void_list_node
13545          && ia < nargs)
13546     {
13547       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13548         break;
13549
13550       parm = TREE_VALUE (parms);
13551       parms = TREE_CHAIN (parms);
13552       arg = args[ia];
13553       ++ia;
13554       arg_expr = NULL;
13555
13556       if (arg == error_mark_node)
13557         return 1;
13558       if (arg == unknown_type_node)
13559         /* We can't deduce anything from this, but we might get all the
13560            template args from other function args.  */
13561         continue;
13562
13563       /* Conversions will be performed on a function argument that
13564          corresponds with a function parameter that contains only
13565          non-deducible template parameters and explicitly specified
13566          template parameters.  */
13567       if (!uses_template_parms (parm))
13568         {
13569           tree type;
13570
13571           if (!TYPE_P (arg))
13572             type = TREE_TYPE (arg);
13573           else
13574             type = arg;
13575
13576           if (same_type_p (parm, type))
13577             continue;
13578           if (strict != DEDUCE_EXACT
13579               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13580                                   flags))
13581             continue;
13582
13583           return 1;
13584         }
13585
13586       if (!TYPE_P (arg))
13587         {
13588           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13589           if (type_unknown_p (arg))
13590             {
13591               /* [temp.deduct.type] 
13592
13593                  A template-argument can be deduced from a pointer to
13594                  function or pointer to member function argument if
13595                  the set of overloaded functions does not contain
13596                  function templates and at most one of a set of
13597                  overloaded functions provides a unique match.  */
13598               if (resolve_overloaded_unification
13599                   (tparms, targs, parm, arg, strict, sub_strict))
13600                 continue;
13601
13602               return 1;
13603             }
13604           arg_expr = arg;
13605           arg = unlowered_expr_type (arg);
13606           if (arg == error_mark_node)
13607             return 1;
13608         }
13609
13610       {
13611         int arg_strict = sub_strict;
13612
13613         if (!subr)
13614           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13615                                                           arg_expr);
13616
13617         if (arg == init_list_type_node && arg_expr)
13618           arg = arg_expr;
13619         if (unify (tparms, targs, parm, arg, arg_strict))
13620           return 1;
13621       }
13622     }
13623
13624
13625   if (parms 
13626       && parms != void_list_node
13627       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13628     {
13629       /* Unify the remaining arguments with the pack expansion type.  */
13630       tree argvec;
13631       tree parmvec = make_tree_vec (1);
13632
13633       /* Allocate a TREE_VEC and copy in all of the arguments */ 
13634       argvec = make_tree_vec (nargs - ia);
13635       for (i = 0; ia < nargs; ++ia, ++i)
13636         TREE_VEC_ELT (argvec, i) = args[ia];
13637
13638       /* Copy the parameter into parmvec.  */
13639       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13640       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13641                                 /*call_args_p=*/true, /*subr=*/subr))
13642         return 1;
13643
13644       /* Advance to the end of the list of parameters.  */
13645       parms = TREE_CHAIN (parms);
13646     }
13647
13648   /* Fail if we've reached the end of the parm list, and more args
13649      are present, and the parm list isn't variadic.  */
13650   if (ia < nargs && parms == void_list_node)
13651     return 1;
13652   /* Fail if parms are left and they don't have default values.  */
13653   if (parms && parms != void_list_node
13654       && TREE_PURPOSE (parms) == NULL_TREE)
13655     return 1;
13656
13657   if (!subr)
13658     for (i = 0; i < ntparms; i++)
13659       if (!TREE_VEC_ELT (targs, i))
13660         {
13661           tree tparm;
13662
13663           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13664             continue;
13665
13666           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13667
13668           /* If this is an undeduced nontype parameter that depends on
13669              a type parameter, try another pass; its type may have been
13670              deduced from a later argument than the one from which
13671              this parameter can be deduced.  */
13672           if (TREE_CODE (tparm) == PARM_DECL
13673               && uses_template_parms (TREE_TYPE (tparm))
13674               && !saw_undeduced++)
13675             goto again;
13676
13677           /* Core issue #226 (C++0x) [temp.deduct]:
13678
13679                If a template argument has not been deduced, its
13680                default template argument, if any, is used. 
13681
13682              When we are in C++98 mode, TREE_PURPOSE will either
13683              be NULL_TREE or ERROR_MARK_NODE, so we do not need
13684              to explicitly check cxx_dialect here.  */
13685           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13686             {
13687               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13688               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13689               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13690               arg = convert_template_argument (parm, arg, targs, tf_none,
13691                                                i, NULL_TREE);
13692               if (arg == error_mark_node)
13693                 return 1;
13694               else
13695                 {
13696                   TREE_VEC_ELT (targs, i) = arg;
13697                   /* The position of the first default template argument,
13698                      is also the number of non-defaulted arguments in TARGS.
13699                      Record that.  */
13700                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13701                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
13702                   continue;
13703                 }
13704             }
13705
13706           /* If the type parameter is a parameter pack, then it will
13707              be deduced to an empty parameter pack.  */
13708           if (template_parameter_pack_p (tparm))
13709             {
13710               tree arg;
13711
13712               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13713                 {
13714                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13715                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13716                   TREE_CONSTANT (arg) = 1;
13717                 }
13718               else
13719                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13720
13721               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13722
13723               TREE_VEC_ELT (targs, i) = arg;
13724               continue;
13725             }
13726
13727           return 2;
13728         }
13729 #ifdef ENABLE_CHECKING
13730   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13731     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
13732 #endif
13733
13734   return 0;
13735 }
13736
13737 /* Subroutine of type_unification_real.  Args are like the variables
13738    at the call site.  ARG is an overloaded function (or template-id);
13739    we try deducing template args from each of the overloads, and if
13740    only one succeeds, we go with that.  Modifies TARGS and returns
13741    true on success.  */
13742
13743 static bool
13744 resolve_overloaded_unification (tree tparms,
13745                                 tree targs,
13746                                 tree parm,
13747                                 tree arg,
13748                                 unification_kind_t strict,
13749                                 int sub_strict)
13750 {
13751   tree tempargs = copy_node (targs);
13752   int good = 0;
13753   tree goodfn = NULL_TREE;
13754   bool addr_p;
13755
13756   if (TREE_CODE (arg) == ADDR_EXPR)
13757     {
13758       arg = TREE_OPERAND (arg, 0);
13759       addr_p = true;
13760     }
13761   else
13762     addr_p = false;
13763
13764   if (TREE_CODE (arg) == COMPONENT_REF)
13765     /* Handle `&x' where `x' is some static or non-static member
13766        function name.  */
13767     arg = TREE_OPERAND (arg, 1);
13768
13769   if (TREE_CODE (arg) == OFFSET_REF)
13770     arg = TREE_OPERAND (arg, 1);
13771
13772   /* Strip baselink information.  */
13773   if (BASELINK_P (arg))
13774     arg = BASELINK_FUNCTIONS (arg);
13775
13776   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13777     {
13778       /* If we got some explicit template args, we need to plug them into
13779          the affected templates before we try to unify, in case the
13780          explicit args will completely resolve the templates in question.  */
13781
13782       tree expl_subargs = TREE_OPERAND (arg, 1);
13783       arg = TREE_OPERAND (arg, 0);
13784
13785       for (; arg; arg = OVL_NEXT (arg))
13786         {
13787           tree fn = OVL_CURRENT (arg);
13788           tree subargs, elem;
13789
13790           if (TREE_CODE (fn) != TEMPLATE_DECL)
13791             continue;
13792
13793           ++processing_template_decl;
13794           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13795                                   expl_subargs, /*check_ret=*/false);
13796           if (subargs)
13797             {
13798               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13799               if (try_one_overload (tparms, targs, tempargs, parm,
13800                                     elem, strict, sub_strict, addr_p)
13801                   && (!goodfn || !decls_match (goodfn, elem)))
13802                 {
13803                   goodfn = elem;
13804                   ++good;
13805                 }
13806             }
13807           --processing_template_decl;
13808         }
13809     }
13810   else if (TREE_CODE (arg) != OVERLOAD
13811            && TREE_CODE (arg) != FUNCTION_DECL)
13812     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13813        -- but the deduction does not succeed because the expression is
13814        not just the function on its own.  */
13815     return false;
13816   else
13817     for (; arg; arg = OVL_NEXT (arg))
13818       if (try_one_overload (tparms, targs, tempargs, parm,
13819                             TREE_TYPE (OVL_CURRENT (arg)),
13820                             strict, sub_strict, addr_p)
13821           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13822         {
13823           goodfn = OVL_CURRENT (arg);
13824           ++good;
13825         }
13826
13827   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13828      to function or pointer to member function argument if the set of
13829      overloaded functions does not contain function templates and at most
13830      one of a set of overloaded functions provides a unique match.
13831
13832      So if we found multiple possibilities, we return success but don't
13833      deduce anything.  */
13834
13835   if (good == 1)
13836     {
13837       int i = TREE_VEC_LENGTH (targs);
13838       for (; i--; )
13839         if (TREE_VEC_ELT (tempargs, i))
13840           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13841     }
13842   if (good)
13843     return true;
13844
13845   return false;
13846 }
13847
13848 /* Core DR 115: In contexts where deduction is done and fails, or in
13849    contexts where deduction is not done, if a template argument list is
13850    specified and it, along with any default template arguments, identifies
13851    a single function template specialization, then the template-id is an
13852    lvalue for the function template specialization.  */
13853
13854 tree
13855 resolve_nondeduced_context (tree orig_expr)
13856 {
13857   tree expr, offset, baselink;
13858   bool addr;
13859
13860   if (!type_unknown_p (orig_expr))
13861     return orig_expr;
13862
13863   expr = orig_expr;
13864   addr = false;
13865   offset = NULL_TREE;
13866   baselink = NULL_TREE;
13867
13868   if (TREE_CODE (expr) == ADDR_EXPR)
13869     {
13870       expr = TREE_OPERAND (expr, 0);
13871       addr = true;
13872     }
13873   if (TREE_CODE (expr) == OFFSET_REF)
13874     {
13875       offset = expr;
13876       expr = TREE_OPERAND (expr, 1);
13877     }
13878   if (TREE_CODE (expr) == BASELINK)
13879     {
13880       baselink = expr;
13881       expr = BASELINK_FUNCTIONS (expr);
13882     }
13883
13884   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13885     {
13886       int good = 0;
13887       tree goodfn = NULL_TREE;
13888
13889       /* If we got some explicit template args, we need to plug them into
13890          the affected templates before we try to unify, in case the
13891          explicit args will completely resolve the templates in question.  */
13892
13893       tree expl_subargs = TREE_OPERAND (expr, 1);
13894       tree arg = TREE_OPERAND (expr, 0);
13895       tree badfn = NULL_TREE;
13896       tree badargs = NULL_TREE;
13897
13898       for (; arg; arg = OVL_NEXT (arg))
13899         {
13900           tree fn = OVL_CURRENT (arg);
13901           tree subargs, elem;
13902
13903           if (TREE_CODE (fn) != TEMPLATE_DECL)
13904             continue;
13905
13906           ++processing_template_decl;
13907           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13908                                   expl_subargs, /*check_ret=*/false);
13909           if (subargs && !any_dependent_template_arguments_p (subargs))
13910             {
13911               elem = instantiate_template (fn, subargs, tf_none);
13912               if (elem == error_mark_node)
13913                 {
13914                   badfn = fn;
13915                   badargs = subargs;
13916                 }
13917               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13918                 {
13919                   goodfn = elem;
13920                   ++good;
13921                 }
13922             }
13923           --processing_template_decl;
13924         }
13925       if (good == 1)
13926         {
13927           expr = goodfn;
13928           if (baselink)
13929             expr = build_baselink (BASELINK_BINFO (baselink),
13930                                    BASELINK_ACCESS_BINFO (baselink),
13931                                    expr, BASELINK_OPTYPE (baselink));
13932           if (offset)
13933             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13934                            TREE_OPERAND (offset, 0), expr);
13935           if (addr)
13936             expr = build_address (expr);
13937           return expr;
13938         }
13939       else if (good == 0 && badargs)
13940         /* There were no good options and at least one bad one, so let the
13941            user know what the problem is.  */
13942         instantiate_template (badfn, badargs, tf_warning_or_error);
13943     }
13944   return orig_expr;
13945 }
13946
13947 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13948    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13949    different overloads deduce different arguments for a given parm.
13950    ADDR_P is true if the expression for which deduction is being
13951    performed was of the form "& fn" rather than simply "fn".
13952
13953    Returns 1 on success.  */
13954
13955 static int
13956 try_one_overload (tree tparms,
13957                   tree orig_targs,
13958                   tree targs,
13959                   tree parm,
13960                   tree arg,
13961                   unification_kind_t strict,
13962                   int sub_strict,
13963                   bool addr_p)
13964 {
13965   int nargs;
13966   tree tempargs;
13967   int i;
13968
13969   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13970      to function or pointer to member function argument if the set of
13971      overloaded functions does not contain function templates and at most
13972      one of a set of overloaded functions provides a unique match.
13973
13974      So if this is a template, just return success.  */
13975
13976   if (uses_template_parms (arg))
13977     return 1;
13978
13979   if (TREE_CODE (arg) == METHOD_TYPE)
13980     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13981   else if (addr_p)
13982     arg = build_pointer_type (arg);
13983
13984   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13985
13986   /* We don't copy orig_targs for this because if we have already deduced
13987      some template args from previous args, unify would complain when we
13988      try to deduce a template parameter for the same argument, even though
13989      there isn't really a conflict.  */
13990   nargs = TREE_VEC_LENGTH (targs);
13991   tempargs = make_tree_vec (nargs);
13992
13993   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13994     return 0;
13995
13996   /* First make sure we didn't deduce anything that conflicts with
13997      explicitly specified args.  */
13998   for (i = nargs; i--; )
13999     {
14000       tree elt = TREE_VEC_ELT (tempargs, i);
14001       tree oldelt = TREE_VEC_ELT (orig_targs, i);
14002
14003       if (!elt)
14004         /*NOP*/;
14005       else if (uses_template_parms (elt))
14006         /* Since we're unifying against ourselves, we will fill in
14007            template args used in the function parm list with our own
14008            template parms.  Discard them.  */
14009         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
14010       else if (oldelt && !template_args_equal (oldelt, elt))
14011         return 0;
14012     }
14013
14014   for (i = nargs; i--; )
14015     {
14016       tree elt = TREE_VEC_ELT (tempargs, i);
14017
14018       if (elt)
14019         TREE_VEC_ELT (targs, i) = elt;
14020     }
14021
14022   return 1;
14023 }
14024
14025 /* PARM is a template class (perhaps with unbound template
14026    parameters).  ARG is a fully instantiated type.  If ARG can be
14027    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
14028    TARGS are as for unify.  */
14029
14030 static tree
14031 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
14032 {
14033   tree copy_of_targs;
14034
14035   if (!CLASSTYPE_TEMPLATE_INFO (arg)
14036       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
14037           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
14038     return NULL_TREE;
14039
14040   /* We need to make a new template argument vector for the call to
14041      unify.  If we used TARGS, we'd clutter it up with the result of
14042      the attempted unification, even if this class didn't work out.
14043      We also don't want to commit ourselves to all the unifications
14044      we've already done, since unification is supposed to be done on
14045      an argument-by-argument basis.  In other words, consider the
14046      following pathological case:
14047
14048        template <int I, int J, int K>
14049        struct S {};
14050
14051        template <int I, int J>
14052        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
14053
14054        template <int I, int J, int K>
14055        void f(S<I, J, K>, S<I, I, I>);
14056
14057        void g() {
14058          S<0, 0, 0> s0;
14059          S<0, 1, 2> s2;
14060
14061          f(s0, s2);
14062        }
14063
14064      Now, by the time we consider the unification involving `s2', we
14065      already know that we must have `f<0, 0, 0>'.  But, even though
14066      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
14067      because there are two ways to unify base classes of S<0, 1, 2>
14068      with S<I, I, I>.  If we kept the already deduced knowledge, we
14069      would reject the possibility I=1.  */
14070   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
14071
14072   /* If unification failed, we're done.  */
14073   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
14074              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
14075     return NULL_TREE;
14076
14077   return arg;
14078 }
14079
14080 /* Given a template type PARM and a class type ARG, find the unique
14081    base type in ARG that is an instance of PARM.  We do not examine
14082    ARG itself; only its base-classes.  If there is not exactly one
14083    appropriate base class, return NULL_TREE.  PARM may be the type of
14084    a partial specialization, as well as a plain template type.  Used
14085    by unify.  */
14086
14087 static tree
14088 get_template_base (tree tparms, tree targs, tree parm, tree arg)
14089 {
14090   tree rval = NULL_TREE;
14091   tree binfo;
14092
14093   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
14094
14095   binfo = TYPE_BINFO (complete_type (arg));
14096   if (!binfo)
14097     /* The type could not be completed.  */
14098     return NULL_TREE;
14099
14100   /* Walk in inheritance graph order.  The search order is not
14101      important, and this avoids multiple walks of virtual bases.  */
14102   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
14103     {
14104       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
14105
14106       if (r)
14107         {
14108           /* If there is more than one satisfactory baseclass, then:
14109
14110                [temp.deduct.call]
14111
14112               If they yield more than one possible deduced A, the type
14113               deduction fails.
14114
14115              applies.  */
14116           if (rval && !same_type_p (r, rval))
14117             return NULL_TREE;
14118
14119           rval = r;
14120         }
14121     }
14122
14123   return rval;
14124 }
14125
14126 /* Returns the level of DECL, which declares a template parameter.  */
14127
14128 static int
14129 template_decl_level (tree decl)
14130 {
14131   switch (TREE_CODE (decl))
14132     {
14133     case TYPE_DECL:
14134     case TEMPLATE_DECL:
14135       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
14136
14137     case PARM_DECL:
14138       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
14139
14140     default:
14141       gcc_unreachable ();
14142     }
14143   return 0;
14144 }
14145
14146 /* Decide whether ARG can be unified with PARM, considering only the
14147    cv-qualifiers of each type, given STRICT as documented for unify.
14148    Returns nonzero iff the unification is OK on that basis.  */
14149
14150 static int
14151 check_cv_quals_for_unify (int strict, tree arg, tree parm)
14152 {
14153   int arg_quals = cp_type_quals (arg);
14154   int parm_quals = cp_type_quals (parm);
14155
14156   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14157       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14158     {
14159       /*  Although a CVR qualifier is ignored when being applied to a
14160           substituted template parameter ([8.3.2]/1 for example), that
14161           does not allow us to unify "const T" with "int&" because both
14162           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
14163           It is ok when we're allowing additional CV qualifiers
14164           at the outer level [14.8.2.1]/3,1st bullet.  */
14165       if ((TREE_CODE (arg) == REFERENCE_TYPE
14166            || TREE_CODE (arg) == FUNCTION_TYPE
14167            || TREE_CODE (arg) == METHOD_TYPE)
14168           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14169         return 0;
14170
14171       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14172           && (parm_quals & TYPE_QUAL_RESTRICT))
14173         return 0;
14174     }
14175
14176   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14177       && (arg_quals & parm_quals) != parm_quals)
14178     return 0;
14179
14180   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14181       && (parm_quals & arg_quals) != arg_quals)
14182     return 0;
14183
14184   return 1;
14185 }
14186
14187 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
14188 void 
14189 template_parm_level_and_index (tree parm, int* level, int* index)
14190 {
14191   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14192       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14193       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14194     {
14195       *index = TEMPLATE_TYPE_IDX (parm);
14196       *level = TEMPLATE_TYPE_LEVEL (parm);
14197     }
14198   else
14199     {
14200       *index = TEMPLATE_PARM_IDX (parm);
14201       *level = TEMPLATE_PARM_LEVEL (parm);
14202     }
14203 }
14204
14205 /* Unifies the remaining arguments in PACKED_ARGS with the pack
14206    expansion at the end of PACKED_PARMS. Returns 0 if the type
14207    deduction succeeds, 1 otherwise. STRICT is the same as in
14208    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14209    call argument list. We'll need to adjust the arguments to make them
14210    types. SUBR tells us if this is from a recursive call to
14211    type_unification_real.  */
14212 int
14213 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
14214                       tree packed_args, int strict, bool call_args_p,
14215                       bool subr)
14216 {
14217   tree parm 
14218     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14219   tree pattern = PACK_EXPANSION_PATTERN (parm);
14220   tree pack, packs = NULL_TREE;
14221   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14222   int len = TREE_VEC_LENGTH (packed_args);
14223
14224   /* Determine the parameter packs we will be deducing from the
14225      pattern, and record their current deductions.  */
14226   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
14227        pack; pack = TREE_CHAIN (pack))
14228     {
14229       tree parm_pack = TREE_VALUE (pack);
14230       int idx, level;
14231
14232       /* Determine the index and level of this parameter pack.  */
14233       template_parm_level_and_index (parm_pack, &level, &idx);
14234
14235       /* Keep track of the parameter packs and their corresponding
14236          argument packs.  */
14237       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
14238       TREE_TYPE (packs) = make_tree_vec (len - start);
14239     }
14240   
14241   /* Loop through all of the arguments that have not yet been
14242      unified and unify each with the pattern.  */
14243   for (i = start; i < len; i++)
14244     {
14245       tree parm = pattern;
14246
14247       /* For each parameter pack, clear out the deduced value so that
14248          we can deduce it again.  */
14249       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14250         {
14251           int idx, level;
14252           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14253
14254           TMPL_ARG (targs, level, idx) = NULL_TREE;
14255         }
14256
14257       /* Unify the pattern with the current argument.  */
14258       {
14259         tree arg = TREE_VEC_ELT (packed_args, i);
14260         tree arg_expr = NULL_TREE;
14261         int arg_strict = strict;
14262         bool skip_arg_p = false;
14263
14264         if (call_args_p)
14265           {
14266             int sub_strict;
14267
14268             /* This mirrors what we do in type_unification_real.  */
14269             switch (strict)
14270               {
14271               case DEDUCE_CALL:
14272                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
14273                               | UNIFY_ALLOW_MORE_CV_QUAL
14274                               | UNIFY_ALLOW_DERIVED);
14275                 break;
14276                 
14277               case DEDUCE_CONV:
14278                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14279                 break;
14280                 
14281               case DEDUCE_EXACT:
14282                 sub_strict = UNIFY_ALLOW_NONE;
14283                 break;
14284                 
14285               default:
14286                 gcc_unreachable ();
14287               }
14288
14289             if (!TYPE_P (arg))
14290               {
14291                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14292                 if (type_unknown_p (arg))
14293                   {
14294                     /* [temp.deduct.type] A template-argument can be
14295                        deduced from a pointer to function or pointer
14296                        to member function argument if the set of
14297                        overloaded functions does not contain function
14298                        templates and at most one of a set of
14299                        overloaded functions provides a unique
14300                        match.  */
14301
14302                     if (resolve_overloaded_unification
14303                         (tparms, targs, parm, arg,
14304                          (unification_kind_t) strict,
14305                          sub_strict)
14306                         != 0)
14307                       return 1;
14308                     skip_arg_p = true;
14309                   }
14310
14311                 if (!skip_arg_p)
14312                   {
14313                     arg_expr = arg;
14314                     arg = unlowered_expr_type (arg);
14315                     if (arg == error_mark_node)
14316                       return 1;
14317                   }
14318               }
14319       
14320             arg_strict = sub_strict;
14321
14322             if (!subr)
14323               arg_strict |= 
14324                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
14325                                                   &parm, &arg, arg_expr);
14326           }
14327
14328         if (!skip_arg_p)
14329           {
14330             /* For deduction from an init-list we need the actual list.  */
14331             if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14332               arg = arg_expr;
14333             if (unify (tparms, targs, parm, arg, arg_strict))
14334               return 1;
14335           }
14336       }
14337
14338       /* For each parameter pack, collect the deduced value.  */
14339       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14340         {
14341           int idx, level;
14342           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14343
14344           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
14345             TMPL_ARG (targs, level, idx);
14346         }
14347     }
14348
14349   /* Verify that the results of unification with the parameter packs
14350      produce results consistent with what we've seen before, and make
14351      the deduced argument packs available.  */
14352   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14353     {
14354       tree old_pack = TREE_VALUE (pack);
14355       tree new_args = TREE_TYPE (pack);
14356       int i, len = TREE_VEC_LENGTH (new_args);
14357       int idx, level;
14358       bool nondeduced_p = false;
14359
14360       /* By default keep the original deduced argument pack.
14361          If necessary, more specific code is going to update the
14362          resulting deduced argument later down in this function.  */
14363       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14364       TMPL_ARG (targs, level, idx) = old_pack;
14365
14366       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14367          actually deduce anything.  */
14368       for (i = 0; i < len && !nondeduced_p; ++i)
14369         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14370           nondeduced_p = true;
14371       if (nondeduced_p)
14372         continue;
14373
14374       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14375         {
14376           /* Prepend the explicit arguments onto NEW_ARGS.  */
14377           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14378           tree old_args = new_args;
14379           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14380           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14381
14382           /* Copy the explicit arguments.  */
14383           new_args = make_tree_vec (len);
14384           for (i = 0; i < explicit_len; i++)
14385             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14386
14387           /* Copy the deduced arguments.  */
14388           for (; i < len; i++)
14389             TREE_VEC_ELT (new_args, i) =
14390               TREE_VEC_ELT (old_args, i - explicit_len);
14391         }
14392
14393       if (!old_pack)
14394         {
14395           tree result;
14396           /* Build the deduced *_ARGUMENT_PACK.  */
14397           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14398             {
14399               result = make_node (NONTYPE_ARGUMENT_PACK);
14400               TREE_TYPE (result) = 
14401                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14402               TREE_CONSTANT (result) = 1;
14403             }
14404           else
14405             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14406
14407           SET_ARGUMENT_PACK_ARGS (result, new_args);
14408
14409           /* Note the deduced argument packs for this parameter
14410              pack.  */
14411           TMPL_ARG (targs, level, idx) = result;
14412         }
14413       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14414                && (ARGUMENT_PACK_ARGS (old_pack) 
14415                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14416         {
14417           /* We only had the explicitly-provided arguments before, but
14418              now we have a complete set of arguments.  */
14419           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14420
14421           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14422           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14423           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14424         }
14425       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14426                                     new_args))
14427         /* Inconsistent unification of this parameter pack.  */
14428         return 1;
14429     }
14430
14431   return 0;
14432 }
14433
14434 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14435    set of template parameters to a template.  TARGS is the bindings
14436    for those template parameters, as determined thus far; TARGS may
14437    include template arguments for outer levels of template parameters
14438    as well.  PARM is a parameter to a template function, or a
14439    subcomponent of that parameter; ARG is the corresponding argument.
14440    This function attempts to match PARM with ARG in a manner
14441    consistent with the existing assignments in TARGS.  If more values
14442    are deduced, then TARGS is updated.
14443
14444    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14445    parameter STRICT is a bitwise or of the following flags:
14446
14447      UNIFY_ALLOW_NONE:
14448        Require an exact match between PARM and ARG.
14449      UNIFY_ALLOW_MORE_CV_QUAL:
14450        Allow the deduced ARG to be more cv-qualified (by qualification
14451        conversion) than ARG.
14452      UNIFY_ALLOW_LESS_CV_QUAL:
14453        Allow the deduced ARG to be less cv-qualified than ARG.
14454      UNIFY_ALLOW_DERIVED:
14455        Allow the deduced ARG to be a template base class of ARG,
14456        or a pointer to a template base class of the type pointed to by
14457        ARG.
14458      UNIFY_ALLOW_INTEGER:
14459        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14460        case for more information.
14461      UNIFY_ALLOW_OUTER_LEVEL:
14462        This is the outermost level of a deduction. Used to determine validity
14463        of qualification conversions. A valid qualification conversion must
14464        have const qualified pointers leading up to the inner type which
14465        requires additional CV quals, except at the outer level, where const
14466        is not required [conv.qual]. It would be normal to set this flag in
14467        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14468      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14469        This is the outermost level of a deduction, and PARM can be more CV
14470        qualified at this point.
14471      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14472        This is the outermost level of a deduction, and PARM can be less CV
14473        qualified at this point.  */
14474
14475 static int
14476 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14477 {
14478   int idx;
14479   tree targ;
14480   tree tparm;
14481   int strict_in = strict;
14482
14483   /* I don't think this will do the right thing with respect to types.
14484      But the only case I've seen it in so far has been array bounds, where
14485      signedness is the only information lost, and I think that will be
14486      okay.  */
14487   while (TREE_CODE (parm) == NOP_EXPR)
14488     parm = TREE_OPERAND (parm, 0);
14489
14490   if (arg == error_mark_node)
14491     return 1;
14492   if (arg == unknown_type_node
14493       || arg == init_list_type_node)
14494     /* We can't deduce anything from this, but we might get all the
14495        template args from other function args.  */
14496     return 0;
14497
14498   /* If PARM uses template parameters, then we can't bail out here,
14499      even if ARG == PARM, since we won't record unifications for the
14500      template parameters.  We might need them if we're trying to
14501      figure out which of two things is more specialized.  */
14502   if (arg == parm && !uses_template_parms (parm))
14503     return 0;
14504
14505   /* Handle init lists early, so the rest of the function can assume
14506      we're dealing with a type. */
14507   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14508     {
14509       tree elt, elttype;
14510       unsigned i;
14511       tree orig_parm = parm;
14512
14513       /* Replace T with std::initializer_list<T> for deduction.  */
14514       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14515           && flag_deduce_init_list)
14516         parm = listify (parm);
14517
14518       if (!is_std_init_list (parm))
14519         /* We can only deduce from an initializer list argument if the
14520            parameter is std::initializer_list; otherwise this is a
14521            non-deduced context. */
14522         return 0;
14523
14524       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14525
14526       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14527         {
14528           int elt_strict = strict;
14529
14530           if (elt == error_mark_node)
14531             return 1;
14532
14533           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14534             {
14535               tree type = TREE_TYPE (elt);
14536               /* It should only be possible to get here for a call.  */
14537               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14538               elt_strict |= maybe_adjust_types_for_deduction
14539                 (DEDUCE_CALL, &elttype, &type, elt);
14540               elt = type;
14541             }
14542
14543           if (unify (tparms, targs, elttype, elt, elt_strict))
14544             return 1;
14545         }
14546
14547       /* If the std::initializer_list<T> deduction worked, replace the
14548          deduced A with std::initializer_list<A>.  */
14549       if (orig_parm != parm)
14550         {
14551           idx = TEMPLATE_TYPE_IDX (orig_parm);
14552           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14553           targ = listify (targ);
14554           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14555         }
14556       return 0;
14557     }
14558
14559   /* Immediately reject some pairs that won't unify because of
14560      cv-qualification mismatches.  */
14561   if (TREE_CODE (arg) == TREE_CODE (parm)
14562       && TYPE_P (arg)
14563       /* It is the elements of the array which hold the cv quals of an array
14564          type, and the elements might be template type parms. We'll check
14565          when we recurse.  */
14566       && TREE_CODE (arg) != ARRAY_TYPE
14567       /* We check the cv-qualifiers when unifying with template type
14568          parameters below.  We want to allow ARG `const T' to unify with
14569          PARM `T' for example, when computing which of two templates
14570          is more specialized, for example.  */
14571       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14572       && !check_cv_quals_for_unify (strict_in, arg, parm))
14573     return 1;
14574
14575   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14576       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14577     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14578   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14579   strict &= ~UNIFY_ALLOW_DERIVED;
14580   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14581   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14582
14583   switch (TREE_CODE (parm))
14584     {
14585     case TYPENAME_TYPE:
14586     case SCOPE_REF:
14587     case UNBOUND_CLASS_TEMPLATE:
14588       /* In a type which contains a nested-name-specifier, template
14589          argument values cannot be deduced for template parameters used
14590          within the nested-name-specifier.  */
14591       return 0;
14592
14593     case TEMPLATE_TYPE_PARM:
14594     case TEMPLATE_TEMPLATE_PARM:
14595     case BOUND_TEMPLATE_TEMPLATE_PARM:
14596       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14597       if (tparm == error_mark_node)
14598         return 1;
14599
14600       if (TEMPLATE_TYPE_LEVEL (parm)
14601           != template_decl_level (tparm))
14602         /* The PARM is not one we're trying to unify.  Just check
14603            to see if it matches ARG.  */
14604         return (TREE_CODE (arg) == TREE_CODE (parm)
14605                 && same_type_p (parm, arg)) ? 0 : 1;
14606       idx = TEMPLATE_TYPE_IDX (parm);
14607       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14608       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14609
14610       /* Check for mixed types and values.  */
14611       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14612            && TREE_CODE (tparm) != TYPE_DECL)
14613           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14614               && TREE_CODE (tparm) != TEMPLATE_DECL))
14615         return 1;
14616
14617       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14618         {
14619           /* ARG must be constructed from a template class or a template
14620              template parameter.  */
14621           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14622               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14623             return 1;
14624
14625           {
14626             tree parmvec = TYPE_TI_ARGS (parm);
14627             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14628             tree parm_parms 
14629               = DECL_INNERMOST_TEMPLATE_PARMS
14630                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14631             int i, len;
14632             int parm_variadic_p = 0;
14633
14634             /* The resolution to DR150 makes clear that default
14635                arguments for an N-argument may not be used to bind T
14636                to a template template parameter with fewer than N
14637                parameters.  It is not safe to permit the binding of
14638                default arguments as an extension, as that may change
14639                the meaning of a conforming program.  Consider:
14640
14641                   struct Dense { static const unsigned int dim = 1; };
14642
14643                   template <template <typename> class View,
14644                             typename Block>
14645                   void operator+(float, View<Block> const&);
14646
14647                   template <typename Block,
14648                             unsigned int Dim = Block::dim>
14649                   struct Lvalue_proxy { operator float() const; };
14650
14651                   void
14652                   test_1d (void) {
14653                     Lvalue_proxy<Dense> p;
14654                     float b;
14655                     b + p;
14656                   }
14657
14658               Here, if Lvalue_proxy is permitted to bind to View, then
14659               the global operator+ will be used; if they are not, the
14660               Lvalue_proxy will be converted to float.  */
14661             if (coerce_template_parms (parm_parms,
14662                                        argvec,
14663                                        TYPE_TI_TEMPLATE (parm),
14664                                        tf_none,
14665                                        /*require_all_args=*/true,
14666                                        /*use_default_args=*/false)
14667                 == error_mark_node)
14668               return 1;
14669
14670             /* Deduce arguments T, i from TT<T> or TT<i>.
14671                We check each element of PARMVEC and ARGVEC individually
14672                rather than the whole TREE_VEC since they can have
14673                different number of elements.  */
14674
14675             parmvec = expand_template_argument_pack (parmvec);
14676             argvec = expand_template_argument_pack (argvec);
14677
14678             len = TREE_VEC_LENGTH (parmvec);
14679
14680             /* Check if the parameters end in a pack, making them
14681                variadic.  */
14682             if (len > 0
14683                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14684               parm_variadic_p = 1;
14685             
14686             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14687               return 1;
14688
14689              for (i = 0; i < len - parm_variadic_p; ++i)
14690               {
14691                 if (unify (tparms, targs,
14692                            TREE_VEC_ELT (parmvec, i),
14693                            TREE_VEC_ELT (argvec, i),
14694                            UNIFY_ALLOW_NONE))
14695                   return 1;
14696               }
14697
14698             if (parm_variadic_p
14699                 && unify_pack_expansion (tparms, targs,
14700                                          parmvec, argvec,
14701                                          UNIFY_ALLOW_NONE,
14702                                          /*call_args_p=*/false,
14703                                          /*subr=*/false))
14704               return 1;
14705           }
14706           arg = TYPE_TI_TEMPLATE (arg);
14707
14708           /* Fall through to deduce template name.  */
14709         }
14710
14711       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14712           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14713         {
14714           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14715
14716           /* Simple cases: Value already set, does match or doesn't.  */
14717           if (targ != NULL_TREE && template_args_equal (targ, arg))
14718             return 0;
14719           else if (targ)
14720             return 1;
14721         }
14722       else
14723         {
14724           /* If PARM is `const T' and ARG is only `int', we don't have
14725              a match unless we are allowing additional qualification.
14726              If ARG is `const int' and PARM is just `T' that's OK;
14727              that binds `const int' to `T'.  */
14728           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14729                                          arg, parm))
14730             return 1;
14731
14732           /* Consider the case where ARG is `const volatile int' and
14733              PARM is `const T'.  Then, T should be `volatile int'.  */
14734           arg = cp_build_qualified_type_real
14735             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14736           if (arg == error_mark_node)
14737             return 1;
14738
14739           /* Simple cases: Value already set, does match or doesn't.  */
14740           if (targ != NULL_TREE && same_type_p (targ, arg))
14741             return 0;
14742           else if (targ)
14743             return 1;
14744
14745           /* Make sure that ARG is not a variable-sized array.  (Note
14746              that were talking about variable-sized arrays (like
14747              `int[n]'), rather than arrays of unknown size (like
14748              `int[]').)  We'll get very confused by such a type since
14749              the bound of the array will not be computable in an
14750              instantiation.  Besides, such types are not allowed in
14751              ISO C++, so we can do as we please here.  */
14752           if (variably_modified_type_p (arg, NULL_TREE))
14753             return 1;
14754
14755           /* Strip typedefs as in convert_template_argument.  */
14756           arg = strip_typedefs (arg);
14757         }
14758
14759       /* If ARG is a parameter pack or an expansion, we cannot unify
14760          against it unless PARM is also a parameter pack.  */
14761       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14762           && !template_parameter_pack_p (parm))
14763         return 1;
14764
14765       /* If the argument deduction results is a METHOD_TYPE,
14766          then there is a problem.
14767          METHOD_TYPE doesn't map to any real C++ type the result of
14768          the deduction can not be of that type.  */
14769       if (TREE_CODE (arg) == METHOD_TYPE)
14770         return 1;
14771
14772       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14773       return 0;
14774
14775     case TEMPLATE_PARM_INDEX:
14776       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14777       if (tparm == error_mark_node)
14778         return 1;
14779
14780       if (TEMPLATE_PARM_LEVEL (parm)
14781           != template_decl_level (tparm))
14782         /* The PARM is not one we're trying to unify.  Just check
14783            to see if it matches ARG.  */
14784         return !(TREE_CODE (arg) == TREE_CODE (parm)
14785                  && cp_tree_equal (parm, arg));
14786
14787       idx = TEMPLATE_PARM_IDX (parm);
14788       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14789
14790       if (targ)
14791         return !cp_tree_equal (targ, arg);
14792
14793       /* [temp.deduct.type] If, in the declaration of a function template
14794          with a non-type template-parameter, the non-type
14795          template-parameter is used in an expression in the function
14796          parameter-list and, if the corresponding template-argument is
14797          deduced, the template-argument type shall match the type of the
14798          template-parameter exactly, except that a template-argument
14799          deduced from an array bound may be of any integral type.
14800          The non-type parameter might use already deduced type parameters.  */
14801       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14802       if (!TREE_TYPE (arg))
14803         /* Template-parameter dependent expression.  Just accept it for now.
14804            It will later be processed in convert_template_argument.  */
14805         ;
14806       else if (same_type_p (TREE_TYPE (arg), tparm))
14807         /* OK */;
14808       else if ((strict & UNIFY_ALLOW_INTEGER)
14809                && (TREE_CODE (tparm) == INTEGER_TYPE
14810                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
14811         /* Convert the ARG to the type of PARM; the deduced non-type
14812            template argument must exactly match the types of the
14813            corresponding parameter.  */
14814         arg = fold (build_nop (tparm, arg));
14815       else if (uses_template_parms (tparm))
14816         /* We haven't deduced the type of this parameter yet.  Try again
14817            later.  */
14818         return 0;
14819       else
14820         return 1;
14821
14822       /* If ARG is a parameter pack or an expansion, we cannot unify
14823          against it unless PARM is also a parameter pack.  */
14824       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14825           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14826         return 1;
14827
14828       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14829       return 0;
14830
14831     case PTRMEM_CST:
14832      {
14833         /* A pointer-to-member constant can be unified only with
14834          another constant.  */
14835       if (TREE_CODE (arg) != PTRMEM_CST)
14836         return 1;
14837
14838       /* Just unify the class member. It would be useless (and possibly
14839          wrong, depending on the strict flags) to unify also
14840          PTRMEM_CST_CLASS, because we want to be sure that both parm and
14841          arg refer to the same variable, even if through different
14842          classes. For instance:
14843
14844          struct A { int x; };
14845          struct B : A { };
14846
14847          Unification of &A::x and &B::x must succeed.  */
14848       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14849                     PTRMEM_CST_MEMBER (arg), strict);
14850      }
14851
14852     case POINTER_TYPE:
14853       {
14854         if (TREE_CODE (arg) != POINTER_TYPE)
14855           return 1;
14856
14857         /* [temp.deduct.call]
14858
14859            A can be another pointer or pointer to member type that can
14860            be converted to the deduced A via a qualification
14861            conversion (_conv.qual_).
14862
14863            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14864            This will allow for additional cv-qualification of the
14865            pointed-to types if appropriate.  */
14866
14867         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14868           /* The derived-to-base conversion only persists through one
14869              level of pointers.  */
14870           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14871
14872         return unify (tparms, targs, TREE_TYPE (parm),
14873                       TREE_TYPE (arg), strict);
14874       }
14875
14876     case REFERENCE_TYPE:
14877       if (TREE_CODE (arg) != REFERENCE_TYPE)
14878         return 1;
14879       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14880                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14881
14882     case ARRAY_TYPE:
14883       if (TREE_CODE (arg) != ARRAY_TYPE)
14884         return 1;
14885       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14886           != (TYPE_DOMAIN (arg) == NULL_TREE))
14887         return 1;
14888       if (TYPE_DOMAIN (parm) != NULL_TREE)
14889         {
14890           tree parm_max;
14891           tree arg_max;
14892           bool parm_cst;
14893           bool arg_cst;
14894
14895           /* Our representation of array types uses "N - 1" as the
14896              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14897              not an integer constant.  We cannot unify arbitrarily
14898              complex expressions, so we eliminate the MINUS_EXPRs
14899              here.  */
14900           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14901           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14902           if (!parm_cst)
14903             {
14904               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14905               parm_max = TREE_OPERAND (parm_max, 0);
14906             }
14907           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14908           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14909           if (!arg_cst)
14910             {
14911               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14912                  trying to unify the type of a variable with the type
14913                  of a template parameter.  For example:
14914
14915                    template <unsigned int N>
14916                    void f (char (&) [N]);
14917                    int g(); 
14918                    void h(int i) {
14919                      char a[g(i)];
14920                      f(a); 
14921                    }
14922
14923                 Here, the type of the ARG will be "int [g(i)]", and
14924                 may be a SAVE_EXPR, etc.  */
14925               if (TREE_CODE (arg_max) != MINUS_EXPR)
14926                 return 1;
14927               arg_max = TREE_OPERAND (arg_max, 0);
14928             }
14929
14930           /* If only one of the bounds used a MINUS_EXPR, compensate
14931              by adding one to the other bound.  */
14932           if (parm_cst && !arg_cst)
14933             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14934                                     integer_type_node,
14935                                     parm_max,
14936                                     integer_one_node);
14937           else if (arg_cst && !parm_cst)
14938             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14939                                    integer_type_node,
14940                                    arg_max,
14941                                    integer_one_node);
14942
14943           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14944             return 1;
14945         }
14946       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14947                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14948
14949     case REAL_TYPE:
14950     case COMPLEX_TYPE:
14951     case VECTOR_TYPE:
14952     case INTEGER_TYPE:
14953     case BOOLEAN_TYPE:
14954     case ENUMERAL_TYPE:
14955     case VOID_TYPE:
14956       if (TREE_CODE (arg) != TREE_CODE (parm))
14957         return 1;
14958
14959       /* We have already checked cv-qualification at the top of the
14960          function.  */
14961       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14962         return 1;
14963
14964       /* As far as unification is concerned, this wins.  Later checks
14965          will invalidate it if necessary.  */
14966       return 0;
14967
14968       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14969       /* Type INTEGER_CST can come from ordinary constant template args.  */
14970     case INTEGER_CST:
14971       while (TREE_CODE (arg) == NOP_EXPR)
14972         arg = TREE_OPERAND (arg, 0);
14973
14974       if (TREE_CODE (arg) != INTEGER_CST)
14975         return 1;
14976       return !tree_int_cst_equal (parm, arg);
14977
14978     case TREE_VEC:
14979       {
14980         int i;
14981         if (TREE_CODE (arg) != TREE_VEC)
14982           return 1;
14983         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14984           return 1;
14985         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14986           if (unify (tparms, targs,
14987                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14988                      UNIFY_ALLOW_NONE))
14989             return 1;
14990         return 0;
14991       }
14992
14993     case RECORD_TYPE:
14994     case UNION_TYPE:
14995       if (TREE_CODE (arg) != TREE_CODE (parm))
14996         return 1;
14997
14998       if (TYPE_PTRMEMFUNC_P (parm))
14999         {
15000           if (!TYPE_PTRMEMFUNC_P (arg))
15001             return 1;
15002
15003           return unify (tparms, targs,
15004                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
15005                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
15006                         strict);
15007         }
15008
15009       if (CLASSTYPE_TEMPLATE_INFO (parm))
15010         {
15011           tree t = NULL_TREE;
15012
15013           if (strict_in & UNIFY_ALLOW_DERIVED)
15014             {
15015               /* First, we try to unify the PARM and ARG directly.  */
15016               t = try_class_unification (tparms, targs,
15017                                          parm, arg);
15018
15019               if (!t)
15020                 {
15021                   /* Fallback to the special case allowed in
15022                      [temp.deduct.call]:
15023
15024                        If P is a class, and P has the form
15025                        template-id, then A can be a derived class of
15026                        the deduced A.  Likewise, if P is a pointer to
15027                        a class of the form template-id, A can be a
15028                        pointer to a derived class pointed to by the
15029                        deduced A.  */
15030                   t = get_template_base (tparms, targs, parm, arg);
15031
15032                   if (!t)
15033                     return 1;
15034                 }
15035             }
15036           else if (CLASSTYPE_TEMPLATE_INFO (arg)
15037                    && (CLASSTYPE_TI_TEMPLATE (parm)
15038                        == CLASSTYPE_TI_TEMPLATE (arg)))
15039             /* Perhaps PARM is something like S<U> and ARG is S<int>.
15040                Then, we should unify `int' and `U'.  */
15041             t = arg;
15042           else
15043             /* There's no chance of unification succeeding.  */
15044             return 1;
15045
15046           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
15047                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
15048         }
15049       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
15050         return 1;
15051       return 0;
15052
15053     case METHOD_TYPE:
15054     case FUNCTION_TYPE:
15055       {
15056         unsigned int nargs;
15057         tree *args;
15058         tree a;
15059         unsigned int i;
15060
15061         if (TREE_CODE (arg) != TREE_CODE (parm))
15062           return 1;
15063
15064         /* CV qualifications for methods can never be deduced, they must
15065            match exactly.  We need to check them explicitly here,
15066            because type_unification_real treats them as any other
15067            cv-qualified parameter.  */
15068         if (TREE_CODE (parm) == METHOD_TYPE
15069             && (!check_cv_quals_for_unify
15070                 (UNIFY_ALLOW_NONE,
15071                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
15072                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
15073           return 1;
15074
15075         if (unify (tparms, targs, TREE_TYPE (parm),
15076                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
15077           return 1;
15078
15079         nargs = list_length (TYPE_ARG_TYPES (arg));
15080         args = XALLOCAVEC (tree, nargs);
15081         for (a = TYPE_ARG_TYPES (arg), i = 0;
15082              a != NULL_TREE && a != void_list_node;
15083              a = TREE_CHAIN (a), ++i)
15084           args[i] = TREE_VALUE (a);
15085         nargs = i;
15086
15087         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
15088                                       args, nargs, 1, DEDUCE_EXACT,
15089                                       LOOKUP_NORMAL);
15090       }
15091
15092     case OFFSET_TYPE:
15093       /* Unify a pointer to member with a pointer to member function, which
15094          deduces the type of the member as a function type. */
15095       if (TYPE_PTRMEMFUNC_P (arg))
15096         {
15097           tree method_type;
15098           tree fntype;
15099
15100           /* Check top-level cv qualifiers */
15101           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
15102             return 1;
15103
15104           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15105                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
15106             return 1;
15107
15108           /* Determine the type of the function we are unifying against. */
15109           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
15110           fntype =
15111             build_function_type (TREE_TYPE (method_type),
15112                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
15113
15114           /* Extract the cv-qualifiers of the member function from the
15115              implicit object parameter and place them on the function
15116              type to be restored later. */
15117           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
15118           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
15119         }
15120
15121       if (TREE_CODE (arg) != OFFSET_TYPE)
15122         return 1;
15123       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15124                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
15125         return 1;
15126       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15127                     strict);
15128
15129     case CONST_DECL:
15130       if (DECL_TEMPLATE_PARM_P (parm))
15131         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
15132       if (arg != integral_constant_value (parm))
15133         return 1;
15134       return 0;
15135
15136     case FIELD_DECL:
15137     case TEMPLATE_DECL:
15138       /* Matched cases are handled by the ARG == PARM test above.  */
15139       return 1;
15140
15141     case VAR_DECL:
15142       /* A non-type template parameter that is a variable should be a
15143          an integral constant, in which case, it whould have been
15144          folded into its (constant) value. So we should not be getting
15145          a variable here.  */
15146       gcc_unreachable ();
15147
15148     case TYPE_ARGUMENT_PACK:
15149     case NONTYPE_ARGUMENT_PACK:
15150       {
15151         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
15152         tree packed_args = ARGUMENT_PACK_ARGS (arg);
15153         int i, len = TREE_VEC_LENGTH (packed_parms);
15154         int argslen = TREE_VEC_LENGTH (packed_args);
15155         int parm_variadic_p = 0;
15156
15157         for (i = 0; i < len; ++i)
15158           {
15159             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
15160               {
15161                 if (i == len - 1)
15162                   /* We can unify against something with a trailing
15163                      parameter pack.  */
15164                   parm_variadic_p = 1;
15165                 else
15166                   /* Since there is something following the pack
15167                      expansion, we cannot unify this template argument
15168                      list.  */
15169                   return 0;
15170               }
15171           }
15172           
15173
15174         /* If we don't have enough arguments to satisfy the parameters
15175            (not counting the pack expression at the end), or we have
15176            too many arguments for a parameter list that doesn't end in
15177            a pack expression, we can't unify.  */
15178         if (argslen < (len - parm_variadic_p)
15179             || (argslen > len && !parm_variadic_p))
15180           return 1;
15181
15182         /* Unify all of the parameters that precede the (optional)
15183            pack expression.  */
15184         for (i = 0; i < len - parm_variadic_p; ++i)
15185           {
15186             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15187                        TREE_VEC_ELT (packed_args, i), strict))
15188               return 1;
15189           }
15190
15191         if (parm_variadic_p)
15192           return unify_pack_expansion (tparms, targs, 
15193                                        packed_parms, packed_args,
15194                                        strict, /*call_args_p=*/false,
15195                                        /*subr=*/false);
15196         return 0;
15197       }
15198
15199       break;
15200
15201     case TYPEOF_TYPE:
15202     case DECLTYPE_TYPE:
15203       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
15204          nodes.  */
15205       return 0;
15206
15207     case ERROR_MARK:
15208       /* Unification fails if we hit an error node.  */
15209       return 1;
15210
15211     default:
15212       gcc_assert (EXPR_P (parm));
15213
15214       /* We must be looking at an expression.  This can happen with
15215          something like:
15216
15217            template <int I>
15218            void foo(S<I>, S<I + 2>);
15219
15220          This is a "nondeduced context":
15221
15222            [deduct.type]
15223
15224            The nondeduced contexts are:
15225
15226            --A type that is a template-id in which one or more of
15227              the template-arguments is an expression that references
15228              a template-parameter.
15229
15230          In these cases, we assume deduction succeeded, but don't
15231          actually infer any unifications.  */
15232
15233       if (!uses_template_parms (parm)
15234           && !template_args_equal (parm, arg))
15235         return 1;
15236       else
15237         return 0;
15238     }
15239 }
15240 \f
15241 /* Note that DECL can be defined in this translation unit, if
15242    required.  */
15243
15244 static void
15245 mark_definable (tree decl)
15246 {
15247   tree clone;
15248   DECL_NOT_REALLY_EXTERN (decl) = 1;
15249   FOR_EACH_CLONE (clone, decl)
15250     DECL_NOT_REALLY_EXTERN (clone) = 1;
15251 }
15252
15253 /* Called if RESULT is explicitly instantiated, or is a member of an
15254    explicitly instantiated class.  */
15255
15256 void
15257 mark_decl_instantiated (tree result, int extern_p)
15258 {
15259   SET_DECL_EXPLICIT_INSTANTIATION (result);
15260
15261   /* If this entity has already been written out, it's too late to
15262      make any modifications.  */
15263   if (TREE_ASM_WRITTEN (result))
15264     return;
15265
15266   if (TREE_CODE (result) != FUNCTION_DECL)
15267     /* The TREE_PUBLIC flag for function declarations will have been
15268        set correctly by tsubst.  */
15269     TREE_PUBLIC (result) = 1;
15270
15271   /* This might have been set by an earlier implicit instantiation.  */
15272   DECL_COMDAT (result) = 0;
15273
15274   if (extern_p)
15275     DECL_NOT_REALLY_EXTERN (result) = 0;
15276   else
15277     {
15278       mark_definable (result);
15279       /* Always make artificials weak.  */
15280       if (DECL_ARTIFICIAL (result) && flag_weak)
15281         comdat_linkage (result);
15282       /* For WIN32 we also want to put explicit instantiations in
15283          linkonce sections.  */
15284       else if (TREE_PUBLIC (result))
15285         maybe_make_one_only (result);
15286     }
15287
15288   /* If EXTERN_P, then this function will not be emitted -- unless
15289      followed by an explicit instantiation, at which point its linkage
15290      will be adjusted.  If !EXTERN_P, then this function will be
15291      emitted here.  In neither circumstance do we want
15292      import_export_decl to adjust the linkage.  */
15293   DECL_INTERFACE_KNOWN (result) = 1;
15294 }
15295
15296 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
15297    important template arguments.  If any are missing, we check whether
15298    they're important by using error_mark_node for substituting into any
15299    args that were used for partial ordering (the ones between ARGS and END)
15300    and seeing if it bubbles up.  */
15301
15302 static bool
15303 check_undeduced_parms (tree targs, tree args, tree end)
15304 {
15305   bool found = false;
15306   int i;
15307   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
15308     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
15309       {
15310         found = true;
15311         TREE_VEC_ELT (targs, i) = error_mark_node;
15312       }
15313   if (found)
15314     {
15315       for (; args != end; args = TREE_CHAIN (args))
15316         {
15317           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
15318           if (substed == error_mark_node)
15319             return true;
15320         }
15321     }
15322   return false;
15323 }
15324
15325 /* Given two function templates PAT1 and PAT2, return:
15326
15327    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
15328    -1 if PAT2 is more specialized than PAT1.
15329    0 if neither is more specialized.
15330
15331    LEN indicates the number of parameters we should consider
15332    (defaulted parameters should not be considered).
15333
15334    The 1998 std underspecified function template partial ordering, and
15335    DR214 addresses the issue.  We take pairs of arguments, one from
15336    each of the templates, and deduce them against each other.  One of
15337    the templates will be more specialized if all the *other*
15338    template's arguments deduce against its arguments and at least one
15339    of its arguments *does* *not* deduce against the other template's
15340    corresponding argument.  Deduction is done as for class templates.
15341    The arguments used in deduction have reference and top level cv
15342    qualifiers removed.  Iff both arguments were originally reference
15343    types *and* deduction succeeds in both directions, the template
15344    with the more cv-qualified argument wins for that pairing (if
15345    neither is more cv-qualified, they both are equal).  Unlike regular
15346    deduction, after all the arguments have been deduced in this way,
15347    we do *not* verify the deduced template argument values can be
15348    substituted into non-deduced contexts.
15349
15350    The logic can be a bit confusing here, because we look at deduce1 and
15351    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15352    can find template arguments for pat1 to make arg1 look like arg2, that
15353    means that arg2 is at least as specialized as arg1.  */
15354
15355 int
15356 more_specialized_fn (tree pat1, tree pat2, int len)
15357 {
15358   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15359   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15360   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15361   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15362   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15363   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15364   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15365   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15366   tree origs1, origs2;
15367   bool lose1 = false;
15368   bool lose2 = false;
15369
15370   /* Remove the this parameter from non-static member functions.  If
15371      one is a non-static member function and the other is not a static
15372      member function, remove the first parameter from that function
15373      also.  This situation occurs for operator functions where we
15374      locate both a member function (with this pointer) and non-member
15375      operator (with explicit first operand).  */
15376   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15377     {
15378       len--; /* LEN is the number of significant arguments for DECL1 */
15379       args1 = TREE_CHAIN (args1);
15380       if (!DECL_STATIC_FUNCTION_P (decl2))
15381         args2 = TREE_CHAIN (args2);
15382     }
15383   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15384     {
15385       args2 = TREE_CHAIN (args2);
15386       if (!DECL_STATIC_FUNCTION_P (decl1))
15387         {
15388           len--;
15389           args1 = TREE_CHAIN (args1);
15390         }
15391     }
15392
15393   /* If only one is a conversion operator, they are unordered.  */
15394   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15395     return 0;
15396
15397   /* Consider the return type for a conversion function */
15398   if (DECL_CONV_FN_P (decl1))
15399     {
15400       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15401       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15402       len++;
15403     }
15404
15405   processing_template_decl++;
15406
15407   origs1 = args1;
15408   origs2 = args2;
15409
15410   while (len--
15411          /* Stop when an ellipsis is seen.  */
15412          && args1 != NULL_TREE && args2 != NULL_TREE)
15413     {
15414       tree arg1 = TREE_VALUE (args1);
15415       tree arg2 = TREE_VALUE (args2);
15416       int deduce1, deduce2;
15417       int quals1 = -1;
15418       int quals2 = -1;
15419
15420       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15421           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15422         {
15423           /* When both arguments are pack expansions, we need only
15424              unify the patterns themselves.  */
15425           arg1 = PACK_EXPANSION_PATTERN (arg1);
15426           arg2 = PACK_EXPANSION_PATTERN (arg2);
15427
15428           /* This is the last comparison we need to do.  */
15429           len = 0;
15430         }
15431
15432       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15433         {
15434           arg1 = TREE_TYPE (arg1);
15435           quals1 = cp_type_quals (arg1);
15436         }
15437
15438       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15439         {
15440           arg2 = TREE_TYPE (arg2);
15441           quals2 = cp_type_quals (arg2);
15442         }
15443
15444       if ((quals1 < 0) != (quals2 < 0))
15445         {
15446           /* Only of the args is a reference, see if we should apply
15447              array/function pointer decay to it.  This is not part of
15448              DR214, but is, IMHO, consistent with the deduction rules
15449              for the function call itself, and with our earlier
15450              implementation of the underspecified partial ordering
15451              rules.  (nathan).  */
15452           if (quals1 >= 0)
15453             {
15454               switch (TREE_CODE (arg1))
15455                 {
15456                 case ARRAY_TYPE:
15457                   arg1 = TREE_TYPE (arg1);
15458                   /* FALLTHROUGH. */
15459                 case FUNCTION_TYPE:
15460                   arg1 = build_pointer_type (arg1);
15461                   break;
15462
15463                 default:
15464                   break;
15465                 }
15466             }
15467           else
15468             {
15469               switch (TREE_CODE (arg2))
15470                 {
15471                 case ARRAY_TYPE:
15472                   arg2 = TREE_TYPE (arg2);
15473                   /* FALLTHROUGH. */
15474                 case FUNCTION_TYPE:
15475                   arg2 = build_pointer_type (arg2);
15476                   break;
15477
15478                 default:
15479                   break;
15480                 }
15481             }
15482         }
15483
15484       arg1 = TYPE_MAIN_VARIANT (arg1);
15485       arg2 = TYPE_MAIN_VARIANT (arg2);
15486
15487       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15488         {
15489           int i, len2 = list_length (args2);
15490           tree parmvec = make_tree_vec (1);
15491           tree argvec = make_tree_vec (len2);
15492           tree ta = args2;
15493
15494           /* Setup the parameter vector, which contains only ARG1.  */
15495           TREE_VEC_ELT (parmvec, 0) = arg1;
15496
15497           /* Setup the argument vector, which contains the remaining
15498              arguments.  */
15499           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15500             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15501
15502           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15503                                            argvec, UNIFY_ALLOW_NONE, 
15504                                            /*call_args_p=*/false, 
15505                                            /*subr=*/0);
15506
15507           /* We cannot deduce in the other direction, because ARG1 is
15508              a pack expansion but ARG2 is not.  */
15509           deduce2 = 0;
15510         }
15511       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15512         {
15513           int i, len1 = list_length (args1);
15514           tree parmvec = make_tree_vec (1);
15515           tree argvec = make_tree_vec (len1);
15516           tree ta = args1;
15517
15518           /* Setup the parameter vector, which contains only ARG1.  */
15519           TREE_VEC_ELT (parmvec, 0) = arg2;
15520
15521           /* Setup the argument vector, which contains the remaining
15522              arguments.  */
15523           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15524             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15525
15526           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15527                                            argvec, UNIFY_ALLOW_NONE, 
15528                                            /*call_args_p=*/false, 
15529                                            /*subr=*/0);
15530
15531           /* We cannot deduce in the other direction, because ARG2 is
15532              a pack expansion but ARG1 is not.*/
15533           deduce1 = 0;
15534         }
15535
15536       else
15537         {
15538           /* The normal case, where neither argument is a pack
15539              expansion.  */
15540           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15541           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15542         }
15543
15544       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15545          arg2, then arg2 is not as specialized as arg1.  */
15546       if (!deduce1)
15547         lose2 = true;
15548       if (!deduce2)
15549         lose1 = true;
15550
15551       /* "If, for a given type, deduction succeeds in both directions
15552          (i.e., the types are identical after the transformations above)
15553          and if the type from the argument template is more cv-qualified
15554          than the type from the parameter template (as described above)
15555          that type is considered to be more specialized than the other. If
15556          neither type is more cv-qualified than the other then neither type
15557          is more specialized than the other."  */
15558
15559       if (deduce1 && deduce2
15560           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
15561         {
15562           if ((quals1 & quals2) == quals2)
15563             lose2 = true;
15564           if ((quals1 & quals2) == quals1)
15565             lose1 = true;
15566         }
15567
15568       if (lose1 && lose2)
15569         /* We've failed to deduce something in either direction.
15570            These must be unordered.  */
15571         break;
15572
15573       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15574           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15575         /* We have already processed all of the arguments in our
15576            handing of the pack expansion type.  */
15577         len = 0;
15578
15579       args1 = TREE_CHAIN (args1);
15580       args2 = TREE_CHAIN (args2);
15581     }
15582
15583   /* "In most cases, all template parameters must have values in order for
15584      deduction to succeed, but for partial ordering purposes a template
15585      parameter may remain without a value provided it is not used in the
15586      types being used for partial ordering."
15587
15588      Thus, if we are missing any of the targs1 we need to substitute into
15589      origs1, then pat2 is not as specialized as pat1.  This can happen when
15590      there is a nondeduced context.  */
15591   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15592     lose2 = true;
15593   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15594     lose1 = true;
15595
15596   processing_template_decl--;
15597
15598   /* All things being equal, if the next argument is a pack expansion
15599      for one function but not for the other, prefer the
15600      non-variadic function.  FIXME this is bogus; see c++/41958.  */
15601   if (lose1 == lose2
15602       && args1 && TREE_VALUE (args1)
15603       && args2 && TREE_VALUE (args2))
15604     {
15605       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15606       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15607     }
15608
15609   if (lose1 == lose2)
15610     return 0;
15611   else if (!lose1)
15612     return 1;
15613   else
15614     return -1;
15615 }
15616
15617 /* Determine which of two partial specializations is more specialized.
15618
15619    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15620    to the first partial specialization.  The TREE_VALUE is the
15621    innermost set of template parameters for the partial
15622    specialization.  PAT2 is similar, but for the second template.
15623
15624    Return 1 if the first partial specialization is more specialized;
15625    -1 if the second is more specialized; 0 if neither is more
15626    specialized.
15627
15628    See [temp.class.order] for information about determining which of
15629    two templates is more specialized.  */
15630
15631 static int
15632 more_specialized_class (tree pat1, tree pat2)
15633 {
15634   tree targs;
15635   tree tmpl1, tmpl2;
15636   int winner = 0;
15637   bool any_deductions = false;
15638
15639   tmpl1 = TREE_TYPE (pat1);
15640   tmpl2 = TREE_TYPE (pat2);
15641
15642   /* Just like what happens for functions, if we are ordering between
15643      different class template specializations, we may encounter dependent
15644      types in the arguments, and we need our dependency check functions
15645      to behave correctly.  */
15646   ++processing_template_decl;
15647   targs = get_class_bindings (TREE_VALUE (pat1),
15648                               CLASSTYPE_TI_ARGS (tmpl1),
15649                               CLASSTYPE_TI_ARGS (tmpl2));
15650   if (targs)
15651     {
15652       --winner;
15653       any_deductions = true;
15654     }
15655
15656   targs = get_class_bindings (TREE_VALUE (pat2),
15657                               CLASSTYPE_TI_ARGS (tmpl2),
15658                               CLASSTYPE_TI_ARGS (tmpl1));
15659   if (targs)
15660     {
15661       ++winner;
15662       any_deductions = true;
15663     }
15664   --processing_template_decl;
15665
15666   /* In the case of a tie where at least one of the class templates
15667      has a parameter pack at the end, the template with the most
15668      non-packed parameters wins.  */
15669   if (winner == 0
15670       && any_deductions
15671       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15672           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15673     {
15674       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15675       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15676       int len1 = TREE_VEC_LENGTH (args1);
15677       int len2 = TREE_VEC_LENGTH (args2);
15678
15679       /* We don't count the pack expansion at the end.  */
15680       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15681         --len1;
15682       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15683         --len2;
15684
15685       if (len1 > len2)
15686         return 1;
15687       else if (len1 < len2)
15688         return -1;
15689     }
15690
15691   return winner;
15692 }
15693
15694 /* Return the template arguments that will produce the function signature
15695    DECL from the function template FN, with the explicit template
15696    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15697    also match.  Return NULL_TREE if no satisfactory arguments could be
15698    found.  */
15699
15700 static tree
15701 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15702 {
15703   int ntparms = DECL_NTPARMS (fn);
15704   tree targs = make_tree_vec (ntparms);
15705   tree decl_type;
15706   tree decl_arg_types;
15707   tree *args;
15708   unsigned int nargs, ix;
15709   tree arg;
15710
15711   /* Substitute the explicit template arguments into the type of DECL.
15712      The call to fn_type_unification will handle substitution into the
15713      FN.  */
15714   decl_type = TREE_TYPE (decl);
15715   if (explicit_args && uses_template_parms (decl_type))
15716     {
15717       tree tmpl;
15718       tree converted_args;
15719
15720       if (DECL_TEMPLATE_INFO (decl))
15721         tmpl = DECL_TI_TEMPLATE (decl);
15722       else
15723         /* We can get here for some invalid specializations.  */
15724         return NULL_TREE;
15725
15726       converted_args
15727         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15728                                  explicit_args, NULL_TREE,
15729                                  tf_none,
15730                                  /*require_all_args=*/false,
15731                                  /*use_default_args=*/false);
15732       if (converted_args == error_mark_node)
15733         return NULL_TREE;
15734
15735       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15736       if (decl_type == error_mark_node)
15737         return NULL_TREE;
15738     }
15739
15740   /* Never do unification on the 'this' parameter.  */
15741   decl_arg_types = skip_artificial_parms_for (decl, 
15742                                               TYPE_ARG_TYPES (decl_type));
15743
15744   nargs = list_length (decl_arg_types);
15745   args = XALLOCAVEC (tree, nargs);
15746   for (arg = decl_arg_types, ix = 0;
15747        arg != NULL_TREE && arg != void_list_node;
15748        arg = TREE_CHAIN (arg), ++ix)
15749     args[ix] = TREE_VALUE (arg);
15750
15751   if (fn_type_unification (fn, explicit_args, targs,
15752                            args, ix,
15753                            (check_rettype || DECL_CONV_FN_P (fn)
15754                             ? TREE_TYPE (decl_type) : NULL_TREE),
15755                            DEDUCE_EXACT, LOOKUP_NORMAL))
15756     return NULL_TREE;
15757
15758   return targs;
15759 }
15760
15761 /* Return the innermost template arguments that, when applied to a
15762    template specialization whose innermost template parameters are
15763    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15764    ARGS.
15765
15766    For example, suppose we have:
15767
15768      template <class T, class U> struct S {};
15769      template <class T> struct S<T*, int> {};
15770
15771    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15772    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15773    int}.  The resulting vector will be {double}, indicating that `T'
15774    is bound to `double'.  */
15775
15776 static tree
15777 get_class_bindings (tree tparms, tree spec_args, tree args)
15778 {
15779   int i, ntparms = TREE_VEC_LENGTH (tparms);
15780   tree deduced_args;
15781   tree innermost_deduced_args;
15782
15783   innermost_deduced_args = make_tree_vec (ntparms);
15784   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15785     {
15786       deduced_args = copy_node (args);
15787       SET_TMPL_ARGS_LEVEL (deduced_args,
15788                            TMPL_ARGS_DEPTH (deduced_args),
15789                            innermost_deduced_args);
15790     }
15791   else
15792     deduced_args = innermost_deduced_args;
15793
15794   if (unify (tparms, deduced_args,
15795              INNERMOST_TEMPLATE_ARGS (spec_args),
15796              INNERMOST_TEMPLATE_ARGS (args),
15797              UNIFY_ALLOW_NONE))
15798     return NULL_TREE;
15799
15800   for (i =  0; i < ntparms; ++i)
15801     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15802       return NULL_TREE;
15803
15804   /* Verify that nondeduced template arguments agree with the type
15805      obtained from argument deduction.
15806
15807      For example:
15808
15809        struct A { typedef int X; };
15810        template <class T, class U> struct C {};
15811        template <class T> struct C<T, typename T::X> {};
15812
15813      Then with the instantiation `C<A, int>', we can deduce that
15814      `T' is `A' but unify () does not check whether `typename T::X'
15815      is `int'.  */
15816   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15817   if (spec_args == error_mark_node
15818       /* We only need to check the innermost arguments; the other
15819          arguments will always agree.  */
15820       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15821                               INNERMOST_TEMPLATE_ARGS (args)))
15822     return NULL_TREE;
15823
15824   /* Now that we have bindings for all of the template arguments,
15825      ensure that the arguments deduced for the template template
15826      parameters have compatible template parameter lists.  See the use
15827      of template_template_parm_bindings_ok_p in fn_type_unification
15828      for more information.  */
15829   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15830     return NULL_TREE;
15831
15832   return deduced_args;
15833 }
15834
15835 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15836    Return the TREE_LIST node with the most specialized template, if
15837    any.  If there is no most specialized template, the error_mark_node
15838    is returned.
15839
15840    Note that this function does not look at, or modify, the
15841    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15842    returned is one of the elements of INSTANTIATIONS, callers may
15843    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15844    and retrieve it from the value returned.  */
15845
15846 tree
15847 most_specialized_instantiation (tree templates)
15848 {
15849   tree fn, champ;
15850
15851   ++processing_template_decl;
15852
15853   champ = templates;
15854   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15855     {
15856       int fate = 0;
15857
15858       if (get_bindings (TREE_VALUE (champ),
15859                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15860                         NULL_TREE, /*check_ret=*/false))
15861         fate--;
15862
15863       if (get_bindings (TREE_VALUE (fn),
15864                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15865                         NULL_TREE, /*check_ret=*/false))
15866         fate++;
15867
15868       if (fate == -1)
15869         champ = fn;
15870       else if (!fate)
15871         {
15872           /* Equally specialized, move to next function.  If there
15873              is no next function, nothing's most specialized.  */
15874           fn = TREE_CHAIN (fn);
15875           champ = fn;
15876           if (!fn)
15877             break;
15878         }
15879     }
15880
15881   if (champ)
15882     /* Now verify that champ is better than everything earlier in the
15883        instantiation list.  */
15884     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15885       if (get_bindings (TREE_VALUE (champ),
15886                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15887                         NULL_TREE, /*check_ret=*/false)
15888           || !get_bindings (TREE_VALUE (fn),
15889                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15890                             NULL_TREE, /*check_ret=*/false))
15891         {
15892           champ = NULL_TREE;
15893           break;
15894         }
15895
15896   processing_template_decl--;
15897
15898   if (!champ)
15899     return error_mark_node;
15900
15901   return champ;
15902 }
15903
15904 /* If DECL is a specialization of some template, return the most
15905    general such template.  Otherwise, returns NULL_TREE.
15906
15907    For example, given:
15908
15909      template <class T> struct S { template <class U> void f(U); };
15910
15911    if TMPL is `template <class U> void S<int>::f(U)' this will return
15912    the full template.  This function will not trace past partial
15913    specializations, however.  For example, given in addition:
15914
15915      template <class T> struct S<T*> { template <class U> void f(U); };
15916
15917    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15918    `template <class T> template <class U> S<T*>::f(U)'.  */
15919
15920 tree
15921 most_general_template (tree decl)
15922 {
15923   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15924      an immediate specialization.  */
15925   if (TREE_CODE (decl) == FUNCTION_DECL)
15926     {
15927       if (DECL_TEMPLATE_INFO (decl)) {
15928         decl = DECL_TI_TEMPLATE (decl);
15929
15930         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15931            template friend.  */
15932         if (TREE_CODE (decl) != TEMPLATE_DECL)
15933           return NULL_TREE;
15934       } else
15935         return NULL_TREE;
15936     }
15937
15938   /* Look for more and more general templates.  */
15939   while (DECL_TEMPLATE_INFO (decl))
15940     {
15941       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15942          (See cp-tree.h for details.)  */
15943       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15944         break;
15945
15946       if (CLASS_TYPE_P (TREE_TYPE (decl))
15947           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15948         break;
15949
15950       /* Stop if we run into an explicitly specialized class template.  */
15951       if (!DECL_NAMESPACE_SCOPE_P (decl)
15952           && DECL_CONTEXT (decl)
15953           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15954         break;
15955
15956       decl = DECL_TI_TEMPLATE (decl);
15957     }
15958
15959   return decl;
15960 }
15961
15962 /* Return the most specialized of the class template partial
15963    specializations of TMPL which can produce TYPE, a specialization of
15964    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15965    a _TYPE node corresponding to the partial specialization, while the
15966    TREE_PURPOSE is the set of template arguments that must be
15967    substituted into the TREE_TYPE in order to generate TYPE.
15968
15969    If the choice of partial specialization is ambiguous, a diagnostic
15970    is issued, and the error_mark_node is returned.  If there are no
15971    partial specializations of TMPL matching TYPE, then NULL_TREE is
15972    returned.  */
15973
15974 static tree
15975 most_specialized_class (tree type, tree tmpl)
15976 {
15977   tree list = NULL_TREE;
15978   tree t;
15979   tree champ;
15980   int fate;
15981   bool ambiguous_p;
15982   tree args;
15983   tree outer_args = NULL_TREE;
15984
15985   tmpl = most_general_template (tmpl);
15986   args = CLASSTYPE_TI_ARGS (type);
15987
15988   /* For determining which partial specialization to use, only the
15989      innermost args are interesting.  */
15990   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15991     {
15992       outer_args = strip_innermost_template_args (args, 1);
15993       args = INNERMOST_TEMPLATE_ARGS (args);
15994     }
15995
15996   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15997     {
15998       tree partial_spec_args;
15999       tree spec_args;
16000       tree parms = TREE_VALUE (t);
16001
16002       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
16003
16004       ++processing_template_decl;
16005
16006       if (outer_args)
16007         {
16008           int i;
16009
16010           /* Discard the outer levels of args, and then substitute in the
16011              template args from the enclosing class.  */
16012           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
16013           partial_spec_args = tsubst_template_args
16014             (partial_spec_args, outer_args, tf_none, NULL_TREE);
16015
16016           /* PARMS already refers to just the innermost parms, but the
16017              template parms in partial_spec_args had their levels lowered
16018              by tsubst, so we need to do the same for the parm list.  We
16019              can't just tsubst the TREE_VEC itself, as tsubst wants to
16020              treat a TREE_VEC as an argument vector.  */
16021           parms = copy_node (parms);
16022           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
16023             TREE_VEC_ELT (parms, i) =
16024               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
16025
16026         }
16027
16028       partial_spec_args =
16029           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16030                                  add_to_template_args (outer_args,
16031                                                        partial_spec_args),
16032                                  tmpl, tf_none,
16033                                  /*require_all_args=*/true,
16034                                  /*use_default_args=*/true);
16035
16036       --processing_template_decl;
16037
16038       if (partial_spec_args == error_mark_node)
16039         return error_mark_node;
16040
16041       spec_args = get_class_bindings (parms,
16042                                       partial_spec_args,
16043                                       args);
16044       if (spec_args)
16045         {
16046           if (outer_args)
16047             spec_args = add_to_template_args (outer_args, spec_args);
16048           list = tree_cons (spec_args, TREE_VALUE (t), list);
16049           TREE_TYPE (list) = TREE_TYPE (t);
16050         }
16051     }
16052
16053   if (! list)
16054     return NULL_TREE;
16055
16056   ambiguous_p = false;
16057   t = list;
16058   champ = t;
16059   t = TREE_CHAIN (t);
16060   for (; t; t = TREE_CHAIN (t))
16061     {
16062       fate = more_specialized_class (champ, t);
16063       if (fate == 1)
16064         ;
16065       else
16066         {
16067           if (fate == 0)
16068             {
16069               t = TREE_CHAIN (t);
16070               if (! t)
16071                 {
16072                   ambiguous_p = true;
16073                   break;
16074                 }
16075             }
16076           champ = t;
16077         }
16078     }
16079
16080   if (!ambiguous_p)
16081     for (t = list; t && t != champ; t = TREE_CHAIN (t))
16082       {
16083         fate = more_specialized_class (champ, t);
16084         if (fate != 1)
16085           {
16086             ambiguous_p = true;
16087             break;
16088           }
16089       }
16090
16091   if (ambiguous_p)
16092     {
16093       const char *str;
16094       char *spaces = NULL;
16095       error ("ambiguous class template instantiation for %q#T", type);
16096       str = TREE_CHAIN (list) ? _("candidates are:") : _("candidate is:");
16097       for (t = list; t; t = TREE_CHAIN (t))
16098         {
16099           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
16100           spaces = spaces ? spaces : get_spaces (str);
16101         }
16102       free (spaces);
16103       return error_mark_node;
16104     }
16105
16106   return champ;
16107 }
16108
16109 /* Explicitly instantiate DECL.  */
16110
16111 void
16112 do_decl_instantiation (tree decl, tree storage)
16113 {
16114   tree result = NULL_TREE;
16115   int extern_p = 0;
16116
16117   if (!decl || decl == error_mark_node)
16118     /* An error occurred, for which grokdeclarator has already issued
16119        an appropriate message.  */
16120     return;
16121   else if (! DECL_LANG_SPECIFIC (decl))
16122     {
16123       error ("explicit instantiation of non-template %q#D", decl);
16124       return;
16125     }
16126   else if (TREE_CODE (decl) == VAR_DECL)
16127     {
16128       /* There is an asymmetry here in the way VAR_DECLs and
16129          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
16130          the latter, the DECL we get back will be marked as a
16131          template instantiation, and the appropriate
16132          DECL_TEMPLATE_INFO will be set up.  This does not happen for
16133          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
16134          should handle VAR_DECLs as it currently handles
16135          FUNCTION_DECLs.  */
16136       if (!DECL_CLASS_SCOPE_P (decl))
16137         {
16138           error ("%qD is not a static data member of a class template", decl);
16139           return;
16140         }
16141       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
16142       if (!result || TREE_CODE (result) != VAR_DECL)
16143         {
16144           error ("no matching template for %qD found", decl);
16145           return;
16146         }
16147       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
16148         {
16149           error ("type %qT for explicit instantiation %qD does not match "
16150                  "declared type %qT", TREE_TYPE (result), decl,
16151                  TREE_TYPE (decl));
16152           return;
16153         }
16154     }
16155   else if (TREE_CODE (decl) != FUNCTION_DECL)
16156     {
16157       error ("explicit instantiation of %q#D", decl);
16158       return;
16159     }
16160   else
16161     result = decl;
16162
16163   /* Check for various error cases.  Note that if the explicit
16164      instantiation is valid the RESULT will currently be marked as an
16165      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
16166      until we get here.  */
16167
16168   if (DECL_TEMPLATE_SPECIALIZATION (result))
16169     {
16170       /* DR 259 [temp.spec].
16171
16172          Both an explicit instantiation and a declaration of an explicit
16173          specialization shall not appear in a program unless the explicit
16174          instantiation follows a declaration of the explicit specialization.
16175
16176          For a given set of template parameters, if an explicit
16177          instantiation of a template appears after a declaration of an
16178          explicit specialization for that template, the explicit
16179          instantiation has no effect.  */
16180       return;
16181     }
16182   else if (DECL_EXPLICIT_INSTANTIATION (result))
16183     {
16184       /* [temp.spec]
16185
16186          No program shall explicitly instantiate any template more
16187          than once.
16188
16189          We check DECL_NOT_REALLY_EXTERN so as not to complain when
16190          the first instantiation was `extern' and the second is not,
16191          and EXTERN_P for the opposite case.  */
16192       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16193         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16194       /* If an "extern" explicit instantiation follows an ordinary
16195          explicit instantiation, the template is instantiated.  */
16196       if (extern_p)
16197         return;
16198     }
16199   else if (!DECL_IMPLICIT_INSTANTIATION (result))
16200     {
16201       error ("no matching template for %qD found", result);
16202       return;
16203     }
16204   else if (!DECL_TEMPLATE_INFO (result))
16205     {
16206       permerror (input_location, "explicit instantiation of non-template %q#D", result);
16207       return;
16208     }
16209
16210   if (storage == NULL_TREE)
16211     ;
16212   else if (storage == ridpointers[(int) RID_EXTERN])
16213     {
16214       if (!in_system_header && (cxx_dialect == cxx98))
16215         pedwarn (input_location, OPT_pedantic, 
16216                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16217                  "instantiations");
16218       extern_p = 1;
16219     }
16220   else
16221     error ("storage class %qD applied to template instantiation", storage);
16222
16223   check_explicit_instantiation_namespace (result);
16224   mark_decl_instantiated (result, extern_p);
16225   if (! extern_p)
16226     instantiate_decl (result, /*defer_ok=*/1,
16227                       /*expl_inst_class_mem_p=*/false);
16228 }
16229
16230 static void
16231 mark_class_instantiated (tree t, int extern_p)
16232 {
16233   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
16234   SET_CLASSTYPE_INTERFACE_KNOWN (t);
16235   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
16236   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
16237   if (! extern_p)
16238     {
16239       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
16240       rest_of_type_compilation (t, 1);
16241     }
16242 }
16243
16244 /* Called from do_type_instantiation through binding_table_foreach to
16245    do recursive instantiation for the type bound in ENTRY.  */
16246 static void
16247 bt_instantiate_type_proc (binding_entry entry, void *data)
16248 {
16249   tree storage = *(tree *) data;
16250
16251   if (MAYBE_CLASS_TYPE_P (entry->type)
16252       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
16253     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
16254 }
16255
16256 /* Called from do_type_instantiation to instantiate a member
16257    (a member function or a static member variable) of an
16258    explicitly instantiated class template.  */
16259 static void
16260 instantiate_class_member (tree decl, int extern_p)
16261 {
16262   mark_decl_instantiated (decl, extern_p);
16263   if (! extern_p)
16264     instantiate_decl (decl, /*defer_ok=*/1,
16265                       /*expl_inst_class_mem_p=*/true);
16266 }
16267
16268 /* Perform an explicit instantiation of template class T.  STORAGE, if
16269    non-null, is the RID for extern, inline or static.  COMPLAIN is
16270    nonzero if this is called from the parser, zero if called recursively,
16271    since the standard is unclear (as detailed below).  */
16272
16273 void
16274 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
16275 {
16276   int extern_p = 0;
16277   int nomem_p = 0;
16278   int static_p = 0;
16279   int previous_instantiation_extern_p = 0;
16280
16281   if (TREE_CODE (t) == TYPE_DECL)
16282     t = TREE_TYPE (t);
16283
16284   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
16285     {
16286       error ("explicit instantiation of non-template type %qT", t);
16287       return;
16288     }
16289
16290   complete_type (t);
16291
16292   if (!COMPLETE_TYPE_P (t))
16293     {
16294       if (complain & tf_error)
16295         error ("explicit instantiation of %q#T before definition of template",
16296                t);
16297       return;
16298     }
16299
16300   if (storage != NULL_TREE)
16301     {
16302       if (!in_system_header)
16303         {
16304           if (storage == ridpointers[(int) RID_EXTERN])
16305             {
16306               if (cxx_dialect == cxx98)
16307                 pedwarn (input_location, OPT_pedantic, 
16308                          "ISO C++ 1998 forbids the use of %<extern%> on "
16309                          "explicit instantiations");
16310             }
16311           else
16312             pedwarn (input_location, OPT_pedantic, 
16313                      "ISO C++ forbids the use of %qE"
16314                      " on explicit instantiations", storage);
16315         }
16316
16317       if (storage == ridpointers[(int) RID_INLINE])
16318         nomem_p = 1;
16319       else if (storage == ridpointers[(int) RID_EXTERN])
16320         extern_p = 1;
16321       else if (storage == ridpointers[(int) RID_STATIC])
16322         static_p = 1;
16323       else
16324         {
16325           error ("storage class %qD applied to template instantiation",
16326                  storage);
16327           extern_p = 0;
16328         }
16329     }
16330
16331   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
16332     {
16333       /* DR 259 [temp.spec].
16334
16335          Both an explicit instantiation and a declaration of an explicit
16336          specialization shall not appear in a program unless the explicit
16337          instantiation follows a declaration of the explicit specialization.
16338
16339          For a given set of template parameters, if an explicit
16340          instantiation of a template appears after a declaration of an
16341          explicit specialization for that template, the explicit
16342          instantiation has no effect.  */
16343       return;
16344     }
16345   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
16346     {
16347       /* [temp.spec]
16348
16349          No program shall explicitly instantiate any template more
16350          than once.
16351
16352          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
16353          instantiation was `extern'.  If EXTERN_P then the second is.
16354          These cases are OK.  */
16355       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
16356
16357       if (!previous_instantiation_extern_p && !extern_p
16358           && (complain & tf_error))
16359         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16360
16361       /* If we've already instantiated the template, just return now.  */
16362       if (!CLASSTYPE_INTERFACE_ONLY (t))
16363         return;
16364     }
16365
16366   check_explicit_instantiation_namespace (TYPE_NAME (t));
16367   mark_class_instantiated (t, extern_p);
16368
16369   if (nomem_p)
16370     return;
16371
16372   {
16373     tree tmp;
16374
16375     /* In contrast to implicit instantiation, where only the
16376        declarations, and not the definitions, of members are
16377        instantiated, we have here:
16378
16379          [temp.explicit]
16380
16381          The explicit instantiation of a class template specialization
16382          implies the instantiation of all of its members not
16383          previously explicitly specialized in the translation unit
16384          containing the explicit instantiation.
16385
16386        Of course, we can't instantiate member template classes, since
16387        we don't have any arguments for them.  Note that the standard
16388        is unclear on whether the instantiation of the members are
16389        *explicit* instantiations or not.  However, the most natural
16390        interpretation is that it should be an explicit instantiation.  */
16391
16392     if (! static_p)
16393       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
16394         if (TREE_CODE (tmp) == FUNCTION_DECL
16395             && DECL_TEMPLATE_INSTANTIATION (tmp))
16396           instantiate_class_member (tmp, extern_p);
16397
16398     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
16399       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16400         instantiate_class_member (tmp, extern_p);
16401
16402     if (CLASSTYPE_NESTED_UTDS (t))
16403       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16404                              bt_instantiate_type_proc, &storage);
16405   }
16406 }
16407
16408 /* Given a function DECL, which is a specialization of TMPL, modify
16409    DECL to be a re-instantiation of TMPL with the same template
16410    arguments.  TMPL should be the template into which tsubst'ing
16411    should occur for DECL, not the most general template.
16412
16413    One reason for doing this is a scenario like this:
16414
16415      template <class T>
16416      void f(const T&, int i);
16417
16418      void g() { f(3, 7); }
16419
16420      template <class T>
16421      void f(const T& t, const int i) { }
16422
16423    Note that when the template is first instantiated, with
16424    instantiate_template, the resulting DECL will have no name for the
16425    first parameter, and the wrong type for the second.  So, when we go
16426    to instantiate the DECL, we regenerate it.  */
16427
16428 static void
16429 regenerate_decl_from_template (tree decl, tree tmpl)
16430 {
16431   /* The arguments used to instantiate DECL, from the most general
16432      template.  */
16433   tree args;
16434   tree code_pattern;
16435
16436   args = DECL_TI_ARGS (decl);
16437   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16438
16439   /* Make sure that we can see identifiers, and compute access
16440      correctly.  */
16441   push_access_scope (decl);
16442
16443   if (TREE_CODE (decl) == FUNCTION_DECL)
16444     {
16445       tree decl_parm;
16446       tree pattern_parm;
16447       tree specs;
16448       int args_depth;
16449       int parms_depth;
16450
16451       args_depth = TMPL_ARGS_DEPTH (args);
16452       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16453       if (args_depth > parms_depth)
16454         args = get_innermost_template_args (args, parms_depth);
16455
16456       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16457                                               args, tf_error, NULL_TREE);
16458       if (specs)
16459         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16460                                                     specs);
16461
16462       /* Merge parameter declarations.  */
16463       decl_parm = skip_artificial_parms_for (decl,
16464                                              DECL_ARGUMENTS (decl));
16465       pattern_parm
16466         = skip_artificial_parms_for (code_pattern,
16467                                      DECL_ARGUMENTS (code_pattern));
16468       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16469         {
16470           tree parm_type;
16471           tree attributes;
16472           
16473           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16474             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16475           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16476                               NULL_TREE);
16477           parm_type = type_decays_to (parm_type);
16478           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16479             TREE_TYPE (decl_parm) = parm_type;
16480           attributes = DECL_ATTRIBUTES (pattern_parm);
16481           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16482             {
16483               DECL_ATTRIBUTES (decl_parm) = attributes;
16484               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16485             }
16486           decl_parm = TREE_CHAIN (decl_parm);
16487           pattern_parm = TREE_CHAIN (pattern_parm);
16488         }
16489       /* Merge any parameters that match with the function parameter
16490          pack.  */
16491       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16492         {
16493           int i, len;
16494           tree expanded_types;
16495           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16496              the parameters in this function parameter pack.  */
16497           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16498                                                  args, tf_error, NULL_TREE);
16499           len = TREE_VEC_LENGTH (expanded_types);
16500           for (i = 0; i < len; i++)
16501             {
16502               tree parm_type;
16503               tree attributes;
16504           
16505               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16506                 /* Rename the parameter to include the index.  */
16507                 DECL_NAME (decl_parm) = 
16508                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16509               parm_type = TREE_VEC_ELT (expanded_types, i);
16510               parm_type = type_decays_to (parm_type);
16511               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16512                 TREE_TYPE (decl_parm) = parm_type;
16513               attributes = DECL_ATTRIBUTES (pattern_parm);
16514               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16515                 {
16516                   DECL_ATTRIBUTES (decl_parm) = attributes;
16517                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16518                 }
16519               decl_parm = TREE_CHAIN (decl_parm);
16520             }
16521         }
16522       /* Merge additional specifiers from the CODE_PATTERN.  */
16523       if (DECL_DECLARED_INLINE_P (code_pattern)
16524           && !DECL_DECLARED_INLINE_P (decl))
16525         DECL_DECLARED_INLINE_P (decl) = 1;
16526     }
16527   else if (TREE_CODE (decl) == VAR_DECL)
16528     {
16529       DECL_INITIAL (decl) =
16530         tsubst_expr (DECL_INITIAL (code_pattern), args,
16531                      tf_error, DECL_TI_TEMPLATE (decl),
16532                      /*integral_constant_expression_p=*/false);
16533       if (VAR_HAD_UNKNOWN_BOUND (decl))
16534         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
16535                                    tf_error, DECL_TI_TEMPLATE (decl));
16536     }
16537   else
16538     gcc_unreachable ();
16539
16540   pop_access_scope (decl);
16541 }
16542
16543 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16544    substituted to get DECL.  */
16545
16546 tree
16547 template_for_substitution (tree decl)
16548 {
16549   tree tmpl = DECL_TI_TEMPLATE (decl);
16550
16551   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16552      for the instantiation.  This is not always the most general
16553      template.  Consider, for example:
16554
16555         template <class T>
16556         struct S { template <class U> void f();
16557                    template <> void f<int>(); };
16558
16559      and an instantiation of S<double>::f<int>.  We want TD to be the
16560      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16561   while (/* An instantiation cannot have a definition, so we need a
16562             more general template.  */
16563          DECL_TEMPLATE_INSTANTIATION (tmpl)
16564            /* We must also deal with friend templates.  Given:
16565
16566                 template <class T> struct S {
16567                   template <class U> friend void f() {};
16568                 };
16569
16570               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16571               so far as the language is concerned, but that's still
16572               where we get the pattern for the instantiation from.  On
16573               other hand, if the definition comes outside the class, say:
16574
16575                 template <class T> struct S {
16576                   template <class U> friend void f();
16577                 };
16578                 template <class U> friend void f() {}
16579
16580               we don't need to look any further.  That's what the check for
16581               DECL_INITIAL is for.  */
16582           || (TREE_CODE (decl) == FUNCTION_DECL
16583               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16584               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16585     {
16586       /* The present template, TD, should not be a definition.  If it
16587          were a definition, we should be using it!  Note that we
16588          cannot restructure the loop to just keep going until we find
16589          a template with a definition, since that might go too far if
16590          a specialization was declared, but not defined.  */
16591       gcc_assert (TREE_CODE (decl) != VAR_DECL
16592                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16593
16594       /* Fetch the more general template.  */
16595       tmpl = DECL_TI_TEMPLATE (tmpl);
16596     }
16597
16598   return tmpl;
16599 }
16600
16601 /* Returns true if we need to instantiate this template instance even if we
16602    know we aren't going to emit it..  */
16603
16604 bool
16605 always_instantiate_p (tree decl)
16606 {
16607   /* We always instantiate inline functions so that we can inline them.  An
16608      explicit instantiation declaration prohibits implicit instantiation of
16609      non-inline functions.  With high levels of optimization, we would
16610      normally inline non-inline functions -- but we're not allowed to do
16611      that for "extern template" functions.  Therefore, we check
16612      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16613   return ((TREE_CODE (decl) == FUNCTION_DECL
16614            && DECL_DECLARED_INLINE_P (decl))
16615           /* And we need to instantiate static data members so that
16616              their initializers are available in integral constant
16617              expressions.  */
16618           || (TREE_CODE (decl) == VAR_DECL
16619               && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16620 }
16621
16622 /* Produce the definition of D, a _DECL generated from a template.  If
16623    DEFER_OK is nonzero, then we don't have to actually do the
16624    instantiation now; we just have to do it sometime.  Normally it is
16625    an error if this is an explicit instantiation but D is undefined.
16626    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16627    explicitly instantiated class template.  */
16628
16629 tree
16630 instantiate_decl (tree d, int defer_ok,
16631                   bool expl_inst_class_mem_p)
16632 {
16633   tree tmpl = DECL_TI_TEMPLATE (d);
16634   tree gen_args;
16635   tree args;
16636   tree td;
16637   tree code_pattern;
16638   tree spec;
16639   tree gen_tmpl;
16640   bool pattern_defined;
16641   int need_push;
16642   location_t saved_loc = input_location;
16643   bool external_p;
16644
16645   /* This function should only be used to instantiate templates for
16646      functions and static member variables.  */
16647   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16648               || TREE_CODE (d) == VAR_DECL);
16649
16650   /* Variables are never deferred; if instantiation is required, they
16651      are instantiated right away.  That allows for better code in the
16652      case that an expression refers to the value of the variable --
16653      if the variable has a constant value the referring expression can
16654      take advantage of that fact.  */
16655   if (TREE_CODE (d) == VAR_DECL)
16656     defer_ok = 0;
16657
16658   /* Don't instantiate cloned functions.  Instead, instantiate the
16659      functions they cloned.  */
16660   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16661     d = DECL_CLONED_FUNCTION (d);
16662
16663   if (DECL_TEMPLATE_INSTANTIATED (d)
16664       || DECL_TEMPLATE_SPECIALIZATION (d))
16665     /* D has already been instantiated or explicitly specialized, so
16666        there's nothing for us to do here.
16667
16668        It might seem reasonable to check whether or not D is an explicit
16669        instantiation, and, if so, stop here.  But when an explicit
16670        instantiation is deferred until the end of the compilation,
16671        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16672        the instantiation.  */
16673     return d;
16674
16675   /* Check to see whether we know that this template will be
16676      instantiated in some other file, as with "extern template"
16677      extension.  */
16678   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16679
16680   /* In general, we do not instantiate such templates.  */
16681   if (external_p && !always_instantiate_p (d))
16682     return d;
16683
16684   gen_tmpl = most_general_template (tmpl);
16685   gen_args = DECL_TI_ARGS (d);
16686
16687   if (tmpl != gen_tmpl)
16688     /* We should already have the extra args.  */
16689     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16690                 == TMPL_ARGS_DEPTH (gen_args));
16691   /* And what's in the hash table should match D.  */
16692   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16693               || spec == NULL_TREE);
16694
16695   /* This needs to happen before any tsubsting.  */
16696   if (! push_tinst_level (d))
16697     return d;
16698
16699   timevar_push (TV_PARSE);
16700
16701   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16702      for the instantiation.  */
16703   td = template_for_substitution (d);
16704   code_pattern = DECL_TEMPLATE_RESULT (td);
16705
16706   /* We should never be trying to instantiate a member of a class
16707      template or partial specialization.  */
16708   gcc_assert (d != code_pattern);
16709
16710   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16711       || DECL_TEMPLATE_SPECIALIZATION (td))
16712     /* In the case of a friend template whose definition is provided
16713        outside the class, we may have too many arguments.  Drop the
16714        ones we don't need.  The same is true for specializations.  */
16715     args = get_innermost_template_args
16716       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16717   else
16718     args = gen_args;
16719
16720   if (TREE_CODE (d) == FUNCTION_DECL)
16721     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16722   else
16723     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16724
16725   /* We may be in the middle of deferred access check.  Disable it now.  */
16726   push_deferring_access_checks (dk_no_deferred);
16727
16728   /* Unless an explicit instantiation directive has already determined
16729      the linkage of D, remember that a definition is available for
16730      this entity.  */
16731   if (pattern_defined
16732       && !DECL_INTERFACE_KNOWN (d)
16733       && !DECL_NOT_REALLY_EXTERN (d))
16734     mark_definable (d);
16735
16736   input_location = DECL_SOURCE_LOCATION (d);
16737
16738   /* If D is a member of an explicitly instantiated class template,
16739      and no definition is available, treat it like an implicit
16740      instantiation.  */
16741   if (!pattern_defined && expl_inst_class_mem_p
16742       && DECL_EXPLICIT_INSTANTIATION (d))
16743     {
16744       DECL_NOT_REALLY_EXTERN (d) = 0;
16745       DECL_INTERFACE_KNOWN (d) = 0;
16746       SET_DECL_IMPLICIT_INSTANTIATION (d);
16747     }
16748
16749   /* Recheck the substitutions to obtain any warning messages
16750      about ignoring cv qualifiers.  Don't do this for artificial decls,
16751      as it breaks the context-sensitive substitution for lambda op(). */
16752   if (!defer_ok && !DECL_ARTIFICIAL (d))
16753     {
16754       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16755       tree type = TREE_TYPE (gen);
16756
16757       /* Make sure that we can see identifiers, and compute access
16758          correctly.  D is already the target FUNCTION_DECL with the
16759          right context.  */
16760       push_access_scope (d);
16761
16762       if (TREE_CODE (gen) == FUNCTION_DECL)
16763         {
16764           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16765           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16766                                           d);
16767           /* Don't simply tsubst the function type, as that will give
16768              duplicate warnings about poor parameter qualifications.
16769              The function arguments are the same as the decl_arguments
16770              without the top level cv qualifiers.  */
16771           type = TREE_TYPE (type);
16772         }
16773       tsubst (type, gen_args, tf_warning_or_error, d);
16774
16775       pop_access_scope (d);
16776     }
16777
16778   /* Defer all other templates, unless we have been explicitly
16779      forbidden from doing so.  */
16780   if (/* If there is no definition, we cannot instantiate the
16781          template.  */
16782       ! pattern_defined
16783       /* If it's OK to postpone instantiation, do so.  */
16784       || defer_ok
16785       /* If this is a static data member that will be defined
16786          elsewhere, we don't want to instantiate the entire data
16787          member, but we do want to instantiate the initializer so that
16788          we can substitute that elsewhere.  */
16789       || (external_p && TREE_CODE (d) == VAR_DECL))
16790     {
16791       /* The definition of the static data member is now required so
16792          we must substitute the initializer.  */
16793       if (TREE_CODE (d) == VAR_DECL
16794           && !DECL_INITIAL (d)
16795           && DECL_INITIAL (code_pattern))
16796         {
16797           tree ns;
16798           tree init;
16799
16800           ns = decl_namespace_context (d);
16801           push_nested_namespace (ns);
16802           push_nested_class (DECL_CONTEXT (d));
16803           init = tsubst_expr (DECL_INITIAL (code_pattern),
16804                               args,
16805                               tf_warning_or_error, NULL_TREE,
16806                               /*integral_constant_expression_p=*/false);
16807           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16808                           /*asmspec_tree=*/NULL_TREE,
16809                           LOOKUP_ONLYCONVERTING);
16810           pop_nested_class ();
16811           pop_nested_namespace (ns);
16812         }
16813
16814       /* We restore the source position here because it's used by
16815          add_pending_template.  */
16816       input_location = saved_loc;
16817
16818       if (at_eof && !pattern_defined
16819           && DECL_EXPLICIT_INSTANTIATION (d)
16820           && DECL_NOT_REALLY_EXTERN (d))
16821         /* [temp.explicit]
16822
16823            The definition of a non-exported function template, a
16824            non-exported member function template, or a non-exported
16825            member function or static data member of a class template
16826            shall be present in every translation unit in which it is
16827            explicitly instantiated.  */
16828         permerror (input_location,  "explicit instantiation of %qD "
16829                    "but no definition available", d);
16830
16831       /* ??? Historically, we have instantiated inline functions, even
16832          when marked as "extern template".  */
16833       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16834         add_pending_template (d);
16835       goto out;
16836     }
16837   /* Tell the repository that D is available in this translation unit
16838      -- and see if it is supposed to be instantiated here.  */
16839   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16840     {
16841       /* In a PCH file, despite the fact that the repository hasn't
16842          requested instantiation in the PCH it is still possible that
16843          an instantiation will be required in a file that includes the
16844          PCH.  */
16845       if (pch_file)
16846         add_pending_template (d);
16847       /* Instantiate inline functions so that the inliner can do its
16848          job, even though we'll not be emitting a copy of this
16849          function.  */
16850       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16851         goto out;
16852     }
16853
16854   need_push = !cfun || !global_bindings_p ();
16855   if (need_push)
16856     push_to_top_level ();
16857
16858   /* Mark D as instantiated so that recursive calls to
16859      instantiate_decl do not try to instantiate it again.  */
16860   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16861
16862   /* Regenerate the declaration in case the template has been modified
16863      by a subsequent redeclaration.  */
16864   regenerate_decl_from_template (d, td);
16865
16866   /* We already set the file and line above.  Reset them now in case
16867      they changed as a result of calling regenerate_decl_from_template.  */
16868   input_location = DECL_SOURCE_LOCATION (d);
16869
16870   if (TREE_CODE (d) == VAR_DECL)
16871     {
16872       tree init;
16873
16874       /* Clear out DECL_RTL; whatever was there before may not be right
16875          since we've reset the type of the declaration.  */
16876       SET_DECL_RTL (d, NULL);
16877       DECL_IN_AGGR_P (d) = 0;
16878
16879       /* The initializer is placed in DECL_INITIAL by
16880          regenerate_decl_from_template.  Pull it out so that
16881          cp_finish_decl can process it.  */
16882       init = DECL_INITIAL (d);
16883       DECL_INITIAL (d) = NULL_TREE;
16884       DECL_INITIALIZED_P (d) = 0;
16885
16886       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16887          initializer.  That function will defer actual emission until
16888          we have a chance to determine linkage.  */
16889       DECL_EXTERNAL (d) = 0;
16890
16891       /* Enter the scope of D so that access-checking works correctly.  */
16892       push_nested_class (DECL_CONTEXT (d));
16893       cp_finish_decl (d, init, false, NULL_TREE, 0);
16894       pop_nested_class ();
16895     }
16896   else if (TREE_CODE (d) == FUNCTION_DECL)
16897     {
16898       htab_t saved_local_specializations;
16899       tree subst_decl;
16900       tree tmpl_parm;
16901       tree spec_parm;
16902
16903       /* Save away the current list, in case we are instantiating one
16904          template from within the body of another.  */
16905       saved_local_specializations = local_specializations;
16906
16907       /* Set up the list of local specializations.  */
16908       local_specializations = htab_create (37,
16909                                            hash_local_specialization,
16910                                            eq_local_specializations,
16911                                            NULL);
16912
16913       /* Set up context.  */
16914       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16915
16916       /* Create substitution entries for the parameters.  */
16917       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16918       tmpl_parm = DECL_ARGUMENTS (subst_decl);
16919       spec_parm = DECL_ARGUMENTS (d);
16920       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16921         {
16922           register_local_specialization (spec_parm, tmpl_parm);
16923           spec_parm = skip_artificial_parms_for (d, spec_parm);
16924           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16925         }
16926       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16927         {
16928           register_local_specialization (spec_parm, tmpl_parm);
16929           tmpl_parm = TREE_CHAIN (tmpl_parm);
16930           spec_parm = TREE_CHAIN (spec_parm);
16931         }
16932       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16933         {
16934           /* Register the (value) argument pack as a specialization of
16935              TMPL_PARM, then move on.  */
16936           tree argpack = make_fnparm_pack (spec_parm);
16937           register_local_specialization (argpack, tmpl_parm);
16938           tmpl_parm = TREE_CHAIN (tmpl_parm);
16939           spec_parm = NULL_TREE;
16940         }
16941       gcc_assert (!spec_parm);
16942
16943       /* Substitute into the body of the function.  */
16944       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16945                    tf_warning_or_error, tmpl,
16946                    /*integral_constant_expression_p=*/false);
16947
16948       /* Set the current input_location to the end of the function
16949          so that finish_function knows where we are.  */
16950       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16951
16952       /* We don't need the local specializations any more.  */
16953       htab_delete (local_specializations);
16954       local_specializations = saved_local_specializations;
16955
16956       /* Finish the function.  */
16957       d = finish_function (0);
16958       expand_or_defer_fn (d);
16959     }
16960
16961   /* We're not deferring instantiation any more.  */
16962   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16963
16964   if (need_push)
16965     pop_from_top_level ();
16966
16967 out:
16968   input_location = saved_loc;
16969   pop_deferring_access_checks ();
16970   pop_tinst_level ();
16971
16972   timevar_pop (TV_PARSE);
16973
16974   return d;
16975 }
16976
16977 /* Run through the list of templates that we wish we could
16978    instantiate, and instantiate any we can.  RETRIES is the
16979    number of times we retry pending template instantiation.  */
16980
16981 void
16982 instantiate_pending_templates (int retries)
16983 {
16984   int reconsider;
16985   location_t saved_loc = input_location;
16986
16987   /* Instantiating templates may trigger vtable generation.  This in turn
16988      may require further template instantiations.  We place a limit here
16989      to avoid infinite loop.  */
16990   if (pending_templates && retries >= max_tinst_depth)
16991     {
16992       tree decl = pending_templates->tinst->decl;
16993
16994       error ("template instantiation depth exceeds maximum of %d"
16995              " instantiating %q+D, possibly from virtual table generation"
16996              " (use -ftemplate-depth= to increase the maximum)",
16997              max_tinst_depth, decl);
16998       if (TREE_CODE (decl) == FUNCTION_DECL)
16999         /* Pretend that we defined it.  */
17000         DECL_INITIAL (decl) = error_mark_node;
17001       return;
17002     }
17003
17004   do
17005     {
17006       struct pending_template **t = &pending_templates;
17007       struct pending_template *last = NULL;
17008       reconsider = 0;
17009       while (*t)
17010         {
17011           tree instantiation = reopen_tinst_level ((*t)->tinst);
17012           bool complete = false;
17013
17014           if (TYPE_P (instantiation))
17015             {
17016               tree fn;
17017
17018               if (!COMPLETE_TYPE_P (instantiation))
17019                 {
17020                   instantiate_class_template (instantiation);
17021                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
17022                     for (fn = TYPE_METHODS (instantiation);
17023                          fn;
17024                          fn = TREE_CHAIN (fn))
17025                       if (! DECL_ARTIFICIAL (fn))
17026                         instantiate_decl (fn,
17027                                           /*defer_ok=*/0,
17028                                           /*expl_inst_class_mem_p=*/false);
17029                   if (COMPLETE_TYPE_P (instantiation))
17030                     reconsider = 1;
17031                 }
17032
17033               complete = COMPLETE_TYPE_P (instantiation);
17034             }
17035           else
17036             {
17037               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
17038                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
17039                 {
17040                   instantiation
17041                     = instantiate_decl (instantiation,
17042                                         /*defer_ok=*/0,
17043                                         /*expl_inst_class_mem_p=*/false);
17044                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
17045                     reconsider = 1;
17046                 }
17047
17048               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
17049                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
17050             }
17051
17052           if (complete)
17053             /* If INSTANTIATION has been instantiated, then we don't
17054                need to consider it again in the future.  */
17055             *t = (*t)->next;
17056           else
17057             {
17058               last = *t;
17059               t = &(*t)->next;
17060             }
17061           tinst_depth = 0;
17062           current_tinst_level = NULL;
17063         }
17064       last_pending_template = last;
17065     }
17066   while (reconsider);
17067
17068   input_location = saved_loc;
17069 }
17070
17071 /* Substitute ARGVEC into T, which is a list of initializers for
17072    either base class or a non-static data member.  The TREE_PURPOSEs
17073    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
17074    instantiate_decl.  */
17075
17076 static tree
17077 tsubst_initializer_list (tree t, tree argvec)
17078 {
17079   tree inits = NULL_TREE;
17080
17081   for (; t; t = TREE_CHAIN (t))
17082     {
17083       tree decl;
17084       tree init;
17085       tree expanded_bases = NULL_TREE;
17086       tree expanded_arguments = NULL_TREE;
17087       int i, len = 1;
17088
17089       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
17090         {
17091           tree expr;
17092           tree arg;
17093
17094           /* Expand the base class expansion type into separate base
17095              classes.  */
17096           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
17097                                                  tf_warning_or_error,
17098                                                  NULL_TREE);
17099           if (expanded_bases == error_mark_node)
17100             continue;
17101           
17102           /* We'll be building separate TREE_LISTs of arguments for
17103              each base.  */
17104           len = TREE_VEC_LENGTH (expanded_bases);
17105           expanded_arguments = make_tree_vec (len);
17106           for (i = 0; i < len; i++)
17107             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
17108
17109           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
17110              expand each argument in the TREE_VALUE of t.  */
17111           expr = make_node (EXPR_PACK_EXPANSION);
17112           PACK_EXPANSION_PARAMETER_PACKS (expr) =
17113             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
17114
17115           if (TREE_VALUE (t) == void_type_node)
17116             /* VOID_TYPE_NODE is used to indicate
17117                value-initialization.  */
17118             {
17119               for (i = 0; i < len; i++)
17120                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
17121             }
17122           else
17123             {
17124               /* Substitute parameter packs into each argument in the
17125                  TREE_LIST.  */
17126               in_base_initializer = 1;
17127               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
17128                 {
17129                   tree expanded_exprs;
17130
17131                   /* Expand the argument.  */
17132                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
17133                   expanded_exprs 
17134                     = tsubst_pack_expansion (expr, argvec,
17135                                              tf_warning_or_error,
17136                                              NULL_TREE);
17137                   if (expanded_exprs == error_mark_node)
17138                     continue;
17139
17140                   /* Prepend each of the expanded expressions to the
17141                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
17142                   for (i = 0; i < len; i++)
17143                     {
17144                       TREE_VEC_ELT (expanded_arguments, i) = 
17145                         tree_cons (NULL_TREE, 
17146                                    TREE_VEC_ELT (expanded_exprs, i),
17147                                    TREE_VEC_ELT (expanded_arguments, i));
17148                     }
17149                 }
17150               in_base_initializer = 0;
17151
17152               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
17153                  since we built them backwards.  */
17154               for (i = 0; i < len; i++)
17155                 {
17156                   TREE_VEC_ELT (expanded_arguments, i) = 
17157                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
17158                 }
17159             }
17160         }
17161
17162       for (i = 0; i < len; ++i)
17163         {
17164           if (expanded_bases)
17165             {
17166               decl = TREE_VEC_ELT (expanded_bases, i);
17167               decl = expand_member_init (decl);
17168               init = TREE_VEC_ELT (expanded_arguments, i);
17169             }
17170           else
17171             {
17172               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
17173                                   tf_warning_or_error, NULL_TREE);
17174
17175               decl = expand_member_init (decl);
17176               if (decl && !DECL_P (decl))
17177                 in_base_initializer = 1;
17178
17179               init = tsubst_expr (TREE_VALUE (t), argvec, 
17180                                   tf_warning_or_error, NULL_TREE,
17181                                   /*integral_constant_expression_p=*/false);
17182               in_base_initializer = 0;
17183             }
17184
17185           if (decl)
17186             {
17187               init = build_tree_list (decl, init);
17188               TREE_CHAIN (init) = inits;
17189               inits = init;
17190             }
17191         }
17192     }
17193   return inits;
17194 }
17195
17196 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
17197
17198 static void
17199 set_current_access_from_decl (tree decl)
17200 {
17201   if (TREE_PRIVATE (decl))
17202     current_access_specifier = access_private_node;
17203   else if (TREE_PROTECTED (decl))
17204     current_access_specifier = access_protected_node;
17205   else
17206     current_access_specifier = access_public_node;
17207 }
17208
17209 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
17210    is the instantiation (which should have been created with
17211    start_enum) and ARGS are the template arguments to use.  */
17212
17213 static void
17214 tsubst_enum (tree tag, tree newtag, tree args)
17215 {
17216   tree e;
17217
17218   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
17219     {
17220       tree value;
17221       tree decl;
17222
17223       decl = TREE_VALUE (e);
17224       /* Note that in a template enum, the TREE_VALUE is the
17225          CONST_DECL, not the corresponding INTEGER_CST.  */
17226       value = tsubst_expr (DECL_INITIAL (decl),
17227                            args, tf_warning_or_error, NULL_TREE,
17228                            /*integral_constant_expression_p=*/true);
17229
17230       /* Give this enumeration constant the correct access.  */
17231       set_current_access_from_decl (decl);
17232
17233       /* Actually build the enumerator itself.  */
17234       build_enumerator (DECL_NAME (decl), value, newtag);
17235     }
17236
17237   finish_enum (newtag);
17238   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
17239     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
17240 }
17241
17242 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
17243    its type -- but without substituting the innermost set of template
17244    arguments.  So, innermost set of template parameters will appear in
17245    the type.  */
17246
17247 tree
17248 get_mostly_instantiated_function_type (tree decl)
17249 {
17250   tree fn_type;
17251   tree tmpl;
17252   tree targs;
17253   tree tparms;
17254   int parm_depth;
17255
17256   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
17257   targs = DECL_TI_ARGS (decl);
17258   tparms = DECL_TEMPLATE_PARMS (tmpl);
17259   parm_depth = TMPL_PARMS_DEPTH (tparms);
17260
17261   /* There should be as many levels of arguments as there are levels
17262      of parameters.  */
17263   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
17264
17265   fn_type = TREE_TYPE (tmpl);
17266
17267   if (parm_depth == 1)
17268     /* No substitution is necessary.  */
17269     ;
17270   else
17271     {
17272       int i, save_access_control;
17273       tree partial_args;
17274
17275       /* Replace the innermost level of the TARGS with NULL_TREEs to
17276          let tsubst know not to substitute for those parameters.  */
17277       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
17278       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
17279         SET_TMPL_ARGS_LEVEL (partial_args, i,
17280                              TMPL_ARGS_LEVEL (targs, i));
17281       SET_TMPL_ARGS_LEVEL (partial_args,
17282                            TMPL_ARGS_DEPTH (targs),
17283                            make_tree_vec (DECL_NTPARMS (tmpl)));
17284
17285       /* Disable access control as this function is used only during
17286          name-mangling.  */
17287       save_access_control = flag_access_control;
17288       flag_access_control = 0;
17289
17290       ++processing_template_decl;
17291       /* Now, do the (partial) substitution to figure out the
17292          appropriate function type.  */
17293       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
17294       --processing_template_decl;
17295
17296       /* Substitute into the template parameters to obtain the real
17297          innermost set of parameters.  This step is important if the
17298          innermost set of template parameters contains value
17299          parameters whose types depend on outer template parameters.  */
17300       TREE_VEC_LENGTH (partial_args)--;
17301       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
17302
17303       flag_access_control = save_access_control;
17304     }
17305
17306   return fn_type;
17307 }
17308
17309 /* Return truthvalue if we're processing a template different from
17310    the last one involved in diagnostics.  */
17311 int
17312 problematic_instantiation_changed (void)
17313 {
17314   return last_template_error_tick != tinst_level_tick;
17315 }
17316
17317 /* Remember current template involved in diagnostics.  */
17318 void
17319 record_last_problematic_instantiation (void)
17320 {
17321   last_template_error_tick = tinst_level_tick;
17322 }
17323
17324 struct tinst_level *
17325 current_instantiation (void)
17326 {
17327   return current_tinst_level;
17328 }
17329
17330 /* [temp.param] Check that template non-type parm TYPE is of an allowable
17331    type. Return zero for ok, nonzero for disallowed. Issue error and
17332    warning messages under control of COMPLAIN.  */
17333
17334 static int
17335 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
17336 {
17337   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
17338     return 0;
17339   else if (POINTER_TYPE_P (type))
17340     return 0;
17341   else if (TYPE_PTR_TO_MEMBER_P (type))
17342     return 0;
17343   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
17344     return 0;
17345   else if (TREE_CODE (type) == TYPENAME_TYPE)
17346     return 0;
17347
17348   if (complain & tf_error)
17349     error ("%q#T is not a valid type for a template constant parameter", type);
17350   return 1;
17351 }
17352
17353 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
17354    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
17355
17356 static bool
17357 dependent_type_p_r (tree type)
17358 {
17359   tree scope;
17360
17361   /* [temp.dep.type]
17362
17363      A type is dependent if it is:
17364
17365      -- a template parameter. Template template parameters are types
17366         for us (since TYPE_P holds true for them) so we handle
17367         them here.  */
17368   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17369       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17370     return true;
17371   /* -- a qualified-id with a nested-name-specifier which contains a
17372         class-name that names a dependent type or whose unqualified-id
17373         names a dependent type.  */
17374   if (TREE_CODE (type) == TYPENAME_TYPE)
17375     return true;
17376   /* -- a cv-qualified type where the cv-unqualified type is
17377         dependent.  */
17378   type = TYPE_MAIN_VARIANT (type);
17379   /* -- a compound type constructed from any dependent type.  */
17380   if (TYPE_PTR_TO_MEMBER_P (type))
17381     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17382             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17383                                            (type)));
17384   else if (TREE_CODE (type) == POINTER_TYPE
17385            || TREE_CODE (type) == REFERENCE_TYPE)
17386     return dependent_type_p (TREE_TYPE (type));
17387   else if (TREE_CODE (type) == FUNCTION_TYPE
17388            || TREE_CODE (type) == METHOD_TYPE)
17389     {
17390       tree arg_type;
17391
17392       if (dependent_type_p (TREE_TYPE (type)))
17393         return true;
17394       for (arg_type = TYPE_ARG_TYPES (type);
17395            arg_type;
17396            arg_type = TREE_CHAIN (arg_type))
17397         if (dependent_type_p (TREE_VALUE (arg_type)))
17398           return true;
17399       return false;
17400     }
17401   /* -- an array type constructed from any dependent type or whose
17402         size is specified by a constant expression that is
17403         value-dependent.  */
17404   if (TREE_CODE (type) == ARRAY_TYPE)
17405     {
17406       if (TYPE_DOMAIN (type)
17407           && dependent_type_p (TYPE_DOMAIN (type)))
17408         return true;
17409       return dependent_type_p (TREE_TYPE (type));
17410     }
17411   else if (TREE_CODE (type) == INTEGER_TYPE
17412            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
17413     {
17414       /* If this is the TYPE_DOMAIN of an array type, consider it
17415          dependent.  We already checked for value-dependence in
17416          compute_array_index_type.  */
17417       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
17418     }
17419
17420   /* -- a template-id in which either the template name is a template
17421      parameter ...  */
17422   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17423     return true;
17424   /* ... or any of the template arguments is a dependent type or
17425         an expression that is type-dependent or value-dependent.  */
17426   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17427            && (any_dependent_template_arguments_p
17428                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17429     return true;
17430
17431   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17432      argument of the `typeof' expression is not type-dependent, then
17433      it should already been have resolved.  */
17434   if (TREE_CODE (type) == TYPEOF_TYPE
17435       || TREE_CODE (type) == DECLTYPE_TYPE)
17436     return true;
17437
17438   /* A template argument pack is dependent if any of its packed
17439      arguments are.  */
17440   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17441     {
17442       tree args = ARGUMENT_PACK_ARGS (type);
17443       int i, len = TREE_VEC_LENGTH (args);
17444       for (i = 0; i < len; ++i)
17445         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17446           return true;
17447     }
17448
17449   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17450      be template parameters.  */
17451   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17452     return true;
17453
17454   /* The standard does not specifically mention types that are local
17455      to template functions or local classes, but they should be
17456      considered dependent too.  For example:
17457
17458        template <int I> void f() {
17459          enum E { a = I };
17460          S<sizeof (E)> s;
17461        }
17462
17463      The size of `E' cannot be known until the value of `I' has been
17464      determined.  Therefore, `E' must be considered dependent.  */
17465   scope = TYPE_CONTEXT (type);
17466   if (scope && TYPE_P (scope))
17467     return dependent_type_p (scope);
17468   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17469     return type_dependent_expression_p (scope);
17470
17471   /* Other types are non-dependent.  */
17472   return false;
17473 }
17474
17475 /* Returns TRUE if TYPE is dependent, in the sense of
17476    [temp.dep.type].  */
17477
17478 bool
17479 dependent_type_p (tree type)
17480 {
17481   /* If there are no template parameters in scope, then there can't be
17482      any dependent types.  */
17483   if (!processing_template_decl)
17484     {
17485       /* If we are not processing a template, then nobody should be
17486          providing us with a dependent type.  */
17487       gcc_assert (type);
17488       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17489       return false;
17490     }
17491
17492   /* If the type is NULL, we have not computed a type for the entity
17493      in question; in that case, the type is dependent.  */
17494   if (!type)
17495     return true;
17496
17497   /* Erroneous types can be considered non-dependent.  */
17498   if (type == error_mark_node)
17499     return false;
17500
17501   /* If we have not already computed the appropriate value for TYPE,
17502      do so now.  */
17503   if (!TYPE_DEPENDENT_P_VALID (type))
17504     {
17505       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17506       TYPE_DEPENDENT_P_VALID (type) = 1;
17507     }
17508
17509   return TYPE_DEPENDENT_P (type);
17510 }
17511
17512 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17513    lookup.  In other words, a dependent type that is not the current
17514    instantiation.  */
17515
17516 bool
17517 dependent_scope_p (tree scope)
17518 {
17519   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17520           && !currently_open_class (scope));
17521 }
17522
17523 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17524    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17525    expression.  */
17526
17527 bool
17528 value_dependent_expression_p (tree expression)
17529 {
17530   if (!processing_template_decl)
17531     return false;
17532
17533   /* A name declared with a dependent type.  */
17534   if (DECL_P (expression) && type_dependent_expression_p (expression))
17535     return true;
17536
17537   switch (TREE_CODE (expression))
17538     {
17539     case IDENTIFIER_NODE:
17540       /* A name that has not been looked up -- must be dependent.  */
17541       return true;
17542
17543     case TEMPLATE_PARM_INDEX:
17544       /* A non-type template parm.  */
17545       return true;
17546
17547     case CONST_DECL:
17548       /* A non-type template parm.  */
17549       if (DECL_TEMPLATE_PARM_P (expression))
17550         return true;
17551       return value_dependent_expression_p (DECL_INITIAL (expression));
17552
17553     case VAR_DECL:
17554        /* A constant with integral or enumeration type and is initialized
17555           with an expression that is value-dependent.  */
17556       if (DECL_INITIAL (expression)
17557           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17558           && value_dependent_expression_p (DECL_INITIAL (expression)))
17559         return true;
17560       return false;
17561
17562     case DYNAMIC_CAST_EXPR:
17563     case STATIC_CAST_EXPR:
17564     case CONST_CAST_EXPR:
17565     case REINTERPRET_CAST_EXPR:
17566     case CAST_EXPR:
17567       /* These expressions are value-dependent if the type to which
17568          the cast occurs is dependent or the expression being casted
17569          is value-dependent.  */
17570       {
17571         tree type = TREE_TYPE (expression);
17572
17573         if (dependent_type_p (type))
17574           return true;
17575
17576         /* A functional cast has a list of operands.  */
17577         expression = TREE_OPERAND (expression, 0);
17578         if (!expression)
17579           {
17580             /* If there are no operands, it must be an expression such
17581                as "int()". This should not happen for aggregate types
17582                because it would form non-constant expressions.  */
17583             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17584
17585             return false;
17586           }
17587
17588         if (TREE_CODE (expression) == TREE_LIST)
17589           return any_value_dependent_elements_p (expression);
17590
17591         return value_dependent_expression_p (expression);
17592       }
17593
17594     case SIZEOF_EXPR:
17595     case ALIGNOF_EXPR:
17596       /* A `sizeof' expression is value-dependent if the operand is
17597          type-dependent or is a pack expansion.  */
17598       expression = TREE_OPERAND (expression, 0);
17599       if (PACK_EXPANSION_P (expression))
17600         return true;
17601       else if (TYPE_P (expression))
17602         return dependent_type_p (expression);
17603       return type_dependent_expression_p (expression);
17604
17605     case NOEXCEPT_EXPR:
17606       expression = TREE_OPERAND (expression, 0);
17607       /* FIXME why check value-dependency?  */
17608       return (type_dependent_expression_p (expression)
17609               || value_dependent_expression_p (expression));
17610
17611     case SCOPE_REF:
17612       {
17613         tree name = TREE_OPERAND (expression, 1);
17614         return value_dependent_expression_p (name);
17615       }
17616
17617     case COMPONENT_REF:
17618       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17619               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17620
17621     case CALL_EXPR:
17622       /* A CALL_EXPR may appear in a constant expression if it is a
17623          call to a builtin function, e.g., __builtin_constant_p.  All
17624          such calls are value-dependent.  */
17625       return true;
17626
17627     case NONTYPE_ARGUMENT_PACK:
17628       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17629          is value-dependent.  */
17630       {
17631         tree values = ARGUMENT_PACK_ARGS (expression);
17632         int i, len = TREE_VEC_LENGTH (values);
17633         
17634         for (i = 0; i < len; ++i)
17635           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17636             return true;
17637         
17638         return false;
17639       }
17640
17641     case TRAIT_EXPR:
17642       {
17643         tree type2 = TRAIT_EXPR_TYPE2 (expression);
17644         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17645                 || (type2 ? dependent_type_p (type2) : false));
17646       }
17647
17648     case MODOP_EXPR:
17649       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17650               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17651
17652     case ADDR_EXPR:
17653       {
17654         tree op = TREE_OPERAND (expression, 0);
17655         return (value_dependent_expression_p (op)
17656                 || has_value_dependent_address (op));
17657       }
17658
17659     default:
17660       /* A constant expression is value-dependent if any subexpression is
17661          value-dependent.  */
17662       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17663         {
17664         case tcc_reference:
17665         case tcc_unary:
17666           return (value_dependent_expression_p
17667                   (TREE_OPERAND (expression, 0)));
17668
17669         case tcc_comparison:
17670         case tcc_binary:
17671           return ((value_dependent_expression_p
17672                    (TREE_OPERAND (expression, 0)))
17673                   || (value_dependent_expression_p
17674                       (TREE_OPERAND (expression, 1))));
17675
17676         case tcc_expression:
17677         case tcc_vl_exp:
17678           {
17679             int i;
17680             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17681               /* In some cases, some of the operands may be missing.
17682                  (For example, in the case of PREDECREMENT_EXPR, the
17683                  amount to increment by may be missing.)  That doesn't
17684                  make the expression dependent.  */
17685               if (TREE_OPERAND (expression, i)
17686                   && (value_dependent_expression_p
17687                       (TREE_OPERAND (expression, i))))
17688                 return true;
17689             return false;
17690           }
17691
17692         default:
17693           break;
17694         }
17695     }
17696
17697   /* The expression is not value-dependent.  */
17698   return false;
17699 }
17700
17701 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17702    [temp.dep.expr].  */
17703
17704 bool
17705 type_dependent_expression_p (tree expression)
17706 {
17707   if (!processing_template_decl)
17708     return false;
17709
17710   if (expression == error_mark_node)
17711     return false;
17712
17713   /* An unresolved name is always dependent.  */
17714   if (TREE_CODE (expression) == IDENTIFIER_NODE
17715       || TREE_CODE (expression) == USING_DECL)
17716     return true;
17717
17718   /* Some expression forms are never type-dependent.  */
17719   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17720       || TREE_CODE (expression) == SIZEOF_EXPR
17721       || TREE_CODE (expression) == ALIGNOF_EXPR
17722       || TREE_CODE (expression) == NOEXCEPT_EXPR
17723       || TREE_CODE (expression) == TRAIT_EXPR
17724       || TREE_CODE (expression) == TYPEID_EXPR
17725       || TREE_CODE (expression) == DELETE_EXPR
17726       || TREE_CODE (expression) == VEC_DELETE_EXPR
17727       || TREE_CODE (expression) == THROW_EXPR)
17728     return false;
17729
17730   /* The types of these expressions depends only on the type to which
17731      the cast occurs.  */
17732   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17733       || TREE_CODE (expression) == STATIC_CAST_EXPR
17734       || TREE_CODE (expression) == CONST_CAST_EXPR
17735       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17736       || TREE_CODE (expression) == CAST_EXPR)
17737     return dependent_type_p (TREE_TYPE (expression));
17738
17739   /* The types of these expressions depends only on the type created
17740      by the expression.  */
17741   if (TREE_CODE (expression) == NEW_EXPR
17742       || TREE_CODE (expression) == VEC_NEW_EXPR)
17743     {
17744       /* For NEW_EXPR tree nodes created inside a template, either
17745          the object type itself or a TREE_LIST may appear as the
17746          operand 1.  */
17747       tree type = TREE_OPERAND (expression, 1);
17748       if (TREE_CODE (type) == TREE_LIST)
17749         /* This is an array type.  We need to check array dimensions
17750            as well.  */
17751         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17752                || value_dependent_expression_p
17753                     (TREE_OPERAND (TREE_VALUE (type), 1));
17754       else
17755         return dependent_type_p (type);
17756     }
17757
17758   if (TREE_CODE (expression) == SCOPE_REF)
17759     {
17760       tree scope = TREE_OPERAND (expression, 0);
17761       tree name = TREE_OPERAND (expression, 1);
17762
17763       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
17764          contains an identifier associated by name lookup with one or more
17765          declarations declared with a dependent type, or...a
17766          nested-name-specifier or qualified-id that names a member of an
17767          unknown specialization.  */
17768       return (type_dependent_expression_p (name)
17769               || dependent_scope_p (scope));
17770     }
17771
17772   if (TREE_CODE (expression) == FUNCTION_DECL
17773       && DECL_LANG_SPECIFIC (expression)
17774       && DECL_TEMPLATE_INFO (expression)
17775       && (any_dependent_template_arguments_p
17776           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17777     return true;
17778
17779   if (TREE_CODE (expression) == TEMPLATE_DECL
17780       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17781     return false;
17782
17783   if (TREE_CODE (expression) == STMT_EXPR)
17784     expression = stmt_expr_value_expr (expression);
17785
17786   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17787     {
17788       tree elt;
17789       unsigned i;
17790
17791       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17792         {
17793           if (type_dependent_expression_p (elt))
17794             return true;
17795         }
17796       return false;
17797     }
17798
17799   /* A static data member of the current instantiation with incomplete
17800      array type is type-dependent, as the definition and specializations
17801      can have different bounds.  */
17802   if (TREE_CODE (expression) == VAR_DECL
17803       && DECL_CLASS_SCOPE_P (expression)
17804       && dependent_type_p (DECL_CONTEXT (expression))
17805       && VAR_HAD_UNKNOWN_BOUND (expression))
17806     return true;
17807
17808   if (TREE_TYPE (expression) == unknown_type_node)
17809     {
17810       if (TREE_CODE (expression) == ADDR_EXPR)
17811         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17812       if (TREE_CODE (expression) == COMPONENT_REF
17813           || TREE_CODE (expression) == OFFSET_REF)
17814         {
17815           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17816             return true;
17817           expression = TREE_OPERAND (expression, 1);
17818           if (TREE_CODE (expression) == IDENTIFIER_NODE)
17819             return false;
17820         }
17821       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17822       if (TREE_CODE (expression) == SCOPE_REF)
17823         return false;
17824
17825       if (TREE_CODE (expression) == BASELINK)
17826         expression = BASELINK_FUNCTIONS (expression);
17827
17828       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17829         {
17830           if (any_dependent_template_arguments_p
17831               (TREE_OPERAND (expression, 1)))
17832             return true;
17833           expression = TREE_OPERAND (expression, 0);
17834         }
17835       gcc_assert (TREE_CODE (expression) == OVERLOAD
17836                   || TREE_CODE (expression) == FUNCTION_DECL);
17837
17838       while (expression)
17839         {
17840           if (type_dependent_expression_p (OVL_CURRENT (expression)))
17841             return true;
17842           expression = OVL_NEXT (expression);
17843         }
17844       return false;
17845     }
17846
17847   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17848
17849   return (dependent_type_p (TREE_TYPE (expression)));
17850 }
17851
17852 /* Like type_dependent_expression_p, but it also works while not processing
17853    a template definition, i.e. during substitution or mangling.  */
17854
17855 bool
17856 type_dependent_expression_p_push (tree expr)
17857 {
17858   bool b;
17859   ++processing_template_decl;
17860   b = type_dependent_expression_p (expr);
17861   --processing_template_decl;
17862   return b;
17863 }
17864
17865 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17866
17867 bool
17868 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17869 {
17870   unsigned int i;
17871   tree arg;
17872
17873   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
17874     {
17875       if (type_dependent_expression_p (arg))
17876         return true;
17877     }
17878   return false;
17879 }
17880
17881 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17882    expressions) contains any value-dependent expressions.  */
17883
17884 bool
17885 any_value_dependent_elements_p (const_tree list)
17886 {
17887   for (; list; list = TREE_CHAIN (list))
17888     if (value_dependent_expression_p (TREE_VALUE (list)))
17889       return true;
17890
17891   return false;
17892 }
17893
17894 /* Returns TRUE if the ARG (a template argument) is dependent.  */
17895
17896 bool
17897 dependent_template_arg_p (tree arg)
17898 {
17899   if (!processing_template_decl)
17900     return false;
17901
17902   if (TREE_CODE (arg) == TEMPLATE_DECL
17903       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17904     return dependent_template_p (arg);
17905   else if (ARGUMENT_PACK_P (arg))
17906     {
17907       tree args = ARGUMENT_PACK_ARGS (arg);
17908       int i, len = TREE_VEC_LENGTH (args);
17909       for (i = 0; i < len; ++i)
17910         {
17911           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17912             return true;
17913         }
17914
17915       return false;
17916     }
17917   else if (TYPE_P (arg))
17918     return dependent_type_p (arg);
17919   else
17920     return (type_dependent_expression_p (arg)
17921             || value_dependent_expression_p (arg));
17922 }
17923
17924 /* Returns true if ARGS (a collection of template arguments) contains
17925    any types that require structural equality testing.  */
17926
17927 bool
17928 any_template_arguments_need_structural_equality_p (tree args)
17929 {
17930   int i;
17931   int j;
17932
17933   if (!args)
17934     return false;
17935   if (args == error_mark_node)
17936     return true;
17937
17938   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17939     {
17940       tree level = TMPL_ARGS_LEVEL (args, i + 1);
17941       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17942         {
17943           tree arg = TREE_VEC_ELT (level, j);
17944           tree packed_args = NULL_TREE;
17945           int k, len = 1;
17946
17947           if (ARGUMENT_PACK_P (arg))
17948             {
17949               /* Look inside the argument pack.  */
17950               packed_args = ARGUMENT_PACK_ARGS (arg);
17951               len = TREE_VEC_LENGTH (packed_args);
17952             }
17953
17954           for (k = 0; k < len; ++k)
17955             {
17956               if (packed_args)
17957                 arg = TREE_VEC_ELT (packed_args, k);
17958
17959               if (error_operand_p (arg))
17960                 return true;
17961               else if (TREE_CODE (arg) == TEMPLATE_DECL
17962                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17963                 continue;
17964               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17965                 return true;
17966               else if (!TYPE_P (arg) && TREE_TYPE (arg)
17967                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17968                 return true;
17969             }
17970         }
17971     }
17972
17973   return false;
17974 }
17975
17976 /* Returns true if ARGS (a collection of template arguments) contains
17977    any dependent arguments.  */
17978
17979 bool
17980 any_dependent_template_arguments_p (const_tree args)
17981 {
17982   int i;
17983   int j;
17984
17985   if (!args)
17986     return false;
17987   if (args == error_mark_node)
17988     return true;
17989
17990   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17991     {
17992       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17993       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17994         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17995           return true;
17996     }
17997
17998   return false;
17999 }
18000
18001 /* Returns TRUE if the template TMPL is dependent.  */
18002
18003 bool
18004 dependent_template_p (tree tmpl)
18005 {
18006   if (TREE_CODE (tmpl) == OVERLOAD)
18007     {
18008       while (tmpl)
18009         {
18010           if (dependent_template_p (OVL_FUNCTION (tmpl)))
18011             return true;
18012           tmpl = OVL_CHAIN (tmpl);
18013         }
18014       return false;
18015     }
18016
18017   /* Template template parameters are dependent.  */
18018   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
18019       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
18020     return true;
18021   /* So are names that have not been looked up.  */
18022   if (TREE_CODE (tmpl) == SCOPE_REF
18023       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
18024     return true;
18025   /* So are member templates of dependent classes.  */
18026   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
18027     return dependent_type_p (DECL_CONTEXT (tmpl));
18028   return false;
18029 }
18030
18031 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
18032
18033 bool
18034 dependent_template_id_p (tree tmpl, tree args)
18035 {
18036   return (dependent_template_p (tmpl)
18037           || any_dependent_template_arguments_p (args));
18038 }
18039
18040 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
18041    is dependent.  */
18042
18043 bool
18044 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
18045 {
18046   int i;
18047
18048   if (!processing_template_decl)
18049     return false;
18050
18051   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
18052     {
18053       tree decl = TREE_VEC_ELT (declv, i);
18054       tree init = TREE_VEC_ELT (initv, i);
18055       tree cond = TREE_VEC_ELT (condv, i);
18056       tree incr = TREE_VEC_ELT (incrv, i);
18057
18058       if (type_dependent_expression_p (decl))
18059         return true;
18060
18061       if (init && type_dependent_expression_p (init))
18062         return true;
18063
18064       if (type_dependent_expression_p (cond))
18065         return true;
18066
18067       if (COMPARISON_CLASS_P (cond)
18068           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
18069               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
18070         return true;
18071
18072       if (TREE_CODE (incr) == MODOP_EXPR)
18073         {
18074           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
18075               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
18076             return true;
18077         }
18078       else if (type_dependent_expression_p (incr))
18079         return true;
18080       else if (TREE_CODE (incr) == MODIFY_EXPR)
18081         {
18082           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
18083             return true;
18084           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
18085             {
18086               tree t = TREE_OPERAND (incr, 1);
18087               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
18088                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
18089                 return true;
18090             }
18091         }
18092     }
18093
18094   return false;
18095 }
18096
18097 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
18098    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
18099    no such TYPE can be found.  Note that this function peers inside
18100    uninstantiated templates and therefore should be used only in
18101    extremely limited situations.  ONLY_CURRENT_P restricts this
18102    peering to the currently open classes hierarchy (which is required
18103    when comparing types).  */
18104
18105 tree
18106 resolve_typename_type (tree type, bool only_current_p)
18107 {
18108   tree scope;
18109   tree name;
18110   tree decl;
18111   int quals;
18112   tree pushed_scope;
18113   tree result;
18114
18115   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
18116
18117   scope = TYPE_CONTEXT (type);
18118   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
18119      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
18120      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
18121      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
18122      identifier  of the TYPENAME_TYPE anymore.
18123      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
18124      TYPENAME_TYPE instead, we avoid messing up with a possible
18125      typedef variant case.  */
18126   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
18127
18128   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
18129      it first before we can figure out what NAME refers to.  */
18130   if (TREE_CODE (scope) == TYPENAME_TYPE)
18131     scope = resolve_typename_type (scope, only_current_p);
18132   /* If we don't know what SCOPE refers to, then we cannot resolve the
18133      TYPENAME_TYPE.  */
18134   if (TREE_CODE (scope) == TYPENAME_TYPE)
18135     return type;
18136   /* If the SCOPE is a template type parameter, we have no way of
18137      resolving the name.  */
18138   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
18139     return type;
18140   /* If the SCOPE is not the current instantiation, there's no reason
18141      to look inside it.  */
18142   if (only_current_p && !currently_open_class (scope))
18143     return type;
18144   /* If this is a typedef, we don't want to look inside (c++/11987).  */
18145   if (typedef_variant_p (type))
18146     return type;
18147   /* If SCOPE isn't the template itself, it will not have a valid
18148      TYPE_FIELDS list.  */
18149   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
18150     /* scope is either the template itself or a compatible instantiation
18151        like X<T>, so look up the name in the original template.  */
18152     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
18153   else
18154     /* scope is a partial instantiation, so we can't do the lookup or we
18155        will lose the template arguments.  */
18156     return type;
18157   /* Enter the SCOPE so that name lookup will be resolved as if we
18158      were in the class definition.  In particular, SCOPE will no
18159      longer be considered a dependent type.  */
18160   pushed_scope = push_scope (scope);
18161   /* Look up the declaration.  */
18162   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
18163
18164   result = NULL_TREE;
18165   
18166   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
18167      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
18168   if (!decl)
18169     /*nop*/;
18170   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
18171            && TREE_CODE (decl) == TYPE_DECL)
18172     {
18173       result = TREE_TYPE (decl);
18174       if (result == error_mark_node)
18175         result = NULL_TREE;
18176     }
18177   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
18178            && DECL_CLASS_TEMPLATE_P (decl))
18179     {
18180       tree tmpl;
18181       tree args;
18182       /* Obtain the template and the arguments.  */
18183       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
18184       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
18185       /* Instantiate the template.  */
18186       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
18187                                       /*entering_scope=*/0,
18188                                       tf_error | tf_user);
18189       if (result == error_mark_node)
18190         result = NULL_TREE;
18191     }
18192   
18193   /* Leave the SCOPE.  */
18194   if (pushed_scope)
18195     pop_scope (pushed_scope);
18196
18197   /* If we failed to resolve it, return the original typename.  */
18198   if (!result)
18199     return type;
18200   
18201   /* If lookup found a typename type, resolve that too.  */
18202   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
18203     {
18204       /* Ill-formed programs can cause infinite recursion here, so we
18205          must catch that.  */
18206       TYPENAME_IS_RESOLVING_P (type) = 1;
18207       result = resolve_typename_type (result, only_current_p);
18208       TYPENAME_IS_RESOLVING_P (type) = 0;
18209     }
18210   
18211   /* Qualify the resulting type.  */
18212   quals = cp_type_quals (type);
18213   if (quals)
18214     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
18215
18216   return result;
18217 }
18218
18219 /* EXPR is an expression which is not type-dependent.  Return a proxy
18220    for EXPR that can be used to compute the types of larger
18221    expressions containing EXPR.  */
18222
18223 tree
18224 build_non_dependent_expr (tree expr)
18225 {
18226   tree inner_expr;
18227
18228   /* Preserve null pointer constants so that the type of things like
18229      "p == 0" where "p" is a pointer can be determined.  */
18230   if (null_ptr_cst_p (expr))
18231     return expr;
18232   /* Preserve OVERLOADs; the functions must be available to resolve
18233      types.  */
18234   inner_expr = expr;
18235   if (TREE_CODE (inner_expr) == STMT_EXPR)
18236     inner_expr = stmt_expr_value_expr (inner_expr);
18237   if (TREE_CODE (inner_expr) == ADDR_EXPR)
18238     inner_expr = TREE_OPERAND (inner_expr, 0);
18239   if (TREE_CODE (inner_expr) == COMPONENT_REF)
18240     inner_expr = TREE_OPERAND (inner_expr, 1);
18241   if (is_overloaded_fn (inner_expr)
18242       || TREE_CODE (inner_expr) == OFFSET_REF)
18243     return expr;
18244   /* There is no need to return a proxy for a variable.  */
18245   if (TREE_CODE (expr) == VAR_DECL)
18246     return expr;
18247   /* Preserve string constants; conversions from string constants to
18248      "char *" are allowed, even though normally a "const char *"
18249      cannot be used to initialize a "char *".  */
18250   if (TREE_CODE (expr) == STRING_CST)
18251     return expr;
18252   /* Preserve arithmetic constants, as an optimization -- there is no
18253      reason to create a new node.  */
18254   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
18255     return expr;
18256   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
18257      There is at least one place where we want to know that a
18258      particular expression is a throw-expression: when checking a ?:
18259      expression, there are special rules if the second or third
18260      argument is a throw-expression.  */
18261   if (TREE_CODE (expr) == THROW_EXPR)
18262     return expr;
18263
18264   if (TREE_CODE (expr) == COND_EXPR)
18265     return build3 (COND_EXPR,
18266                    TREE_TYPE (expr),
18267                    TREE_OPERAND (expr, 0),
18268                    (TREE_OPERAND (expr, 1)
18269                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
18270                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
18271                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
18272   if (TREE_CODE (expr) == COMPOUND_EXPR
18273       && !COMPOUND_EXPR_OVERLOADED (expr))
18274     return build2 (COMPOUND_EXPR,
18275                    TREE_TYPE (expr),
18276                    TREE_OPERAND (expr, 0),
18277                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
18278
18279   /* If the type is unknown, it can't really be non-dependent */
18280   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
18281
18282   /* Otherwise, build a NON_DEPENDENT_EXPR.
18283
18284      REFERENCE_TYPEs are not stripped for expressions in templates
18285      because doing so would play havoc with mangling.  Consider, for
18286      example:
18287
18288        template <typename T> void f<T& g>() { g(); }
18289
18290      In the body of "f", the expression for "g" will have
18291      REFERENCE_TYPE, even though the standard says that it should
18292      not.  The reason is that we must preserve the syntactic form of
18293      the expression so that mangling (say) "f<g>" inside the body of
18294      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
18295      stripped here.  */
18296   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
18297 }
18298
18299 /* ARGS is a vector of expressions as arguments to a function call.
18300    Replace the arguments with equivalent non-dependent expressions.
18301    This modifies ARGS in place.  */
18302
18303 void
18304 make_args_non_dependent (VEC(tree,gc) *args)
18305 {
18306   unsigned int ix;
18307   tree arg;
18308
18309   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
18310     {
18311       tree newarg = build_non_dependent_expr (arg);
18312       if (newarg != arg)
18313         VEC_replace (tree, args, ix, newarg);
18314     }
18315 }
18316
18317 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
18318    with a level one deeper than the actual template parms.  */
18319
18320 tree
18321 make_auto (void)
18322 {
18323   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
18324   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
18325                                TYPE_DECL, get_identifier ("auto"), au);
18326   TYPE_STUB_DECL (au) = TYPE_NAME (au);
18327   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
18328     (0, processing_template_decl + 1, processing_template_decl + 1,
18329      TYPE_NAME (au), NULL_TREE);
18330   TYPE_CANONICAL (au) = canonical_type_parameter (au);
18331   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
18332   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
18333
18334   return au;
18335 }
18336
18337 /* Given type ARG, return std::initializer_list<ARG>.  */
18338
18339 static tree
18340 listify (tree arg)
18341 {
18342   tree std_init_list = namespace_binding
18343     (get_identifier ("initializer_list"), std_node);
18344   tree argvec;
18345   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
18346     {    
18347       error ("deducing from brace-enclosed initializer list requires "
18348              "#include <initializer_list>");
18349       return error_mark_node;
18350     }
18351   argvec = make_tree_vec (1);
18352   TREE_VEC_ELT (argvec, 0) = arg;
18353   return lookup_template_class (std_init_list, argvec, NULL_TREE,
18354                                 NULL_TREE, 0, tf_warning_or_error);
18355 }
18356
18357 /* Replace auto in TYPE with std::initializer_list<auto>.  */
18358
18359 static tree
18360 listify_autos (tree type, tree auto_node)
18361 {
18362   tree init_auto = listify (auto_node);
18363   tree argvec = make_tree_vec (1);
18364   TREE_VEC_ELT (argvec, 0) = init_auto;
18365   if (processing_template_decl)
18366     argvec = add_to_template_args (current_template_args (), argvec);
18367   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18368 }
18369
18370 /* walk_tree helper for do_auto_deduction.  */
18371
18372 static tree
18373 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
18374                  void *type)
18375 {
18376   /* Is this a variable with the type we're looking for?  */
18377   if (DECL_P (*tp)
18378       && TREE_TYPE (*tp) == type)
18379     return *tp;
18380   else
18381     return NULL_TREE;
18382 }
18383
18384 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18385    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18386
18387 tree
18388 do_auto_deduction (tree type, tree init, tree auto_node)
18389 {
18390   tree parms, tparms, targs;
18391   tree args[1];
18392   tree decl;
18393   int val;
18394
18395   /* The name of the object being declared shall not appear in the
18396      initializer expression.  */
18397   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
18398   if (decl)
18399     {
18400       error ("variable %q#D with %<auto%> type used in its own "
18401              "initializer", decl);
18402       return error_mark_node;
18403     }
18404
18405   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18406      with either a new invented type template parameter U or, if the
18407      initializer is a braced-init-list (8.5.4), with
18408      std::initializer_list<U>.  */
18409   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18410     type = listify_autos (type, auto_node);
18411
18412   parms = build_tree_list (NULL_TREE, type);
18413   args[0] = init;
18414   tparms = make_tree_vec (1);
18415   targs = make_tree_vec (1);
18416   TREE_VEC_ELT (tparms, 0)
18417     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18418   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18419                                DEDUCE_CALL, LOOKUP_NORMAL);
18420   if (val > 0)
18421     {
18422       error ("unable to deduce %qT from %qE", type, init);
18423       return error_mark_node;
18424     }
18425
18426   /* If the list of declarators contains more than one declarator, the type
18427      of each declared variable is determined as described above. If the
18428      type deduced for the template parameter U is not the same in each
18429      deduction, the program is ill-formed.  */
18430   if (TREE_TYPE (auto_node)
18431       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18432     {
18433       error ("inconsistent deduction for %qT: %qT and then %qT",
18434              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18435       return error_mark_node;
18436     }
18437   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18438
18439   if (processing_template_decl)
18440     targs = add_to_template_args (current_template_args (), targs);
18441   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18442 }
18443
18444 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18445    result.  */
18446
18447 tree
18448 splice_late_return_type (tree type, tree late_return_type)
18449 {
18450   tree argvec;
18451
18452   if (late_return_type == NULL_TREE)
18453     return type;
18454   argvec = make_tree_vec (1);
18455   TREE_VEC_ELT (argvec, 0) = late_return_type;
18456   if (processing_template_decl)
18457     argvec = add_to_template_args (current_template_args (), argvec);
18458   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18459 }
18460
18461 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18462
18463 bool
18464 is_auto (const_tree type)
18465 {
18466   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18467       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18468     return true;
18469   else
18470     return false;
18471 }
18472
18473 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18474    appear as a type-specifier for the declaration in question, we don't
18475    have to look through the whole type.  */
18476
18477 tree
18478 type_uses_auto (tree type)
18479 {
18480   enum tree_code code;
18481   if (is_auto (type))
18482     return type;
18483
18484   code = TREE_CODE (type);
18485
18486   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18487       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18488       || code == METHOD_TYPE || code == ARRAY_TYPE)
18489     return type_uses_auto (TREE_TYPE (type));
18490
18491   if (TYPE_PTRMEMFUNC_P (type))
18492     return type_uses_auto (TREE_TYPE (TREE_TYPE
18493                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18494
18495   return NULL_TREE;
18496 }
18497
18498 /* For a given template T, return the vector of typedefs referenced
18499    in T for which access check is needed at T instantiation time.
18500    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18501    Those typedefs were added to T by the function
18502    append_type_to_template_for_access_check.  */
18503
18504 VEC(qualified_typedef_usage_t,gc)*
18505 get_types_needing_access_check (tree t)
18506 {
18507   tree ti;
18508   VEC(qualified_typedef_usage_t,gc) *result = NULL;
18509
18510   if (!t || t == error_mark_node)
18511     return NULL;
18512
18513   if (!(ti = get_template_info (t)))
18514     return NULL;
18515
18516   if (CLASS_TYPE_P (t)
18517       || TREE_CODE (t) == FUNCTION_DECL)
18518     {
18519       if (!TI_TEMPLATE (ti))
18520         return NULL;
18521
18522       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18523     }
18524
18525   return result;
18526 }
18527
18528 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
18529    tied to T. That list of typedefs will be access checked at
18530    T instantiation time.
18531    T is either a FUNCTION_DECL or a RECORD_TYPE.
18532    TYPE_DECL is a TYPE_DECL node representing a typedef.
18533    SCOPE is the scope through which TYPE_DECL is accessed.
18534    LOCATION is the location of the usage point of TYPE_DECL.
18535
18536    This function is a subroutine of
18537    append_type_to_template_for_access_check.  */
18538
18539 static void
18540 append_type_to_template_for_access_check_1 (tree t,
18541                                             tree type_decl,
18542                                             tree scope,
18543                                             location_t location)
18544 {
18545   qualified_typedef_usage_t typedef_usage;
18546   tree ti;
18547
18548   if (!t || t == error_mark_node)
18549     return;
18550
18551   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18552                || CLASS_TYPE_P (t))
18553               && type_decl
18554               && TREE_CODE (type_decl) == TYPE_DECL
18555               && scope);
18556
18557   if (!(ti = get_template_info (t)))
18558     return;
18559
18560   gcc_assert (TI_TEMPLATE (ti));
18561
18562   typedef_usage.typedef_decl = type_decl;
18563   typedef_usage.context = scope;
18564   typedef_usage.locus = location;
18565
18566   VEC_safe_push (qualified_typedef_usage_t, gc,
18567                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
18568                  &typedef_usage);
18569 }
18570
18571 /* Append TYPE_DECL to the template TEMPL.
18572    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18573    At TEMPL instanciation time, TYPE_DECL will be checked to see
18574    if it can be accessed through SCOPE.
18575    LOCATION is the location of the usage point of TYPE_DECL.
18576
18577    e.g. consider the following code snippet:
18578
18579      class C
18580      {
18581        typedef int myint;
18582      };
18583
18584      template<class U> struct S
18585      {
18586        C::myint mi; // <-- usage point of the typedef C::myint
18587      };
18588
18589      S<char> s;
18590
18591    At S<char> instantiation time, we need to check the access of C::myint
18592    In other words, we need to check the access of the myint typedef through
18593    the C scope. For that purpose, this function will add the myint typedef
18594    and the scope C through which its being accessed to a list of typedefs
18595    tied to the template S. That list will be walked at template instantiation
18596    time and access check performed on each typedefs it contains.
18597    Note that this particular code snippet should yield an error because
18598    myint is private to C.  */
18599
18600 void
18601 append_type_to_template_for_access_check (tree templ,
18602                                           tree type_decl,
18603                                           tree scope,
18604                                           location_t location)
18605 {
18606   qualified_typedef_usage_t *iter;
18607   int i;
18608
18609   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18610
18611   /* Make sure we don't append the type to the template twice.  */
18612   for (i = 0;
18613        VEC_iterate (qualified_typedef_usage_t,
18614                     get_types_needing_access_check (templ),
18615                     i, iter);
18616        ++i)
18617     if (iter->typedef_decl == type_decl && scope == iter->context)
18618       return;
18619
18620   append_type_to_template_for_access_check_1 (templ, type_decl,
18621                                               scope, location);
18622 }
18623
18624 /* Set up the hash tables for template instantiations.  */
18625
18626 void
18627 init_template_processing (void)
18628 {
18629   decl_specializations = htab_create_ggc (37,
18630                                           hash_specialization,
18631                                           eq_specializations,
18632                                           ggc_free);
18633   type_specializations = htab_create_ggc (37,
18634                                           hash_specialization,
18635                                           eq_specializations,
18636                                           ggc_free);
18637 }
18638
18639 /* Print stats about the template hash tables for -fstats.  */
18640
18641 void
18642 print_template_statistics (void)
18643 {
18644   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
18645            "%f collisions\n", (long) htab_size (decl_specializations),
18646            (long) htab_elements (decl_specializations),
18647            htab_collisions (decl_specializations));
18648   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
18649            "%f collisions\n", (long) htab_size (type_specializations),
18650            (long) htab_elements (type_specializations),
18651            htab_collisions (type_specializations));
18652 }
18653
18654 #include "gt-cp-pt.h"