db403c8225a871b3f39fc87a85128b5079cd59c0
[platform/upstream/linaro-gcc.git] / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2    Copyright (C) 1992-2016 Free Software Foundation, Inc.
3    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
4    Rewritten by Jason Merrill (jason@cygnus.com).
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 /* Known bugs or deficiencies include:
23
24      all methods must be provided in header files; can't use a source
25      file that contains only the method templates and "just win".  */
26
27 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "cp-tree.h"
31 #include "timevar.h"
32 #include "stringpool.h"
33 #include "varasm.h"
34 #include "attribs.h"
35 #include "stor-layout.h"
36 #include "intl.h"
37 #include "c-family/c-objc.h"
38 #include "cp-objcp-common.h"
39 #include "toplev.h"
40 #include "tree-iterator.h"
41 #include "type-utils.h"
42 #include "gimplify.h"
43
44 /* The type of functions taking a tree, and some additional data, and
45    returning an int.  */
46 typedef int (*tree_fn_t) (tree, void*);
47
48 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
49    instantiations have been deferred, either because their definitions
50    were not yet available, or because we were putting off doing the work.  */
51 struct GTY ((chain_next ("%h.next"))) pending_template {
52   struct pending_template *next;
53   struct tinst_level *tinst;
54 };
55
56 static GTY(()) struct pending_template *pending_templates;
57 static GTY(()) struct pending_template *last_pending_template;
58
59 int processing_template_parmlist;
60 static int template_header_count;
61
62 static GTY(()) tree saved_trees;
63 static vec<int> inline_parm_levels;
64
65 static GTY(()) struct tinst_level *current_tinst_level;
66
67 static GTY(()) tree saved_access_scope;
68
69 /* Live only within one (recursive) call to tsubst_expr.  We use
70    this to pass the statement expression node from the STMT_EXPR
71    to the EXPR_STMT that is its result.  */
72 static tree cur_stmt_expr;
73
74 // -------------------------------------------------------------------------- //
75 // Local Specialization Stack
76 //
77 // Implementation of the RAII helper for creating new local
78 // specializations.
79 local_specialization_stack::local_specialization_stack ()
80   : saved (local_specializations)
81 {
82   local_specializations = new hash_map<tree, tree>;
83 }
84
85 local_specialization_stack::~local_specialization_stack ()
86 {
87   delete local_specializations;
88   local_specializations = saved;
89 }
90
91 /* True if we've recursed into fn_type_unification too many times.  */
92 static bool excessive_deduction_depth;
93
94 struct GTY((for_user)) spec_entry
95 {
96   tree tmpl;
97   tree args;
98   tree spec;
99 };
100
101 struct spec_hasher : ggc_ptr_hash<spec_entry>
102 {
103   static hashval_t hash (spec_entry *);
104   static bool equal (spec_entry *, spec_entry *);
105 };
106
107 static GTY (()) hash_table<spec_hasher> *decl_specializations;
108
109 static GTY (()) hash_table<spec_hasher> *type_specializations;
110
111 /* Contains canonical template parameter types. The vector is indexed by
112    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
113    TREE_LIST, whose TREE_VALUEs contain the canonical template
114    parameters of various types and levels.  */
115 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
116
117 #define UNIFY_ALLOW_NONE 0
118 #define UNIFY_ALLOW_MORE_CV_QUAL 1
119 #define UNIFY_ALLOW_LESS_CV_QUAL 2
120 #define UNIFY_ALLOW_DERIVED 4
121 #define UNIFY_ALLOW_INTEGER 8
122 #define UNIFY_ALLOW_OUTER_LEVEL 16
123 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
124 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
125
126 enum template_base_result {
127   tbr_incomplete_type,
128   tbr_ambiguous_baseclass,
129   tbr_success
130 };
131
132 static void push_access_scope (tree);
133 static void pop_access_scope (tree);
134 static bool resolve_overloaded_unification (tree, tree, tree, tree,
135                                             unification_kind_t, int,
136                                             bool);
137 static int try_one_overload (tree, tree, tree, tree, tree,
138                              unification_kind_t, int, bool, bool);
139 static int unify (tree, tree, tree, tree, int, bool);
140 static void add_pending_template (tree);
141 static tree reopen_tinst_level (struct tinst_level *);
142 static tree tsubst_initializer_list (tree, tree);
143 static tree get_partial_spec_bindings (tree, tree, tree, tree);
144 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
145                                    bool, bool);
146 static tree coerce_innermost_template_parms (tree, tree, tree, tsubst_flags_t,
147                                               bool, bool);
148 static void tsubst_enum (tree, tree, tree);
149 static tree add_to_template_args (tree, tree);
150 static tree add_outermost_template_args (tree, tree);
151 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
152 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
153                                              tree);
154 static int type_unification_real (tree, tree, tree, const tree *,
155                                   unsigned int, int, unification_kind_t, int,
156                                   vec<deferred_access_check, va_gc> **,
157                                   bool);
158 static void note_template_header (int);
159 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
160 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
161 static tree convert_template_argument (tree, tree, tree,
162                                        tsubst_flags_t, int, tree);
163 static tree for_each_template_parm (tree, tree_fn_t, void*,
164                                     hash_set<tree> *, bool);
165 static tree expand_template_argument_pack (tree);
166 static tree build_template_parm_index (int, int, int, tree, tree);
167 static bool inline_needs_template_parms (tree, bool);
168 static void push_inline_template_parms_recursive (tree, int);
169 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
170 static int mark_template_parm (tree, void *);
171 static int template_parm_this_level_p (tree, void *);
172 static tree tsubst_friend_function (tree, tree);
173 static tree tsubst_friend_class (tree, tree);
174 static int can_complete_type_without_circularity (tree);
175 static tree get_bindings (tree, tree, tree, bool);
176 static int template_decl_level (tree);
177 static int check_cv_quals_for_unify (int, tree, tree);
178 static void template_parm_level_and_index (tree, int*, int*);
179 static int unify_pack_expansion (tree, tree, tree,
180                                  tree, unification_kind_t, bool, bool);
181 static tree copy_template_args (tree);
182 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
183 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
184 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
185 static tree most_specialized_partial_spec (tree, tsubst_flags_t);
186 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
187 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
188 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
189 static bool check_specialization_scope (void);
190 static tree process_partial_specialization (tree);
191 static void set_current_access_from_decl (tree);
192 static enum template_base_result get_template_base (tree, tree, tree, tree,
193                                                     bool , tree *);
194 static tree try_class_unification (tree, tree, tree, tree, bool);
195 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
196                                            tree, tree);
197 static bool template_template_parm_bindings_ok_p (tree, tree);
198 static void tsubst_default_arguments (tree, tsubst_flags_t);
199 static tree for_each_template_parm_r (tree *, int *, void *);
200 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
201 static void copy_default_args_to_explicit_spec (tree);
202 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
203 static bool dependent_template_arg_p (tree);
204 static bool any_template_arguments_need_structural_equality_p (tree);
205 static bool dependent_type_p_r (tree);
206 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
207 static tree tsubst_decl (tree, tree, tsubst_flags_t);
208 static void perform_typedefs_access_check (tree tmpl, tree targs);
209 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
210                                                         location_t);
211 static tree listify (tree);
212 static tree listify_autos (tree, tree);
213 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
214 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
215 static bool complex_alias_template_p (const_tree tmpl);
216 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
217
218 /* Make the current scope suitable for access checking when we are
219    processing T.  T can be FUNCTION_DECL for instantiated function
220    template, VAR_DECL for static member variable, or TYPE_DECL for
221    alias template (needed by instantiate_decl).  */
222
223 static void
224 push_access_scope (tree t)
225 {
226   gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
227               || TREE_CODE (t) == TYPE_DECL);
228
229   if (DECL_FRIEND_CONTEXT (t))
230     push_nested_class (DECL_FRIEND_CONTEXT (t));
231   else if (DECL_CLASS_SCOPE_P (t))
232     push_nested_class (DECL_CONTEXT (t));
233   else
234     push_to_top_level ();
235
236   if (TREE_CODE (t) == FUNCTION_DECL)
237     {
238       saved_access_scope = tree_cons
239         (NULL_TREE, current_function_decl, saved_access_scope);
240       current_function_decl = t;
241     }
242 }
243
244 /* Restore the scope set up by push_access_scope.  T is the node we
245    are processing.  */
246
247 static void
248 pop_access_scope (tree t)
249 {
250   if (TREE_CODE (t) == FUNCTION_DECL)
251     {
252       current_function_decl = TREE_VALUE (saved_access_scope);
253       saved_access_scope = TREE_CHAIN (saved_access_scope);
254     }
255
256   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
257     pop_nested_class ();
258   else
259     pop_from_top_level ();
260 }
261
262 /* Do any processing required when DECL (a member template
263    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
264    to DECL, unless it is a specialization, in which case the DECL
265    itself is returned.  */
266
267 tree
268 finish_member_template_decl (tree decl)
269 {
270   if (decl == error_mark_node)
271     return error_mark_node;
272
273   gcc_assert (DECL_P (decl));
274
275   if (TREE_CODE (decl) == TYPE_DECL)
276     {
277       tree type;
278
279       type = TREE_TYPE (decl);
280       if (type == error_mark_node)
281         return error_mark_node;
282       if (MAYBE_CLASS_TYPE_P (type)
283           && CLASSTYPE_TEMPLATE_INFO (type)
284           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
285         {
286           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
287           check_member_template (tmpl);
288           return tmpl;
289         }
290       return NULL_TREE;
291     }
292   else if (TREE_CODE (decl) == FIELD_DECL)
293     error ("data member %qD cannot be a member template", decl);
294   else if (DECL_TEMPLATE_INFO (decl))
295     {
296       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
297         {
298           check_member_template (DECL_TI_TEMPLATE (decl));
299           return DECL_TI_TEMPLATE (decl);
300         }
301       else
302         return decl;
303     }
304   else
305     error ("invalid member template declaration %qD", decl);
306
307   return error_mark_node;
308 }
309
310 /* Create a template info node.  */
311
312 tree
313 build_template_info (tree template_decl, tree template_args)
314 {
315   tree result = make_node (TEMPLATE_INFO);
316   TI_TEMPLATE (result) = template_decl;
317   TI_ARGS (result) = template_args;
318   return result;
319 }
320
321 /* Return the template info node corresponding to T, whatever T is.  */
322
323 tree
324 get_template_info (const_tree t)
325 {
326   tree tinfo = NULL_TREE;
327
328   if (!t || t == error_mark_node)
329     return NULL;
330
331   if (TREE_CODE (t) == NAMESPACE_DECL
332       || TREE_CODE (t) == PARM_DECL)
333     return NULL;
334
335   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
336     tinfo = DECL_TEMPLATE_INFO (t);
337
338   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
339     t = TREE_TYPE (t);
340
341   if (OVERLOAD_TYPE_P (t))
342     tinfo = TYPE_TEMPLATE_INFO (t);
343   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
344     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
345
346   return tinfo;
347 }
348
349 /* Returns the template nesting level of the indicated class TYPE.
350
351    For example, in:
352      template <class T>
353      struct A
354      {
355        template <class U>
356        struct B {};
357      };
358
359    A<T>::B<U> has depth two, while A<T> has depth one.
360    Both A<T>::B<int> and A<int>::B<U> have depth one, if
361    they are instantiations, not specializations.
362
363    This function is guaranteed to return 0 if passed NULL_TREE so
364    that, for example, `template_class_depth (current_class_type)' is
365    always safe.  */
366
367 int
368 template_class_depth (tree type)
369 {
370   int depth;
371
372   for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
373     {
374       tree tinfo = get_template_info (type);
375
376       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
377           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
378         ++depth;
379
380       if (DECL_P (type))
381         type = CP_DECL_CONTEXT (type);
382       else if (LAMBDA_TYPE_P (type))
383         type = LAMBDA_TYPE_EXTRA_SCOPE (type);
384       else
385         type = CP_TYPE_CONTEXT (type);
386     }
387
388   return depth;
389 }
390
391 /* Subroutine of maybe_begin_member_template_processing.
392    Returns true if processing DECL needs us to push template parms.  */
393
394 static bool
395 inline_needs_template_parms (tree decl, bool nsdmi)
396 {
397   if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
398     return false;
399
400   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
401           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
402 }
403
404 /* Subroutine of maybe_begin_member_template_processing.
405    Push the template parms in PARMS, starting from LEVELS steps into the
406    chain, and ending at the beginning, since template parms are listed
407    innermost first.  */
408
409 static void
410 push_inline_template_parms_recursive (tree parmlist, int levels)
411 {
412   tree parms = TREE_VALUE (parmlist);
413   int i;
414
415   if (levels > 1)
416     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
417
418   ++processing_template_decl;
419   current_template_parms
420     = tree_cons (size_int (processing_template_decl),
421                  parms, current_template_parms);
422   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
423
424   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
425                NULL);
426   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
427     {
428       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
429
430       if (error_operand_p (parm))
431         continue;
432
433       gcc_assert (DECL_P (parm));
434
435       switch (TREE_CODE (parm))
436         {
437         case TYPE_DECL:
438         case TEMPLATE_DECL:
439           pushdecl (parm);
440           break;
441
442         case PARM_DECL:
443           /* Push the CONST_DECL.  */
444           pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
445           break;
446
447         default:
448           gcc_unreachable ();
449         }
450     }
451 }
452
453 /* Restore the template parameter context for a member template, a
454    friend template defined in a class definition, or a non-template
455    member of template class.  */
456
457 void
458 maybe_begin_member_template_processing (tree decl)
459 {
460   tree parms;
461   int levels = 0;
462   bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
463
464   if (nsdmi)
465     {
466       tree ctx = DECL_CONTEXT (decl);
467       decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
468               /* Disregard full specializations (c++/60999).  */
469               && uses_template_parms (ctx)
470               ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
471     }
472
473   if (inline_needs_template_parms (decl, nsdmi))
474     {
475       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
476       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
477
478       if (DECL_TEMPLATE_SPECIALIZATION (decl))
479         {
480           --levels;
481           parms = TREE_CHAIN (parms);
482         }
483
484       push_inline_template_parms_recursive (parms, levels);
485     }
486
487   /* Remember how many levels of template parameters we pushed so that
488      we can pop them later.  */
489   inline_parm_levels.safe_push (levels);
490 }
491
492 /* Undo the effects of maybe_begin_member_template_processing.  */
493
494 void
495 maybe_end_member_template_processing (void)
496 {
497   int i;
498   int last;
499
500   if (inline_parm_levels.length () == 0)
501     return;
502
503   last = inline_parm_levels.pop ();
504   for (i = 0; i < last; ++i)
505     {
506       --processing_template_decl;
507       current_template_parms = TREE_CHAIN (current_template_parms);
508       poplevel (0, 0, 0);
509     }
510 }
511
512 /* Return a new template argument vector which contains all of ARGS,
513    but has as its innermost set of arguments the EXTRA_ARGS.  */
514
515 static tree
516 add_to_template_args (tree args, tree extra_args)
517 {
518   tree new_args;
519   int extra_depth;
520   int i;
521   int j;
522
523   if (args == NULL_TREE || extra_args == error_mark_node)
524     return extra_args;
525
526   extra_depth = TMPL_ARGS_DEPTH (extra_args);
527   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
528
529   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
530     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
531
532   for (j = 1; j <= extra_depth; ++j, ++i)
533     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
534
535   return new_args;
536 }
537
538 /* Like add_to_template_args, but only the outermost ARGS are added to
539    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
540    (EXTRA_ARGS) levels are added.  This function is used to combine
541    the template arguments from a partial instantiation with the
542    template arguments used to attain the full instantiation from the
543    partial instantiation.  */
544
545 static tree
546 add_outermost_template_args (tree args, tree extra_args)
547 {
548   tree new_args;
549
550   /* If there are more levels of EXTRA_ARGS than there are ARGS,
551      something very fishy is going on.  */
552   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
553
554   /* If *all* the new arguments will be the EXTRA_ARGS, just return
555      them.  */
556   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
557     return extra_args;
558
559   /* For the moment, we make ARGS look like it contains fewer levels.  */
560   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
561
562   new_args = add_to_template_args (args, extra_args);
563
564   /* Now, we restore ARGS to its full dimensions.  */
565   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
566
567   return new_args;
568 }
569
570 /* Return the N levels of innermost template arguments from the ARGS.  */
571
572 tree
573 get_innermost_template_args (tree args, int n)
574 {
575   tree new_args;
576   int extra_levels;
577   int i;
578
579   gcc_assert (n >= 0);
580
581   /* If N is 1, just return the innermost set of template arguments.  */
582   if (n == 1)
583     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
584
585   /* If we're not removing anything, just return the arguments we were
586      given.  */
587   extra_levels = TMPL_ARGS_DEPTH (args) - n;
588   gcc_assert (extra_levels >= 0);
589   if (extra_levels == 0)
590     return args;
591
592   /* Make a new set of arguments, not containing the outer arguments.  */
593   new_args = make_tree_vec (n);
594   for (i = 1; i <= n; ++i)
595     SET_TMPL_ARGS_LEVEL (new_args, i,
596                          TMPL_ARGS_LEVEL (args, i + extra_levels));
597
598   return new_args;
599 }
600
601 /* The inverse of get_innermost_template_args: Return all but the innermost
602    EXTRA_LEVELS levels of template arguments from the ARGS.  */
603
604 static tree
605 strip_innermost_template_args (tree args, int extra_levels)
606 {
607   tree new_args;
608   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
609   int i;
610
611   gcc_assert (n >= 0);
612
613   /* If N is 1, just return the outermost set of template arguments.  */
614   if (n == 1)
615     return TMPL_ARGS_LEVEL (args, 1);
616
617   /* If we're not removing anything, just return the arguments we were
618      given.  */
619   gcc_assert (extra_levels >= 0);
620   if (extra_levels == 0)
621     return args;
622
623   /* Make a new set of arguments, not containing the inner arguments.  */
624   new_args = make_tree_vec (n);
625   for (i = 1; i <= n; ++i)
626     SET_TMPL_ARGS_LEVEL (new_args, i,
627                          TMPL_ARGS_LEVEL (args, i));
628
629   return new_args;
630 }
631
632 /* We've got a template header coming up; push to a new level for storing
633    the parms.  */
634
635 void
636 begin_template_parm_list (void)
637 {
638   /* We use a non-tag-transparent scope here, which causes pushtag to
639      put tags in this scope, rather than in the enclosing class or
640      namespace scope.  This is the right thing, since we want
641      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
642      global template class, push_template_decl handles putting the
643      TEMPLATE_DECL into top-level scope.  For a nested template class,
644      e.g.:
645
646        template <class T> struct S1 {
647          template <class T> struct S2 {};
648        };
649
650      pushtag contains special code to call pushdecl_with_scope on the
651      TEMPLATE_DECL for S2.  */
652   begin_scope (sk_template_parms, NULL);
653   ++processing_template_decl;
654   ++processing_template_parmlist;
655   note_template_header (0);
656
657   /* Add a dummy parameter level while we process the parameter list.  */
658   current_template_parms
659     = tree_cons (size_int (processing_template_decl),
660                  make_tree_vec (0),
661                  current_template_parms);
662 }
663
664 /* This routine is called when a specialization is declared.  If it is
665    invalid to declare a specialization here, an error is reported and
666    false is returned, otherwise this routine will return true.  */
667
668 static bool
669 check_specialization_scope (void)
670 {
671   tree scope = current_scope ();
672
673   /* [temp.expl.spec]
674
675      An explicit specialization shall be declared in the namespace of
676      which the template is a member, or, for member templates, in the
677      namespace of which the enclosing class or enclosing class
678      template is a member.  An explicit specialization of a member
679      function, member class or static data member of a class template
680      shall be declared in the namespace of which the class template
681      is a member.  */
682   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
683     {
684       error ("explicit specialization in non-namespace scope %qD", scope);
685       return false;
686     }
687
688   /* [temp.expl.spec]
689
690      In an explicit specialization declaration for a member of a class
691      template or a member template that appears in namespace scope,
692      the member template and some of its enclosing class templates may
693      remain unspecialized, except that the declaration shall not
694      explicitly specialize a class member template if its enclosing
695      class templates are not explicitly specialized as well.  */
696   if (current_template_parms)
697     {
698       error ("enclosing class templates are not explicitly specialized");
699       return false;
700     }
701
702   return true;
703 }
704
705 /* We've just seen template <>.  */
706
707 bool
708 begin_specialization (void)
709 {
710   begin_scope (sk_template_spec, NULL);
711   note_template_header (1);
712   return check_specialization_scope ();
713 }
714
715 /* Called at then end of processing a declaration preceded by
716    template<>.  */
717
718 void
719 end_specialization (void)
720 {
721   finish_scope ();
722   reset_specialization ();
723 }
724
725 /* Any template <>'s that we have seen thus far are not referring to a
726    function specialization.  */
727
728 void
729 reset_specialization (void)
730 {
731   processing_specialization = 0;
732   template_header_count = 0;
733 }
734
735 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
736    it was of the form template <>.  */
737
738 static void
739 note_template_header (int specialization)
740 {
741   processing_specialization = specialization;
742   template_header_count++;
743 }
744
745 /* We're beginning an explicit instantiation.  */
746
747 void
748 begin_explicit_instantiation (void)
749 {
750   gcc_assert (!processing_explicit_instantiation);
751   processing_explicit_instantiation = true;
752 }
753
754
755 void
756 end_explicit_instantiation (void)
757 {
758   gcc_assert (processing_explicit_instantiation);
759   processing_explicit_instantiation = false;
760 }
761
762 /* An explicit specialization or partial specialization of TMPL is being
763    declared.  Check that the namespace in which the specialization is
764    occurring is permissible.  Returns false iff it is invalid to
765    specialize TMPL in the current namespace.  */
766
767 static bool
768 check_specialization_namespace (tree tmpl)
769 {
770   tree tpl_ns = decl_namespace_context (tmpl);
771
772   /* [tmpl.expl.spec]
773
774      An explicit specialization shall be declared in the namespace of
775      which the template is a member, or, for member templates, in the
776      namespace of which the enclosing class or enclosing class
777      template is a member.  An explicit specialization of a member
778      function, member class or static data member of a class template
779      shall be declared in the namespace of which the class template is
780      a member.  */
781   if (current_scope() != DECL_CONTEXT (tmpl)
782       && !at_namespace_scope_p ())
783     {
784       error ("specialization of %qD must appear at namespace scope", tmpl);
785       return false;
786     }
787   if (is_associated_namespace (current_namespace, tpl_ns))
788     /* Same or super-using namespace.  */
789     return true;
790   else
791     {
792       permerror (input_location,
793                  "specialization of %qD in different namespace", tmpl);
794       permerror (DECL_SOURCE_LOCATION (tmpl),
795                  "  from definition of %q#D", tmpl);
796       return false;
797     }
798 }
799
800 /* SPEC is an explicit instantiation.  Check that it is valid to
801    perform this explicit instantiation in the current namespace.  */
802
803 static void
804 check_explicit_instantiation_namespace (tree spec)
805 {
806   tree ns;
807
808   /* DR 275: An explicit instantiation shall appear in an enclosing
809      namespace of its template.  */
810   ns = decl_namespace_context (spec);
811   if (!is_ancestor (current_namespace, ns))
812     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
813                "(which does not enclose namespace %qD)",
814                spec, current_namespace, ns);
815 }
816
817 // Returns the type of a template specialization only if that
818 // specialization needs to be defined. Otherwise (e.g., if the type has
819 // already been defined), the function returns NULL_TREE.
820 static tree
821 maybe_new_partial_specialization (tree type)
822 {
823   // An implicit instantiation of an incomplete type implies
824   // the definition of a new class template.
825   //
826   //    template<typename T>
827   //      struct S;
828   //
829   //    template<typename T>
830   //      struct S<T*>;
831   //
832   // Here, S<T*> is an implicit instantiation of S whose type
833   // is incomplete.
834   if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
835     return type;
836
837   // It can also be the case that TYPE is a completed specialization.
838   // Continuing the previous example, suppose we also declare:
839   //
840   //    template<typename T>
841   //      requires Integral<T>
842   //        struct S<T*>;
843   //
844   // Here, S<T*> refers to the specialization S<T*> defined
845   // above. However, we need to differentiate definitions because
846   // we intend to define a new partial specialization. In this case,
847   // we rely on the fact that the constraints are different for
848   // this declaration than that above.
849   //
850   // Note that we also get here for injected class names and
851   // late-parsed template definitions. We must ensure that we
852   // do not create new type declarations for those cases.
853   if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
854     {
855       tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
856       tree args = CLASSTYPE_TI_ARGS (type);
857
858       // If there are no template parameters, this cannot be a new
859       // partial template specializtion?
860       if (!current_template_parms)
861         return NULL_TREE;
862
863       // The injected-class-name is not a new partial specialization.
864       if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
865         return NULL_TREE;
866
867       // If the constraints are not the same as those of the primary
868       // then, we can probably create a new specialization.
869       tree type_constr = current_template_constraints ();
870
871       if (type == TREE_TYPE (tmpl))
872         {
873           tree main_constr = get_constraints (tmpl);
874           if (equivalent_constraints (type_constr, main_constr))
875             return NULL_TREE;
876         }
877
878       // Also, if there's a pre-existing specialization with matching
879       // constraints, then this also isn't new.
880       tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
881       while (specs)
882         {
883           tree spec_tmpl = TREE_VALUE (specs);
884           tree spec_args = TREE_PURPOSE (specs);
885           tree spec_constr = get_constraints (spec_tmpl);
886           if (comp_template_args (args, spec_args)
887               && equivalent_constraints (type_constr, spec_constr))
888             return NULL_TREE;
889           specs = TREE_CHAIN (specs);
890         }
891
892       // Create a new type node (and corresponding type decl)
893       // for the newly declared specialization.
894       tree t = make_class_type (TREE_CODE (type));
895       CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
896       TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (type);
897       SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
898
899       /* We only need a separate type node for storing the definition of this
900          partial specialization; uses of S<T*> are unconstrained, so all are
901          equivalent.  So keep TYPE_CANONICAL the same.  */
902       TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
903
904       // Build the corresponding type decl.
905       tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
906       DECL_CONTEXT (d) = TYPE_CONTEXT (t);
907       DECL_SOURCE_LOCATION (d) = input_location;
908
909       return t;
910     }
911
912   return NULL_TREE;
913 }
914
915 /* The TYPE is being declared.  If it is a template type, that means it
916    is a partial specialization.  Do appropriate error-checking.  */
917
918 tree
919 maybe_process_partial_specialization (tree type)
920 {
921   tree context;
922
923   if (type == error_mark_node)
924     return error_mark_node;
925
926   /* A lambda that appears in specialization context is not itself a
927      specialization.  */
928   if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
929     return type;
930
931   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
932     {
933       error ("name of class shadows template template parameter %qD",
934              TYPE_NAME (type));
935       return error_mark_node;
936     }
937
938   context = TYPE_CONTEXT (type);
939
940   if (TYPE_ALIAS_P (type))
941     {
942       if (TYPE_TEMPLATE_INFO (type)
943           && DECL_ALIAS_TEMPLATE_P (TYPE_TI_TEMPLATE (type)))
944         error ("specialization of alias template %qD",
945                TYPE_TI_TEMPLATE (type));
946       else
947         error ("explicit specialization of non-template %qT", type);
948       return error_mark_node;
949     }
950   else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
951     {
952       /* This is for ordinary explicit specialization and partial
953          specialization of a template class such as:
954
955            template <> class C<int>;
956
957          or:
958
959            template <class T> class C<T*>;
960
961          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
962
963       if (tree t = maybe_new_partial_specialization (type))
964         {
965           if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (t))
966               && !at_namespace_scope_p ())
967             return error_mark_node;
968           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (t);
969           DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (t)) = input_location;
970           if (processing_template_decl)
971             {
972               tree decl = push_template_decl (TYPE_MAIN_DECL (t));
973               if (decl == error_mark_node)
974                 return error_mark_node;
975               return TREE_TYPE (decl);
976             }
977         }
978       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
979         error ("specialization of %qT after instantiation", type);
980       else if (errorcount && !processing_specialization
981                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
982                && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
983         /* Trying to define a specialization either without a template<> header
984            or in an inappropriate place.  We've already given an error, so just
985            bail now so we don't actually define the specialization.  */
986         return error_mark_node;
987     }
988   else if (CLASS_TYPE_P (type)
989            && !CLASSTYPE_USE_TEMPLATE (type)
990            && CLASSTYPE_TEMPLATE_INFO (type)
991            && context && CLASS_TYPE_P (context)
992            && CLASSTYPE_TEMPLATE_INFO (context))
993     {
994       /* This is for an explicit specialization of member class
995          template according to [temp.expl.spec/18]:
996
997            template <> template <class U> class C<int>::D;
998
999          The context `C<int>' must be an implicit instantiation.
1000          Otherwise this is just a member class template declared
1001          earlier like:
1002
1003            template <> class C<int> { template <class U> class D; };
1004            template <> template <class U> class C<int>::D;
1005
1006          In the first case, `C<int>::D' is a specialization of `C<T>::D'
1007          while in the second case, `C<int>::D' is a primary template
1008          and `C<T>::D' may not exist.  */
1009
1010       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1011           && !COMPLETE_TYPE_P (type))
1012         {
1013           tree t;
1014           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1015
1016           if (current_namespace
1017               != decl_namespace_context (tmpl))
1018             {
1019               permerror (input_location,
1020                          "specializing %q#T in different namespace", type);
1021               permerror (DECL_SOURCE_LOCATION (tmpl),
1022                          "  from definition of %q#D", tmpl);
1023             }
1024
1025           /* Check for invalid specialization after instantiation:
1026
1027                template <> template <> class C<int>::D<int>;
1028                template <> template <class U> class C<int>::D;  */
1029
1030           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1031                t; t = TREE_CHAIN (t))
1032             {
1033               tree inst = TREE_VALUE (t);
1034               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1035                   || !COMPLETE_OR_OPEN_TYPE_P (inst))
1036                 {
1037                   /* We already have a full specialization of this partial
1038                      instantiation, or a full specialization has been
1039                      looked up but not instantiated.  Reassign it to the
1040                      new member specialization template.  */
1041                   spec_entry elt;
1042                   spec_entry *entry;
1043
1044                   elt.tmpl = most_general_template (tmpl);
1045                   elt.args = CLASSTYPE_TI_ARGS (inst);
1046                   elt.spec = inst;
1047
1048                   type_specializations->remove_elt (&elt);
1049
1050                   elt.tmpl = tmpl;
1051                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1052
1053                   spec_entry **slot
1054                     = type_specializations->find_slot (&elt, INSERT);
1055                   entry = ggc_alloc<spec_entry> ();
1056                   *entry = elt;
1057                   *slot = entry;
1058                 }
1059               else
1060                 /* But if we've had an implicit instantiation, that's a
1061                    problem ([temp.expl.spec]/6).  */
1062                 error ("specialization %qT after instantiation %qT",
1063                        type, inst);
1064             }
1065
1066           /* Mark TYPE as a specialization.  And as a result, we only
1067              have one level of template argument for the innermost
1068              class template.  */
1069           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1070           DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1071           CLASSTYPE_TI_ARGS (type)
1072             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1073         }
1074     }
1075   else if (processing_specialization)
1076     {
1077        /* Someday C++0x may allow for enum template specialization.  */
1078       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1079           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1080         pedwarn (input_location, OPT_Wpedantic, "template specialization "
1081                  "of %qD not allowed by ISO C++", type);
1082       else
1083         {
1084           error ("explicit specialization of non-template %qT", type);
1085           return error_mark_node;
1086         }
1087     }
1088
1089   return type;
1090 }
1091
1092 /* Returns nonzero if we can optimize the retrieval of specializations
1093    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
1094    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
1095
1096 static inline bool
1097 optimize_specialization_lookup_p (tree tmpl)
1098 {
1099   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1100           && DECL_CLASS_SCOPE_P (tmpl)
1101           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1102              parameter.  */
1103           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1104           /* The optimized lookup depends on the fact that the
1105              template arguments for the member function template apply
1106              purely to the containing class, which is not true if the
1107              containing class is an explicit or partial
1108              specialization.  */
1109           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1110           && !DECL_MEMBER_TEMPLATE_P (tmpl)
1111           && !DECL_CONV_FN_P (tmpl)
1112           /* It is possible to have a template that is not a member
1113              template and is not a member of a template class:
1114
1115              template <typename T>
1116              struct S { friend A::f(); };
1117
1118              Here, the friend function is a template, but the context does
1119              not have template information.  The optimized lookup relies
1120              on having ARGS be the template arguments for both the class
1121              and the function template.  */
1122           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1123 }
1124
1125 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1126    gone through coerce_template_parms by now.  */
1127
1128 static void
1129 verify_unstripped_args (tree args)
1130 {
1131   ++processing_template_decl;
1132   if (!any_dependent_template_arguments_p (args))
1133     {
1134       tree inner = INNERMOST_TEMPLATE_ARGS (args);
1135       for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1136         {
1137           tree arg = TREE_VEC_ELT (inner, i);
1138           if (TREE_CODE (arg) == TEMPLATE_DECL)
1139             /* OK */;
1140           else if (TYPE_P (arg))
1141             gcc_assert (strip_typedefs (arg, NULL) == arg);
1142           else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1143             /* Allow typedefs on the type of a non-type argument, since a
1144                parameter can have them.  */;
1145           else
1146             gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1147         }
1148     }
1149   --processing_template_decl;
1150 }
1151
1152 /* Retrieve the specialization (in the sense of [temp.spec] - a
1153    specialization is either an instantiation or an explicit
1154    specialization) of TMPL for the given template ARGS.  If there is
1155    no such specialization, return NULL_TREE.  The ARGS are a vector of
1156    arguments, or a vector of vectors of arguments, in the case of
1157    templates with more than one level of parameters.
1158
1159    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1160    then we search for a partial specialization matching ARGS.  This
1161    parameter is ignored if TMPL is not a class template.
1162
1163    We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1164    result is a NONTYPE_ARGUMENT_PACK.  */
1165
1166 static tree
1167 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1168 {
1169   if (tmpl == NULL_TREE)
1170     return NULL_TREE;
1171
1172   if (args == error_mark_node)
1173     return NULL_TREE;
1174
1175   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1176               || TREE_CODE (tmpl) == FIELD_DECL);
1177
1178   /* There should be as many levels of arguments as there are
1179      levels of parameters.  */
1180   gcc_assert (TMPL_ARGS_DEPTH (args)
1181               == (TREE_CODE (tmpl) == TEMPLATE_DECL
1182                   ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1183                   : template_class_depth (DECL_CONTEXT (tmpl))));
1184
1185   if (flag_checking)
1186     verify_unstripped_args (args);
1187
1188   if (optimize_specialization_lookup_p (tmpl))
1189     {
1190       tree class_template;
1191       tree class_specialization;
1192       vec<tree, va_gc> *methods;
1193       tree fns;
1194       int idx;
1195
1196       /* The template arguments actually apply to the containing
1197          class.  Find the class specialization with those
1198          arguments.  */
1199       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1200       class_specialization
1201         = retrieve_specialization (class_template, args, 0);
1202       if (!class_specialization)
1203         return NULL_TREE;
1204       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
1205          for the specialization.  */
1206       idx = class_method_index_for_fn (class_specialization, tmpl);
1207       if (idx == -1)
1208         return NULL_TREE;
1209       /* Iterate through the methods with the indicated name, looking
1210          for the one that has an instance of TMPL.  */
1211       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1212       for (fns = (*methods)[idx]; fns; fns = OVL_NEXT (fns))
1213         {
1214           tree fn = OVL_CURRENT (fns);
1215           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1216               /* using-declarations can add base methods to the method vec,
1217                  and we don't want those here.  */
1218               && DECL_CONTEXT (fn) == class_specialization)
1219             return fn;
1220         }
1221       return NULL_TREE;
1222     }
1223   else
1224     {
1225       spec_entry *found;
1226       spec_entry elt;
1227       hash_table<spec_hasher> *specializations;
1228
1229       elt.tmpl = tmpl;
1230       elt.args = args;
1231       elt.spec = NULL_TREE;
1232
1233       if (DECL_CLASS_TEMPLATE_P (tmpl))
1234         specializations = type_specializations;
1235       else
1236         specializations = decl_specializations;
1237
1238       if (hash == 0)
1239         hash = spec_hasher::hash (&elt);
1240       found = specializations->find_with_hash (&elt, hash);
1241       if (found)
1242         return found->spec;
1243     }
1244
1245   return NULL_TREE;
1246 }
1247
1248 /* Like retrieve_specialization, but for local declarations.  */
1249
1250 tree
1251 retrieve_local_specialization (tree tmpl)
1252 {
1253   if (local_specializations == NULL)
1254     return NULL_TREE;
1255
1256   tree *slot = local_specializations->get (tmpl);
1257   return slot ? *slot : NULL_TREE;
1258 }
1259
1260 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1261
1262 int
1263 is_specialization_of (tree decl, tree tmpl)
1264 {
1265   tree t;
1266
1267   if (TREE_CODE (decl) == FUNCTION_DECL)
1268     {
1269       for (t = decl;
1270            t != NULL_TREE;
1271            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1272         if (t == tmpl)
1273           return 1;
1274     }
1275   else
1276     {
1277       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1278
1279       for (t = TREE_TYPE (decl);
1280            t != NULL_TREE;
1281            t = CLASSTYPE_USE_TEMPLATE (t)
1282              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1283         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1284           return 1;
1285     }
1286
1287   return 0;
1288 }
1289
1290 /* Returns nonzero iff DECL is a specialization of friend declaration
1291    FRIEND_DECL according to [temp.friend].  */
1292
1293 bool
1294 is_specialization_of_friend (tree decl, tree friend_decl)
1295 {
1296   bool need_template = true;
1297   int template_depth;
1298
1299   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1300               || TREE_CODE (decl) == TYPE_DECL);
1301
1302   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1303      of a template class, we want to check if DECL is a specialization
1304      if this.  */
1305   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1306       && DECL_TEMPLATE_INFO (friend_decl)
1307       && !DECL_USE_TEMPLATE (friend_decl))
1308     {
1309       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1310       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1311       need_template = false;
1312     }
1313   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1314            && !PRIMARY_TEMPLATE_P (friend_decl))
1315     need_template = false;
1316
1317   /* There is nothing to do if this is not a template friend.  */
1318   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1319     return false;
1320
1321   if (is_specialization_of (decl, friend_decl))
1322     return true;
1323
1324   /* [temp.friend/6]
1325      A member of a class template may be declared to be a friend of a
1326      non-template class.  In this case, the corresponding member of
1327      every specialization of the class template is a friend of the
1328      class granting friendship.
1329
1330      For example, given a template friend declaration
1331
1332        template <class T> friend void A<T>::f();
1333
1334      the member function below is considered a friend
1335
1336        template <> struct A<int> {
1337          void f();
1338        };
1339
1340      For this type of template friend, TEMPLATE_DEPTH below will be
1341      nonzero.  To determine if DECL is a friend of FRIEND, we first
1342      check if the enclosing class is a specialization of another.  */
1343
1344   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1345   if (template_depth
1346       && DECL_CLASS_SCOPE_P (decl)
1347       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1348                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1349     {
1350       /* Next, we check the members themselves.  In order to handle
1351          a few tricky cases, such as when FRIEND_DECL's are
1352
1353            template <class T> friend void A<T>::g(T t);
1354            template <class T> template <T t> friend void A<T>::h();
1355
1356          and DECL's are
1357
1358            void A<int>::g(int);
1359            template <int> void A<int>::h();
1360
1361          we need to figure out ARGS, the template arguments from
1362          the context of DECL.  This is required for template substitution
1363          of `T' in the function parameter of `g' and template parameter
1364          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1365
1366       tree context = DECL_CONTEXT (decl);
1367       tree args = NULL_TREE;
1368       int current_depth = 0;
1369
1370       while (current_depth < template_depth)
1371         {
1372           if (CLASSTYPE_TEMPLATE_INFO (context))
1373             {
1374               if (current_depth == 0)
1375                 args = TYPE_TI_ARGS (context);
1376               else
1377                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1378               current_depth++;
1379             }
1380           context = TYPE_CONTEXT (context);
1381         }
1382
1383       if (TREE_CODE (decl) == FUNCTION_DECL)
1384         {
1385           bool is_template;
1386           tree friend_type;
1387           tree decl_type;
1388           tree friend_args_type;
1389           tree decl_args_type;
1390
1391           /* Make sure that both DECL and FRIEND_DECL are templates or
1392              non-templates.  */
1393           is_template = DECL_TEMPLATE_INFO (decl)
1394                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1395           if (need_template ^ is_template)
1396             return false;
1397           else if (is_template)
1398             {
1399               /* If both are templates, check template parameter list.  */
1400               tree friend_parms
1401                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1402                                          args, tf_none);
1403               if (!comp_template_parms
1404                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1405                       friend_parms))
1406                 return false;
1407
1408               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1409             }
1410           else
1411             decl_type = TREE_TYPE (decl);
1412
1413           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1414                                               tf_none, NULL_TREE);
1415           if (friend_type == error_mark_node)
1416             return false;
1417
1418           /* Check if return types match.  */
1419           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1420             return false;
1421
1422           /* Check if function parameter types match, ignoring the
1423              `this' parameter.  */
1424           friend_args_type = TYPE_ARG_TYPES (friend_type);
1425           decl_args_type = TYPE_ARG_TYPES (decl_type);
1426           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1427             friend_args_type = TREE_CHAIN (friend_args_type);
1428           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1429             decl_args_type = TREE_CHAIN (decl_args_type);
1430
1431           return compparms (decl_args_type, friend_args_type);
1432         }
1433       else
1434         {
1435           /* DECL is a TYPE_DECL */
1436           bool is_template;
1437           tree decl_type = TREE_TYPE (decl);
1438
1439           /* Make sure that both DECL and FRIEND_DECL are templates or
1440              non-templates.  */
1441           is_template
1442             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1443               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1444
1445           if (need_template ^ is_template)
1446             return false;
1447           else if (is_template)
1448             {
1449               tree friend_parms;
1450               /* If both are templates, check the name of the two
1451                  TEMPLATE_DECL's first because is_friend didn't.  */
1452               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1453                   != DECL_NAME (friend_decl))
1454                 return false;
1455
1456               /* Now check template parameter list.  */
1457               friend_parms
1458                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1459                                          args, tf_none);
1460               return comp_template_parms
1461                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1462                  friend_parms);
1463             }
1464           else
1465             return (DECL_NAME (decl)
1466                     == DECL_NAME (friend_decl));
1467         }
1468     }
1469   return false;
1470 }
1471
1472 /* Register the specialization SPEC as a specialization of TMPL with
1473    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1474    is actually just a friend declaration.  Returns SPEC, or an
1475    equivalent prior declaration, if available.
1476
1477    We also store instantiations of field packs in the hash table, even
1478    though they are not themselves templates, to make lookup easier.  */
1479
1480 static tree
1481 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1482                          hashval_t hash)
1483 {
1484   tree fn;
1485   spec_entry **slot = NULL;
1486   spec_entry elt;
1487
1488   gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1489               || (TREE_CODE (tmpl) == FIELD_DECL
1490                   && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1491
1492   if (TREE_CODE (spec) == FUNCTION_DECL
1493       && uses_template_parms (DECL_TI_ARGS (spec)))
1494     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1495        register it; we want the corresponding TEMPLATE_DECL instead.
1496        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1497        the more obvious `uses_template_parms (spec)' to avoid problems
1498        with default function arguments.  In particular, given
1499        something like this:
1500
1501           template <class T> void f(T t1, T t = T())
1502
1503        the default argument expression is not substituted for in an
1504        instantiation unless and until it is actually needed.  */
1505     return spec;
1506
1507   if (optimize_specialization_lookup_p (tmpl))
1508     /* We don't put these specializations in the hash table, but we might
1509        want to give an error about a mismatch.  */
1510     fn = retrieve_specialization (tmpl, args, 0);
1511   else
1512     {
1513       elt.tmpl = tmpl;
1514       elt.args = args;
1515       elt.spec = spec;
1516
1517       if (hash == 0)
1518         hash = spec_hasher::hash (&elt);
1519
1520       slot =
1521         decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1522       if (*slot)
1523         fn = ((spec_entry *) *slot)->spec;
1524       else
1525         fn = NULL_TREE;
1526     }
1527
1528   /* We can sometimes try to re-register a specialization that we've
1529      already got.  In particular, regenerate_decl_from_template calls
1530      duplicate_decls which will update the specialization list.  But,
1531      we'll still get called again here anyhow.  It's more convenient
1532      to simply allow this than to try to prevent it.  */
1533   if (fn == spec)
1534     return spec;
1535   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1536     {
1537       if (DECL_TEMPLATE_INSTANTIATION (fn))
1538         {
1539           if (DECL_ODR_USED (fn)
1540               || DECL_EXPLICIT_INSTANTIATION (fn))
1541             {
1542               error ("specialization of %qD after instantiation",
1543                      fn);
1544               return error_mark_node;
1545             }
1546           else
1547             {
1548               tree clone;
1549               /* This situation should occur only if the first
1550                  specialization is an implicit instantiation, the
1551                  second is an explicit specialization, and the
1552                  implicit instantiation has not yet been used.  That
1553                  situation can occur if we have implicitly
1554                  instantiated a member function and then specialized
1555                  it later.
1556
1557                  We can also wind up here if a friend declaration that
1558                  looked like an instantiation turns out to be a
1559                  specialization:
1560
1561                    template <class T> void foo(T);
1562                    class S { friend void foo<>(int) };
1563                    template <> void foo(int);
1564
1565                  We transform the existing DECL in place so that any
1566                  pointers to it become pointers to the updated
1567                  declaration.
1568
1569                  If there was a definition for the template, but not
1570                  for the specialization, we want this to look as if
1571                  there were no definition, and vice versa.  */
1572               DECL_INITIAL (fn) = NULL_TREE;
1573               duplicate_decls (spec, fn, is_friend);
1574               /* The call to duplicate_decls will have applied
1575                  [temp.expl.spec]:
1576
1577                    An explicit specialization of a function template
1578                    is inline only if it is explicitly declared to be,
1579                    and independently of whether its function template
1580                    is.
1581
1582                 to the primary function; now copy the inline bits to
1583                 the various clones.  */
1584               FOR_EACH_CLONE (clone, fn)
1585                 {
1586                   DECL_DECLARED_INLINE_P (clone)
1587                     = DECL_DECLARED_INLINE_P (fn);
1588                   DECL_SOURCE_LOCATION (clone)
1589                     = DECL_SOURCE_LOCATION (fn);
1590                   DECL_DELETED_FN (clone)
1591                     = DECL_DELETED_FN (fn);
1592                 }
1593               check_specialization_namespace (tmpl);
1594
1595               return fn;
1596             }
1597         }
1598       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1599         {
1600           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1601             /* Dup decl failed, but this is a new definition. Set the
1602                line number so any errors match this new
1603                definition.  */
1604             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1605
1606           return fn;
1607         }
1608     }
1609   else if (fn)
1610     return duplicate_decls (spec, fn, is_friend);
1611
1612   /* A specialization must be declared in the same namespace as the
1613      template it is specializing.  */
1614   if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1615       && !check_specialization_namespace (tmpl))
1616     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1617
1618   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1619     {
1620       spec_entry *entry = ggc_alloc<spec_entry> ();
1621       gcc_assert (tmpl && args && spec);
1622       *entry = elt;
1623       *slot = entry;
1624       if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1625            && PRIMARY_TEMPLATE_P (tmpl)
1626            && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1627           || variable_template_p (tmpl))
1628         /* If TMPL is a forward declaration of a template function, keep a list
1629            of all specializations in case we need to reassign them to a friend
1630            template later in tsubst_friend_function.
1631
1632            Also keep a list of all variable template instantiations so that
1633            process_partial_specialization can check whether a later partial
1634            specialization would have used it.  */
1635         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1636           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1637     }
1638
1639   return spec;
1640 }
1641
1642 /* Returns true iff two spec_entry nodes are equivalent.  */
1643
1644 int comparing_specializations;
1645
1646 bool
1647 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1648 {
1649   int equal;
1650
1651   ++comparing_specializations;
1652   equal = (e1->tmpl == e2->tmpl
1653            && comp_template_args (e1->args, e2->args));
1654   if (equal && flag_concepts
1655       /* tmpl could be a FIELD_DECL for a capture pack.  */
1656       && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1657       && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1658       && uses_template_parms (e1->args))
1659     {
1660       /* Partial specializations of a variable template can be distinguished by
1661          constraints.  */
1662       tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1663       tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1664       equal = equivalent_constraints (c1, c2);
1665     }
1666   --comparing_specializations;
1667
1668   return equal;
1669 }
1670
1671 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1672
1673 static hashval_t
1674 hash_tmpl_and_args (tree tmpl, tree args)
1675 {
1676   hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1677   return iterative_hash_template_arg (args, val);
1678 }
1679
1680 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1681    ignoring SPEC.  */
1682
1683 hashval_t
1684 spec_hasher::hash (spec_entry *e)
1685 {
1686   return hash_tmpl_and_args (e->tmpl, e->args);
1687 }
1688
1689 /* Recursively calculate a hash value for a template argument ARG, for use
1690    in the hash tables of template specializations.  */
1691
1692 hashval_t
1693 iterative_hash_template_arg (tree arg, hashval_t val)
1694 {
1695   unsigned HOST_WIDE_INT i;
1696   enum tree_code code;
1697   char tclass;
1698
1699   if (arg == NULL_TREE)
1700     return iterative_hash_object (arg, val);
1701
1702   if (!TYPE_P (arg))
1703     STRIP_NOPS (arg);
1704
1705   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1706     /* We can get one of these when re-hashing a previous entry in the middle
1707        of substituting into a pack expansion.  Just look through it.  */
1708     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1709
1710   code = TREE_CODE (arg);
1711   tclass = TREE_CODE_CLASS (code);
1712
1713   val = iterative_hash_object (code, val);
1714
1715   switch (code)
1716     {
1717     case ERROR_MARK:
1718       return val;
1719
1720     case IDENTIFIER_NODE:
1721       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1722
1723     case TREE_VEC:
1724       {
1725         int i, len = TREE_VEC_LENGTH (arg);
1726         for (i = 0; i < len; ++i)
1727           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1728         return val;
1729       }
1730
1731     case TYPE_PACK_EXPANSION:
1732     case EXPR_PACK_EXPANSION:
1733       val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1734       return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1735
1736     case TYPE_ARGUMENT_PACK:
1737     case NONTYPE_ARGUMENT_PACK:
1738       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1739
1740     case TREE_LIST:
1741       for (; arg; arg = TREE_CHAIN (arg))
1742         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1743       return val;
1744
1745     case OVERLOAD:
1746       for (; arg; arg = OVL_NEXT (arg))
1747         val = iterative_hash_template_arg (OVL_CURRENT (arg), val);
1748       return val;
1749
1750     case CONSTRUCTOR:
1751       {
1752         tree field, value;
1753         iterative_hash_template_arg (TREE_TYPE (arg), val);
1754         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1755           {
1756             val = iterative_hash_template_arg (field, val);
1757             val = iterative_hash_template_arg (value, val);
1758           }
1759         return val;
1760       }
1761
1762     case PARM_DECL:
1763       if (!DECL_ARTIFICIAL (arg))
1764         {
1765           val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1766           val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1767         }
1768       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1769
1770     case TARGET_EXPR:
1771       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1772
1773     case PTRMEM_CST:
1774       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1775       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1776
1777     case TEMPLATE_PARM_INDEX:
1778       val = iterative_hash_template_arg
1779         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1780       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1781       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1782
1783     case TRAIT_EXPR:
1784       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1785       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1786       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1787
1788     case BASELINK:
1789       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1790                                          val);
1791       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1792                                           val);
1793
1794     case MODOP_EXPR:
1795       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1796       code = TREE_CODE (TREE_OPERAND (arg, 1));
1797       val = iterative_hash_object (code, val);
1798       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1799
1800     case LAMBDA_EXPR:
1801       /* A lambda can't appear in a template arg, but don't crash on
1802          erroneous input.  */
1803       gcc_assert (seen_error ());
1804       return val;
1805
1806     case CAST_EXPR:
1807     case IMPLICIT_CONV_EXPR:
1808     case STATIC_CAST_EXPR:
1809     case REINTERPRET_CAST_EXPR:
1810     case CONST_CAST_EXPR:
1811     case DYNAMIC_CAST_EXPR:
1812     case NEW_EXPR:
1813       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1814       /* Now hash operands as usual.  */
1815       break;
1816
1817     default:
1818       break;
1819     }
1820
1821   switch (tclass)
1822     {
1823     case tcc_type:
1824       if (alias_template_specialization_p (arg))
1825         {
1826           // We want an alias specialization that survived strip_typedefs
1827           // to hash differently from its TYPE_CANONICAL, to avoid hash
1828           // collisions that compare as different in template_args_equal.
1829           // These could be dependent specializations that strip_typedefs
1830           // left alone, or untouched specializations because
1831           // coerce_template_parms returns the unconverted template
1832           // arguments if it sees incomplete argument packs.
1833           tree ti = TYPE_TEMPLATE_INFO (arg);
1834           return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1835         }
1836       if (TYPE_CANONICAL (arg))
1837         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1838                                       val);
1839       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1840         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1841       /* Otherwise just compare the types during lookup.  */
1842       return val;
1843
1844     case tcc_declaration:
1845     case tcc_constant:
1846       return iterative_hash_expr (arg, val);
1847
1848     default:
1849       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1850       {
1851         unsigned n = cp_tree_operand_length (arg);
1852         for (i = 0; i < n; ++i)
1853           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1854         return val;
1855       }
1856     }
1857   gcc_unreachable ();
1858   return 0;
1859 }
1860
1861 /* Unregister the specialization SPEC as a specialization of TMPL.
1862    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1863    if the SPEC was listed as a specialization of TMPL.
1864
1865    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1866
1867 bool
1868 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1869 {
1870   spec_entry *entry;
1871   spec_entry elt;
1872
1873   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1874   elt.args = TI_ARGS (tinfo);
1875   elt.spec = NULL_TREE;
1876
1877   entry = decl_specializations->find (&elt);
1878   if (entry != NULL)
1879     {
1880       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1881       gcc_assert (new_spec != NULL_TREE);
1882       entry->spec = new_spec;
1883       return 1;
1884     }
1885
1886   return 0;
1887 }
1888
1889 /* Like register_specialization, but for local declarations.  We are
1890    registering SPEC, an instantiation of TMPL.  */
1891
1892 void
1893 register_local_specialization (tree spec, tree tmpl)
1894 {
1895   local_specializations->put (tmpl, spec);
1896 }
1897
1898 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1899    specialized class.  */
1900
1901 bool
1902 explicit_class_specialization_p (tree type)
1903 {
1904   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1905     return false;
1906   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1907 }
1908
1909 /* Print the list of functions at FNS, going through all the overloads
1910    for each element of the list.  Alternatively, FNS can not be a
1911    TREE_LIST, in which case it will be printed together with all the
1912    overloads.
1913
1914    MORE and *STR should respectively be FALSE and NULL when the function
1915    is called from the outside.  They are used internally on recursive
1916    calls.  print_candidates manages the two parameters and leaves NULL
1917    in *STR when it ends.  */
1918
1919 static void
1920 print_candidates_1 (tree fns, bool more, const char **str)
1921 {
1922   tree fn, fn2;
1923   char *spaces = NULL;
1924
1925   for (fn = fns; fn; fn = OVL_NEXT (fn))
1926     if (TREE_CODE (fn) == TREE_LIST)
1927       {
1928         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1929           print_candidates_1 (TREE_VALUE (fn2),
1930                               TREE_CHAIN (fn2) || more, str);
1931       }
1932     else
1933       {
1934         tree cand = OVL_CURRENT (fn);
1935         if (!*str)
1936           {
1937             /* Pick the prefix string.  */
1938             if (!more && !OVL_NEXT (fns))
1939               {
1940                 inform (DECL_SOURCE_LOCATION (cand),
1941                         "candidate is: %#D", cand);
1942                 continue;
1943               }
1944
1945             *str = _("candidates are:");
1946             spaces = get_spaces (*str);
1947           }
1948         inform (DECL_SOURCE_LOCATION (cand), "%s %#D", *str, cand);
1949         *str = spaces ? spaces : *str;
1950       }
1951
1952   if (!more)
1953     {
1954       free (spaces);
1955       *str = NULL;
1956     }
1957 }
1958
1959 /* Print the list of candidate FNS in an error message.  FNS can also
1960    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1961
1962 void
1963 print_candidates (tree fns)
1964 {
1965   const char *str = NULL;
1966   print_candidates_1 (fns, false, &str);
1967   gcc_assert (str == NULL);
1968 }
1969
1970 /* Get a (possibly) constrained template declaration for the
1971    purpose of ordering candidates.  */
1972 static tree
1973 get_template_for_ordering (tree list)
1974 {
1975   gcc_assert (TREE_CODE (list) == TREE_LIST);
1976   tree f = TREE_VALUE (list);
1977   if (tree ti = DECL_TEMPLATE_INFO (f))
1978     return TI_TEMPLATE (ti);
1979   return f;
1980 }
1981
1982 /* Among candidates having the same signature, return the
1983    most constrained or NULL_TREE if there is no best candidate.
1984    If the signatures of candidates vary (e.g., template
1985    specialization vs. member function), then there can be no
1986    most constrained.
1987
1988    Note that we don't compare constraints on the functions
1989    themselves, but rather those of their templates. */
1990 static tree
1991 most_constrained_function (tree candidates)
1992 {
1993   // Try to find the best candidate in a first pass.
1994   tree champ = candidates;
1995   for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
1996     {
1997       int winner = more_constrained (get_template_for_ordering (champ),
1998                                      get_template_for_ordering (c));
1999       if (winner == -1)
2000         champ = c; // The candidate is more constrained
2001       else if (winner == 0)
2002         return NULL_TREE; // Neither is more constrained
2003     }
2004
2005   // Verify that the champ is better than previous candidates.
2006   for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2007     if (!more_constrained (get_template_for_ordering (champ),
2008                            get_template_for_ordering (c)))
2009       return NULL_TREE;
2010   }
2011
2012   return champ;
2013 }
2014
2015
2016 /* Returns the template (one of the functions given by TEMPLATE_ID)
2017    which can be specialized to match the indicated DECL with the
2018    explicit template args given in TEMPLATE_ID.  The DECL may be
2019    NULL_TREE if none is available.  In that case, the functions in
2020    TEMPLATE_ID are non-members.
2021
2022    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2023    specialization of a member template.
2024
2025    The TEMPLATE_COUNT is the number of references to qualifying
2026    template classes that appeared in the name of the function. See
2027    check_explicit_specialization for a more accurate description.
2028
2029    TSK indicates what kind of template declaration (if any) is being
2030    declared.  TSK_TEMPLATE indicates that the declaration given by
2031    DECL, though a FUNCTION_DECL, has template parameters, and is
2032    therefore a template function.
2033
2034    The template args (those explicitly specified and those deduced)
2035    are output in a newly created vector *TARGS_OUT.
2036
2037    If it is impossible to determine the result, an error message is
2038    issued.  The error_mark_node is returned to indicate failure.  */
2039
2040 static tree
2041 determine_specialization (tree template_id,
2042                           tree decl,
2043                           tree* targs_out,
2044                           int need_member_template,
2045                           int template_count,
2046                           tmpl_spec_kind tsk)
2047 {
2048   tree fns;
2049   tree targs;
2050   tree explicit_targs;
2051   tree candidates = NULL_TREE;
2052
2053   /* A TREE_LIST of templates of which DECL may be a specialization.
2054      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
2055      corresponding TREE_PURPOSE is the set of template arguments that,
2056      when used to instantiate the template, would produce a function
2057      with the signature of DECL.  */
2058   tree templates = NULL_TREE;
2059   int header_count;
2060   cp_binding_level *b;
2061
2062   *targs_out = NULL_TREE;
2063
2064   if (template_id == error_mark_node || decl == error_mark_node)
2065     return error_mark_node;
2066
2067   /* We shouldn't be specializing a member template of an
2068      unspecialized class template; we already gave an error in
2069      check_specialization_scope, now avoid crashing.  */
2070   if (template_count && DECL_CLASS_SCOPE_P (decl)
2071       && template_class_depth (DECL_CONTEXT (decl)) > 0)
2072     {
2073       gcc_assert (errorcount);
2074       return error_mark_node;
2075     }
2076
2077   fns = TREE_OPERAND (template_id, 0);
2078   explicit_targs = TREE_OPERAND (template_id, 1);
2079
2080   if (fns == error_mark_node)
2081     return error_mark_node;
2082
2083   /* Check for baselinks.  */
2084   if (BASELINK_P (fns))
2085     fns = BASELINK_FUNCTIONS (fns);
2086
2087   if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2088     {
2089       error ("%qD is not a function template", fns);
2090       return error_mark_node;
2091     }
2092   else if (VAR_P (decl) && !variable_template_p (fns))
2093     {
2094       error ("%qD is not a variable template", fns);
2095       return error_mark_node;
2096     }
2097
2098   /* Count the number of template headers specified for this
2099      specialization.  */
2100   header_count = 0;
2101   for (b = current_binding_level;
2102        b->kind == sk_template_parms;
2103        b = b->level_chain)
2104     ++header_count;
2105
2106   tree orig_fns = fns;
2107
2108   if (variable_template_p (fns))
2109     {
2110       tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2111       targs = coerce_template_parms (parms, explicit_targs, fns,
2112                                      tf_warning_or_error,
2113                                      /*req_all*/true, /*use_defarg*/true);
2114       if (targs != error_mark_node)
2115         templates = tree_cons (targs, fns, templates);
2116     }
2117   else for (; fns; fns = OVL_NEXT (fns))
2118     {
2119       tree fn = OVL_CURRENT (fns);
2120
2121       if (TREE_CODE (fn) == TEMPLATE_DECL)
2122         {
2123           tree decl_arg_types;
2124           tree fn_arg_types;
2125           tree insttype;
2126
2127           /* In case of explicit specialization, we need to check if
2128              the number of template headers appearing in the specialization
2129              is correct. This is usually done in check_explicit_specialization,
2130              but the check done there cannot be exhaustive when specializing
2131              member functions. Consider the following code:
2132
2133              template <> void A<int>::f(int);
2134              template <> template <> void A<int>::f(int);
2135
2136              Assuming that A<int> is not itself an explicit specialization
2137              already, the first line specializes "f" which is a non-template
2138              member function, whilst the second line specializes "f" which
2139              is a template member function. So both lines are syntactically
2140              correct, and check_explicit_specialization does not reject
2141              them.
2142
2143              Here, we can do better, as we are matching the specialization
2144              against the declarations. We count the number of template
2145              headers, and we check if they match TEMPLATE_COUNT + 1
2146              (TEMPLATE_COUNT is the number of qualifying template classes,
2147              plus there must be another header for the member template
2148              itself).
2149
2150              Notice that if header_count is zero, this is not a
2151              specialization but rather a template instantiation, so there
2152              is no check we can perform here.  */
2153           if (header_count && header_count != template_count + 1)
2154             continue;
2155
2156           /* Check that the number of template arguments at the
2157              innermost level for DECL is the same as for FN.  */
2158           if (current_binding_level->kind == sk_template_parms
2159               && !current_binding_level->explicit_spec_p
2160               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2161                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2162                                       (current_template_parms))))
2163             continue;
2164
2165           /* DECL might be a specialization of FN.  */
2166           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2167           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2168
2169           /* For a non-static member function, we need to make sure
2170              that the const qualification is the same.  Since
2171              get_bindings does not try to merge the "this" parameter,
2172              we must do the comparison explicitly.  */
2173           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2174               && !same_type_p (TREE_VALUE (fn_arg_types),
2175                                TREE_VALUE (decl_arg_types)))
2176             continue;
2177
2178           /* Skip the "this" parameter and, for constructors of
2179              classes with virtual bases, the VTT parameter.  A
2180              full specialization of a constructor will have a VTT
2181              parameter, but a template never will.  */ 
2182           decl_arg_types 
2183             = skip_artificial_parms_for (decl, decl_arg_types);
2184           fn_arg_types 
2185             = skip_artificial_parms_for (fn, fn_arg_types);
2186
2187           /* Function templates cannot be specializations; there are
2188              no partial specializations of functions.  Therefore, if
2189              the type of DECL does not match FN, there is no
2190              match.
2191
2192              Note that it should never be the case that we have both
2193              candidates added here, and for regular member functions
2194              below. */
2195           if (tsk == tsk_template)
2196             {
2197               if (compparms (fn_arg_types, decl_arg_types))
2198                 candidates = tree_cons (NULL_TREE, fn, candidates);
2199               continue;
2200             }
2201
2202           /* See whether this function might be a specialization of this
2203              template.  Suppress access control because we might be trying
2204              to make this specialization a friend, and we have already done
2205              access control for the declaration of the specialization.  */
2206           push_deferring_access_checks (dk_no_check);
2207           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2208           pop_deferring_access_checks ();
2209
2210           if (!targs)
2211             /* We cannot deduce template arguments that when used to
2212                specialize TMPL will produce DECL.  */
2213             continue;
2214
2215           /* Remove, from the set of candidates, all those functions
2216              whose constraints are not satisfied. */
2217           if (flag_concepts && !constraints_satisfied_p (fn, targs))
2218             continue;
2219
2220           // Then, try to form the new function type.
2221           insttype = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
2222           if (insttype == error_mark_node)
2223             continue;
2224           fn_arg_types
2225             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
2226           if (!compparms (fn_arg_types, decl_arg_types))
2227             continue;
2228
2229           /* Save this template, and the arguments deduced.  */
2230           templates = tree_cons (targs, fn, templates);
2231         }
2232       else if (need_member_template)
2233         /* FN is an ordinary member function, and we need a
2234            specialization of a member template.  */
2235         ;
2236       else if (TREE_CODE (fn) != FUNCTION_DECL)
2237         /* We can get IDENTIFIER_NODEs here in certain erroneous
2238            cases.  */
2239         ;
2240       else if (!DECL_FUNCTION_MEMBER_P (fn))
2241         /* This is just an ordinary non-member function.  Nothing can
2242            be a specialization of that.  */
2243         ;
2244       else if (DECL_ARTIFICIAL (fn))
2245         /* Cannot specialize functions that are created implicitly.  */
2246         ;
2247       else
2248         {
2249           tree decl_arg_types;
2250
2251           /* This is an ordinary member function.  However, since
2252              we're here, we can assume its enclosing class is a
2253              template class.  For example,
2254
2255                template <typename T> struct S { void f(); };
2256                template <> void S<int>::f() {}
2257
2258              Here, S<int>::f is a non-template, but S<int> is a
2259              template class.  If FN has the same type as DECL, we
2260              might be in business.  */
2261
2262           if (!DECL_TEMPLATE_INFO (fn))
2263             /* Its enclosing class is an explicit specialization
2264                of a template class.  This is not a candidate.  */
2265             continue;
2266
2267           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2268                             TREE_TYPE (TREE_TYPE (fn))))
2269             /* The return types differ.  */
2270             continue;
2271
2272           /* Adjust the type of DECL in case FN is a static member.  */
2273           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2274           if (DECL_STATIC_FUNCTION_P (fn)
2275               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2276             decl_arg_types = TREE_CHAIN (decl_arg_types);
2277
2278           if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2279                          decl_arg_types))
2280             continue;
2281
2282           // If the deduced arguments do not satisfy the constraints,
2283           // this is not a candidate.
2284           if (flag_concepts && !constraints_satisfied_p (fn))
2285             continue;
2286
2287           // Add the candidate.
2288           candidates = tree_cons (NULL_TREE, fn, candidates);
2289         }
2290     }
2291
2292   if (templates && TREE_CHAIN (templates))
2293     {
2294       /* We have:
2295
2296            [temp.expl.spec]
2297
2298            It is possible for a specialization with a given function
2299            signature to be instantiated from more than one function
2300            template.  In such cases, explicit specification of the
2301            template arguments must be used to uniquely identify the
2302            function template specialization being specialized.
2303
2304          Note that here, there's no suggestion that we're supposed to
2305          determine which of the candidate templates is most
2306          specialized.  However, we, also have:
2307
2308            [temp.func.order]
2309
2310            Partial ordering of overloaded function template
2311            declarations is used in the following contexts to select
2312            the function template to which a function template
2313            specialization refers:
2314
2315            -- when an explicit specialization refers to a function
2316               template.
2317
2318          So, we do use the partial ordering rules, at least for now.
2319          This extension can only serve to make invalid programs valid,
2320          so it's safe.  And, there is strong anecdotal evidence that
2321          the committee intended the partial ordering rules to apply;
2322          the EDG front end has that behavior, and John Spicer claims
2323          that the committee simply forgot to delete the wording in
2324          [temp.expl.spec].  */
2325       tree tmpl = most_specialized_instantiation (templates);
2326       if (tmpl != error_mark_node)
2327         {
2328           templates = tmpl;
2329           TREE_CHAIN (templates) = NULL_TREE;
2330         }
2331     }
2332
2333   // Concepts allows multiple declarations of member functions
2334   // with the same signature. Like above, we need to rely on
2335   // on the partial ordering of those candidates to determine which
2336   // is the best.
2337   if (flag_concepts && candidates && TREE_CHAIN (candidates))
2338     {
2339       if (tree cand = most_constrained_function (candidates))
2340         {
2341           candidates = cand;
2342           TREE_CHAIN (cand) = NULL_TREE;
2343         }
2344     }
2345
2346   if (templates == NULL_TREE && candidates == NULL_TREE)
2347     {
2348       error ("template-id %qD for %q+D does not match any template "
2349              "declaration", template_id, decl);
2350       if (header_count && header_count != template_count + 1)
2351         inform (input_location, "saw %d %<template<>%>, need %d for "
2352                 "specializing a member function template",
2353                 header_count, template_count + 1);
2354       else
2355         print_candidates (orig_fns);
2356       return error_mark_node;
2357     }
2358   else if ((templates && TREE_CHAIN (templates))
2359            || (candidates && TREE_CHAIN (candidates))
2360            || (templates && candidates))
2361     {
2362       error ("ambiguous template specialization %qD for %q+D",
2363              template_id, decl);
2364       candidates = chainon (candidates, templates);
2365       print_candidates (candidates);
2366       return error_mark_node;
2367     }
2368
2369   /* We have one, and exactly one, match.  */
2370   if (candidates)
2371     {
2372       tree fn = TREE_VALUE (candidates);
2373       *targs_out = copy_node (DECL_TI_ARGS (fn));
2374
2375       // Propagate the candidate's constraints to the declaration.
2376       set_constraints (decl, get_constraints (fn));
2377
2378       /* DECL is a re-declaration or partial instantiation of a template
2379          function.  */
2380       if (TREE_CODE (fn) == TEMPLATE_DECL)
2381         return fn;
2382       /* It was a specialization of an ordinary member function in a
2383          template class.  */
2384       return DECL_TI_TEMPLATE (fn);
2385     }
2386
2387   /* It was a specialization of a template.  */
2388   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2389   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2390     {
2391       *targs_out = copy_node (targs);
2392       SET_TMPL_ARGS_LEVEL (*targs_out,
2393                            TMPL_ARGS_DEPTH (*targs_out),
2394                            TREE_PURPOSE (templates));
2395     }
2396   else
2397     *targs_out = TREE_PURPOSE (templates);
2398   return TREE_VALUE (templates);
2399 }
2400
2401 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2402    but with the default argument values filled in from those in the
2403    TMPL_TYPES.  */
2404
2405 static tree
2406 copy_default_args_to_explicit_spec_1 (tree spec_types,
2407                                       tree tmpl_types)
2408 {
2409   tree new_spec_types;
2410
2411   if (!spec_types)
2412     return NULL_TREE;
2413
2414   if (spec_types == void_list_node)
2415     return void_list_node;
2416
2417   /* Substitute into the rest of the list.  */
2418   new_spec_types =
2419     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2420                                           TREE_CHAIN (tmpl_types));
2421
2422   /* Add the default argument for this parameter.  */
2423   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2424                          TREE_VALUE (spec_types),
2425                          new_spec_types);
2426 }
2427
2428 /* DECL is an explicit specialization.  Replicate default arguments
2429    from the template it specializes.  (That way, code like:
2430
2431      template <class T> void f(T = 3);
2432      template <> void f(double);
2433      void g () { f (); }
2434
2435    works, as required.)  An alternative approach would be to look up
2436    the correct default arguments at the call-site, but this approach
2437    is consistent with how implicit instantiations are handled.  */
2438
2439 static void
2440 copy_default_args_to_explicit_spec (tree decl)
2441 {
2442   tree tmpl;
2443   tree spec_types;
2444   tree tmpl_types;
2445   tree new_spec_types;
2446   tree old_type;
2447   tree new_type;
2448   tree t;
2449   tree object_type = NULL_TREE;
2450   tree in_charge = NULL_TREE;
2451   tree vtt = NULL_TREE;
2452
2453   /* See if there's anything we need to do.  */
2454   tmpl = DECL_TI_TEMPLATE (decl);
2455   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2456   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2457     if (TREE_PURPOSE (t))
2458       break;
2459   if (!t)
2460     return;
2461
2462   old_type = TREE_TYPE (decl);
2463   spec_types = TYPE_ARG_TYPES (old_type);
2464
2465   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2466     {
2467       /* Remove the this pointer, but remember the object's type for
2468          CV quals.  */
2469       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2470       spec_types = TREE_CHAIN (spec_types);
2471       tmpl_types = TREE_CHAIN (tmpl_types);
2472
2473       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2474         {
2475           /* DECL may contain more parameters than TMPL due to the extra
2476              in-charge parameter in constructors and destructors.  */
2477           in_charge = spec_types;
2478           spec_types = TREE_CHAIN (spec_types);
2479         }
2480       if (DECL_HAS_VTT_PARM_P (decl))
2481         {
2482           vtt = spec_types;
2483           spec_types = TREE_CHAIN (spec_types);
2484         }
2485     }
2486
2487   /* Compute the merged default arguments.  */
2488   new_spec_types =
2489     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2490
2491   /* Compute the new FUNCTION_TYPE.  */
2492   if (object_type)
2493     {
2494       if (vtt)
2495         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2496                                          TREE_VALUE (vtt),
2497                                          new_spec_types);
2498
2499       if (in_charge)
2500         /* Put the in-charge parameter back.  */
2501         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2502                                          TREE_VALUE (in_charge),
2503                                          new_spec_types);
2504
2505       new_type = build_method_type_directly (object_type,
2506                                              TREE_TYPE (old_type),
2507                                              new_spec_types);
2508     }
2509   else
2510     new_type = build_function_type (TREE_TYPE (old_type),
2511                                     new_spec_types);
2512   new_type = cp_build_type_attribute_variant (new_type,
2513                                               TYPE_ATTRIBUTES (old_type));
2514   new_type = build_exception_variant (new_type,
2515                                       TYPE_RAISES_EXCEPTIONS (old_type));
2516
2517   if (TYPE_HAS_LATE_RETURN_TYPE (old_type))
2518     TYPE_HAS_LATE_RETURN_TYPE (new_type) = 1;
2519
2520   TREE_TYPE (decl) = new_type;
2521 }
2522
2523 /* Return the number of template headers we expect to see for a definition
2524    or specialization of CTYPE or one of its non-template members.  */
2525
2526 int
2527 num_template_headers_for_class (tree ctype)
2528 {
2529   int num_templates = 0;
2530
2531   while (ctype && CLASS_TYPE_P (ctype))
2532     {
2533       /* You're supposed to have one `template <...>' for every
2534          template class, but you don't need one for a full
2535          specialization.  For example:
2536
2537          template <class T> struct S{};
2538          template <> struct S<int> { void f(); };
2539          void S<int>::f () {}
2540
2541          is correct; there shouldn't be a `template <>' for the
2542          definition of `S<int>::f'.  */
2543       if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2544         /* If CTYPE does not have template information of any
2545            kind,  then it is not a template, nor is it nested
2546            within a template.  */
2547         break;
2548       if (explicit_class_specialization_p (ctype))
2549         break;
2550       if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2551         ++num_templates;
2552
2553       ctype = TYPE_CONTEXT (ctype);
2554     }
2555
2556   return num_templates;
2557 }
2558
2559 /* Do a simple sanity check on the template headers that precede the
2560    variable declaration DECL.  */
2561
2562 void
2563 check_template_variable (tree decl)
2564 {
2565   tree ctx = CP_DECL_CONTEXT (decl);
2566   int wanted = num_template_headers_for_class (ctx);
2567   if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2568       && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2569     {
2570       if (cxx_dialect < cxx14)
2571         pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2572                  "variable templates only available with "
2573                  "-std=c++14 or -std=gnu++14");
2574
2575       // Namespace-scope variable templates should have a template header.
2576       ++wanted;
2577     }
2578   if (template_header_count > wanted)
2579     {
2580       bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2581                              "too many template headers for %D (should be %d)",
2582                              decl, wanted);
2583       if (warned && CLASS_TYPE_P (ctx)
2584           && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2585         inform (DECL_SOURCE_LOCATION (decl),
2586                 "members of an explicitly specialized class are defined "
2587                 "without a template header");
2588     }
2589 }
2590
2591 /* Check to see if the function just declared, as indicated in
2592    DECLARATOR, and in DECL, is a specialization of a function
2593    template.  We may also discover that the declaration is an explicit
2594    instantiation at this point.
2595
2596    Returns DECL, or an equivalent declaration that should be used
2597    instead if all goes well.  Issues an error message if something is
2598    amiss.  Returns error_mark_node if the error is not easily
2599    recoverable.
2600
2601    FLAGS is a bitmask consisting of the following flags:
2602
2603    2: The function has a definition.
2604    4: The function is a friend.
2605
2606    The TEMPLATE_COUNT is the number of references to qualifying
2607    template classes that appeared in the name of the function.  For
2608    example, in
2609
2610      template <class T> struct S { void f(); };
2611      void S<int>::f();
2612
2613    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2614    classes are not counted in the TEMPLATE_COUNT, so that in
2615
2616      template <class T> struct S {};
2617      template <> struct S<int> { void f(); }
2618      template <> void S<int>::f();
2619
2620    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2621    invalid; there should be no template <>.)
2622
2623    If the function is a specialization, it is marked as such via
2624    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2625    is set up correctly, and it is added to the list of specializations
2626    for that template.  */
2627
2628 tree
2629 check_explicit_specialization (tree declarator,
2630                                tree decl,
2631                                int template_count,
2632                                int flags)
2633 {
2634   int have_def = flags & 2;
2635   int is_friend = flags & 4;
2636   bool is_concept = flags & 8;
2637   int specialization = 0;
2638   int explicit_instantiation = 0;
2639   int member_specialization = 0;
2640   tree ctype = DECL_CLASS_CONTEXT (decl);
2641   tree dname = DECL_NAME (decl);
2642   tmpl_spec_kind tsk;
2643
2644   if (is_friend)
2645     {
2646       if (!processing_specialization)
2647         tsk = tsk_none;
2648       else
2649         tsk = tsk_excessive_parms;
2650     }
2651   else
2652     tsk = current_tmpl_spec_kind (template_count);
2653
2654   switch (tsk)
2655     {
2656     case tsk_none:
2657       if (processing_specialization && !VAR_P (decl))
2658         {
2659           specialization = 1;
2660           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2661         }
2662       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2663         {
2664           if (is_friend)
2665             /* This could be something like:
2666
2667                template <class T> void f(T);
2668                class S { friend void f<>(int); }  */
2669             specialization = 1;
2670           else
2671             {
2672               /* This case handles bogus declarations like template <>
2673                  template <class T> void f<int>(); */
2674
2675               error ("template-id %qD in declaration of primary template",
2676                      declarator);
2677               return decl;
2678             }
2679         }
2680       break;
2681
2682     case tsk_invalid_member_spec:
2683       /* The error has already been reported in
2684          check_specialization_scope.  */
2685       return error_mark_node;
2686
2687     case tsk_invalid_expl_inst:
2688       error ("template parameter list used in explicit instantiation");
2689
2690       /* Fall through.  */
2691
2692     case tsk_expl_inst:
2693       if (have_def)
2694         error ("definition provided for explicit instantiation");
2695
2696       explicit_instantiation = 1;
2697       break;
2698
2699     case tsk_excessive_parms:
2700     case tsk_insufficient_parms:
2701       if (tsk == tsk_excessive_parms)
2702         error ("too many template parameter lists in declaration of %qD",
2703                decl);
2704       else if (template_header_count)
2705         error("too few template parameter lists in declaration of %qD", decl);
2706       else
2707         error("explicit specialization of %qD must be introduced by "
2708               "%<template <>%>", decl);
2709
2710       /* Fall through.  */
2711     case tsk_expl_spec:
2712       if (is_concept)
2713         error ("explicit specialization declared %<concept%>");
2714
2715       if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2716         /* In cases like template<> constexpr bool v = true;
2717            We'll give an error in check_template_variable.  */
2718         break;
2719
2720       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2721       if (ctype)
2722         member_specialization = 1;
2723       else
2724         specialization = 1;
2725       break;
2726
2727     case tsk_template:
2728       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2729         {
2730           /* This case handles bogus declarations like template <>
2731              template <class T> void f<int>(); */
2732
2733           if (!uses_template_parms (declarator))
2734             error ("template-id %qD in declaration of primary template",
2735                    declarator);
2736           else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2737             {
2738               /* Partial specialization of variable template.  */
2739               SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2740               specialization = 1;
2741               goto ok;
2742             }
2743           else if (cxx_dialect < cxx14)
2744             error ("non-type partial specialization %qD "
2745                    "is not allowed", declarator);
2746           else
2747             error ("non-class, non-variable partial specialization %qD "
2748                    "is not allowed", declarator);
2749           return decl;
2750         ok:;
2751         }
2752
2753       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2754         /* This is a specialization of a member template, without
2755            specialization the containing class.  Something like:
2756
2757              template <class T> struct S {
2758                template <class U> void f (U);
2759              };
2760              template <> template <class U> void S<int>::f(U) {}
2761
2762            That's a specialization -- but of the entire template.  */
2763         specialization = 1;
2764       break;
2765
2766     default:
2767       gcc_unreachable ();
2768     }
2769
2770   if ((specialization || member_specialization)
2771       /* This doesn't apply to variable templates.  */
2772       && (TREE_CODE (TREE_TYPE (decl)) == FUNCTION_TYPE
2773           || TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE))
2774     {
2775       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2776       for (; t; t = TREE_CHAIN (t))
2777         if (TREE_PURPOSE (t))
2778           {
2779             permerror (input_location, 
2780                        "default argument specified in explicit specialization");
2781             break;
2782           }
2783     }
2784
2785   if (specialization || member_specialization || explicit_instantiation)
2786     {
2787       tree tmpl = NULL_TREE;
2788       tree targs = NULL_TREE;
2789       bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2790
2791       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2792       if (!was_template_id)
2793         {
2794           tree fns;
2795
2796           gcc_assert (identifier_p (declarator));
2797           if (ctype)
2798             fns = dname;
2799           else
2800             {
2801               /* If there is no class context, the explicit instantiation
2802                  must be at namespace scope.  */
2803               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2804
2805               /* Find the namespace binding, using the declaration
2806                  context.  */
2807               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2808                                            false, true);
2809               if (fns == error_mark_node)
2810                 /* If lookup fails, look for a friend declaration so we can
2811                    give a better diagnostic.  */
2812                 fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2813                                              /*type*/false, /*complain*/true,
2814                                              /*hidden*/true);
2815
2816               if (fns == error_mark_node || !is_overloaded_fn (fns))
2817                 {
2818                   error ("%qD is not a template function", dname);
2819                   fns = error_mark_node;
2820                 }
2821             }
2822
2823           declarator = lookup_template_function (fns, NULL_TREE);
2824         }
2825
2826       if (declarator == error_mark_node)
2827         return error_mark_node;
2828
2829       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2830         {
2831           if (!explicit_instantiation)
2832             /* A specialization in class scope.  This is invalid,
2833                but the error will already have been flagged by
2834                check_specialization_scope.  */
2835             return error_mark_node;
2836           else
2837             {
2838               /* It's not valid to write an explicit instantiation in
2839                  class scope, e.g.:
2840
2841                    class C { template void f(); }
2842
2843                    This case is caught by the parser.  However, on
2844                    something like:
2845
2846                    template class C { void f(); };
2847
2848                    (which is invalid) we can get here.  The error will be
2849                    issued later.  */
2850               ;
2851             }
2852
2853           return decl;
2854         }
2855       else if (ctype != NULL_TREE
2856                && (identifier_p (TREE_OPERAND (declarator, 0))))
2857         {
2858           // We'll match variable templates in start_decl.
2859           if (VAR_P (decl))
2860             return decl;
2861
2862           /* Find the list of functions in ctype that have the same
2863              name as the declared function.  */
2864           tree name = TREE_OPERAND (declarator, 0);
2865           tree fns = NULL_TREE;
2866           int idx;
2867
2868           if (constructor_name_p (name, ctype))
2869             {
2870               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2871
2872               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2873                   : !CLASSTYPE_DESTRUCTORS (ctype))
2874                 {
2875                   /* From [temp.expl.spec]:
2876
2877                      If such an explicit specialization for the member
2878                      of a class template names an implicitly-declared
2879                      special member function (clause _special_), the
2880                      program is ill-formed.
2881
2882                      Similar language is found in [temp.explicit].  */
2883                   error ("specialization of implicitly-declared special member function");
2884                   return error_mark_node;
2885                 }
2886
2887               name = is_constructor ? ctor_identifier : dtor_identifier;
2888             }
2889
2890           if (!DECL_CONV_FN_P (decl))
2891             {
2892               idx = lookup_fnfields_1 (ctype, name);
2893               if (idx >= 0)
2894                 fns = (*CLASSTYPE_METHOD_VEC (ctype))[idx];
2895             }
2896           else
2897             {
2898               vec<tree, va_gc> *methods;
2899               tree ovl;
2900
2901               /* For a type-conversion operator, we cannot do a
2902                  name-based lookup.  We might be looking for `operator
2903                  int' which will be a specialization of `operator T'.
2904                  So, we find *all* the conversion operators, and then
2905                  select from them.  */
2906               fns = NULL_TREE;
2907
2908               methods = CLASSTYPE_METHOD_VEC (ctype);
2909               if (methods)
2910                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2911                      methods->iterate (idx, &ovl);
2912                      ++idx)
2913                   {
2914                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2915                       /* There are no more conversion functions.  */
2916                       break;
2917
2918                     /* Glue all these conversion functions together
2919                        with those we already have.  */
2920                     for (; ovl; ovl = OVL_NEXT (ovl))
2921                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2922                   }
2923             }
2924
2925           if (fns == NULL_TREE)
2926             {
2927               error ("no member function %qD declared in %qT", name, ctype);
2928               return error_mark_node;
2929             }
2930           else
2931             TREE_OPERAND (declarator, 0) = fns;
2932         }
2933
2934       /* Figure out what exactly is being specialized at this point.
2935          Note that for an explicit instantiation, even one for a
2936          member function, we cannot tell apriori whether the
2937          instantiation is for a member template, or just a member
2938          function of a template class.  Even if a member template is
2939          being instantiated, the member template arguments may be
2940          elided if they can be deduced from the rest of the
2941          declaration.  */
2942       tmpl = determine_specialization (declarator, decl,
2943                                        &targs,
2944                                        member_specialization,
2945                                        template_count,
2946                                        tsk);
2947
2948       if (!tmpl || tmpl == error_mark_node)
2949         /* We couldn't figure out what this declaration was
2950            specializing.  */
2951         return error_mark_node;
2952       else
2953         {
2954           if (!ctype && !was_template_id
2955               && (specialization || member_specialization
2956                   || explicit_instantiation)
2957               && !is_associated_namespace (CP_DECL_CONTEXT (decl),
2958                                            CP_DECL_CONTEXT (tmpl)))
2959             error ("%qD is not declared in %qD",
2960                    tmpl, current_namespace);
2961           else if (TREE_CODE (decl) == FUNCTION_DECL
2962                    && DECL_HIDDEN_FRIEND_P (tmpl))
2963             {
2964               if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2965                            "friend declaration %qD is not visible to "
2966                            "explicit specialization", tmpl))
2967                 inform (DECL_SOURCE_LOCATION (tmpl),
2968                         "friend declaration here");
2969             }
2970
2971           tree gen_tmpl = most_general_template (tmpl);
2972
2973           if (explicit_instantiation)
2974             {
2975               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2976                  is done by do_decl_instantiation later.  */
2977
2978               int arg_depth = TMPL_ARGS_DEPTH (targs);
2979               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2980
2981               if (arg_depth > parm_depth)
2982                 {
2983                   /* If TMPL is not the most general template (for
2984                      example, if TMPL is a friend template that is
2985                      injected into namespace scope), then there will
2986                      be too many levels of TARGS.  Remove some of them
2987                      here.  */
2988                   int i;
2989                   tree new_targs;
2990
2991                   new_targs = make_tree_vec (parm_depth);
2992                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2993                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2994                       = TREE_VEC_ELT (targs, i);
2995                   targs = new_targs;
2996                 }
2997
2998               return instantiate_template (tmpl, targs, tf_error);
2999             }
3000
3001           /* If we thought that the DECL was a member function, but it
3002              turns out to be specializing a static member function,
3003              make DECL a static member function as well.  */
3004           if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3005               && DECL_STATIC_FUNCTION_P (tmpl)
3006               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3007             revert_static_member_fn (decl);
3008
3009           /* If this is a specialization of a member template of a
3010              template class, we want to return the TEMPLATE_DECL, not
3011              the specialization of it.  */
3012           if (tsk == tsk_template && !was_template_id)
3013             {
3014               tree result = DECL_TEMPLATE_RESULT (tmpl);
3015               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3016               DECL_INITIAL (result) = NULL_TREE;
3017               if (have_def)
3018                 {
3019                   tree parm;
3020                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3021                   DECL_SOURCE_LOCATION (result)
3022                     = DECL_SOURCE_LOCATION (decl);
3023                   /* We want to use the argument list specified in the
3024                      definition, not in the original declaration.  */
3025                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3026                   for (parm = DECL_ARGUMENTS (result); parm;
3027                        parm = DECL_CHAIN (parm))
3028                     DECL_CONTEXT (parm) = result;
3029                 }
3030               return register_specialization (tmpl, gen_tmpl, targs,
3031                                               is_friend, 0);
3032             }
3033
3034           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
3035           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3036
3037           if (was_template_id)
3038             TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3039
3040           /* Inherit default function arguments from the template
3041              DECL is specializing.  */
3042           if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3043             copy_default_args_to_explicit_spec (decl);
3044
3045           /* This specialization has the same protection as the
3046              template it specializes.  */
3047           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3048           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3049
3050           /* 7.1.1-1 [dcl.stc]
3051
3052              A storage-class-specifier shall not be specified in an
3053              explicit specialization...
3054
3055              The parser rejects these, so unless action is taken here,
3056              explicit function specializations will always appear with
3057              global linkage.
3058
3059              The action recommended by the C++ CWG in response to C++
3060              defect report 605 is to make the storage class and linkage
3061              of the explicit specialization match the templated function:
3062
3063              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3064            */
3065           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3066             {
3067               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3068               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3069
3070               /* A concept cannot be specialized.  */
3071               if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3072                 {
3073                   error ("explicit specialization of function concept %qD",
3074                          gen_tmpl);
3075                   return error_mark_node;
3076                 }
3077
3078               /* This specialization has the same linkage and visibility as
3079                  the function template it specializes.  */
3080               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3081               if (! TREE_PUBLIC (decl))
3082                 {
3083                   DECL_INTERFACE_KNOWN (decl) = 1;
3084                   DECL_NOT_REALLY_EXTERN (decl) = 1;
3085                 }
3086               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3087               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3088                 {
3089                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
3090                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3091                 }
3092             }
3093
3094           /* If DECL is a friend declaration, declared using an
3095              unqualified name, the namespace associated with DECL may
3096              have been set incorrectly.  For example, in:
3097
3098                template <typename T> void f(T);
3099                namespace N {
3100                  struct S { friend void f<int>(int); }
3101                }
3102
3103              we will have set the DECL_CONTEXT for the friend
3104              declaration to N, rather than to the global namespace.  */
3105           if (DECL_NAMESPACE_SCOPE_P (decl))
3106             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3107
3108           if (is_friend && !have_def)
3109             /* This is not really a declaration of a specialization.
3110                It's just the name of an instantiation.  But, it's not
3111                a request for an instantiation, either.  */
3112             SET_DECL_IMPLICIT_INSTANTIATION (decl);
3113           else if (TREE_CODE (decl) == FUNCTION_DECL)
3114             /* A specialization is not necessarily COMDAT.  */
3115             DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3116                                   && DECL_DECLARED_INLINE_P (decl));
3117           else if (VAR_P (decl))
3118             DECL_COMDAT (decl) = false;
3119
3120           /* If this is a full specialization, register it so that we can find
3121              it again.  Partial specializations will be registered in
3122              process_partial_specialization.  */
3123           if (!processing_template_decl)
3124             decl = register_specialization (decl, gen_tmpl, targs,
3125                                             is_friend, 0);
3126
3127           /* A 'structor should already have clones.  */
3128           gcc_assert (decl == error_mark_node
3129                       || variable_template_p (tmpl)
3130                       || !(DECL_CONSTRUCTOR_P (decl)
3131                            || DECL_DESTRUCTOR_P (decl))
3132                       || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3133         }
3134     }
3135
3136   return decl;
3137 }
3138
3139 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3140    parameters.  These are represented in the same format used for
3141    DECL_TEMPLATE_PARMS.  */
3142
3143 int
3144 comp_template_parms (const_tree parms1, const_tree parms2)
3145 {
3146   const_tree p1;
3147   const_tree p2;
3148
3149   if (parms1 == parms2)
3150     return 1;
3151
3152   for (p1 = parms1, p2 = parms2;
3153        p1 != NULL_TREE && p2 != NULL_TREE;
3154        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3155     {
3156       tree t1 = TREE_VALUE (p1);
3157       tree t2 = TREE_VALUE (p2);
3158       int i;
3159
3160       gcc_assert (TREE_CODE (t1) == TREE_VEC);
3161       gcc_assert (TREE_CODE (t2) == TREE_VEC);
3162
3163       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3164         return 0;
3165
3166       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3167         {
3168           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3169           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3170
3171           /* If either of the template parameters are invalid, assume
3172              they match for the sake of error recovery. */
3173           if (error_operand_p (parm1) || error_operand_p (parm2))
3174             return 1;
3175
3176           if (TREE_CODE (parm1) != TREE_CODE (parm2))
3177             return 0;
3178
3179           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3180               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3181                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3182             continue;
3183           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3184             return 0;
3185         }
3186     }
3187
3188   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3189     /* One set of parameters has more parameters lists than the
3190        other.  */
3191     return 0;
3192
3193   return 1;
3194 }
3195
3196 /* Determine whether PARM is a parameter pack.  */
3197
3198 bool 
3199 template_parameter_pack_p (const_tree parm)
3200 {
3201   /* Determine if we have a non-type template parameter pack.  */
3202   if (TREE_CODE (parm) == PARM_DECL)
3203     return (DECL_TEMPLATE_PARM_P (parm) 
3204             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3205   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3206     return TEMPLATE_PARM_PARAMETER_PACK (parm);
3207
3208   /* If this is a list of template parameters, we could get a
3209      TYPE_DECL or a TEMPLATE_DECL.  */ 
3210   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3211     parm = TREE_TYPE (parm);
3212
3213   /* Otherwise it must be a type template parameter.  */
3214   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3215            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3216           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3217 }
3218
3219 /* Determine if T is a function parameter pack.  */
3220
3221 bool
3222 function_parameter_pack_p (const_tree t)
3223 {
3224   if (t && TREE_CODE (t) == PARM_DECL)
3225     return DECL_PACK_P (t);
3226   return false;
3227 }
3228
3229 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3230    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
3231
3232 tree
3233 get_function_template_decl (const_tree primary_func_tmpl_inst)
3234 {
3235   if (! primary_func_tmpl_inst
3236       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3237       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
3238     return NULL;
3239
3240   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3241 }
3242
3243 /* Return true iff the function parameter PARAM_DECL was expanded
3244    from the function parameter pack PACK.  */
3245
3246 bool
3247 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3248 {
3249   if (DECL_ARTIFICIAL (param_decl)
3250       || !function_parameter_pack_p (pack))
3251     return false;
3252
3253   /* The parameter pack and its pack arguments have the same
3254      DECL_PARM_INDEX.  */
3255   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3256 }
3257
3258 /* Determine whether ARGS describes a variadic template args list,
3259    i.e., one that is terminated by a template argument pack.  */
3260
3261 static bool 
3262 template_args_variadic_p (tree args)
3263 {
3264   int nargs;
3265   tree last_parm;
3266
3267   if (args == NULL_TREE)
3268     return false;
3269
3270   args = INNERMOST_TEMPLATE_ARGS (args);
3271   nargs = TREE_VEC_LENGTH (args);
3272
3273   if (nargs == 0)
3274     return false;
3275
3276   last_parm = TREE_VEC_ELT (args, nargs - 1);
3277
3278   return ARGUMENT_PACK_P (last_parm);
3279 }
3280
3281 /* Generate a new name for the parameter pack name NAME (an
3282    IDENTIFIER_NODE) that incorporates its */
3283
3284 static tree
3285 make_ith_pack_parameter_name (tree name, int i)
3286 {
3287   /* Munge the name to include the parameter index.  */
3288 #define NUMBUF_LEN 128
3289   char numbuf[NUMBUF_LEN];
3290   char* newname;
3291   int newname_len;
3292
3293   if (name == NULL_TREE)
3294     return name;
3295   snprintf (numbuf, NUMBUF_LEN, "%i", i);
3296   newname_len = IDENTIFIER_LENGTH (name)
3297                 + strlen (numbuf) + 2;
3298   newname = (char*)alloca (newname_len);
3299   snprintf (newname, newname_len,
3300             "%s#%i", IDENTIFIER_POINTER (name), i);
3301   return get_identifier (newname);
3302 }
3303
3304 /* Return true if T is a primary function, class or alias template
3305    instantiation.  */
3306
3307 bool
3308 primary_template_instantiation_p (const_tree t)
3309 {
3310   if (!t)
3311     return false;
3312
3313   if (TREE_CODE (t) == FUNCTION_DECL)
3314     return DECL_LANG_SPECIFIC (t)
3315            && DECL_TEMPLATE_INSTANTIATION (t)
3316            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
3317   else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3318     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
3319            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
3320   else if (alias_template_specialization_p (t))
3321     return true;
3322   return false;
3323 }
3324
3325 /* Return true if PARM is a template template parameter.  */
3326
3327 bool
3328 template_template_parameter_p (const_tree parm)
3329 {
3330   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3331 }
3332
3333 /* Return true iff PARM is a DECL representing a type template
3334    parameter.  */
3335
3336 bool
3337 template_type_parameter_p (const_tree parm)
3338 {
3339   return (parm
3340           && (TREE_CODE (parm) == TYPE_DECL
3341               || TREE_CODE (parm) == TEMPLATE_DECL)
3342           && DECL_TEMPLATE_PARM_P (parm));
3343 }
3344
3345 /* Return the template parameters of T if T is a
3346    primary template instantiation, NULL otherwise.  */
3347
3348 tree
3349 get_primary_template_innermost_parameters (const_tree t)
3350 {
3351   tree parms = NULL, template_info = NULL;
3352
3353   if ((template_info = get_template_info (t))
3354       && primary_template_instantiation_p (t))
3355     parms = INNERMOST_TEMPLATE_PARMS
3356         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3357
3358   return parms;
3359 }
3360
3361 /* Return the template parameters of the LEVELth level from the full list
3362    of template parameters PARMS.  */
3363
3364 tree
3365 get_template_parms_at_level (tree parms, int level)
3366 {
3367   tree p;
3368   if (!parms
3369       || TREE_CODE (parms) != TREE_LIST
3370       || level > TMPL_PARMS_DEPTH (parms))
3371     return NULL_TREE;
3372
3373   for (p = parms; p; p = TREE_CHAIN (p))
3374     if (TMPL_PARMS_DEPTH (p) == level)
3375       return p;
3376
3377   return NULL_TREE;
3378 }
3379
3380 /* Returns the template arguments of T if T is a template instantiation,
3381    NULL otherwise.  */
3382
3383 tree
3384 get_template_innermost_arguments (const_tree t)
3385 {
3386   tree args = NULL, template_info = NULL;
3387
3388   if ((template_info = get_template_info (t))
3389       && TI_ARGS (template_info))
3390     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3391
3392   return args;
3393 }
3394
3395 /* Return the argument pack elements of T if T is a template argument pack,
3396    NULL otherwise.  */
3397
3398 tree
3399 get_template_argument_pack_elems (const_tree t)
3400 {
3401   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3402       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3403     return NULL;
3404
3405   return ARGUMENT_PACK_ARGS (t);
3406 }
3407
3408 /* Structure used to track the progress of find_parameter_packs_r.  */
3409 struct find_parameter_pack_data 
3410 {
3411   /* TREE_LIST that will contain all of the parameter packs found by
3412      the traversal.  */
3413   tree* parameter_packs;
3414
3415   /* Set of AST nodes that have been visited by the traversal.  */
3416   hash_set<tree> *visited;
3417
3418   /* True iff we're making a type pack expansion.  */
3419   bool type_pack_expansion_p;
3420 };
3421
3422 /* Identifies all of the argument packs that occur in a template
3423    argument and appends them to the TREE_LIST inside DATA, which is a
3424    find_parameter_pack_data structure. This is a subroutine of
3425    make_pack_expansion and uses_parameter_packs.  */
3426 static tree
3427 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3428 {
3429   tree t = *tp;
3430   struct find_parameter_pack_data* ppd = 
3431     (struct find_parameter_pack_data*)data;
3432   bool parameter_pack_p = false;
3433
3434   /* Handle type aliases/typedefs.  */
3435   if (TYPE_ALIAS_P (t))
3436     {
3437       if (TYPE_TEMPLATE_INFO (t))
3438         cp_walk_tree (&TYPE_TI_ARGS (t),
3439                       &find_parameter_packs_r,
3440                       ppd, ppd->visited);
3441       *walk_subtrees = 0;
3442       return NULL_TREE;
3443     }
3444
3445   /* Identify whether this is a parameter pack or not.  */
3446   switch (TREE_CODE (t))
3447     {
3448     case TEMPLATE_PARM_INDEX:
3449       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3450         parameter_pack_p = true;
3451       break;
3452
3453     case TEMPLATE_TYPE_PARM:
3454       t = TYPE_MAIN_VARIANT (t);
3455     case TEMPLATE_TEMPLATE_PARM:
3456       /* If the placeholder appears in the decl-specifier-seq of a function
3457          parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3458          is a pack expansion, the invented template parameter is a template
3459          parameter pack.  */
3460       if (ppd->type_pack_expansion_p && is_auto_or_concept (t))
3461         TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3462       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3463         parameter_pack_p = true;
3464       break;
3465
3466     case FIELD_DECL:
3467     case PARM_DECL:
3468       if (DECL_PACK_P (t))
3469         {
3470           /* We don't want to walk into the type of a PARM_DECL,
3471              because we don't want to see the type parameter pack.  */
3472           *walk_subtrees = 0;
3473           parameter_pack_p = true;
3474         }
3475       break;
3476
3477       /* Look through a lambda capture proxy to the field pack.  */
3478     case VAR_DECL:
3479       if (DECL_HAS_VALUE_EXPR_P (t))
3480         {
3481           tree v = DECL_VALUE_EXPR (t);
3482           cp_walk_tree (&v,
3483                         &find_parameter_packs_r,
3484                         ppd, ppd->visited);
3485           *walk_subtrees = 0;
3486         }
3487       else if (variable_template_specialization_p (t))
3488         {
3489           cp_walk_tree (&DECL_TI_ARGS (t),
3490                         find_parameter_packs_r,
3491                         ppd, ppd->visited);
3492           *walk_subtrees = 0;
3493         }
3494       break;
3495
3496     case BASES:
3497       parameter_pack_p = true;
3498       break;
3499     default:
3500       /* Not a parameter pack.  */
3501       break;
3502     }
3503
3504   if (parameter_pack_p)
3505     {
3506       /* Add this parameter pack to the list.  */
3507       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3508     }
3509
3510   if (TYPE_P (t))
3511     cp_walk_tree (&TYPE_CONTEXT (t), 
3512                   &find_parameter_packs_r, ppd, ppd->visited);
3513
3514   /* This switch statement will return immediately if we don't find a
3515      parameter pack.  */
3516   switch (TREE_CODE (t)) 
3517     {
3518     case TEMPLATE_PARM_INDEX:
3519       return NULL_TREE;
3520
3521     case BOUND_TEMPLATE_TEMPLATE_PARM:
3522       /* Check the template itself.  */
3523       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
3524                     &find_parameter_packs_r, ppd, ppd->visited);
3525       /* Check the template arguments.  */
3526       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
3527                     ppd->visited);
3528       *walk_subtrees = 0;
3529       return NULL_TREE;
3530
3531     case TEMPLATE_TYPE_PARM:
3532     case TEMPLATE_TEMPLATE_PARM:
3533       return NULL_TREE;
3534
3535     case PARM_DECL:
3536       return NULL_TREE;
3537
3538     case RECORD_TYPE:
3539       if (TYPE_PTRMEMFUNC_P (t))
3540         return NULL_TREE;
3541       /* Fall through.  */
3542
3543     case UNION_TYPE:
3544     case ENUMERAL_TYPE:
3545       if (TYPE_TEMPLATE_INFO (t))
3546         cp_walk_tree (&TYPE_TI_ARGS (t),
3547                       &find_parameter_packs_r, ppd, ppd->visited);
3548
3549       *walk_subtrees = 0;
3550       return NULL_TREE;
3551
3552     case CONSTRUCTOR:
3553     case TEMPLATE_DECL:
3554       cp_walk_tree (&TREE_TYPE (t),
3555                     &find_parameter_packs_r, ppd, ppd->visited);
3556       return NULL_TREE;
3557  
3558     case TYPENAME_TYPE:
3559       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3560                    ppd, ppd->visited);
3561       *walk_subtrees = 0;
3562       return NULL_TREE;
3563       
3564     case TYPE_PACK_EXPANSION:
3565     case EXPR_PACK_EXPANSION:
3566       *walk_subtrees = 0;
3567       return NULL_TREE;
3568
3569     case INTEGER_TYPE:
3570       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3571                     ppd, ppd->visited);
3572       *walk_subtrees = 0;
3573       return NULL_TREE;
3574
3575     case IDENTIFIER_NODE:
3576       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3577                     ppd->visited);
3578       *walk_subtrees = 0;
3579       return NULL_TREE;
3580
3581     case DECLTYPE_TYPE:
3582       {
3583         /* When traversing a DECLTYPE_TYPE_EXPR, we need to set
3584            type_pack_expansion_p to false so that any placeholders
3585            within the expression don't get marked as parameter packs.  */
3586         bool type_pack_expansion_p = ppd->type_pack_expansion_p;
3587         ppd->type_pack_expansion_p = false;
3588         cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
3589                       ppd, ppd->visited);
3590         ppd->type_pack_expansion_p = type_pack_expansion_p;
3591         *walk_subtrees = 0;
3592         return NULL_TREE;
3593       }
3594
3595     default:
3596       return NULL_TREE;
3597     }
3598
3599   return NULL_TREE;
3600 }
3601
3602 /* Determines if the expression or type T uses any parameter packs.  */
3603 bool
3604 uses_parameter_packs (tree t)
3605 {
3606   tree parameter_packs = NULL_TREE;
3607   struct find_parameter_pack_data ppd;
3608   ppd.parameter_packs = &parameter_packs;
3609   ppd.visited = new hash_set<tree>;
3610   ppd.type_pack_expansion_p = false;
3611   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3612   delete ppd.visited;
3613   return parameter_packs != NULL_TREE;
3614 }
3615
3616 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3617    representation a base-class initializer into a parameter pack
3618    expansion. If all goes well, the resulting node will be an
3619    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3620    respectively.  */
3621 tree 
3622 make_pack_expansion (tree arg)
3623 {
3624   tree result;
3625   tree parameter_packs = NULL_TREE;
3626   bool for_types = false;
3627   struct find_parameter_pack_data ppd;
3628
3629   if (!arg || arg == error_mark_node)
3630     return arg;
3631
3632   if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
3633     {
3634       /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
3635          class initializer.  In this case, the TREE_PURPOSE will be a
3636          _TYPE node (representing the base class expansion we're
3637          initializing) and the TREE_VALUE will be a TREE_LIST
3638          containing the initialization arguments. 
3639
3640          The resulting expansion looks somewhat different from most
3641          expansions. Rather than returning just one _EXPANSION, we
3642          return a TREE_LIST whose TREE_PURPOSE is a
3643          TYPE_PACK_EXPANSION containing the bases that will be
3644          initialized.  The TREE_VALUE will be identical to the
3645          original TREE_VALUE, which is a list of arguments that will
3646          be passed to each base.  We do not introduce any new pack
3647          expansion nodes into the TREE_VALUE (although it is possible
3648          that some already exist), because the TREE_PURPOSE and
3649          TREE_VALUE all need to be expanded together with the same
3650          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3651          resulting TREE_PURPOSE will mention the parameter packs in
3652          both the bases and the arguments to the bases.  */
3653       tree purpose;
3654       tree value;
3655       tree parameter_packs = NULL_TREE;
3656
3657       /* Determine which parameter packs will be used by the base
3658          class expansion.  */
3659       ppd.visited = new hash_set<tree>;
3660       ppd.parameter_packs = &parameter_packs;
3661       ppd.type_pack_expansion_p = true;
3662       gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
3663       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3664                     &ppd, ppd.visited);
3665
3666       if (parameter_packs == NULL_TREE)
3667         {
3668           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3669           delete ppd.visited;
3670           return error_mark_node;
3671         }
3672
3673       if (TREE_VALUE (arg) != void_type_node)
3674         {
3675           /* Collect the sets of parameter packs used in each of the
3676              initialization arguments.  */
3677           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3678             {
3679               /* Determine which parameter packs will be expanded in this
3680                  argument.  */
3681               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3682                             &ppd, ppd.visited);
3683             }
3684         }
3685
3686       delete ppd.visited;
3687
3688       /* Create the pack expansion type for the base type.  */
3689       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3690       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3691       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3692
3693       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3694          they will rarely be compared to anything.  */
3695       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3696
3697       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3698     }
3699
3700   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3701     for_types = true;
3702
3703   /* Build the PACK_EXPANSION_* node.  */
3704   result = for_types
3705      ? cxx_make_type (TYPE_PACK_EXPANSION)
3706      : make_node (EXPR_PACK_EXPANSION);
3707   SET_PACK_EXPANSION_PATTERN (result, arg);
3708   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3709     {
3710       /* Propagate type and const-expression information.  */
3711       TREE_TYPE (result) = TREE_TYPE (arg);
3712       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3713       /* Mark this read now, since the expansion might be length 0.  */
3714       mark_exp_read (arg);
3715     }
3716   else
3717     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3718        they will rarely be compared to anything.  */
3719     SET_TYPE_STRUCTURAL_EQUALITY (result);
3720
3721   /* Determine which parameter packs will be expanded.  */
3722   ppd.parameter_packs = &parameter_packs;
3723   ppd.visited = new hash_set<tree>;
3724   ppd.type_pack_expansion_p = TYPE_P (arg);
3725   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3726   delete ppd.visited;
3727
3728   /* Make sure we found some parameter packs.  */
3729   if (parameter_packs == NULL_TREE)
3730     {
3731       if (TYPE_P (arg))
3732         error ("expansion pattern %<%T%> contains no argument packs", arg);
3733       else
3734         error ("expansion pattern %<%E%> contains no argument packs", arg);
3735       return error_mark_node;
3736     }
3737   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3738
3739   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
3740
3741   return result;
3742 }
3743
3744 /* Checks T for any "bare" parameter packs, which have not yet been
3745    expanded, and issues an error if any are found. This operation can
3746    only be done on full expressions or types (e.g., an expression
3747    statement, "if" condition, etc.), because we could have expressions like:
3748
3749      foo(f(g(h(args)))...)
3750
3751    where "args" is a parameter pack. check_for_bare_parameter_packs
3752    should not be called for the subexpressions args, h(args),
3753    g(h(args)), or f(g(h(args))), because we would produce erroneous
3754    error messages. 
3755
3756    Returns TRUE and emits an error if there were bare parameter packs,
3757    returns FALSE otherwise.  */
3758 bool 
3759 check_for_bare_parameter_packs (tree t)
3760 {
3761   tree parameter_packs = NULL_TREE;
3762   struct find_parameter_pack_data ppd;
3763
3764   if (!processing_template_decl || !t || t == error_mark_node)
3765     return false;
3766
3767   if (TREE_CODE (t) == TYPE_DECL)
3768     t = TREE_TYPE (t);
3769
3770   ppd.parameter_packs = &parameter_packs;
3771   ppd.visited = new hash_set<tree>;
3772   ppd.type_pack_expansion_p = false;
3773   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3774   delete ppd.visited;
3775
3776   if (parameter_packs) 
3777     {
3778       error ("parameter packs not expanded with %<...%>:");
3779       while (parameter_packs)
3780         {
3781           tree pack = TREE_VALUE (parameter_packs);
3782           tree name = NULL_TREE;
3783
3784           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3785               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3786             name = TYPE_NAME (pack);
3787           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3788             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3789           else
3790             name = DECL_NAME (pack);
3791
3792           if (name)
3793             inform (input_location, "        %qD", name);
3794           else
3795             inform (input_location, "        <anonymous>");
3796
3797           parameter_packs = TREE_CHAIN (parameter_packs);
3798         }
3799
3800       return true;
3801     }
3802
3803   return false;
3804 }
3805
3806 /* Expand any parameter packs that occur in the template arguments in
3807    ARGS.  */
3808 tree
3809 expand_template_argument_pack (tree args)
3810 {
3811   tree result_args = NULL_TREE;
3812   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3813   int num_result_args = -1;
3814   int non_default_args_count = -1;
3815
3816   /* First, determine if we need to expand anything, and the number of
3817      slots we'll need.  */
3818   for (in_arg = 0; in_arg < nargs; ++in_arg)
3819     {
3820       tree arg = TREE_VEC_ELT (args, in_arg);
3821       if (arg == NULL_TREE)
3822         return args;
3823       if (ARGUMENT_PACK_P (arg))
3824         {
3825           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3826           if (num_result_args < 0)
3827             num_result_args = in_arg + num_packed;
3828           else
3829             num_result_args += num_packed;
3830         }
3831       else
3832         {
3833           if (num_result_args >= 0)
3834             num_result_args++;
3835         }
3836     }
3837
3838   /* If no expansion is necessary, we're done.  */
3839   if (num_result_args < 0)
3840     return args;
3841
3842   /* Expand arguments.  */
3843   result_args = make_tree_vec (num_result_args);
3844   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3845     non_default_args_count =
3846       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3847   for (in_arg = 0; in_arg < nargs; ++in_arg)
3848     {
3849       tree arg = TREE_VEC_ELT (args, in_arg);
3850       if (ARGUMENT_PACK_P (arg))
3851         {
3852           tree packed = ARGUMENT_PACK_ARGS (arg);
3853           int i, num_packed = TREE_VEC_LENGTH (packed);
3854           for (i = 0; i < num_packed; ++i, ++out_arg)
3855             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3856           if (non_default_args_count > 0)
3857             non_default_args_count += num_packed - 1;
3858         }
3859       else
3860         {
3861           TREE_VEC_ELT (result_args, out_arg) = arg;
3862           ++out_arg;
3863         }
3864     }
3865   if (non_default_args_count >= 0)
3866     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3867   return result_args;
3868 }
3869
3870 /* Checks if DECL shadows a template parameter.
3871
3872    [temp.local]: A template-parameter shall not be redeclared within its
3873    scope (including nested scopes).
3874
3875    Emits an error and returns TRUE if the DECL shadows a parameter,
3876    returns FALSE otherwise.  */
3877
3878 bool
3879 check_template_shadow (tree decl)
3880 {
3881   tree olddecl;
3882
3883   /* If we're not in a template, we can't possibly shadow a template
3884      parameter.  */
3885   if (!current_template_parms)
3886     return true;
3887
3888   /* Figure out what we're shadowing.  */
3889   if (TREE_CODE (decl) == OVERLOAD)
3890     decl = OVL_CURRENT (decl);
3891   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3892
3893   /* If there's no previous binding for this name, we're not shadowing
3894      anything, let alone a template parameter.  */
3895   if (!olddecl)
3896     return true;
3897
3898   /* If we're not shadowing a template parameter, we're done.  Note
3899      that OLDDECL might be an OVERLOAD (or perhaps even an
3900      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3901      node.  */
3902   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3903     return true;
3904
3905   /* We check for decl != olddecl to avoid bogus errors for using a
3906      name inside a class.  We check TPFI to avoid duplicate errors for
3907      inline member templates.  */
3908   if (decl == olddecl
3909       || (DECL_TEMPLATE_PARM_P (decl)
3910           && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
3911     return true;
3912
3913   /* Don't complain about the injected class name, as we've already
3914      complained about the class itself.  */
3915   if (DECL_SELF_REFERENCE_P (decl))
3916     return false;
3917
3918   if (DECL_TEMPLATE_PARM_P (decl))
3919     error ("declaration of template parameter %q+D shadows "
3920            "template parameter", decl);
3921   else
3922     error ("declaration of %q+#D shadows template parameter", decl);
3923   inform (DECL_SOURCE_LOCATION (olddecl),
3924           "template parameter %qD declared here", olddecl);
3925   return false;
3926 }
3927
3928 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3929    ORIG_LEVEL, DECL, and TYPE.  */
3930
3931 static tree
3932 build_template_parm_index (int index,
3933                            int level,
3934                            int orig_level,
3935                            tree decl,
3936                            tree type)
3937 {
3938   tree t = make_node (TEMPLATE_PARM_INDEX);
3939   TEMPLATE_PARM_IDX (t) = index;
3940   TEMPLATE_PARM_LEVEL (t) = level;
3941   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3942   TEMPLATE_PARM_DECL (t) = decl;
3943   TREE_TYPE (t) = type;
3944   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3945   TREE_READONLY (t) = TREE_READONLY (decl);
3946
3947   return t;
3948 }
3949
3950 /* Find the canonical type parameter for the given template type
3951    parameter.  Returns the canonical type parameter, which may be TYPE
3952    if no such parameter existed.  */
3953
3954 static tree
3955 canonical_type_parameter (tree type)
3956 {
3957   tree list;
3958   int idx = TEMPLATE_TYPE_IDX (type);
3959   if (!canonical_template_parms)
3960     vec_alloc (canonical_template_parms, idx+1);
3961
3962   while (canonical_template_parms->length () <= (unsigned)idx)
3963     vec_safe_push (canonical_template_parms, NULL_TREE);
3964
3965   list = (*canonical_template_parms)[idx];
3966   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3967     list = TREE_CHAIN (list);
3968
3969   if (list)
3970     return TREE_VALUE (list);
3971   else
3972     {
3973       (*canonical_template_parms)[idx]
3974                 = tree_cons (NULL_TREE, type,
3975                              (*canonical_template_parms)[idx]);
3976       return type;
3977     }
3978 }
3979
3980 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3981    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3982    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3983    new one is created.  */
3984
3985 static tree
3986 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3987                             tsubst_flags_t complain)
3988 {
3989   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3990       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3991           != TEMPLATE_PARM_LEVEL (index) - levels)
3992       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3993     {
3994       tree orig_decl = TEMPLATE_PARM_DECL (index);
3995       tree decl, t;
3996
3997       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3998                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3999       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4000       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4001       DECL_ARTIFICIAL (decl) = 1;
4002       SET_DECL_TEMPLATE_PARM_P (decl);
4003
4004       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4005                                      TEMPLATE_PARM_LEVEL (index) - levels,
4006                                      TEMPLATE_PARM_ORIG_LEVEL (index),
4007                                      decl, type);
4008       TEMPLATE_PARM_DESCENDANTS (index) = t;
4009       TEMPLATE_PARM_PARAMETER_PACK (t) 
4010         = TEMPLATE_PARM_PARAMETER_PACK (index);
4011
4012         /* Template template parameters need this.  */
4013       if (TREE_CODE (decl) == TEMPLATE_DECL)
4014         {
4015           DECL_TEMPLATE_RESULT (decl)
4016             = build_decl (DECL_SOURCE_LOCATION (decl),
4017                           TYPE_DECL, DECL_NAME (decl), type);
4018           DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (decl)) = true;
4019           DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4020             (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4021         }
4022     }
4023
4024   return TEMPLATE_PARM_DESCENDANTS (index);
4025 }
4026
4027 /* Process information from new template parameter PARM and append it
4028    to the LIST being built.  This new parameter is a non-type
4029    parameter iff IS_NON_TYPE is true. This new parameter is a
4030    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
4031    is in PARM_LOC.  */
4032
4033 tree
4034 process_template_parm (tree list, location_t parm_loc, tree parm,
4035                        bool is_non_type, bool is_parameter_pack)
4036 {
4037   tree decl = 0;
4038   int idx = 0;
4039
4040   gcc_assert (TREE_CODE (parm) == TREE_LIST);
4041   tree defval = TREE_PURPOSE (parm);
4042   tree constr = TREE_TYPE (parm);
4043
4044   if (list)
4045     {
4046       tree p = tree_last (list);
4047
4048       if (p && TREE_VALUE (p) != error_mark_node)
4049         {
4050           p = TREE_VALUE (p);
4051           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4052             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4053           else
4054             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4055         }
4056
4057       ++idx;
4058     }
4059
4060   if (is_non_type)
4061     {
4062       parm = TREE_VALUE (parm);
4063
4064       SET_DECL_TEMPLATE_PARM_P (parm);
4065
4066       if (TREE_TYPE (parm) != error_mark_node)
4067         {
4068           /* [temp.param]
4069
4070              The top-level cv-qualifiers on the template-parameter are
4071              ignored when determining its type.  */
4072           TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4073           if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4074             TREE_TYPE (parm) = error_mark_node;
4075           else if (uses_parameter_packs (TREE_TYPE (parm))
4076                    && !is_parameter_pack
4077                    /* If we're in a nested template parameter list, the template
4078                       template parameter could be a parameter pack.  */
4079                    && processing_template_parmlist == 1)
4080             {
4081               /* This template parameter is not a parameter pack, but it
4082                  should be. Complain about "bare" parameter packs.  */
4083               check_for_bare_parameter_packs (TREE_TYPE (parm));
4084
4085               /* Recover by calling this a parameter pack.  */
4086               is_parameter_pack = true;
4087             }
4088         }
4089
4090       /* A template parameter is not modifiable.  */
4091       TREE_CONSTANT (parm) = 1;
4092       TREE_READONLY (parm) = 1;
4093       decl = build_decl (parm_loc,
4094                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4095       TREE_CONSTANT (decl) = 1;
4096       TREE_READONLY (decl) = 1;
4097       DECL_INITIAL (parm) = DECL_INITIAL (decl)
4098         = build_template_parm_index (idx, processing_template_decl,
4099                                      processing_template_decl,
4100                                      decl, TREE_TYPE (parm));
4101
4102       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
4103         = is_parameter_pack;
4104     }
4105   else
4106     {
4107       tree t;
4108       parm = TREE_VALUE (TREE_VALUE (parm));
4109
4110       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4111         {
4112           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4113           /* This is for distinguishing between real templates and template
4114              template parameters */
4115           TREE_TYPE (parm) = t;
4116           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
4117           decl = parm;
4118         }
4119       else
4120         {
4121           t = cxx_make_type (TEMPLATE_TYPE_PARM);
4122           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
4123           decl = build_decl (parm_loc,
4124                              TYPE_DECL, parm, t);
4125         }
4126
4127       TYPE_NAME (t) = decl;
4128       TYPE_STUB_DECL (t) = decl;
4129       parm = decl;
4130       TEMPLATE_TYPE_PARM_INDEX (t)
4131         = build_template_parm_index (idx, processing_template_decl,
4132                                      processing_template_decl,
4133                                      decl, TREE_TYPE (parm));
4134       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4135       TYPE_CANONICAL (t) = canonical_type_parameter (t);
4136     }
4137   DECL_ARTIFICIAL (decl) = 1;
4138   SET_DECL_TEMPLATE_PARM_P (decl);
4139
4140   /* Build requirements for the type/template parameter.
4141      This must be done after SET_DECL_TEMPLATE_PARM_P or
4142      process_template_parm could fail. */
4143   tree reqs = finish_shorthand_constraint (parm, constr);
4144
4145   pushdecl (decl);
4146
4147   /* Build the parameter node linking the parameter declaration,
4148      its default argument (if any), and its constraints (if any). */
4149   parm = build_tree_list (defval, parm);
4150   TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4151
4152   return chainon (list, parm);
4153 }
4154
4155 /* The end of a template parameter list has been reached.  Process the
4156    tree list into a parameter vector, converting each parameter into a more
4157    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
4158    as PARM_DECLs.  */
4159
4160 tree
4161 end_template_parm_list (tree parms)
4162 {
4163   int nparms;
4164   tree parm, next;
4165   tree saved_parmlist = make_tree_vec (list_length (parms));
4166
4167   /* Pop the dummy parameter level and add the real one.  */
4168   current_template_parms = TREE_CHAIN (current_template_parms);
4169
4170   current_template_parms
4171     = tree_cons (size_int (processing_template_decl),
4172                  saved_parmlist, current_template_parms);
4173
4174   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
4175     {
4176       next = TREE_CHAIN (parm);
4177       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
4178       TREE_CHAIN (parm) = NULL_TREE;
4179     }
4180
4181   --processing_template_parmlist;
4182
4183   return saved_parmlist;
4184 }
4185
4186 // Explicitly indicate the end of the template parameter list. We assume
4187 // that the current template parameters have been constructed and/or
4188 // managed explicitly, as when creating new template template parameters
4189 // from a shorthand constraint.
4190 void
4191 end_template_parm_list ()
4192 {
4193   --processing_template_parmlist;
4194 }
4195
4196 /* end_template_decl is called after a template declaration is seen.  */
4197
4198 void
4199 end_template_decl (void)
4200 {
4201   reset_specialization ();
4202
4203   if (! processing_template_decl)
4204     return;
4205
4206   /* This matches the pushlevel in begin_template_parm_list.  */
4207   finish_scope ();
4208
4209   --processing_template_decl;
4210   current_template_parms = TREE_CHAIN (current_template_parms);
4211 }
4212
4213 /* Takes a TREE_LIST representing a template parameter and convert it
4214    into an argument suitable to be passed to the type substitution
4215    functions.  Note that If the TREE_LIST contains an error_mark
4216    node, the returned argument is error_mark_node.  */
4217
4218 tree
4219 template_parm_to_arg (tree t)
4220 {
4221
4222   if (t == NULL_TREE
4223       || TREE_CODE (t) != TREE_LIST)
4224     return t;
4225
4226   if (error_operand_p (TREE_VALUE (t)))
4227     return error_mark_node;
4228
4229   t = TREE_VALUE (t);
4230
4231   if (TREE_CODE (t) == TYPE_DECL
4232       || TREE_CODE (t) == TEMPLATE_DECL)
4233     {
4234       t = TREE_TYPE (t);
4235
4236       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4237         {
4238           /* Turn this argument into a TYPE_ARGUMENT_PACK
4239              with a single element, which expands T.  */
4240           tree vec = make_tree_vec (1);
4241           if (CHECKING_P)
4242             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4243
4244           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4245
4246           t = cxx_make_type (TYPE_ARGUMENT_PACK);
4247           SET_ARGUMENT_PACK_ARGS (t, vec);
4248         }
4249     }
4250   else
4251     {
4252       t = DECL_INITIAL (t);
4253
4254       if (TEMPLATE_PARM_PARAMETER_PACK (t))
4255         {
4256           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4257              with a single element, which expands T.  */
4258           tree vec = make_tree_vec (1);
4259           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
4260           if (CHECKING_P)
4261             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4262
4263           t = convert_from_reference (t);
4264           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4265
4266           t  = make_node (NONTYPE_ARGUMENT_PACK);
4267           SET_ARGUMENT_PACK_ARGS (t, vec);
4268           TREE_TYPE (t) = type;
4269         }
4270       else
4271         t = convert_from_reference (t);
4272     }
4273   return t;
4274 }
4275
4276 /* Given a set of template parameters, return them as a set of template
4277    arguments.  The template parameters are represented as a TREE_VEC, in
4278    the form documented in cp-tree.h for template arguments.  */
4279
4280 static tree
4281 template_parms_to_args (tree parms)
4282 {
4283   tree header;
4284   tree args = NULL_TREE;
4285   int length = TMPL_PARMS_DEPTH (parms);
4286   int l = length;
4287
4288   /* If there is only one level of template parameters, we do not
4289      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4290      TREE_VEC containing the arguments.  */
4291   if (length > 1)
4292     args = make_tree_vec (length);
4293
4294   for (header = parms; header; header = TREE_CHAIN (header))
4295     {
4296       tree a = copy_node (TREE_VALUE (header));
4297       int i;
4298
4299       TREE_TYPE (a) = NULL_TREE;
4300       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4301         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4302
4303       if (CHECKING_P)
4304         SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4305
4306       if (length > 1)
4307         TREE_VEC_ELT (args, --l) = a;
4308       else
4309         args = a;
4310     }
4311
4312   return args;
4313 }
4314
4315 /* Within the declaration of a template, return the currently active
4316    template parameters as an argument TREE_VEC.  */
4317
4318 static tree
4319 current_template_args (void)
4320 {
4321   return template_parms_to_args (current_template_parms);
4322 }
4323
4324 /* Update the declared TYPE by doing any lookups which were thought to be
4325    dependent, but are not now that we know the SCOPE of the declarator.  */
4326
4327 tree
4328 maybe_update_decl_type (tree orig_type, tree scope)
4329 {
4330   tree type = orig_type;
4331
4332   if (type == NULL_TREE)
4333     return type;
4334
4335   if (TREE_CODE (orig_type) == TYPE_DECL)
4336     type = TREE_TYPE (type);
4337
4338   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4339       && dependent_type_p (type)
4340       /* Don't bother building up the args in this case.  */
4341       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4342     {
4343       /* tsubst in the args corresponding to the template parameters,
4344          including auto if present.  Most things will be unchanged, but
4345          make_typename_type and tsubst_qualified_id will resolve
4346          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4347       tree args = current_template_args ();
4348       tree auto_node = type_uses_auto (type);
4349       tree pushed;
4350       if (auto_node)
4351         {
4352           tree auto_vec = make_tree_vec (1);
4353           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4354           args = add_to_template_args (args, auto_vec);
4355         }
4356       pushed = push_scope (scope);
4357       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4358       if (pushed)
4359         pop_scope (scope);
4360     }
4361
4362   if (type == error_mark_node)
4363     return orig_type;
4364
4365   if (TREE_CODE (orig_type) == TYPE_DECL)
4366     {
4367       if (same_type_p (type, TREE_TYPE (orig_type)))
4368         type = orig_type;
4369       else
4370         type = TYPE_NAME (type);
4371     }
4372   return type;
4373 }
4374
4375 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4376    template PARMS and constraints, CONSTR.  If MEMBER_TEMPLATE_P is true,
4377    the new  template is a member template. */
4378
4379 tree
4380 build_template_decl (tree decl, tree parms, bool member_template_p)
4381 {
4382   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4383   DECL_TEMPLATE_PARMS (tmpl) = parms;
4384   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4385   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4386   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4387
4388   return tmpl;
4389 }
4390
4391 struct template_parm_data
4392 {
4393   /* The level of the template parameters we are currently
4394      processing.  */
4395   int level;
4396
4397   /* The index of the specialization argument we are currently
4398      processing.  */
4399   int current_arg;
4400
4401   /* An array whose size is the number of template parameters.  The
4402      elements are nonzero if the parameter has been used in any one
4403      of the arguments processed so far.  */
4404   int* parms;
4405
4406   /* An array whose size is the number of template arguments.  The
4407      elements are nonzero if the argument makes use of template
4408      parameters of this level.  */
4409   int* arg_uses_template_parms;
4410 };
4411
4412 /* Subroutine of push_template_decl used to see if each template
4413    parameter in a partial specialization is used in the explicit
4414    argument list.  If T is of the LEVEL given in DATA (which is
4415    treated as a template_parm_data*), then DATA->PARMS is marked
4416    appropriately.  */
4417
4418 static int
4419 mark_template_parm (tree t, void* data)
4420 {
4421   int level;
4422   int idx;
4423   struct template_parm_data* tpd = (struct template_parm_data*) data;
4424
4425   template_parm_level_and_index (t, &level, &idx);
4426
4427   if (level == tpd->level)
4428     {
4429       tpd->parms[idx] = 1;
4430       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4431     }
4432
4433   /* Return zero so that for_each_template_parm will continue the
4434      traversal of the tree; we want to mark *every* template parm.  */
4435   return 0;
4436 }
4437
4438 /* Process the partial specialization DECL.  */
4439
4440 static tree
4441 process_partial_specialization (tree decl)
4442 {
4443   tree type = TREE_TYPE (decl);
4444   tree tinfo = get_template_info (decl);
4445   tree maintmpl = TI_TEMPLATE (tinfo);
4446   tree specargs = TI_ARGS (tinfo);
4447   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4448   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4449   tree inner_parms;
4450   tree inst;
4451   int nargs = TREE_VEC_LENGTH (inner_args);
4452   int ntparms;
4453   int  i;
4454   bool did_error_intro = false;
4455   struct template_parm_data tpd;
4456   struct template_parm_data tpd2;
4457
4458   gcc_assert (current_template_parms);
4459
4460   /* A concept cannot be specialized.  */
4461   if (flag_concepts && variable_concept_p (maintmpl))
4462     {
4463       error ("specialization of variable concept %q#D", maintmpl);
4464       return error_mark_node;
4465     }
4466
4467   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4468   ntparms = TREE_VEC_LENGTH (inner_parms);
4469
4470   /* We check that each of the template parameters given in the
4471      partial specialization is used in the argument list to the
4472      specialization.  For example:
4473
4474        template <class T> struct S;
4475        template <class T> struct S<T*>;
4476
4477      The second declaration is OK because `T*' uses the template
4478      parameter T, whereas
4479
4480        template <class T> struct S<int>;
4481
4482      is no good.  Even trickier is:
4483
4484        template <class T>
4485        struct S1
4486        {
4487           template <class U>
4488           struct S2;
4489           template <class U>
4490           struct S2<T>;
4491        };
4492
4493      The S2<T> declaration is actually invalid; it is a
4494      full-specialization.  Of course,
4495
4496           template <class U>
4497           struct S2<T (*)(U)>;
4498
4499      or some such would have been OK.  */
4500   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4501   tpd.parms = XALLOCAVEC (int, ntparms);
4502   memset (tpd.parms, 0, sizeof (int) * ntparms);
4503
4504   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4505   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4506   for (i = 0; i < nargs; ++i)
4507     {
4508       tpd.current_arg = i;
4509       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4510                               &mark_template_parm,
4511                               &tpd,
4512                               NULL,
4513                               /*include_nondeduced_p=*/false);
4514     }
4515   for (i = 0; i < ntparms; ++i)
4516     if (tpd.parms[i] == 0)
4517       {
4518         /* One of the template parms was not used in a deduced context in the
4519            specialization.  */
4520         if (!did_error_intro)
4521           {
4522             error ("template parameters not deducible in "
4523                    "partial specialization:");
4524             did_error_intro = true;
4525           }
4526
4527         inform (input_location, "        %qD",
4528                 TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4529       }
4530
4531   if (did_error_intro)
4532     return error_mark_node;
4533
4534   /* [temp.class.spec]
4535
4536      The argument list of the specialization shall not be identical to
4537      the implicit argument list of the primary template.  */
4538   tree main_args
4539     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
4540   if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
4541       && (!flag_concepts
4542           || !strictly_subsumes (current_template_constraints (),
4543                                  get_constraints (maintmpl))))
4544     {
4545       if (!flag_concepts)
4546         error ("partial specialization %q+D does not specialize "
4547                "any template arguments", decl);
4548       else
4549         error ("partial specialization %q+D does not specialize any "
4550                "template arguments and is not more constrained than", decl);
4551       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4552     }
4553
4554   /* A partial specialization that replaces multiple parameters of the
4555      primary template with a pack expansion is less specialized for those
4556      parameters.  */
4557   if (nargs < DECL_NTPARMS (maintmpl))
4558     {
4559       error ("partial specialization is not more specialized than the "
4560              "primary template because it replaces multiple parameters "
4561              "with a pack expansion");
4562       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4563       return decl;
4564     }
4565
4566   /* [temp.class.spec]
4567
4568      A partially specialized non-type argument expression shall not
4569      involve template parameters of the partial specialization except
4570      when the argument expression is a simple identifier.
4571
4572      The type of a template parameter corresponding to a specialized
4573      non-type argument shall not be dependent on a parameter of the
4574      specialization. 
4575
4576      Also, we verify that pack expansions only occur at the
4577      end of the argument list.  */
4578   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4579   tpd2.parms = 0;
4580   for (i = 0; i < nargs; ++i)
4581     {
4582       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4583       tree arg = TREE_VEC_ELT (inner_args, i);
4584       tree packed_args = NULL_TREE;
4585       int j, len = 1;
4586
4587       if (ARGUMENT_PACK_P (arg))
4588         {
4589           /* Extract the arguments from the argument pack. We'll be
4590              iterating over these in the following loop.  */
4591           packed_args = ARGUMENT_PACK_ARGS (arg);
4592           len = TREE_VEC_LENGTH (packed_args);
4593         }
4594
4595       for (j = 0; j < len; j++)
4596         {
4597           if (packed_args)
4598             /* Get the Jth argument in the parameter pack.  */
4599             arg = TREE_VEC_ELT (packed_args, j);
4600
4601           if (PACK_EXPANSION_P (arg))
4602             {
4603               /* Pack expansions must come at the end of the
4604                  argument list.  */
4605               if ((packed_args && j < len - 1)
4606                   || (!packed_args && i < nargs - 1))
4607                 {
4608                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4609                     error ("parameter pack argument %qE must be at the "
4610                            "end of the template argument list", arg);
4611                   else
4612                     error ("parameter pack argument %qT must be at the "
4613                            "end of the template argument list", arg);
4614                 }
4615             }
4616
4617           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4618             /* We only care about the pattern.  */
4619             arg = PACK_EXPANSION_PATTERN (arg);
4620
4621           if (/* These first two lines are the `non-type' bit.  */
4622               !TYPE_P (arg)
4623               && TREE_CODE (arg) != TEMPLATE_DECL
4624               /* This next two lines are the `argument expression is not just a
4625                  simple identifier' condition and also the `specialized
4626                  non-type argument' bit.  */
4627               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
4628               && !(REFERENCE_REF_P (arg)
4629                    && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
4630             {
4631               if ((!packed_args && tpd.arg_uses_template_parms[i])
4632                   || (packed_args && uses_template_parms (arg)))
4633                 error ("template argument %qE involves template parameter(s)",
4634                        arg);
4635               else 
4636                 {
4637                   /* Look at the corresponding template parameter,
4638                      marking which template parameters its type depends
4639                      upon.  */
4640                   tree type = TREE_TYPE (parm);
4641
4642                   if (!tpd2.parms)
4643                     {
4644                       /* We haven't yet initialized TPD2.  Do so now.  */
4645                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4646                       /* The number of parameters here is the number in the
4647                          main template, which, as checked in the assertion
4648                          above, is NARGS.  */
4649                       tpd2.parms = XALLOCAVEC (int, nargs);
4650                       tpd2.level = 
4651                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4652                     }
4653
4654                   /* Mark the template parameters.  But this time, we're
4655                      looking for the template parameters of the main
4656                      template, not in the specialization.  */
4657                   tpd2.current_arg = i;
4658                   tpd2.arg_uses_template_parms[i] = 0;
4659                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4660                   for_each_template_parm (type,
4661                                           &mark_template_parm,
4662                                           &tpd2,
4663                                           NULL,
4664                                           /*include_nondeduced_p=*/false);
4665
4666                   if (tpd2.arg_uses_template_parms [i])
4667                     {
4668                       /* The type depended on some template parameters.
4669                          If they are fully specialized in the
4670                          specialization, that's OK.  */
4671                       int j;
4672                       int count = 0;
4673                       for (j = 0; j < nargs; ++j)
4674                         if (tpd2.parms[j] != 0
4675                             && tpd.arg_uses_template_parms [j])
4676                           ++count;
4677                       if (count != 0)
4678                         error_n (input_location, count,
4679                                  "type %qT of template argument %qE depends "
4680                                  "on a template parameter",
4681                                  "type %qT of template argument %qE depends "
4682                                  "on template parameters",
4683                                  type,
4684                                  arg);
4685                     }
4686                 }
4687             }
4688         }
4689     }
4690
4691   /* We should only get here once.  */
4692   if (TREE_CODE (decl) == TYPE_DECL)
4693     gcc_assert (!COMPLETE_TYPE_P (type));
4694
4695   // Build the template decl.
4696   tree tmpl = build_template_decl (decl, current_template_parms,
4697                                    DECL_MEMBER_TEMPLATE_P (maintmpl));
4698   TREE_TYPE (tmpl) = type;
4699   DECL_TEMPLATE_RESULT (tmpl) = decl;
4700   SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4701   DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
4702   DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
4703
4704   if (VAR_P (decl))
4705     /* We didn't register this in check_explicit_specialization so we could
4706        wait until the constraints were set.  */
4707     decl = register_specialization (decl, maintmpl, specargs, false, 0);
4708   else
4709     associate_classtype_constraints (type);
4710
4711   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4712     = tree_cons (specargs, tmpl,
4713                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4714   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4715
4716   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4717        inst = TREE_CHAIN (inst))
4718     {
4719       tree instance = TREE_VALUE (inst);
4720       if (TYPE_P (instance)
4721           ? (COMPLETE_TYPE_P (instance)
4722              && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
4723           : DECL_TEMPLATE_INSTANTIATION (instance))
4724         {
4725           tree spec = most_specialized_partial_spec (instance, tf_none);
4726           tree inst_decl = (DECL_P (instance)
4727                             ? instance : TYPE_NAME (instance));
4728           if (!spec)
4729             /* OK */;
4730           else if (spec == error_mark_node)
4731             permerror (input_location,
4732                        "declaration of %qD ambiguates earlier template "
4733                        "instantiation for %qD", decl, inst_decl);
4734           else if (TREE_VALUE (spec) == tmpl)
4735             permerror (input_location,
4736                        "partial specialization of %qD after instantiation "
4737                        "of %qD", decl, inst_decl);
4738         }
4739     }
4740
4741   return decl;
4742 }
4743
4744 /* PARM is a template parameter of some form; return the corresponding
4745    TEMPLATE_PARM_INDEX.  */
4746
4747 static tree
4748 get_template_parm_index (tree parm)
4749 {
4750   if (TREE_CODE (parm) == PARM_DECL
4751       || TREE_CODE (parm) == CONST_DECL)
4752     parm = DECL_INITIAL (parm);
4753   else if (TREE_CODE (parm) == TYPE_DECL
4754            || TREE_CODE (parm) == TEMPLATE_DECL)
4755     parm = TREE_TYPE (parm);
4756   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
4757       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
4758       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
4759     parm = TEMPLATE_TYPE_PARM_INDEX (parm);
4760   gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
4761   return parm;
4762 }
4763
4764 /* Subroutine of fixed_parameter_pack_p below.  Look for any template
4765    parameter packs used by the template parameter PARM.  */
4766
4767 static void
4768 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
4769 {
4770   /* A type parm can't refer to another parm.  */
4771   if (TREE_CODE (parm) == TYPE_DECL)
4772     return;
4773   else if (TREE_CODE (parm) == PARM_DECL)
4774     {
4775       cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
4776                     ppd, ppd->visited);
4777       return;
4778     }
4779
4780   gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
4781
4782   tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
4783   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
4784     fixed_parameter_pack_p_1 (TREE_VALUE (TREE_VEC_ELT (vec, i)), ppd);
4785 }
4786
4787 /* PARM is a template parameter pack.  Return any parameter packs used in
4788    its type or the type of any of its template parameters.  If there are
4789    any such packs, it will be instantiated into a fixed template parameter
4790    list by partial instantiation rather than be fully deduced.  */
4791
4792 tree
4793 fixed_parameter_pack_p (tree parm)
4794 {
4795   /* This can only be true in a member template.  */
4796   if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
4797     return NULL_TREE;
4798   /* This can only be true for a parameter pack.  */
4799   if (!template_parameter_pack_p (parm))
4800     return NULL_TREE;
4801   /* A type parm can't refer to another parm.  */
4802   if (TREE_CODE (parm) == TYPE_DECL)
4803     return NULL_TREE;
4804
4805   tree parameter_packs = NULL_TREE;
4806   struct find_parameter_pack_data ppd;
4807   ppd.parameter_packs = &parameter_packs;
4808   ppd.visited = new hash_set<tree>;
4809   ppd.type_pack_expansion_p = false;
4810
4811   fixed_parameter_pack_p_1 (parm, &ppd);
4812
4813   delete ppd.visited;
4814   return parameter_packs;
4815 }
4816
4817 /* Check that a template declaration's use of default arguments and
4818    parameter packs is not invalid.  Here, PARMS are the template
4819    parameters.  IS_PRIMARY is true if DECL is the thing declared by
4820    a primary template.  IS_PARTIAL is true if DECL is a partial
4821    specialization.
4822
4823    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4824    declaration (but not a definition); 1 indicates a declaration, 2
4825    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4826    emitted for extraneous default arguments.
4827
4828    Returns TRUE if there were no errors found, FALSE otherwise. */
4829
4830 bool
4831 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
4832                          bool is_partial, int is_friend_decl)
4833 {
4834   const char *msg;
4835   int last_level_to_check;
4836   tree parm_level;
4837   bool no_errors = true;
4838
4839   /* [temp.param]
4840
4841      A default template-argument shall not be specified in a
4842      function template declaration or a function template definition, nor
4843      in the template-parameter-list of the definition of a member of a
4844      class template.  */
4845
4846   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
4847       || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_FUNCTION_P (decl)))
4848     /* You can't have a function template declaration in a local
4849        scope, nor you can you define a member of a class template in a
4850        local scope.  */
4851     return true;
4852
4853   if ((TREE_CODE (decl) == TYPE_DECL
4854        && TREE_TYPE (decl)
4855        && LAMBDA_TYPE_P (TREE_TYPE (decl)))
4856       || (TREE_CODE (decl) == FUNCTION_DECL
4857           && LAMBDA_FUNCTION_P (decl)))
4858     /* A lambda doesn't have an explicit declaration; don't complain
4859        about the parms of the enclosing class.  */
4860     return true;
4861
4862   if (current_class_type
4863       && !TYPE_BEING_DEFINED (current_class_type)
4864       && DECL_LANG_SPECIFIC (decl)
4865       && DECL_DECLARES_FUNCTION_P (decl)
4866       /* If this is either a friend defined in the scope of the class
4867          or a member function.  */
4868       && (DECL_FUNCTION_MEMBER_P (decl)
4869           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4870           : DECL_FRIEND_CONTEXT (decl)
4871           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4872           : false)
4873       /* And, if it was a member function, it really was defined in
4874          the scope of the class.  */
4875       && (!DECL_FUNCTION_MEMBER_P (decl)
4876           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4877     /* We already checked these parameters when the template was
4878        declared, so there's no need to do it again now.  This function
4879        was defined in class scope, but we're processing its body now
4880        that the class is complete.  */
4881     return true;
4882
4883   /* Core issue 226 (C++0x only): the following only applies to class
4884      templates.  */
4885   if (is_primary
4886       && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
4887     {
4888       /* [temp.param]
4889
4890          If a template-parameter has a default template-argument, all
4891          subsequent template-parameters shall have a default
4892          template-argument supplied.  */
4893       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4894         {
4895           tree inner_parms = TREE_VALUE (parm_level);
4896           int ntparms = TREE_VEC_LENGTH (inner_parms);
4897           int seen_def_arg_p = 0;
4898           int i;
4899
4900           for (i = 0; i < ntparms; ++i)
4901             {
4902               tree parm = TREE_VEC_ELT (inner_parms, i);
4903
4904               if (parm == error_mark_node)
4905                 continue;
4906
4907               if (TREE_PURPOSE (parm))
4908                 seen_def_arg_p = 1;
4909               else if (seen_def_arg_p
4910                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4911                 {
4912                   error ("no default argument for %qD", TREE_VALUE (parm));
4913                   /* For better subsequent error-recovery, we indicate that
4914                      there should have been a default argument.  */
4915                   TREE_PURPOSE (parm) = error_mark_node;
4916                   no_errors = false;
4917                 }
4918               else if (!is_partial
4919                        && !is_friend_decl
4920                        /* Don't complain about an enclosing partial
4921                           specialization.  */
4922                        && parm_level == parms
4923                        && TREE_CODE (decl) == TYPE_DECL
4924                        && i < ntparms - 1
4925                        && template_parameter_pack_p (TREE_VALUE (parm))
4926                        /* A fixed parameter pack will be partially
4927                           instantiated into a fixed length list.  */
4928                        && !fixed_parameter_pack_p (TREE_VALUE (parm)))
4929                 {
4930                   /* A primary class template can only have one
4931                      parameter pack, at the end of the template
4932                      parameter list.  */
4933
4934                   error ("parameter pack %q+D must be at the end of the"
4935                          " template parameter list", TREE_VALUE (parm));
4936
4937                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4938                     = error_mark_node;
4939                   no_errors = false;
4940                 }
4941             }
4942         }
4943     }
4944
4945   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4946       || is_partial 
4947       || !is_primary
4948       || is_friend_decl)
4949     /* For an ordinary class template, default template arguments are
4950        allowed at the innermost level, e.g.:
4951          template <class T = int>
4952          struct S {};
4953        but, in a partial specialization, they're not allowed even
4954        there, as we have in [temp.class.spec]:
4955
4956          The template parameter list of a specialization shall not
4957          contain default template argument values.
4958
4959        So, for a partial specialization, or for a function template
4960        (in C++98/C++03), we look at all of them.  */
4961     ;
4962   else
4963     /* But, for a primary class template that is not a partial
4964        specialization we look at all template parameters except the
4965        innermost ones.  */
4966     parms = TREE_CHAIN (parms);
4967
4968   /* Figure out what error message to issue.  */
4969   if (is_friend_decl == 2)
4970     msg = G_("default template arguments may not be used in function template "
4971              "friend re-declaration");
4972   else if (is_friend_decl)
4973     msg = G_("default template arguments may not be used in function template "
4974              "friend declarations");
4975   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4976     msg = G_("default template arguments may not be used in function templates "
4977              "without -std=c++11 or -std=gnu++11");
4978   else if (is_partial)
4979     msg = G_("default template arguments may not be used in "
4980              "partial specializations");
4981   else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
4982     msg = G_("default argument for template parameter for class enclosing %qD");
4983   else
4984     /* Per [temp.param]/9, "A default template-argument shall not be
4985        specified in the template-parameter-lists of the definition of
4986        a member of a class template that appears outside of the member's
4987        class.", thus if we aren't handling a member of a class template
4988        there is no need to examine the parameters.  */
4989     return true;
4990
4991   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4992     /* If we're inside a class definition, there's no need to
4993        examine the parameters to the class itself.  On the one
4994        hand, they will be checked when the class is defined, and,
4995        on the other, default arguments are valid in things like:
4996          template <class T = double>
4997          struct S { template <class U> void f(U); };
4998        Here the default argument for `S' has no bearing on the
4999        declaration of `f'.  */
5000     last_level_to_check = template_class_depth (current_class_type) + 1;
5001   else
5002     /* Check everything.  */
5003     last_level_to_check = 0;
5004
5005   for (parm_level = parms;
5006        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5007        parm_level = TREE_CHAIN (parm_level))
5008     {
5009       tree inner_parms = TREE_VALUE (parm_level);
5010       int i;
5011       int ntparms;
5012
5013       ntparms = TREE_VEC_LENGTH (inner_parms);
5014       for (i = 0; i < ntparms; ++i)
5015         {
5016           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5017             continue;
5018
5019           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5020             {
5021               if (msg)
5022                 {
5023                   no_errors = false;
5024                   if (is_friend_decl == 2)
5025                     return no_errors;
5026
5027                   error (msg, decl);
5028                   msg = 0;
5029                 }
5030
5031               /* Clear out the default argument so that we are not
5032                  confused later.  */
5033               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5034             }
5035         }
5036
5037       /* At this point, if we're still interested in issuing messages,
5038          they must apply to classes surrounding the object declared.  */
5039       if (msg)
5040         msg = G_("default argument for template parameter for class "
5041                  "enclosing %qD");
5042     }
5043
5044   return no_errors;
5045 }
5046
5047 /* Worker for push_template_decl_real, called via
5048    for_each_template_parm.  DATA is really an int, indicating the
5049    level of the parameters we are interested in.  If T is a template
5050    parameter of that level, return nonzero.  */
5051
5052 static int
5053 template_parm_this_level_p (tree t, void* data)
5054 {
5055   int this_level = *(int *)data;
5056   int level;
5057
5058   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5059     level = TEMPLATE_PARM_LEVEL (t);
5060   else
5061     level = TEMPLATE_TYPE_LEVEL (t);
5062   return level == this_level;
5063 }
5064
5065 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5066    parameters given by current_template_args, or reuses a
5067    previously existing one, if appropriate.  Returns the DECL, or an
5068    equivalent one, if it is replaced via a call to duplicate_decls.
5069
5070    If IS_FRIEND is true, DECL is a friend declaration.  */
5071
5072 tree
5073 push_template_decl_real (tree decl, bool is_friend)
5074 {
5075   tree tmpl;
5076   tree args;
5077   tree info;
5078   tree ctx;
5079   bool is_primary;
5080   bool is_partial;
5081   int new_template_p = 0;
5082   /* True if the template is a member template, in the sense of
5083      [temp.mem].  */
5084   bool member_template_p = false;
5085
5086   if (decl == error_mark_node || !current_template_parms)
5087     return error_mark_node;
5088
5089   /* See if this is a partial specialization.  */
5090   is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5091                  && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5092                  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5093                 || (VAR_P (decl)
5094                     && DECL_LANG_SPECIFIC (decl)
5095                     && DECL_TEMPLATE_SPECIALIZATION (decl)
5096                     && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5097
5098   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
5099     is_friend = true;
5100
5101   if (is_friend)
5102     /* For a friend, we want the context of the friend function, not
5103        the type of which it is a friend.  */
5104     ctx = CP_DECL_CONTEXT (decl);
5105   else if (CP_DECL_CONTEXT (decl)
5106            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5107     /* In the case of a virtual function, we want the class in which
5108        it is defined.  */
5109     ctx = CP_DECL_CONTEXT (decl);
5110   else
5111     /* Otherwise, if we're currently defining some class, the DECL
5112        is assumed to be a member of the class.  */
5113     ctx = current_scope ();
5114
5115   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5116     ctx = NULL_TREE;
5117
5118   if (!DECL_CONTEXT (decl))
5119     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5120
5121   /* See if this is a primary template.  */
5122   if (is_friend && ctx
5123       && uses_template_parms_level (ctx, processing_template_decl))
5124     /* A friend template that specifies a class context, i.e.
5125          template <typename T> friend void A<T>::f();
5126        is not primary.  */
5127     is_primary = false;
5128   else if (TREE_CODE (decl) == TYPE_DECL
5129            && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5130     is_primary = false;
5131   else
5132     is_primary = template_parm_scope_p ();
5133
5134   if (is_primary)
5135     {
5136       warning (OPT_Wtemplates, "template %qD declared", decl);
5137       
5138       if (DECL_CLASS_SCOPE_P (decl))
5139         member_template_p = true;
5140       if (TREE_CODE (decl) == TYPE_DECL
5141           && anon_aggrname_p (DECL_NAME (decl)))
5142         {
5143           error ("template class without a name");
5144           return error_mark_node;
5145         }
5146       else if (TREE_CODE (decl) == FUNCTION_DECL)
5147         {
5148           if (member_template_p)
5149             {
5150               if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5151                 error ("member template %qD may not have virt-specifiers", decl);
5152             }
5153           if (DECL_DESTRUCTOR_P (decl))
5154             {
5155               /* [temp.mem]
5156
5157                  A destructor shall not be a member template.  */
5158               error ("destructor %qD declared as member template", decl);
5159               return error_mark_node;
5160             }
5161           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
5162               && (!prototype_p (TREE_TYPE (decl))
5163                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5164                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5165                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
5166                       == void_list_node)))
5167             {
5168               /* [basic.stc.dynamic.allocation]
5169
5170                  An allocation function can be a function
5171                  template. ... Template allocation functions shall
5172                  have two or more parameters.  */
5173               error ("invalid template declaration of %qD", decl);
5174               return error_mark_node;
5175             }
5176         }
5177       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5178                && CLASS_TYPE_P (TREE_TYPE (decl)))
5179         /* OK */;
5180       else if (TREE_CODE (decl) == TYPE_DECL
5181                && TYPE_DECL_ALIAS_P (decl))
5182         /* alias-declaration */
5183         gcc_assert (!DECL_ARTIFICIAL (decl));
5184       else if (VAR_P (decl))
5185         /* C++14 variable template. */;
5186       else
5187         {
5188           error ("template declaration of %q#D", decl);
5189           return error_mark_node;
5190         }
5191     }
5192
5193   /* Check to see that the rules regarding the use of default
5194      arguments are not being violated.  */
5195   check_default_tmpl_args (decl, current_template_parms,
5196                            is_primary, is_partial, /*is_friend_decl=*/0);
5197
5198   /* Ensure that there are no parameter packs in the type of this
5199      declaration that have not been expanded.  */
5200   if (TREE_CODE (decl) == FUNCTION_DECL)
5201     {
5202       /* Check each of the arguments individually to see if there are
5203          any bare parameter packs.  */
5204       tree type = TREE_TYPE (decl);
5205       tree arg = DECL_ARGUMENTS (decl);
5206       tree argtype = TYPE_ARG_TYPES (type);
5207
5208       while (arg && argtype)
5209         {
5210           if (!DECL_PACK_P (arg)
5211               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5212             {
5213             /* This is a PARM_DECL that contains unexpanded parameter
5214                packs. We have already complained about this in the
5215                check_for_bare_parameter_packs call, so just replace
5216                these types with ERROR_MARK_NODE.  */
5217               TREE_TYPE (arg) = error_mark_node;
5218               TREE_VALUE (argtype) = error_mark_node;
5219             }
5220
5221           arg = DECL_CHAIN (arg);
5222           argtype = TREE_CHAIN (argtype);
5223         }
5224
5225       /* Check for bare parameter packs in the return type and the
5226          exception specifiers.  */
5227       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5228         /* Errors were already issued, set return type to int
5229            as the frontend doesn't expect error_mark_node as
5230            the return type.  */
5231         TREE_TYPE (type) = integer_type_node;
5232       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5233         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5234     }
5235   else if (check_for_bare_parameter_packs ((TREE_CODE (decl) == TYPE_DECL
5236                                             && TYPE_DECL_ALIAS_P (decl))
5237                                            ? DECL_ORIGINAL_TYPE (decl)
5238                                            : TREE_TYPE (decl)))
5239     {
5240       TREE_TYPE (decl) = error_mark_node;
5241       return error_mark_node;
5242     }
5243
5244   if (is_partial)
5245     return process_partial_specialization (decl);
5246
5247   args = current_template_args ();
5248
5249   if (!ctx
5250       || TREE_CODE (ctx) == FUNCTION_DECL
5251       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5252       || (TREE_CODE (decl) == TYPE_DECL
5253           && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5254       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
5255     {
5256       if (DECL_LANG_SPECIFIC (decl)
5257           && DECL_TEMPLATE_INFO (decl)
5258           && DECL_TI_TEMPLATE (decl))
5259         tmpl = DECL_TI_TEMPLATE (decl);
5260       /* If DECL is a TYPE_DECL for a class-template, then there won't
5261          be DECL_LANG_SPECIFIC.  The information equivalent to
5262          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
5263       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5264                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
5265                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
5266         {
5267           /* Since a template declaration already existed for this
5268              class-type, we must be redeclaring it here.  Make sure
5269              that the redeclaration is valid.  */
5270           redeclare_class_template (TREE_TYPE (decl),
5271                                     current_template_parms,
5272                                     current_template_constraints ());
5273           /* We don't need to create a new TEMPLATE_DECL; just use the
5274              one we already had.  */
5275           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
5276         }
5277       else
5278         {
5279           tmpl = build_template_decl (decl, current_template_parms,
5280                                       member_template_p);
5281           new_template_p = 1;
5282
5283           if (DECL_LANG_SPECIFIC (decl)
5284               && DECL_TEMPLATE_SPECIALIZATION (decl))
5285             {
5286               /* A specialization of a member template of a template
5287                  class.  */
5288               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5289               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
5290               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
5291             }
5292         }
5293     }
5294   else
5295     {
5296       tree a, t, current, parms;
5297       int i;
5298       tree tinfo = get_template_info (decl);
5299
5300       if (!tinfo)
5301         {
5302           error ("template definition of non-template %q#D", decl);
5303           return error_mark_node;
5304         }
5305
5306       tmpl = TI_TEMPLATE (tinfo);
5307
5308       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
5309           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
5310           && DECL_TEMPLATE_SPECIALIZATION (decl)
5311           && DECL_MEMBER_TEMPLATE_P (tmpl))
5312         {
5313           tree new_tmpl;
5314
5315           /* The declaration is a specialization of a member
5316              template, declared outside the class.  Therefore, the
5317              innermost template arguments will be NULL, so we
5318              replace them with the arguments determined by the
5319              earlier call to check_explicit_specialization.  */
5320           args = DECL_TI_ARGS (decl);
5321
5322           new_tmpl
5323             = build_template_decl (decl, current_template_parms,
5324                                    member_template_p);
5325           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
5326           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
5327           DECL_TI_TEMPLATE (decl) = new_tmpl;
5328           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
5329           DECL_TEMPLATE_INFO (new_tmpl)
5330             = build_template_info (tmpl, args);
5331
5332           register_specialization (new_tmpl,
5333                                    most_general_template (tmpl),
5334                                    args,
5335                                    is_friend, 0);
5336           return decl;
5337         }
5338
5339       /* Make sure the template headers we got make sense.  */
5340
5341       parms = DECL_TEMPLATE_PARMS (tmpl);
5342       i = TMPL_PARMS_DEPTH (parms);
5343       if (TMPL_ARGS_DEPTH (args) != i)
5344         {
5345           error ("expected %d levels of template parms for %q#D, got %d",
5346                  i, decl, TMPL_ARGS_DEPTH (args));
5347           DECL_INTERFACE_KNOWN (decl) = 1;
5348           return error_mark_node;
5349         }
5350       else
5351         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
5352           {
5353             a = TMPL_ARGS_LEVEL (args, i);
5354             t = INNERMOST_TEMPLATE_PARMS (parms);
5355
5356             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
5357               {
5358                 if (current == decl)
5359                   error ("got %d template parameters for %q#D",
5360                          TREE_VEC_LENGTH (a), decl);
5361                 else
5362                   error ("got %d template parameters for %q#T",
5363                          TREE_VEC_LENGTH (a), current);
5364                 error ("  but %d required", TREE_VEC_LENGTH (t));
5365                 /* Avoid crash in import_export_decl.  */
5366                 DECL_INTERFACE_KNOWN (decl) = 1;
5367                 return error_mark_node;
5368               }
5369
5370             if (current == decl)
5371               current = ctx;
5372             else if (current == NULL_TREE)
5373               /* Can happen in erroneous input.  */
5374               break;
5375             else
5376               current = get_containing_scope (current);
5377           }
5378
5379       /* Check that the parms are used in the appropriate qualifying scopes
5380          in the declarator.  */
5381       if (!comp_template_args
5382           (TI_ARGS (tinfo),
5383            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5384         {
5385           error ("\
5386 template arguments to %qD do not match original template %qD",
5387                  decl, DECL_TEMPLATE_RESULT (tmpl));
5388           if (!uses_template_parms (TI_ARGS (tinfo)))
5389             inform (input_location, "use template<> for an explicit specialization");
5390           /* Avoid crash in import_export_decl.  */
5391           DECL_INTERFACE_KNOWN (decl) = 1;
5392           return error_mark_node;
5393         }
5394     }
5395
5396   DECL_TEMPLATE_RESULT (tmpl) = decl;
5397   TREE_TYPE (tmpl) = TREE_TYPE (decl);
5398
5399   /* Push template declarations for global functions and types.  Note
5400      that we do not try to push a global template friend declared in a
5401      template class; such a thing may well depend on the template
5402      parameters of the class.  */
5403   if (new_template_p && !ctx
5404       && !(is_friend && template_class_depth (current_class_type) > 0))
5405     {
5406       tmpl = pushdecl_namespace_level (tmpl, is_friend);
5407       if (tmpl == error_mark_node)
5408         return error_mark_node;
5409
5410       /* Hide template friend classes that haven't been declared yet.  */
5411       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
5412         {
5413           DECL_ANTICIPATED (tmpl) = 1;
5414           DECL_FRIEND_P (tmpl) = 1;
5415         }
5416     }
5417
5418   if (is_primary)
5419     {
5420       tree parms = DECL_TEMPLATE_PARMS (tmpl);
5421       int i;
5422
5423       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5424       if (DECL_CONV_FN_P (tmpl))
5425         {
5426           int depth = TMPL_PARMS_DEPTH (parms);
5427
5428           /* It is a conversion operator. See if the type converted to
5429              depends on innermost template operands.  */
5430
5431           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
5432                                          depth))
5433             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
5434         }
5435
5436       /* Give template template parms a DECL_CONTEXT of the template
5437          for which they are a parameter.  */
5438       parms = INNERMOST_TEMPLATE_PARMS (parms);
5439       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5440         {
5441           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5442           if (TREE_CODE (parm) == TEMPLATE_DECL)
5443             DECL_CONTEXT (parm) = tmpl;
5444         }
5445
5446       if (TREE_CODE (decl) == TYPE_DECL
5447           && TYPE_DECL_ALIAS_P (decl)
5448           && complex_alias_template_p (tmpl))
5449         TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
5450     }
5451
5452   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5453      back to its most general template.  If TMPL is a specialization,
5454      ARGS may only have the innermost set of arguments.  Add the missing
5455      argument levels if necessary.  */
5456   if (DECL_TEMPLATE_INFO (tmpl))
5457     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5458
5459   info = build_template_info (tmpl, args);
5460
5461   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5462     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5463   else
5464     {
5465       if (is_primary && !DECL_LANG_SPECIFIC (decl))
5466         retrofit_lang_decl (decl);
5467       if (DECL_LANG_SPECIFIC (decl))
5468         DECL_TEMPLATE_INFO (decl) = info;
5469     }
5470
5471   if (flag_implicit_templates
5472       && !is_friend
5473       && TREE_PUBLIC (decl)
5474       && VAR_OR_FUNCTION_DECL_P (decl))
5475     /* Set DECL_COMDAT on template instantiations; if we force
5476        them to be emitted by explicit instantiation or -frepo,
5477        mark_needed will tell cgraph to do the right thing.  */
5478     DECL_COMDAT (decl) = true;
5479
5480   return DECL_TEMPLATE_RESULT (tmpl);
5481 }
5482
5483 tree
5484 push_template_decl (tree decl)
5485 {
5486   return push_template_decl_real (decl, false);
5487 }
5488
5489 /* FN is an inheriting constructor that inherits from the constructor
5490    template INHERITED; turn FN into a constructor template with a matching
5491    template header.  */
5492
5493 tree
5494 add_inherited_template_parms (tree fn, tree inherited)
5495 {
5496   tree inner_parms
5497     = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
5498   inner_parms = copy_node (inner_parms);
5499   tree parms
5500     = tree_cons (size_int (processing_template_decl + 1),
5501                  inner_parms, current_template_parms);
5502   tree tmpl = build_template_decl (fn, parms, /*member*/true);
5503   tree args = template_parms_to_args (parms);
5504   DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
5505   TREE_TYPE (tmpl) = TREE_TYPE (fn);
5506   DECL_TEMPLATE_RESULT (tmpl) = fn;
5507   DECL_ARTIFICIAL (tmpl) = true;
5508   DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5509   return tmpl;
5510 }
5511
5512 /* Called when a class template TYPE is redeclared with the indicated
5513    template PARMS, e.g.:
5514
5515      template <class T> struct S;
5516      template <class T> struct S {};  */
5517
5518 bool
5519 redeclare_class_template (tree type, tree parms, tree cons)
5520 {
5521   tree tmpl;
5522   tree tmpl_parms;
5523   int i;
5524
5525   if (!TYPE_TEMPLATE_INFO (type))
5526     {
5527       error ("%qT is not a template type", type);
5528       return false;
5529     }
5530
5531   tmpl = TYPE_TI_TEMPLATE (type);
5532   if (!PRIMARY_TEMPLATE_P (tmpl))
5533     /* The type is nested in some template class.  Nothing to worry
5534        about here; there are no new template parameters for the nested
5535        type.  */
5536     return true;
5537
5538   if (!parms)
5539     {
5540       error ("template specifiers not specified in declaration of %qD",
5541              tmpl);
5542       return false;
5543     }
5544
5545   parms = INNERMOST_TEMPLATE_PARMS (parms);
5546   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5547
5548   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5549     {
5550       error_n (input_location, TREE_VEC_LENGTH (parms),
5551                "redeclared with %d template parameter",
5552                "redeclared with %d template parameters",
5553                TREE_VEC_LENGTH (parms));
5554       inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
5555                 "previous declaration %qD used %d template parameter",
5556                 "previous declaration %qD used %d template parameters",
5557                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5558       return false;
5559     }
5560
5561   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5562     {
5563       tree tmpl_parm;
5564       tree parm;
5565       tree tmpl_default;
5566       tree parm_default;
5567
5568       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5569           || TREE_VEC_ELT (parms, i) == error_mark_node)
5570         continue;
5571
5572       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5573       if (error_operand_p (tmpl_parm))
5574         return false;
5575
5576       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5577       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5578       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5579
5580       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5581          TEMPLATE_DECL.  */
5582       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5583           || (TREE_CODE (tmpl_parm) != TYPE_DECL
5584               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5585           || (TREE_CODE (tmpl_parm) != PARM_DECL
5586               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5587                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5588           || (TREE_CODE (tmpl_parm) == PARM_DECL
5589               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5590                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5591         {
5592           error ("template parameter %q+#D", tmpl_parm);
5593           error ("redeclared here as %q#D", parm);
5594           return false;
5595         }
5596
5597       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5598         {
5599           /* We have in [temp.param]:
5600
5601              A template-parameter may not be given default arguments
5602              by two different declarations in the same scope.  */
5603           error_at (input_location, "redefinition of default argument for %q#D", parm);
5604           inform (DECL_SOURCE_LOCATION (tmpl_parm),
5605                   "original definition appeared here");
5606           return false;
5607         }
5608
5609       if (parm_default != NULL_TREE)
5610         /* Update the previous template parameters (which are the ones
5611            that will really count) with the new default value.  */
5612         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5613       else if (tmpl_default != NULL_TREE)
5614         /* Update the new parameters, too; they'll be used as the
5615            parameters for any members.  */
5616         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5617
5618       /* Give each template template parm in this redeclaration a
5619          DECL_CONTEXT of the template for which they are a parameter.  */
5620       if (TREE_CODE (parm) == TEMPLATE_DECL)
5621         {
5622           gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
5623           DECL_CONTEXT (parm) = tmpl;
5624         }
5625     }
5626
5627   // Cannot redeclare a class template with a different set of constraints.
5628   if (!equivalent_constraints (get_constraints (tmpl), cons))
5629     {
5630       error_at (input_location, "redeclaration %q#D with different "
5631                                 "constraints", tmpl);
5632       inform (DECL_SOURCE_LOCATION (tmpl),
5633               "original declaration appeared here");
5634     }
5635
5636     return true;
5637 }
5638
5639 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
5640    to be used when the caller has already checked
5641    (processing_template_decl
5642     && !instantiation_dependent_expression_p (expr)
5643     && potential_constant_expression (expr))
5644    and cleared processing_template_decl.  */
5645
5646 tree
5647 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
5648 {
5649   return tsubst_copy_and_build (expr,
5650                                 /*args=*/NULL_TREE,
5651                                 complain,
5652                                 /*in_decl=*/NULL_TREE,
5653                                 /*function_p=*/false,
5654                                 /*integral_constant_expression_p=*/true);
5655 }
5656
5657 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5658    (possibly simplified) expression.  */
5659
5660 tree
5661 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5662 {
5663   if (expr == NULL_TREE)
5664     return NULL_TREE;
5665
5666   /* If we're in a template, but EXPR isn't value dependent, simplify
5667      it.  We're supposed to treat:
5668
5669        template <typename T> void f(T[1 + 1]);
5670        template <typename T> void f(T[2]);
5671
5672      as two declarations of the same function, for example.  */
5673   if (processing_template_decl
5674       && potential_nondependent_constant_expression (expr))
5675     {
5676       processing_template_decl_sentinel s;
5677       expr = instantiate_non_dependent_expr_internal (expr, complain);
5678     }
5679   return expr;
5680 }
5681
5682 tree
5683 instantiate_non_dependent_expr (tree expr)
5684 {
5685   return instantiate_non_dependent_expr_sfinae (expr, tf_error);
5686 }
5687
5688 /* Like instantiate_non_dependent_expr, but return NULL_TREE rather than
5689    an uninstantiated expression.  */
5690
5691 tree
5692 instantiate_non_dependent_or_null (tree expr)
5693 {
5694   if (expr == NULL_TREE)
5695     return NULL_TREE;
5696   if (processing_template_decl)
5697     {
5698       if (!potential_nondependent_constant_expression (expr))
5699         expr = NULL_TREE;
5700       else
5701         {
5702           processing_template_decl_sentinel s;
5703           expr = instantiate_non_dependent_expr_internal (expr, tf_error);
5704         }
5705     }
5706   return expr;
5707 }
5708
5709 /* True iff T is a specialization of a variable template.  */
5710
5711 bool
5712 variable_template_specialization_p (tree t)
5713 {
5714   if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
5715     return false;
5716   tree tmpl = DECL_TI_TEMPLATE (t);
5717   return variable_template_p (tmpl);
5718 }
5719
5720 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
5721    template declaration, or a TYPE_DECL for an alias declaration.  */
5722
5723 bool
5724 alias_type_or_template_p (tree t)
5725 {
5726   if (t == NULL_TREE)
5727     return false;
5728   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
5729           || (TYPE_P (t)
5730               && TYPE_NAME (t)
5731               && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
5732           || DECL_ALIAS_TEMPLATE_P (t));
5733 }
5734
5735 /* Return TRUE iff T is a specialization of an alias template.  */
5736
5737 bool
5738 alias_template_specialization_p (const_tree t)
5739 {
5740   /* It's an alias template specialization if it's an alias and its
5741      TYPE_NAME is a specialization of a primary template.  */
5742   if (TYPE_ALIAS_P (t))
5743     {
5744       tree name = TYPE_NAME (t);
5745       if (DECL_LANG_SPECIFIC (name))
5746         if (tree ti = DECL_TEMPLATE_INFO (name))
5747           {
5748             tree tmpl = TI_TEMPLATE (ti);
5749             return PRIMARY_TEMPLATE_P (tmpl);
5750           }
5751     }
5752   return false;
5753 }
5754
5755 /* An alias template is complex from a SFINAE perspective if a template-id
5756    using that alias can be ill-formed when the expansion is not, as with
5757    the void_t template.  We determine this by checking whether the
5758    expansion for the alias template uses all its template parameters.  */
5759
5760 struct uses_all_template_parms_data
5761 {
5762   int level;
5763   bool *seen;
5764 };
5765
5766 static int
5767 uses_all_template_parms_r (tree t, void *data_)
5768 {
5769   struct uses_all_template_parms_data &data
5770     = *(struct uses_all_template_parms_data*)data_;
5771   tree idx = get_template_parm_index (t);
5772
5773   if (TEMPLATE_PARM_LEVEL (idx) == data.level)
5774     data.seen[TEMPLATE_PARM_IDX (idx)] = true;
5775   return 0;
5776 }
5777
5778 static bool
5779 complex_alias_template_p (const_tree tmpl)
5780 {
5781   struct uses_all_template_parms_data data;
5782   tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
5783   tree parms = DECL_TEMPLATE_PARMS (tmpl);
5784   data.level = TMPL_PARMS_DEPTH (parms);
5785   int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
5786   data.seen = XALLOCAVEC (bool, len);
5787   for (int i = 0; i < len; ++i)
5788     data.seen[i] = false;
5789
5790   for_each_template_parm (pat, uses_all_template_parms_r, &data, NULL, true);
5791   for (int i = 0; i < len; ++i)
5792     if (!data.seen[i])
5793       return true;
5794   return false;
5795 }
5796
5797 /* Return TRUE iff T is a specialization of a complex alias template with
5798    dependent template-arguments.  */
5799
5800 bool
5801 dependent_alias_template_spec_p (const_tree t)
5802 {
5803   return (alias_template_specialization_p (t)
5804           && TEMPLATE_DECL_COMPLEX_ALIAS_P (DECL_TI_TEMPLATE (TYPE_NAME (t)))
5805           && (any_dependent_template_arguments_p
5806               (INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (t)))));
5807 }
5808
5809 /* Return the number of innermost template parameters in TMPL.  */
5810
5811 static int
5812 num_innermost_template_parms (tree tmpl)
5813 {
5814   tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
5815   return TREE_VEC_LENGTH (parms);
5816 }
5817
5818 /* Return either TMPL or another template that it is equivalent to under DR
5819    1286: An alias that just changes the name of a template is equivalent to
5820    the other template.  */
5821
5822 static tree
5823 get_underlying_template (tree tmpl)
5824 {
5825   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
5826   while (DECL_ALIAS_TEMPLATE_P (tmpl))
5827     {
5828       tree result = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
5829       if (TYPE_TEMPLATE_INFO (result))
5830         {
5831           tree sub = TYPE_TI_TEMPLATE (result);
5832           if (PRIMARY_TEMPLATE_P (sub)
5833               && (num_innermost_template_parms (tmpl)
5834                   == num_innermost_template_parms (sub)))
5835             {
5836               tree alias_args = INNERMOST_TEMPLATE_ARGS
5837                 (template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl)));
5838               if (!comp_template_args (TYPE_TI_ARGS (result), alias_args))
5839                 break;
5840               /* The alias type is equivalent to the pattern of the
5841                  underlying template, so strip the alias.  */
5842               tmpl = sub;
5843               continue;
5844             }
5845         }
5846       break;
5847     }
5848   return tmpl;
5849 }
5850
5851 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5852    must be a function or a pointer-to-function type, as specified
5853    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5854    and check that the resulting function has external linkage.  */
5855
5856 static tree
5857 convert_nontype_argument_function (tree type, tree expr,
5858                                    tsubst_flags_t complain)
5859 {
5860   tree fns = expr;
5861   tree fn, fn_no_ptr;
5862   linkage_kind linkage;
5863
5864   fn = instantiate_type (type, fns, tf_none);
5865   if (fn == error_mark_node)
5866     return error_mark_node;
5867
5868   fn_no_ptr = fn;
5869   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5870     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5871   if (BASELINK_P (fn_no_ptr))
5872     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5873  
5874   /* [temp.arg.nontype]/1
5875
5876      A template-argument for a non-type, non-template template-parameter
5877      shall be one of:
5878      [...]
5879      -- the address of an object or function with external [C++11: or
5880         internal] linkage.  */
5881
5882   if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
5883     {
5884       if (complain & tf_error)
5885         {
5886           error ("%qE is not a valid template argument for type %qT",
5887                  expr, type);
5888           if (TYPE_PTR_P (type))
5889             error ("it must be the address of a function with "
5890                    "external linkage");
5891           else
5892             error ("it must be the name of a function with "
5893                    "external linkage");
5894         }
5895       return NULL_TREE;
5896     }
5897
5898   linkage = decl_linkage (fn_no_ptr);
5899   if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
5900     {
5901       if (complain & tf_error)
5902         {
5903           if (cxx_dialect >= cxx11)
5904             error ("%qE is not a valid template argument for type %qT "
5905                    "because %qD has no linkage",
5906                    expr, type, fn_no_ptr);
5907           else
5908             error ("%qE is not a valid template argument for type %qT "
5909                    "because %qD does not have external linkage",
5910                    expr, type, fn_no_ptr);
5911         }
5912       return NULL_TREE;
5913     }
5914
5915   return fn;
5916 }
5917
5918 /* Subroutine of convert_nontype_argument.
5919    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5920    Emit an error otherwise.  */
5921
5922 static bool
5923 check_valid_ptrmem_cst_expr (tree type, tree expr,
5924                              tsubst_flags_t complain)
5925 {
5926   STRIP_NOPS (expr);
5927   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5928     return true;
5929   if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
5930     return true;
5931   if (processing_template_decl
5932       && TREE_CODE (expr) == ADDR_EXPR
5933       && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
5934     return true;
5935   if (complain & tf_error)
5936     {
5937       error ("%qE is not a valid template argument for type %qT",
5938              expr, type);
5939       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5940     }
5941   return false;
5942 }
5943
5944 /* Returns TRUE iff the address of OP is value-dependent.
5945
5946    14.6.2.4 [temp.dep.temp]:
5947    A non-integral non-type template-argument is dependent if its type is
5948    dependent or it has either of the following forms
5949      qualified-id
5950      & qualified-id
5951    and contains a nested-name-specifier which specifies a class-name that
5952    names a dependent type.
5953
5954    We generalize this to just say that the address of a member of a
5955    dependent class is value-dependent; the above doesn't cover the
5956    address of a static data member named with an unqualified-id.  */
5957
5958 static bool
5959 has_value_dependent_address (tree op)
5960 {
5961   /* We could use get_inner_reference here, but there's no need;
5962      this is only relevant for template non-type arguments, which
5963      can only be expressed as &id-expression.  */
5964   if (DECL_P (op))
5965     {
5966       tree ctx = CP_DECL_CONTEXT (op);
5967       if (TYPE_P (ctx) && dependent_type_p (ctx))
5968         return true;
5969     }
5970
5971   return false;
5972 }
5973
5974 /* The next set of functions are used for providing helpful explanatory
5975    diagnostics for failed overload resolution.  Their messages should be
5976    indented by two spaces for consistency with the messages in
5977    call.c  */
5978
5979 static int
5980 unify_success (bool /*explain_p*/)
5981 {
5982   return 0;
5983 }
5984
5985 static int
5986 unify_parameter_deduction_failure (bool explain_p, tree parm)
5987 {
5988   if (explain_p)
5989     inform (input_location,
5990             "  couldn't deduce template parameter %qD", parm);
5991   return 1;
5992 }
5993
5994 static int
5995 unify_invalid (bool /*explain_p*/)
5996 {
5997   return 1;
5998 }
5999
6000 static int
6001 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6002 {
6003   if (explain_p)
6004     inform (input_location,
6005             "  types %qT and %qT have incompatible cv-qualifiers",
6006             parm, arg);
6007   return 1;
6008 }
6009
6010 static int
6011 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6012 {
6013   if (explain_p)
6014     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
6015   return 1;
6016 }
6017
6018 static int
6019 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6020 {
6021   if (explain_p)
6022     inform (input_location,
6023             "  template parameter %qD is not a parameter pack, but "
6024             "argument %qD is",
6025             parm, arg);
6026   return 1;
6027 }
6028
6029 static int
6030 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6031 {
6032   if (explain_p)
6033     inform (input_location,
6034             "  template argument %qE does not match "
6035             "pointer-to-member constant %qE",
6036             arg, parm);
6037   return 1;
6038 }
6039
6040 static int
6041 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6042 {
6043   if (explain_p)
6044     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
6045   return 1;
6046 }
6047
6048 static int
6049 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6050 {
6051   if (explain_p)
6052     inform (input_location,
6053             "  inconsistent parameter pack deduction with %qT and %qT",
6054             old_arg, new_arg);
6055   return 1;
6056 }
6057
6058 static int
6059 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6060 {
6061   if (explain_p)
6062     {
6063       if (TYPE_P (parm))
6064         inform (input_location,
6065                 "  deduced conflicting types for parameter %qT (%qT and %qT)",
6066                 parm, first, second);
6067       else
6068         inform (input_location,
6069                 "  deduced conflicting values for non-type parameter "
6070                 "%qE (%qE and %qE)", parm, first, second);
6071     }
6072   return 1;
6073 }
6074
6075 static int
6076 unify_vla_arg (bool explain_p, tree arg)
6077 {
6078   if (explain_p)
6079     inform (input_location,
6080             "  variable-sized array type %qT is not "
6081             "a valid template argument",
6082             arg);
6083   return 1;
6084 }
6085
6086 static int
6087 unify_method_type_error (bool explain_p, tree arg)
6088 {
6089   if (explain_p)
6090     inform (input_location,
6091             "  member function type %qT is not a valid template argument",
6092             arg);
6093   return 1;
6094 }
6095
6096 static int
6097 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6098 {
6099   if (explain_p)
6100     {
6101       if (least_p)
6102         inform_n (input_location, wanted,
6103                   "  candidate expects at least %d argument, %d provided",
6104                   "  candidate expects at least %d arguments, %d provided",
6105                   wanted, have);
6106       else
6107         inform_n (input_location, wanted,
6108                   "  candidate expects %d argument, %d provided",
6109                   "  candidate expects %d arguments, %d provided",
6110                   wanted, have);
6111     }
6112   return 1;
6113 }
6114
6115 static int
6116 unify_too_many_arguments (bool explain_p, int have, int wanted)
6117 {
6118   return unify_arity (explain_p, have, wanted);
6119 }
6120
6121 static int
6122 unify_too_few_arguments (bool explain_p, int have, int wanted,
6123                          bool least_p = false)
6124 {
6125   return unify_arity (explain_p, have, wanted, least_p);
6126 }
6127
6128 static int
6129 unify_arg_conversion (bool explain_p, tree to_type,
6130                       tree from_type, tree arg)
6131 {
6132   if (explain_p)
6133     inform (EXPR_LOC_OR_LOC (arg, input_location),
6134             "  cannot convert %qE (type %qT) to type %qT",
6135             arg, from_type, to_type);
6136   return 1;
6137 }
6138
6139 static int
6140 unify_no_common_base (bool explain_p, enum template_base_result r,
6141                       tree parm, tree arg)
6142 {
6143   if (explain_p)
6144     switch (r)
6145       {
6146       case tbr_ambiguous_baseclass:
6147         inform (input_location, "  %qT is an ambiguous base class of %qT",
6148                 parm, arg);
6149         break;
6150       default:
6151         inform (input_location, "  %qT is not derived from %qT", arg, parm);
6152         break;
6153       }
6154   return 1;
6155 }
6156
6157 static int
6158 unify_inconsistent_template_template_parameters (bool explain_p)
6159 {
6160   if (explain_p)
6161     inform (input_location,
6162             "  template parameters of a template template argument are "
6163             "inconsistent with other deduced template arguments");
6164   return 1;
6165 }
6166
6167 static int
6168 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
6169 {
6170   if (explain_p)
6171     inform (input_location,
6172             "  can't deduce a template for %qT from non-template type %qT",
6173             parm, arg);
6174   return 1;
6175 }
6176
6177 static int
6178 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
6179 {
6180   if (explain_p)
6181     inform (input_location,
6182             "  template argument %qE does not match %qD", arg, parm);
6183   return 1;
6184 }
6185
6186 static int
6187 unify_overload_resolution_failure (bool explain_p, tree arg)
6188 {
6189   if (explain_p)
6190     inform (input_location,
6191             "  could not resolve address from overloaded function %qE",
6192             arg);
6193   return 1;
6194 }
6195
6196 /* Attempt to convert the non-type template parameter EXPR to the
6197    indicated TYPE.  If the conversion is successful, return the
6198    converted value.  If the conversion is unsuccessful, return
6199    NULL_TREE if we issued an error message, or error_mark_node if we
6200    did not.  We issue error messages for out-and-out bad template
6201    parameters, but not simply because the conversion failed, since we
6202    might be just trying to do argument deduction.  Both TYPE and EXPR
6203    must be non-dependent.
6204
6205    The conversion follows the special rules described in
6206    [temp.arg.nontype], and it is much more strict than an implicit
6207    conversion.
6208
6209    This function is called twice for each template argument (see
6210    lookup_template_class for a more accurate description of this
6211    problem). This means that we need to handle expressions which
6212    are not valid in a C++ source, but can be created from the
6213    first call (for instance, casts to perform conversions). These
6214    hacks can go away after we fix the double coercion problem.  */
6215
6216 static tree
6217 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
6218 {
6219   tree expr_type;
6220
6221   /* Detect immediately string literals as invalid non-type argument.
6222      This special-case is not needed for correctness (we would easily
6223      catch this later), but only to provide better diagnostic for this
6224      common user mistake. As suggested by DR 100, we do not mention
6225      linkage issues in the diagnostic as this is not the point.  */
6226   /* FIXME we're making this OK.  */
6227   if (TREE_CODE (expr) == STRING_CST)
6228     {
6229       if (complain & tf_error)
6230         error ("%qE is not a valid template argument for type %qT "
6231                "because string literals can never be used in this context",
6232                expr, type);
6233       return NULL_TREE;
6234     }
6235
6236   /* Add the ADDR_EXPR now for the benefit of
6237      value_dependent_expression_p.  */
6238   if (TYPE_PTROBV_P (type)
6239       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
6240     {
6241       expr = decay_conversion (expr, complain);
6242       if (expr == error_mark_node)
6243         return error_mark_node;
6244     }
6245
6246   /* If we are in a template, EXPR may be non-dependent, but still
6247      have a syntactic, rather than semantic, form.  For example, EXPR
6248      might be a SCOPE_REF, rather than the VAR_DECL to which the
6249      SCOPE_REF refers.  Preserving the qualifying scope is necessary
6250      so that access checking can be performed when the template is
6251      instantiated -- but here we need the resolved form so that we can
6252      convert the argument.  */
6253   bool non_dep = false;
6254   if (TYPE_REF_OBJ_P (type)
6255       && has_value_dependent_address (expr))
6256     /* If we want the address and it's value-dependent, don't fold.  */;
6257   else if (processing_template_decl
6258            && potential_nondependent_constant_expression (expr))
6259     non_dep = true;
6260   if (error_operand_p (expr))
6261     return error_mark_node;
6262   expr_type = TREE_TYPE (expr);
6263   if (TREE_CODE (type) == REFERENCE_TYPE)
6264     expr = mark_lvalue_use (expr);
6265   else
6266     expr = mark_rvalue_use (expr);
6267
6268   /* If the argument is non-dependent, perform any conversions in
6269      non-dependent context as well.  */
6270   processing_template_decl_sentinel s (non_dep);
6271   if (non_dep)
6272     expr = instantiate_non_dependent_expr_internal (expr, complain);
6273
6274   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
6275      to a non-type argument of "nullptr".  */
6276   if (expr == nullptr_node && TYPE_PTR_OR_PTRMEM_P (type))
6277     expr = fold_simple (convert (type, expr));
6278
6279   /* In C++11, integral or enumeration non-type template arguments can be
6280      arbitrary constant expressions.  Pointer and pointer to
6281      member arguments can be general constant expressions that evaluate
6282      to a null value, but otherwise still need to be of a specific form.  */
6283   if (cxx_dialect >= cxx11)
6284     {
6285       if (TREE_CODE (expr) == PTRMEM_CST)
6286         /* A PTRMEM_CST is already constant, and a valid template
6287            argument for a parameter of pointer to member type, we just want
6288            to leave it in that form rather than lower it to a
6289            CONSTRUCTOR.  */;
6290       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
6291         expr = maybe_constant_value (expr);
6292       else if (cxx_dialect >= cxx1z)
6293         {
6294           if (TREE_CODE (type) != REFERENCE_TYPE)
6295             expr = maybe_constant_value (expr);
6296           else if (REFERENCE_REF_P (expr))
6297             {
6298               expr = TREE_OPERAND (expr, 0);
6299               expr = maybe_constant_value (expr);
6300               expr = convert_from_reference (expr);
6301             }
6302         }
6303       else if (TYPE_PTR_OR_PTRMEM_P (type))
6304         {
6305           tree folded = maybe_constant_value (expr);
6306           if (TYPE_PTR_P (type) ? integer_zerop (folded)
6307               : null_member_pointer_value_p (folded))
6308             expr = folded;
6309         }
6310     }
6311
6312   /* HACK: Due to double coercion, we can get a
6313      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
6314      which is the tree that we built on the first call (see
6315      below when coercing to reference to object or to reference to
6316      function). We just strip everything and get to the arg.
6317      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
6318      for examples.  */
6319   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
6320     {
6321       tree probe_type, probe = expr;
6322       if (REFERENCE_REF_P (probe))
6323         probe = TREE_OPERAND (probe, 0);
6324       probe_type = TREE_TYPE (probe);
6325       if (TREE_CODE (probe) == NOP_EXPR)
6326         {
6327           /* ??? Maybe we could use convert_from_reference here, but we
6328              would need to relax its constraints because the NOP_EXPR
6329              could actually change the type to something more cv-qualified,
6330              and this is not folded by convert_from_reference.  */
6331           tree addr = TREE_OPERAND (probe, 0);
6332           if (TREE_CODE (probe_type) == REFERENCE_TYPE
6333               && TREE_CODE (addr) == ADDR_EXPR
6334               && TYPE_PTR_P (TREE_TYPE (addr))
6335               && (same_type_ignoring_top_level_qualifiers_p
6336                   (TREE_TYPE (probe_type),
6337                    TREE_TYPE (TREE_TYPE (addr)))))
6338             {
6339               expr = TREE_OPERAND (addr, 0);
6340               expr_type = TREE_TYPE (probe_type);
6341             }
6342         }
6343     }
6344
6345   /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
6346      parameter is a pointer to object, through decay and
6347      qualification conversion. Let's strip everything.  */
6348   else if (TREE_CODE (expr) == NOP_EXPR && TYPE_PTROBV_P (type))
6349     {
6350       tree probe = expr;
6351       STRIP_NOPS (probe);
6352       if (TREE_CODE (probe) == ADDR_EXPR
6353           && TYPE_PTR_P (TREE_TYPE (probe)))
6354         {
6355           /* Skip the ADDR_EXPR only if it is part of the decay for
6356              an array. Otherwise, it is part of the original argument
6357              in the source code.  */
6358           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (probe, 0))) == ARRAY_TYPE)
6359             probe = TREE_OPERAND (probe, 0);
6360           expr = probe;
6361           expr_type = TREE_TYPE (expr);
6362         }
6363     }
6364
6365   /* [temp.arg.nontype]/5, bullet 1
6366
6367      For a non-type template-parameter of integral or enumeration type,
6368      integral promotions (_conv.prom_) and integral conversions
6369      (_conv.integral_) are applied.  */
6370   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
6371     {
6372       tree t = build_integral_nontype_arg_conv (type, expr, complain);
6373       t = maybe_constant_value (t);
6374       if (t != error_mark_node)
6375         expr = t;
6376
6377       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
6378         return error_mark_node;
6379
6380       /* Notice that there are constant expressions like '4 % 0' which
6381          do not fold into integer constants.  */
6382       if (TREE_CODE (expr) != INTEGER_CST)
6383         {
6384           if (complain & tf_error)
6385             {
6386               int errs = errorcount, warns = warningcount + werrorcount;
6387               if (processing_template_decl
6388                   && !require_potential_constant_expression (expr))
6389                 return NULL_TREE;
6390               expr = cxx_constant_value (expr);
6391               if (errorcount > errs || warningcount + werrorcount > warns)
6392                 inform (EXPR_LOC_OR_LOC (expr, input_location),
6393                         "in template argument for type %qT ", type);
6394               if (expr == error_mark_node)
6395                 return NULL_TREE;
6396               /* else cxx_constant_value complained but gave us
6397                  a real constant, so go ahead.  */
6398               gcc_assert (TREE_CODE (expr) == INTEGER_CST);
6399             }
6400           else
6401             return NULL_TREE;
6402         }
6403
6404       /* Avoid typedef problems.  */
6405       if (TREE_TYPE (expr) != type)
6406         expr = fold_convert (type, expr);
6407     }
6408   /* [temp.arg.nontype]/5, bullet 2
6409
6410      For a non-type template-parameter of type pointer to object,
6411      qualification conversions (_conv.qual_) and the array-to-pointer
6412      conversion (_conv.array_) are applied.  */
6413   else if (TYPE_PTROBV_P (type))
6414     {
6415       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
6416
6417          A template-argument for a non-type, non-template template-parameter
6418          shall be one of: [...]
6419
6420          -- the name of a non-type template-parameter;
6421          -- the address of an object or function with external linkage, [...]
6422             expressed as "& id-expression" where the & is optional if the name
6423             refers to a function or array, or if the corresponding
6424             template-parameter is a reference.
6425
6426         Here, we do not care about functions, as they are invalid anyway
6427         for a parameter of type pointer-to-object.  */
6428
6429       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
6430         /* Non-type template parameters are OK.  */
6431         ;
6432       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
6433         /* Null pointer values are OK in C++11.  */;
6434       else if (TREE_CODE (expr) != ADDR_EXPR
6435                && TREE_CODE (expr_type) != ARRAY_TYPE)
6436         {
6437           if (VAR_P (expr))
6438             {
6439               if (complain & tf_error)
6440                 error ("%qD is not a valid template argument "
6441                        "because %qD is a variable, not the address of "
6442                        "a variable", expr, expr);
6443               return NULL_TREE;
6444             }
6445           if (POINTER_TYPE_P (expr_type))
6446             {
6447               if (complain & tf_error)
6448                 error ("%qE is not a valid template argument for %qT "
6449                        "because it is not the address of a variable",
6450                        expr, type);
6451               return NULL_TREE;
6452             }
6453           /* Other values, like integer constants, might be valid
6454              non-type arguments of some other type.  */
6455           return error_mark_node;
6456         }
6457       else
6458         {
6459           tree decl;
6460
6461           decl = ((TREE_CODE (expr) == ADDR_EXPR)
6462                   ? TREE_OPERAND (expr, 0) : expr);
6463           if (!VAR_P (decl))
6464             {
6465               if (complain & tf_error)
6466                 error ("%qE is not a valid template argument of type %qT "
6467                        "because %qE is not a variable", expr, type, decl);
6468               return NULL_TREE;
6469             }
6470           else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
6471             {
6472               if (complain & tf_error)
6473                 error ("%qE is not a valid template argument of type %qT "
6474                        "because %qD does not have external linkage",
6475                        expr, type, decl);
6476               return NULL_TREE;
6477             }
6478           else if (cxx_dialect >= cxx11 && decl_linkage (decl) == lk_none)
6479             {
6480               if (complain & tf_error)
6481                 error ("%qE is not a valid template argument of type %qT "
6482                        "because %qD has no linkage", expr, type, decl);
6483               return NULL_TREE;
6484             }
6485         }
6486
6487       expr = decay_conversion (expr, complain);
6488       if (expr == error_mark_node)
6489         return error_mark_node;
6490
6491       expr = perform_qualification_conversions (type, expr);
6492       if (expr == error_mark_node)
6493         return error_mark_node;
6494     }
6495   /* [temp.arg.nontype]/5, bullet 3
6496
6497      For a non-type template-parameter of type reference to object, no
6498      conversions apply. The type referred to by the reference may be more
6499      cv-qualified than the (otherwise identical) type of the
6500      template-argument. The template-parameter is bound directly to the
6501      template-argument, which must be an lvalue.  */
6502   else if (TYPE_REF_OBJ_P (type))
6503     {
6504       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
6505                                                       expr_type))
6506         return error_mark_node;
6507
6508       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
6509         {
6510           if (complain & tf_error)
6511             error ("%qE is not a valid template argument for type %qT "
6512                    "because of conflicts in cv-qualification", expr, type);
6513           return NULL_TREE;
6514         }
6515
6516       if (!real_lvalue_p (expr))
6517         {
6518           if (complain & tf_error)
6519             error ("%qE is not a valid template argument for type %qT "
6520                    "because it is not an lvalue", expr, type);
6521           return NULL_TREE;
6522         }
6523
6524       /* [temp.arg.nontype]/1
6525
6526          A template-argument for a non-type, non-template template-parameter
6527          shall be one of: [...]
6528
6529          -- the address of an object or function with external linkage.  */
6530       if (INDIRECT_REF_P (expr)
6531           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
6532         {
6533           expr = TREE_OPERAND (expr, 0);
6534           if (DECL_P (expr))
6535             {
6536               if (complain & tf_error)
6537                 error ("%q#D is not a valid template argument for type %qT "
6538                        "because a reference variable does not have a constant "
6539                        "address", expr, type);
6540               return NULL_TREE;
6541             }
6542         }
6543
6544       if (!DECL_P (expr))
6545         {
6546           if (complain & tf_error)
6547             error ("%qE is not a valid template argument for type %qT "
6548                    "because it is not an object with linkage",
6549                    expr, type);
6550           return NULL_TREE;
6551         }
6552
6553       /* DR 1155 allows internal linkage in C++11 and up.  */
6554       linkage_kind linkage = decl_linkage (expr);
6555       if (linkage < (cxx_dialect >= cxx11 ? lk_internal : lk_external))
6556         {
6557           if (complain & tf_error)
6558             error ("%qE is not a valid template argument for type %qT "
6559                    "because object %qD does not have linkage",
6560                    expr, type, expr);
6561           return NULL_TREE;
6562         }
6563
6564       expr = build_nop (type, build_address (expr));
6565     }
6566   /* [temp.arg.nontype]/5, bullet 4
6567
6568      For a non-type template-parameter of type pointer to function, only
6569      the function-to-pointer conversion (_conv.func_) is applied. If the
6570      template-argument represents a set of overloaded functions (or a
6571      pointer to such), the matching function is selected from the set
6572      (_over.over_).  */
6573   else if (TYPE_PTRFN_P (type))
6574     {
6575       /* If the argument is a template-id, we might not have enough
6576          context information to decay the pointer.  */
6577       if (!type_unknown_p (expr_type))
6578         {
6579           expr = decay_conversion (expr, complain);
6580           if (expr == error_mark_node)
6581             return error_mark_node;
6582         }
6583
6584       if (cxx_dialect >= cxx11 && integer_zerop (expr))
6585         /* Null pointer values are OK in C++11.  */
6586         return perform_qualification_conversions (type, expr);
6587
6588       expr = convert_nontype_argument_function (type, expr, complain);
6589       if (!expr || expr == error_mark_node)
6590         return expr;
6591     }
6592   /* [temp.arg.nontype]/5, bullet 5
6593
6594      For a non-type template-parameter of type reference to function, no
6595      conversions apply. If the template-argument represents a set of
6596      overloaded functions, the matching function is selected from the set
6597      (_over.over_).  */
6598   else if (TYPE_REFFN_P (type))
6599     {
6600       if (TREE_CODE (expr) == ADDR_EXPR)
6601         {
6602           if (complain & tf_error)
6603             {
6604               error ("%qE is not a valid template argument for type %qT "
6605                      "because it is a pointer", expr, type);
6606               inform (input_location, "try using %qE instead",
6607                       TREE_OPERAND (expr, 0));
6608             }
6609           return NULL_TREE;
6610         }
6611
6612       expr = convert_nontype_argument_function (type, expr, complain);
6613       if (!expr || expr == error_mark_node)
6614         return expr;
6615
6616       expr = build_nop (type, build_address (expr));
6617     }
6618   /* [temp.arg.nontype]/5, bullet 6
6619
6620      For a non-type template-parameter of type pointer to member function,
6621      no conversions apply. If the template-argument represents a set of
6622      overloaded member functions, the matching member function is selected
6623      from the set (_over.over_).  */
6624   else if (TYPE_PTRMEMFUNC_P (type))
6625     {
6626       expr = instantiate_type (type, expr, tf_none);
6627       if (expr == error_mark_node)
6628         return error_mark_node;
6629
6630       /* [temp.arg.nontype] bullet 1 says the pointer to member
6631          expression must be a pointer-to-member constant.  */
6632       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
6633         return error_mark_node;
6634
6635       /* There is no way to disable standard conversions in
6636          resolve_address_of_overloaded_function (called by
6637          instantiate_type). It is possible that the call succeeded by
6638          converting &B::I to &D::I (where B is a base of D), so we need
6639          to reject this conversion here.
6640
6641          Actually, even if there was a way to disable standard conversions,
6642          it would still be better to reject them here so that we can
6643          provide a superior diagnostic.  */
6644       if (!same_type_p (TREE_TYPE (expr), type))
6645         {
6646           if (complain & tf_error)
6647             {
6648               error ("%qE is not a valid template argument for type %qT "
6649                      "because it is of type %qT", expr, type,
6650                      TREE_TYPE (expr));
6651               /* If we are just one standard conversion off, explain.  */
6652               if (can_convert_standard (type, TREE_TYPE (expr), complain))
6653                 inform (input_location,
6654                         "standard conversions are not allowed in this context");
6655             }
6656           return NULL_TREE;
6657         }
6658     }
6659   /* [temp.arg.nontype]/5, bullet 7
6660
6661      For a non-type template-parameter of type pointer to data member,
6662      qualification conversions (_conv.qual_) are applied.  */
6663   else if (TYPE_PTRDATAMEM_P (type))
6664     {
6665       /* [temp.arg.nontype] bullet 1 says the pointer to member
6666          expression must be a pointer-to-member constant.  */
6667       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
6668         return error_mark_node;
6669
6670       expr = perform_qualification_conversions (type, expr);
6671       if (expr == error_mark_node)
6672         return expr;
6673     }
6674   else if (NULLPTR_TYPE_P (type))
6675     {
6676       if (expr != nullptr_node)
6677         {
6678           if (complain & tf_error)
6679             error ("%qE is not a valid template argument for type %qT "
6680                    "because it is of type %qT", expr, type, TREE_TYPE (expr));
6681           return NULL_TREE;
6682         }
6683       return expr;
6684     }
6685   /* A template non-type parameter must be one of the above.  */
6686   else
6687     gcc_unreachable ();
6688
6689   /* Sanity check: did we actually convert the argument to the
6690      right type?  */
6691   gcc_assert (same_type_ignoring_top_level_qualifiers_p
6692               (type, TREE_TYPE (expr)));
6693   return convert_from_reference (expr);
6694 }
6695
6696 /* Subroutine of coerce_template_template_parms, which returns 1 if
6697    PARM_PARM and ARG_PARM match using the rule for the template
6698    parameters of template template parameters. Both PARM and ARG are
6699    template parameters; the rest of the arguments are the same as for
6700    coerce_template_template_parms.
6701  */
6702 static int
6703 coerce_template_template_parm (tree parm,
6704                               tree arg,
6705                               tsubst_flags_t complain,
6706                               tree in_decl,
6707                               tree outer_args)
6708 {
6709   if (arg == NULL_TREE || error_operand_p (arg)
6710       || parm == NULL_TREE || error_operand_p (parm))
6711     return 0;
6712   
6713   if (TREE_CODE (arg) != TREE_CODE (parm))
6714     return 0;
6715   
6716   switch (TREE_CODE (parm))
6717     {
6718     case TEMPLATE_DECL:
6719       /* We encounter instantiations of templates like
6720          template <template <template <class> class> class TT>
6721          class C;  */
6722       {
6723         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6724         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6725         
6726         if (!coerce_template_template_parms
6727             (parmparm, argparm, complain, in_decl, outer_args))
6728           return 0;
6729       }
6730       /* Fall through.  */
6731       
6732     case TYPE_DECL:
6733       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
6734           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6735         /* Argument is a parameter pack but parameter is not.  */
6736         return 0;
6737       break;
6738       
6739     case PARM_DECL:
6740       /* The tsubst call is used to handle cases such as
6741          
6742            template <int> class C {};
6743            template <class T, template <T> class TT> class D {};
6744            D<int, C> d;
6745
6746          i.e. the parameter list of TT depends on earlier parameters.  */
6747       if (!uses_template_parms (TREE_TYPE (arg)))
6748         {
6749           tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
6750           if (!uses_template_parms (t)
6751               && !same_type_p (t, TREE_TYPE (arg)))
6752             return 0;
6753         }
6754       
6755       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
6756           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6757         /* Argument is a parameter pack but parameter is not.  */
6758         return 0;
6759       
6760       break;
6761
6762     default:
6763       gcc_unreachable ();
6764     }
6765
6766   return 1;
6767 }
6768
6769
6770 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
6771    template template parameters.  Both PARM_PARMS and ARG_PARMS are
6772    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
6773    or PARM_DECL.
6774
6775    Consider the example:
6776      template <class T> class A;
6777      template<template <class U> class TT> class B;
6778
6779    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
6780    the parameters to A, and OUTER_ARGS contains A.  */
6781
6782 static int
6783 coerce_template_template_parms (tree parm_parms,
6784                                 tree arg_parms,
6785                                 tsubst_flags_t complain,
6786                                 tree in_decl,
6787                                 tree outer_args)
6788 {
6789   int nparms, nargs, i;
6790   tree parm, arg;
6791   int variadic_p = 0;
6792
6793   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
6794   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
6795
6796   nparms = TREE_VEC_LENGTH (parm_parms);
6797   nargs = TREE_VEC_LENGTH (arg_parms);
6798
6799   /* Determine whether we have a parameter pack at the end of the
6800      template template parameter's template parameter list.  */
6801   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
6802     {
6803       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
6804       
6805       if (error_operand_p (parm))
6806         return 0;
6807
6808       switch (TREE_CODE (parm))
6809         {
6810         case TEMPLATE_DECL:
6811         case TYPE_DECL:
6812           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6813             variadic_p = 1;
6814           break;
6815           
6816         case PARM_DECL:
6817           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6818             variadic_p = 1;
6819           break;
6820           
6821         default:
6822           gcc_unreachable ();
6823         }
6824     }
6825  
6826   if (nargs != nparms
6827       && !(variadic_p && nargs >= nparms - 1))
6828     return 0;
6829
6830   /* Check all of the template parameters except the parameter pack at
6831      the end (if any).  */
6832   for (i = 0; i < nparms - variadic_p; ++i)
6833     {
6834       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
6835           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6836         continue;
6837
6838       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6839       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6840
6841       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6842                                           outer_args))
6843         return 0;
6844
6845     }
6846
6847   if (variadic_p)
6848     {
6849       /* Check each of the template parameters in the template
6850          argument against the template parameter pack at the end of
6851          the template template parameter.  */
6852       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
6853         return 0;
6854
6855       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6856
6857       for (; i < nargs; ++i)
6858         {
6859           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6860             continue;
6861  
6862           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6863  
6864           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6865                                               outer_args))
6866             return 0;
6867         }
6868     }
6869
6870   return 1;
6871 }
6872
6873 /* Verifies that the deduced template arguments (in TARGS) for the
6874    template template parameters (in TPARMS) represent valid bindings,
6875    by comparing the template parameter list of each template argument
6876    to the template parameter list of its corresponding template
6877    template parameter, in accordance with DR150. This
6878    routine can only be called after all template arguments have been
6879    deduced. It will return TRUE if all of the template template
6880    parameter bindings are okay, FALSE otherwise.  */
6881 bool 
6882 template_template_parm_bindings_ok_p (tree tparms, tree targs)
6883 {
6884   int i, ntparms = TREE_VEC_LENGTH (tparms);
6885   bool ret = true;
6886
6887   /* We're dealing with template parms in this process.  */
6888   ++processing_template_decl;
6889
6890   targs = INNERMOST_TEMPLATE_ARGS (targs);
6891
6892   for (i = 0; i < ntparms; ++i)
6893     {
6894       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
6895       tree targ = TREE_VEC_ELT (targs, i);
6896
6897       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
6898         {
6899           tree packed_args = NULL_TREE;
6900           int idx, len = 1;
6901
6902           if (ARGUMENT_PACK_P (targ))
6903             {
6904               /* Look inside the argument pack.  */
6905               packed_args = ARGUMENT_PACK_ARGS (targ);
6906               len = TREE_VEC_LENGTH (packed_args);
6907             }
6908
6909           for (idx = 0; idx < len; ++idx)
6910             {
6911               tree targ_parms = NULL_TREE;
6912
6913               if (packed_args)
6914                 /* Extract the next argument from the argument
6915                    pack.  */
6916                 targ = TREE_VEC_ELT (packed_args, idx);
6917
6918               if (PACK_EXPANSION_P (targ))
6919                 /* Look at the pattern of the pack expansion.  */
6920                 targ = PACK_EXPANSION_PATTERN (targ);
6921
6922               /* Extract the template parameters from the template
6923                  argument.  */
6924               if (TREE_CODE (targ) == TEMPLATE_DECL)
6925                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
6926               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
6927                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
6928
6929               /* Verify that we can coerce the template template
6930                  parameters from the template argument to the template
6931                  parameter.  This requires an exact match.  */
6932               if (targ_parms
6933                   && !coerce_template_template_parms
6934                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
6935                         targ_parms,
6936                         tf_none,
6937                         tparm,
6938                         targs))
6939                 {
6940                   ret = false;
6941                   goto out;
6942                 }
6943             }
6944         }
6945     }
6946
6947  out:
6948
6949   --processing_template_decl;
6950   return ret;
6951 }
6952
6953 /* Since type attributes aren't mangled, we need to strip them from
6954    template type arguments.  */
6955
6956 static tree
6957 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
6958 {
6959   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
6960     return arg;
6961   bool removed_attributes = false;
6962   tree canon = strip_typedefs (arg, &removed_attributes);
6963   if (removed_attributes
6964       && (complain & tf_warning))
6965     warning (OPT_Wignored_attributes,
6966              "ignoring attributes on template argument %qT", arg);
6967   return canon;
6968 }
6969
6970 // A template declaration can be substituted for a constrained
6971 // template template parameter only when the argument is more
6972 // constrained than the parameter.
6973 static bool
6974 is_compatible_template_arg (tree parm, tree arg)
6975 {
6976   tree parm_cons = get_constraints (parm);
6977
6978   /* For now, allow constrained template template arguments
6979      and unconstrained template template parameters.  */
6980   if (parm_cons == NULL_TREE)
6981     return true;
6982
6983   tree arg_cons = get_constraints (arg);
6984
6985   // If the template parameter is constrained, we need to rewrite its
6986   // constraints in terms of the ARG's template parameters. This ensures
6987   // that all of the template parameter types will have the same depth.
6988   //
6989   // Note that this is only valid when coerce_template_template_parm is
6990   // true for the innermost template parameters of PARM and ARG. In other
6991   // words, because coercion is successful, this conversion will be valid.
6992   if (parm_cons)
6993     {
6994       tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (arg));
6995       parm_cons = tsubst_constraint_info (parm_cons,
6996                                           INNERMOST_TEMPLATE_ARGS (args),
6997                                           tf_none, NULL_TREE);
6998       if (parm_cons == error_mark_node)
6999         return false;
7000     }
7001
7002   return subsumes (parm_cons, arg_cons);
7003 }
7004
7005 // Convert a placeholder argument into a binding to the original
7006 // parameter. The original parameter is saved as the TREE_TYPE of
7007 // ARG.
7008 static inline tree
7009 convert_wildcard_argument (tree parm, tree arg)
7010 {
7011   TREE_TYPE (arg) = parm;
7012   return arg;
7013 }
7014
7015 /* Convert the indicated template ARG as necessary to match the
7016    indicated template PARM.  Returns the converted ARG, or
7017    error_mark_node if the conversion was unsuccessful.  Error and
7018    warning messages are issued under control of COMPLAIN.  This
7019    conversion is for the Ith parameter in the parameter list.  ARGS is
7020    the full set of template arguments deduced so far.  */
7021
7022 static tree
7023 convert_template_argument (tree parm,
7024                            tree arg,
7025                            tree args,
7026                            tsubst_flags_t complain,
7027                            int i,
7028                            tree in_decl)
7029 {
7030   tree orig_arg;
7031   tree val;
7032   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
7033
7034   if (parm == error_mark_node)
7035     return error_mark_node;
7036
7037   /* Trivially convert placeholders. */
7038   if (TREE_CODE (arg) == WILDCARD_DECL)
7039     return convert_wildcard_argument (parm, arg);
7040
7041   if (TREE_CODE (arg) == TREE_LIST
7042       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
7043     {
7044       /* The template argument was the name of some
7045          member function.  That's usually
7046          invalid, but static members are OK.  In any
7047          case, grab the underlying fields/functions
7048          and issue an error later if required.  */
7049       orig_arg = TREE_VALUE (arg);
7050       TREE_TYPE (arg) = unknown_type_node;
7051     }
7052
7053   orig_arg = arg;
7054
7055   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
7056   requires_type = (TREE_CODE (parm) == TYPE_DECL
7057                    || requires_tmpl_type);
7058
7059   /* When determining whether an argument pack expansion is a template,
7060      look at the pattern.  */
7061   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
7062     arg = PACK_EXPANSION_PATTERN (arg);
7063
7064   /* Deal with an injected-class-name used as a template template arg.  */
7065   if (requires_tmpl_type && CLASS_TYPE_P (arg))
7066     {
7067       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
7068       if (TREE_CODE (t) == TEMPLATE_DECL)
7069         {
7070           if (cxx_dialect >= cxx11)
7071             /* OK under DR 1004.  */;
7072           else if (complain & tf_warning_or_error)
7073             pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
7074                      " used as template template argument", TYPE_NAME (arg));
7075           else if (flag_pedantic_errors)
7076             t = arg;
7077
7078           arg = t;
7079         }
7080     }
7081
7082   is_tmpl_type = 
7083     ((TREE_CODE (arg) == TEMPLATE_DECL
7084       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
7085      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
7086      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
7087      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
7088
7089   if (is_tmpl_type
7090       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
7091           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
7092     arg = TYPE_STUB_DECL (arg);
7093
7094   is_type = TYPE_P (arg) || is_tmpl_type;
7095
7096   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
7097       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
7098     {
7099       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
7100         {
7101           if (complain & tf_error)
7102             error ("invalid use of destructor %qE as a type", orig_arg);
7103           return error_mark_node;
7104         }
7105
7106       permerror (input_location,
7107                  "to refer to a type member of a template parameter, "
7108                  "use %<typename %E%>", orig_arg);
7109
7110       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
7111                                      TREE_OPERAND (arg, 1),
7112                                      typename_type,
7113                                      complain);
7114       arg = orig_arg;
7115       is_type = 1;
7116     }
7117   if (is_type != requires_type)
7118     {
7119       if (in_decl)
7120         {
7121           if (complain & tf_error)
7122             {
7123               error ("type/value mismatch at argument %d in template "
7124                      "parameter list for %qD",
7125                      i + 1, in_decl);
7126               if (is_type)
7127                 inform (input_location,
7128                         "  expected a constant of type %qT, got %qT",
7129                         TREE_TYPE (parm),
7130                         (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
7131               else if (requires_tmpl_type)
7132                 inform (input_location,
7133                         "  expected a class template, got %qE", orig_arg);
7134               else
7135                 inform (input_location,
7136                         "  expected a type, got %qE", orig_arg);
7137             }
7138         }
7139       return error_mark_node;
7140     }
7141   if (is_tmpl_type ^ requires_tmpl_type)
7142     {
7143       if (in_decl && (complain & tf_error))
7144         {
7145           error ("type/value mismatch at argument %d in template "
7146                  "parameter list for %qD",
7147                  i + 1, in_decl);
7148           if (is_tmpl_type)
7149             inform (input_location,
7150                     "  expected a type, got %qT", DECL_NAME (arg));
7151           else
7152             inform (input_location,
7153                     "  expected a class template, got %qT", orig_arg);
7154         }
7155       return error_mark_node;
7156     }
7157
7158   if (is_type)
7159     {
7160       if (requires_tmpl_type)
7161         {
7162           if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
7163             val = orig_arg;
7164           else if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
7165             /* The number of argument required is not known yet.
7166                Just accept it for now.  */
7167             val = TREE_TYPE (arg);
7168           else
7169             {
7170               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7171               tree argparm;
7172
7173               /* Strip alias templates that are equivalent to another
7174                  template.  */
7175               arg = get_underlying_template (arg);
7176               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7177
7178               if (coerce_template_template_parms (parmparm, argparm,
7179                                                   complain, in_decl,
7180                                                   args))
7181                 {
7182                   val = arg;
7183
7184                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
7185                      TEMPLATE_DECL.  */
7186                   if (val != error_mark_node)
7187                     {
7188                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
7189                         val = TREE_TYPE (val);
7190                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
7191                         val = make_pack_expansion (val);
7192                     }
7193                 }
7194               else
7195                 {
7196                   if (in_decl && (complain & tf_error))
7197                     {
7198                       error ("type/value mismatch at argument %d in "
7199                              "template parameter list for %qD",
7200                              i + 1, in_decl);
7201                       inform (input_location,
7202                               "  expected a template of type %qD, got %qT",
7203                               parm, orig_arg);
7204                     }
7205
7206                   val = error_mark_node;
7207                 }
7208
7209               // Check that the constraints are compatible before allowing the
7210               // substitution.
7211               if (val != error_mark_node)
7212                 if (!is_compatible_template_arg (parm, arg))
7213                   {
7214                     if (in_decl && (complain & tf_error))
7215                       {
7216                         error ("constraint mismatch at argument %d in "
7217                                "template parameter list for %qD",
7218                                i + 1, in_decl);
7219                         inform (input_location, "  expected %qD but got %qD",
7220                                 parm, arg);
7221                       }
7222                     val = error_mark_node;
7223                   }
7224             }
7225         }
7226       else
7227         val = orig_arg;
7228       /* We only form one instance of each template specialization.
7229          Therefore, if we use a non-canonical variant (i.e., a
7230          typedef), any future messages referring to the type will use
7231          the typedef, which is confusing if those future uses do not
7232          themselves also use the typedef.  */
7233       if (TYPE_P (val))
7234         val = canonicalize_type_argument (val, complain);
7235     }
7236   else
7237     {
7238       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
7239
7240       if (invalid_nontype_parm_type_p (t, complain))
7241         return error_mark_node;
7242
7243       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
7244         {
7245           if (same_type_p (t, TREE_TYPE (orig_arg)))
7246             val = orig_arg;
7247           else
7248             {
7249               /* Not sure if this is reachable, but it doesn't hurt
7250                  to be robust.  */
7251               error ("type mismatch in nontype parameter pack");
7252               val = error_mark_node;
7253             }
7254         }
7255       else if (!dependent_template_arg_p (orig_arg)
7256                && !uses_template_parms (t))
7257         /* We used to call digest_init here.  However, digest_init
7258            will report errors, which we don't want when complain
7259            is zero.  More importantly, digest_init will try too
7260            hard to convert things: for example, `0' should not be
7261            converted to pointer type at this point according to
7262            the standard.  Accepting this is not merely an
7263            extension, since deciding whether or not these
7264            conversions can occur is part of determining which
7265            function template to call, or whether a given explicit
7266            argument specification is valid.  */
7267         val = convert_nontype_argument (t, orig_arg, complain);
7268       else
7269         {
7270           bool removed_attr = false;
7271           val = strip_typedefs_expr (orig_arg, &removed_attr);
7272         }
7273
7274       if (val == NULL_TREE)
7275         val = error_mark_node;
7276       else if (val == error_mark_node && (complain & tf_error))
7277         error ("could not convert template argument %qE to %qT",  orig_arg, t);
7278
7279       if (INDIRECT_REF_P (val))
7280         {
7281           /* Reject template arguments that are references to built-in
7282              functions with no library fallbacks.  */
7283           const_tree inner = TREE_OPERAND (val, 0);
7284           if (TREE_CODE (TREE_TYPE (inner)) == REFERENCE_TYPE
7285               && TREE_CODE (TREE_TYPE (TREE_TYPE (inner))) == FUNCTION_TYPE
7286               && TREE_CODE (TREE_TYPE (inner)) == REFERENCE_TYPE
7287               && 0 < TREE_OPERAND_LENGTH (inner)
7288               && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
7289               return error_mark_node;
7290         }
7291
7292       if (TREE_CODE (val) == SCOPE_REF)
7293         {
7294           /* Strip typedefs from the SCOPE_REF.  */
7295           tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
7296           tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
7297                                                    complain);
7298           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
7299                                       QUALIFIED_NAME_IS_TEMPLATE (val));
7300         }
7301     }
7302
7303   return val;
7304 }
7305
7306 /* Coerces the remaining template arguments in INNER_ARGS (from
7307    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
7308    Returns the coerced argument pack. PARM_IDX is the position of this
7309    parameter in the template parameter list. ARGS is the original
7310    template argument list.  */
7311 static tree
7312 coerce_template_parameter_pack (tree parms,
7313                                 int parm_idx,
7314                                 tree args,
7315                                 tree inner_args,
7316                                 int arg_idx,
7317                                 tree new_args,
7318                                 int* lost,
7319                                 tree in_decl,
7320                                 tsubst_flags_t complain)
7321 {
7322   tree parm = TREE_VEC_ELT (parms, parm_idx);
7323   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
7324   tree packed_args;
7325   tree argument_pack;
7326   tree packed_parms = NULL_TREE;
7327
7328   if (arg_idx > nargs)
7329     arg_idx = nargs;
7330
7331   if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
7332     {
7333       /* When the template parameter is a non-type template parameter pack
7334          or template template parameter pack whose type or template
7335          parameters use parameter packs, we know exactly how many arguments
7336          we are looking for.  Build a vector of the instantiated decls for
7337          these template parameters in PACKED_PARMS.  */
7338       /* We can't use make_pack_expansion here because it would interpret a
7339          _DECL as a use rather than a declaration.  */
7340       tree decl = TREE_VALUE (parm);
7341       tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
7342       SET_PACK_EXPANSION_PATTERN (exp, decl);
7343       PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
7344       SET_TYPE_STRUCTURAL_EQUALITY (exp);
7345
7346       TREE_VEC_LENGTH (args)--;
7347       packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
7348       TREE_VEC_LENGTH (args)++;
7349
7350       if (packed_parms == error_mark_node)
7351         return error_mark_node;
7352
7353       /* If we're doing a partial instantiation of a member template,
7354          verify that all of the types used for the non-type
7355          template parameter pack are, in fact, valid for non-type
7356          template parameters.  */
7357       if (arg_idx < nargs
7358           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
7359         {
7360           int j, len = TREE_VEC_LENGTH (packed_parms);
7361           for (j = 0; j < len; ++j)
7362             {
7363               tree t = TREE_TYPE (TREE_VEC_ELT (packed_parms, j));
7364               if (invalid_nontype_parm_type_p (t, complain))
7365                 return error_mark_node;
7366             }
7367           /* We don't know how many args we have yet, just
7368              use the unconverted ones for now.  */
7369           return NULL_TREE;
7370         }
7371
7372       packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
7373     }
7374   /* Check if we have a placeholder pack, which indicates we're
7375      in the context of a introduction list.  In that case we want
7376      to match this pack to the single placeholder.  */
7377   else if (arg_idx < nargs
7378            && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
7379            && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
7380     {
7381       nargs = arg_idx + 1;
7382       packed_args = make_tree_vec (1);
7383     }
7384   else
7385     packed_args = make_tree_vec (nargs - arg_idx);
7386
7387   /* Convert the remaining arguments, which will be a part of the
7388      parameter pack "parm".  */
7389   int first_pack_arg = arg_idx;
7390   for (; arg_idx < nargs; ++arg_idx)
7391     {
7392       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
7393       tree actual_parm = TREE_VALUE (parm);
7394       int pack_idx = arg_idx - first_pack_arg;
7395
7396       if (packed_parms)
7397         {
7398           /* Once we've packed as many args as we have types, stop.  */
7399           if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
7400             break;
7401           else if (PACK_EXPANSION_P (arg))
7402             /* We don't know how many args we have yet, just
7403                use the unconverted ones for now.  */
7404             return NULL_TREE;
7405           else
7406             actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
7407         }
7408
7409       if (arg == error_mark_node)
7410         {
7411           if (complain & tf_error)
7412             error ("template argument %d is invalid", arg_idx + 1);
7413         }
7414       else
7415         arg = convert_template_argument (actual_parm, 
7416                                          arg, new_args, complain, parm_idx,
7417                                          in_decl);
7418       if (arg == error_mark_node)
7419         (*lost)++;
7420       TREE_VEC_ELT (packed_args, pack_idx) = arg;
7421     }
7422
7423   if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
7424       && TREE_VEC_LENGTH (packed_args) > 0)
7425     {
7426       if (complain & tf_error)
7427         error ("wrong number of template arguments (%d, should be %d)",
7428                arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
7429       return error_mark_node;
7430     }
7431
7432   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
7433       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
7434     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
7435   else
7436     {
7437       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
7438       TREE_TYPE (argument_pack) 
7439         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
7440       TREE_CONSTANT (argument_pack) = 1;
7441     }
7442
7443   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
7444   if (CHECKING_P)
7445     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
7446                                          TREE_VEC_LENGTH (packed_args));
7447   return argument_pack;
7448 }
7449
7450 /* Returns the number of pack expansions in the template argument vector
7451    ARGS.  */
7452
7453 static int
7454 pack_expansion_args_count (tree args)
7455 {
7456   int i;
7457   int count = 0;
7458   if (args)
7459     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
7460       {
7461         tree elt = TREE_VEC_ELT (args, i);
7462         if (elt && PACK_EXPANSION_P (elt))
7463           ++count;
7464       }
7465   return count;
7466 }
7467
7468 /* Convert all template arguments to their appropriate types, and
7469    return a vector containing the innermost resulting template
7470    arguments.  If any error occurs, return error_mark_node. Error and
7471    warning messages are issued under control of COMPLAIN.
7472
7473    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
7474    for arguments not specified in ARGS.  Otherwise, if
7475    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
7476    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
7477    USE_DEFAULT_ARGS is false, then all arguments must be specified in
7478    ARGS.  */
7479
7480 static tree
7481 coerce_template_parms (tree parms,
7482                        tree args,
7483                        tree in_decl,
7484                        tsubst_flags_t complain,
7485                        bool require_all_args,
7486                        bool use_default_args)
7487 {
7488   int nparms, nargs, parm_idx, arg_idx, lost = 0;
7489   tree orig_inner_args;
7490   tree inner_args;
7491   tree new_args;
7492   tree new_inner_args;
7493   int saved_unevaluated_operand;
7494   int saved_inhibit_evaluation_warnings;
7495
7496   /* When used as a boolean value, indicates whether this is a
7497      variadic template parameter list. Since it's an int, we can also
7498      subtract it from nparms to get the number of non-variadic
7499      parameters.  */
7500   int variadic_p = 0;
7501   int variadic_args_p = 0;
7502   int post_variadic_parms = 0;
7503
7504   /* Likewise for parameters with default arguments.  */
7505   int default_p = 0;
7506
7507   if (args == error_mark_node)
7508     return error_mark_node;
7509
7510   nparms = TREE_VEC_LENGTH (parms);
7511
7512   /* Determine if there are any parameter packs or default arguments.  */
7513   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
7514     {
7515       tree parm = TREE_VEC_ELT (parms, parm_idx);
7516       if (variadic_p)
7517         ++post_variadic_parms;
7518       if (template_parameter_pack_p (TREE_VALUE (parm)))
7519         ++variadic_p;
7520       if (TREE_PURPOSE (parm))
7521         ++default_p;
7522     }
7523
7524   inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
7525   /* If there are no parameters that follow a parameter pack, we need to
7526      expand any argument packs so that we can deduce a parameter pack from
7527      some non-packed args followed by an argument pack, as in variadic85.C.
7528      If there are such parameters, we need to leave argument packs intact
7529      so the arguments are assigned properly.  This can happen when dealing
7530      with a nested class inside a partial specialization of a class
7531      template, as in variadic92.C, or when deducing a template parameter pack
7532      from a sub-declarator, as in variadic114.C.  */
7533   if (!post_variadic_parms)
7534     inner_args = expand_template_argument_pack (inner_args);
7535
7536   /* Count any pack expansion args.  */
7537   variadic_args_p = pack_expansion_args_count (inner_args);
7538
7539   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
7540   if ((nargs > nparms && !variadic_p)
7541       || (nargs < nparms - variadic_p
7542           && require_all_args
7543           && !variadic_args_p
7544           && (!use_default_args
7545               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
7546                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
7547     {
7548       if (complain & tf_error)
7549         {
7550           if (variadic_p || default_p)
7551             {
7552               nparms -= variadic_p + default_p;
7553               error ("wrong number of template arguments "
7554                      "(%d, should be at least %d)", nargs, nparms);
7555             }
7556           else
7557              error ("wrong number of template arguments "
7558                     "(%d, should be %d)", nargs, nparms);
7559
7560           if (in_decl)
7561             inform (DECL_SOURCE_LOCATION (in_decl),
7562                     "provided for %qD", in_decl);
7563         }
7564
7565       return error_mark_node;
7566     }
7567   /* We can't pass a pack expansion to a non-pack parameter of an alias
7568      template (DR 1430).  */
7569   else if (in_decl
7570            && (DECL_ALIAS_TEMPLATE_P (in_decl)
7571                || concept_template_p (in_decl))
7572            && variadic_args_p
7573            && nargs - variadic_args_p < nparms - variadic_p)
7574     {
7575       if (complain & tf_error)
7576         {
7577           for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
7578             {
7579               tree arg = TREE_VEC_ELT (inner_args, i);
7580               tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
7581
7582               if (PACK_EXPANSION_P (arg)
7583                   && !template_parameter_pack_p (parm))
7584                 {
7585                   if (DECL_ALIAS_TEMPLATE_P (in_decl))
7586                     error_at (location_of (arg),
7587                               "pack expansion argument for non-pack parameter "
7588                               "%qD of alias template %qD", parm, in_decl);
7589                   else
7590                     error_at (location_of (arg),
7591                               "pack expansion argument for non-pack parameter "
7592                               "%qD of concept %qD", parm, in_decl);
7593                   inform (DECL_SOURCE_LOCATION (parm), "declared here");
7594                   goto found;
7595                 }
7596             }
7597           gcc_unreachable ();
7598         found:;
7599         }
7600       return error_mark_node;
7601     }
7602
7603   /* We need to evaluate the template arguments, even though this
7604      template-id may be nested within a "sizeof".  */
7605   saved_unevaluated_operand = cp_unevaluated_operand;
7606   cp_unevaluated_operand = 0;
7607   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
7608   c_inhibit_evaluation_warnings = 0;
7609   new_inner_args = make_tree_vec (nparms);
7610   new_args = add_outermost_template_args (args, new_inner_args);
7611   int pack_adjust = 0;
7612   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
7613     {
7614       tree arg;
7615       tree parm;
7616
7617       /* Get the Ith template parameter.  */
7618       parm = TREE_VEC_ELT (parms, parm_idx);
7619  
7620       if (parm == error_mark_node)
7621       {
7622         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
7623         continue;
7624       }
7625
7626       /* Calculate the next argument.  */
7627       if (arg_idx < nargs)
7628         arg = TREE_VEC_ELT (inner_args, arg_idx);
7629       else
7630         arg = NULL_TREE;
7631
7632       if (template_parameter_pack_p (TREE_VALUE (parm))
7633           && !(arg && ARGUMENT_PACK_P (arg)))
7634         {
7635           /* Some arguments will be placed in the
7636              template parameter pack PARM.  */
7637           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
7638                                                 inner_args, arg_idx,
7639                                                 new_args, &lost,
7640                                                 in_decl, complain);
7641
7642           if (arg == NULL_TREE)
7643             {
7644               /* We don't know how many args we have yet, just use the
7645                  unconverted (and still packed) ones for now.  */
7646               new_inner_args = orig_inner_args;
7647               arg_idx = nargs;
7648               break;
7649             }
7650
7651           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
7652
7653           /* Store this argument.  */
7654           if (arg == error_mark_node)
7655             {
7656               lost++;
7657               /* We are done with all of the arguments.  */
7658               arg_idx = nargs;
7659             }
7660           else
7661             {
7662               pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
7663               arg_idx += pack_adjust;
7664             }
7665           
7666           continue;
7667         }
7668       else if (arg)
7669         {
7670           if (PACK_EXPANSION_P (arg))
7671             {
7672               /* "If every valid specialization of a variadic template
7673                  requires an empty template parameter pack, the template is
7674                  ill-formed, no diagnostic required."  So check that the
7675                  pattern works with this parameter.  */
7676               tree pattern = PACK_EXPANSION_PATTERN (arg);
7677               tree conv = convert_template_argument (TREE_VALUE (parm),
7678                                                      pattern, new_args,
7679                                                      complain, parm_idx,
7680                                                      in_decl);
7681               if (conv == error_mark_node)
7682                 {
7683                   inform (input_location, "so any instantiation with a "
7684                          "non-empty parameter pack would be ill-formed");
7685                   ++lost;
7686                 }
7687               else if (TYPE_P (conv) && !TYPE_P (pattern))
7688                 /* Recover from missing typename.  */
7689                 TREE_VEC_ELT (inner_args, arg_idx)
7690                   = make_pack_expansion (conv);
7691
7692               /* We don't know how many args we have yet, just
7693                  use the unconverted ones for now.  */
7694               new_inner_args = inner_args;
7695               arg_idx = nargs;
7696               break;
7697             }
7698         }
7699       else if (require_all_args)
7700         {
7701           /* There must be a default arg in this case.  */
7702           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
7703                                      complain, in_decl);
7704           /* The position of the first default template argument,
7705              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
7706              Record that.  */
7707           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
7708             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
7709                                                  arg_idx - pack_adjust);
7710         }
7711       else
7712         break;
7713
7714       if (arg == error_mark_node)
7715         {
7716           if (complain & tf_error)
7717             error ("template argument %d is invalid", arg_idx + 1);
7718         }
7719       else if (!arg)
7720         /* This only occurs if there was an error in the template
7721            parameter list itself (which we would already have
7722            reported) that we are trying to recover from, e.g., a class
7723            template with a parameter list such as
7724            template<typename..., typename>.  */
7725         ++lost;
7726       else
7727         arg = convert_template_argument (TREE_VALUE (parm),
7728                                          arg, new_args, complain, 
7729                                          parm_idx, in_decl);
7730
7731       if (arg == error_mark_node)
7732         lost++;
7733       TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
7734     }
7735   cp_unevaluated_operand = saved_unevaluated_operand;
7736   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
7737
7738   if (variadic_p && arg_idx < nargs)
7739     {
7740       if (complain & tf_error)
7741         {
7742           error ("wrong number of template arguments "
7743                  "(%d, should be %d)", nargs, arg_idx);
7744           if (in_decl)
7745             error ("provided for %q+D", in_decl);
7746         }
7747       return error_mark_node;
7748     }
7749
7750   if (lost)
7751     return error_mark_node;
7752
7753   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
7754     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
7755                                          TREE_VEC_LENGTH (new_inner_args));
7756
7757   return new_inner_args;
7758 }
7759
7760 /* Convert all template arguments to their appropriate types, and
7761    return a vector containing the innermost resulting template
7762    arguments.  If any error occurs, return error_mark_node. Error and
7763    warning messages are not issued.
7764
7765    Note that no function argument deduction is performed, and default
7766    arguments are used to fill in unspecified arguments. */
7767 tree
7768 coerce_template_parms (tree parms, tree args, tree in_decl)
7769 {
7770   return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
7771 }
7772
7773 /* Convert all template arguments to their appropriate type, and
7774    instantiate default arguments as needed. This returns a vector
7775    containing the innermost resulting template arguments, or
7776    error_mark_node if unsuccessful.  */
7777 tree
7778 coerce_template_parms (tree parms, tree args, tree in_decl,
7779                        tsubst_flags_t complain)
7780 {
7781   return coerce_template_parms (parms, args, in_decl, complain, true, true);
7782 }
7783
7784 /* Like coerce_template_parms.  If PARMS represents all template
7785    parameters levels, this function returns a vector of vectors
7786    representing all the resulting argument levels.  Note that in this
7787    case, only the innermost arguments are coerced because the
7788    outermost ones are supposed to have been coerced already.
7789
7790    Otherwise, if PARMS represents only (the innermost) vector of
7791    parameters, this function returns a vector containing just the
7792    innermost resulting arguments.  */
7793
7794 static tree
7795 coerce_innermost_template_parms (tree parms,
7796                                   tree args,
7797                                   tree in_decl,
7798                                   tsubst_flags_t complain,
7799                                   bool require_all_args,
7800                                   bool use_default_args)
7801 {
7802   int parms_depth = TMPL_PARMS_DEPTH (parms);
7803   int args_depth = TMPL_ARGS_DEPTH (args);
7804   tree coerced_args;
7805
7806   if (parms_depth > 1)
7807     {
7808       coerced_args = make_tree_vec (parms_depth);
7809       tree level;
7810       int cur_depth;
7811
7812       for (level = parms, cur_depth = parms_depth;
7813            parms_depth > 0 && level != NULL_TREE;
7814            level = TREE_CHAIN (level), --cur_depth)
7815         {
7816           tree l;
7817           if (cur_depth == args_depth)
7818             l = coerce_template_parms (TREE_VALUE (level),
7819                                        args, in_decl, complain,
7820                                        require_all_args,
7821                                        use_default_args);
7822           else
7823             l = TMPL_ARGS_LEVEL (args, cur_depth);
7824
7825           if (l == error_mark_node)
7826             return error_mark_node;
7827
7828           SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
7829         }
7830     }
7831   else
7832     coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
7833                                           args, in_decl, complain,
7834                                           require_all_args,
7835                                           use_default_args);
7836   return coerced_args;
7837 }
7838
7839 /* Returns 1 if template args OT and NT are equivalent.  */
7840
7841 int
7842 template_args_equal (tree ot, tree nt)
7843 {
7844   if (nt == ot)
7845     return 1;
7846   if (nt == NULL_TREE || ot == NULL_TREE)
7847     return false;
7848
7849   if (TREE_CODE (nt) == TREE_VEC)
7850     /* For member templates */
7851     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
7852   else if (PACK_EXPANSION_P (ot))
7853     return (PACK_EXPANSION_P (nt)
7854             && template_args_equal (PACK_EXPANSION_PATTERN (ot),
7855                                     PACK_EXPANSION_PATTERN (nt))
7856             && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
7857                                     PACK_EXPANSION_EXTRA_ARGS (nt)));
7858   else if (ARGUMENT_PACK_P (ot))
7859     {
7860       int i, len;
7861       tree opack, npack;
7862
7863       if (!ARGUMENT_PACK_P (nt))
7864         return 0;
7865
7866       opack = ARGUMENT_PACK_ARGS (ot);
7867       npack = ARGUMENT_PACK_ARGS (nt);
7868       len = TREE_VEC_LENGTH (opack);
7869       if (TREE_VEC_LENGTH (npack) != len)
7870         return 0;
7871       for (i = 0; i < len; ++i)
7872         if (!template_args_equal (TREE_VEC_ELT (opack, i),
7873                                   TREE_VEC_ELT (npack, i)))
7874           return 0;
7875       return 1;
7876     }
7877   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
7878     {
7879       /* We get here probably because we are in the middle of substituting
7880          into the pattern of a pack expansion. In that case the
7881          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
7882          interested in. So we want to use the initial pack argument for
7883          the comparison.  */
7884       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
7885       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
7886         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
7887       return template_args_equal (ot, nt);
7888     }
7889   else if (TYPE_P (nt))
7890     {
7891       if (!TYPE_P (ot))
7892         return false;
7893       /* Don't treat an alias template specialization with dependent
7894          arguments as equivalent to its underlying type when used as a
7895          template argument; we need them to be distinct so that we
7896          substitute into the specialization arguments at instantiation
7897          time.  And aliases can't be equivalent without being ==, so
7898          we don't need to look any deeper.  */
7899       if (TYPE_ALIAS_P (nt) || TYPE_ALIAS_P (ot))
7900         return false;
7901       else
7902         return same_type_p (ot, nt);
7903     }
7904   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
7905     return 0;
7906   else
7907     {
7908       /* Try to treat a template non-type argument that has been converted
7909          to the parameter type as equivalent to one that hasn't yet.  */
7910       for (enum tree_code code1 = TREE_CODE (ot);
7911            CONVERT_EXPR_CODE_P (code1)
7912              || code1 == NON_LVALUE_EXPR;
7913            code1 = TREE_CODE (ot))
7914         ot = TREE_OPERAND (ot, 0);
7915       for (enum tree_code code2 = TREE_CODE (nt);
7916            CONVERT_EXPR_CODE_P (code2)
7917              || code2 == NON_LVALUE_EXPR;
7918            code2 = TREE_CODE (nt))
7919         nt = TREE_OPERAND (nt, 0);
7920
7921       return cp_tree_equal (ot, nt);
7922     }
7923 }
7924
7925 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
7926    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
7927    NEWARG_PTR with the offending arguments if they are non-NULL.  */
7928
7929 int
7930 comp_template_args (tree oldargs, tree newargs,
7931                     tree *oldarg_ptr, tree *newarg_ptr)
7932 {
7933   int i;
7934
7935   if (oldargs == newargs)
7936     return 1;
7937
7938   if (!oldargs || !newargs)
7939     return 0;
7940
7941   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
7942     return 0;
7943
7944   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
7945     {
7946       tree nt = TREE_VEC_ELT (newargs, i);
7947       tree ot = TREE_VEC_ELT (oldargs, i);
7948
7949       if (! template_args_equal (ot, nt))
7950         {
7951           if (oldarg_ptr != NULL)
7952             *oldarg_ptr = ot;
7953           if (newarg_ptr != NULL)
7954             *newarg_ptr = nt;
7955           return 0;
7956         }
7957     }
7958   return 1;
7959 }
7960
7961 static void
7962 add_pending_template (tree d)
7963 {
7964   tree ti = (TYPE_P (d)
7965              ? CLASSTYPE_TEMPLATE_INFO (d)
7966              : DECL_TEMPLATE_INFO (d));
7967   struct pending_template *pt;
7968   int level;
7969
7970   if (TI_PENDING_TEMPLATE_FLAG (ti))
7971     return;
7972
7973   /* We are called both from instantiate_decl, where we've already had a
7974      tinst_level pushed, and instantiate_template, where we haven't.
7975      Compensate.  */
7976   level = !current_tinst_level || current_tinst_level->decl != d;
7977
7978   if (level)
7979     push_tinst_level (d);
7980
7981   pt = ggc_alloc<pending_template> ();
7982   pt->next = NULL;
7983   pt->tinst = current_tinst_level;
7984   if (last_pending_template)
7985     last_pending_template->next = pt;
7986   else
7987     pending_templates = pt;
7988
7989   last_pending_template = pt;
7990
7991   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
7992
7993   if (level)
7994     pop_tinst_level ();
7995 }
7996
7997
7998 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
7999    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
8000    documentation for TEMPLATE_ID_EXPR.  */
8001
8002 tree
8003 lookup_template_function (tree fns, tree arglist)
8004 {
8005   tree type;
8006
8007   if (fns == error_mark_node || arglist == error_mark_node)
8008     return error_mark_node;
8009
8010   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
8011
8012   if (!is_overloaded_fn (fns) && !identifier_p (fns))
8013     {
8014       error ("%q#D is not a function template", fns);
8015       return error_mark_node;
8016     }
8017
8018   if (BASELINK_P (fns))
8019     {
8020       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
8021                                          unknown_type_node,
8022                                          BASELINK_FUNCTIONS (fns),
8023                                          arglist);
8024       return fns;
8025     }
8026
8027   type = TREE_TYPE (fns);
8028   if (TREE_CODE (fns) == OVERLOAD || !type)
8029     type = unknown_type_node;
8030
8031   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
8032 }
8033
8034 /* Within the scope of a template class S<T>, the name S gets bound
8035    (in build_self_reference) to a TYPE_DECL for the class, not a
8036    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
8037    or one of its enclosing classes, and that type is a template,
8038    return the associated TEMPLATE_DECL.  Otherwise, the original
8039    DECL is returned.
8040
8041    Also handle the case when DECL is a TREE_LIST of ambiguous
8042    injected-class-names from different bases.  */
8043
8044 tree
8045 maybe_get_template_decl_from_type_decl (tree decl)
8046 {
8047   if (decl == NULL_TREE)
8048     return decl;
8049
8050   /* DR 176: A lookup that finds an injected-class-name (10.2
8051      [class.member.lookup]) can result in an ambiguity in certain cases
8052      (for example, if it is found in more than one base class). If all of
8053      the injected-class-names that are found refer to specializations of
8054      the same class template, and if the name is followed by a
8055      template-argument-list, the reference refers to the class template
8056      itself and not a specialization thereof, and is not ambiguous.  */
8057   if (TREE_CODE (decl) == TREE_LIST)
8058     {
8059       tree t, tmpl = NULL_TREE;
8060       for (t = decl; t; t = TREE_CHAIN (t))
8061         {
8062           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
8063           if (!tmpl)
8064             tmpl = elt;
8065           else if (tmpl != elt)
8066             break;
8067         }
8068       if (tmpl && t == NULL_TREE)
8069         return tmpl;
8070       else
8071         return decl;
8072     }
8073
8074   return (decl != NULL_TREE
8075           && DECL_SELF_REFERENCE_P (decl)
8076           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
8077     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
8078 }
8079
8080 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
8081    parameters, find the desired type.
8082
8083    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
8084
8085    IN_DECL, if non-NULL, is the template declaration we are trying to
8086    instantiate.
8087
8088    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
8089    the class we are looking up.
8090
8091    Issue error and warning messages under control of COMPLAIN.
8092
8093    If the template class is really a local class in a template
8094    function, then the FUNCTION_CONTEXT is the function in which it is
8095    being instantiated.
8096
8097    ??? Note that this function is currently called *twice* for each
8098    template-id: the first time from the parser, while creating the
8099    incomplete type (finish_template_type), and the second type during the
8100    real instantiation (instantiate_template_class). This is surely something
8101    that we want to avoid. It also causes some problems with argument
8102    coercion (see convert_nontype_argument for more information on this).  */
8103
8104 static tree
8105 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
8106                          int entering_scope, tsubst_flags_t complain)
8107 {
8108   tree templ = NULL_TREE, parmlist;
8109   tree t;
8110   spec_entry **slot;
8111   spec_entry *entry;
8112   spec_entry elt;
8113   hashval_t hash;
8114
8115   if (identifier_p (d1))
8116     {
8117       tree value = innermost_non_namespace_value (d1);
8118       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
8119         templ = value;
8120       else
8121         {
8122           if (context)
8123             push_decl_namespace (context);
8124           templ = lookup_name (d1);
8125           templ = maybe_get_template_decl_from_type_decl (templ);
8126           if (context)
8127             pop_decl_namespace ();
8128         }
8129       if (templ)
8130         context = DECL_CONTEXT (templ);
8131     }
8132   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
8133     {
8134       tree type = TREE_TYPE (d1);
8135
8136       /* If we are declaring a constructor, say A<T>::A<T>, we will get
8137          an implicit typename for the second A.  Deal with it.  */
8138       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
8139         type = TREE_TYPE (type);
8140
8141       if (CLASSTYPE_TEMPLATE_INFO (type))
8142         {
8143           templ = CLASSTYPE_TI_TEMPLATE (type);
8144           d1 = DECL_NAME (templ);
8145         }
8146     }
8147   else if (TREE_CODE (d1) == ENUMERAL_TYPE
8148            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
8149     {
8150       templ = TYPE_TI_TEMPLATE (d1);
8151       d1 = DECL_NAME (templ);
8152     }
8153   else if (DECL_TYPE_TEMPLATE_P (d1))
8154     {
8155       templ = d1;
8156       d1 = DECL_NAME (templ);
8157       context = DECL_CONTEXT (templ);
8158     }
8159   else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
8160     {
8161       templ = d1;
8162       d1 = DECL_NAME (templ);
8163     }
8164
8165   /* Issue an error message if we didn't find a template.  */
8166   if (! templ)
8167     {
8168       if (complain & tf_error)
8169         error ("%qT is not a template", d1);
8170       return error_mark_node;
8171     }
8172
8173   if (TREE_CODE (templ) != TEMPLATE_DECL
8174          /* Make sure it's a user visible template, if it was named by
8175             the user.  */
8176       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
8177           && !PRIMARY_TEMPLATE_P (templ)))
8178     {
8179       if (complain & tf_error)
8180         {
8181           error ("non-template type %qT used as a template", d1);
8182           if (in_decl)
8183             error ("for template declaration %q+D", in_decl);
8184         }
8185       return error_mark_node;
8186     }
8187
8188   complain &= ~tf_user;
8189
8190   /* An alias that just changes the name of a template is equivalent to the
8191      other template, so if any of the arguments are pack expansions, strip
8192      the alias to avoid problems with a pack expansion passed to a non-pack
8193      alias template parameter (DR 1430).  */
8194   if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
8195     templ = get_underlying_template (templ);
8196
8197   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
8198     {
8199       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
8200          template arguments */
8201
8202       tree parm;
8203       tree arglist2;
8204       tree outer;
8205
8206       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
8207
8208       /* Consider an example where a template template parameter declared as
8209
8210            template <class T, class U = std::allocator<T> > class TT
8211
8212          The template parameter level of T and U are one level larger than
8213          of TT.  To proper process the default argument of U, say when an
8214          instantiation `TT<int>' is seen, we need to build the full
8215          arguments containing {int} as the innermost level.  Outer levels,
8216          available when not appearing as default template argument, can be
8217          obtained from the arguments of the enclosing template.
8218
8219          Suppose that TT is later substituted with std::vector.  The above
8220          instantiation is `TT<int, std::allocator<T> >' with TT at
8221          level 1, and T at level 2, while the template arguments at level 1
8222          becomes {std::vector} and the inner level 2 is {int}.  */
8223
8224       outer = DECL_CONTEXT (templ);
8225       if (outer)
8226         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
8227       else if (current_template_parms)
8228         {
8229           /* This is an argument of the current template, so we haven't set
8230              DECL_CONTEXT yet.  */
8231           tree relevant_template_parms;
8232
8233           /* Parameter levels that are greater than the level of the given
8234              template template parm are irrelevant.  */
8235           relevant_template_parms = current_template_parms;
8236           while (TMPL_PARMS_DEPTH (relevant_template_parms)
8237                  != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
8238             relevant_template_parms = TREE_CHAIN (relevant_template_parms);
8239
8240           outer = template_parms_to_args (relevant_template_parms);
8241         }
8242
8243       if (outer)
8244         arglist = add_to_template_args (outer, arglist);
8245
8246       arglist2 = coerce_template_parms (parmlist, arglist, templ,
8247                                         complain,
8248                                         /*require_all_args=*/true,
8249                                         /*use_default_args=*/true);
8250       if (arglist2 == error_mark_node
8251           || (!uses_template_parms (arglist2)
8252               && check_instantiated_args (templ, arglist2, complain)))
8253         return error_mark_node;
8254
8255       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
8256       return parm;
8257     }
8258   else
8259     {
8260       tree template_type = TREE_TYPE (templ);
8261       tree gen_tmpl;
8262       tree type_decl;
8263       tree found = NULL_TREE;
8264       int arg_depth;
8265       int parm_depth;
8266       int is_dependent_type;
8267       int use_partial_inst_tmpl = false;
8268
8269       if (template_type == error_mark_node)
8270         /* An error occurred while building the template TEMPL, and a
8271            diagnostic has most certainly been emitted for that
8272            already.  Let's propagate that error.  */
8273         return error_mark_node;
8274
8275       gen_tmpl = most_general_template (templ);
8276       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
8277       parm_depth = TMPL_PARMS_DEPTH (parmlist);
8278       arg_depth = TMPL_ARGS_DEPTH (arglist);
8279
8280       if (arg_depth == 1 && parm_depth > 1)
8281         {
8282           /* We've been given an incomplete set of template arguments.
8283              For example, given:
8284
8285                template <class T> struct S1 {
8286                  template <class U> struct S2 {};
8287                  template <class U> struct S2<U*> {};
8288                 };
8289
8290              we will be called with an ARGLIST of `U*', but the
8291              TEMPLATE will be `template <class T> template
8292              <class U> struct S1<T>::S2'.  We must fill in the missing
8293              arguments.  */
8294           arglist
8295             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
8296                                            arglist);
8297           arg_depth = TMPL_ARGS_DEPTH (arglist);
8298         }
8299
8300       /* Now we should have enough arguments.  */
8301       gcc_assert (parm_depth == arg_depth);
8302
8303       /* From here on, we're only interested in the most general
8304          template.  */
8305
8306       /* Calculate the BOUND_ARGS.  These will be the args that are
8307          actually tsubst'd into the definition to create the
8308          instantiation.  */
8309       arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
8310                                                  complain,
8311                                                  /*require_all_args=*/true,
8312                                                  /*use_default_args=*/true);
8313
8314       if (arglist == error_mark_node)
8315         /* We were unable to bind the arguments.  */
8316         return error_mark_node;
8317
8318       /* In the scope of a template class, explicit references to the
8319          template class refer to the type of the template, not any
8320          instantiation of it.  For example, in:
8321
8322            template <class T> class C { void f(C<T>); }
8323
8324          the `C<T>' is just the same as `C'.  Outside of the
8325          class, however, such a reference is an instantiation.  */
8326       if ((entering_scope
8327            || !PRIMARY_TEMPLATE_P (gen_tmpl)
8328            || currently_open_class (template_type))
8329           /* comp_template_args is expensive, check it last.  */
8330           && comp_template_args (TYPE_TI_ARGS (template_type),
8331                                  arglist))
8332         return template_type;
8333
8334       /* If we already have this specialization, return it.  */
8335       elt.tmpl = gen_tmpl;
8336       elt.args = arglist;
8337       elt.spec = NULL_TREE;
8338       hash = spec_hasher::hash (&elt);
8339       entry = type_specializations->find_with_hash (&elt, hash);
8340
8341       if (entry)
8342         return entry->spec;
8343
8344       /* If the the template's constraints are not satisfied,
8345          then we cannot form a valid type.
8346
8347          Note that the check is deferred until after the hash
8348          lookup. This prevents redundant checks on previously
8349          instantiated specializations. */
8350       if (flag_concepts && !constraints_satisfied_p (gen_tmpl, arglist))
8351         {
8352           if (complain & tf_error)
8353             {
8354               error ("template constraint failure");
8355               diagnose_constraints (input_location, gen_tmpl, arglist);
8356             }
8357           return error_mark_node;
8358         }
8359
8360       is_dependent_type = uses_template_parms (arglist);
8361
8362       /* If the deduced arguments are invalid, then the binding
8363          failed.  */
8364       if (!is_dependent_type
8365           && check_instantiated_args (gen_tmpl,
8366                                       INNERMOST_TEMPLATE_ARGS (arglist),
8367                                       complain))
8368         return error_mark_node;
8369
8370       if (!is_dependent_type
8371           && !PRIMARY_TEMPLATE_P (gen_tmpl)
8372           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
8373           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
8374         {
8375           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
8376                                       DECL_NAME (gen_tmpl),
8377                                       /*tag_scope=*/ts_global);
8378           return found;
8379         }
8380
8381       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
8382                         complain, in_decl);
8383       if (context == error_mark_node)
8384         return error_mark_node;
8385
8386       if (!context)
8387         context = global_namespace;
8388
8389       /* Create the type.  */
8390       if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
8391         {
8392           /* The user referred to a specialization of an alias
8393             template represented by GEN_TMPL.
8394
8395             [temp.alias]/2 says:
8396
8397                 When a template-id refers to the specialization of an
8398                 alias template, it is equivalent to the associated
8399                 type obtained by substitution of its
8400                 template-arguments for the template-parameters in the
8401                 type-id of the alias template.  */
8402
8403           t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
8404           /* Note that the call above (by indirectly calling
8405              register_specialization in tsubst_decl) registers the
8406              TYPE_DECL representing the specialization of the alias
8407              template.  So next time someone substitutes ARGLIST for
8408              the template parms into the alias template (GEN_TMPL),
8409              she'll get that TYPE_DECL back.  */
8410
8411           if (t == error_mark_node)
8412             return t;
8413         }
8414       else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
8415         {
8416           if (!is_dependent_type)
8417             {
8418               set_current_access_from_decl (TYPE_NAME (template_type));
8419               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
8420                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
8421                                       arglist, complain, in_decl),
8422                               tsubst_attributes (TYPE_ATTRIBUTES (template_type),
8423                                                  arglist, complain, in_decl),
8424                               SCOPED_ENUM_P (template_type), NULL);
8425
8426               if (t == error_mark_node)
8427                 return t;
8428             }
8429           else
8430             {
8431               /* We don't want to call start_enum for this type, since
8432                  the values for the enumeration constants may involve
8433                  template parameters.  And, no one should be interested
8434                  in the enumeration constants for such a type.  */
8435               t = cxx_make_type (ENUMERAL_TYPE);
8436               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
8437             }
8438           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
8439           ENUM_FIXED_UNDERLYING_TYPE_P (t)
8440             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
8441         }
8442       else if (CLASS_TYPE_P (template_type))
8443         {
8444           t = make_class_type (TREE_CODE (template_type));
8445           CLASSTYPE_DECLARED_CLASS (t)
8446             = CLASSTYPE_DECLARED_CLASS (template_type);
8447           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
8448           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
8449
8450           /* A local class.  Make sure the decl gets registered properly.  */
8451           if (context == current_function_decl)
8452             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
8453
8454           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
8455             /* This instantiation is another name for the primary
8456                template type. Set the TYPE_CANONICAL field
8457                appropriately. */
8458             TYPE_CANONICAL (t) = template_type;
8459           else if (any_template_arguments_need_structural_equality_p (arglist))
8460             /* Some of the template arguments require structural
8461                equality testing, so this template class requires
8462                structural equality testing. */
8463             SET_TYPE_STRUCTURAL_EQUALITY (t);
8464         }
8465       else
8466         gcc_unreachable ();
8467
8468       /* If we called start_enum or pushtag above, this information
8469          will already be set up.  */
8470       if (!TYPE_NAME (t))
8471         {
8472           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
8473
8474           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
8475           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
8476           DECL_SOURCE_LOCATION (type_decl)
8477             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
8478         }
8479       else
8480         type_decl = TYPE_NAME (t);
8481
8482       if (CLASS_TYPE_P (template_type))
8483         {
8484           TREE_PRIVATE (type_decl)
8485             = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
8486           TREE_PROTECTED (type_decl)
8487             = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
8488           if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
8489             {
8490               DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
8491               DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
8492             }
8493         }
8494
8495       if (OVERLOAD_TYPE_P (t)
8496           && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
8497         {
8498           static const char *tags[] = {"abi_tag", "may_alias"};
8499
8500           for (unsigned ix = 0; ix != 2; ix++)
8501             {
8502               tree attributes
8503                 = lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
8504
8505               if (attributes)
8506                 TYPE_ATTRIBUTES (t)
8507                   = tree_cons (TREE_PURPOSE (attributes),
8508                                TREE_VALUE (attributes),
8509                                TYPE_ATTRIBUTES (t));
8510             }
8511         }
8512
8513       /* Let's consider the explicit specialization of a member
8514          of a class template specialization that is implicitly instantiated,
8515          e.g.:
8516              template<class T>
8517              struct S
8518              {
8519                template<class U> struct M {}; //#0
8520              };
8521
8522              template<>
8523              template<>
8524              struct S<int>::M<char> //#1
8525              {
8526                int i;
8527              };
8528         [temp.expl.spec]/4 says this is valid.
8529
8530         In this case, when we write:
8531         S<int>::M<char> m;
8532
8533         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
8534         the one of #0.
8535
8536         When we encounter #1, we want to store the partial instantiation
8537         of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
8538
8539         For all cases other than this "explicit specialization of member of a
8540         class template", we just want to store the most general template into
8541         the CLASSTYPE_TI_TEMPLATE of M.
8542
8543         This case of "explicit specialization of member of a class template"
8544         only happens when:
8545         1/ the enclosing class is an instantiation of, and therefore not
8546         the same as, the context of the most general template, and
8547         2/ we aren't looking at the partial instantiation itself, i.e.
8548         the innermost arguments are not the same as the innermost parms of
8549         the most general template.
8550
8551         So it's only when 1/ and 2/ happens that we want to use the partial
8552         instantiation of the member template in lieu of its most general
8553         template.  */
8554
8555       if (PRIMARY_TEMPLATE_P (gen_tmpl)
8556           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
8557           /* the enclosing class must be an instantiation...  */
8558           && CLASS_TYPE_P (context)
8559           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
8560         {
8561           tree partial_inst_args;
8562           TREE_VEC_LENGTH (arglist)--;
8563           ++processing_template_decl;
8564           partial_inst_args =
8565             tsubst (INNERMOST_TEMPLATE_ARGS
8566                         (TYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
8567                     arglist, complain, NULL_TREE);
8568           --processing_template_decl;
8569           TREE_VEC_LENGTH (arglist)++;
8570           if (partial_inst_args == error_mark_node)
8571             return error_mark_node;
8572           use_partial_inst_tmpl =
8573             /*...and we must not be looking at the partial instantiation
8574              itself. */
8575             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
8576                                  partial_inst_args);
8577         }
8578
8579       if (!use_partial_inst_tmpl)
8580         /* This case is easy; there are no member templates involved.  */
8581         found = gen_tmpl;
8582       else
8583         {
8584           /* This is a full instantiation of a member template.  Find
8585              the partial instantiation of which this is an instance.  */
8586
8587           /* Temporarily reduce by one the number of levels in the ARGLIST
8588              so as to avoid comparing the last set of arguments.  */
8589           TREE_VEC_LENGTH (arglist)--;
8590           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
8591           TREE_VEC_LENGTH (arglist)++;
8592           /* FOUND is either a proper class type, or an alias
8593              template specialization.  In the later case, it's a
8594              TYPE_DECL, resulting from the substituting of arguments
8595              for parameters in the TYPE_DECL of the alias template
8596              done earlier.  So be careful while getting the template
8597              of FOUND.  */
8598           found = TREE_CODE (found) == TEMPLATE_DECL
8599             ? found
8600             : TREE_CODE (found) == TYPE_DECL
8601             ? TYPE_TI_TEMPLATE (TREE_TYPE (found))
8602             : CLASSTYPE_TI_TEMPLATE (found);
8603         }
8604
8605       // Build template info for the new specialization.
8606       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
8607
8608       elt.spec = t;
8609       slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
8610       entry = ggc_alloc<spec_entry> ();
8611       *entry = elt;
8612       *slot = entry;
8613
8614       /* Note this use of the partial instantiation so we can check it
8615          later in maybe_process_partial_specialization.  */
8616       DECL_TEMPLATE_INSTANTIATIONS (found)
8617         = tree_cons (arglist, t,
8618                      DECL_TEMPLATE_INSTANTIATIONS (found));
8619
8620       if (TREE_CODE (template_type) == ENUMERAL_TYPE && !is_dependent_type
8621           && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
8622         /* Now that the type has been registered on the instantiations
8623            list, we set up the enumerators.  Because the enumeration
8624            constants may involve the enumeration type itself, we make
8625            sure to register the type first, and then create the
8626            constants.  That way, doing tsubst_expr for the enumeration
8627            constants won't result in recursive calls here; we'll find
8628            the instantiation and exit above.  */
8629         tsubst_enum (template_type, t, arglist);
8630
8631       if (CLASS_TYPE_P (template_type) && is_dependent_type)
8632         /* If the type makes use of template parameters, the
8633            code that generates debugging information will crash.  */
8634         DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
8635
8636       /* Possibly limit visibility based on template args.  */
8637       TREE_PUBLIC (type_decl) = 1;
8638       determine_visibility (type_decl);
8639
8640       inherit_targ_abi_tags (t);
8641
8642       return t;
8643     }
8644 }
8645
8646 /* Wrapper for lookup_template_class_1.  */
8647
8648 tree
8649 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
8650                        int entering_scope, tsubst_flags_t complain)
8651 {
8652   tree ret;
8653   timevar_push (TV_TEMPLATE_INST);
8654   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
8655                                  entering_scope, complain);
8656   timevar_pop (TV_TEMPLATE_INST);
8657   return ret;
8658 }
8659
8660 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST.  */
8661
8662 tree
8663 lookup_template_variable (tree templ, tree arglist)
8664 {
8665   /* The type of the expression is NULL_TREE since the template-id could refer
8666      to an explicit or partial specialization. */
8667   tree type = NULL_TREE;
8668   if (flag_concepts && variable_concept_p (templ))
8669     /* Except that concepts are always bool.  */
8670     type = boolean_type_node;
8671   return build2 (TEMPLATE_ID_EXPR, type, templ, arglist);
8672 }
8673
8674 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
8675
8676 tree
8677 finish_template_variable (tree var, tsubst_flags_t complain)
8678 {
8679   tree templ = TREE_OPERAND (var, 0);
8680   tree arglist = TREE_OPERAND (var, 1);
8681
8682   /* We never want to return a VAR_DECL for a variable concept, since they
8683      aren't instantiated.  In a template, leave the TEMPLATE_ID_EXPR alone.  */
8684   bool concept_p = flag_concepts && variable_concept_p (templ);
8685   if (concept_p && processing_template_decl)
8686     return var;
8687
8688   tree tmpl_args = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (templ));
8689   arglist = add_outermost_template_args (tmpl_args, arglist);
8690
8691   tree parms = DECL_TEMPLATE_PARMS (templ);
8692   arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
8693                                              /*req_all*/true,
8694                                              /*use_default*/true);
8695
8696   if (flag_concepts && !constraints_satisfied_p (templ, arglist))
8697     {
8698       if (complain & tf_error)
8699         {
8700           error ("use of invalid variable template %qE", var);
8701           diagnose_constraints (location_of (var), templ, arglist);
8702         }
8703       return error_mark_node;
8704     }
8705
8706   /* If a template-id refers to a specialization of a variable
8707      concept, then the expression is true if and only if the
8708      concept's constraints are satisfied by the given template
8709      arguments.
8710
8711      NOTE: This is an extension of Concepts Lite TS that
8712      allows constraints to be used in expressions. */
8713   if (concept_p)
8714     {
8715       tree decl = DECL_TEMPLATE_RESULT (templ);
8716       return evaluate_variable_concept (decl, arglist);
8717     }
8718
8719   return instantiate_template (templ, arglist, complain);
8720 }
8721
8722 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
8723    TARGS template args, and instantiate it if it's not dependent.  */
8724
8725 static tree
8726 lookup_and_finish_template_variable (tree templ, tree targs,
8727                                      tsubst_flags_t complain)
8728 {
8729   templ = lookup_template_variable (templ, targs);
8730   if (!any_dependent_template_arguments_p (targs))
8731     {
8732       templ = finish_template_variable (templ, complain);
8733       mark_used (templ);
8734     }
8735
8736   return convert_from_reference (templ);
8737 }
8738
8739 \f
8740 struct pair_fn_data
8741 {
8742   tree_fn_t fn;
8743   void *data;
8744   /* True when we should also visit template parameters that occur in
8745      non-deduced contexts.  */
8746   bool include_nondeduced_p;
8747   hash_set<tree> *visited;
8748 };
8749
8750 /* Called from for_each_template_parm via walk_tree.  */
8751
8752 static tree
8753 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
8754 {
8755   tree t = *tp;
8756   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
8757   tree_fn_t fn = pfd->fn;
8758   void *data = pfd->data;
8759   tree result = NULL_TREE;
8760
8761 #define WALK_SUBTREE(NODE)                                              \
8762   do                                                                    \
8763     {                                                                   \
8764       result = for_each_template_parm (NODE, fn, data, pfd->visited,    \
8765                                        pfd->include_nondeduced_p);      \
8766       if (result) goto out;                                             \
8767     }                                                                   \
8768   while (0)
8769
8770   if (TYPE_P (t)
8771       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
8772     WALK_SUBTREE (TYPE_CONTEXT (t));
8773
8774   switch (TREE_CODE (t))
8775     {
8776     case RECORD_TYPE:
8777       if (TYPE_PTRMEMFUNC_P (t))
8778         break;
8779       /* Fall through.  */
8780
8781     case UNION_TYPE:
8782     case ENUMERAL_TYPE:
8783       if (!TYPE_TEMPLATE_INFO (t))
8784         *walk_subtrees = 0;
8785       else
8786         WALK_SUBTREE (TYPE_TI_ARGS (t));
8787       break;
8788
8789     case INTEGER_TYPE:
8790       WALK_SUBTREE (TYPE_MIN_VALUE (t));
8791       WALK_SUBTREE (TYPE_MAX_VALUE (t));
8792       break;
8793
8794     case METHOD_TYPE:
8795       /* Since we're not going to walk subtrees, we have to do this
8796          explicitly here.  */
8797       WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
8798       /* Fall through.  */
8799
8800     case FUNCTION_TYPE:
8801       /* Check the return type.  */
8802       WALK_SUBTREE (TREE_TYPE (t));
8803
8804       /* Check the parameter types.  Since default arguments are not
8805          instantiated until they are needed, the TYPE_ARG_TYPES may
8806          contain expressions that involve template parameters.  But,
8807          no-one should be looking at them yet.  And, once they're
8808          instantiated, they don't contain template parameters, so
8809          there's no point in looking at them then, either.  */
8810       {
8811         tree parm;
8812
8813         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
8814           WALK_SUBTREE (TREE_VALUE (parm));
8815
8816         /* Since we've already handled the TYPE_ARG_TYPES, we don't
8817            want walk_tree walking into them itself.  */
8818         *walk_subtrees = 0;
8819       }
8820       break;
8821
8822     case TYPEOF_TYPE:
8823     case UNDERLYING_TYPE:
8824       if (pfd->include_nondeduced_p
8825           && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
8826                                      pfd->visited, 
8827                                      pfd->include_nondeduced_p))
8828         return error_mark_node;
8829       break;
8830
8831     case FUNCTION_DECL:
8832     case VAR_DECL:
8833       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
8834         WALK_SUBTREE (DECL_TI_ARGS (t));
8835       /* Fall through.  */
8836
8837     case PARM_DECL:
8838     case CONST_DECL:
8839       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t))
8840         WALK_SUBTREE (DECL_INITIAL (t));
8841       if (DECL_CONTEXT (t)
8842           && pfd->include_nondeduced_p)
8843         WALK_SUBTREE (DECL_CONTEXT (t));
8844       break;
8845
8846     case BOUND_TEMPLATE_TEMPLATE_PARM:
8847       /* Record template parameters such as `T' inside `TT<T>'.  */
8848       WALK_SUBTREE (TYPE_TI_ARGS (t));
8849       /* Fall through.  */
8850
8851     case TEMPLATE_TEMPLATE_PARM:
8852     case TEMPLATE_TYPE_PARM:
8853     case TEMPLATE_PARM_INDEX:
8854       if (fn && (*fn)(t, data))
8855         return t;
8856       else if (!fn)
8857         return t;
8858       break;
8859
8860     case TEMPLATE_DECL:
8861       /* A template template parameter is encountered.  */
8862       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8863         WALK_SUBTREE (TREE_TYPE (t));
8864
8865       /* Already substituted template template parameter */
8866       *walk_subtrees = 0;
8867       break;
8868
8869     case TYPENAME_TYPE:
8870       /* A template-id in a TYPENAME_TYPE might be a deduced context after
8871          partial instantiation.  */
8872       WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
8873       break;
8874
8875     case CONSTRUCTOR:
8876       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
8877           && pfd->include_nondeduced_p)
8878         WALK_SUBTREE (TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (t)));
8879       break;
8880
8881     case INDIRECT_REF:
8882     case COMPONENT_REF:
8883       /* If there's no type, then this thing must be some expression
8884          involving template parameters.  */
8885       if (!fn && !TREE_TYPE (t))
8886         return error_mark_node;
8887       break;
8888
8889     case MODOP_EXPR:
8890     case CAST_EXPR:
8891     case IMPLICIT_CONV_EXPR:
8892     case REINTERPRET_CAST_EXPR:
8893     case CONST_CAST_EXPR:
8894     case STATIC_CAST_EXPR:
8895     case DYNAMIC_CAST_EXPR:
8896     case ARROW_EXPR:
8897     case DOTSTAR_EXPR:
8898     case TYPEID_EXPR:
8899     case PSEUDO_DTOR_EXPR:
8900       if (!fn)
8901         return error_mark_node;
8902       break;
8903
8904     default:
8905       break;
8906     }
8907
8908   #undef WALK_SUBTREE
8909
8910   /* We didn't find any template parameters we liked.  */
8911  out:
8912   return result;
8913 }
8914
8915 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
8916    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
8917    call FN with the parameter and the DATA.
8918    If FN returns nonzero, the iteration is terminated, and
8919    for_each_template_parm returns 1.  Otherwise, the iteration
8920    continues.  If FN never returns a nonzero value, the value
8921    returned by for_each_template_parm is 0.  If FN is NULL, it is
8922    considered to be the function which always returns 1.
8923
8924    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
8925    parameters that occur in non-deduced contexts.  When false, only
8926    visits those template parameters that can be deduced.  */
8927
8928 static tree
8929 for_each_template_parm (tree t, tree_fn_t fn, void* data,
8930                         hash_set<tree> *visited,
8931                         bool include_nondeduced_p)
8932 {
8933   struct pair_fn_data pfd;
8934   tree result;
8935
8936   /* Set up.  */
8937   pfd.fn = fn;
8938   pfd.data = data;
8939   pfd.include_nondeduced_p = include_nondeduced_p;
8940
8941   /* Walk the tree.  (Conceptually, we would like to walk without
8942      duplicates, but for_each_template_parm_r recursively calls
8943      for_each_template_parm, so we would need to reorganize a fair
8944      bit to use walk_tree_without_duplicates, so we keep our own
8945      visited list.)  */
8946   if (visited)
8947     pfd.visited = visited;
8948   else
8949     pfd.visited = new hash_set<tree>;
8950   result = cp_walk_tree (&t,
8951                          for_each_template_parm_r,
8952                          &pfd,
8953                          pfd.visited);
8954
8955   /* Clean up.  */
8956   if (!visited)
8957     {
8958       delete pfd.visited;
8959       pfd.visited = 0;
8960     }
8961
8962   return result;
8963 }
8964
8965 /* Returns true if T depends on any template parameter.  */
8966
8967 int
8968 uses_template_parms (tree t)
8969 {
8970   if (t == NULL_TREE)
8971     return false;
8972
8973   bool dependent_p;
8974   int saved_processing_template_decl;
8975
8976   saved_processing_template_decl = processing_template_decl;
8977   if (!saved_processing_template_decl)
8978     processing_template_decl = 1;
8979   if (TYPE_P (t))
8980     dependent_p = dependent_type_p (t);
8981   else if (TREE_CODE (t) == TREE_VEC)
8982     dependent_p = any_dependent_template_arguments_p (t);
8983   else if (TREE_CODE (t) == TREE_LIST)
8984     dependent_p = (uses_template_parms (TREE_VALUE (t))
8985                    || uses_template_parms (TREE_CHAIN (t)));
8986   else if (TREE_CODE (t) == TYPE_DECL)
8987     dependent_p = dependent_type_p (TREE_TYPE (t));
8988   else if (DECL_P (t)
8989            || EXPR_P (t)
8990            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
8991            || TREE_CODE (t) == OVERLOAD
8992            || BASELINK_P (t)
8993            || identifier_p (t)
8994            || TREE_CODE (t) == TRAIT_EXPR
8995            || TREE_CODE (t) == CONSTRUCTOR
8996            || CONSTANT_CLASS_P (t))
8997     dependent_p = (type_dependent_expression_p (t)
8998                    || value_dependent_expression_p (t));
8999   else
9000     {
9001       gcc_assert (t == error_mark_node);
9002       dependent_p = false;
9003     }
9004
9005   processing_template_decl = saved_processing_template_decl;
9006
9007   return dependent_p;
9008 }
9009
9010 /* Returns true iff current_function_decl is an incompletely instantiated
9011    template.  Useful instead of processing_template_decl because the latter
9012    is set to 0 during instantiate_non_dependent_expr.  */
9013
9014 bool
9015 in_template_function (void)
9016 {
9017   tree fn = current_function_decl;
9018   bool ret;
9019   ++processing_template_decl;
9020   ret = (fn && DECL_LANG_SPECIFIC (fn)
9021          && DECL_TEMPLATE_INFO (fn)
9022          && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
9023   --processing_template_decl;
9024   return ret;
9025 }
9026
9027 /* Returns true if T depends on any template parameter with level LEVEL.  */
9028
9029 bool
9030 uses_template_parms_level (tree t, int level)
9031 {
9032   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
9033                                  /*include_nondeduced_p=*/true);
9034 }
9035
9036 /* Returns TRUE iff INST is an instantiation we don't need to do in an
9037    ill-formed translation unit, i.e. a variable or function that isn't
9038    usable in a constant expression.  */
9039
9040 static inline bool
9041 neglectable_inst_p (tree d)
9042 {
9043   return (DECL_P (d)
9044           && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
9045                : decl_maybe_constant_var_p (d)));
9046 }
9047
9048 /* Returns TRUE iff we should refuse to instantiate DECL because it's
9049    neglectable and instantiated from within an erroneous instantiation.  */
9050
9051 static bool
9052 limit_bad_template_recursion (tree decl)
9053 {
9054   struct tinst_level *lev = current_tinst_level;
9055   int errs = errorcount + sorrycount;
9056   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
9057     return false;
9058
9059   for (; lev; lev = lev->next)
9060     if (neglectable_inst_p (lev->decl))
9061       break;
9062
9063   return (lev && errs > lev->errors);
9064 }
9065
9066 static int tinst_depth;
9067 extern int max_tinst_depth;
9068 int depth_reached;
9069
9070 static GTY(()) struct tinst_level *last_error_tinst_level;
9071
9072 /* We're starting to instantiate D; record the template instantiation context
9073    for diagnostics and to restore it later.  */
9074
9075 bool
9076 push_tinst_level (tree d)
9077 {
9078   return push_tinst_level_loc (d, input_location);
9079 }
9080
9081 /* We're starting to instantiate D; record the template instantiation context
9082    at LOC for diagnostics and to restore it later.  */
9083
9084 bool
9085 push_tinst_level_loc (tree d, location_t loc)
9086 {
9087   struct tinst_level *new_level;
9088
9089   if (tinst_depth >= max_tinst_depth)
9090     {
9091       /* Tell error.c not to try to instantiate any templates.  */
9092       at_eof = 2;
9093       fatal_error (input_location,
9094                    "template instantiation depth exceeds maximum of %d"
9095                    " (use -ftemplate-depth= to increase the maximum)",
9096                    max_tinst_depth);
9097       return false;
9098     }
9099
9100   /* If the current instantiation caused problems, don't let it instantiate
9101      anything else.  Do allow deduction substitution and decls usable in
9102      constant expressions.  */
9103   if (limit_bad_template_recursion (d))
9104     return false;
9105
9106   new_level = ggc_alloc<tinst_level> ();
9107   new_level->decl = d;
9108   new_level->locus = loc;
9109   new_level->errors = errorcount+sorrycount;
9110   new_level->in_system_header_p = in_system_header_at (input_location);
9111   new_level->next = current_tinst_level;
9112   current_tinst_level = new_level;
9113
9114   ++tinst_depth;
9115   if (GATHER_STATISTICS && (tinst_depth > depth_reached))
9116     depth_reached = tinst_depth;
9117
9118   return true;
9119 }
9120
9121 /* We're done instantiating this template; return to the instantiation
9122    context.  */
9123
9124 void
9125 pop_tinst_level (void)
9126 {
9127   /* Restore the filename and line number stashed away when we started
9128      this instantiation.  */
9129   input_location = current_tinst_level->locus;
9130   current_tinst_level = current_tinst_level->next;
9131   --tinst_depth;
9132 }
9133
9134 /* We're instantiating a deferred template; restore the template
9135    instantiation context in which the instantiation was requested, which
9136    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
9137
9138 static tree
9139 reopen_tinst_level (struct tinst_level *level)
9140 {
9141   struct tinst_level *t;
9142
9143   tinst_depth = 0;
9144   for (t = level; t; t = t->next)
9145     ++tinst_depth;
9146
9147   current_tinst_level = level;
9148   pop_tinst_level ();
9149   if (current_tinst_level)
9150     current_tinst_level->errors = errorcount+sorrycount;
9151   return level->decl;
9152 }
9153
9154 /* Returns the TINST_LEVEL which gives the original instantiation
9155    context.  */
9156
9157 struct tinst_level *
9158 outermost_tinst_level (void)
9159 {
9160   struct tinst_level *level = current_tinst_level;
9161   if (level)
9162     while (level->next)
9163       level = level->next;
9164   return level;
9165 }
9166
9167 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
9168    vector of template arguments, as for tsubst.
9169
9170    Returns an appropriate tsubst'd friend declaration.  */
9171
9172 static tree
9173 tsubst_friend_function (tree decl, tree args)
9174 {
9175   tree new_friend;
9176
9177   if (TREE_CODE (decl) == FUNCTION_DECL
9178       && DECL_TEMPLATE_INSTANTIATION (decl)
9179       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
9180     /* This was a friend declared with an explicit template
9181        argument list, e.g.:
9182
9183        friend void f<>(T);
9184
9185        to indicate that f was a template instantiation, not a new
9186        function declaration.  Now, we have to figure out what
9187        instantiation of what template.  */
9188     {
9189       tree template_id, arglist, fns;
9190       tree new_args;
9191       tree tmpl;
9192       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
9193
9194       /* Friend functions are looked up in the containing namespace scope.
9195          We must enter that scope, to avoid finding member functions of the
9196          current class with same name.  */
9197       push_nested_namespace (ns);
9198       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
9199                          tf_warning_or_error, NULL_TREE,
9200                          /*integral_constant_expression_p=*/false);
9201       pop_nested_namespace (ns);
9202       arglist = tsubst (DECL_TI_ARGS (decl), args,
9203                         tf_warning_or_error, NULL_TREE);
9204       template_id = lookup_template_function (fns, arglist);
9205
9206       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
9207       tmpl = determine_specialization (template_id, new_friend,
9208                                        &new_args,
9209                                        /*need_member_template=*/0,
9210                                        TREE_VEC_LENGTH (args),
9211                                        tsk_none);
9212       return instantiate_template (tmpl, new_args, tf_error);
9213     }
9214
9215   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
9216
9217   /* The NEW_FRIEND will look like an instantiation, to the
9218      compiler, but is not an instantiation from the point of view of
9219      the language.  For example, we might have had:
9220
9221      template <class T> struct S {
9222        template <class U> friend void f(T, U);
9223      };
9224
9225      Then, in S<int>, template <class U> void f(int, U) is not an
9226      instantiation of anything.  */
9227   if (new_friend == error_mark_node)
9228     return error_mark_node;
9229
9230   DECL_USE_TEMPLATE (new_friend) = 0;
9231   if (TREE_CODE (decl) == TEMPLATE_DECL)
9232     {
9233       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
9234       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
9235         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
9236     }
9237
9238   /* The mangled name for the NEW_FRIEND is incorrect.  The function
9239      is not a template instantiation and should not be mangled like
9240      one.  Therefore, we forget the mangling here; we'll recompute it
9241      later if we need it.  */
9242   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
9243     {
9244       SET_DECL_RTL (new_friend, NULL);
9245       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
9246     }
9247
9248   if (DECL_NAMESPACE_SCOPE_P (new_friend))
9249     {
9250       tree old_decl;
9251       tree new_friend_template_info;
9252       tree new_friend_result_template_info;
9253       tree ns;
9254       int  new_friend_is_defn;
9255
9256       /* We must save some information from NEW_FRIEND before calling
9257          duplicate decls since that function will free NEW_FRIEND if
9258          possible.  */
9259       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
9260       new_friend_is_defn =
9261             (DECL_INITIAL (DECL_TEMPLATE_RESULT
9262                            (template_for_substitution (new_friend)))
9263              != NULL_TREE);
9264       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
9265         {
9266           /* This declaration is a `primary' template.  */
9267           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
9268
9269           new_friend_result_template_info
9270             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
9271         }
9272       else
9273         new_friend_result_template_info = NULL_TREE;
9274
9275       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
9276       if (new_friend_is_defn)
9277         DECL_INITIAL (new_friend) = error_mark_node;
9278
9279       /* Inside pushdecl_namespace_level, we will push into the
9280          current namespace. However, the friend function should go
9281          into the namespace of the template.  */
9282       ns = decl_namespace_context (new_friend);
9283       push_nested_namespace (ns);
9284       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
9285       pop_nested_namespace (ns);
9286
9287       if (old_decl == error_mark_node)
9288         return error_mark_node;
9289
9290       if (old_decl != new_friend)
9291         {
9292           /* This new friend declaration matched an existing
9293              declaration.  For example, given:
9294
9295                template <class T> void f(T);
9296                template <class U> class C {
9297                  template <class T> friend void f(T) {}
9298                };
9299
9300              the friend declaration actually provides the definition
9301              of `f', once C has been instantiated for some type.  So,
9302              old_decl will be the out-of-class template declaration,
9303              while new_friend is the in-class definition.
9304
9305              But, if `f' was called before this point, the
9306              instantiation of `f' will have DECL_TI_ARGS corresponding
9307              to `T' but not to `U', references to which might appear
9308              in the definition of `f'.  Previously, the most general
9309              template for an instantiation of `f' was the out-of-class
9310              version; now it is the in-class version.  Therefore, we
9311              run through all specialization of `f', adding to their
9312              DECL_TI_ARGS appropriately.  In particular, they need a
9313              new set of outer arguments, corresponding to the
9314              arguments for this class instantiation.
9315
9316              The same situation can arise with something like this:
9317
9318                friend void f(int);
9319                template <class T> class C {
9320                  friend void f(T) {}
9321                };
9322
9323              when `C<int>' is instantiated.  Now, `f(int)' is defined
9324              in the class.  */
9325
9326           if (!new_friend_is_defn)
9327             /* On the other hand, if the in-class declaration does
9328                *not* provide a definition, then we don't want to alter
9329                existing definitions.  We can just leave everything
9330                alone.  */
9331             ;
9332           else
9333             {
9334               tree new_template = TI_TEMPLATE (new_friend_template_info);
9335               tree new_args = TI_ARGS (new_friend_template_info);
9336
9337               /* Overwrite whatever template info was there before, if
9338                  any, with the new template information pertaining to
9339                  the declaration.  */
9340               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
9341
9342               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
9343                 {
9344                   /* We should have called reregister_specialization in
9345                      duplicate_decls.  */
9346                   gcc_assert (retrieve_specialization (new_template,
9347                                                        new_args, 0)
9348                               == old_decl);
9349
9350                   /* Instantiate it if the global has already been used.  */
9351                   if (DECL_ODR_USED (old_decl))
9352                     instantiate_decl (old_decl, /*defer_ok=*/true,
9353                                       /*expl_inst_class_mem_p=*/false);
9354                 }
9355               else
9356                 {
9357                   tree t;
9358
9359                   /* Indicate that the old function template is a partial
9360                      instantiation.  */
9361                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
9362                     = new_friend_result_template_info;
9363
9364                   gcc_assert (new_template
9365                               == most_general_template (new_template));
9366                   gcc_assert (new_template != old_decl);
9367
9368                   /* Reassign any specializations already in the hash table
9369                      to the new more general template, and add the
9370                      additional template args.  */
9371                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
9372                        t != NULL_TREE;
9373                        t = TREE_CHAIN (t))
9374                     {
9375                       tree spec = TREE_VALUE (t);
9376                       spec_entry elt;
9377
9378                       elt.tmpl = old_decl;
9379                       elt.args = DECL_TI_ARGS (spec);
9380                       elt.spec = NULL_TREE;
9381
9382                       decl_specializations->remove_elt (&elt);
9383
9384                       DECL_TI_ARGS (spec)
9385                         = add_outermost_template_args (new_args,
9386                                                        DECL_TI_ARGS (spec));
9387
9388                       register_specialization
9389                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
9390
9391                     }
9392                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
9393                 }
9394             }
9395
9396           /* The information from NEW_FRIEND has been merged into OLD_DECL
9397              by duplicate_decls.  */
9398           new_friend = old_decl;
9399         }
9400     }
9401   else
9402     {
9403       tree context = DECL_CONTEXT (new_friend);
9404       bool dependent_p;
9405
9406       /* In the code
9407            template <class T> class C {
9408              template <class U> friend void C1<U>::f (); // case 1
9409              friend void C2<T>::f ();                    // case 2
9410            };
9411          we only need to make sure CONTEXT is a complete type for
9412          case 2.  To distinguish between the two cases, we note that
9413          CONTEXT of case 1 remains dependent type after tsubst while
9414          this isn't true for case 2.  */
9415       ++processing_template_decl;
9416       dependent_p = dependent_type_p (context);
9417       --processing_template_decl;
9418
9419       if (!dependent_p
9420           && !complete_type_or_else (context, NULL_TREE))
9421         return error_mark_node;
9422
9423       if (COMPLETE_TYPE_P (context))
9424         {
9425           tree fn = new_friend;
9426           /* do_friend adds the TEMPLATE_DECL for any member friend
9427              template even if it isn't a member template, i.e.
9428                template <class T> friend A<T>::f();
9429              Look through it in that case.  */
9430           if (TREE_CODE (fn) == TEMPLATE_DECL
9431               && !PRIMARY_TEMPLATE_P (fn))
9432             fn = DECL_TEMPLATE_RESULT (fn);
9433           /* Check to see that the declaration is really present, and,
9434              possibly obtain an improved declaration.  */
9435           fn = check_classfn (context, fn, NULL_TREE);
9436
9437           if (fn)
9438             new_friend = fn;
9439         }
9440     }
9441
9442   return new_friend;
9443 }
9444
9445 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
9446    template arguments, as for tsubst.
9447
9448    Returns an appropriate tsubst'd friend type or error_mark_node on
9449    failure.  */
9450
9451 static tree
9452 tsubst_friend_class (tree friend_tmpl, tree args)
9453 {
9454   tree friend_type;
9455   tree tmpl;
9456   tree context;
9457
9458   if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
9459     {
9460       tree t = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
9461       return TREE_TYPE (t);
9462     }
9463
9464   context = CP_DECL_CONTEXT (friend_tmpl);
9465
9466   if (context != global_namespace)
9467     {
9468       if (TREE_CODE (context) == NAMESPACE_DECL)
9469         push_nested_namespace (context);
9470       else
9471         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
9472     }
9473
9474   /* Look for a class template declaration.  We look for hidden names
9475      because two friend declarations of the same template are the
9476      same.  For example, in:
9477
9478        struct A { 
9479          template <typename> friend class F;
9480        };
9481        template <typename> struct B { 
9482          template <typename> friend class F;
9483        };
9484
9485      both F templates are the same.  */
9486   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
9487                            /*block_p=*/true, 0, LOOKUP_HIDDEN);
9488
9489   /* But, if we don't find one, it might be because we're in a
9490      situation like this:
9491
9492        template <class T>
9493        struct S {
9494          template <class U>
9495          friend struct S;
9496        };
9497
9498      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
9499      for `S<int>', not the TEMPLATE_DECL.  */
9500   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
9501     {
9502       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
9503       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
9504     }
9505
9506   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
9507     {
9508       /* The friend template has already been declared.  Just
9509          check to see that the declarations match, and install any new
9510          default parameters.  We must tsubst the default parameters,
9511          of course.  We only need the innermost template parameters
9512          because that is all that redeclare_class_template will look
9513          at.  */
9514       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
9515           > TMPL_ARGS_DEPTH (args))
9516         {
9517           tree parms;
9518           location_t saved_input_location;
9519           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
9520                                          args, tf_warning_or_error);
9521
9522           saved_input_location = input_location;
9523           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
9524           tree cons = get_constraints (tmpl);
9525           redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
9526           input_location = saved_input_location;
9527           
9528         }
9529
9530       friend_type = TREE_TYPE (tmpl);
9531     }
9532   else
9533     {
9534       /* The friend template has not already been declared.  In this
9535          case, the instantiation of the template class will cause the
9536          injection of this template into the global scope.  */
9537       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
9538       if (tmpl == error_mark_node)
9539         return error_mark_node;
9540
9541       /* The new TMPL is not an instantiation of anything, so we
9542          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
9543          the new type because that is supposed to be the corresponding
9544          template decl, i.e., TMPL.  */
9545       DECL_USE_TEMPLATE (tmpl) = 0;
9546       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
9547       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
9548       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
9549         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
9550
9551       /* Inject this template into the global scope.  */
9552       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
9553     }
9554
9555   if (context != global_namespace)
9556     {
9557       if (TREE_CODE (context) == NAMESPACE_DECL)
9558         pop_nested_namespace (context);
9559       else
9560         pop_nested_class ();
9561     }
9562
9563   return friend_type;
9564 }
9565
9566 /* Returns zero if TYPE cannot be completed later due to circularity.
9567    Otherwise returns one.  */
9568
9569 static int
9570 can_complete_type_without_circularity (tree type)
9571 {
9572   if (type == NULL_TREE || type == error_mark_node)
9573     return 0;
9574   else if (COMPLETE_TYPE_P (type))
9575     return 1;
9576   else if (TREE_CODE (type) == ARRAY_TYPE)
9577     return can_complete_type_without_circularity (TREE_TYPE (type));
9578   else if (CLASS_TYPE_P (type)
9579            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
9580     return 0;
9581   else
9582     return 1;
9583 }
9584
9585 static tree tsubst_omp_clauses (tree, bool, bool, tree, tsubst_flags_t, tree);
9586
9587 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
9588    T or a new TREE_LIST, possibly a chain in the case of a pack expansion.  */
9589
9590 static tree
9591 tsubst_attribute (tree t, tree *decl_p, tree args,
9592                   tsubst_flags_t complain, tree in_decl)
9593 {
9594   gcc_assert (ATTR_IS_DEPENDENT (t));
9595
9596   tree val = TREE_VALUE (t);
9597   if (val == NULL_TREE)
9598     /* Nothing to do.  */;
9599   else if ((flag_openmp || flag_openmp_simd || flag_cilkplus)
9600            && is_attribute_p ("omp declare simd",
9601                               get_attribute_name (t)))
9602     {
9603       tree clauses = TREE_VALUE (val);
9604       clauses = tsubst_omp_clauses (clauses, true, false, args,
9605                                     complain, in_decl);
9606       c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
9607       clauses = finish_omp_clauses (clauses, false, true);
9608       tree parms = DECL_ARGUMENTS (*decl_p);
9609       clauses
9610         = c_omp_declare_simd_clauses_to_numbers (parms, clauses);
9611       if (clauses)
9612         val = build_tree_list (NULL_TREE, clauses);
9613       else
9614         val = NULL_TREE;
9615     }
9616   /* If the first attribute argument is an identifier, don't
9617      pass it through tsubst.  Attributes like mode, format,
9618      cleanup and several target specific attributes expect it
9619      unmodified.  */
9620   else if (attribute_takes_identifier_p (get_attribute_name (t)))
9621     {
9622       tree chain
9623         = tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
9624                        /*integral_constant_expression_p=*/false);
9625       if (chain != TREE_CHAIN (val))
9626         val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
9627     }
9628   else if (PACK_EXPANSION_P (val))
9629     {
9630       /* An attribute pack expansion.  */
9631       tree purp = TREE_PURPOSE (t);
9632       tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
9633       int len = TREE_VEC_LENGTH (pack);
9634       tree list = NULL_TREE;
9635       tree *q = &list;
9636       for (int i = 0; i < len; ++i)
9637         {
9638           tree elt = TREE_VEC_ELT (pack, i);
9639           *q = build_tree_list (purp, elt);
9640           q = &TREE_CHAIN (*q);
9641         }
9642       return list;
9643     }
9644   else
9645     val = tsubst_expr (val, args, complain, in_decl,
9646                        /*integral_constant_expression_p=*/false);
9647
9648   if (val != TREE_VALUE (t))
9649     return build_tree_list (TREE_PURPOSE (t), val);
9650   return t;
9651 }
9652
9653 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
9654    unchanged or a new TREE_LIST chain.  */
9655
9656 static tree
9657 tsubst_attributes (tree attributes, tree args,
9658                    tsubst_flags_t complain, tree in_decl)
9659 {
9660   tree last_dep = NULL_TREE;
9661
9662   for (tree t = attributes; t; t = TREE_CHAIN (t))
9663     if (ATTR_IS_DEPENDENT (t))
9664       {
9665         last_dep = t;
9666         attributes = copy_list (attributes);
9667         break;
9668       }
9669
9670   if (last_dep)
9671     for (tree *p = &attributes; *p; )
9672       {
9673         tree t = *p;
9674         if (ATTR_IS_DEPENDENT (t))
9675           {
9676             tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
9677             if (subst != t)
9678               {
9679                 *p = subst;
9680                 do
9681                   p = &TREE_CHAIN (*p);
9682                 while (*p);
9683                 *p = TREE_CHAIN (t);
9684                 continue;
9685               }
9686           }
9687         p = &TREE_CHAIN (*p);
9688       }
9689
9690   return attributes;
9691 }
9692
9693 /* Apply any attributes which had to be deferred until instantiation
9694    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
9695    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
9696
9697 static void
9698 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
9699                                 tree args, tsubst_flags_t complain, tree in_decl)
9700 {
9701   tree last_dep = NULL_TREE;
9702   tree t;
9703   tree *p;
9704
9705   for (t = attributes; t; t = TREE_CHAIN (t))
9706     if (ATTR_IS_DEPENDENT (t))
9707       {
9708         last_dep = t;
9709         attributes = copy_list (attributes);
9710         break;
9711       }
9712
9713   if (DECL_P (*decl_p))
9714     {
9715       if (TREE_TYPE (*decl_p) == error_mark_node)
9716         return;
9717       p = &DECL_ATTRIBUTES (*decl_p);
9718     }
9719   else
9720     p = &TYPE_ATTRIBUTES (*decl_p);
9721
9722   if (last_dep)
9723     {
9724       tree late_attrs = NULL_TREE;
9725       tree *q = &late_attrs;
9726
9727       for (*p = attributes; *p; )
9728         {
9729           t = *p;
9730           if (ATTR_IS_DEPENDENT (t))
9731             {
9732               *p = TREE_CHAIN (t);
9733               TREE_CHAIN (t) = NULL_TREE;
9734               *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
9735               do
9736                 q = &TREE_CHAIN (*q);
9737               while (*q);
9738             }
9739           else
9740             p = &TREE_CHAIN (t);
9741         }
9742
9743       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
9744     }
9745 }
9746
9747 /* Perform (or defer) access check for typedefs that were referenced
9748    from within the template TMPL code.
9749    This is a subroutine of instantiate_decl and instantiate_class_template.
9750    TMPL is the template to consider and TARGS is the list of arguments of
9751    that template.  */
9752
9753 static void
9754 perform_typedefs_access_check (tree tmpl, tree targs)
9755 {
9756   location_t saved_location;
9757   unsigned i;
9758   qualified_typedef_usage_t *iter;
9759
9760   if (!tmpl
9761       || (!CLASS_TYPE_P (tmpl)
9762           && TREE_CODE (tmpl) != FUNCTION_DECL))
9763     return;
9764
9765   saved_location = input_location;
9766   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (tmpl), i, iter)
9767     {
9768       tree type_decl = iter->typedef_decl;
9769       tree type_scope = iter->context;
9770
9771       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
9772         continue;
9773
9774       if (uses_template_parms (type_decl))
9775         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
9776       if (uses_template_parms (type_scope))
9777         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
9778
9779       /* Make access check error messages point to the location
9780          of the use of the typedef.  */
9781       input_location = iter->locus;
9782       perform_or_defer_access_check (TYPE_BINFO (type_scope),
9783                                      type_decl, type_decl,
9784                                      tf_warning_or_error);
9785     }
9786     input_location = saved_location;
9787 }
9788
9789 static tree
9790 instantiate_class_template_1 (tree type)
9791 {
9792   tree templ, args, pattern, t, member;
9793   tree typedecl;
9794   tree pbinfo;
9795   tree base_list;
9796   unsigned int saved_maximum_field_alignment;
9797   tree fn_context;
9798
9799   if (type == error_mark_node)
9800     return error_mark_node;
9801
9802   if (COMPLETE_OR_OPEN_TYPE_P (type)
9803       || uses_template_parms (type))
9804     return type;
9805
9806   /* Figure out which template is being instantiated.  */
9807   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
9808   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
9809
9810   /* Determine what specialization of the original template to
9811      instantiate.  */
9812   t = most_specialized_partial_spec (type, tf_warning_or_error);
9813   if (t == error_mark_node)
9814     {
9815       TYPE_BEING_DEFINED (type) = 1;
9816       return error_mark_node;
9817     }
9818   else if (t)
9819     {
9820       /* This TYPE is actually an instantiation of a partial
9821          specialization.  We replace the innermost set of ARGS with
9822          the arguments appropriate for substitution.  For example,
9823          given:
9824
9825            template <class T> struct S {};
9826            template <class T> struct S<T*> {};
9827
9828          and supposing that we are instantiating S<int*>, ARGS will
9829          presently be {int*} -- but we need {int}.  */
9830       pattern = TREE_TYPE (t);
9831       args = TREE_PURPOSE (t);
9832     }
9833   else
9834     {
9835       pattern = TREE_TYPE (templ);
9836       args = CLASSTYPE_TI_ARGS (type);
9837     }
9838
9839   /* If the template we're instantiating is incomplete, then clearly
9840      there's nothing we can do.  */
9841   if (!COMPLETE_TYPE_P (pattern))
9842     return type;
9843
9844   /* If we've recursively instantiated too many templates, stop.  */
9845   if (! push_tinst_level (type))
9846     return type;
9847
9848   /* Now we're really doing the instantiation.  Mark the type as in
9849      the process of being defined.  */
9850   TYPE_BEING_DEFINED (type) = 1;
9851
9852   /* We may be in the middle of deferred access check.  Disable
9853      it now.  */
9854   push_deferring_access_checks (dk_no_deferred);
9855
9856   int saved_unevaluated_operand = cp_unevaluated_operand;
9857   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9858
9859   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
9860   /* Also avoid push_to_top_level for a lambda in an NSDMI.  */
9861   if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
9862     fn_context = error_mark_node;
9863   if (!fn_context)
9864     push_to_top_level ();
9865   else
9866     {
9867       cp_unevaluated_operand = 0;
9868       c_inhibit_evaluation_warnings = 0;
9869     }
9870   /* Use #pragma pack from the template context.  */
9871   saved_maximum_field_alignment = maximum_field_alignment;
9872   maximum_field_alignment = TYPE_PRECISION (pattern);
9873
9874   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
9875
9876   /* Set the input location to the most specialized template definition.
9877      This is needed if tsubsting causes an error.  */
9878   typedecl = TYPE_MAIN_DECL (pattern);
9879   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
9880     DECL_SOURCE_LOCATION (typedecl);
9881
9882   TYPE_PACKED (type) = TYPE_PACKED (pattern);
9883   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
9884   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
9885   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
9886   if (ANON_AGGR_TYPE_P (pattern))
9887     SET_ANON_AGGR_TYPE_P (type);
9888   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
9889     {
9890       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
9891       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
9892       /* Adjust visibility for template arguments.  */
9893       determine_visibility (TYPE_MAIN_DECL (type));
9894     }
9895   if (CLASS_TYPE_P (type))
9896     CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
9897
9898   pbinfo = TYPE_BINFO (pattern);
9899
9900   /* We should never instantiate a nested class before its enclosing
9901      class; we need to look up the nested class by name before we can
9902      instantiate it, and that lookup should instantiate the enclosing
9903      class.  */
9904   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
9905               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
9906
9907   base_list = NULL_TREE;
9908   if (BINFO_N_BASE_BINFOS (pbinfo))
9909     {
9910       tree pbase_binfo;
9911       tree pushed_scope;
9912       int i;
9913
9914       /* We must enter the scope containing the type, as that is where
9915          the accessibility of types named in dependent bases are
9916          looked up from.  */
9917       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
9918
9919       /* Substitute into each of the bases to determine the actual
9920          basetypes.  */
9921       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
9922         {
9923           tree base;
9924           tree access = BINFO_BASE_ACCESS (pbinfo, i);
9925           tree expanded_bases = NULL_TREE;
9926           int idx, len = 1;
9927
9928           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
9929             {
9930               expanded_bases = 
9931                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
9932                                        args, tf_error, NULL_TREE);
9933               if (expanded_bases == error_mark_node)
9934                 continue;
9935
9936               len = TREE_VEC_LENGTH (expanded_bases);
9937             }
9938
9939           for (idx = 0; idx < len; idx++)
9940             {
9941               if (expanded_bases)
9942                 /* Extract the already-expanded base class.  */
9943                 base = TREE_VEC_ELT (expanded_bases, idx);
9944               else
9945                 /* Substitute to figure out the base class.  */
9946                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
9947                                NULL_TREE);
9948
9949               if (base == error_mark_node)
9950                 continue;
9951
9952               base_list = tree_cons (access, base, base_list);
9953               if (BINFO_VIRTUAL_P (pbase_binfo))
9954                 TREE_TYPE (base_list) = integer_type_node;
9955             }
9956         }
9957
9958       /* The list is now in reverse order; correct that.  */
9959       base_list = nreverse (base_list);
9960
9961       if (pushed_scope)
9962         pop_scope (pushed_scope);
9963     }
9964   /* Now call xref_basetypes to set up all the base-class
9965      information.  */
9966   xref_basetypes (type, base_list);
9967
9968   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
9969                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
9970                                   args, tf_error, NULL_TREE);
9971   fixup_attribute_variants (type);
9972
9973   /* Now that our base classes are set up, enter the scope of the
9974      class, so that name lookups into base classes, etc. will work
9975      correctly.  This is precisely analogous to what we do in
9976      begin_class_definition when defining an ordinary non-template
9977      class, except we also need to push the enclosing classes.  */
9978   push_nested_class (type);
9979
9980   /* Now members are processed in the order of declaration.  */
9981   for (member = CLASSTYPE_DECL_LIST (pattern);
9982        member; member = TREE_CHAIN (member))
9983     {
9984       tree t = TREE_VALUE (member);
9985
9986       if (TREE_PURPOSE (member))
9987         {
9988           if (TYPE_P (t))
9989             {
9990               /* Build new CLASSTYPE_NESTED_UTDS.  */
9991
9992               tree newtag;
9993               bool class_template_p;
9994
9995               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
9996                                   && TYPE_LANG_SPECIFIC (t)
9997                                   && CLASSTYPE_IS_TEMPLATE (t));
9998               /* If the member is a class template, then -- even after
9999                  substitution -- there may be dependent types in the
10000                  template argument list for the class.  We increment
10001                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
10002                  that function will assume that no types are dependent
10003                  when outside of a template.  */
10004               if (class_template_p)
10005                 ++processing_template_decl;
10006               newtag = tsubst (t, args, tf_error, NULL_TREE);
10007               if (class_template_p)
10008                 --processing_template_decl;
10009               if (newtag == error_mark_node)
10010                 continue;
10011
10012               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
10013                 {
10014                   tree name = TYPE_IDENTIFIER (t);
10015
10016                   if (class_template_p)
10017                     /* Unfortunately, lookup_template_class sets
10018                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
10019                        instantiation (i.e., for the type of a member
10020                        template class nested within a template class.)
10021                        This behavior is required for
10022                        maybe_process_partial_specialization to work
10023                        correctly, but is not accurate in this case;
10024                        the TAG is not an instantiation of anything.
10025                        (The corresponding TEMPLATE_DECL is an
10026                        instantiation, but the TYPE is not.) */
10027                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
10028
10029                   /* Now, we call pushtag to put this NEWTAG into the scope of
10030                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
10031                      pushtag calling push_template_decl.  We don't have to do
10032                      this for enums because it will already have been done in
10033                      tsubst_enum.  */
10034                   if (name)
10035                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
10036                   pushtag (name, newtag, /*tag_scope=*/ts_current);
10037                 }
10038             }
10039           else if (DECL_DECLARES_FUNCTION_P (t))
10040             {
10041               /* Build new TYPE_METHODS.  */
10042               tree r;
10043
10044               if (TREE_CODE (t) == TEMPLATE_DECL)
10045                 ++processing_template_decl;
10046               r = tsubst (t, args, tf_error, NULL_TREE);
10047               if (TREE_CODE (t) == TEMPLATE_DECL)
10048                 --processing_template_decl;
10049               set_current_access_from_decl (r);
10050               finish_member_declaration (r);
10051               /* Instantiate members marked with attribute used.  */
10052               if (r != error_mark_node && DECL_PRESERVE_P (r))
10053                 mark_used (r);
10054               if (TREE_CODE (r) == FUNCTION_DECL
10055                   && DECL_OMP_DECLARE_REDUCTION_P (r))
10056                 cp_check_omp_declare_reduction (r);
10057             }
10058           else if (DECL_CLASS_TEMPLATE_P (t)
10059                    && LAMBDA_TYPE_P (TREE_TYPE (t)))
10060             /* A closure type for a lambda in a default argument for a
10061                member template.  Ignore it; it will be instantiated with
10062                the default argument.  */;
10063           else
10064             {
10065               /* Build new TYPE_FIELDS.  */
10066               if (TREE_CODE (t) == STATIC_ASSERT)
10067                 {
10068                   tree condition;
10069  
10070                   ++c_inhibit_evaluation_warnings;
10071                   condition =
10072                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
10073                                  tf_warning_or_error, NULL_TREE,
10074                                  /*integral_constant_expression_p=*/true);
10075                   --c_inhibit_evaluation_warnings;
10076
10077                   finish_static_assert (condition,
10078                                         STATIC_ASSERT_MESSAGE (t), 
10079                                         STATIC_ASSERT_SOURCE_LOCATION (t),
10080                                         /*member_p=*/true);
10081                 }
10082               else if (TREE_CODE (t) != CONST_DECL)
10083                 {
10084                   tree r;
10085                   tree vec = NULL_TREE;
10086                   int len = 1;
10087
10088                   /* The file and line for this declaration, to
10089                      assist in error message reporting.  Since we
10090                      called push_tinst_level above, we don't need to
10091                      restore these.  */
10092                   input_location = DECL_SOURCE_LOCATION (t);
10093
10094                   if (TREE_CODE (t) == TEMPLATE_DECL)
10095                     ++processing_template_decl;
10096                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
10097                   if (TREE_CODE (t) == TEMPLATE_DECL)
10098                     --processing_template_decl;
10099
10100                   if (TREE_CODE (r) == TREE_VEC)
10101                     {
10102                       /* A capture pack became multiple fields.  */
10103                       vec = r;
10104                       len = TREE_VEC_LENGTH (vec);
10105                     }
10106
10107                   for (int i = 0; i < len; ++i)
10108                     {
10109                       if (vec)
10110                         r = TREE_VEC_ELT (vec, i);
10111                       if (VAR_P (r))
10112                         {
10113                           /* In [temp.inst]:
10114
10115                              [t]he initialization (and any associated
10116                              side-effects) of a static data member does
10117                              not occur unless the static data member is
10118                              itself used in a way that requires the
10119                              definition of the static data member to
10120                              exist.
10121
10122                              Therefore, we do not substitute into the
10123                              initialized for the static data member here.  */
10124                           finish_static_data_member_decl
10125                             (r,
10126                              /*init=*/NULL_TREE,
10127                              /*init_const_expr_p=*/false,
10128                              /*asmspec_tree=*/NULL_TREE,
10129                              /*flags=*/0);
10130                           /* Instantiate members marked with attribute used. */
10131                           if (r != error_mark_node && DECL_PRESERVE_P (r))
10132                             mark_used (r);
10133                         }
10134                       else if (TREE_CODE (r) == FIELD_DECL)
10135                         {
10136                           /* Determine whether R has a valid type and can be
10137                              completed later.  If R is invalid, then its type
10138                              is replaced by error_mark_node.  */
10139                           tree rtype = TREE_TYPE (r);
10140                           if (can_complete_type_without_circularity (rtype))
10141                             complete_type (rtype);
10142
10143                           if (!complete_or_array_type_p (rtype))
10144                             {
10145                               /* If R's type couldn't be completed and
10146                                  it isn't a flexible array member (whose
10147                                  type is incomplete by definition) give
10148                                  an error.  */
10149                               cxx_incomplete_type_error (r, rtype);
10150                               TREE_TYPE (r) = error_mark_node;
10151                             }
10152                         }
10153
10154                       /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
10155                          such a thing will already have been added to the field
10156                          list by tsubst_enum in finish_member_declaration in the
10157                          CLASSTYPE_NESTED_UTDS case above.  */
10158                       if (!(TREE_CODE (r) == TYPE_DECL
10159                             && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
10160                             && DECL_ARTIFICIAL (r)))
10161                         {
10162                           set_current_access_from_decl (r);
10163                           finish_member_declaration (r);
10164                         }
10165                     }
10166                 }
10167             }
10168         }
10169       else
10170         {
10171           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
10172               || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10173             {
10174               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
10175
10176               tree friend_type = t;
10177               bool adjust_processing_template_decl = false;
10178
10179               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
10180                 {
10181                   /* template <class T> friend class C;  */
10182                   friend_type = tsubst_friend_class (friend_type, args);
10183                   adjust_processing_template_decl = true;
10184                 }
10185               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
10186                 {
10187                   /* template <class T> friend class C::D;  */
10188                   friend_type = tsubst (friend_type, args,
10189                                         tf_warning_or_error, NULL_TREE);
10190                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
10191                     friend_type = TREE_TYPE (friend_type);
10192                   adjust_processing_template_decl = true;
10193                 }
10194               else if (TREE_CODE (friend_type) == TYPENAME_TYPE
10195                        || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
10196                 {
10197                   /* This could be either
10198
10199                        friend class T::C;
10200
10201                      when dependent_type_p is false or
10202
10203                        template <class U> friend class T::C;
10204
10205                      otherwise.  */
10206                   /* Bump processing_template_decl in case this is something like
10207                      template <class T> friend struct A<T>::B.  */
10208                   ++processing_template_decl;
10209                   friend_type = tsubst (friend_type, args,
10210                                         tf_warning_or_error, NULL_TREE);
10211                   if (dependent_type_p (friend_type))
10212                     adjust_processing_template_decl = true;
10213                   --processing_template_decl;
10214                 }
10215               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
10216                        && hidden_name_p (TYPE_NAME (friend_type)))
10217                 {
10218                   /* friend class C;
10219
10220                      where C hasn't been declared yet.  Let's lookup name
10221                      from namespace scope directly, bypassing any name that
10222                      come from dependent base class.  */
10223                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
10224
10225                   /* The call to xref_tag_from_type does injection for friend
10226                      classes.  */
10227                   push_nested_namespace (ns);
10228                   friend_type =
10229                     xref_tag_from_type (friend_type, NULL_TREE,
10230                                         /*tag_scope=*/ts_current);
10231                   pop_nested_namespace (ns);
10232                 }
10233               else if (uses_template_parms (friend_type))
10234                 /* friend class C<T>;  */
10235                 friend_type = tsubst (friend_type, args,
10236                                       tf_warning_or_error, NULL_TREE);
10237               /* Otherwise it's
10238
10239                    friend class C;
10240
10241                  where C is already declared or
10242
10243                    friend class C<int>;
10244
10245                  We don't have to do anything in these cases.  */
10246
10247               if (adjust_processing_template_decl)
10248                 /* Trick make_friend_class into realizing that the friend
10249                    we're adding is a template, not an ordinary class.  It's
10250                    important that we use make_friend_class since it will
10251                    perform some error-checking and output cross-reference
10252                    information.  */
10253                 ++processing_template_decl;
10254
10255               if (friend_type != error_mark_node)
10256                 make_friend_class (type, friend_type, /*complain=*/false);
10257
10258               if (adjust_processing_template_decl)
10259                 --processing_template_decl;
10260             }
10261           else
10262             {
10263               /* Build new DECL_FRIENDLIST.  */
10264               tree r;
10265
10266               /* The file and line for this declaration, to
10267                  assist in error message reporting.  Since we
10268                  called push_tinst_level above, we don't need to
10269                  restore these.  */
10270               input_location = DECL_SOURCE_LOCATION (t);
10271
10272               if (TREE_CODE (t) == TEMPLATE_DECL)
10273                 {
10274                   ++processing_template_decl;
10275                   push_deferring_access_checks (dk_no_check);
10276                 }
10277
10278               r = tsubst_friend_function (t, args);
10279               add_friend (type, r, /*complain=*/false);
10280               if (TREE_CODE (t) == TEMPLATE_DECL)
10281                 {
10282                   pop_deferring_access_checks ();
10283                   --processing_template_decl;
10284                 }
10285             }
10286         }
10287     }
10288
10289   if (fn_context)
10290     {
10291       /* Restore these before substituting into the lambda capture
10292          initializers.  */
10293       cp_unevaluated_operand = saved_unevaluated_operand;
10294       c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
10295     }
10296
10297   if (tree expr = CLASSTYPE_LAMBDA_EXPR (type))
10298     {
10299       tree decl = lambda_function (type);
10300       if (decl)
10301         {
10302           if (!DECL_TEMPLATE_INFO (decl)
10303               || DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (decl)) != decl)
10304             {
10305               /* Set function_depth to avoid garbage collection.  */
10306               ++function_depth;
10307               instantiate_decl (decl, false, false);
10308               --function_depth;
10309             }
10310
10311           /* We need to instantiate the capture list from the template
10312              after we've instantiated the closure members, but before we
10313              consider adding the conversion op.  Also keep any captures
10314              that may have been added during instantiation of the op().  */
10315           tree tmpl_expr = CLASSTYPE_LAMBDA_EXPR (pattern);
10316           tree tmpl_cap
10317             = tsubst_copy_and_build (LAMBDA_EXPR_CAPTURE_LIST (tmpl_expr),
10318                                      args, tf_warning_or_error, NULL_TREE,
10319                                      false, false);
10320
10321           LAMBDA_EXPR_CAPTURE_LIST (expr)
10322             = chainon (tmpl_cap, nreverse (LAMBDA_EXPR_CAPTURE_LIST (expr)));
10323
10324           maybe_add_lambda_conv_op (type);
10325         }
10326       else
10327         gcc_assert (errorcount);
10328     }
10329
10330   /* Set the file and line number information to whatever is given for
10331      the class itself.  This puts error messages involving generated
10332      implicit functions at a predictable point, and the same point
10333      that would be used for non-template classes.  */
10334   input_location = DECL_SOURCE_LOCATION (typedecl);
10335
10336   unreverse_member_declarations (type);
10337   finish_struct_1 (type);
10338   TYPE_BEING_DEFINED (type) = 0;
10339
10340   /* We don't instantiate default arguments for member functions.  14.7.1:
10341
10342      The implicit instantiation of a class template specialization causes
10343      the implicit instantiation of the declarations, but not of the
10344      definitions or default arguments, of the class member functions,
10345      member classes, static data members and member templates....  */
10346
10347   /* Some typedefs referenced from within the template code need to be access
10348      checked at template instantiation time, i.e now. These types were
10349      added to the template at parsing time. Let's get those and perform
10350      the access checks then.  */
10351   perform_typedefs_access_check (pattern, args);
10352   perform_deferred_access_checks (tf_warning_or_error);
10353   pop_nested_class ();
10354   maximum_field_alignment = saved_maximum_field_alignment;
10355   if (!fn_context)
10356     pop_from_top_level ();
10357   pop_deferring_access_checks ();
10358   pop_tinst_level ();
10359
10360   /* The vtable for a template class can be emitted in any translation
10361      unit in which the class is instantiated.  When there is no key
10362      method, however, finish_struct_1 will already have added TYPE to
10363      the keyed_classes list.  */
10364   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
10365     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
10366
10367   return type;
10368 }
10369
10370 /* Wrapper for instantiate_class_template_1.  */
10371
10372 tree
10373 instantiate_class_template (tree type)
10374 {
10375   tree ret;
10376   timevar_push (TV_TEMPLATE_INST);
10377   ret = instantiate_class_template_1 (type);
10378   timevar_pop (TV_TEMPLATE_INST);
10379   return ret;
10380 }
10381
10382 static tree
10383 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10384 {
10385   tree r;
10386
10387   if (!t)
10388     r = t;
10389   else if (TYPE_P (t))
10390     r = tsubst (t, args, complain, in_decl);
10391   else
10392     {
10393       if (!(complain & tf_warning))
10394         ++c_inhibit_evaluation_warnings;
10395       r = tsubst_expr (t, args, complain, in_decl,
10396                        /*integral_constant_expression_p=*/true);
10397       if (!(complain & tf_warning))
10398         --c_inhibit_evaluation_warnings;
10399     }
10400   return r;
10401 }
10402
10403 /* Given a function parameter pack TMPL_PARM and some function parameters
10404    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
10405    and set *SPEC_P to point at the next point in the list.  */
10406
10407 tree
10408 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
10409 {
10410   /* Collect all of the extra "packed" parameters into an
10411      argument pack.  */
10412   tree parmvec;
10413   tree parmtypevec;
10414   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
10415   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
10416   tree spec_parm = *spec_p;
10417   int i, len;
10418
10419   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
10420     if (tmpl_parm
10421         && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
10422       break;
10423
10424   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
10425   parmvec = make_tree_vec (len);
10426   parmtypevec = make_tree_vec (len);
10427   spec_parm = *spec_p;
10428   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
10429     {
10430       TREE_VEC_ELT (parmvec, i) = spec_parm;
10431       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
10432     }
10433
10434   /* Build the argument packs.  */
10435   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
10436   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
10437   TREE_TYPE (argpack) = argtypepack;
10438   *spec_p = spec_parm;
10439
10440   return argpack;
10441 }
10442
10443 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
10444    NONTYPE_ARGUMENT_PACK.  */
10445
10446 static tree
10447 make_fnparm_pack (tree spec_parm)
10448 {
10449   return extract_fnparm_pack (NULL_TREE, &spec_parm);
10450 }
10451
10452 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
10453    pack expansion with no extra args, 2 if it has extra args, or 0
10454    if it is not a pack expansion.  */
10455
10456 static int
10457 argument_pack_element_is_expansion_p (tree arg_pack, int i)
10458 {
10459   tree vec = ARGUMENT_PACK_ARGS (arg_pack);
10460   if (i >= TREE_VEC_LENGTH (vec))
10461     return 0;
10462   tree elt = TREE_VEC_ELT (vec, i);
10463   if (DECL_P (elt))
10464     /* A decl pack is itself an expansion.  */
10465     elt = TREE_TYPE (elt);
10466   if (!PACK_EXPANSION_P (elt))
10467     return 0;
10468   if (PACK_EXPANSION_EXTRA_ARGS (elt))
10469     return 2;
10470   return 1;
10471 }
10472
10473
10474 /* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
10475
10476 static tree
10477 make_argument_pack_select (tree arg_pack, unsigned index)
10478 {
10479   tree aps = make_node (ARGUMENT_PACK_SELECT);
10480
10481   ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
10482   ARGUMENT_PACK_SELECT_INDEX (aps) = index;
10483
10484   return aps;
10485 }
10486
10487 /*  This is a subroutine of tsubst_pack_expansion.
10488
10489     It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
10490     mechanism to store the (non complete list of) arguments of the
10491     substitution and return a non substituted pack expansion, in order
10492     to wait for when we have enough arguments to really perform the
10493     substitution.  */
10494
10495 static bool
10496 use_pack_expansion_extra_args_p (tree parm_packs,
10497                                  int arg_pack_len,
10498                                  bool has_empty_arg)
10499 {
10500   /* If one pack has an expansion and another pack has a normal
10501      argument or if one pack has an empty argument and an another
10502      one hasn't then tsubst_pack_expansion cannot perform the
10503      substitution and need to fall back on the
10504      PACK_EXPANSION_EXTRA mechanism.  */
10505   if (parm_packs == NULL_TREE)
10506     return false;
10507   else if (has_empty_arg)
10508     return true;
10509
10510   bool has_expansion_arg = false;
10511   for (int i = 0 ; i < arg_pack_len; ++i)
10512     {
10513       bool has_non_expansion_arg = false;
10514       for (tree parm_pack = parm_packs;
10515            parm_pack;
10516            parm_pack = TREE_CHAIN (parm_pack))
10517         {
10518           tree arg = TREE_VALUE (parm_pack);
10519
10520           int exp = argument_pack_element_is_expansion_p (arg, i);
10521           if (exp == 2)
10522             /* We can't substitute a pack expansion with extra args into
10523                our pattern.  */
10524             return true;
10525           else if (exp)
10526             has_expansion_arg = true;
10527           else
10528             has_non_expansion_arg = true;
10529         }
10530
10531       if (has_expansion_arg && has_non_expansion_arg)
10532         return true;
10533     }
10534   return false;
10535 }
10536
10537 /* [temp.variadic]/6 says that:
10538
10539        The instantiation of a pack expansion [...]
10540        produces a list E1,E2, ..., En, where N is the number of elements
10541        in the pack expansion parameters.
10542
10543    This subroutine of tsubst_pack_expansion produces one of these Ei.
10544
10545    PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
10546    TREE_LIST in which each TREE_PURPOSE is a parameter pack of
10547    PATTERN, and each TREE_VALUE is its corresponding argument pack.
10548    INDEX is the index 'i' of the element Ei to produce.  ARGS,
10549    COMPLAIN, and IN_DECL are the same parameters as for the
10550    tsubst_pack_expansion function.
10551
10552    The function returns the resulting Ei upon successful completion,
10553    or error_mark_node.
10554
10555    Note that this function possibly modifies the ARGS parameter, so
10556    it's the responsibility of the caller to restore it.  */
10557
10558 static tree
10559 gen_elem_of_pack_expansion_instantiation (tree pattern,
10560                                           tree parm_packs,
10561                                           unsigned index,
10562                                           tree args /* This parm gets
10563                                                        modified.  */,
10564                                           tsubst_flags_t complain,
10565                                           tree in_decl)
10566 {
10567   tree t;
10568   bool ith_elem_is_expansion = false;
10569
10570   /* For each parameter pack, change the substitution of the parameter
10571      pack to the ith argument in its argument pack, then expand the
10572      pattern.  */
10573   for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
10574     {
10575       tree parm = TREE_PURPOSE (pack);
10576       tree arg_pack = TREE_VALUE (pack);
10577       tree aps;                 /* instance of ARGUMENT_PACK_SELECT.  */
10578
10579       ith_elem_is_expansion |=
10580         argument_pack_element_is_expansion_p (arg_pack, index);
10581
10582       /* Select the Ith argument from the pack.  */
10583       if (TREE_CODE (parm) == PARM_DECL
10584           || TREE_CODE (parm) == FIELD_DECL)
10585         {
10586           if (index == 0)
10587             {
10588               aps = make_argument_pack_select (arg_pack, index);
10589               if (!mark_used (parm, complain) && !(complain & tf_error))
10590                 return error_mark_node;
10591               register_local_specialization (aps, parm);
10592             }
10593           else
10594             aps = retrieve_local_specialization (parm);
10595         }
10596       else
10597         {
10598           int idx, level;
10599           template_parm_level_and_index (parm, &level, &idx);
10600
10601           if (index == 0)
10602             {
10603               aps = make_argument_pack_select (arg_pack, index);
10604               /* Update the corresponding argument.  */
10605               TMPL_ARG (args, level, idx) = aps;
10606             }
10607           else
10608             /* Re-use the ARGUMENT_PACK_SELECT.  */
10609             aps = TMPL_ARG (args, level, idx);
10610         }
10611       ARGUMENT_PACK_SELECT_INDEX (aps) = index;
10612     }
10613
10614   /* Substitute into the PATTERN with the (possibly altered)
10615      arguments.  */
10616   if (pattern == in_decl)
10617     /* Expanding a fixed parameter pack from
10618        coerce_template_parameter_pack.  */
10619     t = tsubst_decl (pattern, args, complain);
10620   else if (pattern == error_mark_node)
10621     t = error_mark_node;
10622   else if (constraint_p (pattern))
10623     {
10624       if (processing_template_decl)
10625         t = tsubst_constraint (pattern, args, complain, in_decl);
10626       else
10627         t = (constraints_satisfied_p (pattern, args)
10628              ? boolean_true_node : boolean_false_node);
10629     }
10630   else if (!TYPE_P (pattern))
10631     t = tsubst_expr (pattern, args, complain, in_decl,
10632                      /*integral_constant_expression_p=*/false);
10633   else
10634     t = tsubst (pattern, args, complain, in_decl);
10635
10636   /*  If the Ith argument pack element is a pack expansion, then
10637       the Ith element resulting from the substituting is going to
10638       be a pack expansion as well.  */
10639   if (ith_elem_is_expansion)
10640     t = make_pack_expansion (t);
10641
10642   return t;
10643 }
10644
10645 /* When the unexpanded parameter pack in a fold expression expands to an empty
10646    sequence, the value of the expression is as follows; the program is
10647    ill-formed if the operator is not listed in this table.
10648
10649    &&   true
10650    ||   false
10651    ,    void()  */
10652
10653 tree
10654 expand_empty_fold (tree t, tsubst_flags_t complain)
10655 {
10656   tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
10657   if (!FOLD_EXPR_MODIFY_P (t))
10658     switch (code)
10659       {
10660       case TRUTH_ANDIF_EXPR:
10661         return boolean_true_node;
10662       case TRUTH_ORIF_EXPR:
10663         return boolean_false_node;
10664       case COMPOUND_EXPR:
10665         return void_node;
10666       default:
10667         break;
10668       }
10669
10670   if (complain & tf_error)
10671     error_at (location_of (t),
10672               "fold of empty expansion over %O", code);
10673   return error_mark_node;
10674 }
10675
10676 /* Given a fold-expression T and a current LEFT and RIGHT operand,
10677    form an expression that combines the two terms using the
10678    operator of T. */
10679
10680 static tree
10681 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
10682 {
10683   tree op = FOLD_EXPR_OP (t);
10684   tree_code code = (tree_code)TREE_INT_CST_LOW (op);
10685
10686   // Handle compound assignment operators.
10687   if (FOLD_EXPR_MODIFY_P (t))
10688     return build_x_modify_expr (input_location, left, code, right, complain);
10689
10690   switch (code)
10691     {
10692     case COMPOUND_EXPR:
10693       return build_x_compound_expr (input_location, left, right, complain);
10694     case DOTSTAR_EXPR:
10695       return build_m_component_ref (left, right, complain);
10696     default:
10697       return build_x_binary_op (input_location, code,
10698                                 left, TREE_CODE (left),
10699                                 right, TREE_CODE (right),
10700                                 /*overload=*/NULL,
10701                                 complain);
10702     }
10703 }
10704
10705 /* Substitute ARGS into the pack of a fold expression T. */
10706
10707 static inline tree
10708 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10709 {
10710   return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
10711 }
10712
10713 /* Substitute ARGS into the pack of a fold expression T. */
10714
10715 static inline tree
10716 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10717 {
10718   return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
10719 }
10720
10721 /* Expand a PACK of arguments into a grouped as left fold.
10722    Given a pack containing elements A0, A1, ..., An and an
10723    operator @, this builds the expression:
10724
10725       ((A0 @ A1) @ A2) ... @ An
10726
10727    Note that PACK must not be empty.
10728
10729    The operator is defined by the original fold expression T. */
10730
10731 static tree
10732 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
10733 {
10734   tree left = TREE_VEC_ELT (pack, 0);
10735   for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
10736     {
10737       tree right = TREE_VEC_ELT (pack, i);
10738       left = fold_expression (t, left, right, complain);
10739     }
10740   return left;
10741 }
10742
10743 /* Substitute into a unary left fold expression. */
10744
10745 static tree
10746 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
10747                         tree in_decl)
10748 {
10749   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
10750   if (pack == error_mark_node)
10751     return error_mark_node;
10752   if (PACK_EXPANSION_P (pack))
10753     {
10754       tree r = copy_node (t);
10755       FOLD_EXPR_PACK (r) = pack;
10756       return r;
10757     }
10758   if (TREE_VEC_LENGTH (pack) == 0)
10759     return expand_empty_fold (t, complain);
10760   else
10761     return expand_left_fold (t, pack, complain);
10762 }
10763
10764 /* Substitute into a binary left fold expression.
10765
10766    Do ths by building a single (non-empty) vector of argumnts and
10767    building the expression from those elements. */
10768
10769 static tree
10770 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
10771                          tree in_decl)
10772 {
10773   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
10774   if (pack == error_mark_node)
10775     return error_mark_node;
10776   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
10777   if (init == error_mark_node)
10778     return error_mark_node;
10779
10780   if (PACK_EXPANSION_P (pack))
10781     {
10782       tree r = copy_node (t);
10783       FOLD_EXPR_PACK (r) = pack;
10784       FOLD_EXPR_INIT (r) = init;
10785       return r;
10786     }
10787
10788   tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
10789   TREE_VEC_ELT (vec, 0) = init;
10790   for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
10791     TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
10792
10793   return expand_left_fold (t, vec, complain);
10794 }
10795
10796 /* Expand a PACK of arguments into a grouped as right fold.
10797    Given a pack containing elementns A0, A1, ..., and an
10798    operator @, this builds the expression:
10799
10800       A0@ ... (An-2 @ (An-1 @ An))
10801
10802    Note that PACK must not be empty.
10803
10804    The operator is defined by the original fold expression T. */
10805
10806 tree
10807 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
10808 {
10809   // Build the expression.
10810   int n = TREE_VEC_LENGTH (pack);
10811   tree right = TREE_VEC_ELT (pack, n - 1);
10812   for (--n; n != 0; --n)
10813     {
10814       tree left = TREE_VEC_ELT (pack, n - 1);
10815       right = fold_expression (t, left, right, complain);
10816     }
10817   return right;
10818 }
10819
10820 /* Substitute into a unary right fold expression. */
10821
10822 static tree
10823 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
10824                          tree in_decl)
10825 {
10826   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
10827   if (pack == error_mark_node)
10828     return error_mark_node;
10829   if (PACK_EXPANSION_P (pack))
10830     {
10831       tree r = copy_node (t);
10832       FOLD_EXPR_PACK (r) = pack;
10833       return r;
10834     }
10835   if (TREE_VEC_LENGTH (pack) == 0)
10836     return expand_empty_fold (t, complain);
10837   else
10838     return expand_right_fold (t, pack, complain);
10839 }
10840
10841 /* Substitute into a binary right fold expression.
10842
10843    Do ths by building a single (non-empty) vector of arguments and
10844    building the expression from those elements. */
10845
10846 static tree
10847 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
10848                          tree in_decl)
10849 {
10850   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
10851   if (pack == error_mark_node)
10852     return error_mark_node;
10853   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
10854   if (init == error_mark_node)
10855     return error_mark_node;
10856
10857   if (PACK_EXPANSION_P (pack))
10858     {
10859       tree r = copy_node (t);
10860       FOLD_EXPR_PACK (r) = pack;
10861       FOLD_EXPR_INIT (r) = init;
10862       return r;
10863     }
10864
10865   int n = TREE_VEC_LENGTH (pack);
10866   tree vec = make_tree_vec (n + 1);
10867   for (int i = 0; i < n; ++i)
10868     TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
10869   TREE_VEC_ELT (vec, n) = init;
10870
10871   return expand_right_fold (t, vec, complain);
10872 }
10873
10874
10875 /* Substitute ARGS into T, which is an pack expansion
10876    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
10877    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
10878    (if only a partial substitution could be performed) or
10879    ERROR_MARK_NODE if there was an error.  */
10880 tree
10881 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
10882                        tree in_decl)
10883 {
10884   tree pattern;
10885   tree pack, packs = NULL_TREE;
10886   bool unsubstituted_packs = false;
10887   int i, len = -1;
10888   tree result;
10889   hash_map<tree, tree> *saved_local_specializations = NULL;
10890   bool need_local_specializations = false;
10891   int levels;
10892
10893   gcc_assert (PACK_EXPANSION_P (t));
10894   pattern = PACK_EXPANSION_PATTERN (t);
10895
10896   /* Add in any args remembered from an earlier partial instantiation.  */
10897   args = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
10898
10899   levels = TMPL_ARGS_DEPTH (args);
10900
10901   /* Determine the argument packs that will instantiate the parameter
10902      packs used in the expansion expression. While we're at it,
10903      compute the number of arguments to be expanded and make sure it
10904      is consistent.  */
10905   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
10906        pack = TREE_CHAIN (pack))
10907     {
10908       tree parm_pack = TREE_VALUE (pack);
10909       tree arg_pack = NULL_TREE;
10910       tree orig_arg = NULL_TREE;
10911       int level = 0;
10912
10913       if (TREE_CODE (parm_pack) == BASES)
10914        {
10915          if (BASES_DIRECT (parm_pack))
10916            return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
10917                                                         args, complain, in_decl, false));
10918          else
10919            return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
10920                                                  args, complain, in_decl, false));
10921        }
10922       if (TREE_CODE (parm_pack) == PARM_DECL)
10923         {
10924           /* We know we have correct local_specializations if this
10925              expansion is at function scope, or if we're dealing with a
10926              local parameter in a requires expression; for the latter,
10927              tsubst_requires_expr set it up appropriately.  */
10928           if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
10929             arg_pack = retrieve_local_specialization (parm_pack);
10930           else
10931             /* We can't rely on local_specializations for a parameter
10932                name used later in a function declaration (such as in a
10933                late-specified return type).  Even if it exists, it might
10934                have the wrong value for a recursive call.  */
10935             need_local_specializations = true;
10936
10937           if (!arg_pack)
10938             {
10939               /* This parameter pack was used in an unevaluated context.  Just
10940                  make a dummy decl, since it's only used for its type.  */
10941               arg_pack = tsubst_decl (parm_pack, args, complain);
10942               if (arg_pack && DECL_PACK_P (arg_pack))
10943                 /* Partial instantiation of the parm_pack, we can't build
10944                    up an argument pack yet.  */
10945                 arg_pack = NULL_TREE;
10946               else
10947                 arg_pack = make_fnparm_pack (arg_pack);
10948             }
10949         }
10950       else if (TREE_CODE (parm_pack) == FIELD_DECL)
10951         arg_pack = tsubst_copy (parm_pack, args, complain, in_decl);
10952       else
10953         {
10954           int idx;
10955           template_parm_level_and_index (parm_pack, &level, &idx);
10956
10957           if (level <= levels)
10958             arg_pack = TMPL_ARG (args, level, idx);
10959         }
10960
10961       orig_arg = arg_pack;
10962       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
10963         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
10964       
10965       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
10966         /* This can only happen if we forget to expand an argument
10967            pack somewhere else. Just return an error, silently.  */
10968         {
10969           result = make_tree_vec (1);
10970           TREE_VEC_ELT (result, 0) = error_mark_node;
10971           return result;
10972         }
10973
10974       if (arg_pack)
10975         {
10976           int my_len = 
10977             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
10978
10979           /* Don't bother trying to do a partial substitution with
10980              incomplete packs; we'll try again after deduction.  */
10981           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
10982             return t;
10983
10984           if (len < 0)
10985             len = my_len;
10986           else if (len != my_len)
10987             {
10988               if (!(complain & tf_error))
10989                 /* Fail quietly.  */;
10990               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
10991                 error ("mismatched argument pack lengths while expanding "
10992                        "%<%T%>",
10993                        pattern);
10994               else
10995                 error ("mismatched argument pack lengths while expanding "
10996                        "%<%E%>",
10997                        pattern);
10998               return error_mark_node;
10999             }
11000
11001           /* Keep track of the parameter packs and their corresponding
11002              argument packs.  */
11003           packs = tree_cons (parm_pack, arg_pack, packs);
11004           TREE_TYPE (packs) = orig_arg;
11005         }
11006       else
11007         {
11008           /* We can't substitute for this parameter pack.  We use a flag as
11009              well as the missing_level counter because function parameter
11010              packs don't have a level.  */
11011           unsubstituted_packs = true;
11012         }
11013     }
11014
11015   /* If the expansion is just T..., return the matching argument pack, unless
11016      we need to call convert_from_reference on all the elements.  This is an
11017      important optimization; see c++/68422.  */
11018   if (!unsubstituted_packs
11019       && TREE_PURPOSE (packs) == pattern)
11020     {
11021       tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
11022       /* Types need no adjustment, nor does sizeof..., and if we still have
11023          some pack expansion args we won't do anything yet.  */
11024       if (TREE_CODE (t) == TYPE_PACK_EXPANSION
11025           || PACK_EXPANSION_SIZEOF_P (t)
11026           || pack_expansion_args_count (args))
11027         return args;
11028       /* Also optimize expression pack expansions if we can tell that the
11029          elements won't have reference type.  */
11030       tree type = TREE_TYPE (pattern);
11031       if (type && TREE_CODE (type) != REFERENCE_TYPE
11032           && !PACK_EXPANSION_P (type)
11033           && !WILDCARD_TYPE_P (type))
11034         return args;
11035       /* Otherwise use the normal path so we get convert_from_reference.  */
11036     }
11037
11038   /* We cannot expand this expansion expression, because we don't have
11039      all of the argument packs we need.  */
11040   if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
11041     {
11042       /* We got some full packs, but we can't substitute them in until we
11043          have values for all the packs.  So remember these until then.  */
11044
11045       t = make_pack_expansion (pattern);
11046       PACK_EXPANSION_EXTRA_ARGS (t) = args;
11047       return t;
11048     }
11049   else if (unsubstituted_packs)
11050     {
11051       /* There were no real arguments, we're just replacing a parameter
11052          pack with another version of itself. Substitute into the
11053          pattern and return a PACK_EXPANSION_*. The caller will need to
11054          deal with that.  */
11055       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
11056         t = tsubst_expr (pattern, args, complain, in_decl,
11057                          /*integral_constant_expression_p=*/false);
11058       else
11059         t = tsubst (pattern, args, complain, in_decl);
11060       t = make_pack_expansion (t);
11061       return t;
11062     }
11063
11064   gcc_assert (len >= 0);
11065
11066   if (need_local_specializations)
11067     {
11068       /* We're in a late-specified return type, so create our own local
11069          specializations map; the current map is either NULL or (in the
11070          case of recursive unification) might have bindings that we don't
11071          want to use or alter.  */
11072       saved_local_specializations = local_specializations;
11073       local_specializations = new hash_map<tree, tree>;
11074     }
11075
11076   /* For each argument in each argument pack, substitute into the
11077      pattern.  */
11078   result = make_tree_vec (len);
11079   tree elem_args = copy_template_args (args);
11080   for (i = 0; i < len; ++i)
11081     {
11082       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
11083                                                     i,
11084                                                     elem_args, complain,
11085                                                     in_decl);
11086       TREE_VEC_ELT (result, i) = t;
11087       if (t == error_mark_node)
11088         {
11089           result = error_mark_node;
11090           break;
11091         }
11092     }
11093
11094   /* Update ARGS to restore the substitution from parameter packs to
11095      their argument packs.  */
11096   for (pack = packs; pack; pack = TREE_CHAIN (pack))
11097     {
11098       tree parm = TREE_PURPOSE (pack);
11099
11100       if (TREE_CODE (parm) == PARM_DECL
11101           || TREE_CODE (parm) == FIELD_DECL)
11102         register_local_specialization (TREE_TYPE (pack), parm);
11103       else
11104         {
11105           int idx, level;
11106
11107           if (TREE_VALUE (pack) == NULL_TREE)
11108             continue;
11109
11110           template_parm_level_and_index (parm, &level, &idx);
11111           
11112           /* Update the corresponding argument.  */
11113           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
11114             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
11115               TREE_TYPE (pack);
11116           else
11117             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
11118         }
11119     }
11120
11121   if (need_local_specializations)
11122     {
11123       delete local_specializations;
11124       local_specializations = saved_local_specializations;
11125     }
11126   
11127   /* If the dependent pack arguments were such that we end up with only a
11128      single pack expansion again, there's no need to keep it in a TREE_VEC.  */
11129   if (len == 1 && TREE_CODE (result) == TREE_VEC
11130       && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
11131     return TREE_VEC_ELT (result, 0);
11132
11133   return result;
11134 }
11135
11136 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
11137    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
11138    parameter packs; all parms generated from a function parameter pack will
11139    have the same DECL_PARM_INDEX.  */
11140
11141 tree
11142 get_pattern_parm (tree parm, tree tmpl)
11143 {
11144   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
11145   tree patparm;
11146
11147   if (DECL_ARTIFICIAL (parm))
11148     {
11149       for (patparm = DECL_ARGUMENTS (pattern);
11150            patparm; patparm = DECL_CHAIN (patparm))
11151         if (DECL_ARTIFICIAL (patparm)
11152             && DECL_NAME (parm) == DECL_NAME (patparm))
11153           break;
11154     }
11155   else
11156     {
11157       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
11158       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
11159       gcc_assert (DECL_PARM_INDEX (patparm)
11160                   == DECL_PARM_INDEX (parm));
11161     }
11162
11163   return patparm;
11164 }
11165
11166 /* Make an argument pack out of the TREE_VEC VEC.  */
11167
11168 static tree
11169 make_argument_pack (tree vec)
11170 {
11171   tree pack;
11172   tree elt = TREE_VEC_ELT (vec, 0);
11173   if (TYPE_P (elt))
11174     pack = cxx_make_type (TYPE_ARGUMENT_PACK);
11175   else
11176     {
11177       pack = make_node (NONTYPE_ARGUMENT_PACK);
11178       TREE_TYPE (pack) = TREE_TYPE (elt);
11179       TREE_CONSTANT (pack) = 1;
11180     }
11181   SET_ARGUMENT_PACK_ARGS (pack, vec);
11182   return pack;
11183 }
11184
11185 /* Return an exact copy of template args T that can be modified
11186    independently.  */
11187
11188 static tree
11189 copy_template_args (tree t)
11190 {
11191   if (t == error_mark_node)
11192     return t;
11193
11194   int len = TREE_VEC_LENGTH (t);
11195   tree new_vec = make_tree_vec (len);
11196
11197   for (int i = 0; i < len; ++i)
11198     {
11199       tree elt = TREE_VEC_ELT (t, i);
11200       if (elt && TREE_CODE (elt) == TREE_VEC)
11201         elt = copy_template_args (elt);
11202       TREE_VEC_ELT (new_vec, i) = elt;
11203     }
11204
11205   NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
11206     = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
11207
11208   return new_vec;
11209 }
11210
11211 /* Substitute ARGS into the vector or list of template arguments T.  */
11212
11213 static tree
11214 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11215 {
11216   tree orig_t = t;
11217   int len, need_new = 0, i, expanded_len_adjust = 0, out;
11218   tree *elts;
11219
11220   if (t == error_mark_node)
11221     return error_mark_node;
11222
11223   len = TREE_VEC_LENGTH (t);
11224   elts = XALLOCAVEC (tree, len);
11225
11226   for (i = 0; i < len; i++)
11227     {
11228       tree orig_arg = TREE_VEC_ELT (t, i);
11229       tree new_arg;
11230
11231       if (TREE_CODE (orig_arg) == TREE_VEC)
11232         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
11233       else if (PACK_EXPANSION_P (orig_arg))
11234         {
11235           /* Substitute into an expansion expression.  */
11236           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
11237
11238           if (TREE_CODE (new_arg) == TREE_VEC)
11239             /* Add to the expanded length adjustment the number of
11240                expanded arguments. We subtract one from this
11241                measurement, because the argument pack expression
11242                itself is already counted as 1 in
11243                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
11244                the argument pack is empty.  */
11245             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
11246         }
11247       else if (ARGUMENT_PACK_P (orig_arg))
11248         {
11249           /* Substitute into each of the arguments.  */
11250           new_arg = TYPE_P (orig_arg)
11251             ? cxx_make_type (TREE_CODE (orig_arg))
11252             : make_node (TREE_CODE (orig_arg));
11253           
11254           SET_ARGUMENT_PACK_ARGS (
11255             new_arg,
11256             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
11257                                   args, complain, in_decl));
11258
11259           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
11260             new_arg = error_mark_node;
11261
11262           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
11263             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
11264                                           complain, in_decl);
11265             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
11266
11267             if (TREE_TYPE (new_arg) == error_mark_node)
11268               new_arg = error_mark_node;
11269           }
11270         }
11271       else
11272         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
11273
11274       if (new_arg == error_mark_node)
11275         return error_mark_node;
11276
11277       elts[i] = new_arg;
11278       if (new_arg != orig_arg)
11279         need_new = 1;
11280     }
11281
11282   if (!need_new)
11283     return t;
11284
11285   /* Make space for the expanded arguments coming from template
11286      argument packs.  */
11287   t = make_tree_vec (len + expanded_len_adjust);
11288   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
11289      arguments for a member template.
11290      In that case each TREE_VEC in ORIG_T represents a level of template
11291      arguments, and ORIG_T won't carry any non defaulted argument count.
11292      It will rather be the nested TREE_VECs that will carry one.
11293      In other words, ORIG_T carries a non defaulted argument count only
11294      if it doesn't contain any nested TREE_VEC.  */
11295   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
11296     {
11297       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
11298       count += expanded_len_adjust;
11299       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
11300     }
11301   for (i = 0, out = 0; i < len; i++)
11302     {
11303       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
11304            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
11305           && TREE_CODE (elts[i]) == TREE_VEC)
11306         {
11307           int idx;
11308
11309           /* Now expand the template argument pack "in place".  */
11310           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
11311             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
11312         }
11313       else
11314         {
11315           TREE_VEC_ELT (t, out) = elts[i];
11316           out++;
11317         }
11318     }
11319
11320   return t;
11321 }
11322
11323 /* Return the result of substituting ARGS into the template parameters
11324    given by PARMS.  If there are m levels of ARGS and m + n levels of
11325    PARMS, then the result will contain n levels of PARMS.  For
11326    example, if PARMS is `template <class T> template <class U>
11327    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
11328    result will be `template <int*, double, class V>'.  */
11329
11330 static tree
11331 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
11332 {
11333   tree r = NULL_TREE;
11334   tree* new_parms;
11335
11336   /* When substituting into a template, we must set
11337      PROCESSING_TEMPLATE_DECL as the template parameters may be
11338      dependent if they are based on one-another, and the dependency
11339      predicates are short-circuit outside of templates.  */
11340   ++processing_template_decl;
11341
11342   for (new_parms = &r;
11343        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
11344        new_parms = &(TREE_CHAIN (*new_parms)),
11345          parms = TREE_CHAIN (parms))
11346     {
11347       tree new_vec =
11348         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
11349       int i;
11350
11351       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
11352         {
11353           tree tuple;
11354
11355           if (parms == error_mark_node)
11356             continue;
11357
11358           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
11359
11360           if (tuple == error_mark_node)
11361             continue;
11362
11363           TREE_VEC_ELT (new_vec, i) =
11364             tsubst_template_parm (tuple, args, complain);
11365         }
11366
11367       *new_parms =
11368         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
11369                              - TMPL_ARGS_DEPTH (args)),
11370                    new_vec, NULL_TREE);
11371     }
11372
11373   --processing_template_decl;
11374
11375   return r;
11376 }
11377
11378 /* Return the result of substituting ARGS into one template parameter
11379    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
11380    parameter and which TREE_PURPOSE is the default argument of the
11381    template parameter.  */
11382
11383 static tree
11384 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
11385 {
11386   tree default_value, parm_decl;
11387
11388   if (args == NULL_TREE
11389       || t == NULL_TREE
11390       || t == error_mark_node)
11391     return t;
11392
11393   gcc_assert (TREE_CODE (t) == TREE_LIST);
11394
11395   default_value = TREE_PURPOSE (t);
11396   parm_decl = TREE_VALUE (t);
11397
11398   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
11399   if (TREE_CODE (parm_decl) == PARM_DECL
11400       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
11401     parm_decl = error_mark_node;
11402   default_value = tsubst_template_arg (default_value, args,
11403                                        complain, NULL_TREE);
11404
11405   return build_tree_list (default_value, parm_decl);
11406 }
11407
11408 /* Substitute the ARGS into the indicated aggregate (or enumeration)
11409    type T.  If T is not an aggregate or enumeration type, it is
11410    handled as if by tsubst.  IN_DECL is as for tsubst.  If
11411    ENTERING_SCOPE is nonzero, T is the context for a template which
11412    we are presently tsubst'ing.  Return the substituted value.  */
11413
11414 static tree
11415 tsubst_aggr_type (tree t,
11416                   tree args,
11417                   tsubst_flags_t complain,
11418                   tree in_decl,
11419                   int entering_scope)
11420 {
11421   if (t == NULL_TREE)
11422     return NULL_TREE;
11423
11424   switch (TREE_CODE (t))
11425     {
11426     case RECORD_TYPE:
11427       if (TYPE_PTRMEMFUNC_P (t))
11428         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
11429
11430       /* Else fall through.  */
11431     case ENUMERAL_TYPE:
11432     case UNION_TYPE:
11433       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
11434         {
11435           tree argvec;
11436           tree context;
11437           tree r;
11438           int saved_unevaluated_operand;
11439           int saved_inhibit_evaluation_warnings;
11440
11441           /* In "sizeof(X<I>)" we need to evaluate "I".  */
11442           saved_unevaluated_operand = cp_unevaluated_operand;
11443           cp_unevaluated_operand = 0;
11444           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
11445           c_inhibit_evaluation_warnings = 0;
11446
11447           /* First, determine the context for the type we are looking
11448              up.  */
11449           context = TYPE_CONTEXT (t);
11450           if (context && TYPE_P (context))
11451             {
11452               context = tsubst_aggr_type (context, args, complain,
11453                                           in_decl, /*entering_scope=*/1);
11454               /* If context is a nested class inside a class template,
11455                  it may still need to be instantiated (c++/33959).  */
11456               context = complete_type (context);
11457             }
11458
11459           /* Then, figure out what arguments are appropriate for the
11460              type we are trying to find.  For example, given:
11461
11462                template <class T> struct S;
11463                template <class T, class U> void f(T, U) { S<U> su; }
11464
11465              and supposing that we are instantiating f<int, double>,
11466              then our ARGS will be {int, double}, but, when looking up
11467              S we only want {double}.  */
11468           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
11469                                          complain, in_decl);
11470           if (argvec == error_mark_node)
11471             r = error_mark_node;
11472           else
11473             {
11474               r = lookup_template_class (t, argvec, in_decl, context,
11475                                          entering_scope, complain);
11476               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
11477             }
11478
11479           cp_unevaluated_operand = saved_unevaluated_operand;
11480           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
11481
11482           return r;
11483         }
11484       else
11485         /* This is not a template type, so there's nothing to do.  */
11486         return t;
11487
11488     default:
11489       return tsubst (t, args, complain, in_decl);
11490     }
11491 }
11492
11493 /* Substitute into the default argument ARG (a default argument for
11494    FN), which has the indicated TYPE.  */
11495
11496 tree
11497 tsubst_default_argument (tree fn, tree type, tree arg, tsubst_flags_t complain)
11498 {
11499   tree saved_class_ptr = NULL_TREE;
11500   tree saved_class_ref = NULL_TREE;
11501   int errs = errorcount + sorrycount;
11502
11503   /* This can happen in invalid code.  */
11504   if (TREE_CODE (arg) == DEFAULT_ARG)
11505     return arg;
11506
11507   /* This default argument came from a template.  Instantiate the
11508      default argument here, not in tsubst.  In the case of
11509      something like:
11510
11511        template <class T>
11512        struct S {
11513          static T t();
11514          void f(T = t());
11515        };
11516
11517      we must be careful to do name lookup in the scope of S<T>,
11518      rather than in the current class.  */
11519   push_access_scope (fn);
11520   /* The "this" pointer is not valid in a default argument.  */
11521   if (cfun)
11522     {
11523       saved_class_ptr = current_class_ptr;
11524       cp_function_chain->x_current_class_ptr = NULL_TREE;
11525       saved_class_ref = current_class_ref;
11526       cp_function_chain->x_current_class_ref = NULL_TREE;
11527     }
11528
11529   push_deferring_access_checks(dk_no_deferred);
11530   /* The default argument expression may cause implicitly defined
11531      member functions to be synthesized, which will result in garbage
11532      collection.  We must treat this situation as if we were within
11533      the body of function so as to avoid collecting live data on the
11534      stack.  */
11535   ++function_depth;
11536   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
11537                      complain, NULL_TREE,
11538                      /*integral_constant_expression_p=*/false);
11539   --function_depth;
11540   pop_deferring_access_checks();
11541
11542   /* Restore the "this" pointer.  */
11543   if (cfun)
11544     {
11545       cp_function_chain->x_current_class_ptr = saved_class_ptr;
11546       cp_function_chain->x_current_class_ref = saved_class_ref;
11547     }
11548
11549   if (errorcount+sorrycount > errs
11550       && (complain & tf_warning_or_error))
11551     inform (input_location,
11552             "  when instantiating default argument for call to %D", fn);
11553
11554   /* Make sure the default argument is reasonable.  */
11555   arg = check_default_argument (type, arg, complain);
11556
11557   pop_access_scope (fn);
11558
11559   return arg;
11560 }
11561
11562 /* Substitute into all the default arguments for FN.  */
11563
11564 static void
11565 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
11566 {
11567   tree arg;
11568   tree tmpl_args;
11569
11570   tmpl_args = DECL_TI_ARGS (fn);
11571
11572   /* If this function is not yet instantiated, we certainly don't need
11573      its default arguments.  */
11574   if (uses_template_parms (tmpl_args))
11575     return;
11576   /* Don't do this again for clones.  */
11577   if (DECL_CLONED_FUNCTION_P (fn))
11578     return;
11579
11580   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
11581        arg;
11582        arg = TREE_CHAIN (arg))
11583     if (TREE_PURPOSE (arg))
11584       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
11585                                                     TREE_VALUE (arg),
11586                                                     TREE_PURPOSE (arg),
11587                                                     complain);
11588 }
11589
11590 /* Substitute the ARGS into the T, which is a _DECL.  Return the
11591    result of the substitution.  Issue error and warning messages under
11592    control of COMPLAIN.  */
11593
11594 static tree
11595 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
11596 {
11597 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
11598   location_t saved_loc;
11599   tree r = NULL_TREE;
11600   tree in_decl = t;
11601   hashval_t hash = 0;
11602
11603   /* Set the filename and linenumber to improve error-reporting.  */
11604   saved_loc = input_location;
11605   input_location = DECL_SOURCE_LOCATION (t);
11606
11607   switch (TREE_CODE (t))
11608     {
11609     case TEMPLATE_DECL:
11610       {
11611         /* We can get here when processing a member function template,
11612            member class template, or template template parameter.  */
11613         tree decl = DECL_TEMPLATE_RESULT (t);
11614         tree spec;
11615         tree tmpl_args;
11616         tree full_args;
11617
11618         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11619           {
11620             /* Template template parameter is treated here.  */
11621             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11622             if (new_type == error_mark_node)
11623               r = error_mark_node;
11624             /* If we get a real template back, return it.  This can happen in
11625                the context of most_specialized_partial_spec.  */
11626             else if (TREE_CODE (new_type) == TEMPLATE_DECL)
11627               r = new_type;
11628             else
11629               /* The new TEMPLATE_DECL was built in
11630                  reduce_template_parm_level.  */
11631               r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
11632             break;
11633           }
11634
11635         /* We might already have an instance of this template.
11636            The ARGS are for the surrounding class type, so the
11637            full args contain the tsubst'd args for the context,
11638            plus the innermost args from the template decl.  */
11639         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
11640           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
11641           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
11642         /* Because this is a template, the arguments will still be
11643            dependent, even after substitution.  If
11644            PROCESSING_TEMPLATE_DECL is not set, the dependency
11645            predicates will short-circuit.  */
11646         ++processing_template_decl;
11647         full_args = tsubst_template_args (tmpl_args, args,
11648                                           complain, in_decl);
11649         --processing_template_decl;
11650         if (full_args == error_mark_node)
11651           RETURN (error_mark_node);
11652
11653         /* If this is a default template template argument,
11654            tsubst might not have changed anything.  */
11655         if (full_args == tmpl_args)
11656           RETURN (t);
11657
11658         hash = hash_tmpl_and_args (t, full_args);
11659         spec = retrieve_specialization (t, full_args, hash);
11660         if (spec != NULL_TREE)
11661           {
11662             r = spec;
11663             break;
11664           }
11665
11666         /* Make a new template decl.  It will be similar to the
11667            original, but will record the current template arguments.
11668            We also create a new function declaration, which is just
11669            like the old one, but points to this new template, rather
11670            than the old one.  */
11671         r = copy_decl (t);
11672         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
11673         DECL_CHAIN (r) = NULL_TREE;
11674
11675         // Build new template info linking to the original template decl.
11676         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
11677
11678         if (TREE_CODE (decl) == TYPE_DECL
11679             && !TYPE_DECL_ALIAS_P (decl))
11680           {
11681             tree new_type;
11682             ++processing_template_decl;
11683             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11684             --processing_template_decl;
11685             if (new_type == error_mark_node)
11686               RETURN (error_mark_node);
11687
11688             TREE_TYPE (r) = new_type;
11689             /* For a partial specialization, we need to keep pointing to
11690                the primary template.  */
11691             if (!DECL_TEMPLATE_SPECIALIZATION (t))
11692               CLASSTYPE_TI_TEMPLATE (new_type) = r;
11693             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
11694             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
11695             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
11696           }
11697         else
11698           {
11699             tree new_decl;
11700             ++processing_template_decl;
11701             new_decl = tsubst (decl, args, complain, in_decl);
11702             --processing_template_decl;
11703             if (new_decl == error_mark_node)
11704               RETURN (error_mark_node);
11705
11706             DECL_TEMPLATE_RESULT (r) = new_decl;
11707             DECL_TI_TEMPLATE (new_decl) = r;
11708             TREE_TYPE (r) = TREE_TYPE (new_decl);
11709             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
11710             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
11711           }
11712
11713         SET_DECL_IMPLICIT_INSTANTIATION (r);
11714         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
11715         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
11716
11717         /* The template parameters for this new template are all the
11718            template parameters for the old template, except the
11719            outermost level of parameters.  */
11720         DECL_TEMPLATE_PARMS (r)
11721           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
11722                                    complain);
11723
11724         if (PRIMARY_TEMPLATE_P (t))
11725           DECL_PRIMARY_TEMPLATE (r) = r;
11726
11727         if (TREE_CODE (decl) != TYPE_DECL && !VAR_P (decl))
11728           /* Record this non-type partial instantiation.  */
11729           register_specialization (r, t,
11730                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
11731                                    false, hash);
11732       }
11733       break;
11734
11735     case FUNCTION_DECL:
11736       {
11737         tree ctx;
11738         tree argvec = NULL_TREE;
11739         tree *friends;
11740         tree gen_tmpl;
11741         tree type;
11742         int member;
11743         int args_depth;
11744         int parms_depth;
11745
11746         /* Nobody should be tsubst'ing into non-template functions.  */
11747         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
11748
11749         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
11750           {
11751             tree spec;
11752             bool dependent_p;
11753
11754             /* If T is not dependent, just return it.  We have to
11755                increment PROCESSING_TEMPLATE_DECL because
11756                value_dependent_expression_p assumes that nothing is
11757                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
11758             ++processing_template_decl;
11759             dependent_p = value_dependent_expression_p (t);
11760             --processing_template_decl;
11761             if (!dependent_p)
11762               RETURN (t);
11763
11764             /* Calculate the most general template of which R is a
11765                specialization, and the complete set of arguments used to
11766                specialize R.  */
11767             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
11768             argvec = tsubst_template_args (DECL_TI_ARGS
11769                                           (DECL_TEMPLATE_RESULT
11770                                                  (DECL_TI_TEMPLATE (t))),
11771                                            args, complain, in_decl);
11772             if (argvec == error_mark_node)
11773               RETURN (error_mark_node);
11774
11775             /* Check to see if we already have this specialization.  */
11776             hash = hash_tmpl_and_args (gen_tmpl, argvec);
11777             spec = retrieve_specialization (gen_tmpl, argvec, hash);
11778
11779             if (spec)
11780               {
11781                 r = spec;
11782                 break;
11783               }
11784
11785             /* We can see more levels of arguments than parameters if
11786                there was a specialization of a member template, like
11787                this:
11788
11789                  template <class T> struct S { template <class U> void f(); }
11790                  template <> template <class U> void S<int>::f(U);
11791
11792                Here, we'll be substituting into the specialization,
11793                because that's where we can find the code we actually
11794                want to generate, but we'll have enough arguments for
11795                the most general template.
11796
11797                We also deal with the peculiar case:
11798
11799                  template <class T> struct S {
11800                    template <class U> friend void f();
11801                  };
11802                  template <class U> void f() {}
11803                  template S<int>;
11804                  template void f<double>();
11805
11806                Here, the ARGS for the instantiation of will be {int,
11807                double}.  But, we only need as many ARGS as there are
11808                levels of template parameters in CODE_PATTERN.  We are
11809                careful not to get fooled into reducing the ARGS in
11810                situations like:
11811
11812                  template <class T> struct S { template <class U> void f(U); }
11813                  template <class T> template <> void S<T>::f(int) {}
11814
11815                which we can spot because the pattern will be a
11816                specialization in this case.  */
11817             args_depth = TMPL_ARGS_DEPTH (args);
11818             parms_depth =
11819               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
11820             if (args_depth > parms_depth
11821                 && !DECL_TEMPLATE_SPECIALIZATION (t))
11822               args = get_innermost_template_args (args, parms_depth);
11823           }
11824         else
11825           {
11826             /* This special case arises when we have something like this:
11827
11828                  template <class T> struct S {
11829                    friend void f<int>(int, double);
11830                  };
11831
11832                Here, the DECL_TI_TEMPLATE for the friend declaration
11833                will be an IDENTIFIER_NODE.  We are being called from
11834                tsubst_friend_function, and we want only to create a
11835                new decl (R) with appropriate types so that we can call
11836                determine_specialization.  */
11837             gen_tmpl = NULL_TREE;
11838           }
11839
11840         if (DECL_CLASS_SCOPE_P (t))
11841           {
11842             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
11843               member = 2;
11844             else
11845               member = 1;
11846             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
11847                                     complain, t, /*entering_scope=*/1);
11848           }
11849         else
11850           {
11851             member = 0;
11852             ctx = DECL_CONTEXT (t);
11853           }
11854         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11855         if (type == error_mark_node)
11856           RETURN (error_mark_node);
11857
11858         /* If we hit excessive deduction depth, the type is bogus even if
11859            it isn't error_mark_node, so don't build a decl.  */
11860         if (excessive_deduction_depth)
11861           RETURN (error_mark_node);
11862
11863         /* We do NOT check for matching decls pushed separately at this
11864            point, as they may not represent instantiations of this
11865            template, and in any case are considered separate under the
11866            discrete model.  */
11867         r = copy_decl (t);
11868         DECL_USE_TEMPLATE (r) = 0;
11869         TREE_TYPE (r) = type;
11870         /* Clear out the mangled name and RTL for the instantiation.  */
11871         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
11872         SET_DECL_RTL (r, NULL);
11873         /* Leave DECL_INITIAL set on deleted instantiations.  */
11874         if (!DECL_DELETED_FN (r))
11875           DECL_INITIAL (r) = NULL_TREE;
11876         DECL_CONTEXT (r) = ctx;
11877
11878         /* OpenMP UDRs have the only argument a reference to the declared
11879            type.  We want to diagnose if the declared type is a reference,
11880            which is invalid, but as references to references are usually
11881            quietly merged, diagnose it here.  */
11882         if (DECL_OMP_DECLARE_REDUCTION_P (t))
11883           {
11884             tree argtype
11885               = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
11886             argtype = tsubst (argtype, args, complain, in_decl);
11887             if (TREE_CODE (argtype) == REFERENCE_TYPE)
11888               error_at (DECL_SOURCE_LOCATION (t),
11889                         "reference type %qT in "
11890                         "%<#pragma omp declare reduction%>", argtype);
11891             if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
11892               DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
11893                                                 argtype);
11894           }
11895
11896         if (member && DECL_CONV_FN_P (r))
11897           /* Type-conversion operator.  Reconstruct the name, in
11898              case it's the name of one of the template's parameters.  */
11899           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
11900
11901         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
11902                                      complain, t);
11903         DECL_RESULT (r) = NULL_TREE;
11904
11905         TREE_STATIC (r) = 0;
11906         TREE_PUBLIC (r) = TREE_PUBLIC (t);
11907         DECL_EXTERNAL (r) = 1;
11908         /* If this is an instantiation of a function with internal
11909            linkage, we already know what object file linkage will be
11910            assigned to the instantiation.  */
11911         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
11912         DECL_DEFER_OUTPUT (r) = 0;
11913         DECL_CHAIN (r) = NULL_TREE;
11914         DECL_PENDING_INLINE_INFO (r) = 0;
11915         DECL_PENDING_INLINE_P (r) = 0;
11916         DECL_SAVED_TREE (r) = NULL_TREE;
11917         DECL_STRUCT_FUNCTION (r) = NULL;
11918         TREE_USED (r) = 0;
11919         /* We'll re-clone as appropriate in instantiate_template.  */
11920         DECL_CLONED_FUNCTION (r) = NULL_TREE;
11921
11922         /* If we aren't complaining now, return on error before we register
11923            the specialization so that we'll complain eventually.  */
11924         if ((complain & tf_error) == 0
11925             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
11926             && !grok_op_properties (r, /*complain=*/false))
11927           RETURN (error_mark_node);
11928
11929         /* When instantiating a constrained member, substitute
11930            into the constraints to create a new constraint.  */
11931         if (tree ci = get_constraints (t))
11932           if (member)
11933             {
11934               ci = tsubst_constraint_info (ci, argvec, complain, NULL_TREE);
11935               set_constraints (r, ci);
11936             }
11937
11938         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
11939            this in the special friend case mentioned above where
11940            GEN_TMPL is NULL.  */
11941         if (gen_tmpl)
11942           {
11943             DECL_TEMPLATE_INFO (r)
11944               = build_template_info (gen_tmpl, argvec);
11945             SET_DECL_IMPLICIT_INSTANTIATION (r);
11946
11947             tree new_r
11948               = register_specialization (r, gen_tmpl, argvec, false, hash);
11949             if (new_r != r)
11950               /* We instantiated this while substituting into
11951                  the type earlier (template/friend54.C).  */
11952               RETURN (new_r);
11953
11954             /* We're not supposed to instantiate default arguments
11955                until they are called, for a template.  But, for a
11956                declaration like:
11957
11958                  template <class T> void f ()
11959                  { extern void g(int i = T()); }
11960
11961                we should do the substitution when the template is
11962                instantiated.  We handle the member function case in
11963                instantiate_class_template since the default arguments
11964                might refer to other members of the class.  */
11965             if (!member
11966                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
11967                 && !uses_template_parms (argvec))
11968               tsubst_default_arguments (r, complain);
11969           }
11970         else
11971           DECL_TEMPLATE_INFO (r) = NULL_TREE;
11972
11973         /* Copy the list of befriending classes.  */
11974         for (friends = &DECL_BEFRIENDING_CLASSES (r);
11975              *friends;
11976              friends = &TREE_CHAIN (*friends))
11977           {
11978             *friends = copy_node (*friends);
11979             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
11980                                             args, complain,
11981                                             in_decl);
11982           }
11983
11984         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
11985           {
11986             maybe_retrofit_in_chrg (r);
11987             if (DECL_CONSTRUCTOR_P (r))
11988               grok_ctor_properties (ctx, r);
11989             if (DECL_INHERITED_CTOR_BASE (r))
11990               deduce_inheriting_ctor (r);
11991             /* If this is an instantiation of a member template, clone it.
11992                If it isn't, that'll be handled by
11993                clone_constructors_and_destructors.  */
11994             if (PRIMARY_TEMPLATE_P (gen_tmpl))
11995               clone_function_decl (r, /*update_method_vec_p=*/0);
11996           }
11997         else if ((complain & tf_error) != 0
11998                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
11999                  && !grok_op_properties (r, /*complain=*/true))
12000           RETURN (error_mark_node);
12001
12002         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
12003           SET_DECL_FRIEND_CONTEXT (r,
12004                                    tsubst (DECL_FRIEND_CONTEXT (t),
12005                                             args, complain, in_decl));
12006
12007         /* Possibly limit visibility based on template args.  */
12008         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
12009         if (DECL_VISIBILITY_SPECIFIED (t))
12010           {
12011             DECL_VISIBILITY_SPECIFIED (r) = 0;
12012             DECL_ATTRIBUTES (r)
12013               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
12014           }
12015         determine_visibility (r);
12016         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
12017             && !processing_template_decl)
12018           defaulted_late_check (r);
12019
12020         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
12021                                         args, complain, in_decl);
12022       }
12023       break;
12024
12025     case PARM_DECL:
12026       {
12027         tree type = NULL_TREE;
12028         int i, len = 1;
12029         tree expanded_types = NULL_TREE;
12030         tree prev_r = NULL_TREE;
12031         tree first_r = NULL_TREE;
12032
12033         if (DECL_PACK_P (t))
12034           {
12035             /* If there is a local specialization that isn't a
12036                parameter pack, it means that we're doing a "simple"
12037                substitution from inside tsubst_pack_expansion. Just
12038                return the local specialization (which will be a single
12039                parm).  */
12040             tree spec = retrieve_local_specialization (t);
12041             if (spec 
12042                 && TREE_CODE (spec) == PARM_DECL
12043                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
12044               RETURN (spec);
12045
12046             /* Expand the TYPE_PACK_EXPANSION that provides the types for
12047                the parameters in this function parameter pack.  */
12048             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
12049                                                     complain, in_decl);
12050             if (TREE_CODE (expanded_types) == TREE_VEC)
12051               {
12052                 len = TREE_VEC_LENGTH (expanded_types);
12053
12054                 /* Zero-length parameter packs are boring. Just substitute
12055                    into the chain.  */
12056                 if (len == 0)
12057                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
12058                                   TREE_CHAIN (t)));
12059               }
12060             else
12061               {
12062                 /* All we did was update the type. Make a note of that.  */
12063                 type = expanded_types;
12064                 expanded_types = NULL_TREE;
12065               }
12066           }
12067
12068         /* Loop through all of the parameters we'll build. When T is
12069            a function parameter pack, LEN is the number of expanded
12070            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
12071         r = NULL_TREE;
12072         for (i = 0; i < len; ++i)
12073           {
12074             prev_r = r;
12075             r = copy_node (t);
12076             if (DECL_TEMPLATE_PARM_P (t))
12077               SET_DECL_TEMPLATE_PARM_P (r);
12078
12079             if (expanded_types)
12080               /* We're on the Ith parameter of the function parameter
12081                  pack.  */
12082               {
12083                 /* Get the Ith type.  */
12084                 type = TREE_VEC_ELT (expanded_types, i);
12085
12086                 /* Rename the parameter to include the index.  */
12087                 DECL_NAME (r)
12088                   = make_ith_pack_parameter_name (DECL_NAME (r), i);
12089               }
12090             else if (!type)
12091               /* We're dealing with a normal parameter.  */
12092               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12093
12094             type = type_decays_to (type);
12095             TREE_TYPE (r) = type;
12096             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
12097
12098             if (DECL_INITIAL (r))
12099               {
12100                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
12101                   DECL_INITIAL (r) = TREE_TYPE (r);
12102                 else
12103                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
12104                                              complain, in_decl);
12105               }
12106
12107             DECL_CONTEXT (r) = NULL_TREE;
12108
12109             if (!DECL_TEMPLATE_PARM_P (r))
12110               DECL_ARG_TYPE (r) = type_passed_as (type);
12111
12112             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
12113                                             args, complain, in_decl);
12114
12115             /* Keep track of the first new parameter we
12116                generate. That's what will be returned to the
12117                caller.  */
12118             if (!first_r)
12119               first_r = r;
12120
12121             /* Build a proper chain of parameters when substituting
12122                into a function parameter pack.  */
12123             if (prev_r)
12124               DECL_CHAIN (prev_r) = r;
12125           }
12126
12127         /* If cp_unevaluated_operand is set, we're just looking for a
12128            single dummy parameter, so don't keep going.  */
12129         if (DECL_CHAIN (t) && !cp_unevaluated_operand)
12130           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
12131                                    complain, DECL_CHAIN (t));
12132
12133         /* FIRST_R contains the start of the chain we've built.  */
12134         r = first_r;
12135       }
12136       break;
12137
12138     case FIELD_DECL:
12139       {
12140         tree type = NULL_TREE;
12141         tree vec = NULL_TREE;
12142         tree expanded_types = NULL_TREE;
12143         int len = 1;
12144
12145         if (PACK_EXPANSION_P (TREE_TYPE (t)))
12146           {
12147             /* This field is a lambda capture pack.  Return a TREE_VEC of
12148                the expanded fields to instantiate_class_template_1 and
12149                store them in the specializations hash table as a
12150                NONTYPE_ARGUMENT_PACK so that tsubst_copy can find them.  */
12151             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
12152                                                     complain, in_decl);
12153             if (TREE_CODE (expanded_types) == TREE_VEC)
12154               {
12155                 len = TREE_VEC_LENGTH (expanded_types);
12156                 vec = make_tree_vec (len);
12157               }
12158             else
12159               {
12160                 /* All we did was update the type. Make a note of that.  */
12161                 type = expanded_types;
12162                 expanded_types = NULL_TREE;
12163               }
12164           }
12165
12166         for (int i = 0; i < len; ++i)
12167           {
12168             r = copy_decl (t);
12169             if (expanded_types)
12170               {
12171                 type = TREE_VEC_ELT (expanded_types, i);
12172                 DECL_NAME (r)
12173                   = make_ith_pack_parameter_name (DECL_NAME (r), i);
12174               }
12175             else if (!type)
12176               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12177
12178             if (type == error_mark_node)
12179               RETURN (error_mark_node);
12180             TREE_TYPE (r) = type;
12181             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
12182
12183             if (DECL_C_BIT_FIELD (r))
12184               /* For bit-fields, DECL_INITIAL gives the number of bits.  For
12185                  non-bit-fields DECL_INITIAL is a non-static data member
12186                  initializer, which gets deferred instantiation.  */
12187               DECL_INITIAL (r)
12188                 = tsubst_expr (DECL_INITIAL (t), args,
12189                                complain, in_decl,
12190                                /*integral_constant_expression_p=*/true);
12191             else if (DECL_INITIAL (t))
12192               {
12193                 /* Set up DECL_TEMPLATE_INFO so that we can get at the
12194                    NSDMI in perform_member_init.  Still set DECL_INITIAL
12195                    so that we know there is one.  */
12196                 DECL_INITIAL (r) = void_node;
12197                 gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
12198                 retrofit_lang_decl (r);
12199                 DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
12200               }
12201             /* We don't have to set DECL_CONTEXT here; it is set by
12202                finish_member_declaration.  */
12203             DECL_CHAIN (r) = NULL_TREE;
12204
12205             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
12206                                             args, complain, in_decl);
12207
12208             if (vec)
12209               TREE_VEC_ELT (vec, i) = r;
12210           }
12211
12212         if (vec)
12213           {
12214             r = vec;
12215             tree pack = make_node (NONTYPE_ARGUMENT_PACK);
12216             tree tpack = cxx_make_type (TYPE_ARGUMENT_PACK);
12217             SET_ARGUMENT_PACK_ARGS (pack, vec);
12218             SET_ARGUMENT_PACK_ARGS (tpack, expanded_types);
12219             TREE_TYPE (pack) = tpack;
12220             register_specialization (pack, t, args, false, 0);
12221           }
12222       }
12223       break;
12224
12225     case USING_DECL:
12226       /* We reach here only for member using decls.  We also need to check
12227          uses_template_parms because DECL_DEPENDENT_P is not set for a
12228          using-declaration that designates a member of the current
12229          instantiation (c++/53549).  */
12230       if (DECL_DEPENDENT_P (t)
12231           || uses_template_parms (USING_DECL_SCOPE (t)))
12232         {
12233           tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
12234                                          complain, in_decl);
12235           tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
12236           r = do_class_using_decl (inst_scope, name);
12237           if (!r)
12238             r = error_mark_node;
12239           else
12240             {
12241               TREE_PROTECTED (r) = TREE_PROTECTED (t);
12242               TREE_PRIVATE (r) = TREE_PRIVATE (t);
12243             }
12244         }
12245       else
12246         {
12247           r = copy_node (t);
12248           DECL_CHAIN (r) = NULL_TREE;
12249         }
12250       break;
12251
12252     case TYPE_DECL:
12253     case VAR_DECL:
12254       {
12255         tree argvec = NULL_TREE;
12256         tree gen_tmpl = NULL_TREE;
12257         tree spec;
12258         tree tmpl = NULL_TREE;
12259         tree ctx;
12260         tree type = NULL_TREE;
12261         bool local_p;
12262
12263         if (TREE_TYPE (t) == error_mark_node)
12264           RETURN (error_mark_node);
12265
12266         if (TREE_CODE (t) == TYPE_DECL
12267             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
12268           {
12269             /* If this is the canonical decl, we don't have to
12270                mess with instantiations, and often we can't (for
12271                typename, template type parms and such).  Note that
12272                TYPE_NAME is not correct for the above test if
12273                we've copied the type for a typedef.  */
12274             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12275             if (type == error_mark_node)
12276               RETURN (error_mark_node);
12277             r = TYPE_NAME (type);
12278             break;
12279           }
12280
12281         /* Check to see if we already have the specialization we
12282            need.  */
12283         spec = NULL_TREE;
12284         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
12285           {
12286             /* T is a static data member or namespace-scope entity.
12287                We have to substitute into namespace-scope variables
12288                (not just variable templates) because of cases like:
12289                
12290                  template <class T> void f() { extern T t; }
12291
12292                where the entity referenced is not known until
12293                instantiation time.  */
12294             local_p = false;
12295             ctx = DECL_CONTEXT (t);
12296             if (DECL_CLASS_SCOPE_P (t))
12297               {
12298                 ctx = tsubst_aggr_type (ctx, args,
12299                                         complain,
12300                                         in_decl, /*entering_scope=*/1);
12301                 /* If CTX is unchanged, then T is in fact the
12302                    specialization we want.  That situation occurs when
12303                    referencing a static data member within in its own
12304                    class.  We can use pointer equality, rather than
12305                    same_type_p, because DECL_CONTEXT is always
12306                    canonical...  */
12307                 if (ctx == DECL_CONTEXT (t)
12308                     /* ... unless T is a member template; in which
12309                        case our caller can be willing to create a
12310                        specialization of that template represented
12311                        by T.  */
12312                     && !(DECL_TI_TEMPLATE (t)
12313                          && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
12314                   spec = t;
12315               }
12316
12317             if (!spec)
12318               {
12319                 tmpl = DECL_TI_TEMPLATE (t);
12320                 gen_tmpl = most_general_template (tmpl);
12321                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
12322                 if (argvec != error_mark_node)
12323                   argvec = (coerce_innermost_template_parms
12324                             (DECL_TEMPLATE_PARMS (gen_tmpl),
12325                              argvec, t, complain,
12326                              /*all*/true, /*defarg*/true));
12327                 if (argvec == error_mark_node)
12328                   RETURN (error_mark_node);
12329                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
12330                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
12331               }
12332           }
12333         else
12334           {
12335             /* A local variable.  */
12336             local_p = true;
12337             /* Subsequent calls to pushdecl will fill this in.  */
12338             ctx = NULL_TREE;
12339             /* Unless this is a reference to a static variable from an
12340                enclosing function, in which case we need to fill it in now.  */
12341             if (TREE_STATIC (t))
12342               {
12343                 tree fn = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
12344                 if (fn != current_function_decl)
12345                   ctx = fn;
12346               }
12347             spec = retrieve_local_specialization (t);
12348           }
12349         /* If we already have the specialization we need, there is
12350            nothing more to do.  */ 
12351         if (spec)
12352           {
12353             r = spec;
12354             break;
12355           }
12356
12357         /* Create a new node for the specialization we need.  */
12358         r = copy_decl (t);
12359         if (type == NULL_TREE)
12360           {
12361             if (is_typedef_decl (t))
12362               type = DECL_ORIGINAL_TYPE (t);
12363             else
12364               type = TREE_TYPE (t);
12365             if (VAR_P (t)
12366                 && VAR_HAD_UNKNOWN_BOUND (t)
12367                 && type != error_mark_node)
12368               type = strip_array_domain (type);
12369             type = tsubst (type, args, complain, in_decl);
12370           }
12371         if (VAR_P (r))
12372           {
12373             /* Even if the original location is out of scope, the
12374                newly substituted one is not.  */
12375             DECL_DEAD_FOR_LOCAL (r) = 0;
12376             DECL_INITIALIZED_P (r) = 0;
12377             DECL_TEMPLATE_INSTANTIATED (r) = 0;
12378             if (type == error_mark_node)
12379               RETURN (error_mark_node);
12380             if (TREE_CODE (type) == FUNCTION_TYPE)
12381               {
12382                 /* It may seem that this case cannot occur, since:
12383
12384                    typedef void f();
12385                    void g() { f x; }
12386
12387                    declares a function, not a variable.  However:
12388       
12389                    typedef void f();
12390                    template <typename T> void g() { T t; }
12391                    template void g<f>();
12392
12393                    is an attempt to declare a variable with function
12394                    type.  */
12395                 error ("variable %qD has function type",
12396                        /* R is not yet sufficiently initialized, so we
12397                           just use its name.  */
12398                        DECL_NAME (r));
12399                 RETURN (error_mark_node);
12400               }
12401             type = complete_type (type);
12402             /* Wait until cp_finish_decl to set this again, to handle
12403                circular dependency (template/instantiate6.C). */
12404             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
12405             type = check_var_type (DECL_NAME (r), type);
12406
12407             if (DECL_HAS_VALUE_EXPR_P (t))
12408               {
12409                 tree ve = DECL_VALUE_EXPR (t);
12410                 ve = tsubst_expr (ve, args, complain, in_decl,
12411                                   /*constant_expression_p=*/false);
12412                 if (REFERENCE_REF_P (ve))
12413                   {
12414                     gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
12415                     ve = TREE_OPERAND (ve, 0);
12416                   }
12417                 SET_DECL_VALUE_EXPR (r, ve);
12418               }
12419             if (CP_DECL_THREAD_LOCAL_P (r)
12420                 && !processing_template_decl)
12421               set_decl_tls_model (r, decl_default_tls_model (r));
12422           }
12423         else if (DECL_SELF_REFERENCE_P (t))
12424           SET_DECL_SELF_REFERENCE_P (r);
12425         TREE_TYPE (r) = type;
12426         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
12427         DECL_CONTEXT (r) = ctx;
12428         /* Clear out the mangled name and RTL for the instantiation.  */
12429         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
12430         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
12431           SET_DECL_RTL (r, NULL);
12432         /* The initializer must not be expanded until it is required;
12433            see [temp.inst].  */
12434         DECL_INITIAL (r) = NULL_TREE;
12435         if (VAR_P (r))
12436           DECL_MODE (r) = VOIDmode;
12437         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
12438           SET_DECL_RTL (r, NULL);
12439         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
12440         if (VAR_P (r))
12441           {
12442             /* Possibly limit visibility based on template args.  */
12443             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
12444             if (DECL_VISIBILITY_SPECIFIED (t))
12445               {
12446                 DECL_VISIBILITY_SPECIFIED (r) = 0;
12447                 DECL_ATTRIBUTES (r)
12448                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
12449               }
12450             determine_visibility (r);
12451           }
12452
12453         if (!local_p)
12454           {
12455             /* A static data member declaration is always marked
12456                external when it is declared in-class, even if an
12457                initializer is present.  We mimic the non-template
12458                processing here.  */
12459             DECL_EXTERNAL (r) = 1;
12460             if (DECL_NAMESPACE_SCOPE_P (t))
12461               DECL_NOT_REALLY_EXTERN (r) = 1;
12462
12463             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
12464             SET_DECL_IMPLICIT_INSTANTIATION (r);
12465             register_specialization (r, gen_tmpl, argvec, false, hash);
12466           }
12467         else
12468           {
12469             if (DECL_LANG_SPECIFIC (r))
12470               DECL_TEMPLATE_INFO (r) = NULL_TREE;
12471             if (!cp_unevaluated_operand)
12472               register_local_specialization (r, t);
12473           }
12474
12475         DECL_CHAIN (r) = NULL_TREE;
12476
12477         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
12478                                         /*flags=*/0,
12479                                         args, complain, in_decl);
12480
12481         /* Preserve a typedef that names a type.  */
12482         if (is_typedef_decl (r))
12483           {
12484             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
12485             set_underlying_type (r);
12486             if (TYPE_DECL_ALIAS_P (r) && type != error_mark_node)
12487               /* An alias template specialization can be dependent
12488                  even if its underlying type is not.  */
12489               TYPE_DEPENDENT_P_VALID (TREE_TYPE (r)) = false;
12490           }
12491
12492         layout_decl (r, 0);
12493       }
12494       break;
12495
12496     default:
12497       gcc_unreachable ();
12498     }
12499 #undef RETURN
12500
12501  out:
12502   /* Restore the file and line information.  */
12503   input_location = saved_loc;
12504
12505   return r;
12506 }
12507
12508 /* Substitute into the ARG_TYPES of a function type.
12509    If END is a TREE_CHAIN, leave it and any following types
12510    un-substituted.  */
12511
12512 static tree
12513 tsubst_arg_types (tree arg_types,
12514                   tree args,
12515                   tree end,
12516                   tsubst_flags_t complain,
12517                   tree in_decl)
12518 {
12519   tree remaining_arg_types;
12520   tree type = NULL_TREE;
12521   int i = 1;
12522   tree expanded_args = NULL_TREE;
12523   tree default_arg;
12524
12525   if (!arg_types || arg_types == void_list_node || arg_types == end)
12526     return arg_types;
12527
12528   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
12529                                           args, end, complain, in_decl);
12530   if (remaining_arg_types == error_mark_node)
12531     return error_mark_node;
12532
12533   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
12534     {
12535       /* For a pack expansion, perform substitution on the
12536          entire expression. Later on, we'll handle the arguments
12537          one-by-one.  */
12538       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
12539                                             args, complain, in_decl);
12540
12541       if (TREE_CODE (expanded_args) == TREE_VEC)
12542         /* So that we'll spin through the parameters, one by one.  */
12543         i = TREE_VEC_LENGTH (expanded_args);
12544       else
12545         {
12546           /* We only partially substituted into the parameter
12547              pack. Our type is TYPE_PACK_EXPANSION.  */
12548           type = expanded_args;
12549           expanded_args = NULL_TREE;
12550         }
12551     }
12552
12553   while (i > 0) {
12554     --i;
12555     
12556     if (expanded_args)
12557       type = TREE_VEC_ELT (expanded_args, i);
12558     else if (!type)
12559       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
12560
12561     if (type == error_mark_node)
12562       return error_mark_node;
12563     if (VOID_TYPE_P (type))
12564       {
12565         if (complain & tf_error)
12566           {
12567             error ("invalid parameter type %qT", type);
12568             if (in_decl)
12569               error ("in declaration %q+D", in_decl);
12570           }
12571         return error_mark_node;
12572     }
12573     /* DR 657. */
12574     if (abstract_virtuals_error_sfinae (ACU_PARM, type, complain))
12575       return error_mark_node;
12576     
12577     /* Do array-to-pointer, function-to-pointer conversion, and ignore
12578        top-level qualifiers as required.  */
12579     type = cv_unqualified (type_decays_to (type));
12580
12581     /* We do not substitute into default arguments here.  The standard
12582        mandates that they be instantiated only when needed, which is
12583        done in build_over_call.  */
12584     default_arg = TREE_PURPOSE (arg_types);
12585
12586     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
12587       {
12588         /* We've instantiated a template before its default arguments
12589            have been parsed.  This can happen for a nested template
12590            class, and is not an error unless we require the default
12591            argument in a call of this function.  */
12592         remaining_arg_types = 
12593           tree_cons (default_arg, type, remaining_arg_types);
12594         vec_safe_push (DEFARG_INSTANTIATIONS(default_arg), remaining_arg_types);
12595       }
12596     else
12597       remaining_arg_types = 
12598         hash_tree_cons (default_arg, type, remaining_arg_types);
12599   }
12600         
12601   return remaining_arg_types;
12602 }
12603
12604 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
12605    *not* handle the exception-specification for FNTYPE, because the
12606    initial substitution of explicitly provided template parameters
12607    during argument deduction forbids substitution into the
12608    exception-specification:
12609
12610      [temp.deduct]
12611
12612      All references in the function type of the function template to  the
12613      corresponding template parameters are replaced by the specified tem-
12614      plate argument values.  If a substitution in a template parameter or
12615      in  the function type of the function template results in an invalid
12616      type, type deduction fails.  [Note: The equivalent  substitution  in
12617      exception specifications is done only when the function is instanti-
12618      ated, at which point a program is  ill-formed  if  the  substitution
12619      results in an invalid type.]  */
12620
12621 static tree
12622 tsubst_function_type (tree t,
12623                       tree args,
12624                       tsubst_flags_t complain,
12625                       tree in_decl)
12626 {
12627   tree return_type;
12628   tree arg_types = NULL_TREE;
12629   tree fntype;
12630
12631   /* The TYPE_CONTEXT is not used for function/method types.  */
12632   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
12633
12634   /* DR 1227: Mixing immediate and non-immediate contexts in deduction
12635      failure.  */
12636   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
12637
12638   if (late_return_type_p)
12639     {
12640       /* Substitute the argument types.  */
12641       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
12642                                     complain, in_decl);
12643       if (arg_types == error_mark_node)
12644         return error_mark_node;
12645
12646       tree save_ccp = current_class_ptr;
12647       tree save_ccr = current_class_ref;
12648       tree this_type = (TREE_CODE (t) == METHOD_TYPE
12649                         ? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
12650       bool do_inject = this_type && CLASS_TYPE_P (this_type);
12651       if (do_inject)
12652         {
12653           /* DR 1207: 'this' is in scope in the trailing return type.  */
12654           inject_this_parameter (this_type, cp_type_quals (this_type));
12655         }
12656
12657       /* Substitute the return type.  */
12658       return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12659
12660       if (do_inject)
12661         {
12662           current_class_ptr = save_ccp;
12663           current_class_ref = save_ccr;
12664         }
12665     }
12666   else
12667     /* Substitute the return type.  */
12668     return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12669
12670   if (return_type == error_mark_node)
12671     return error_mark_node;
12672   /* DR 486 clarifies that creation of a function type with an
12673      invalid return type is a deduction failure.  */
12674   if (TREE_CODE (return_type) == ARRAY_TYPE
12675       || TREE_CODE (return_type) == FUNCTION_TYPE)
12676     {
12677       if (complain & tf_error)
12678         {
12679           if (TREE_CODE (return_type) == ARRAY_TYPE)
12680             error ("function returning an array");
12681           else
12682             error ("function returning a function");
12683         }
12684       return error_mark_node;
12685     }
12686   /* And DR 657. */
12687   if (abstract_virtuals_error_sfinae (ACU_RETURN, return_type, complain))
12688     return error_mark_node;
12689
12690   if (!late_return_type_p)
12691     {
12692       /* Substitute the argument types.  */
12693       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
12694                                     complain, in_decl);
12695       if (arg_types == error_mark_node)
12696         return error_mark_node;
12697     }
12698
12699   /* Construct a new type node and return it.  */
12700   if (TREE_CODE (t) == FUNCTION_TYPE)
12701     {
12702       fntype = build_function_type (return_type, arg_types);
12703       fntype = apply_memfn_quals (fntype,
12704                                   type_memfn_quals (t),
12705                                   type_memfn_rqual (t));
12706     }
12707   else
12708     {
12709       tree r = TREE_TYPE (TREE_VALUE (arg_types));
12710       /* Don't pick up extra function qualifiers from the basetype.  */
12711       r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
12712       if (! MAYBE_CLASS_TYPE_P (r))
12713         {
12714           /* [temp.deduct]
12715
12716              Type deduction may fail for any of the following
12717              reasons:
12718
12719              -- Attempting to create "pointer to member of T" when T
12720              is not a class type.  */
12721           if (complain & tf_error)
12722             error ("creating pointer to member function of non-class type %qT",
12723                       r);
12724           return error_mark_node;
12725         }
12726
12727       fntype = build_method_type_directly (r, return_type,
12728                                            TREE_CHAIN (arg_types));
12729       fntype = build_ref_qualified_type (fntype, type_memfn_rqual (t));
12730     }
12731   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
12732
12733   if (late_return_type_p)
12734     TYPE_HAS_LATE_RETURN_TYPE (fntype) = 1;
12735
12736   return fntype;
12737 }
12738
12739 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
12740    ARGS into that specification, and return the substituted
12741    specification.  If there is no specification, return NULL_TREE.  */
12742
12743 static tree
12744 tsubst_exception_specification (tree fntype,
12745                                 tree args,
12746                                 tsubst_flags_t complain,
12747                                 tree in_decl,
12748                                 bool defer_ok)
12749 {
12750   tree specs;
12751   tree new_specs;
12752
12753   specs = TYPE_RAISES_EXCEPTIONS (fntype);
12754   new_specs = NULL_TREE;
12755   if (specs && TREE_PURPOSE (specs))
12756     {
12757       /* A noexcept-specifier.  */
12758       tree expr = TREE_PURPOSE (specs);
12759       if (TREE_CODE (expr) == INTEGER_CST)
12760         new_specs = expr;
12761       else if (defer_ok)
12762         {
12763           /* Defer instantiation of noexcept-specifiers to avoid
12764              excessive instantiations (c++/49107).  */
12765           new_specs = make_node (DEFERRED_NOEXCEPT);
12766           if (DEFERRED_NOEXCEPT_SPEC_P (specs))
12767             {
12768               /* We already partially instantiated this member template,
12769                  so combine the new args with the old.  */
12770               DEFERRED_NOEXCEPT_PATTERN (new_specs)
12771                 = DEFERRED_NOEXCEPT_PATTERN (expr);
12772               DEFERRED_NOEXCEPT_ARGS (new_specs)
12773                 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
12774             }
12775           else
12776             {
12777               DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
12778               DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
12779             }
12780         }
12781       else
12782         new_specs = tsubst_copy_and_build
12783           (expr, args, complain, in_decl, /*function_p=*/false,
12784            /*integral_constant_expression_p=*/true);
12785       new_specs = build_noexcept_spec (new_specs, complain);
12786     }
12787   else if (specs)
12788     {
12789       if (! TREE_VALUE (specs))
12790         new_specs = specs;
12791       else
12792         while (specs)
12793           {
12794             tree spec;
12795             int i, len = 1;
12796             tree expanded_specs = NULL_TREE;
12797
12798             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
12799               {
12800                 /* Expand the pack expansion type.  */
12801                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
12802                                                        args, complain,
12803                                                        in_decl);
12804
12805                 if (expanded_specs == error_mark_node)
12806                   return error_mark_node;
12807                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
12808                   len = TREE_VEC_LENGTH (expanded_specs);
12809                 else
12810                   {
12811                     /* We're substituting into a member template, so
12812                        we got a TYPE_PACK_EXPANSION back.  Add that
12813                        expansion and move on.  */
12814                     gcc_assert (TREE_CODE (expanded_specs) 
12815                                 == TYPE_PACK_EXPANSION);
12816                     new_specs = add_exception_specifier (new_specs,
12817                                                          expanded_specs,
12818                                                          complain);
12819                     specs = TREE_CHAIN (specs);
12820                     continue;
12821                   }
12822               }
12823
12824             for (i = 0; i < len; ++i)
12825               {
12826                 if (expanded_specs)
12827                   spec = TREE_VEC_ELT (expanded_specs, i);
12828                 else
12829                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
12830                 if (spec == error_mark_node)
12831                   return spec;
12832                 new_specs = add_exception_specifier (new_specs, spec, 
12833                                                      complain);
12834               }
12835
12836             specs = TREE_CHAIN (specs);
12837           }
12838     }
12839   return new_specs;
12840 }
12841
12842 /* Take the tree structure T and replace template parameters used
12843    therein with the argument vector ARGS.  IN_DECL is an associated
12844    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
12845    Issue error and warning messages under control of COMPLAIN.  Note
12846    that we must be relatively non-tolerant of extensions here, in
12847    order to preserve conformance; if we allow substitutions that
12848    should not be allowed, we may allow argument deductions that should
12849    not succeed, and therefore report ambiguous overload situations
12850    where there are none.  In theory, we could allow the substitution,
12851    but indicate that it should have failed, and allow our caller to
12852    make sure that the right thing happens, but we don't try to do this
12853    yet.
12854
12855    This function is used for dealing with types, decls and the like;
12856    for expressions, use tsubst_expr or tsubst_copy.  */
12857
12858 tree
12859 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12860 {
12861   enum tree_code code;
12862   tree type, r = NULL_TREE;
12863
12864   if (t == NULL_TREE || t == error_mark_node
12865       || t == integer_type_node
12866       || t == void_type_node
12867       || t == char_type_node
12868       || t == unknown_type_node
12869       || TREE_CODE (t) == NAMESPACE_DECL
12870       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
12871     return t;
12872
12873   if (DECL_P (t))
12874     return tsubst_decl (t, args, complain);
12875
12876   if (args == NULL_TREE)
12877     return t;
12878
12879   code = TREE_CODE (t);
12880
12881   if (code == IDENTIFIER_NODE)
12882     type = IDENTIFIER_TYPE_VALUE (t);
12883   else
12884     type = TREE_TYPE (t);
12885
12886   gcc_assert (type != unknown_type_node);
12887
12888   /* Reuse typedefs.  We need to do this to handle dependent attributes,
12889      such as attribute aligned.  */
12890   if (TYPE_P (t)
12891       && typedef_variant_p (t))
12892     {
12893       tree decl = TYPE_NAME (t);
12894
12895       if (alias_template_specialization_p (t))
12896         {
12897           /* DECL represents an alias template and we want to
12898              instantiate it.  */
12899           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
12900           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
12901           r = instantiate_alias_template (tmpl, gen_args, complain);
12902         }
12903       else if (DECL_CLASS_SCOPE_P (decl)
12904                && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
12905                && uses_template_parms (DECL_CONTEXT (decl)))
12906         {
12907           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
12908           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
12909           r = retrieve_specialization (tmpl, gen_args, 0);
12910         }
12911       else if (DECL_FUNCTION_SCOPE_P (decl)
12912                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
12913                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
12914         r = retrieve_local_specialization (decl);
12915       else
12916         /* The typedef is from a non-template context.  */
12917         return t;
12918
12919       if (r)
12920         {
12921           r = TREE_TYPE (r);
12922           r = cp_build_qualified_type_real
12923             (r, cp_type_quals (t) | cp_type_quals (r),
12924              complain | tf_ignore_bad_quals);
12925           return r;
12926         }
12927       else
12928         {
12929           /* We don't have an instantiation yet, so drop the typedef.  */
12930           int quals = cp_type_quals (t);
12931           t = DECL_ORIGINAL_TYPE (decl);
12932           t = cp_build_qualified_type_real (t, quals,
12933                                             complain | tf_ignore_bad_quals);
12934         }
12935     }
12936
12937   if (type
12938       && code != TYPENAME_TYPE
12939       && code != TEMPLATE_TYPE_PARM
12940       && code != IDENTIFIER_NODE
12941       && code != FUNCTION_TYPE
12942       && code != METHOD_TYPE)
12943     type = tsubst (type, args, complain, in_decl);
12944   if (type == error_mark_node)
12945     return error_mark_node;
12946
12947   switch (code)
12948     {
12949     case RECORD_TYPE:
12950     case UNION_TYPE:
12951     case ENUMERAL_TYPE:
12952       return tsubst_aggr_type (t, args, complain, in_decl,
12953                                /*entering_scope=*/0);
12954
12955     case ERROR_MARK:
12956     case IDENTIFIER_NODE:
12957     case VOID_TYPE:
12958     case REAL_TYPE:
12959     case COMPLEX_TYPE:
12960     case VECTOR_TYPE:
12961     case BOOLEAN_TYPE:
12962     case NULLPTR_TYPE:
12963     case LANG_TYPE:
12964       return t;
12965
12966     case INTEGER_TYPE:
12967       if (t == integer_type_node)
12968         return t;
12969
12970       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
12971           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
12972         return t;
12973
12974       {
12975         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
12976
12977         max = tsubst_expr (omax, args, complain, in_decl,
12978                            /*integral_constant_expression_p=*/false);
12979
12980         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
12981            needed.  */
12982         if (TREE_CODE (max) == NOP_EXPR
12983             && TREE_SIDE_EFFECTS (omax)
12984             && !TREE_TYPE (max))
12985           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
12986
12987         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
12988            with TREE_SIDE_EFFECTS that indicates this is not an integral
12989            constant expression.  */
12990         if (processing_template_decl
12991             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
12992           {
12993             gcc_assert (TREE_CODE (max) == NOP_EXPR);
12994             TREE_SIDE_EFFECTS (max) = 1;
12995           }
12996
12997         return compute_array_index_type (NULL_TREE, max, complain);
12998       }
12999
13000     case TEMPLATE_TYPE_PARM:
13001     case TEMPLATE_TEMPLATE_PARM:
13002     case BOUND_TEMPLATE_TEMPLATE_PARM:
13003     case TEMPLATE_PARM_INDEX:
13004       {
13005         int idx;
13006         int level;
13007         int levels;
13008         tree arg = NULL_TREE;
13009
13010         /* Early in template argument deduction substitution, we don't
13011            want to reduce the level of 'auto', or it will be confused
13012            with a normal template parm in subsequent deduction.  */
13013         if (is_auto (t) && (complain & tf_partial))
13014           return t;
13015
13016         r = NULL_TREE;
13017
13018         gcc_assert (TREE_VEC_LENGTH (args) > 0);
13019         template_parm_level_and_index (t, &level, &idx); 
13020
13021         levels = TMPL_ARGS_DEPTH (args);
13022         if (level <= levels
13023             && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
13024           {
13025             arg = TMPL_ARG (args, level, idx);
13026
13027             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
13028               {
13029                 /* See through ARGUMENT_PACK_SELECT arguments. */
13030                 arg = ARGUMENT_PACK_SELECT_ARG (arg);
13031                 /* If the selected argument is an expansion E, that most
13032                    likely means we were called from
13033                    gen_elem_of_pack_expansion_instantiation during the
13034                    substituting of pack an argument pack (which Ith
13035                    element is a pack expansion, where I is
13036                    ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
13037                    In this case, the Ith element resulting from this
13038                    substituting is going to be a pack expansion, which
13039                    pattern is the pattern of E.  Let's return the
13040                    pattern of E, and
13041                    gen_elem_of_pack_expansion_instantiation will
13042                    build the resulting pack expansion from it.  */
13043                 if (PACK_EXPANSION_P (arg))
13044                   {
13045                     /* Make sure we aren't throwing away arg info.  */
13046                     gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
13047                     arg = PACK_EXPANSION_PATTERN (arg);
13048                   }
13049               }
13050           }
13051
13052         if (arg == error_mark_node)
13053           return error_mark_node;
13054         else if (arg != NULL_TREE)
13055           {
13056             if (ARGUMENT_PACK_P (arg))
13057               /* If ARG is an argument pack, we don't actually want to
13058                  perform a substitution here, because substitutions
13059                  for argument packs are only done
13060                  element-by-element. We can get to this point when
13061                  substituting the type of a non-type template
13062                  parameter pack, when that type actually contains
13063                  template parameter packs from an outer template, e.g.,
13064
13065                  template<typename... Types> struct A {
13066                    template<Types... Values> struct B { };
13067                  };  */
13068               return t;
13069
13070             if (code == TEMPLATE_TYPE_PARM)
13071               {
13072                 int quals;
13073                 gcc_assert (TYPE_P (arg));
13074
13075                 quals = cp_type_quals (arg) | cp_type_quals (t);
13076                   
13077                 return cp_build_qualified_type_real
13078                   (arg, quals, complain | tf_ignore_bad_quals);
13079               }
13080             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
13081               {
13082                 /* We are processing a type constructed from a
13083                    template template parameter.  */
13084                 tree argvec = tsubst (TYPE_TI_ARGS (t),
13085                                       args, complain, in_decl);
13086                 if (argvec == error_mark_node)
13087                   return error_mark_node;
13088
13089                 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
13090                             || TREE_CODE (arg) == TEMPLATE_DECL
13091                             || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
13092
13093                 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
13094                   /* Consider this code:
13095
13096                         template <template <class> class Template>
13097                         struct Internal {
13098                         template <class Arg> using Bind = Template<Arg>;
13099                         };
13100
13101                         template <template <class> class Template, class Arg>
13102                         using Instantiate = Template<Arg>; //#0
13103
13104                         template <template <class> class Template,
13105                                   class Argument>
13106                         using Bind =
13107                           Instantiate<Internal<Template>::template Bind,
13108                                       Argument>; //#1
13109
13110                      When #1 is parsed, the
13111                      BOUND_TEMPLATE_TEMPLATE_PARM representing the
13112                      parameter `Template' in #0 matches the
13113                      UNBOUND_CLASS_TEMPLATE representing the argument
13114                      `Internal<Template>::template Bind'; We then want
13115                      to assemble the type `Bind<Argument>' that can't
13116                      be fully created right now, because
13117                      `Internal<Template>' not being complete, the Bind
13118                      template cannot be looked up in that context.  So
13119                      we need to "store" `Bind<Argument>' for later
13120                      when the context of Bind becomes complete.  Let's
13121                      store that in a TYPENAME_TYPE.  */
13122                   return make_typename_type (TYPE_CONTEXT (arg),
13123                                              build_nt (TEMPLATE_ID_EXPR,
13124                                                        TYPE_IDENTIFIER (arg),
13125                                                        argvec),
13126                                              typename_type,
13127                                              complain);
13128
13129                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
13130                    are resolving nested-types in the signature of a
13131                    member function templates.  Otherwise ARG is a
13132                    TEMPLATE_DECL and is the real template to be
13133                    instantiated.  */
13134                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
13135                   arg = TYPE_NAME (arg);
13136
13137                 r = lookup_template_class (arg,
13138                                            argvec, in_decl,
13139                                            DECL_CONTEXT (arg),
13140                                             /*entering_scope=*/0,
13141                                            complain);
13142                 return cp_build_qualified_type_real
13143                   (r, cp_type_quals (t) | cp_type_quals (r), complain);
13144               }
13145             else
13146               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
13147               return convert_from_reference (unshare_expr (arg));
13148           }
13149
13150         if (level == 1)
13151           /* This can happen during the attempted tsubst'ing in
13152              unify.  This means that we don't yet have any information
13153              about the template parameter in question.  */
13154           return t;
13155
13156         /* If we get here, we must have been looking at a parm for a
13157            more deeply nested template.  Make a new version of this
13158            template parameter, but with a lower level.  */
13159         switch (code)
13160           {
13161           case TEMPLATE_TYPE_PARM:
13162           case TEMPLATE_TEMPLATE_PARM:
13163           case BOUND_TEMPLATE_TEMPLATE_PARM:
13164             if (cp_type_quals (t))
13165               {
13166                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
13167                 r = cp_build_qualified_type_real
13168                   (r, cp_type_quals (t),
13169                    complain | (code == TEMPLATE_TYPE_PARM
13170                                ? tf_ignore_bad_quals : 0));
13171               }
13172             else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
13173                      && PLACEHOLDER_TYPE_CONSTRAINTS (t)
13174                      && (r = (TEMPLATE_PARM_DESCENDANTS
13175                               (TEMPLATE_TYPE_PARM_INDEX (t))))
13176                      && (r = TREE_TYPE (r))
13177                      && !PLACEHOLDER_TYPE_CONSTRAINTS (r))
13178               /* Break infinite recursion when substituting the constraints
13179                  of a constrained placeholder.  */;
13180             else
13181               {
13182                 r = copy_type (t);
13183                 TEMPLATE_TYPE_PARM_INDEX (r)
13184                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
13185                                                 r, levels, args, complain);
13186                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
13187                 TYPE_MAIN_VARIANT (r) = r;
13188                 TYPE_POINTER_TO (r) = NULL_TREE;
13189                 TYPE_REFERENCE_TO (r) = NULL_TREE;
13190
13191                 /* Propagate constraints on placeholders.  */
13192                 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
13193                   if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
13194                     PLACEHOLDER_TYPE_CONSTRAINTS (r)
13195                       = tsubst_constraint (constr, args, complain, in_decl);
13196
13197                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
13198                   /* We have reduced the level of the template
13199                      template parameter, but not the levels of its
13200                      template parameters, so canonical_type_parameter
13201                      will not be able to find the canonical template
13202                      template parameter for this level. Thus, we
13203                      require structural equality checking to compare
13204                      TEMPLATE_TEMPLATE_PARMs. */
13205                   SET_TYPE_STRUCTURAL_EQUALITY (r);
13206                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
13207                   SET_TYPE_STRUCTURAL_EQUALITY (r);
13208                 else
13209                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
13210
13211                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
13212                   {
13213                     tree tinfo = TYPE_TEMPLATE_INFO (t);
13214                     /* We might need to substitute into the types of non-type
13215                        template parameters.  */
13216                     tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
13217                                         complain, in_decl);
13218                     if (tmpl == error_mark_node)
13219                       return error_mark_node;
13220                     tree argvec = tsubst (TI_ARGS (tinfo), args,
13221                                           complain, in_decl);
13222                     if (argvec == error_mark_node)
13223                       return error_mark_node;
13224
13225                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
13226                       = build_template_info (tmpl, argvec);
13227                   }
13228               }
13229             break;
13230
13231           case TEMPLATE_PARM_INDEX:
13232             r = reduce_template_parm_level (t, type, levels, args, complain);
13233             break;
13234
13235           default:
13236             gcc_unreachable ();
13237           }
13238
13239         return r;
13240       }
13241
13242     case TREE_LIST:
13243       {
13244         tree purpose, value, chain;
13245
13246         if (t == void_list_node)
13247           return t;
13248
13249         purpose = TREE_PURPOSE (t);
13250         if (purpose)
13251           {
13252             purpose = tsubst (purpose, args, complain, in_decl);
13253             if (purpose == error_mark_node)
13254               return error_mark_node;
13255           }
13256         value = TREE_VALUE (t);
13257         if (value)
13258           {
13259             value = tsubst (value, args, complain, in_decl);
13260             if (value == error_mark_node)
13261               return error_mark_node;
13262           }
13263         chain = TREE_CHAIN (t);
13264         if (chain && chain != void_type_node)
13265           {
13266             chain = tsubst (chain, args, complain, in_decl);
13267             if (chain == error_mark_node)
13268               return error_mark_node;
13269           }
13270         if (purpose == TREE_PURPOSE (t)
13271             && value == TREE_VALUE (t)
13272             && chain == TREE_CHAIN (t))
13273           return t;
13274         return hash_tree_cons (purpose, value, chain);
13275       }
13276
13277     case TREE_BINFO:
13278       /* We should never be tsubsting a binfo.  */
13279       gcc_unreachable ();
13280
13281     case TREE_VEC:
13282       /* A vector of template arguments.  */
13283       gcc_assert (!type);
13284       return tsubst_template_args (t, args, complain, in_decl);
13285
13286     case POINTER_TYPE:
13287     case REFERENCE_TYPE:
13288       {
13289         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
13290           return t;
13291
13292         /* [temp.deduct]
13293
13294            Type deduction may fail for any of the following
13295            reasons:
13296
13297            -- Attempting to create a pointer to reference type.
13298            -- Attempting to create a reference to a reference type or
13299               a reference to void.
13300
13301           Core issue 106 says that creating a reference to a reference
13302           during instantiation is no longer a cause for failure. We
13303           only enforce this check in strict C++98 mode.  */
13304         if ((TREE_CODE (type) == REFERENCE_TYPE
13305              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
13306             || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
13307           {
13308             static location_t last_loc;
13309
13310             /* We keep track of the last time we issued this error
13311                message to avoid spewing a ton of messages during a
13312                single bad template instantiation.  */
13313             if (complain & tf_error
13314                 && last_loc != input_location)
13315               {
13316                 if (VOID_TYPE_P (type))
13317                   error ("forming reference to void");
13318                else if (code == POINTER_TYPE)
13319                  error ("forming pointer to reference type %qT", type);
13320                else
13321                   error ("forming reference to reference type %qT", type);
13322                 last_loc = input_location;
13323               }
13324
13325             return error_mark_node;
13326           }
13327         else if (TREE_CODE (type) == FUNCTION_TYPE
13328                  && (type_memfn_quals (type) != TYPE_UNQUALIFIED
13329                      || type_memfn_rqual (type) != REF_QUAL_NONE))
13330           {
13331             if (complain & tf_error)
13332               {
13333                 if (code == POINTER_TYPE)
13334                   error ("forming pointer to qualified function type %qT",
13335                          type);
13336                 else
13337                   error ("forming reference to qualified function type %qT",
13338                          type);
13339               }
13340             return error_mark_node;
13341           }
13342         else if (code == POINTER_TYPE)
13343           {
13344             r = build_pointer_type (type);
13345             if (TREE_CODE (type) == METHOD_TYPE)
13346               r = build_ptrmemfunc_type (r);
13347           }
13348         else if (TREE_CODE (type) == REFERENCE_TYPE)
13349           /* In C++0x, during template argument substitution, when there is an
13350              attempt to create a reference to a reference type, reference
13351              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
13352
13353              "If a template-argument for a template-parameter T names a type
13354              that is a reference to a type A, an attempt to create the type
13355              'lvalue reference to cv T' creates the type 'lvalue reference to
13356              A,' while an attempt to create the type type rvalue reference to
13357              cv T' creates the type T"
13358           */
13359           r = cp_build_reference_type
13360               (TREE_TYPE (type),
13361                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
13362         else
13363           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
13364         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
13365
13366         if (r != error_mark_node)
13367           /* Will this ever be needed for TYPE_..._TO values?  */
13368           layout_type (r);
13369
13370         return r;
13371       }
13372     case OFFSET_TYPE:
13373       {
13374         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
13375         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
13376           {
13377             /* [temp.deduct]
13378
13379                Type deduction may fail for any of the following
13380                reasons:
13381
13382                -- Attempting to create "pointer to member of T" when T
13383                   is not a class type.  */
13384             if (complain & tf_error)
13385               error ("creating pointer to member of non-class type %qT", r);
13386             return error_mark_node;
13387           }
13388         if (TREE_CODE (type) == REFERENCE_TYPE)
13389           {
13390             if (complain & tf_error)
13391               error ("creating pointer to member reference type %qT", type);
13392             return error_mark_node;
13393           }
13394         if (VOID_TYPE_P (type))
13395           {
13396             if (complain & tf_error)
13397               error ("creating pointer to member of type void");
13398             return error_mark_node;
13399           }
13400         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
13401         if (TREE_CODE (type) == FUNCTION_TYPE)
13402           {
13403             /* The type of the implicit object parameter gets its
13404                cv-qualifiers from the FUNCTION_TYPE. */
13405             tree memptr;
13406             tree method_type
13407               = build_memfn_type (type, r, type_memfn_quals (type),
13408                                   type_memfn_rqual (type));
13409             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
13410             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
13411                                                  complain);
13412           }
13413         else
13414           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
13415                                                cp_type_quals (t),
13416                                                complain);
13417       }
13418     case FUNCTION_TYPE:
13419     case METHOD_TYPE:
13420       {
13421         tree fntype;
13422         tree specs;
13423         fntype = tsubst_function_type (t, args, complain, in_decl);
13424         if (fntype == error_mark_node)
13425           return error_mark_node;
13426
13427         /* Substitute the exception specification.  */
13428         specs = tsubst_exception_specification (t, args, complain,
13429                                                 in_decl, /*defer_ok*/true);
13430         if (specs == error_mark_node)
13431           return error_mark_node;
13432         if (specs)
13433           fntype = build_exception_variant (fntype, specs);
13434         return fntype;
13435       }
13436     case ARRAY_TYPE:
13437       {
13438         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
13439         if (domain == error_mark_node)
13440           return error_mark_node;
13441
13442         /* As an optimization, we avoid regenerating the array type if
13443            it will obviously be the same as T.  */
13444         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
13445           return t;
13446
13447         /* These checks should match the ones in create_array_type_for_decl.
13448
13449            [temp.deduct]
13450
13451            The deduction may fail for any of the following reasons:
13452
13453            -- Attempting to create an array with an element type that
13454               is void, a function type, or a reference type, or [DR337]
13455               an abstract class type.  */
13456         if (VOID_TYPE_P (type)
13457             || TREE_CODE (type) == FUNCTION_TYPE
13458             || (TREE_CODE (type) == ARRAY_TYPE
13459                 && TYPE_DOMAIN (type) == NULL_TREE)
13460             || TREE_CODE (type) == REFERENCE_TYPE)
13461           {
13462             if (complain & tf_error)
13463               error ("creating array of %qT", type);
13464             return error_mark_node;
13465           }
13466
13467         if (abstract_virtuals_error_sfinae (ACU_ARRAY, type, complain))
13468           return error_mark_node;
13469
13470         r = build_cplus_array_type (type, domain);
13471
13472         if (TYPE_USER_ALIGN (t))
13473           {
13474             TYPE_ALIGN (r) = TYPE_ALIGN (t);
13475             TYPE_USER_ALIGN (r) = 1;
13476           }
13477
13478         return r;
13479       }
13480
13481     case TYPENAME_TYPE:
13482       {
13483         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
13484                                      in_decl, /*entering_scope=*/1);
13485         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
13486                               complain, in_decl);
13487
13488         if (ctx == error_mark_node || f == error_mark_node)
13489           return error_mark_node;
13490
13491         if (!MAYBE_CLASS_TYPE_P (ctx))
13492           {
13493             if (complain & tf_error)
13494               error ("%qT is not a class, struct, or union type", ctx);
13495             return error_mark_node;
13496           }
13497         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
13498           {
13499             /* Normally, make_typename_type does not require that the CTX
13500                have complete type in order to allow things like:
13501
13502                  template <class T> struct S { typename S<T>::X Y; };
13503
13504                But, such constructs have already been resolved by this
13505                point, so here CTX really should have complete type, unless
13506                it's a partial instantiation.  */
13507             ctx = complete_type (ctx);
13508             if (!COMPLETE_TYPE_P (ctx))
13509               {
13510                 if (complain & tf_error)
13511                   cxx_incomplete_type_error (NULL_TREE, ctx);
13512                 return error_mark_node;
13513               }
13514           }
13515
13516         f = make_typename_type (ctx, f, typename_type,
13517                                 complain | tf_keep_type_decl);
13518         if (f == error_mark_node)
13519           return f;
13520         if (TREE_CODE (f) == TYPE_DECL)
13521           {
13522             complain |= tf_ignore_bad_quals;
13523             f = TREE_TYPE (f);
13524           }
13525
13526         if (TREE_CODE (f) != TYPENAME_TYPE)
13527           {
13528             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
13529               {
13530                 if (complain & tf_error)
13531                   error ("%qT resolves to %qT, which is not an enumeration type",
13532                          t, f);
13533                 else
13534                   return error_mark_node;
13535               }
13536             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
13537               {
13538                 if (complain & tf_error)
13539                   error ("%qT resolves to %qT, which is is not a class type",
13540                          t, f);
13541                 else
13542                   return error_mark_node;
13543               }
13544           }
13545
13546         return cp_build_qualified_type_real
13547           (f, cp_type_quals (f) | cp_type_quals (t), complain);
13548       }
13549
13550     case UNBOUND_CLASS_TEMPLATE:
13551       {
13552         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
13553                                      in_decl, /*entering_scope=*/1);
13554         tree name = TYPE_IDENTIFIER (t);
13555         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
13556
13557         if (ctx == error_mark_node || name == error_mark_node)
13558           return error_mark_node;
13559
13560         if (parm_list)
13561           parm_list = tsubst_template_parms (parm_list, args, complain);
13562         return make_unbound_class_template (ctx, name, parm_list, complain);
13563       }
13564
13565     case TYPEOF_TYPE:
13566       {
13567         tree type;
13568
13569         ++cp_unevaluated_operand;
13570         ++c_inhibit_evaluation_warnings;
13571
13572         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
13573                             complain, in_decl,
13574                             /*integral_constant_expression_p=*/false);
13575
13576         --cp_unevaluated_operand;
13577         --c_inhibit_evaluation_warnings;
13578
13579         type = finish_typeof (type);
13580         return cp_build_qualified_type_real (type,
13581                                              cp_type_quals (t)
13582                                              | cp_type_quals (type),
13583                                              complain);
13584       }
13585
13586     case DECLTYPE_TYPE:
13587       {
13588         tree type;
13589
13590         ++cp_unevaluated_operand;
13591         ++c_inhibit_evaluation_warnings;
13592
13593         type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
13594                                       complain|tf_decltype, in_decl,
13595                                       /*function_p*/false,
13596                                       /*integral_constant_expression*/false);
13597
13598         --cp_unevaluated_operand;
13599         --c_inhibit_evaluation_warnings;
13600
13601         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
13602           type = lambda_capture_field_type (type,
13603                                             DECLTYPE_FOR_INIT_CAPTURE (t));
13604         else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
13605           type = lambda_proxy_type (type);
13606         else
13607           {
13608             bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
13609             if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
13610                 && EXPR_P (type))
13611               /* In a template ~id could be either a complement expression
13612                  or an unqualified-id naming a destructor; if instantiating
13613                  it produces an expression, it's not an id-expression or
13614                  member access.  */
13615               id = false;
13616             type = finish_decltype_type (type, id, complain);
13617           }
13618         return cp_build_qualified_type_real (type,
13619                                              cp_type_quals (t)
13620                                              | cp_type_quals (type),
13621                                              complain | tf_ignore_bad_quals);
13622       }
13623
13624     case UNDERLYING_TYPE:
13625       {
13626         tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
13627                             complain, in_decl);
13628         return finish_underlying_type (type);
13629       }
13630
13631     case TYPE_ARGUMENT_PACK:
13632     case NONTYPE_ARGUMENT_PACK:
13633       {
13634         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
13635         tree packed_out = 
13636           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
13637                                 args,
13638                                 complain,
13639                                 in_decl);
13640         SET_ARGUMENT_PACK_ARGS (r, packed_out);
13641
13642         /* For template nontype argument packs, also substitute into
13643            the type.  */
13644         if (code == NONTYPE_ARGUMENT_PACK)
13645           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
13646
13647         return r;
13648       }
13649       break;
13650
13651     case VOID_CST:
13652     case INTEGER_CST:
13653     case REAL_CST:
13654     case STRING_CST:
13655     case PLUS_EXPR:
13656     case MINUS_EXPR:
13657     case NEGATE_EXPR:
13658     case NOP_EXPR:
13659     case INDIRECT_REF:
13660     case ADDR_EXPR:
13661     case CALL_EXPR:
13662     case ARRAY_REF:
13663     case SCOPE_REF:
13664       /* We should use one of the expression tsubsts for these codes.  */
13665       gcc_unreachable ();
13666
13667     default:
13668       sorry ("use of %qs in template", get_tree_code_name (code));
13669       return error_mark_node;
13670     }
13671 }
13672
13673 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
13674    type of the expression on the left-hand side of the "." or "->"
13675    operator.  */
13676
13677 static tree
13678 tsubst_baselink (tree baselink, tree object_type,
13679                  tree args, tsubst_flags_t complain, tree in_decl)
13680 {
13681     tree name;
13682     tree qualifying_scope;
13683     tree fns;
13684     tree optype;
13685     tree template_args = 0;
13686     bool template_id_p = false;
13687     bool qualified = BASELINK_QUALIFIED_P (baselink);
13688
13689     /* A baselink indicates a function from a base class.  Both the
13690        BASELINK_ACCESS_BINFO and the base class referenced may
13691        indicate bases of the template class, rather than the
13692        instantiated class.  In addition, lookups that were not
13693        ambiguous before may be ambiguous now.  Therefore, we perform
13694        the lookup again.  */
13695     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
13696     qualifying_scope = tsubst (qualifying_scope, args,
13697                                complain, in_decl);
13698     fns = BASELINK_FUNCTIONS (baselink);
13699     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
13700     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
13701       {
13702         template_id_p = true;
13703         template_args = TREE_OPERAND (fns, 1);
13704         fns = TREE_OPERAND (fns, 0);
13705         if (template_args)
13706           template_args = tsubst_template_args (template_args, args,
13707                                                 complain, in_decl);
13708       }
13709     name = DECL_NAME (get_first_fn (fns));
13710     if (IDENTIFIER_TYPENAME_P (name))
13711       name = mangle_conv_op_name_for_type (optype);
13712     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
13713     if (!baselink)
13714       {
13715         if (constructor_name_p (name, qualifying_scope))
13716           {
13717             if (complain & tf_error)
13718               error ("cannot call constructor %<%T::%D%> directly",
13719                      qualifying_scope, name);
13720           }
13721         return error_mark_node;
13722       }
13723
13724     /* If lookup found a single function, mark it as used at this
13725        point.  (If it lookup found multiple functions the one selected
13726        later by overload resolution will be marked as used at that
13727        point.)  */
13728     if (BASELINK_P (baselink))
13729       fns = BASELINK_FUNCTIONS (baselink);
13730     if (!template_id_p && !really_overloaded_fn (fns)
13731         && !mark_used (OVL_CURRENT (fns), complain) && !(complain & tf_error))
13732       return error_mark_node;
13733
13734     /* Add back the template arguments, if present.  */
13735     if (BASELINK_P (baselink) && template_id_p)
13736       BASELINK_FUNCTIONS (baselink)
13737         = build2 (TEMPLATE_ID_EXPR,
13738                   unknown_type_node,
13739                   BASELINK_FUNCTIONS (baselink),
13740                   template_args);
13741     /* Update the conversion operator type.  */
13742     BASELINK_OPTYPE (baselink) = optype;
13743
13744     if (!object_type)
13745       object_type = current_class_type;
13746
13747     if (qualified || name == complete_dtor_identifier)
13748       {
13749         baselink = adjust_result_of_qualified_name_lookup (baselink,
13750                                                            qualifying_scope,
13751                                                            object_type);
13752         if (!qualified)
13753           /* We need to call adjust_result_of_qualified_name_lookup in case the
13754              destructor names a base class, but we unset BASELINK_QUALIFIED_P
13755              so that we still get virtual function binding.  */
13756           BASELINK_QUALIFIED_P (baselink) = false;
13757       }
13758     return baselink;
13759 }
13760
13761 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
13762    true if the qualified-id will be a postfix-expression in-and-of
13763    itself; false if more of the postfix-expression follows the
13764    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
13765    of "&".  */
13766
13767 static tree
13768 tsubst_qualified_id (tree qualified_id, tree args,
13769                      tsubst_flags_t complain, tree in_decl,
13770                      bool done, bool address_p)
13771 {
13772   tree expr;
13773   tree scope;
13774   tree name;
13775   bool is_template;
13776   tree template_args;
13777   location_t loc = UNKNOWN_LOCATION;
13778
13779   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
13780
13781   /* Figure out what name to look up.  */
13782   name = TREE_OPERAND (qualified_id, 1);
13783   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
13784     {
13785       is_template = true;
13786       loc = EXPR_LOCATION (name);
13787       template_args = TREE_OPERAND (name, 1);
13788       if (template_args)
13789         template_args = tsubst_template_args (template_args, args,
13790                                               complain, in_decl);
13791       name = TREE_OPERAND (name, 0);
13792     }
13793   else
13794     {
13795       is_template = false;
13796       template_args = NULL_TREE;
13797     }
13798
13799   /* Substitute into the qualifying scope.  When there are no ARGS, we
13800      are just trying to simplify a non-dependent expression.  In that
13801      case the qualifying scope may be dependent, and, in any case,
13802      substituting will not help.  */
13803   scope = TREE_OPERAND (qualified_id, 0);
13804   if (args)
13805     {
13806       scope = tsubst (scope, args, complain, in_decl);
13807       expr = tsubst_copy (name, args, complain, in_decl);
13808     }
13809   else
13810     expr = name;
13811
13812   if (dependent_scope_p (scope))
13813     {
13814       if (is_template)
13815         expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
13816       tree r = build_qualified_name (NULL_TREE, scope, expr,
13817                                      QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
13818       REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (qualified_id);
13819       return r;
13820     }
13821
13822   if (!BASELINK_P (name) && !DECL_P (expr))
13823     {
13824       if (TREE_CODE (expr) == BIT_NOT_EXPR)
13825         {
13826           /* A BIT_NOT_EXPR is used to represent a destructor.  */
13827           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
13828             {
13829               error ("qualifying type %qT does not match destructor name ~%qT",
13830                      scope, TREE_OPERAND (expr, 0));
13831               expr = error_mark_node;
13832             }
13833           else
13834             expr = lookup_qualified_name (scope, complete_dtor_identifier,
13835                                           /*is_type_p=*/0, false);
13836         }
13837       else
13838         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
13839       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
13840                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
13841         {
13842           if (complain & tf_error)
13843             {
13844               error ("dependent-name %qE is parsed as a non-type, but "
13845                      "instantiation yields a type", qualified_id);
13846               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
13847             }
13848           return error_mark_node;
13849         }
13850     }
13851
13852   if (DECL_P (expr))
13853     {
13854       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
13855                                            scope);
13856       /* Remember that there was a reference to this entity.  */
13857       if (!mark_used (expr, complain) && !(complain & tf_error))
13858         return error_mark_node;
13859     }
13860
13861   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
13862     {
13863       if (complain & tf_error)
13864         qualified_name_lookup_error (scope,
13865                                      TREE_OPERAND (qualified_id, 1),
13866                                      expr, input_location);
13867       return error_mark_node;
13868     }
13869
13870   if (is_template)
13871     {
13872       if (variable_template_p (expr))
13873         expr = lookup_and_finish_template_variable (expr, template_args,
13874                                                     complain);
13875       else
13876         expr = lookup_template_function (expr, template_args);
13877     }
13878
13879   if (expr == error_mark_node && complain & tf_error)
13880     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
13881                                  expr, input_location);
13882   else if (TYPE_P (scope))
13883     {
13884       expr = (adjust_result_of_qualified_name_lookup
13885               (expr, scope, current_nonlambda_class_type ()));
13886       expr = (finish_qualified_id_expr
13887               (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
13888                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
13889                /*template_arg_p=*/false, complain));
13890     }
13891
13892   /* Expressions do not generally have reference type.  */
13893   if (TREE_CODE (expr) != SCOPE_REF
13894       /* However, if we're about to form a pointer-to-member, we just
13895          want the referenced member referenced.  */
13896       && TREE_CODE (expr) != OFFSET_REF)
13897     expr = convert_from_reference (expr);
13898
13899   if (REF_PARENTHESIZED_P (qualified_id))
13900     expr = force_paren_expr (expr);
13901
13902   return expr;
13903 }
13904
13905 /* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
13906    initializer, DECL is the substituted VAR_DECL.  Other arguments are as
13907    for tsubst.  */
13908
13909 static tree
13910 tsubst_init (tree init, tree decl, tree args,
13911              tsubst_flags_t complain, tree in_decl)
13912 {
13913   if (!init)
13914     return NULL_TREE;
13915
13916   init = tsubst_expr (init, args, complain, in_decl, false);
13917
13918   if (!init && TREE_TYPE (decl) != error_mark_node)
13919     {
13920       /* If we had an initializer but it
13921          instantiated to nothing,
13922          value-initialize the object.  This will
13923          only occur when the initializer was a
13924          pack expansion where the parameter packs
13925          used in that expansion were of length
13926          zero.  */
13927       init = build_value_init (TREE_TYPE (decl),
13928                                complain);
13929       if (TREE_CODE (init) == AGGR_INIT_EXPR)
13930         init = get_target_expr_sfinae (init, complain);
13931     }
13932
13933   return init;
13934 }
13935
13936 /* Like tsubst, but deals with expressions.  This function just replaces
13937    template parms; to finish processing the resultant expression, use
13938    tsubst_copy_and_build or tsubst_expr.  */
13939
13940 static tree
13941 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13942 {
13943   enum tree_code code;
13944   tree r;
13945
13946   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
13947     return t;
13948
13949   code = TREE_CODE (t);
13950
13951   switch (code)
13952     {
13953     case PARM_DECL:
13954       r = retrieve_local_specialization (t);
13955
13956       if (r == NULL_TREE)
13957         {
13958           /* We get here for a use of 'this' in an NSDMI as part of a
13959              constructor call or as part of an aggregate initialization.  */
13960           if (DECL_NAME (t) == this_identifier
13961               && ((current_function_decl
13962                    && DECL_CONSTRUCTOR_P (current_function_decl))
13963                   || (current_class_ref
13964                       && TREE_CODE (current_class_ref) == PLACEHOLDER_EXPR)))
13965             return current_class_ptr;
13966
13967           /* This can happen for a parameter name used later in a function
13968              declaration (such as in a late-specified return type).  Just
13969              make a dummy decl, since it's only used for its type.  */
13970           gcc_assert (cp_unevaluated_operand != 0);
13971           r = tsubst_decl (t, args, complain);
13972           /* Give it the template pattern as its context; its true context
13973              hasn't been instantiated yet and this is good enough for
13974              mangling.  */
13975           DECL_CONTEXT (r) = DECL_CONTEXT (t);
13976         }
13977       
13978       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
13979         r = ARGUMENT_PACK_SELECT_ARG (r);
13980       if (!mark_used (r, complain) && !(complain & tf_error))
13981         return error_mark_node;
13982       return r;
13983
13984     case CONST_DECL:
13985       {
13986         tree enum_type;
13987         tree v;
13988
13989         if (DECL_TEMPLATE_PARM_P (t))
13990           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
13991         /* There is no need to substitute into namespace-scope
13992            enumerators.  */
13993         if (DECL_NAMESPACE_SCOPE_P (t))
13994           return t;
13995         /* If ARGS is NULL, then T is known to be non-dependent.  */
13996         if (args == NULL_TREE)
13997           return scalar_constant_value (t);
13998
13999         /* Unfortunately, we cannot just call lookup_name here.
14000            Consider:
14001
14002              template <int I> int f() {
14003              enum E { a = I };
14004              struct S { void g() { E e = a; } };
14005              };
14006
14007            When we instantiate f<7>::S::g(), say, lookup_name is not
14008            clever enough to find f<7>::a.  */
14009         enum_type
14010           = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
14011                               /*entering_scope=*/0);
14012
14013         for (v = TYPE_VALUES (enum_type);
14014              v != NULL_TREE;
14015              v = TREE_CHAIN (v))
14016           if (TREE_PURPOSE (v) == DECL_NAME (t))
14017             return TREE_VALUE (v);
14018
14019           /* We didn't find the name.  That should never happen; if
14020              name-lookup found it during preliminary parsing, we
14021              should find it again here during instantiation.  */
14022         gcc_unreachable ();
14023       }
14024       return t;
14025
14026     case FIELD_DECL:
14027       if (PACK_EXPANSION_P (TREE_TYPE (t)))
14028         {
14029           /* Check for a local specialization set up by
14030              tsubst_pack_expansion.  */
14031           if (tree r = retrieve_local_specialization (t))
14032             {
14033               if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
14034                 r = ARGUMENT_PACK_SELECT_ARG (r);
14035               return r;
14036             }
14037
14038           /* When retrieving a capture pack from a generic lambda, remove the
14039              lambda call op's own template argument list from ARGS.  Only the
14040              template arguments active for the closure type should be used to
14041              retrieve the pack specialization.  */
14042           if (LAMBDA_FUNCTION_P (current_function_decl)
14043               && (template_class_depth (DECL_CONTEXT (t))
14044                   != TMPL_ARGS_DEPTH (args)))
14045             args = strip_innermost_template_args (args, 1);
14046
14047           /* Otherwise return the full NONTYPE_ARGUMENT_PACK that
14048              tsubst_decl put in the hash table.  */
14049           return retrieve_specialization (t, args, 0);
14050         }
14051
14052       if (DECL_CONTEXT (t))
14053         {
14054           tree ctx;
14055
14056           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
14057                                   /*entering_scope=*/1);
14058           if (ctx != DECL_CONTEXT (t))
14059             {
14060               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
14061               if (!r)
14062                 {
14063                   if (complain & tf_error)
14064                     error ("using invalid field %qD", t);
14065                   return error_mark_node;
14066                 }
14067               return r;
14068             }
14069         }
14070
14071       return t;
14072
14073     case VAR_DECL:
14074     case FUNCTION_DECL:
14075       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
14076         r = tsubst (t, args, complain, in_decl);
14077       else if (local_variable_p (t)
14078                && uses_template_parms (DECL_CONTEXT (t)))
14079         {
14080           r = retrieve_local_specialization (t);
14081           if (r == NULL_TREE)
14082             {
14083               /* First try name lookup to find the instantiation.  */
14084               r = lookup_name (DECL_NAME (t));
14085               if (r)
14086                 {
14087                   /* Make sure that the one we found is the one we want.  */
14088                   tree ctx = DECL_CONTEXT (t);
14089                   if (DECL_LANG_SPECIFIC (ctx) && DECL_TEMPLATE_INFO (ctx))
14090                     ctx = tsubst (ctx, args, complain, in_decl);
14091                   if (ctx != DECL_CONTEXT (r))
14092                     r = NULL_TREE;
14093                 }
14094
14095               if (r)
14096                 /* OK */;
14097               else
14098                 {
14099                   /* This can happen for a variable used in a
14100                      late-specified return type of a local lambda, or for a
14101                      local static or constant.  Building a new VAR_DECL
14102                      should be OK in all those cases.  */
14103                   r = tsubst_decl (t, args, complain);
14104                   if (decl_maybe_constant_var_p (r))
14105                     {
14106                       /* We can't call cp_finish_decl, so handle the
14107                          initializer by hand.  */
14108                       tree init = tsubst_init (DECL_INITIAL (t), r, args,
14109                                                complain, in_decl);
14110                       if (!processing_template_decl)
14111                         init = maybe_constant_init (init);
14112                       if (processing_template_decl
14113                           ? potential_constant_expression (init)
14114                           : reduced_constant_expression_p (init))
14115                         DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
14116                           = TREE_CONSTANT (r) = true;
14117                       DECL_INITIAL (r) = init;
14118                     }
14119                   gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
14120                               || decl_constant_var_p (r)
14121                               || errorcount || sorrycount);
14122                   if (!processing_template_decl
14123                       && !TREE_STATIC (r))
14124                     r = process_outer_var_ref (r, complain);
14125                 }
14126               /* Remember this for subsequent uses.  */
14127               if (local_specializations)
14128                 register_local_specialization (r, t);
14129             }
14130         }
14131       else
14132         r = t;
14133       if (!mark_used (r, complain) && !(complain & tf_error))
14134         return error_mark_node;
14135       return r;
14136
14137     case NAMESPACE_DECL:
14138       return t;
14139
14140     case OVERLOAD:
14141       /* An OVERLOAD will always be a non-dependent overload set; an
14142          overload set from function scope will just be represented with an
14143          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
14144       gcc_assert (!uses_template_parms (t));
14145       return t;
14146
14147     case BASELINK:
14148       return tsubst_baselink (t, current_nonlambda_class_type (),
14149                               args, complain, in_decl);
14150
14151     case TEMPLATE_DECL:
14152       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14153         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
14154                        args, complain, in_decl);
14155       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
14156         return tsubst (t, args, complain, in_decl);
14157       else if (DECL_CLASS_SCOPE_P (t)
14158                && uses_template_parms (DECL_CONTEXT (t)))
14159         {
14160           /* Template template argument like the following example need
14161              special treatment:
14162
14163                template <template <class> class TT> struct C {};
14164                template <class T> struct D {
14165                  template <class U> struct E {};
14166                  C<E> c;                                // #1
14167                };
14168                D<int> d;                                // #2
14169
14170              We are processing the template argument `E' in #1 for
14171              the template instantiation #2.  Originally, `E' is a
14172              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
14173              have to substitute this with one having context `D<int>'.  */
14174
14175           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
14176           return lookup_field (context, DECL_NAME(t), 0, false);
14177         }
14178       else
14179         /* Ordinary template template argument.  */
14180         return t;
14181
14182     case CAST_EXPR:
14183     case REINTERPRET_CAST_EXPR:
14184     case CONST_CAST_EXPR:
14185     case STATIC_CAST_EXPR:
14186     case DYNAMIC_CAST_EXPR:
14187     case IMPLICIT_CONV_EXPR:
14188     case CONVERT_EXPR:
14189     case NOP_EXPR:
14190       {
14191         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14192         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14193         return build1 (code, type, op0);
14194       }
14195
14196     case SIZEOF_EXPR:
14197       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
14198           || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
14199         {
14200           tree expanded, op = TREE_OPERAND (t, 0);
14201           int len = 0;
14202
14203           if (SIZEOF_EXPR_TYPE_P (t))
14204             op = TREE_TYPE (op);
14205
14206           ++cp_unevaluated_operand;
14207           ++c_inhibit_evaluation_warnings;
14208           /* We only want to compute the number of arguments.  */
14209           if (PACK_EXPANSION_P (op))
14210             expanded = tsubst_pack_expansion (op, args, complain, in_decl);
14211           else
14212             expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
14213                                              args, complain, in_decl);
14214           --cp_unevaluated_operand;
14215           --c_inhibit_evaluation_warnings;
14216
14217           if (TREE_CODE (expanded) == TREE_VEC)
14218             {
14219               len = TREE_VEC_LENGTH (expanded);
14220               /* Set TREE_USED for the benefit of -Wunused.  */
14221               for (int i = 0; i < len; i++)
14222                 if (DECL_P (TREE_VEC_ELT (expanded, i)))
14223                   TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
14224             }
14225
14226           if (expanded == error_mark_node)
14227             return error_mark_node;
14228           else if (PACK_EXPANSION_P (expanded)
14229                    || (TREE_CODE (expanded) == TREE_VEC
14230                        && pack_expansion_args_count (expanded)))
14231
14232             {
14233               if (PACK_EXPANSION_P (expanded))
14234                 /* OK.  */;
14235               else if (TREE_VEC_LENGTH (expanded) == 1)
14236                 expanded = TREE_VEC_ELT (expanded, 0);
14237               else
14238                 expanded = make_argument_pack (expanded);
14239
14240               if (TYPE_P (expanded))
14241                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
14242                                                    complain & tf_error);
14243               else
14244                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
14245                                                    complain & tf_error);
14246             }
14247           else
14248             return build_int_cst (size_type_node, len);
14249         }
14250       if (SIZEOF_EXPR_TYPE_P (t))
14251         {
14252           r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
14253                       args, complain, in_decl);
14254           r = build1 (NOP_EXPR, r, error_mark_node);
14255           r = build1 (SIZEOF_EXPR,
14256                       tsubst (TREE_TYPE (t), args, complain, in_decl), r);
14257           SIZEOF_EXPR_TYPE_P (r) = 1;
14258           return r;
14259         }
14260       /* Fall through */
14261
14262     case INDIRECT_REF:
14263     case NEGATE_EXPR:
14264     case TRUTH_NOT_EXPR:
14265     case BIT_NOT_EXPR:
14266     case ADDR_EXPR:
14267     case UNARY_PLUS_EXPR:      /* Unary + */
14268     case ALIGNOF_EXPR:
14269     case AT_ENCODE_EXPR:
14270     case ARROW_EXPR:
14271     case THROW_EXPR:
14272     case TYPEID_EXPR:
14273     case REALPART_EXPR:
14274     case IMAGPART_EXPR:
14275     case PAREN_EXPR:
14276       {
14277         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14278         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14279         return build1 (code, type, op0);
14280       }
14281
14282     case COMPONENT_REF:
14283       {
14284         tree object;
14285         tree name;
14286
14287         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14288         name = TREE_OPERAND (t, 1);
14289         if (TREE_CODE (name) == BIT_NOT_EXPR)
14290           {
14291             name = tsubst_copy (TREE_OPERAND (name, 0), args,
14292                                 complain, in_decl);
14293             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
14294           }
14295         else if (TREE_CODE (name) == SCOPE_REF
14296                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
14297           {
14298             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
14299                                      complain, in_decl);
14300             name = TREE_OPERAND (name, 1);
14301             name = tsubst_copy (TREE_OPERAND (name, 0), args,
14302                                 complain, in_decl);
14303             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
14304             name = build_qualified_name (/*type=*/NULL_TREE,
14305                                          base, name,
14306                                          /*template_p=*/false);
14307           }
14308         else if (BASELINK_P (name))
14309           name = tsubst_baselink (name,
14310                                   non_reference (TREE_TYPE (object)),
14311                                   args, complain,
14312                                   in_decl);
14313         else
14314           name = tsubst_copy (name, args, complain, in_decl);
14315         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
14316       }
14317
14318     case PLUS_EXPR:
14319     case MINUS_EXPR:
14320     case MULT_EXPR:
14321     case TRUNC_DIV_EXPR:
14322     case CEIL_DIV_EXPR:
14323     case FLOOR_DIV_EXPR:
14324     case ROUND_DIV_EXPR:
14325     case EXACT_DIV_EXPR:
14326     case BIT_AND_EXPR:
14327     case BIT_IOR_EXPR:
14328     case BIT_XOR_EXPR:
14329     case TRUNC_MOD_EXPR:
14330     case FLOOR_MOD_EXPR:
14331     case TRUTH_ANDIF_EXPR:
14332     case TRUTH_ORIF_EXPR:
14333     case TRUTH_AND_EXPR:
14334     case TRUTH_OR_EXPR:
14335     case RSHIFT_EXPR:
14336     case LSHIFT_EXPR:
14337     case RROTATE_EXPR:
14338     case LROTATE_EXPR:
14339     case EQ_EXPR:
14340     case NE_EXPR:
14341     case MAX_EXPR:
14342     case MIN_EXPR:
14343     case LE_EXPR:
14344     case GE_EXPR:
14345     case LT_EXPR:
14346     case GT_EXPR:
14347     case COMPOUND_EXPR:
14348     case DOTSTAR_EXPR:
14349     case MEMBER_REF:
14350     case PREDECREMENT_EXPR:
14351     case PREINCREMENT_EXPR:
14352     case POSTDECREMENT_EXPR:
14353     case POSTINCREMENT_EXPR:
14354       {
14355         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14356         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
14357         return build_nt (code, op0, op1);
14358       }
14359
14360     case SCOPE_REF:
14361       {
14362         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14363         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
14364         return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
14365                                      QUALIFIED_NAME_IS_TEMPLATE (t));
14366       }
14367
14368     case ARRAY_REF:
14369       {
14370         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14371         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
14372         return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
14373       }
14374
14375     case CALL_EXPR:
14376       {
14377         int n = VL_EXP_OPERAND_LENGTH (t);
14378         tree result = build_vl_exp (CALL_EXPR, n);
14379         int i;
14380         for (i = 0; i < n; i++)
14381           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
14382                                              complain, in_decl);
14383         return result;
14384       }
14385
14386     case COND_EXPR:
14387     case MODOP_EXPR:
14388     case PSEUDO_DTOR_EXPR:
14389     case VEC_PERM_EXPR:
14390       {
14391         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14392         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
14393         tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
14394         r = build_nt (code, op0, op1, op2);
14395         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
14396         return r;
14397       }
14398
14399     case NEW_EXPR:
14400       {
14401         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14402         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
14403         tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
14404         r = build_nt (code, op0, op1, op2);
14405         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
14406         return r;
14407       }
14408
14409     case DELETE_EXPR:
14410       {
14411         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14412         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
14413         r = build_nt (code, op0, op1);
14414         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
14415         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
14416         return r;
14417       }
14418
14419     case TEMPLATE_ID_EXPR:
14420       {
14421         /* Substituted template arguments */
14422         tree fn = TREE_OPERAND (t, 0);
14423         tree targs = TREE_OPERAND (t, 1);
14424
14425         fn = tsubst_copy (fn, args, complain, in_decl);
14426         if (targs)
14427           targs = tsubst_template_args (targs, args, complain, in_decl);
14428
14429         return lookup_template_function (fn, targs);
14430       }
14431
14432     case TREE_LIST:
14433       {
14434         tree purpose, value, chain;
14435
14436         if (t == void_list_node)
14437           return t;
14438
14439         purpose = TREE_PURPOSE (t);
14440         if (purpose)
14441           purpose = tsubst_copy (purpose, args, complain, in_decl);
14442         value = TREE_VALUE (t);
14443         if (value)
14444           value = tsubst_copy (value, args, complain, in_decl);
14445         chain = TREE_CHAIN (t);
14446         if (chain && chain != void_type_node)
14447           chain = tsubst_copy (chain, args, complain, in_decl);
14448         if (purpose == TREE_PURPOSE (t)
14449             && value == TREE_VALUE (t)
14450             && chain == TREE_CHAIN (t))
14451           return t;
14452         return tree_cons (purpose, value, chain);
14453       }
14454
14455     case RECORD_TYPE:
14456     case UNION_TYPE:
14457     case ENUMERAL_TYPE:
14458     case INTEGER_TYPE:
14459     case TEMPLATE_TYPE_PARM:
14460     case TEMPLATE_TEMPLATE_PARM:
14461     case BOUND_TEMPLATE_TEMPLATE_PARM:
14462     case TEMPLATE_PARM_INDEX:
14463     case POINTER_TYPE:
14464     case REFERENCE_TYPE:
14465     case OFFSET_TYPE:
14466     case FUNCTION_TYPE:
14467     case METHOD_TYPE:
14468     case ARRAY_TYPE:
14469     case TYPENAME_TYPE:
14470     case UNBOUND_CLASS_TEMPLATE:
14471     case TYPEOF_TYPE:
14472     case DECLTYPE_TYPE:
14473     case TYPE_DECL:
14474       return tsubst (t, args, complain, in_decl);
14475
14476     case USING_DECL:
14477       t = DECL_NAME (t);
14478       /* Fall through.  */
14479     case IDENTIFIER_NODE:
14480       if (IDENTIFIER_TYPENAME_P (t))
14481         {
14482           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14483           return mangle_conv_op_name_for_type (new_type);
14484         }
14485       else
14486         return t;
14487
14488     case CONSTRUCTOR:
14489       /* This is handled by tsubst_copy_and_build.  */
14490       gcc_unreachable ();
14491
14492     case VA_ARG_EXPR:
14493       {
14494         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14495         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14496         return build_x_va_arg (EXPR_LOCATION (t), op0, type);
14497       }
14498
14499     case CLEANUP_POINT_EXPR:
14500       /* We shouldn't have built any of these during initial template
14501          generation.  Instead, they should be built during instantiation
14502          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
14503       gcc_unreachable ();
14504
14505     case OFFSET_REF:
14506       {
14507         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14508         tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14509         tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
14510         r = build2 (code, type, op0, op1);
14511         PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
14512         if (!mark_used (TREE_OPERAND (r, 1), complain)
14513             && !(complain & tf_error))
14514           return error_mark_node;
14515         return r;
14516       }
14517
14518     case EXPR_PACK_EXPANSION:
14519       error ("invalid use of pack expansion expression");
14520       return error_mark_node;
14521
14522     case NONTYPE_ARGUMENT_PACK:
14523       error ("use %<...%> to expand argument pack");
14524       return error_mark_node;
14525
14526     case VOID_CST:
14527       gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
14528       return t;
14529
14530     case INTEGER_CST:
14531     case REAL_CST:
14532     case STRING_CST:
14533     case COMPLEX_CST:
14534       {
14535         /* Instantiate any typedefs in the type.  */
14536         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14537         r = fold_convert (type, t);
14538         gcc_assert (TREE_CODE (r) == code);
14539         return r;
14540       }
14541
14542     case PTRMEM_CST:
14543       /* These can sometimes show up in a partial instantiation, but never
14544          involve template parms.  */
14545       gcc_assert (!uses_template_parms (t));
14546       return t;
14547
14548     case UNARY_LEFT_FOLD_EXPR:
14549       return tsubst_unary_left_fold (t, args, complain, in_decl);
14550     case UNARY_RIGHT_FOLD_EXPR:
14551       return tsubst_unary_right_fold (t, args, complain, in_decl);
14552     case BINARY_LEFT_FOLD_EXPR:
14553       return tsubst_binary_left_fold (t, args, complain, in_decl);
14554     case BINARY_RIGHT_FOLD_EXPR:
14555       return tsubst_binary_right_fold (t, args, complain, in_decl);
14556
14557     default:
14558       /* We shouldn't get here, but keep going if !flag_checking.  */
14559       if (flag_checking)
14560         gcc_unreachable ();
14561       return t;
14562     }
14563 }
14564
14565 /* Helper function for tsubst_omp_clauses, used for instantiation of
14566    OMP_CLAUSE_DECL of clauses.  */
14567
14568 static tree
14569 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
14570                         tree in_decl)
14571 {
14572   if (decl == NULL_TREE)
14573     return NULL_TREE;
14574
14575   /* Handle an OpenMP array section represented as a TREE_LIST (or
14576      OMP_CLAUSE_DEPEND_KIND).  An OMP_CLAUSE_DEPEND (with a depend
14577      kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
14578      TREE_LIST.  We can handle it exactly the same as an array section
14579      (purpose, value, and a chain), even though the nomenclature
14580      (low_bound, length, etc) is different.  */
14581   if (TREE_CODE (decl) == TREE_LIST)
14582     {
14583       tree low_bound
14584         = tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
14585                        /*integral_constant_expression_p=*/false);
14586       tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
14587                                  /*integral_constant_expression_p=*/false);
14588       tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
14589                                            in_decl);
14590       if (TREE_PURPOSE (decl) == low_bound
14591           && TREE_VALUE (decl) == length
14592           && TREE_CHAIN (decl) == chain)
14593         return decl;
14594       tree ret = tree_cons (low_bound, length, chain);
14595       OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
14596         = OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
14597       return ret;
14598     }
14599   tree ret = tsubst_expr (decl, args, complain, in_decl,
14600                           /*integral_constant_expression_p=*/false);
14601   /* Undo convert_from_reference tsubst_expr could have called.  */
14602   if (decl
14603       && REFERENCE_REF_P (ret)
14604       && !REFERENCE_REF_P (decl))
14605     ret = TREE_OPERAND (ret, 0);
14606   return ret;
14607 }
14608
14609 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
14610
14611 static tree
14612 tsubst_omp_clauses (tree clauses, bool declare_simd, bool allow_fields,
14613                     tree args, tsubst_flags_t complain, tree in_decl)
14614 {
14615   tree new_clauses = NULL_TREE, nc, oc;
14616   tree linear_no_step = NULL_TREE;
14617
14618   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
14619     {
14620       nc = copy_node (oc);
14621       OMP_CLAUSE_CHAIN (nc) = new_clauses;
14622       new_clauses = nc;
14623
14624       switch (OMP_CLAUSE_CODE (nc))
14625         {
14626         case OMP_CLAUSE_LASTPRIVATE:
14627           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
14628             {
14629               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
14630               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
14631                            in_decl, /*integral_constant_expression_p=*/false);
14632               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
14633                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
14634             }
14635           /* FALLTHRU */
14636         case OMP_CLAUSE_PRIVATE:
14637         case OMP_CLAUSE_SHARED:
14638         case OMP_CLAUSE_FIRSTPRIVATE:
14639         case OMP_CLAUSE_COPYIN:
14640         case OMP_CLAUSE_COPYPRIVATE:
14641         case OMP_CLAUSE_UNIFORM:
14642         case OMP_CLAUSE_DEPEND:
14643         case OMP_CLAUSE_FROM:
14644         case OMP_CLAUSE_TO:
14645         case OMP_CLAUSE_MAP:
14646         case OMP_CLAUSE_USE_DEVICE_PTR:
14647         case OMP_CLAUSE_IS_DEVICE_PTR:
14648           OMP_CLAUSE_DECL (nc)
14649             = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
14650                                       in_decl);
14651           break;
14652         case OMP_CLAUSE_IF:
14653         case OMP_CLAUSE_NUM_THREADS:
14654         case OMP_CLAUSE_SCHEDULE:
14655         case OMP_CLAUSE_COLLAPSE:
14656         case OMP_CLAUSE_FINAL:
14657         case OMP_CLAUSE_DEVICE:
14658         case OMP_CLAUSE_DIST_SCHEDULE:
14659         case OMP_CLAUSE_NUM_TEAMS:
14660         case OMP_CLAUSE_THREAD_LIMIT:
14661         case OMP_CLAUSE_SAFELEN:
14662         case OMP_CLAUSE_SIMDLEN:
14663         case OMP_CLAUSE_NUM_TASKS:
14664         case OMP_CLAUSE_GRAINSIZE:
14665         case OMP_CLAUSE_PRIORITY:
14666         case OMP_CLAUSE_ORDERED:
14667         case OMP_CLAUSE_HINT:
14668         case OMP_CLAUSE_NUM_GANGS:
14669         case OMP_CLAUSE_NUM_WORKERS:
14670         case OMP_CLAUSE_VECTOR_LENGTH:
14671         case OMP_CLAUSE_WORKER:
14672         case OMP_CLAUSE_VECTOR:
14673         case OMP_CLAUSE_ASYNC:
14674         case OMP_CLAUSE_WAIT:
14675           OMP_CLAUSE_OPERAND (nc, 0)
14676             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
14677                            in_decl, /*integral_constant_expression_p=*/false);
14678           break;
14679         case OMP_CLAUSE_REDUCTION:
14680           if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
14681             {
14682               tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
14683               if (TREE_CODE (placeholder) == SCOPE_REF)
14684                 {
14685                   tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
14686                                        complain, in_decl);
14687                   OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
14688                     = build_qualified_name (NULL_TREE, scope,
14689                                             TREE_OPERAND (placeholder, 1),
14690                                             false);
14691                 }
14692               else
14693                 gcc_assert (identifier_p (placeholder));
14694             }
14695           OMP_CLAUSE_DECL (nc)
14696             = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
14697                                       in_decl);
14698           break;
14699         case OMP_CLAUSE_GANG:
14700         case OMP_CLAUSE_ALIGNED:
14701           OMP_CLAUSE_DECL (nc)
14702             = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
14703                                       in_decl);
14704           OMP_CLAUSE_OPERAND (nc, 1)
14705             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
14706                            in_decl, /*integral_constant_expression_p=*/false);
14707           break;
14708         case OMP_CLAUSE_LINEAR:
14709           OMP_CLAUSE_DECL (nc)
14710             = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
14711                                       in_decl);
14712           if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
14713             {
14714               gcc_assert (!linear_no_step);
14715               linear_no_step = nc;
14716             }
14717           else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
14718             OMP_CLAUSE_LINEAR_STEP (nc)
14719               = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
14720                                         complain, in_decl);
14721           else
14722             OMP_CLAUSE_LINEAR_STEP (nc)
14723               = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
14724                              in_decl,
14725                              /*integral_constant_expression_p=*/false);
14726           break;
14727         case OMP_CLAUSE_NOWAIT:
14728         case OMP_CLAUSE_DEFAULT:
14729         case OMP_CLAUSE_UNTIED:
14730         case OMP_CLAUSE_MERGEABLE:
14731         case OMP_CLAUSE_INBRANCH:
14732         case OMP_CLAUSE_NOTINBRANCH:
14733         case OMP_CLAUSE_PROC_BIND:
14734         case OMP_CLAUSE_FOR:
14735         case OMP_CLAUSE_PARALLEL:
14736         case OMP_CLAUSE_SECTIONS:
14737         case OMP_CLAUSE_TASKGROUP:
14738         case OMP_CLAUSE_NOGROUP:
14739         case OMP_CLAUSE_THREADS:
14740         case OMP_CLAUSE_SIMD:
14741         case OMP_CLAUSE_DEFAULTMAP:
14742         case OMP_CLAUSE_INDEPENDENT:
14743         case OMP_CLAUSE_AUTO:
14744         case OMP_CLAUSE_SEQ:
14745           break;
14746         case OMP_CLAUSE_TILE:
14747           {
14748             tree lnc, loc;
14749             for (lnc = OMP_CLAUSE_TILE_LIST (nc),
14750                    loc = OMP_CLAUSE_TILE_LIST (oc);
14751                  loc;
14752                  loc = TREE_CHAIN (loc), lnc = TREE_CHAIN (lnc))
14753               {
14754                 TREE_VALUE (lnc) = tsubst_expr (TREE_VALUE (loc), args,
14755                                                 complain, in_decl, false);
14756               }
14757           }
14758           break;
14759         default:
14760           gcc_unreachable ();
14761         }
14762       if (allow_fields)
14763         switch (OMP_CLAUSE_CODE (nc))
14764           {
14765           case OMP_CLAUSE_SHARED:
14766           case OMP_CLAUSE_PRIVATE:
14767           case OMP_CLAUSE_FIRSTPRIVATE:
14768           case OMP_CLAUSE_LASTPRIVATE:
14769           case OMP_CLAUSE_COPYPRIVATE:
14770           case OMP_CLAUSE_LINEAR:
14771           case OMP_CLAUSE_REDUCTION:
14772           case OMP_CLAUSE_USE_DEVICE_PTR:
14773           case OMP_CLAUSE_IS_DEVICE_PTR:
14774             /* tsubst_expr on SCOPE_REF results in returning
14775                finish_non_static_data_member result.  Undo that here.  */
14776             if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
14777                 && (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
14778                     == IDENTIFIER_NODE))
14779               {
14780                 tree t = OMP_CLAUSE_DECL (nc);
14781                 tree v = t;
14782                 while (v)
14783                   switch (TREE_CODE (v))
14784                     {
14785                     case COMPONENT_REF:
14786                     case MEM_REF:
14787                     case INDIRECT_REF:
14788                     CASE_CONVERT:
14789                     case POINTER_PLUS_EXPR:
14790                       v = TREE_OPERAND (v, 0);
14791                       continue;
14792                     case PARM_DECL:
14793                       if (DECL_CONTEXT (v) == current_function_decl
14794                           && DECL_ARTIFICIAL (v)
14795                           && DECL_NAME (v) == this_identifier)
14796                         OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
14797                       /* FALLTHRU */
14798                     default:
14799                       v = NULL_TREE;
14800                       break;
14801                     }
14802               }
14803             else if (VAR_P (OMP_CLAUSE_DECL (oc))
14804                      && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
14805                      && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
14806                      && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
14807                      && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
14808               {
14809                 tree decl = OMP_CLAUSE_DECL (nc);
14810                 if (VAR_P (decl))
14811                   {
14812                     if (!DECL_LANG_SPECIFIC (decl))
14813                       retrofit_lang_decl (decl);
14814                     DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
14815                   }
14816               }
14817             break;
14818           default:
14819             break;
14820           }
14821     }
14822
14823   new_clauses = nreverse (new_clauses);
14824   if (!declare_simd)
14825     {
14826       new_clauses = finish_omp_clauses (new_clauses, allow_fields);
14827       if (linear_no_step)
14828         for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
14829           if (nc == linear_no_step)
14830             {
14831               OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
14832               break;
14833             }
14834     }
14835   return new_clauses;
14836 }
14837
14838 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
14839
14840 static tree
14841 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
14842                           tree in_decl)
14843 {
14844 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
14845
14846   tree purpose, value, chain;
14847
14848   if (t == NULL)
14849     return t;
14850
14851   if (TREE_CODE (t) != TREE_LIST)
14852     return tsubst_copy_and_build (t, args, complain, in_decl,
14853                                   /*function_p=*/false,
14854                                   /*integral_constant_expression_p=*/false);
14855
14856   if (t == void_list_node)
14857     return t;
14858
14859   purpose = TREE_PURPOSE (t);
14860   if (purpose)
14861     purpose = RECUR (purpose);
14862   value = TREE_VALUE (t);
14863   if (value)
14864     {
14865       if (TREE_CODE (value) != LABEL_DECL)
14866         value = RECUR (value);
14867       else
14868         {
14869           value = lookup_label (DECL_NAME (value));
14870           gcc_assert (TREE_CODE (value) == LABEL_DECL);
14871           TREE_USED (value) = 1;
14872         }
14873     }
14874   chain = TREE_CHAIN (t);
14875   if (chain && chain != void_type_node)
14876     chain = RECUR (chain);
14877   return tree_cons (purpose, value, chain);
14878 #undef RECUR
14879 }
14880
14881 /* Used to temporarily communicate the list of #pragma omp parallel
14882    clauses to #pragma omp for instantiation if they are combined
14883    together.  */
14884
14885 static tree *omp_parallel_combined_clauses;
14886
14887 /* Substitute one OMP_FOR iterator.  */
14888
14889 static void
14890 tsubst_omp_for_iterator (tree t, int i, tree declv, tree orig_declv,
14891                          tree initv, tree condv, tree incrv, tree *clauses,
14892                          tree args, tsubst_flags_t complain, tree in_decl,
14893                          bool integral_constant_expression_p)
14894 {
14895 #define RECUR(NODE)                             \
14896   tsubst_expr ((NODE), args, complain, in_decl, \
14897                integral_constant_expression_p)
14898   tree decl, init, cond, incr;
14899
14900   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
14901   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
14902
14903   if (orig_declv && OMP_FOR_ORIG_DECLS (t))
14904     {
14905       tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
14906       TREE_VEC_ELT (orig_declv, i) = RECUR (o);
14907     }
14908
14909   decl = TREE_OPERAND (init, 0);
14910   init = TREE_OPERAND (init, 1);
14911   tree decl_expr = NULL_TREE;
14912   if (init && TREE_CODE (init) == DECL_EXPR)
14913     {
14914       /* We need to jump through some hoops to handle declarations in the
14915          for-init-statement, since we might need to handle auto deduction,
14916          but we need to keep control of initialization.  */
14917       decl_expr = init;
14918       init = DECL_INITIAL (DECL_EXPR_DECL (init));
14919       decl = tsubst_decl (decl, args, complain);
14920     }
14921   else
14922     {
14923       if (TREE_CODE (decl) == SCOPE_REF)
14924         {
14925           decl = RECUR (decl);
14926           if (TREE_CODE (decl) == COMPONENT_REF)
14927             {
14928               tree v = decl;
14929               while (v)
14930                 switch (TREE_CODE (v))
14931                   {
14932                   case COMPONENT_REF:
14933                   case MEM_REF:
14934                   case INDIRECT_REF:
14935                   CASE_CONVERT:
14936                   case POINTER_PLUS_EXPR:
14937                     v = TREE_OPERAND (v, 0);
14938                     continue;
14939                   case PARM_DECL:
14940                     if (DECL_CONTEXT (v) == current_function_decl
14941                         && DECL_ARTIFICIAL (v)
14942                         && DECL_NAME (v) == this_identifier)
14943                       {
14944                         decl = TREE_OPERAND (decl, 1);
14945                         decl = omp_privatize_field (decl, false);
14946                       }
14947                     /* FALLTHRU */
14948                   default:
14949                     v = NULL_TREE;
14950                     break;
14951                   }
14952             }
14953         }
14954       else
14955         decl = RECUR (decl);
14956     }
14957   init = RECUR (init);
14958
14959   tree auto_node = type_uses_auto (TREE_TYPE (decl));
14960   if (auto_node && init)
14961     TREE_TYPE (decl)
14962       = do_auto_deduction (TREE_TYPE (decl), init, auto_node);
14963
14964   gcc_assert (!type_dependent_expression_p (decl));
14965
14966   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
14967     {
14968       if (decl_expr)
14969         {
14970           /* Declare the variable, but don't let that initialize it.  */
14971           tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
14972           DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
14973           RECUR (decl_expr);
14974           DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
14975         }
14976
14977       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
14978       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
14979       if (TREE_CODE (incr) == MODIFY_EXPR)
14980         {
14981           tree lhs = RECUR (TREE_OPERAND (incr, 0));
14982           tree rhs = RECUR (TREE_OPERAND (incr, 1));
14983           incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
14984                                       NOP_EXPR, rhs, complain);
14985         }
14986       else
14987         incr = RECUR (incr);
14988       TREE_VEC_ELT (declv, i) = decl;
14989       TREE_VEC_ELT (initv, i) = init;
14990       TREE_VEC_ELT (condv, i) = cond;
14991       TREE_VEC_ELT (incrv, i) = incr;
14992       return;
14993     }
14994
14995   if (decl_expr)
14996     {
14997       /* Declare and initialize the variable.  */
14998       RECUR (decl_expr);
14999       init = NULL_TREE;
15000     }
15001   else if (init)
15002     {
15003       tree *pc;
15004       int j;
15005       for (j = (omp_parallel_combined_clauses == NULL ? 1 : 0); j < 2; j++)
15006         {
15007           for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
15008             {
15009               if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
15010                   && OMP_CLAUSE_DECL (*pc) == decl)
15011                 break;
15012               else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
15013                        && OMP_CLAUSE_DECL (*pc) == decl)
15014                 {
15015                   if (j)
15016                     break;
15017                   /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES.  */
15018                   tree c = *pc;
15019                   *pc = OMP_CLAUSE_CHAIN (c);
15020                   OMP_CLAUSE_CHAIN (c) = *clauses;
15021                   *clauses = c;
15022                 }
15023               else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
15024                        && OMP_CLAUSE_DECL (*pc) == decl)
15025                 {
15026                   error ("iteration variable %qD should not be firstprivate",
15027                          decl);
15028                   *pc = OMP_CLAUSE_CHAIN (*pc);
15029                 }
15030               else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
15031                        && OMP_CLAUSE_DECL (*pc) == decl)
15032                 {
15033                   error ("iteration variable %qD should not be reduction",
15034                          decl);
15035                   *pc = OMP_CLAUSE_CHAIN (*pc);
15036                 }
15037               else
15038                 pc = &OMP_CLAUSE_CHAIN (*pc);
15039             }
15040           if (*pc)
15041             break;
15042         }
15043       if (*pc == NULL_TREE)
15044         {
15045           tree c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
15046           OMP_CLAUSE_DECL (c) = decl;
15047           c = finish_omp_clauses (c, true);
15048           if (c)
15049             {
15050               OMP_CLAUSE_CHAIN (c) = *clauses;
15051               *clauses = c;
15052             }
15053         }
15054     }
15055   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
15056   if (COMPARISON_CLASS_P (cond))
15057     {
15058       tree op0 = RECUR (TREE_OPERAND (cond, 0));
15059       tree op1 = RECUR (TREE_OPERAND (cond, 1));
15060       cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
15061     }
15062   else
15063     cond = RECUR (cond);
15064   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
15065   switch (TREE_CODE (incr))
15066     {
15067     case PREINCREMENT_EXPR:
15068     case PREDECREMENT_EXPR:
15069     case POSTINCREMENT_EXPR:
15070     case POSTDECREMENT_EXPR:
15071       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
15072                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
15073       break;
15074     case MODIFY_EXPR:
15075       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
15076           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
15077         {
15078           tree rhs = TREE_OPERAND (incr, 1);
15079           tree lhs = RECUR (TREE_OPERAND (incr, 0));
15080           tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
15081           tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
15082           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
15083                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
15084                                  rhs0, rhs1));
15085         }
15086       else
15087         incr = RECUR (incr);
15088       break;
15089     case MODOP_EXPR:
15090       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
15091           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
15092         {
15093           tree lhs = RECUR (TREE_OPERAND (incr, 0));
15094           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
15095                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
15096                                  TREE_TYPE (decl), lhs,
15097                                  RECUR (TREE_OPERAND (incr, 2))));
15098         }
15099       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
15100                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
15101                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
15102         {
15103           tree rhs = TREE_OPERAND (incr, 2);
15104           tree lhs = RECUR (TREE_OPERAND (incr, 0));
15105           tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
15106           tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
15107           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
15108                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
15109                                  rhs0, rhs1));
15110         }
15111       else
15112         incr = RECUR (incr);
15113       break;
15114     default:
15115       incr = RECUR (incr);
15116       break;
15117     }
15118
15119   TREE_VEC_ELT (declv, i) = decl;
15120   TREE_VEC_ELT (initv, i) = init;
15121   TREE_VEC_ELT (condv, i) = cond;
15122   TREE_VEC_ELT (incrv, i) = incr;
15123 #undef RECUR
15124 }
15125
15126 /* Helper function of tsubst_expr, find OMP_TEAMS inside
15127    of OMP_TARGET's body.  */
15128
15129 static tree
15130 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
15131 {
15132   *walk_subtrees = 0;
15133   switch (TREE_CODE (*tp))
15134     {
15135     case OMP_TEAMS:
15136       return *tp;
15137     case BIND_EXPR:
15138     case STATEMENT_LIST:
15139       *walk_subtrees = 1;
15140       break;
15141     default:
15142       break;
15143     }
15144   return NULL_TREE;
15145 }
15146
15147 /* Like tsubst_copy for expressions, etc. but also does semantic
15148    processing.  */
15149
15150 tree
15151 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
15152              bool integral_constant_expression_p)
15153 {
15154 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
15155 #define RECUR(NODE)                             \
15156   tsubst_expr ((NODE), args, complain, in_decl, \
15157                integral_constant_expression_p)
15158
15159   tree stmt, tmp;
15160   tree r;
15161   location_t loc;
15162
15163   if (t == NULL_TREE || t == error_mark_node)
15164     return t;
15165
15166   loc = input_location;
15167   if (EXPR_HAS_LOCATION (t))
15168     input_location = EXPR_LOCATION (t);
15169   if (STATEMENT_CODE_P (TREE_CODE (t)))
15170     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
15171
15172   switch (TREE_CODE (t))
15173     {
15174     case STATEMENT_LIST:
15175       {
15176         tree_stmt_iterator i;
15177         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
15178           RECUR (tsi_stmt (i));
15179         break;
15180       }
15181
15182     case CTOR_INITIALIZER:
15183       finish_mem_initializers (tsubst_initializer_list
15184                                (TREE_OPERAND (t, 0), args));
15185       break;
15186
15187     case RETURN_EXPR:
15188       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
15189       break;
15190
15191     case EXPR_STMT:
15192       tmp = RECUR (EXPR_STMT_EXPR (t));
15193       if (EXPR_STMT_STMT_EXPR_RESULT (t))
15194         finish_stmt_expr_expr (tmp, cur_stmt_expr);
15195       else
15196         finish_expr_stmt (tmp);
15197       break;
15198
15199     case USING_STMT:
15200       do_using_directive (USING_STMT_NAMESPACE (t));
15201       break;
15202
15203     case DECL_EXPR:
15204       {
15205         tree decl, pattern_decl;
15206         tree init;
15207
15208         pattern_decl = decl = DECL_EXPR_DECL (t);
15209         if (TREE_CODE (decl) == LABEL_DECL)
15210           finish_label_decl (DECL_NAME (decl));
15211         else if (TREE_CODE (decl) == USING_DECL)
15212           {
15213             tree scope = USING_DECL_SCOPE (decl);
15214             tree name = DECL_NAME (decl);
15215             tree decl;
15216
15217             scope = tsubst (scope, args, complain, in_decl);
15218             decl = lookup_qualified_name (scope, name,
15219                                           /*is_type_p=*/false,
15220                                           /*complain=*/false);
15221             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
15222               qualified_name_lookup_error (scope, name, decl, input_location);
15223             else
15224               do_local_using_decl (decl, scope, name);
15225           }
15226         else if (DECL_PACK_P (decl))
15227           {
15228             /* Don't build up decls for a variadic capture proxy, we'll
15229                instantiate the elements directly as needed.  */
15230             break;
15231           }
15232         else
15233           {
15234             init = DECL_INITIAL (decl);
15235             decl = tsubst (decl, args, complain, in_decl);
15236             if (decl != error_mark_node)
15237               {
15238                 /* By marking the declaration as instantiated, we avoid
15239                    trying to instantiate it.  Since instantiate_decl can't
15240                    handle local variables, and since we've already done
15241                    all that needs to be done, that's the right thing to
15242                    do.  */
15243                 if (VAR_P (decl))
15244                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
15245                 if (VAR_P (decl)
15246                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
15247                   /* Anonymous aggregates are a special case.  */
15248                   finish_anon_union (decl);
15249                 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
15250                   {
15251                     DECL_CONTEXT (decl) = current_function_decl;
15252                     if (DECL_NAME (decl) == this_identifier)
15253                       {
15254                         tree lam = DECL_CONTEXT (current_function_decl);
15255                         lam = CLASSTYPE_LAMBDA_EXPR (lam);
15256                         LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
15257                       }
15258                     insert_capture_proxy (decl);
15259                   }
15260                 else if (DECL_IMPLICIT_TYPEDEF_P (t))
15261                   /* We already did a pushtag.  */;
15262                 else if (TREE_CODE (decl) == FUNCTION_DECL
15263                          && DECL_OMP_DECLARE_REDUCTION_P (decl)
15264                          && DECL_FUNCTION_SCOPE_P (pattern_decl))
15265                   {
15266                     DECL_CONTEXT (decl) = NULL_TREE;
15267                     pushdecl (decl);
15268                     DECL_CONTEXT (decl) = current_function_decl;
15269                     cp_check_omp_declare_reduction (decl);
15270                   }
15271                 else
15272                   {
15273                     int const_init = false;
15274                     maybe_push_decl (decl);
15275                     if (VAR_P (decl)
15276                         && DECL_PRETTY_FUNCTION_P (decl))
15277                       {
15278                         /* For __PRETTY_FUNCTION__ we have to adjust the
15279                            initializer.  */
15280                         const char *const name
15281                           = cxx_printable_name (current_function_decl, 2);
15282                         init = cp_fname_init (name, &TREE_TYPE (decl));
15283                       }
15284                     else
15285                       init = tsubst_init (init, decl, args, complain, in_decl);
15286
15287                     if (VAR_P (decl))
15288                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
15289                                     (pattern_decl));
15290                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
15291                   }
15292               }
15293           }
15294
15295         break;
15296       }
15297
15298     case FOR_STMT:
15299       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
15300       RECUR (FOR_INIT_STMT (t));
15301       finish_for_init_stmt (stmt);
15302       tmp = RECUR (FOR_COND (t));
15303       finish_for_cond (tmp, stmt, false);
15304       tmp = RECUR (FOR_EXPR (t));
15305       finish_for_expr (tmp, stmt);
15306       RECUR (FOR_BODY (t));
15307       finish_for_stmt (stmt);
15308       break;
15309
15310     case RANGE_FOR_STMT:
15311       {
15312         tree decl, expr;
15313         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
15314         decl = RANGE_FOR_DECL (t);
15315         decl = tsubst (decl, args, complain, in_decl);
15316         maybe_push_decl (decl);
15317         expr = RECUR (RANGE_FOR_EXPR (t));
15318         stmt = cp_convert_range_for (stmt, decl, expr, RANGE_FOR_IVDEP (t));
15319         RECUR (RANGE_FOR_BODY (t));
15320         finish_for_stmt (stmt);
15321       }
15322       break;
15323
15324     case WHILE_STMT:
15325       stmt = begin_while_stmt ();
15326       tmp = RECUR (WHILE_COND (t));
15327       finish_while_stmt_cond (tmp, stmt, false);
15328       RECUR (WHILE_BODY (t));
15329       finish_while_stmt (stmt);
15330       break;
15331
15332     case DO_STMT:
15333       stmt = begin_do_stmt ();
15334       RECUR (DO_BODY (t));
15335       finish_do_body (stmt);
15336       tmp = RECUR (DO_COND (t));
15337       finish_do_stmt (tmp, stmt, false);
15338       break;
15339
15340     case IF_STMT:
15341       stmt = begin_if_stmt ();
15342       tmp = RECUR (IF_COND (t));
15343       finish_if_stmt_cond (tmp, stmt);
15344       RECUR (THEN_CLAUSE (t));
15345       finish_then_clause (stmt);
15346
15347       if (ELSE_CLAUSE (t))
15348         {
15349           begin_else_clause (stmt);
15350           RECUR (ELSE_CLAUSE (t));
15351           finish_else_clause (stmt);
15352         }
15353
15354       finish_if_stmt (stmt);
15355       break;
15356
15357     case BIND_EXPR:
15358       if (BIND_EXPR_BODY_BLOCK (t))
15359         stmt = begin_function_body ();
15360       else
15361         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
15362                                     ? BCS_TRY_BLOCK : 0);
15363
15364       RECUR (BIND_EXPR_BODY (t));
15365
15366       if (BIND_EXPR_BODY_BLOCK (t))
15367         finish_function_body (stmt);
15368       else
15369         finish_compound_stmt (stmt);
15370       break;
15371
15372     case BREAK_STMT:
15373       finish_break_stmt ();
15374       break;
15375
15376     case CONTINUE_STMT:
15377       finish_continue_stmt ();
15378       break;
15379
15380     case SWITCH_STMT:
15381       stmt = begin_switch_stmt ();
15382       tmp = RECUR (SWITCH_STMT_COND (t));
15383       finish_switch_cond (tmp, stmt);
15384       RECUR (SWITCH_STMT_BODY (t));
15385       finish_switch_stmt (stmt);
15386       break;
15387
15388     case CASE_LABEL_EXPR:
15389       {
15390         tree low = RECUR (CASE_LOW (t));
15391         tree high = RECUR (CASE_HIGH (t));
15392         finish_case_label (EXPR_LOCATION (t), low, high);
15393       }
15394       break;
15395
15396     case LABEL_EXPR:
15397       {
15398         tree decl = LABEL_EXPR_LABEL (t);
15399         tree label;
15400
15401         label = finish_label_stmt (DECL_NAME (decl));
15402         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
15403           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
15404       }
15405       break;
15406
15407     case GOTO_EXPR:
15408       tmp = GOTO_DESTINATION (t);
15409       if (TREE_CODE (tmp) != LABEL_DECL)
15410         /* Computed goto's must be tsubst'd into.  On the other hand,
15411            non-computed gotos must not be; the identifier in question
15412            will have no binding.  */
15413         tmp = RECUR (tmp);
15414       else
15415         tmp = DECL_NAME (tmp);
15416       finish_goto_stmt (tmp);
15417       break;
15418
15419     case ASM_EXPR:
15420       {
15421         tree string = RECUR (ASM_STRING (t));
15422         tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
15423                                                  complain, in_decl);
15424         tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
15425                                                 complain, in_decl);
15426         tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
15427                                                   complain, in_decl);
15428         tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
15429                                                 complain, in_decl);
15430         tmp = finish_asm_stmt (ASM_VOLATILE_P (t), string, outputs, inputs,
15431                                clobbers, labels);
15432         tree asm_expr = tmp;
15433         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
15434           asm_expr = TREE_OPERAND (asm_expr, 0);
15435         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
15436       }
15437       break;
15438
15439     case TRY_BLOCK:
15440       if (CLEANUP_P (t))
15441         {
15442           stmt = begin_try_block ();
15443           RECUR (TRY_STMTS (t));
15444           finish_cleanup_try_block (stmt);
15445           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
15446         }
15447       else
15448         {
15449           tree compound_stmt = NULL_TREE;
15450
15451           if (FN_TRY_BLOCK_P (t))
15452             stmt = begin_function_try_block (&compound_stmt);
15453           else
15454             stmt = begin_try_block ();
15455
15456           RECUR (TRY_STMTS (t));
15457
15458           if (FN_TRY_BLOCK_P (t))
15459             finish_function_try_block (stmt);
15460           else
15461             finish_try_block (stmt);
15462
15463           RECUR (TRY_HANDLERS (t));
15464           if (FN_TRY_BLOCK_P (t))
15465             finish_function_handler_sequence (stmt, compound_stmt);
15466           else
15467             finish_handler_sequence (stmt);
15468         }
15469       break;
15470
15471     case HANDLER:
15472       {
15473         tree decl = HANDLER_PARMS (t);
15474
15475         if (decl)
15476           {
15477             decl = tsubst (decl, args, complain, in_decl);
15478             /* Prevent instantiate_decl from trying to instantiate
15479                this variable.  We've already done all that needs to be
15480                done.  */
15481             if (decl != error_mark_node)
15482               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
15483           }
15484         stmt = begin_handler ();
15485         finish_handler_parms (decl, stmt);
15486         RECUR (HANDLER_BODY (t));
15487         finish_handler (stmt);
15488       }
15489       break;
15490
15491     case TAG_DEFN:
15492       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
15493       if (CLASS_TYPE_P (tmp))
15494         {
15495           /* Local classes are not independent templates; they are
15496              instantiated along with their containing function.  And this
15497              way we don't have to deal with pushing out of one local class
15498              to instantiate a member of another local class.  */
15499           tree fn;
15500           /* Closures are handled by the LAMBDA_EXPR.  */
15501           gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
15502           complete_type (tmp);
15503           for (fn = TYPE_METHODS (tmp); fn; fn = DECL_CHAIN (fn))
15504             if (!DECL_ARTIFICIAL (fn))
15505               instantiate_decl (fn, /*defer_ok*/0, /*expl_inst_class*/false);
15506         }
15507       break;
15508
15509     case STATIC_ASSERT:
15510       {
15511         tree condition;
15512
15513         ++c_inhibit_evaluation_warnings;
15514         condition = 
15515           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
15516                        args,
15517                        complain, in_decl,
15518                        /*integral_constant_expression_p=*/true);
15519         --c_inhibit_evaluation_warnings;
15520
15521         finish_static_assert (condition,
15522                               STATIC_ASSERT_MESSAGE (t),
15523                               STATIC_ASSERT_SOURCE_LOCATION (t),
15524                               /*member_p=*/false);
15525       }
15526       break;
15527
15528     case OACC_KERNELS:
15529     case OACC_PARALLEL:
15530       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), false, false, args, complain,
15531                                 in_decl);
15532       stmt = begin_omp_parallel ();
15533       RECUR (OMP_BODY (t));
15534       finish_omp_construct (TREE_CODE (t), stmt, tmp);
15535       break;
15536
15537     case OMP_PARALLEL:
15538       r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
15539       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), false, true,
15540                                 args, complain, in_decl);
15541       if (OMP_PARALLEL_COMBINED (t))
15542         omp_parallel_combined_clauses = &tmp;
15543       stmt = begin_omp_parallel ();
15544       RECUR (OMP_PARALLEL_BODY (t));
15545       gcc_assert (omp_parallel_combined_clauses == NULL);
15546       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
15547         = OMP_PARALLEL_COMBINED (t);
15548       pop_omp_privatization_clauses (r);
15549       break;
15550
15551     case OMP_TASK:
15552       r = push_omp_privatization_clauses (false);
15553       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), false, true,
15554                                 args, complain, in_decl);
15555       stmt = begin_omp_task ();
15556       RECUR (OMP_TASK_BODY (t));
15557       finish_omp_task (tmp, stmt);
15558       pop_omp_privatization_clauses (r);
15559       break;
15560
15561     case OMP_FOR:
15562     case OMP_SIMD:
15563     case CILK_SIMD:
15564     case CILK_FOR:
15565     case OMP_DISTRIBUTE:
15566     case OMP_TASKLOOP:
15567     case OACC_LOOP:
15568       {
15569         tree clauses, body, pre_body;
15570         tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
15571         tree orig_declv = NULL_TREE;
15572         tree incrv = NULL_TREE;
15573         int i;
15574
15575         r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
15576         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), false,
15577                                       TREE_CODE (t) != OACC_LOOP,
15578                                       args, complain, in_decl);
15579         if (OMP_FOR_INIT (t) != NULL_TREE)
15580           {
15581             declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
15582             if (OMP_FOR_ORIG_DECLS (t))
15583               orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
15584             initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
15585             condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
15586             incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
15587           }
15588
15589         stmt = begin_omp_structured_block ();
15590
15591         pre_body = push_stmt_list ();
15592         RECUR (OMP_FOR_PRE_BODY (t));
15593         pre_body = pop_stmt_list (pre_body);
15594
15595         if (OMP_FOR_INIT (t) != NULL_TREE)
15596           for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
15597             tsubst_omp_for_iterator (t, i, declv, orig_declv, initv, condv,
15598                                      incrv, &clauses, args, complain, in_decl,
15599                                      integral_constant_expression_p);
15600         omp_parallel_combined_clauses = NULL;
15601
15602         body = push_stmt_list ();
15603         RECUR (OMP_FOR_BODY (t));
15604         body = pop_stmt_list (body);
15605
15606         if (OMP_FOR_INIT (t) != NULL_TREE)
15607           t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
15608                               orig_declv, initv, condv, incrv, body, pre_body,
15609                               NULL, clauses);
15610         else
15611           {
15612             t = make_node (TREE_CODE (t));
15613             TREE_TYPE (t) = void_type_node;
15614             OMP_FOR_BODY (t) = body;
15615             OMP_FOR_PRE_BODY (t) = pre_body;
15616             OMP_FOR_CLAUSES (t) = clauses;
15617             SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
15618             add_stmt (t);
15619           }
15620
15621         add_stmt (finish_omp_structured_block (stmt));
15622         pop_omp_privatization_clauses (r);
15623       }
15624       break;
15625
15626     case OMP_SECTIONS:
15627       omp_parallel_combined_clauses = NULL;
15628       /* FALLTHRU */
15629     case OMP_SINGLE:
15630     case OMP_TEAMS:
15631     case OMP_CRITICAL:
15632       r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
15633                                           && OMP_TEAMS_COMBINED (t));
15634       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), false, true,
15635                                 args, complain, in_decl);
15636       stmt = push_stmt_list ();
15637       RECUR (OMP_BODY (t));
15638       stmt = pop_stmt_list (stmt);
15639
15640       t = copy_node (t);
15641       OMP_BODY (t) = stmt;
15642       OMP_CLAUSES (t) = tmp;
15643       add_stmt (t);
15644       pop_omp_privatization_clauses (r);
15645       break;
15646
15647     case OACC_DATA:
15648     case OMP_TARGET_DATA:
15649     case OMP_TARGET:
15650       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), false,
15651                                 TREE_CODE (t) != OACC_DATA,
15652                                 args, complain, in_decl);
15653       keep_next_level (true);
15654       stmt = begin_omp_structured_block ();
15655
15656       RECUR (OMP_BODY (t));
15657       stmt = finish_omp_structured_block (stmt);
15658
15659       t = copy_node (t);
15660       OMP_BODY (t) = stmt;
15661       OMP_CLAUSES (t) = tmp;
15662       if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
15663         {
15664           tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
15665           if (teams)
15666             {
15667               /* For combined target teams, ensure the num_teams and
15668                  thread_limit clause expressions are evaluated on the host,
15669                  before entering the target construct.  */
15670               tree c;
15671               for (c = OMP_TEAMS_CLAUSES (teams);
15672                    c; c = OMP_CLAUSE_CHAIN (c))
15673                 if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
15674                      || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
15675                     && TREE_CODE (OMP_CLAUSE_OPERAND (c, 0)) != INTEGER_CST)
15676                   {
15677                     tree expr = OMP_CLAUSE_OPERAND (c, 0);
15678                     expr = force_target_expr (TREE_TYPE (expr), expr, tf_none);
15679                     if (expr == error_mark_node)
15680                       continue;
15681                     tmp = TARGET_EXPR_SLOT (expr);
15682                     add_stmt (expr);
15683                     OMP_CLAUSE_OPERAND (c, 0) = expr;
15684                     tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
15685                                                 OMP_CLAUSE_FIRSTPRIVATE);
15686                     OMP_CLAUSE_DECL (tc) = tmp;
15687                     OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
15688                     OMP_TARGET_CLAUSES (t) = tc;
15689                   }
15690             }
15691         }
15692       add_stmt (t);
15693       break;
15694
15695     case OACC_DECLARE:
15696       t = copy_node (t);
15697       tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), false, false,
15698                                 args, complain, in_decl);
15699       OACC_DECLARE_CLAUSES (t) = tmp;
15700       add_stmt (t);
15701       break;
15702
15703     case OMP_TARGET_UPDATE:
15704     case OMP_TARGET_ENTER_DATA:
15705     case OMP_TARGET_EXIT_DATA:
15706       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), false, true,
15707                                 args, complain, in_decl);
15708       t = copy_node (t);
15709       OMP_STANDALONE_CLAUSES (t) = tmp;
15710       add_stmt (t);
15711       break;
15712
15713     case OACC_ENTER_DATA:
15714     case OACC_EXIT_DATA:
15715     case OACC_UPDATE:
15716       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), false, false,
15717                                 args, complain, in_decl);
15718       t = copy_node (t);
15719       OMP_STANDALONE_CLAUSES (t) = tmp;
15720       add_stmt (t);
15721       break;
15722
15723     case OMP_ORDERED:
15724       tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), false, true,
15725                                 args, complain, in_decl);
15726       stmt = push_stmt_list ();
15727       RECUR (OMP_BODY (t));
15728       stmt = pop_stmt_list (stmt);
15729
15730       t = copy_node (t);
15731       OMP_BODY (t) = stmt;
15732       OMP_ORDERED_CLAUSES (t) = tmp;
15733       add_stmt (t);
15734       break;
15735
15736     case OMP_SECTION:
15737     case OMP_MASTER:
15738     case OMP_TASKGROUP:
15739       stmt = push_stmt_list ();
15740       RECUR (OMP_BODY (t));
15741       stmt = pop_stmt_list (stmt);
15742
15743       t = copy_node (t);
15744       OMP_BODY (t) = stmt;
15745       add_stmt (t);
15746       break;
15747
15748     case OMP_ATOMIC:
15749       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
15750       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
15751         {
15752           tree op1 = TREE_OPERAND (t, 1);
15753           tree rhs1 = NULL_TREE;
15754           tree lhs, rhs;
15755           if (TREE_CODE (op1) == COMPOUND_EXPR)
15756             {
15757               rhs1 = RECUR (TREE_OPERAND (op1, 0));
15758               op1 = TREE_OPERAND (op1, 1);
15759             }
15760           lhs = RECUR (TREE_OPERAND (op1, 0));
15761           rhs = RECUR (TREE_OPERAND (op1, 1));
15762           finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
15763                              NULL_TREE, NULL_TREE, rhs1,
15764                              OMP_ATOMIC_SEQ_CST (t));
15765         }
15766       else
15767         {
15768           tree op1 = TREE_OPERAND (t, 1);
15769           tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
15770           tree rhs1 = NULL_TREE;
15771           enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
15772           enum tree_code opcode = NOP_EXPR;
15773           if (code == OMP_ATOMIC_READ)
15774             {
15775               v = RECUR (TREE_OPERAND (op1, 0));
15776               lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
15777             }
15778           else if (code == OMP_ATOMIC_CAPTURE_OLD
15779                    || code == OMP_ATOMIC_CAPTURE_NEW)
15780             {
15781               tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
15782               v = RECUR (TREE_OPERAND (op1, 0));
15783               lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
15784               if (TREE_CODE (op11) == COMPOUND_EXPR)
15785                 {
15786                   rhs1 = RECUR (TREE_OPERAND (op11, 0));
15787                   op11 = TREE_OPERAND (op11, 1);
15788                 }
15789               lhs = RECUR (TREE_OPERAND (op11, 0));
15790               rhs = RECUR (TREE_OPERAND (op11, 1));
15791               opcode = TREE_CODE (op11);
15792               if (opcode == MODIFY_EXPR)
15793                 opcode = NOP_EXPR;
15794             }
15795           else
15796             {
15797               code = OMP_ATOMIC;
15798               lhs = RECUR (TREE_OPERAND (op1, 0));
15799               rhs = RECUR (TREE_OPERAND (op1, 1));
15800             }
15801           finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1,
15802                              OMP_ATOMIC_SEQ_CST (t));
15803         }
15804       break;
15805
15806     case TRANSACTION_EXPR:
15807       {
15808         int flags = 0;
15809         flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
15810         flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
15811
15812         if (TRANSACTION_EXPR_IS_STMT (t))
15813           {
15814             tree body = TRANSACTION_EXPR_BODY (t);
15815             tree noex = NULL_TREE;
15816             if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
15817               {
15818                 noex = MUST_NOT_THROW_COND (body);
15819                 if (noex == NULL_TREE)
15820                   noex = boolean_true_node;
15821                 body = TREE_OPERAND (body, 0);
15822               }
15823             stmt = begin_transaction_stmt (input_location, NULL, flags);
15824             RECUR (body);
15825             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
15826           }
15827         else
15828           {
15829             stmt = build_transaction_expr (EXPR_LOCATION (t),
15830                                            RECUR (TRANSACTION_EXPR_BODY (t)),
15831                                            flags, NULL_TREE);
15832             RETURN (stmt);
15833           }
15834       }
15835       break;
15836
15837     case MUST_NOT_THROW_EXPR:
15838       {
15839         tree op0 = RECUR (TREE_OPERAND (t, 0));
15840         tree cond = RECUR (MUST_NOT_THROW_COND (t));
15841         RETURN (build_must_not_throw_expr (op0, cond));
15842       }
15843
15844     case EXPR_PACK_EXPANSION:
15845       error ("invalid use of pack expansion expression");
15846       RETURN (error_mark_node);
15847
15848     case NONTYPE_ARGUMENT_PACK:
15849       error ("use %<...%> to expand argument pack");
15850       RETURN (error_mark_node);
15851
15852     case CILK_SPAWN_STMT:
15853       cfun->calls_cilk_spawn = 1;
15854       RETURN (build_cilk_spawn (EXPR_LOCATION (t), RECUR (CILK_SPAWN_FN (t))));
15855
15856     case CILK_SYNC_STMT:
15857       RETURN (build_cilk_sync ());
15858
15859     case COMPOUND_EXPR:
15860       tmp = RECUR (TREE_OPERAND (t, 0));
15861       if (tmp == NULL_TREE)
15862         /* If the first operand was a statement, we're done with it.  */
15863         RETURN (RECUR (TREE_OPERAND (t, 1)));
15864       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
15865                                     RECUR (TREE_OPERAND (t, 1)),
15866                                     complain));
15867
15868     case ANNOTATE_EXPR:
15869       tmp = RECUR (TREE_OPERAND (t, 0));
15870       RETURN (build2_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
15871                           TREE_TYPE (tmp), tmp, RECUR (TREE_OPERAND (t, 1))));
15872
15873     case STATEMENT_LIST_END:
15874       RETURN (t);
15875
15876     default:
15877       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
15878
15879       RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
15880                                     /*function_p=*/false,
15881                                     integral_constant_expression_p));
15882     }
15883
15884   RETURN (NULL_TREE);
15885  out:
15886   input_location = loc;
15887   return r;
15888 #undef RECUR
15889 #undef RETURN
15890 }
15891
15892 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
15893    function.  For description of the body see comment above
15894    cp_parser_omp_declare_reduction_exprs.  */
15895
15896 static void
15897 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15898 {
15899   if (t == NULL_TREE || t == error_mark_node)
15900     return;
15901
15902   gcc_assert (TREE_CODE (t) == STATEMENT_LIST);
15903
15904   tree_stmt_iterator tsi;
15905   int i;
15906   tree stmts[7];
15907   memset (stmts, 0, sizeof stmts);
15908   for (i = 0, tsi = tsi_start (t);
15909        i < 7 && !tsi_end_p (tsi);
15910        i++, tsi_next (&tsi))
15911     stmts[i] = tsi_stmt (tsi);
15912   gcc_assert (tsi_end_p (tsi));
15913
15914   if (i >= 3)
15915     {
15916       gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
15917                   && TREE_CODE (stmts[1]) == DECL_EXPR);
15918       tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
15919                              args, complain, in_decl);
15920       tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
15921                             args, complain, in_decl);
15922       DECL_CONTEXT (omp_out) = current_function_decl;
15923       DECL_CONTEXT (omp_in) = current_function_decl;
15924       keep_next_level (true);
15925       tree block = begin_omp_structured_block ();
15926       tsubst_expr (stmts[2], args, complain, in_decl, false);
15927       block = finish_omp_structured_block (block);
15928       block = maybe_cleanup_point_expr_void (block);
15929       add_decl_expr (omp_out);
15930       if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
15931         TREE_NO_WARNING (omp_out) = 1;
15932       add_decl_expr (omp_in);
15933       finish_expr_stmt (block);
15934     }
15935   if (i >= 6)
15936     {
15937       gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
15938                   && TREE_CODE (stmts[4]) == DECL_EXPR);
15939       tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
15940                               args, complain, in_decl);
15941       tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
15942                               args, complain, in_decl);
15943       DECL_CONTEXT (omp_priv) = current_function_decl;
15944       DECL_CONTEXT (omp_orig) = current_function_decl;
15945       keep_next_level (true);
15946       tree block = begin_omp_structured_block ();
15947       tsubst_expr (stmts[5], args, complain, in_decl, false);
15948       block = finish_omp_structured_block (block);
15949       block = maybe_cleanup_point_expr_void (block);
15950       cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
15951       add_decl_expr (omp_priv);
15952       add_decl_expr (omp_orig);
15953       finish_expr_stmt (block);
15954       if (i == 7)
15955         add_decl_expr (omp_orig);
15956     }
15957 }
15958
15959 /* T is a postfix-expression that is not being used in a function
15960    call.  Return the substituted version of T.  */
15961
15962 static tree
15963 tsubst_non_call_postfix_expression (tree t, tree args,
15964                                     tsubst_flags_t complain,
15965                                     tree in_decl)
15966 {
15967   if (TREE_CODE (t) == SCOPE_REF)
15968     t = tsubst_qualified_id (t, args, complain, in_decl,
15969                              /*done=*/false, /*address_p=*/false);
15970   else
15971     t = tsubst_copy_and_build (t, args, complain, in_decl,
15972                                /*function_p=*/false,
15973                                /*integral_constant_expression_p=*/false);
15974
15975   return t;
15976 }
15977
15978 /* Like tsubst but deals with expressions and performs semantic
15979    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
15980
15981 tree
15982 tsubst_copy_and_build (tree t,
15983                        tree args,
15984                        tsubst_flags_t complain,
15985                        tree in_decl,
15986                        bool function_p,
15987                        bool integral_constant_expression_p)
15988 {
15989 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
15990 #define RECUR(NODE)                                             \
15991   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
15992                          /*function_p=*/false,                  \
15993                          integral_constant_expression_p)
15994
15995   tree retval, op1;
15996   location_t loc;
15997
15998   if (t == NULL_TREE || t == error_mark_node)
15999     return t;
16000
16001   loc = input_location;
16002   if (EXPR_HAS_LOCATION (t))
16003     input_location = EXPR_LOCATION (t);
16004
16005   /* N3276 decltype magic only applies to calls at the top level or on the
16006      right side of a comma.  */
16007   tsubst_flags_t decltype_flag = (complain & tf_decltype);
16008   complain &= ~tf_decltype;
16009
16010   switch (TREE_CODE (t))
16011     {
16012     case USING_DECL:
16013       t = DECL_NAME (t);
16014       /* Fall through.  */
16015     case IDENTIFIER_NODE:
16016       {
16017         tree decl;
16018         cp_id_kind idk;
16019         bool non_integral_constant_expression_p;
16020         const char *error_msg;
16021
16022         if (IDENTIFIER_TYPENAME_P (t))
16023           {
16024             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16025             t = mangle_conv_op_name_for_type (new_type);
16026           }
16027
16028         /* Look up the name.  */
16029         decl = lookup_name (t);
16030
16031         /* By convention, expressions use ERROR_MARK_NODE to indicate
16032            failure, not NULL_TREE.  */
16033         if (decl == NULL_TREE)
16034           decl = error_mark_node;
16035
16036         decl = finish_id_expression (t, decl, NULL_TREE,
16037                                      &idk,
16038                                      integral_constant_expression_p,
16039           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
16040                                      &non_integral_constant_expression_p,
16041                                      /*template_p=*/false,
16042                                      /*done=*/true,
16043                                      /*address_p=*/false,
16044                                      /*template_arg_p=*/false,
16045                                      &error_msg,
16046                                      input_location);
16047         if (error_msg)
16048           error (error_msg);
16049         if (!function_p && identifier_p (decl))
16050           {
16051             if (complain & tf_error)
16052               unqualified_name_lookup_error (decl);
16053             decl = error_mark_node;
16054           }
16055         RETURN (decl);
16056       }
16057
16058     case TEMPLATE_ID_EXPR:
16059       {
16060         tree object;
16061         tree templ = RECUR (TREE_OPERAND (t, 0));
16062         tree targs = TREE_OPERAND (t, 1);
16063
16064         if (targs)
16065           targs = tsubst_template_args (targs, args, complain, in_decl);
16066         if (targs == error_mark_node)
16067           return error_mark_node;
16068
16069         if (variable_template_p (templ))
16070           RETURN (lookup_and_finish_template_variable (templ, targs, complain));
16071
16072         if (TREE_CODE (templ) == COMPONENT_REF)
16073           {
16074             object = TREE_OPERAND (templ, 0);
16075             templ = TREE_OPERAND (templ, 1);
16076           }
16077         else
16078           object = NULL_TREE;
16079         templ = lookup_template_function (templ, targs);
16080
16081         if (object)
16082           RETURN (build3 (COMPONENT_REF, TREE_TYPE (templ),
16083                          object, templ, NULL_TREE));
16084         else
16085           RETURN (baselink_for_fns (templ));
16086       }
16087
16088     case INDIRECT_REF:
16089       {
16090         tree r = RECUR (TREE_OPERAND (t, 0));
16091
16092         if (REFERENCE_REF_P (t))
16093           {
16094             /* A type conversion to reference type will be enclosed in
16095                such an indirect ref, but the substitution of the cast
16096                will have also added such an indirect ref.  */
16097             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
16098               r = convert_from_reference (r);
16099           }
16100         else
16101           r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
16102                                     complain|decltype_flag);
16103
16104         if (TREE_CODE (r) == INDIRECT_REF)
16105           REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
16106
16107         RETURN (r);
16108       }
16109
16110     case NOP_EXPR:
16111       {
16112         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16113         tree op0 = RECUR (TREE_OPERAND (t, 0));
16114         RETURN (build_nop (type, op0));
16115       }
16116
16117     case IMPLICIT_CONV_EXPR:
16118       {
16119         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16120         tree expr = RECUR (TREE_OPERAND (t, 0));
16121         int flags = LOOKUP_IMPLICIT;
16122         if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
16123           flags = LOOKUP_NORMAL;
16124         RETURN (perform_implicit_conversion_flags (type, expr, complain,
16125                                                   flags));
16126       }
16127
16128     case CONVERT_EXPR:
16129       {
16130         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16131         tree op0 = RECUR (TREE_OPERAND (t, 0));
16132         RETURN (build1 (CONVERT_EXPR, type, op0));
16133       }
16134
16135     case CAST_EXPR:
16136     case REINTERPRET_CAST_EXPR:
16137     case CONST_CAST_EXPR:
16138     case DYNAMIC_CAST_EXPR:
16139     case STATIC_CAST_EXPR:
16140       {
16141         tree type;
16142         tree op, r = NULL_TREE;
16143
16144         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16145         if (integral_constant_expression_p
16146             && !cast_valid_in_integral_constant_expression_p (type))
16147           {
16148             if (complain & tf_error)
16149               error ("a cast to a type other than an integral or "
16150                      "enumeration type cannot appear in a constant-expression");
16151             RETURN (error_mark_node);
16152           }
16153
16154         op = RECUR (TREE_OPERAND (t, 0));
16155
16156         warning_sentinel s(warn_useless_cast);
16157         switch (TREE_CODE (t))
16158           {
16159           case CAST_EXPR:
16160             r = build_functional_cast (type, op, complain);
16161             break;
16162           case REINTERPRET_CAST_EXPR:
16163             r = build_reinterpret_cast (type, op, complain);
16164             break;
16165           case CONST_CAST_EXPR:
16166             r = build_const_cast (type, op, complain);
16167             break;
16168           case DYNAMIC_CAST_EXPR:
16169             r = build_dynamic_cast (type, op, complain);
16170             break;
16171           case STATIC_CAST_EXPR:
16172             r = build_static_cast (type, op, complain);
16173             break;
16174           default:
16175             gcc_unreachable ();
16176           }
16177
16178         RETURN (r);
16179       }
16180
16181     case POSTDECREMENT_EXPR:
16182     case POSTINCREMENT_EXPR:
16183       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
16184                                                 args, complain, in_decl);
16185       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
16186                                 complain|decltype_flag));
16187
16188     case PREDECREMENT_EXPR:
16189     case PREINCREMENT_EXPR:
16190     case NEGATE_EXPR:
16191     case BIT_NOT_EXPR:
16192     case ABS_EXPR:
16193     case TRUTH_NOT_EXPR:
16194     case UNARY_PLUS_EXPR:  /* Unary + */
16195     case REALPART_EXPR:
16196     case IMAGPART_EXPR:
16197       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
16198                                 RECUR (TREE_OPERAND (t, 0)),
16199                                 complain|decltype_flag));
16200
16201     case FIX_TRUNC_EXPR:
16202       RETURN (cp_build_unary_op (FIX_TRUNC_EXPR, RECUR (TREE_OPERAND (t, 0)),
16203                                  0, complain));
16204
16205     case ADDR_EXPR:
16206       op1 = TREE_OPERAND (t, 0);
16207       if (TREE_CODE (op1) == LABEL_DECL)
16208         RETURN (finish_label_address_expr (DECL_NAME (op1),
16209                                           EXPR_LOCATION (op1)));
16210       if (TREE_CODE (op1) == SCOPE_REF)
16211         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
16212                                    /*done=*/true, /*address_p=*/true);
16213       else
16214         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
16215                                                   in_decl);
16216       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
16217                                 complain|decltype_flag));
16218
16219     case PLUS_EXPR:
16220     case MINUS_EXPR:
16221     case MULT_EXPR:
16222     case TRUNC_DIV_EXPR:
16223     case CEIL_DIV_EXPR:
16224     case FLOOR_DIV_EXPR:
16225     case ROUND_DIV_EXPR:
16226     case EXACT_DIV_EXPR:
16227     case BIT_AND_EXPR:
16228     case BIT_IOR_EXPR:
16229     case BIT_XOR_EXPR:
16230     case TRUNC_MOD_EXPR:
16231     case FLOOR_MOD_EXPR:
16232     case TRUTH_ANDIF_EXPR:
16233     case TRUTH_ORIF_EXPR:
16234     case TRUTH_AND_EXPR:
16235     case TRUTH_OR_EXPR:
16236     case RSHIFT_EXPR:
16237     case LSHIFT_EXPR:
16238     case RROTATE_EXPR:
16239     case LROTATE_EXPR:
16240     case EQ_EXPR:
16241     case NE_EXPR:
16242     case MAX_EXPR:
16243     case MIN_EXPR:
16244     case LE_EXPR:
16245     case GE_EXPR:
16246     case LT_EXPR:
16247     case GT_EXPR:
16248     case MEMBER_REF:
16249     case DOTSTAR_EXPR:
16250       {
16251         warning_sentinel s1(warn_type_limits);
16252         warning_sentinel s2(warn_div_by_zero);
16253         warning_sentinel s3(warn_logical_op);
16254         warning_sentinel s4(warn_tautological_compare);
16255         tree op0 = RECUR (TREE_OPERAND (t, 0));
16256         tree op1 = RECUR (TREE_OPERAND (t, 1));
16257         tree r = build_x_binary_op
16258           (input_location, TREE_CODE (t),
16259            op0,
16260            (TREE_NO_WARNING (TREE_OPERAND (t, 0))
16261             ? ERROR_MARK
16262             : TREE_CODE (TREE_OPERAND (t, 0))),
16263            op1,
16264            (TREE_NO_WARNING (TREE_OPERAND (t, 1))
16265             ? ERROR_MARK
16266             : TREE_CODE (TREE_OPERAND (t, 1))),
16267            /*overload=*/NULL,
16268            complain|decltype_flag);
16269         if (EXPR_P (r) && TREE_NO_WARNING (t))
16270           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
16271
16272         RETURN (r);
16273       }
16274
16275     case POINTER_PLUS_EXPR:
16276       {
16277         tree op0 = RECUR (TREE_OPERAND (t, 0));
16278         tree op1 = RECUR (TREE_OPERAND (t, 1));
16279         return fold_build_pointer_plus (op0, op1);
16280       }
16281
16282     case SCOPE_REF:
16283       RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
16284                                   /*address_p=*/false));
16285     case ARRAY_REF:
16286       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
16287                                                 args, complain, in_decl);
16288       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
16289                                  RECUR (TREE_OPERAND (t, 1)),
16290                                  complain|decltype_flag));
16291
16292     case ARRAY_NOTATION_REF:
16293       {
16294         tree start_index, length, stride;
16295         op1 = tsubst_non_call_postfix_expression (ARRAY_NOTATION_ARRAY (t),
16296                                                   args, complain, in_decl);
16297         start_index = RECUR (ARRAY_NOTATION_START (t));
16298         length = RECUR (ARRAY_NOTATION_LENGTH (t));
16299         stride = RECUR (ARRAY_NOTATION_STRIDE (t));
16300         RETURN (build_array_notation_ref (EXPR_LOCATION (t), op1, start_index,
16301                                           length, stride, TREE_TYPE (op1)));
16302       }
16303     case SIZEOF_EXPR:
16304       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
16305           || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
16306         RETURN (tsubst_copy (t, args, complain, in_decl));
16307       /* Fall through */
16308       
16309     case ALIGNOF_EXPR:
16310       {
16311         tree r;
16312
16313         op1 = TREE_OPERAND (t, 0);
16314         if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
16315           op1 = TREE_TYPE (op1);
16316         if (!args)
16317           {
16318             /* When there are no ARGS, we are trying to evaluate a
16319                non-dependent expression from the parser.  Trying to do
16320                the substitutions may not work.  */
16321             if (!TYPE_P (op1))
16322               op1 = TREE_TYPE (op1);
16323           }
16324         else
16325           {
16326             ++cp_unevaluated_operand;
16327             ++c_inhibit_evaluation_warnings;
16328             if (TYPE_P (op1))
16329               op1 = tsubst (op1, args, complain, in_decl);
16330             else
16331               op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
16332                                            /*function_p=*/false,
16333                                            /*integral_constant_expression_p=*/
16334                                            false);
16335             --cp_unevaluated_operand;
16336             --c_inhibit_evaluation_warnings;
16337           }
16338         if (TYPE_P (op1))
16339           r = cxx_sizeof_or_alignof_type (op1, TREE_CODE (t),
16340                                           complain & tf_error);
16341         else
16342           r = cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t),
16343                                           complain & tf_error);
16344         if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
16345           {
16346             if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
16347               {
16348                 if (!processing_template_decl && TYPE_P (op1))
16349                   {
16350                     r = build_min (SIZEOF_EXPR, size_type_node,
16351                                    build1 (NOP_EXPR, op1, error_mark_node));
16352                     SIZEOF_EXPR_TYPE_P (r) = 1;
16353                   }
16354                 else
16355                   r = build_min (SIZEOF_EXPR, size_type_node, op1);
16356                 TREE_SIDE_EFFECTS (r) = 0;
16357                 TREE_READONLY (r) = 1;
16358               }
16359             SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
16360           }
16361         RETURN (r);
16362       }
16363
16364     case AT_ENCODE_EXPR:
16365       {
16366         op1 = TREE_OPERAND (t, 0);
16367         ++cp_unevaluated_operand;
16368         ++c_inhibit_evaluation_warnings;
16369         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
16370                                      /*function_p=*/false,
16371                                      /*integral_constant_expression_p=*/false);
16372         --cp_unevaluated_operand;
16373         --c_inhibit_evaluation_warnings;
16374         RETURN (objc_build_encode_expr (op1));
16375       }
16376
16377     case NOEXCEPT_EXPR:
16378       op1 = TREE_OPERAND (t, 0);
16379       ++cp_unevaluated_operand;
16380       ++c_inhibit_evaluation_warnings;
16381       ++cp_noexcept_operand;
16382       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
16383                                    /*function_p=*/false,
16384                                    /*integral_constant_expression_p=*/false);
16385       --cp_unevaluated_operand;
16386       --c_inhibit_evaluation_warnings;
16387       --cp_noexcept_operand;
16388       RETURN (finish_noexcept_expr (op1, complain));
16389
16390     case MODOP_EXPR:
16391       {
16392         warning_sentinel s(warn_div_by_zero);
16393         tree lhs = RECUR (TREE_OPERAND (t, 0));
16394         tree rhs = RECUR (TREE_OPERAND (t, 2));
16395         tree r = build_x_modify_expr
16396           (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
16397            complain|decltype_flag);
16398         /* TREE_NO_WARNING must be set if either the expression was
16399            parenthesized or it uses an operator such as >>= rather
16400            than plain assignment.  In the former case, it was already
16401            set and must be copied.  In the latter case,
16402            build_x_modify_expr sets it and it must not be reset
16403            here.  */
16404         if (TREE_NO_WARNING (t))
16405           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
16406
16407         RETURN (r);
16408       }
16409
16410     case ARROW_EXPR:
16411       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
16412                                                 args, complain, in_decl);
16413       /* Remember that there was a reference to this entity.  */
16414       if (DECL_P (op1)
16415           && !mark_used (op1, complain) && !(complain & tf_error))
16416         RETURN (error_mark_node);
16417       RETURN (build_x_arrow (input_location, op1, complain));
16418
16419     case NEW_EXPR:
16420       {
16421         tree placement = RECUR (TREE_OPERAND (t, 0));
16422         tree init = RECUR (TREE_OPERAND (t, 3));
16423         vec<tree, va_gc> *placement_vec;
16424         vec<tree, va_gc> *init_vec;
16425         tree ret;
16426
16427         if (placement == NULL_TREE)
16428           placement_vec = NULL;
16429         else
16430           {
16431             placement_vec = make_tree_vector ();
16432             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
16433               vec_safe_push (placement_vec, TREE_VALUE (placement));
16434           }
16435
16436         /* If there was an initializer in the original tree, but it
16437            instantiated to an empty list, then we should pass a
16438            non-NULL empty vector to tell build_new that it was an
16439            empty initializer() rather than no initializer.  This can
16440            only happen when the initializer is a pack expansion whose
16441            parameter packs are of length zero.  */
16442         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
16443           init_vec = NULL;
16444         else
16445           {
16446             init_vec = make_tree_vector ();
16447             if (init == void_node)
16448               gcc_assert (init_vec != NULL);
16449             else
16450               {
16451                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
16452                   vec_safe_push (init_vec, TREE_VALUE (init));
16453               }
16454           }
16455
16456         tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
16457         tree op2 = RECUR (TREE_OPERAND (t, 2));
16458         ret = build_new (&placement_vec, op1, op2, &init_vec,
16459                          NEW_EXPR_USE_GLOBAL (t),
16460                          complain);
16461
16462         if (placement_vec != NULL)
16463           release_tree_vector (placement_vec);
16464         if (init_vec != NULL)
16465           release_tree_vector (init_vec);
16466
16467         RETURN (ret);
16468       }
16469
16470     case DELETE_EXPR:
16471       {
16472         tree op0 = RECUR (TREE_OPERAND (t, 0));
16473         tree op1 = RECUR (TREE_OPERAND (t, 1));
16474         RETURN (delete_sanity (op0, op1,
16475                                DELETE_EXPR_USE_VEC (t),
16476                                DELETE_EXPR_USE_GLOBAL (t),
16477                                complain));
16478       }
16479
16480     case COMPOUND_EXPR:
16481       {
16482         tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
16483                                           complain & ~tf_decltype, in_decl,
16484                                           /*function_p=*/false,
16485                                           integral_constant_expression_p);
16486         RETURN (build_x_compound_expr (EXPR_LOCATION (t),
16487                                        op0,
16488                                        RECUR (TREE_OPERAND (t, 1)),
16489                                        complain|decltype_flag));
16490       }
16491
16492     case CALL_EXPR:
16493       {
16494         tree function;
16495         vec<tree, va_gc> *call_args;
16496         unsigned int nargs, i;
16497         bool qualified_p;
16498         bool koenig_p;
16499         tree ret;
16500
16501         function = CALL_EXPR_FN (t);
16502         /* When we parsed the expression,  we determined whether or
16503            not Koenig lookup should be performed.  */
16504         koenig_p = KOENIG_LOOKUP_P (t);
16505         if (TREE_CODE (function) == SCOPE_REF)
16506           {
16507             qualified_p = true;
16508             function = tsubst_qualified_id (function, args, complain, in_decl,
16509                                             /*done=*/false,
16510                                             /*address_p=*/false);
16511           }
16512         else if (koenig_p && identifier_p (function))
16513           {
16514             /* Do nothing; calling tsubst_copy_and_build on an identifier
16515                would incorrectly perform unqualified lookup again.
16516
16517                Note that we can also have an IDENTIFIER_NODE if the earlier
16518                unqualified lookup found a member function; in that case
16519                koenig_p will be false and we do want to do the lookup
16520                again to find the instantiated member function.
16521
16522                FIXME but doing that causes c++/15272, so we need to stop
16523                using IDENTIFIER_NODE in that situation.  */
16524             qualified_p = false;
16525           }
16526         else
16527           {
16528             if (TREE_CODE (function) == COMPONENT_REF)
16529               {
16530                 tree op = TREE_OPERAND (function, 1);
16531
16532                 qualified_p = (TREE_CODE (op) == SCOPE_REF
16533                                || (BASELINK_P (op)
16534                                    && BASELINK_QUALIFIED_P (op)));
16535               }
16536             else
16537               qualified_p = false;
16538
16539             if (TREE_CODE (function) == ADDR_EXPR
16540                 && TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
16541               /* Avoid error about taking the address of a constructor.  */
16542               function = TREE_OPERAND (function, 0);
16543
16544             function = tsubst_copy_and_build (function, args, complain,
16545                                               in_decl,
16546                                               !qualified_p,
16547                                               integral_constant_expression_p);
16548
16549             if (BASELINK_P (function))
16550               qualified_p = true;
16551           }
16552
16553         nargs = call_expr_nargs (t);
16554         call_args = make_tree_vector ();
16555         for (i = 0; i < nargs; ++i)
16556           {
16557             tree arg = CALL_EXPR_ARG (t, i);
16558
16559             if (!PACK_EXPANSION_P (arg))
16560               vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
16561             else
16562               {
16563                 /* Expand the pack expansion and push each entry onto
16564                    CALL_ARGS.  */
16565                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
16566                 if (TREE_CODE (arg) == TREE_VEC)
16567                   {
16568                     unsigned int len, j;
16569
16570                     len = TREE_VEC_LENGTH (arg);
16571                     for (j = 0; j < len; ++j)
16572                       {
16573                         tree value = TREE_VEC_ELT (arg, j);
16574                         if (value != NULL_TREE)
16575                           value = convert_from_reference (value);
16576                         vec_safe_push (call_args, value);
16577                       }
16578                   }
16579                 else
16580                   {
16581                     /* A partial substitution.  Add one entry.  */
16582                     vec_safe_push (call_args, arg);
16583                   }
16584               }
16585           }
16586
16587         /* We do not perform argument-dependent lookup if normal
16588            lookup finds a non-function, in accordance with the
16589            expected resolution of DR 218.  */
16590         if (koenig_p
16591             && ((is_overloaded_fn (function)
16592                  /* If lookup found a member function, the Koenig lookup is
16593                     not appropriate, even if an unqualified-name was used
16594                     to denote the function.  */
16595                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
16596                 || identifier_p (function))
16597             /* Only do this when substitution turns a dependent call
16598                into a non-dependent call.  */
16599             && type_dependent_expression_p_push (t)
16600             && !any_type_dependent_arguments_p (call_args))
16601           function = perform_koenig_lookup (function, call_args, tf_none);
16602
16603         if (identifier_p (function)
16604             && !any_type_dependent_arguments_p (call_args))
16605           {
16606             if (koenig_p && (complain & tf_warning_or_error))
16607               {
16608                 /* For backwards compatibility and good diagnostics, try
16609                    the unqualified lookup again if we aren't in SFINAE
16610                    context.  */
16611                 tree unq = (tsubst_copy_and_build
16612                             (function, args, complain, in_decl, true,
16613                              integral_constant_expression_p));
16614                 if (unq == error_mark_node)
16615                   RETURN (error_mark_node);
16616
16617                 if (unq != function)
16618                   {
16619                     tree fn = unq;
16620                     if (INDIRECT_REF_P (fn))
16621                       fn = TREE_OPERAND (fn, 0);
16622                     if (TREE_CODE (fn) == COMPONENT_REF)
16623                       fn = TREE_OPERAND (fn, 1);
16624                     if (is_overloaded_fn (fn))
16625                       fn = get_first_fn (fn);
16626                     if (permerror (EXPR_LOC_OR_LOC (t, input_location),
16627                                    "%qD was not declared in this scope, "
16628                                    "and no declarations were found by "
16629                                    "argument-dependent lookup at the point "
16630                                    "of instantiation", function))
16631                       {
16632                         if (!DECL_P (fn))
16633                           /* Can't say anything more.  */;
16634                         else if (DECL_CLASS_SCOPE_P (fn))
16635                           {
16636                             location_t loc = EXPR_LOC_OR_LOC (t,
16637                                                               input_location);
16638                             inform (loc,
16639                                     "declarations in dependent base %qT are "
16640                                     "not found by unqualified lookup",
16641                                     DECL_CLASS_CONTEXT (fn));
16642                             if (current_class_ptr)
16643                               inform (loc,
16644                                       "use %<this->%D%> instead", function);
16645                             else
16646                               inform (loc,
16647                                       "use %<%T::%D%> instead",
16648                                       current_class_name, function);
16649                           }
16650                         else
16651                           inform (DECL_SOURCE_LOCATION (fn),
16652                                   "%qD declared here, later in the "
16653                                   "translation unit", fn);
16654                       }
16655                     function = unq;
16656                   }
16657               }
16658             if (identifier_p (function))
16659               {
16660                 if (complain & tf_error)
16661                   unqualified_name_lookup_error (function);
16662                 release_tree_vector (call_args);
16663                 RETURN (error_mark_node);
16664               }
16665           }
16666
16667         /* Remember that there was a reference to this entity.  */
16668         if (DECL_P (function)
16669             && !mark_used (function, complain) && !(complain & tf_error))
16670           RETURN (error_mark_node);
16671
16672         /* Put back tf_decltype for the actual call.  */
16673         complain |= decltype_flag;
16674
16675         if (TREE_CODE (function) == OFFSET_REF)
16676           ret = build_offset_ref_call_from_tree (function, &call_args,
16677                                                  complain);
16678         else if (TREE_CODE (function) == COMPONENT_REF)
16679           {
16680             tree instance = TREE_OPERAND (function, 0);
16681             tree fn = TREE_OPERAND (function, 1);
16682
16683             if (processing_template_decl
16684                 && (type_dependent_expression_p (instance)
16685                     || (!BASELINK_P (fn)
16686                         && TREE_CODE (fn) != FIELD_DECL)
16687                     || type_dependent_expression_p (fn)
16688                     || any_type_dependent_arguments_p (call_args)))
16689               ret = build_nt_call_vec (function, call_args);
16690             else if (!BASELINK_P (fn))
16691               ret = finish_call_expr (function, &call_args,
16692                                        /*disallow_virtual=*/false,
16693                                        /*koenig_p=*/false,
16694                                        complain);
16695             else
16696               ret = (build_new_method_call
16697                       (instance, fn,
16698                        &call_args, NULL_TREE,
16699                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
16700                        /*fn_p=*/NULL,
16701                        complain));
16702           }
16703         else
16704           ret = finish_call_expr (function, &call_args,
16705                                   /*disallow_virtual=*/qualified_p,
16706                                   koenig_p,
16707                                   complain);
16708
16709         release_tree_vector (call_args);
16710
16711         RETURN (ret);
16712       }
16713
16714     case COND_EXPR:
16715       {
16716         tree cond = RECUR (TREE_OPERAND (t, 0));
16717         tree folded_cond = fold_non_dependent_expr (cond);
16718         tree exp1, exp2;
16719
16720         if (TREE_CODE (folded_cond) == INTEGER_CST)
16721           {
16722             if (integer_zerop (folded_cond))
16723               {
16724                 ++c_inhibit_evaluation_warnings;
16725                 exp1 = RECUR (TREE_OPERAND (t, 1));
16726                 --c_inhibit_evaluation_warnings;
16727                 exp2 = RECUR (TREE_OPERAND (t, 2));
16728               }
16729             else
16730               {
16731                 exp1 = RECUR (TREE_OPERAND (t, 1));
16732                 ++c_inhibit_evaluation_warnings;
16733                 exp2 = RECUR (TREE_OPERAND (t, 2));
16734                 --c_inhibit_evaluation_warnings;
16735               }
16736             cond = folded_cond;
16737           }
16738         else
16739           {
16740             exp1 = RECUR (TREE_OPERAND (t, 1));
16741             exp2 = RECUR (TREE_OPERAND (t, 2));
16742           }
16743
16744         RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
16745                                          cond, exp1, exp2, complain));
16746       }
16747
16748     case PSEUDO_DTOR_EXPR:
16749       {
16750         tree op0 = RECUR (TREE_OPERAND (t, 0));
16751         tree op1 = RECUR (TREE_OPERAND (t, 1));
16752         tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
16753         RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
16754                                                input_location));
16755       }
16756
16757     case TREE_LIST:
16758       {
16759         tree purpose, value, chain;
16760
16761         if (t == void_list_node)
16762           RETURN (t);
16763
16764         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
16765             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
16766           {
16767             /* We have pack expansions, so expand those and
16768                create a new list out of it.  */
16769             tree purposevec = NULL_TREE;
16770             tree valuevec = NULL_TREE;
16771             tree chain;
16772             int i, len = -1;
16773
16774             /* Expand the argument expressions.  */
16775             if (TREE_PURPOSE (t))
16776               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
16777                                                  complain, in_decl);
16778             if (TREE_VALUE (t))
16779               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
16780                                                complain, in_decl);
16781
16782             /* Build the rest of the list.  */
16783             chain = TREE_CHAIN (t);
16784             if (chain && chain != void_type_node)
16785               chain = RECUR (chain);
16786
16787             /* Determine the number of arguments.  */
16788             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
16789               {
16790                 len = TREE_VEC_LENGTH (purposevec);
16791                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
16792               }
16793             else if (TREE_CODE (valuevec) == TREE_VEC)
16794               len = TREE_VEC_LENGTH (valuevec);
16795             else
16796               {
16797                 /* Since we only performed a partial substitution into
16798                    the argument pack, we only RETURN (a single list
16799                    node.  */
16800                 if (purposevec == TREE_PURPOSE (t)
16801                     && valuevec == TREE_VALUE (t)
16802                     && chain == TREE_CHAIN (t))
16803                   RETURN (t);
16804
16805                 RETURN (tree_cons (purposevec, valuevec, chain));
16806               }
16807             
16808             /* Convert the argument vectors into a TREE_LIST */
16809             i = len;
16810             while (i > 0)
16811               {
16812                 /* Grab the Ith values.  */
16813                 i--;
16814                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
16815                                      : NULL_TREE;
16816                 value 
16817                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
16818                              : NULL_TREE;
16819
16820                 /* Build the list (backwards).  */
16821                 chain = tree_cons (purpose, value, chain);
16822               }
16823
16824             RETURN (chain);
16825           }
16826
16827         purpose = TREE_PURPOSE (t);
16828         if (purpose)
16829           purpose = RECUR (purpose);
16830         value = TREE_VALUE (t);
16831         if (value)
16832           value = RECUR (value);
16833         chain = TREE_CHAIN (t);
16834         if (chain && chain != void_type_node)
16835           chain = RECUR (chain);
16836         if (purpose == TREE_PURPOSE (t)
16837             && value == TREE_VALUE (t)
16838             && chain == TREE_CHAIN (t))
16839           RETURN (t);
16840         RETURN (tree_cons (purpose, value, chain));
16841       }
16842
16843     case COMPONENT_REF:
16844       {
16845         tree object;
16846         tree object_type;
16847         tree member;
16848         tree r;
16849
16850         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
16851                                                      args, complain, in_decl);
16852         /* Remember that there was a reference to this entity.  */
16853         if (DECL_P (object)
16854             && !mark_used (object, complain) && !(complain & tf_error))
16855           RETURN (error_mark_node);
16856         object_type = TREE_TYPE (object);
16857
16858         member = TREE_OPERAND (t, 1);
16859         if (BASELINK_P (member))
16860           member = tsubst_baselink (member,
16861                                     non_reference (TREE_TYPE (object)),
16862                                     args, complain, in_decl);
16863         else
16864           member = tsubst_copy (member, args, complain, in_decl);
16865         if (member == error_mark_node)
16866           RETURN (error_mark_node);
16867
16868         if (type_dependent_expression_p (object))
16869           /* We can't do much here.  */;
16870         else if (!CLASS_TYPE_P (object_type))
16871           {
16872             if (scalarish_type_p (object_type))
16873               {
16874                 tree s = NULL_TREE;
16875                 tree dtor = member;
16876
16877                 if (TREE_CODE (dtor) == SCOPE_REF)
16878                   {
16879                     s = TREE_OPERAND (dtor, 0);
16880                     dtor = TREE_OPERAND (dtor, 1);
16881                   }
16882                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
16883                   {
16884                     dtor = TREE_OPERAND (dtor, 0);
16885                     if (TYPE_P (dtor))
16886                       RETURN (finish_pseudo_destructor_expr
16887                               (object, s, dtor, input_location));
16888                   }
16889               }
16890           }
16891         else if (TREE_CODE (member) == SCOPE_REF
16892                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
16893           {
16894             /* Lookup the template functions now that we know what the
16895                scope is.  */
16896             tree scope = TREE_OPERAND (member, 0);
16897             tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
16898             tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
16899             member = lookup_qualified_name (scope, tmpl,
16900                                             /*is_type_p=*/false,
16901                                             /*complain=*/false);
16902             if (BASELINK_P (member))
16903               {
16904                 BASELINK_FUNCTIONS (member)
16905                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
16906                               args);
16907                 member = (adjust_result_of_qualified_name_lookup
16908                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
16909                            object_type));
16910               }
16911             else
16912               {
16913                 qualified_name_lookup_error (scope, tmpl, member,
16914                                              input_location);
16915                 RETURN (error_mark_node);
16916               }
16917           }
16918         else if (TREE_CODE (member) == SCOPE_REF
16919                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
16920                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
16921           {
16922             if (complain & tf_error)
16923               {
16924                 if (TYPE_P (TREE_OPERAND (member, 0)))
16925                   error ("%qT is not a class or namespace",
16926                          TREE_OPERAND (member, 0));
16927                 else
16928                   error ("%qD is not a class or namespace",
16929                          TREE_OPERAND (member, 0));
16930               }
16931             RETURN (error_mark_node);
16932           }
16933         else if (TREE_CODE (member) == FIELD_DECL)
16934           {
16935             r = finish_non_static_data_member (member, object, NULL_TREE);
16936             if (TREE_CODE (r) == COMPONENT_REF)
16937               REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
16938             RETURN (r);
16939           }
16940
16941         r = finish_class_member_access_expr (object, member,
16942                                              /*template_p=*/false,
16943                                              complain);
16944         if (TREE_CODE (r) == COMPONENT_REF)
16945           REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
16946         RETURN (r);
16947       }
16948
16949     case THROW_EXPR:
16950       RETURN (build_throw
16951         (RECUR (TREE_OPERAND (t, 0))));
16952
16953     case CONSTRUCTOR:
16954       {
16955         vec<constructor_elt, va_gc> *n;
16956         constructor_elt *ce;
16957         unsigned HOST_WIDE_INT idx;
16958         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16959         bool process_index_p;
16960         int newlen;
16961         bool need_copy_p = false;
16962         tree r;
16963
16964         if (type == error_mark_node)
16965           RETURN (error_mark_node);
16966
16967         /* digest_init will do the wrong thing if we let it.  */
16968         if (type && TYPE_PTRMEMFUNC_P (type))
16969           RETURN (t);
16970
16971         /* We do not want to process the index of aggregate
16972            initializers as they are identifier nodes which will be
16973            looked up by digest_init.  */
16974         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
16975
16976         n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
16977         newlen = vec_safe_length (n);
16978         FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
16979           {
16980             if (ce->index && process_index_p
16981                 /* An identifier index is looked up in the type
16982                    being initialized, not the current scope.  */
16983                 && TREE_CODE (ce->index) != IDENTIFIER_NODE)
16984               ce->index = RECUR (ce->index);
16985
16986             if (PACK_EXPANSION_P (ce->value))
16987               {
16988                 /* Substitute into the pack expansion.  */
16989                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
16990                                                   in_decl);
16991
16992                 if (ce->value == error_mark_node
16993                     || PACK_EXPANSION_P (ce->value))
16994                   ;
16995                 else if (TREE_VEC_LENGTH (ce->value) == 1)
16996                   /* Just move the argument into place.  */
16997                   ce->value = TREE_VEC_ELT (ce->value, 0);
16998                 else
16999                   {
17000                     /* Update the length of the final CONSTRUCTOR
17001                        arguments vector, and note that we will need to
17002                        copy.*/
17003                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
17004                     need_copy_p = true;
17005                   }
17006               }
17007             else
17008               ce->value = RECUR (ce->value);
17009           }
17010
17011         if (need_copy_p)
17012           {
17013             vec<constructor_elt, va_gc> *old_n = n;
17014
17015             vec_alloc (n, newlen);
17016             FOR_EACH_VEC_ELT (*old_n, idx, ce)
17017               {
17018                 if (TREE_CODE (ce->value) == TREE_VEC)
17019                   {
17020                     int i, len = TREE_VEC_LENGTH (ce->value);
17021                     for (i = 0; i < len; ++i)
17022                       CONSTRUCTOR_APPEND_ELT (n, 0,
17023                                               TREE_VEC_ELT (ce->value, i));
17024                   }
17025                 else
17026                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
17027               }
17028           }
17029
17030         r = build_constructor (init_list_type_node, n);
17031         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
17032
17033         if (TREE_HAS_CONSTRUCTOR (t))
17034           RETURN (finish_compound_literal (type, r, complain));
17035
17036         TREE_TYPE (r) = type;
17037         RETURN (r);
17038       }
17039
17040     case TYPEID_EXPR:
17041       {
17042         tree operand_0 = TREE_OPERAND (t, 0);
17043         if (TYPE_P (operand_0))
17044           {
17045             operand_0 = tsubst (operand_0, args, complain, in_decl);
17046             RETURN (get_typeid (operand_0, complain));
17047           }
17048         else
17049           {
17050             operand_0 = RECUR (operand_0);
17051             RETURN (build_typeid (operand_0, complain));
17052           }
17053       }
17054
17055     case VAR_DECL:
17056       if (!args)
17057         RETURN (t);
17058       else if (DECL_PACK_P (t))
17059         {
17060           /* We don't build decls for an instantiation of a
17061              variadic capture proxy, we instantiate the elements
17062              when needed.  */
17063           gcc_assert (DECL_HAS_VALUE_EXPR_P (t));
17064           return RECUR (DECL_VALUE_EXPR (t));
17065         }
17066       /* Fall through */
17067
17068     case PARM_DECL:
17069       {
17070         tree r = tsubst_copy (t, args, complain, in_decl);
17071         /* ??? We're doing a subset of finish_id_expression here.  */
17072         if (VAR_P (r)
17073             && !processing_template_decl
17074             && !cp_unevaluated_operand
17075             && (TREE_STATIC (r) || DECL_EXTERNAL (r))
17076             && CP_DECL_THREAD_LOCAL_P (r))
17077           {
17078             if (tree wrap = get_tls_wrapper_fn (r))
17079               /* Replace an evaluated use of the thread_local variable with
17080                  a call to its wrapper.  */
17081               r = build_cxx_call (wrap, 0, NULL, tf_warning_or_error);
17082           }
17083         else if (outer_automatic_var_p (r))
17084           {
17085             r = process_outer_var_ref (r, complain);
17086             if (is_capture_proxy (r))
17087               register_local_specialization (r, t);
17088           }
17089
17090         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
17091           /* If the original type was a reference, we'll be wrapped in
17092              the appropriate INDIRECT_REF.  */
17093           r = convert_from_reference (r);
17094         RETURN (r);
17095       }
17096
17097     case VA_ARG_EXPR:
17098       {
17099         tree op0 = RECUR (TREE_OPERAND (t, 0));
17100         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17101         RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
17102       }
17103
17104     case OFFSETOF_EXPR:
17105       RETURN (finish_offsetof (RECUR (TREE_OPERAND (t, 0)),
17106                                EXPR_LOCATION (t)));
17107
17108     case TRAIT_EXPR:
17109       {
17110         tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
17111                              complain, in_decl);
17112
17113         tree type2 = TRAIT_EXPR_TYPE2 (t);
17114         if (type2 && TREE_CODE (type2) == TREE_LIST)
17115           type2 = RECUR (type2);
17116         else if (type2)
17117           type2 = tsubst (type2, args, complain, in_decl);
17118         
17119         RETURN (finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2));
17120       }
17121
17122     case STMT_EXPR:
17123       {
17124         tree old_stmt_expr = cur_stmt_expr;
17125         tree stmt_expr = begin_stmt_expr ();
17126
17127         cur_stmt_expr = stmt_expr;
17128         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
17129                      integral_constant_expression_p);
17130         stmt_expr = finish_stmt_expr (stmt_expr, false);
17131         cur_stmt_expr = old_stmt_expr;
17132
17133         /* If the resulting list of expression statement is empty,
17134            fold it further into void_node.  */
17135         if (empty_expr_stmt_p (stmt_expr))
17136           stmt_expr = void_node;
17137
17138         RETURN (stmt_expr);
17139       }
17140
17141     case LAMBDA_EXPR:
17142       {
17143         tree r = build_lambda_expr ();
17144
17145         tree type = tsubst (LAMBDA_EXPR_CLOSURE (t), args, complain, NULL_TREE);
17146         LAMBDA_EXPR_CLOSURE (r) = type;
17147         CLASSTYPE_LAMBDA_EXPR (type) = r;
17148
17149         LAMBDA_EXPR_LOCATION (r)
17150           = LAMBDA_EXPR_LOCATION (t);
17151         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
17152           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
17153         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
17154         LAMBDA_EXPR_DISCRIMINATOR (r)
17155           = (LAMBDA_EXPR_DISCRIMINATOR (t));
17156         tree scope = LAMBDA_EXPR_EXTRA_SCOPE (t);
17157         if (!scope)
17158           /* No substitution needed.  */;
17159         else if (VAR_OR_FUNCTION_DECL_P (scope))
17160           /* For a function or variable scope, we want to use tsubst so that we
17161              don't complain about referring to an auto before deduction.  */
17162           scope = tsubst (scope, args, complain, in_decl);
17163         else if (TREE_CODE (scope) == PARM_DECL)
17164           {
17165             /* Look up the parameter we want directly, as tsubst_copy
17166                doesn't do what we need.  */
17167             tree fn = tsubst (DECL_CONTEXT (scope), args, complain, in_decl);
17168             tree parm = FUNCTION_FIRST_USER_PARM (fn);
17169             while (DECL_PARM_INDEX (parm) != DECL_PARM_INDEX (scope))
17170               parm = DECL_CHAIN (parm);
17171             scope = parm;
17172             /* FIXME Work around the parm not having DECL_CONTEXT set.  */
17173             if (DECL_CONTEXT (scope) == NULL_TREE)
17174               DECL_CONTEXT (scope) = fn;
17175           }
17176         else if (TREE_CODE (scope) == FIELD_DECL)
17177           /* For a field, use tsubst_copy so that we look up the existing field
17178              rather than build a new one.  */
17179           scope = RECUR (scope);
17180         else
17181           gcc_unreachable ();
17182         LAMBDA_EXPR_EXTRA_SCOPE (r) = scope;
17183
17184         gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
17185                     && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
17186
17187         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
17188         determine_visibility (TYPE_NAME (type));
17189         /* Now that we know visibility, instantiate the type so we have a
17190            declaration of the op() for later calls to lambda_function.  */
17191         complete_type (type);
17192
17193         if (tree fn = lambda_function (type))
17194           LAMBDA_EXPR_RETURN_TYPE (r) = TREE_TYPE (TREE_TYPE (fn));
17195
17196         LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
17197
17198         insert_pending_capture_proxies ();
17199
17200         RETURN (build_lambda_object (r));
17201       }
17202
17203     case TARGET_EXPR:
17204       /* We can get here for a constant initializer of non-dependent type.
17205          FIXME stop folding in cp_parser_initializer_clause.  */
17206       {
17207         tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
17208                                          complain);
17209         RETURN (r);
17210       }
17211
17212     case TRANSACTION_EXPR:
17213       RETURN (tsubst_expr(t, args, complain, in_decl,
17214              integral_constant_expression_p));
17215
17216     case PAREN_EXPR:
17217       RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
17218
17219     case VEC_PERM_EXPR:
17220       {
17221         tree op0 = RECUR (TREE_OPERAND (t, 0));
17222         tree op1 = RECUR (TREE_OPERAND (t, 1));
17223         tree op2 = RECUR (TREE_OPERAND (t, 2));
17224         RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
17225                                        complain));
17226       }
17227
17228     case REQUIRES_EXPR:
17229       RETURN (tsubst_requires_expr (t, args, complain, in_decl));
17230
17231     default:
17232       /* Handle Objective-C++ constructs, if appropriate.  */
17233       {
17234         tree subst
17235           = objcp_tsubst_copy_and_build (t, args, complain,
17236                                          in_decl, /*function_p=*/false);
17237         if (subst)
17238           RETURN (subst);
17239       }
17240       RETURN (tsubst_copy (t, args, complain, in_decl));
17241     }
17242
17243 #undef RECUR
17244 #undef RETURN
17245  out:
17246   input_location = loc;
17247   return retval;
17248 }
17249
17250 /* Verify that the instantiated ARGS are valid. For type arguments,
17251    make sure that the type's linkage is ok. For non-type arguments,
17252    make sure they are constants if they are integral or enumerations.
17253    Emit an error under control of COMPLAIN, and return TRUE on error.  */
17254
17255 static bool
17256 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
17257 {
17258   if (dependent_template_arg_p (t))
17259     return false;
17260   if (ARGUMENT_PACK_P (t))
17261     {
17262       tree vec = ARGUMENT_PACK_ARGS (t);
17263       int len = TREE_VEC_LENGTH (vec);
17264       bool result = false;
17265       int i;
17266
17267       for (i = 0; i < len; ++i)
17268         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
17269           result = true;
17270       return result;
17271     }
17272   else if (TYPE_P (t))
17273     {
17274       /* [basic.link]: A name with no linkage (notably, the name
17275          of a class or enumeration declared in a local scope)
17276          shall not be used to declare an entity with linkage.
17277          This implies that names with no linkage cannot be used as
17278          template arguments
17279
17280          DR 757 relaxes this restriction for C++0x.  */
17281       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
17282                  : no_linkage_check (t, /*relaxed_p=*/false));
17283
17284       if (nt)
17285         {
17286           /* DR 488 makes use of a type with no linkage cause
17287              type deduction to fail.  */
17288           if (complain & tf_error)
17289             {
17290               if (TYPE_ANONYMOUS_P (nt))
17291                 error ("%qT is/uses anonymous type", t);
17292               else
17293                 error ("template argument for %qD uses local type %qT",
17294                        tmpl, t);
17295             }
17296           return true;
17297         }
17298       /* In order to avoid all sorts of complications, we do not
17299          allow variably-modified types as template arguments.  */
17300       else if (variably_modified_type_p (t, NULL_TREE))
17301         {
17302           if (complain & tf_error)
17303             error ("%qT is a variably modified type", t);
17304           return true;
17305         }
17306     }
17307   /* Class template and alias template arguments should be OK.  */
17308   else if (DECL_TYPE_TEMPLATE_P (t))
17309     ;
17310   /* A non-type argument of integral or enumerated type must be a
17311      constant.  */
17312   else if (TREE_TYPE (t)
17313            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
17314            && !REFERENCE_REF_P (t)
17315            && !TREE_CONSTANT (t))
17316     {
17317       if (complain & tf_error)
17318         error ("integral expression %qE is not constant", t);
17319       return true;
17320     }
17321   return false;
17322 }
17323
17324 static bool
17325 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
17326 {
17327   int ix, len = DECL_NTPARMS (tmpl);
17328   bool result = false;
17329
17330   for (ix = 0; ix != len; ix++)
17331     {
17332       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
17333         result = true;
17334     }
17335   if (result && (complain & tf_error))
17336     error ("  trying to instantiate %qD", tmpl);
17337   return result;
17338 }
17339
17340 /* We're out of SFINAE context now, so generate diagnostics for the access
17341    errors we saw earlier when instantiating D from TMPL and ARGS.  */
17342
17343 static void
17344 recheck_decl_substitution (tree d, tree tmpl, tree args)
17345 {
17346   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
17347   tree type = TREE_TYPE (pattern);
17348   location_t loc = input_location;
17349
17350   push_access_scope (d);
17351   push_deferring_access_checks (dk_no_deferred);
17352   input_location = DECL_SOURCE_LOCATION (pattern);
17353   tsubst (type, args, tf_warning_or_error, d);
17354   input_location = loc;
17355   pop_deferring_access_checks ();
17356   pop_access_scope (d);
17357 }
17358
17359 /* Instantiate the indicated variable, function, or alias template TMPL with
17360    the template arguments in TARG_PTR.  */
17361
17362 static tree
17363 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
17364 {
17365   tree targ_ptr = orig_args;
17366   tree fndecl;
17367   tree gen_tmpl;
17368   tree spec;
17369   bool access_ok = true;
17370
17371   if (tmpl == error_mark_node)
17372     return error_mark_node;
17373
17374   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
17375
17376   /* If this function is a clone, handle it specially.  */
17377   if (DECL_CLONED_FUNCTION_P (tmpl))
17378     {
17379       tree spec;
17380       tree clone;
17381
17382       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
17383          DECL_CLONED_FUNCTION.  */
17384       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
17385                                    targ_ptr, complain);
17386       if (spec == error_mark_node)
17387         return error_mark_node;
17388
17389       /* Look for the clone.  */
17390       FOR_EACH_CLONE (clone, spec)
17391         if (DECL_NAME (clone) == DECL_NAME (tmpl))
17392           return clone;
17393       /* We should always have found the clone by now.  */
17394       gcc_unreachable ();
17395       return NULL_TREE;
17396     }
17397
17398   if (targ_ptr == error_mark_node)
17399     return error_mark_node;
17400
17401   /* Check to see if we already have this specialization.  */
17402   gen_tmpl = most_general_template (tmpl);
17403   if (tmpl != gen_tmpl)
17404     /* The TMPL is a partial instantiation.  To get a full set of
17405        arguments we must add the arguments used to perform the
17406        partial instantiation.  */
17407     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
17408                                             targ_ptr);
17409
17410   /* It would be nice to avoid hashing here and then again in tsubst_decl,
17411      but it doesn't seem to be on the hot path.  */
17412   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
17413
17414   gcc_assert (tmpl == gen_tmpl
17415               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
17416                   == spec)
17417               || fndecl == NULL_TREE);
17418
17419   if (spec != NULL_TREE)
17420     {
17421       if (FNDECL_HAS_ACCESS_ERRORS (spec))
17422         {
17423           if (complain & tf_error)
17424             recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
17425           return error_mark_node;
17426         }
17427       return spec;
17428     }
17429
17430   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
17431                                complain))
17432     return error_mark_node;
17433
17434   /* We are building a FUNCTION_DECL, during which the access of its
17435      parameters and return types have to be checked.  However this
17436      FUNCTION_DECL which is the desired context for access checking
17437      is not built yet.  We solve this chicken-and-egg problem by
17438      deferring all checks until we have the FUNCTION_DECL.  */
17439   push_deferring_access_checks (dk_deferred);
17440
17441   /* Instantiation of the function happens in the context of the function
17442      template, not the context of the overload resolution we're doing.  */
17443   push_to_top_level ();
17444   /* If there are dependent arguments, e.g. because we're doing partial
17445      ordering, make sure processing_template_decl stays set.  */
17446   if (uses_template_parms (targ_ptr))
17447     ++processing_template_decl;
17448   if (DECL_CLASS_SCOPE_P (gen_tmpl))
17449     {
17450       tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
17451                                    complain, gen_tmpl, true);
17452       push_nested_class (ctx);
17453     }
17454
17455   tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
17456
17457   fndecl = NULL_TREE;
17458   if (VAR_P (pattern))
17459     {
17460       /* We need to determine if we're using a partial or explicit
17461          specialization now, because the type of the variable could be
17462          different.  */
17463       tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
17464       tree elt = most_specialized_partial_spec (tid, complain);
17465       if (elt == error_mark_node)
17466         pattern = error_mark_node;
17467       else if (elt)
17468         {
17469           tree partial_tmpl = TREE_VALUE (elt);
17470           tree partial_args = TREE_PURPOSE (elt);
17471           tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
17472           fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
17473         }
17474     }
17475
17476   /* Substitute template parameters to obtain the specialization.  */
17477   if (fndecl == NULL_TREE)
17478     fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
17479   if (DECL_CLASS_SCOPE_P (gen_tmpl))
17480     pop_nested_class ();
17481   pop_from_top_level ();
17482
17483   if (fndecl == error_mark_node)
17484     {
17485       pop_deferring_access_checks ();
17486       return error_mark_node;
17487     }
17488
17489   /* The DECL_TI_TEMPLATE should always be the immediate parent
17490      template, not the most general template.  */
17491   DECL_TI_TEMPLATE (fndecl) = tmpl;
17492   DECL_TI_ARGS (fndecl) = targ_ptr;
17493
17494   /* Now we know the specialization, compute access previously
17495      deferred.  */
17496   push_access_scope (fndecl);
17497   if (!perform_deferred_access_checks (complain))
17498     access_ok = false;
17499   pop_access_scope (fndecl);
17500   pop_deferring_access_checks ();
17501
17502   /* If we've just instantiated the main entry point for a function,
17503      instantiate all the alternate entry points as well.  We do this
17504      by cloning the instantiation of the main entry point, not by
17505      instantiating the template clones.  */
17506   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
17507     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
17508
17509   if (!access_ok)
17510     {
17511       if (!(complain & tf_error))
17512         {
17513           /* Remember to reinstantiate when we're out of SFINAE so the user
17514              can see the errors.  */
17515           FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
17516         }
17517       return error_mark_node;
17518     }
17519   return fndecl;
17520 }
17521
17522 /* Wrapper for instantiate_template_1.  */
17523
17524 tree
17525 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
17526 {
17527   tree ret;
17528   timevar_push (TV_TEMPLATE_INST);
17529   ret = instantiate_template_1 (tmpl, orig_args,  complain);
17530   timevar_pop (TV_TEMPLATE_INST);
17531   return ret;
17532 }
17533
17534 /* Instantiate the alias template TMPL with ARGS.  Also push a template
17535    instantiation level, which instantiate_template doesn't do because
17536    functions and variables have sufficient context established by the
17537    callers.  */
17538
17539 static tree
17540 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
17541 {
17542   struct pending_template *old_last_pend = last_pending_template;
17543   struct tinst_level *old_error_tinst = last_error_tinst_level;
17544   if (tmpl == error_mark_node || args == error_mark_node)
17545     return error_mark_node;
17546   tree tinst = build_tree_list (tmpl, args);
17547   if (!push_tinst_level (tinst))
17548     {
17549       ggc_free (tinst);
17550       return error_mark_node;
17551     }
17552
17553   args =
17554     coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
17555                                      args, tmpl, complain,
17556                                      /*require_all_args=*/true,
17557                                      /*use_default_args=*/true);
17558
17559   tree r = instantiate_template (tmpl, args, complain);
17560   pop_tinst_level ();
17561   /* We can't free this if a pending_template entry or last_error_tinst_level
17562      is pointing at it.  */
17563   if (last_pending_template == old_last_pend
17564       && last_error_tinst_level == old_error_tinst)
17565     ggc_free (tinst);
17566
17567   return r;
17568 }
17569
17570 /* PARM is a template parameter pack for FN.  Returns true iff
17571    PARM is used in a deducible way in the argument list of FN.  */
17572
17573 static bool
17574 pack_deducible_p (tree parm, tree fn)
17575 {
17576   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
17577   for (; t; t = TREE_CHAIN (t))
17578     {
17579       tree type = TREE_VALUE (t);
17580       tree packs;
17581       if (!PACK_EXPANSION_P (type))
17582         continue;
17583       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
17584            packs; packs = TREE_CHAIN (packs))
17585         if (template_args_equal (TREE_VALUE (packs), parm))
17586           {
17587             /* The template parameter pack is used in a function parameter
17588                pack.  If this is the end of the parameter list, the
17589                template parameter pack is deducible.  */
17590             if (TREE_CHAIN (t) == void_list_node)
17591               return true;
17592             else
17593               /* Otherwise, not.  Well, it could be deduced from
17594                  a non-pack parameter, but doing so would end up with
17595                  a deduction mismatch, so don't bother.  */
17596               return false;
17597           }
17598     }
17599   /* The template parameter pack isn't used in any function parameter
17600      packs, but it might be used deeper, e.g. tuple<Args...>.  */
17601   return true;
17602 }
17603
17604 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
17605    NARGS elements of the arguments that are being used when calling
17606    it.  TARGS is a vector into which the deduced template arguments
17607    are placed.
17608
17609    Returns either a FUNCTION_DECL for the matching specialization of FN or
17610    NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
17611    true, diagnostics will be printed to explain why it failed.
17612
17613    If FN is a conversion operator, or we are trying to produce a specific
17614    specialization, RETURN_TYPE is the return type desired.
17615
17616    The EXPLICIT_TARGS are explicit template arguments provided via a
17617    template-id.
17618
17619    The parameter STRICT is one of:
17620
17621    DEDUCE_CALL:
17622      We are deducing arguments for a function call, as in
17623      [temp.deduct.call].  If RETURN_TYPE is non-null, we are
17624      deducing arguments for a call to the result of a conversion
17625      function template, as in [over.call.object].
17626
17627    DEDUCE_CONV:
17628      We are deducing arguments for a conversion function, as in
17629      [temp.deduct.conv].
17630
17631    DEDUCE_EXACT:
17632      We are deducing arguments when doing an explicit instantiation
17633      as in [temp.explicit], when determining an explicit specialization
17634      as in [temp.expl.spec], or when taking the address of a function
17635      template, as in [temp.deduct.funcaddr].  */
17636
17637 tree
17638 fn_type_unification (tree fn,
17639                      tree explicit_targs,
17640                      tree targs,
17641                      const tree *args,
17642                      unsigned int nargs,
17643                      tree return_type,
17644                      unification_kind_t strict,
17645                      int flags,
17646                      bool explain_p,
17647                      bool decltype_p)
17648 {
17649   tree parms;
17650   tree fntype;
17651   tree decl = NULL_TREE;
17652   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
17653   bool ok;
17654   static int deduction_depth;
17655   struct pending_template *old_last_pend = last_pending_template;
17656   struct tinst_level *old_error_tinst = last_error_tinst_level;
17657   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
17658   tree tinst;
17659   tree r = error_mark_node;
17660
17661   if (decltype_p)
17662     complain |= tf_decltype;
17663
17664   /* In C++0x, it's possible to have a function template whose type depends
17665      on itself recursively.  This is most obvious with decltype, but can also
17666      occur with enumeration scope (c++/48969).  So we need to catch infinite
17667      recursion and reject the substitution at deduction time; this function
17668      will return error_mark_node for any repeated substitution.
17669
17670      This also catches excessive recursion such as when f<N> depends on
17671      f<N-1> across all integers, and returns error_mark_node for all the
17672      substitutions back up to the initial one.
17673
17674      This is, of course, not reentrant.  */
17675   if (excessive_deduction_depth)
17676     return error_mark_node;
17677   tinst = build_tree_list (fn, NULL_TREE);
17678   ++deduction_depth;
17679
17680   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
17681
17682   fntype = TREE_TYPE (fn);
17683   if (explicit_targs)
17684     {
17685       /* [temp.deduct]
17686
17687          The specified template arguments must match the template
17688          parameters in kind (i.e., type, nontype, template), and there
17689          must not be more arguments than there are parameters;
17690          otherwise type deduction fails.
17691
17692          Nontype arguments must match the types of the corresponding
17693          nontype template parameters, or must be convertible to the
17694          types of the corresponding nontype parameters as specified in
17695          _temp.arg.nontype_, otherwise type deduction fails.
17696
17697          All references in the function type of the function template
17698          to the corresponding template parameters are replaced by the
17699          specified template argument values.  If a substitution in a
17700          template parameter or in the function type of the function
17701          template results in an invalid type, type deduction fails.  */
17702       int i, len = TREE_VEC_LENGTH (tparms);
17703       location_t loc = input_location;
17704       bool incomplete = false;
17705
17706       /* Adjust any explicit template arguments before entering the
17707          substitution context.  */
17708       explicit_targs
17709         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
17710                                   complain,
17711                                   /*require_all_args=*/false,
17712                                   /*use_default_args=*/false));
17713       if (explicit_targs == error_mark_node)
17714         goto fail;
17715
17716       /* Substitute the explicit args into the function type.  This is
17717          necessary so that, for instance, explicitly declared function
17718          arguments can match null pointed constants.  If we were given
17719          an incomplete set of explicit args, we must not do semantic
17720          processing during substitution as we could create partial
17721          instantiations.  */
17722       for (i = 0; i < len; i++)
17723         {
17724           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
17725           bool parameter_pack = false;
17726           tree targ = TREE_VEC_ELT (explicit_targs, i);
17727
17728           /* Dig out the actual parm.  */
17729           if (TREE_CODE (parm) == TYPE_DECL
17730               || TREE_CODE (parm) == TEMPLATE_DECL)
17731             {
17732               parm = TREE_TYPE (parm);
17733               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
17734             }
17735           else if (TREE_CODE (parm) == PARM_DECL)
17736             {
17737               parm = DECL_INITIAL (parm);
17738               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
17739             }
17740
17741           if (!parameter_pack && targ == NULL_TREE)
17742             /* No explicit argument for this template parameter.  */
17743             incomplete = true;
17744
17745           if (parameter_pack && pack_deducible_p (parm, fn))
17746             {
17747               /* Mark the argument pack as "incomplete". We could
17748                  still deduce more arguments during unification.
17749                  We remove this mark in type_unification_real.  */
17750               if (targ)
17751                 {
17752                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
17753                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
17754                     = ARGUMENT_PACK_ARGS (targ);
17755                 }
17756
17757               /* We have some incomplete argument packs.  */
17758               incomplete = true;
17759             }
17760         }
17761
17762       TREE_VALUE (tinst) = explicit_targs;
17763       if (!push_tinst_level (tinst))
17764         {
17765           excessive_deduction_depth = true;
17766           goto fail;
17767         }
17768       processing_template_decl += incomplete;
17769       input_location = DECL_SOURCE_LOCATION (fn);
17770       /* Ignore any access checks; we'll see them again in
17771          instantiate_template and they might have the wrong
17772          access path at this point.  */
17773       push_deferring_access_checks (dk_deferred);
17774       fntype = tsubst (TREE_TYPE (fn), explicit_targs,
17775                        complain | tf_partial, NULL_TREE);
17776       pop_deferring_access_checks ();
17777       input_location = loc;
17778       processing_template_decl -= incomplete;
17779       pop_tinst_level ();
17780
17781       if (fntype == error_mark_node)
17782         goto fail;
17783
17784       /* Place the explicitly specified arguments in TARGS.  */
17785       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
17786         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
17787     }
17788
17789   /* Never do unification on the 'this' parameter.  */
17790   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
17791
17792   if (return_type && strict == DEDUCE_CALL)
17793     {
17794       /* We're deducing for a call to the result of a template conversion
17795          function.  The parms we really want are in return_type.  */
17796       if (POINTER_TYPE_P (return_type))
17797         return_type = TREE_TYPE (return_type);
17798       parms = TYPE_ARG_TYPES (return_type);
17799     }
17800   else if (return_type)
17801     {
17802       tree *new_args;
17803
17804       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
17805       new_args = XALLOCAVEC (tree, nargs + 1);
17806       new_args[0] = return_type;
17807       memcpy (new_args + 1, args, nargs * sizeof (tree));
17808       args = new_args;
17809       ++nargs;
17810     }
17811
17812   /* We allow incomplete unification without an error message here
17813      because the standard doesn't seem to explicitly prohibit it.  Our
17814      callers must be ready to deal with unification failures in any
17815      event.  */
17816
17817   TREE_VALUE (tinst) = targs;
17818   /* If we aren't explaining yet, push tinst context so we can see where
17819      any errors (e.g. from class instantiations triggered by instantiation
17820      of default template arguments) come from.  If we are explaining, this
17821      context is redundant.  */
17822   if (!explain_p && !push_tinst_level (tinst))
17823     {
17824       excessive_deduction_depth = true;
17825       goto fail;
17826     }
17827
17828   /* type_unification_real will pass back any access checks from default
17829      template argument substitution.  */
17830   vec<deferred_access_check, va_gc> *checks;
17831   checks = NULL;
17832
17833   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
17834                                targs, parms, args, nargs, /*subr=*/0,
17835                                strict, flags, &checks, explain_p);
17836   if (!explain_p)
17837     pop_tinst_level ();
17838   if (!ok)
17839     goto fail;
17840
17841   /* Now that we have bindings for all of the template arguments,
17842      ensure that the arguments deduced for the template template
17843      parameters have compatible template parameter lists.  We cannot
17844      check this property before we have deduced all template
17845      arguments, because the template parameter types of a template
17846      template parameter might depend on prior template parameters
17847      deduced after the template template parameter.  The following
17848      ill-formed example illustrates this issue:
17849
17850        template<typename T, template<T> class C> void f(C<5>, T);
17851
17852        template<int N> struct X {};
17853
17854        void g() {
17855          f(X<5>(), 5l); // error: template argument deduction fails
17856        }
17857
17858      The template parameter list of 'C' depends on the template type
17859      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
17860      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
17861      time that we deduce 'C'.  */
17862   if (!template_template_parm_bindings_ok_p
17863            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
17864     {
17865       unify_inconsistent_template_template_parameters (explain_p);
17866       goto fail;
17867     }
17868
17869   /* All is well so far.  Now, check:
17870
17871      [temp.deduct]
17872
17873      When all template arguments have been deduced, all uses of
17874      template parameters in nondeduced contexts are replaced with
17875      the corresponding deduced argument values.  If the
17876      substitution results in an invalid type, as described above,
17877      type deduction fails.  */
17878   TREE_VALUE (tinst) = targs;
17879   if (!push_tinst_level (tinst))
17880     {
17881       excessive_deduction_depth = true;
17882       goto fail;
17883     }
17884
17885   /* Also collect access checks from the instantiation.  */
17886   reopen_deferring_access_checks (checks);
17887
17888   decl = instantiate_template (fn, targs, complain);
17889
17890   checks = get_deferred_access_checks ();
17891   pop_deferring_access_checks ();
17892
17893   pop_tinst_level ();
17894
17895   if (decl == error_mark_node)
17896     goto fail;
17897
17898   /* Now perform any access checks encountered during substitution.  */
17899   push_access_scope (decl);
17900   ok = perform_access_checks (checks, complain);
17901   pop_access_scope (decl);
17902   if (!ok)
17903     goto fail;
17904
17905   /* If we're looking for an exact match, check that what we got
17906      is indeed an exact match.  It might not be if some template
17907      parameters are used in non-deduced contexts.  But don't check
17908      for an exact match if we have dependent template arguments;
17909      in that case we're doing partial ordering, and we already know
17910      that we have two candidates that will provide the actual type.  */
17911   if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
17912     {
17913       tree substed = TREE_TYPE (decl);
17914       unsigned int i;
17915
17916       tree sarg
17917         = skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
17918       if (return_type)
17919         sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
17920       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
17921         if (!same_type_p (args[i], TREE_VALUE (sarg)))
17922           {
17923             unify_type_mismatch (explain_p, args[i],
17924                                  TREE_VALUE (sarg));
17925             goto fail;
17926           }
17927     }
17928
17929   r = decl;
17930
17931  fail:
17932   --deduction_depth;
17933   if (excessive_deduction_depth)
17934     {
17935       if (deduction_depth == 0)
17936         /* Reset once we're all the way out.  */
17937         excessive_deduction_depth = false;
17938     }
17939
17940   /* We can't free this if a pending_template entry or last_error_tinst_level
17941      is pointing at it.  */
17942   if (last_pending_template == old_last_pend
17943       && last_error_tinst_level == old_error_tinst)
17944     ggc_free (tinst);
17945
17946   return r;
17947 }
17948
17949 /* Adjust types before performing type deduction, as described in
17950    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
17951    sections are symmetric.  PARM is the type of a function parameter
17952    or the return type of the conversion function.  ARG is the type of
17953    the argument passed to the call, or the type of the value
17954    initialized with the result of the conversion function.
17955    ARG_EXPR is the original argument expression, which may be null.  */
17956
17957 static int
17958 maybe_adjust_types_for_deduction (unification_kind_t strict,
17959                                   tree* parm,
17960                                   tree* arg,
17961                                   tree arg_expr)
17962 {
17963   int result = 0;
17964
17965   switch (strict)
17966     {
17967     case DEDUCE_CALL:
17968       break;
17969
17970     case DEDUCE_CONV:
17971       /* Swap PARM and ARG throughout the remainder of this
17972          function; the handling is precisely symmetric since PARM
17973          will initialize ARG rather than vice versa.  */
17974       std::swap (parm, arg);
17975       break;
17976
17977     case DEDUCE_EXACT:
17978       /* Core issue #873: Do the DR606 thing (see below) for these cases,
17979          too, but here handle it by stripping the reference from PARM
17980          rather than by adding it to ARG.  */
17981       if (TREE_CODE (*parm) == REFERENCE_TYPE
17982           && TYPE_REF_IS_RVALUE (*parm)
17983           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
17984           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
17985           && TREE_CODE (*arg) == REFERENCE_TYPE
17986           && !TYPE_REF_IS_RVALUE (*arg))
17987         *parm = TREE_TYPE (*parm);
17988       /* Nothing else to do in this case.  */
17989       return 0;
17990
17991     default:
17992       gcc_unreachable ();
17993     }
17994
17995   if (TREE_CODE (*parm) != REFERENCE_TYPE)
17996     {
17997       /* [temp.deduct.call]
17998
17999          If P is not a reference type:
18000
18001          --If A is an array type, the pointer type produced by the
18002          array-to-pointer standard conversion (_conv.array_) is
18003          used in place of A for type deduction; otherwise,
18004
18005          --If A is a function type, the pointer type produced by
18006          the function-to-pointer standard conversion
18007          (_conv.func_) is used in place of A for type deduction;
18008          otherwise,
18009
18010          --If A is a cv-qualified type, the top level
18011          cv-qualifiers of A's type are ignored for type
18012          deduction.  */
18013       if (TREE_CODE (*arg) == ARRAY_TYPE)
18014         *arg = build_pointer_type (TREE_TYPE (*arg));
18015       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
18016         *arg = build_pointer_type (*arg);
18017       else
18018         *arg = TYPE_MAIN_VARIANT (*arg);
18019     }
18020
18021   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
18022      of the form T&&, where T is a template parameter, and the argument
18023      is an lvalue, T is deduced as A& */
18024   if (TREE_CODE (*parm) == REFERENCE_TYPE
18025       && TYPE_REF_IS_RVALUE (*parm)
18026       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
18027       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
18028       && (arg_expr ? real_lvalue_p (arg_expr)
18029           /* try_one_overload doesn't provide an arg_expr, but
18030              functions are always lvalues.  */
18031           : TREE_CODE (*arg) == FUNCTION_TYPE))
18032     *arg = build_reference_type (*arg);
18033
18034   /* [temp.deduct.call]
18035
18036      If P is a cv-qualified type, the top level cv-qualifiers
18037      of P's type are ignored for type deduction.  If P is a
18038      reference type, the type referred to by P is used for
18039      type deduction.  */
18040   *parm = TYPE_MAIN_VARIANT (*parm);
18041   if (TREE_CODE (*parm) == REFERENCE_TYPE)
18042     {
18043       *parm = TREE_TYPE (*parm);
18044       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
18045     }
18046
18047   /* DR 322. For conversion deduction, remove a reference type on parm
18048      too (which has been swapped into ARG).  */
18049   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
18050     *arg = TREE_TYPE (*arg);
18051
18052   return result;
18053 }
18054
18055 /* Subroutine of unify_one_argument.  PARM is a function parameter of a
18056    template which does contain any deducible template parameters; check if
18057    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
18058    unify_one_argument.  */
18059
18060 static int
18061 check_non_deducible_conversion (tree parm, tree arg, int strict,
18062                                 int flags, bool explain_p)
18063 {
18064   tree type;
18065
18066   if (!TYPE_P (arg))
18067     type = TREE_TYPE (arg);
18068   else
18069     type = arg;
18070
18071   if (same_type_p (parm, type))
18072     return unify_success (explain_p);
18073
18074   if (strict == DEDUCE_CONV)
18075     {
18076       if (can_convert_arg (type, parm, NULL_TREE, flags,
18077                            explain_p ? tf_warning_or_error : tf_none))
18078         return unify_success (explain_p);
18079     }
18080   else if (strict != DEDUCE_EXACT)
18081     {
18082       if (can_convert_arg (parm, type,
18083                            TYPE_P (arg) ? NULL_TREE : arg,
18084                            flags, explain_p ? tf_warning_or_error : tf_none))
18085         return unify_success (explain_p);
18086     }
18087
18088   if (strict == DEDUCE_EXACT)
18089     return unify_type_mismatch (explain_p, parm, arg);
18090   else
18091     return unify_arg_conversion (explain_p, parm, type, arg);
18092 }
18093
18094 static bool uses_deducible_template_parms (tree type);
18095
18096 /* Returns true iff the expression EXPR is one from which a template
18097    argument can be deduced.  In other words, if it's an undecorated
18098    use of a template non-type parameter.  */
18099
18100 static bool
18101 deducible_expression (tree expr)
18102 {
18103   return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
18104 }
18105
18106 /* Returns true iff the array domain DOMAIN uses a template parameter in a
18107    deducible way; that is, if it has a max value of <PARM> - 1.  */
18108
18109 static bool
18110 deducible_array_bound (tree domain)
18111 {
18112   if (domain == NULL_TREE)
18113     return false;
18114
18115   tree max = TYPE_MAX_VALUE (domain);
18116   if (TREE_CODE (max) != MINUS_EXPR)
18117     return false;
18118
18119   return deducible_expression (TREE_OPERAND (max, 0));
18120 }
18121
18122 /* Returns true iff the template arguments ARGS use a template parameter
18123    in a deducible way.  */
18124
18125 static bool
18126 deducible_template_args (tree args)
18127 {
18128   for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
18129     {
18130       bool deducible;
18131       tree elt = TREE_VEC_ELT (args, i);
18132       if (ARGUMENT_PACK_P (elt))
18133         deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
18134       else
18135         {
18136           if (PACK_EXPANSION_P (elt))
18137             elt = PACK_EXPANSION_PATTERN (elt);
18138           if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
18139             deducible = true;
18140           else if (TYPE_P (elt))
18141             deducible = uses_deducible_template_parms (elt);
18142           else
18143             deducible = deducible_expression (elt);
18144         }
18145       if (deducible)
18146         return true;
18147     }
18148   return false;
18149 }
18150
18151 /* Returns true iff TYPE contains any deducible references to template
18152    parameters, as per 14.8.2.5.  */
18153
18154 static bool
18155 uses_deducible_template_parms (tree type)
18156 {
18157   if (PACK_EXPANSION_P (type))
18158     type = PACK_EXPANSION_PATTERN (type);
18159
18160   /* T
18161      cv-list T
18162      TT<T>
18163      TT<i>
18164      TT<> */
18165   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18166       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
18167     return true;
18168
18169   /* T*
18170      T&
18171      T&&  */
18172   if (POINTER_TYPE_P (type))
18173     return uses_deducible_template_parms (TREE_TYPE (type));
18174
18175   /* T[integer-constant ]
18176      type [i]  */
18177   if (TREE_CODE (type) == ARRAY_TYPE)
18178     return (uses_deducible_template_parms (TREE_TYPE (type))
18179             || deducible_array_bound (TYPE_DOMAIN (type)));
18180
18181   /* T type ::*
18182      type T::*
18183      T T::*
18184      T (type ::*)()
18185      type (T::*)()
18186      type (type ::*)(T)
18187      type (T::*)(T)
18188      T (type ::*)(T)
18189      T (T::*)()
18190      T (T::*)(T) */
18191   if (TYPE_PTRMEM_P (type))
18192     return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
18193             || (uses_deducible_template_parms
18194                 (TYPE_PTRMEM_POINTED_TO_TYPE (type))));
18195
18196   /* template-name <T> (where template-name refers to a class template)
18197      template-name <i> (where template-name refers to a class template) */
18198   if (CLASS_TYPE_P (type)
18199       && CLASSTYPE_TEMPLATE_INFO (type)
18200       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
18201     return deducible_template_args (INNERMOST_TEMPLATE_ARGS
18202                                     (CLASSTYPE_TI_ARGS (type)));
18203
18204   /* type (T)
18205      T()
18206      T(T)  */
18207   if (TREE_CODE (type) == FUNCTION_TYPE
18208       || TREE_CODE (type) == METHOD_TYPE)
18209     {
18210       if (uses_deducible_template_parms (TREE_TYPE (type)))
18211         return true;
18212       tree parm = TYPE_ARG_TYPES (type);
18213       if (TREE_CODE (type) == METHOD_TYPE)
18214         parm = TREE_CHAIN (parm);
18215       for (; parm; parm = TREE_CHAIN (parm))
18216         if (uses_deducible_template_parms (TREE_VALUE (parm)))
18217           return true;
18218     }
18219
18220   return false;
18221 }
18222
18223 /* Subroutine of type_unification_real and unify_pack_expansion to
18224    handle unification of a single P/A pair.  Parameters are as
18225    for those functions.  */
18226
18227 static int
18228 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
18229                     int subr, unification_kind_t strict,
18230                     bool explain_p)
18231 {
18232   tree arg_expr = NULL_TREE;
18233   int arg_strict;
18234
18235   if (arg == error_mark_node || parm == error_mark_node)
18236     return unify_invalid (explain_p);
18237   if (arg == unknown_type_node)
18238     /* We can't deduce anything from this, but we might get all the
18239        template args from other function args.  */
18240     return unify_success (explain_p);
18241
18242   /* Implicit conversions (Clause 4) will be performed on a function
18243      argument to convert it to the type of the corresponding function
18244      parameter if the parameter type contains no template-parameters that
18245      participate in template argument deduction.  */
18246   if (strict != DEDUCE_EXACT
18247       && TYPE_P (parm) && !uses_deducible_template_parms (parm))
18248     /* For function parameters with no deducible template parameters,
18249        just return.  We'll check non-dependent conversions later.  */
18250     return unify_success (explain_p);
18251
18252   switch (strict)
18253     {
18254     case DEDUCE_CALL:
18255       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
18256                     | UNIFY_ALLOW_MORE_CV_QUAL
18257                     | UNIFY_ALLOW_DERIVED);
18258       break;
18259
18260     case DEDUCE_CONV:
18261       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
18262       break;
18263
18264     case DEDUCE_EXACT:
18265       arg_strict = UNIFY_ALLOW_NONE;
18266       break;
18267
18268     default:
18269       gcc_unreachable ();
18270     }
18271
18272   /* We only do these transformations if this is the top-level
18273      parameter_type_list in a call or declaration matching; in other
18274      situations (nested function declarators, template argument lists) we
18275      won't be comparing a type to an expression, and we don't do any type
18276      adjustments.  */
18277   if (!subr)
18278     {
18279       if (!TYPE_P (arg))
18280         {
18281           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
18282           if (type_unknown_p (arg))
18283             {
18284               /* [temp.deduct.type] A template-argument can be
18285                  deduced from a pointer to function or pointer
18286                  to member function argument if the set of
18287                  overloaded functions does not contain function
18288                  templates and at most one of a set of
18289                  overloaded functions provides a unique
18290                  match.  */
18291
18292               if (resolve_overloaded_unification
18293                   (tparms, targs, parm, arg, strict,
18294                    arg_strict, explain_p))
18295                 return unify_success (explain_p);
18296               return unify_overload_resolution_failure (explain_p, arg);
18297             }
18298
18299           arg_expr = arg;
18300           arg = unlowered_expr_type (arg);
18301           if (arg == error_mark_node)
18302             return unify_invalid (explain_p);
18303         }
18304
18305       arg_strict |=
18306         maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
18307     }
18308   else
18309     if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
18310         != (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
18311       return unify_template_argument_mismatch (explain_p, parm, arg);
18312
18313   /* For deduction from an init-list we need the actual list.  */
18314   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
18315     arg = arg_expr;
18316   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
18317 }
18318
18319 /* Most parms like fn_type_unification.
18320
18321    If SUBR is 1, we're being called recursively (to unify the
18322    arguments of a function or method parameter of a function
18323    template).
18324
18325    CHECKS is a pointer to a vector of access checks encountered while
18326    substituting default template arguments.  */
18327
18328 static int
18329 type_unification_real (tree tparms,
18330                        tree targs,
18331                        tree xparms,
18332                        const tree *xargs,
18333                        unsigned int xnargs,
18334                        int subr,
18335                        unification_kind_t strict,
18336                        int flags,
18337                        vec<deferred_access_check, va_gc> **checks,
18338                        bool explain_p)
18339 {
18340   tree parm, arg;
18341   int i;
18342   int ntparms = TREE_VEC_LENGTH (tparms);
18343   int saw_undeduced = 0;
18344   tree parms;
18345   const tree *args;
18346   unsigned int nargs;
18347   unsigned int ia;
18348
18349   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
18350   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
18351   gcc_assert (ntparms > 0);
18352
18353   /* Reset the number of non-defaulted template arguments contained
18354      in TARGS.  */
18355   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
18356
18357  again:
18358   parms = xparms;
18359   args = xargs;
18360   nargs = xnargs;
18361
18362   ia = 0;
18363   while (parms && parms != void_list_node
18364          && ia < nargs)
18365     {
18366       parm = TREE_VALUE (parms);
18367
18368       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
18369           && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
18370         /* For a function parameter pack that occurs at the end of the
18371            parameter-declaration-list, the type A of each remaining
18372            argument of the call is compared with the type P of the
18373            declarator-id of the function parameter pack.  */
18374         break;
18375
18376       parms = TREE_CHAIN (parms);
18377
18378       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
18379         /* For a function parameter pack that does not occur at the
18380            end of the parameter-declaration-list, the type of the
18381            parameter pack is a non-deduced context.  */
18382         continue;
18383
18384       arg = args[ia];
18385       ++ia;
18386
18387       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
18388                               explain_p))
18389         return 1;
18390     }
18391
18392   if (parms 
18393       && parms != void_list_node
18394       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
18395     {
18396       /* Unify the remaining arguments with the pack expansion type.  */
18397       tree argvec;
18398       tree parmvec = make_tree_vec (1);
18399
18400       /* Allocate a TREE_VEC and copy in all of the arguments */ 
18401       argvec = make_tree_vec (nargs - ia);
18402       for (i = 0; ia < nargs; ++ia, ++i)
18403         TREE_VEC_ELT (argvec, i) = args[ia];
18404
18405       /* Copy the parameter into parmvec.  */
18406       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
18407       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
18408                                 /*subr=*/subr, explain_p))
18409         return 1;
18410
18411       /* Advance to the end of the list of parameters.  */
18412       parms = TREE_CHAIN (parms);
18413     }
18414
18415   /* Fail if we've reached the end of the parm list, and more args
18416      are present, and the parm list isn't variadic.  */
18417   if (ia < nargs && parms == void_list_node)
18418     return unify_too_many_arguments (explain_p, nargs, ia);
18419   /* Fail if parms are left and they don't have default values and
18420      they aren't all deduced as empty packs (c++/57397).  This is
18421      consistent with sufficient_parms_p.  */
18422   if (parms && parms != void_list_node
18423       && TREE_PURPOSE (parms) == NULL_TREE)
18424     {
18425       unsigned int count = nargs;
18426       tree p = parms;
18427       bool type_pack_p;
18428       do
18429         {
18430           type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
18431           if (!type_pack_p)
18432             count++;
18433           p = TREE_CHAIN (p);
18434         }
18435       while (p && p != void_list_node);
18436       if (count != nargs)
18437         return unify_too_few_arguments (explain_p, ia, count,
18438                                         type_pack_p);
18439     }
18440
18441   if (!subr)
18442     {
18443       tsubst_flags_t complain = (explain_p
18444                                  ? tf_warning_or_error
18445                                  : tf_none);
18446
18447       for (i = 0; i < ntparms; i++)
18448         {
18449           tree targ = TREE_VEC_ELT (targs, i);
18450           tree tparm = TREE_VEC_ELT (tparms, i);
18451
18452           /* Clear the "incomplete" flags on all argument packs now so that
18453              substituting them into later default arguments works.  */
18454           if (targ && ARGUMENT_PACK_P (targ))
18455             {
18456               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
18457               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
18458             }
18459
18460           if (targ || tparm == error_mark_node)
18461             continue;
18462           tparm = TREE_VALUE (tparm);
18463
18464           /* If this is an undeduced nontype parameter that depends on
18465              a type parameter, try another pass; its type may have been
18466              deduced from a later argument than the one from which
18467              this parameter can be deduced.  */
18468           if (TREE_CODE (tparm) == PARM_DECL
18469               && uses_template_parms (TREE_TYPE (tparm))
18470               && saw_undeduced < 2)
18471             {
18472               saw_undeduced = 1;
18473               continue;
18474             }
18475
18476           /* Core issue #226 (C++0x) [temp.deduct]:
18477
18478              If a template argument has not been deduced, its
18479              default template argument, if any, is used. 
18480
18481              When we are in C++98 mode, TREE_PURPOSE will either
18482              be NULL_TREE or ERROR_MARK_NODE, so we do not need
18483              to explicitly check cxx_dialect here.  */
18484           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
18485             /* OK, there is a default argument.  Wait until after the
18486                conversion check to do substitution.  */
18487             continue;
18488
18489           /* If the type parameter is a parameter pack, then it will
18490              be deduced to an empty parameter pack.  */
18491           if (template_parameter_pack_p (tparm))
18492             {
18493               tree arg;
18494
18495               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
18496                 {
18497                   arg = make_node (NONTYPE_ARGUMENT_PACK);
18498                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
18499                   TREE_CONSTANT (arg) = 1;
18500                 }
18501               else
18502                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
18503
18504               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
18505
18506               TREE_VEC_ELT (targs, i) = arg;
18507               continue;
18508             }
18509
18510           return unify_parameter_deduction_failure (explain_p, tparm);
18511         }
18512
18513       /* DR 1391: All parameters have args, now check non-dependent parms for
18514          convertibility.  */
18515       if (saw_undeduced < 2)
18516         for (ia = 0, parms = xparms, args = xargs, nargs = xnargs;
18517              parms && parms != void_list_node && ia < nargs; )
18518           {
18519             parm = TREE_VALUE (parms);
18520
18521             if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
18522                 && (!TREE_CHAIN (parms)
18523                     || TREE_CHAIN (parms) == void_list_node))
18524               /* For a function parameter pack that occurs at the end of the
18525                  parameter-declaration-list, the type A of each remaining
18526                  argument of the call is compared with the type P of the
18527                  declarator-id of the function parameter pack.  */
18528               break;
18529
18530             parms = TREE_CHAIN (parms);
18531
18532             if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
18533               /* For a function parameter pack that does not occur at the
18534                  end of the parameter-declaration-list, the type of the
18535                  parameter pack is a non-deduced context.  */
18536               continue;
18537
18538             arg = args[ia];
18539             ++ia;
18540
18541             if (uses_template_parms (parm))
18542               continue;
18543             if (check_non_deducible_conversion (parm, arg, strict, flags,
18544                                                 explain_p))
18545               return 1;
18546           }
18547
18548       /* Now substitute into the default template arguments.  */
18549       for (i = 0; i < ntparms; i++)
18550         {
18551           tree targ = TREE_VEC_ELT (targs, i);
18552           tree tparm = TREE_VEC_ELT (tparms, i);
18553
18554           if (targ || tparm == error_mark_node)
18555             continue;
18556           tree parm = TREE_VALUE (tparm);
18557
18558           if (TREE_CODE (parm) == PARM_DECL
18559               && uses_template_parms (TREE_TYPE (parm))
18560               && saw_undeduced < 2)
18561             continue;
18562
18563           tree arg = TREE_PURPOSE (tparm);
18564           reopen_deferring_access_checks (*checks);
18565           location_t save_loc = input_location;
18566           if (DECL_P (parm))
18567             input_location = DECL_SOURCE_LOCATION (parm);
18568           arg = tsubst_template_arg (arg, targs, complain, NULL_TREE);
18569           if (!uses_template_parms (arg))
18570             arg = convert_template_argument (parm, arg, targs, complain,
18571                                              i, NULL_TREE);
18572           else if (saw_undeduced < 2)
18573             arg = NULL_TREE;
18574           else
18575             arg = error_mark_node;
18576           input_location = save_loc;
18577           *checks = get_deferred_access_checks ();
18578           pop_deferring_access_checks ();
18579           if (arg == error_mark_node)
18580             return 1;
18581           else if (arg)
18582             {
18583               TREE_VEC_ELT (targs, i) = arg;
18584               /* The position of the first default template argument,
18585                  is also the number of non-defaulted arguments in TARGS.
18586                  Record that.  */
18587               if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
18588                 SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
18589             }
18590         }
18591
18592       if (saw_undeduced++ == 1)
18593         goto again;
18594     }
18595
18596   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
18597     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
18598
18599   return unify_success (explain_p);
18600 }
18601
18602 /* Subroutine of type_unification_real.  Args are like the variables
18603    at the call site.  ARG is an overloaded function (or template-id);
18604    we try deducing template args from each of the overloads, and if
18605    only one succeeds, we go with that.  Modifies TARGS and returns
18606    true on success.  */
18607
18608 static bool
18609 resolve_overloaded_unification (tree tparms,
18610                                 tree targs,
18611                                 tree parm,
18612                                 tree arg,
18613                                 unification_kind_t strict,
18614                                 int sub_strict,
18615                                 bool explain_p)
18616 {
18617   tree tempargs = copy_node (targs);
18618   int good = 0;
18619   tree goodfn = NULL_TREE;
18620   bool addr_p;
18621
18622   if (TREE_CODE (arg) == ADDR_EXPR)
18623     {
18624       arg = TREE_OPERAND (arg, 0);
18625       addr_p = true;
18626     }
18627   else
18628     addr_p = false;
18629
18630   if (TREE_CODE (arg) == COMPONENT_REF)
18631     /* Handle `&x' where `x' is some static or non-static member
18632        function name.  */
18633     arg = TREE_OPERAND (arg, 1);
18634
18635   if (TREE_CODE (arg) == OFFSET_REF)
18636     arg = TREE_OPERAND (arg, 1);
18637
18638   /* Strip baselink information.  */
18639   if (BASELINK_P (arg))
18640     arg = BASELINK_FUNCTIONS (arg);
18641
18642   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
18643     {
18644       /* If we got some explicit template args, we need to plug them into
18645          the affected templates before we try to unify, in case the
18646          explicit args will completely resolve the templates in question.  */
18647
18648       int ok = 0;
18649       tree expl_subargs = TREE_OPERAND (arg, 1);
18650       arg = TREE_OPERAND (arg, 0);
18651
18652       for (; arg; arg = OVL_NEXT (arg))
18653         {
18654           tree fn = OVL_CURRENT (arg);
18655           tree subargs, elem;
18656
18657           if (TREE_CODE (fn) != TEMPLATE_DECL)
18658             continue;
18659
18660           subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
18661                                            expl_subargs, NULL_TREE, tf_none,
18662                                            /*require_all_args=*/true,
18663                                            /*use_default_args=*/true);
18664           if (subargs != error_mark_node
18665               && !any_dependent_template_arguments_p (subargs))
18666             {
18667               elem = TREE_TYPE (instantiate_template (fn, subargs, tf_none));
18668               if (try_one_overload (tparms, targs, tempargs, parm,
18669                                     elem, strict, sub_strict, addr_p, explain_p)
18670                   && (!goodfn || !same_type_p (goodfn, elem)))
18671                 {
18672                   goodfn = elem;
18673                   ++good;
18674                 }
18675             }
18676           else if (subargs)
18677             ++ok;
18678         }
18679       /* If no templates (or more than one) are fully resolved by the
18680          explicit arguments, this template-id is a non-deduced context; it
18681          could still be OK if we deduce all template arguments for the
18682          enclosing call through other arguments.  */
18683       if (good != 1)
18684         good = ok;
18685     }
18686   else if (TREE_CODE (arg) != OVERLOAD
18687            && TREE_CODE (arg) != FUNCTION_DECL)
18688     /* If ARG is, for example, "(0, &f)" then its type will be unknown
18689        -- but the deduction does not succeed because the expression is
18690        not just the function on its own.  */
18691     return false;
18692   else
18693     for (; arg; arg = OVL_NEXT (arg))
18694       if (try_one_overload (tparms, targs, tempargs, parm,
18695                             TREE_TYPE (OVL_CURRENT (arg)),
18696                             strict, sub_strict, addr_p, explain_p)
18697           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
18698         {
18699           goodfn = OVL_CURRENT (arg);
18700           ++good;
18701         }
18702
18703   /* [temp.deduct.type] A template-argument can be deduced from a pointer
18704      to function or pointer to member function argument if the set of
18705      overloaded functions does not contain function templates and at most
18706      one of a set of overloaded functions provides a unique match.
18707
18708      So if we found multiple possibilities, we return success but don't
18709      deduce anything.  */
18710
18711   if (good == 1)
18712     {
18713       int i = TREE_VEC_LENGTH (targs);
18714       for (; i--; )
18715         if (TREE_VEC_ELT (tempargs, i))
18716           {
18717             tree old = TREE_VEC_ELT (targs, i);
18718             tree new_ = TREE_VEC_ELT (tempargs, i);
18719             if (new_ && old && ARGUMENT_PACK_P (old)
18720                 && ARGUMENT_PACK_EXPLICIT_ARGS (old))
18721               /* Don't forget explicit template arguments in a pack.  */
18722               ARGUMENT_PACK_EXPLICIT_ARGS (new_)
18723                 = ARGUMENT_PACK_EXPLICIT_ARGS (old);
18724             TREE_VEC_ELT (targs, i) = new_;
18725           }
18726     }
18727   if (good)
18728     return true;
18729
18730   return false;
18731 }
18732
18733 /* Core DR 115: In contexts where deduction is done and fails, or in
18734    contexts where deduction is not done, if a template argument list is
18735    specified and it, along with any default template arguments, identifies
18736    a single function template specialization, then the template-id is an
18737    lvalue for the function template specialization.  */
18738
18739 tree
18740 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
18741 {
18742   tree expr, offset, baselink;
18743   bool addr;
18744
18745   if (!type_unknown_p (orig_expr))
18746     return orig_expr;
18747
18748   expr = orig_expr;
18749   addr = false;
18750   offset = NULL_TREE;
18751   baselink = NULL_TREE;
18752
18753   if (TREE_CODE (expr) == ADDR_EXPR)
18754     {
18755       expr = TREE_OPERAND (expr, 0);
18756       addr = true;
18757     }
18758   if (TREE_CODE (expr) == OFFSET_REF)
18759     {
18760       offset = expr;
18761       expr = TREE_OPERAND (expr, 1);
18762     }
18763   if (BASELINK_P (expr))
18764     {
18765       baselink = expr;
18766       expr = BASELINK_FUNCTIONS (expr);
18767     }
18768
18769   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
18770     {
18771       int good = 0;
18772       tree goodfn = NULL_TREE;
18773
18774       /* If we got some explicit template args, we need to plug them into
18775          the affected templates before we try to unify, in case the
18776          explicit args will completely resolve the templates in question.  */
18777
18778       tree expl_subargs = TREE_OPERAND (expr, 1);
18779       tree arg = TREE_OPERAND (expr, 0);
18780       tree badfn = NULL_TREE;
18781       tree badargs = NULL_TREE;
18782
18783       for (; arg; arg = OVL_NEXT (arg))
18784         {
18785           tree fn = OVL_CURRENT (arg);
18786           tree subargs, elem;
18787
18788           if (TREE_CODE (fn) != TEMPLATE_DECL)
18789             continue;
18790
18791           subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
18792                                            expl_subargs, NULL_TREE, tf_none,
18793                                            /*require_all_args=*/true,
18794                                            /*use_default_args=*/true);
18795           if (subargs != error_mark_node
18796               && !any_dependent_template_arguments_p (subargs))
18797             {
18798               elem = instantiate_template (fn, subargs, tf_none);
18799               if (elem == error_mark_node)
18800                 {
18801                   badfn = fn;
18802                   badargs = subargs;
18803                 }
18804               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
18805                 {
18806                   goodfn = elem;
18807                   ++good;
18808                 }
18809             }
18810         }
18811       if (good == 1)
18812         {
18813           mark_used (goodfn);
18814           expr = goodfn;
18815           if (baselink)
18816             expr = build_baselink (BASELINK_BINFO (baselink),
18817                                    BASELINK_ACCESS_BINFO (baselink),
18818                                    expr, BASELINK_OPTYPE (baselink));
18819           if (offset)
18820             {
18821               tree base
18822                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
18823               expr = build_offset_ref (base, expr, addr, complain);
18824             }
18825           if (addr)
18826             expr = cp_build_addr_expr (expr, complain);
18827           return expr;
18828         }
18829       else if (good == 0 && badargs && (complain & tf_error))
18830         /* There were no good options and at least one bad one, so let the
18831            user know what the problem is.  */
18832         instantiate_template (badfn, badargs, complain);
18833     }
18834   return orig_expr;
18835 }
18836
18837 /* Subroutine of resolve_overloaded_unification; does deduction for a single
18838    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
18839    different overloads deduce different arguments for a given parm.
18840    ADDR_P is true if the expression for which deduction is being
18841    performed was of the form "& fn" rather than simply "fn".
18842
18843    Returns 1 on success.  */
18844
18845 static int
18846 try_one_overload (tree tparms,
18847                   tree orig_targs,
18848                   tree targs,
18849                   tree parm,
18850                   tree arg,
18851                   unification_kind_t strict,
18852                   int sub_strict,
18853                   bool addr_p,
18854                   bool explain_p)
18855 {
18856   int nargs;
18857   tree tempargs;
18858   int i;
18859
18860   if (arg == error_mark_node)
18861     return 0;
18862
18863   /* [temp.deduct.type] A template-argument can be deduced from a pointer
18864      to function or pointer to member function argument if the set of
18865      overloaded functions does not contain function templates and at most
18866      one of a set of overloaded functions provides a unique match.
18867
18868      So if this is a template, just return success.  */
18869
18870   if (uses_template_parms (arg))
18871     return 1;
18872
18873   if (TREE_CODE (arg) == METHOD_TYPE)
18874     arg = build_ptrmemfunc_type (build_pointer_type (arg));
18875   else if (addr_p)
18876     arg = build_pointer_type (arg);
18877
18878   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
18879
18880   /* We don't copy orig_targs for this because if we have already deduced
18881      some template args from previous args, unify would complain when we
18882      try to deduce a template parameter for the same argument, even though
18883      there isn't really a conflict.  */
18884   nargs = TREE_VEC_LENGTH (targs);
18885   tempargs = make_tree_vec (nargs);
18886
18887   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
18888     return 0;
18889
18890   /* First make sure we didn't deduce anything that conflicts with
18891      explicitly specified args.  */
18892   for (i = nargs; i--; )
18893     {
18894       tree elt = TREE_VEC_ELT (tempargs, i);
18895       tree oldelt = TREE_VEC_ELT (orig_targs, i);
18896
18897       if (!elt)
18898         /*NOP*/;
18899       else if (uses_template_parms (elt))
18900         /* Since we're unifying against ourselves, we will fill in
18901            template args used in the function parm list with our own
18902            template parms.  Discard them.  */
18903         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
18904       else if (oldelt && ARGUMENT_PACK_P (oldelt))
18905         {
18906           /* Check that the argument at each index of the deduced argument pack
18907              is equivalent to the corresponding explicitly specified argument.
18908              We may have deduced more arguments than were explicitly specified,
18909              and that's OK.  */
18910           gcc_assert (ARGUMENT_PACK_INCOMPLETE_P (oldelt));
18911           gcc_assert (ARGUMENT_PACK_ARGS (oldelt)
18912                       == ARGUMENT_PACK_EXPLICIT_ARGS (oldelt));
18913
18914           tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
18915           tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
18916
18917           if (TREE_VEC_LENGTH (deduced_pack)
18918               < TREE_VEC_LENGTH (explicit_pack))
18919             return 0;
18920
18921           for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
18922             if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
18923                                       TREE_VEC_ELT (deduced_pack, j)))
18924               return 0;
18925         }
18926       else if (oldelt && !template_args_equal (oldelt, elt))
18927         return 0;
18928     }
18929
18930   for (i = nargs; i--; )
18931     {
18932       tree elt = TREE_VEC_ELT (tempargs, i);
18933
18934       if (elt)
18935         TREE_VEC_ELT (targs, i) = elt;
18936     }
18937
18938   return 1;
18939 }
18940
18941 /* PARM is a template class (perhaps with unbound template
18942    parameters).  ARG is a fully instantiated type.  If ARG can be
18943    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
18944    TARGS are as for unify.  */
18945
18946 static tree
18947 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
18948                        bool explain_p)
18949 {
18950   tree copy_of_targs;
18951
18952   if (!CLASSTYPE_TEMPLATE_INFO (arg)
18953       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
18954           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
18955     return NULL_TREE;
18956
18957   /* We need to make a new template argument vector for the call to
18958      unify.  If we used TARGS, we'd clutter it up with the result of
18959      the attempted unification, even if this class didn't work out.
18960      We also don't want to commit ourselves to all the unifications
18961      we've already done, since unification is supposed to be done on
18962      an argument-by-argument basis.  In other words, consider the
18963      following pathological case:
18964
18965        template <int I, int J, int K>
18966        struct S {};
18967
18968        template <int I, int J>
18969        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
18970
18971        template <int I, int J, int K>
18972        void f(S<I, J, K>, S<I, I, I>);
18973
18974        void g() {
18975          S<0, 0, 0> s0;
18976          S<0, 1, 2> s2;
18977
18978          f(s0, s2);
18979        }
18980
18981      Now, by the time we consider the unification involving `s2', we
18982      already know that we must have `f<0, 0, 0>'.  But, even though
18983      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
18984      because there are two ways to unify base classes of S<0, 1, 2>
18985      with S<I, I, I>.  If we kept the already deduced knowledge, we
18986      would reject the possibility I=1.  */
18987   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
18988
18989   /* If unification failed, we're done.  */
18990   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
18991              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
18992     return NULL_TREE;
18993
18994   return arg;
18995 }
18996
18997 /* Given a template type PARM and a class type ARG, find the unique
18998    base type in ARG that is an instance of PARM.  We do not examine
18999    ARG itself; only its base-classes.  If there is not exactly one
19000    appropriate base class, return NULL_TREE.  PARM may be the type of
19001    a partial specialization, as well as a plain template type.  Used
19002    by unify.  */
19003
19004 static enum template_base_result
19005 get_template_base (tree tparms, tree targs, tree parm, tree arg,
19006                    bool explain_p, tree *result)
19007 {
19008   tree rval = NULL_TREE;
19009   tree binfo;
19010
19011   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
19012
19013   binfo = TYPE_BINFO (complete_type (arg));
19014   if (!binfo)
19015     {
19016       /* The type could not be completed.  */
19017       *result = NULL_TREE;
19018       return tbr_incomplete_type;
19019     }
19020
19021   /* Walk in inheritance graph order.  The search order is not
19022      important, and this avoids multiple walks of virtual bases.  */
19023   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
19024     {
19025       tree r = try_class_unification (tparms, targs, parm,
19026                                       BINFO_TYPE (binfo), explain_p);
19027
19028       if (r)
19029         {
19030           /* If there is more than one satisfactory baseclass, then:
19031
19032                [temp.deduct.call]
19033
19034               If they yield more than one possible deduced A, the type
19035               deduction fails.
19036
19037              applies.  */
19038           if (rval && !same_type_p (r, rval))
19039             {
19040               *result = NULL_TREE;
19041               return tbr_ambiguous_baseclass;
19042             }
19043
19044           rval = r;
19045         }
19046     }
19047
19048   *result = rval;
19049   return tbr_success;
19050 }
19051
19052 /* Returns the level of DECL, which declares a template parameter.  */
19053
19054 static int
19055 template_decl_level (tree decl)
19056 {
19057   switch (TREE_CODE (decl))
19058     {
19059     case TYPE_DECL:
19060     case TEMPLATE_DECL:
19061       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
19062
19063     case PARM_DECL:
19064       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
19065
19066     default:
19067       gcc_unreachable ();
19068     }
19069   return 0;
19070 }
19071
19072 /* Decide whether ARG can be unified with PARM, considering only the
19073    cv-qualifiers of each type, given STRICT as documented for unify.
19074    Returns nonzero iff the unification is OK on that basis.  */
19075
19076 static int
19077 check_cv_quals_for_unify (int strict, tree arg, tree parm)
19078 {
19079   int arg_quals = cp_type_quals (arg);
19080   int parm_quals = cp_type_quals (parm);
19081
19082   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
19083       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
19084     {
19085       /*  Although a CVR qualifier is ignored when being applied to a
19086           substituted template parameter ([8.3.2]/1 for example), that
19087           does not allow us to unify "const T" with "int&" because both
19088           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
19089           It is ok when we're allowing additional CV qualifiers
19090           at the outer level [14.8.2.1]/3,1st bullet.  */
19091       if ((TREE_CODE (arg) == REFERENCE_TYPE
19092            || TREE_CODE (arg) == FUNCTION_TYPE
19093            || TREE_CODE (arg) == METHOD_TYPE)
19094           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
19095         return 0;
19096
19097       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
19098           && (parm_quals & TYPE_QUAL_RESTRICT))
19099         return 0;
19100     }
19101
19102   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
19103       && (arg_quals & parm_quals) != parm_quals)
19104     return 0;
19105
19106   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
19107       && (parm_quals & arg_quals) != arg_quals)
19108     return 0;
19109
19110   return 1;
19111 }
19112
19113 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
19114 void 
19115 template_parm_level_and_index (tree parm, int* level, int* index)
19116 {
19117   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
19118       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
19119       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
19120     {
19121       *index = TEMPLATE_TYPE_IDX (parm);
19122       *level = TEMPLATE_TYPE_LEVEL (parm);
19123     }
19124   else
19125     {
19126       *index = TEMPLATE_PARM_IDX (parm);
19127       *level = TEMPLATE_PARM_LEVEL (parm);
19128     }
19129 }
19130
19131 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)                    \
19132   do {                                                                  \
19133     if (unify (TP, TA, P, A, S, EP))                                    \
19134       return 1;                                                         \
19135   } while (0);
19136
19137 /* Unifies the remaining arguments in PACKED_ARGS with the pack
19138    expansion at the end of PACKED_PARMS. Returns 0 if the type
19139    deduction succeeds, 1 otherwise. STRICT is the same as in
19140    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
19141    call argument list. We'll need to adjust the arguments to make them
19142    types. SUBR tells us if this is from a recursive call to
19143    type_unification_real, or for comparing two template argument
19144    lists. */
19145
19146 static int
19147 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
19148                       tree packed_args, unification_kind_t strict,
19149                       bool subr, bool explain_p)
19150 {
19151   tree parm 
19152     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
19153   tree pattern = PACK_EXPANSION_PATTERN (parm);
19154   tree pack, packs = NULL_TREE;
19155   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
19156
19157   packed_args = expand_template_argument_pack (packed_args);
19158
19159   int len = TREE_VEC_LENGTH (packed_args);
19160
19161   /* Determine the parameter packs we will be deducing from the
19162      pattern, and record their current deductions.  */
19163   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
19164        pack; pack = TREE_CHAIN (pack))
19165     {
19166       tree parm_pack = TREE_VALUE (pack);
19167       int idx, level;
19168
19169       /* Determine the index and level of this parameter pack.  */
19170       template_parm_level_and_index (parm_pack, &level, &idx);
19171
19172       /* Keep track of the parameter packs and their corresponding
19173          argument packs.  */
19174       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
19175       TREE_TYPE (packs) = make_tree_vec (len - start);
19176     }
19177   
19178   /* Loop through all of the arguments that have not yet been
19179      unified and unify each with the pattern.  */
19180   for (i = start; i < len; i++)
19181     {
19182       tree parm;
19183       bool any_explicit = false;
19184       tree arg = TREE_VEC_ELT (packed_args, i);
19185
19186       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
19187          or the element of its argument pack at the current index if
19188          this argument was explicitly specified.  */
19189       for (pack = packs; pack; pack = TREE_CHAIN (pack))
19190         {
19191           int idx, level;
19192           tree arg, pargs;
19193           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
19194
19195           arg = NULL_TREE;
19196           if (TREE_VALUE (pack)
19197               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
19198               && (i - start < TREE_VEC_LENGTH (pargs)))
19199             {
19200               any_explicit = true;
19201               arg = TREE_VEC_ELT (pargs, i - start);
19202             }
19203           TMPL_ARG (targs, level, idx) = arg;
19204         }
19205
19206       /* If we had explicit template arguments, substitute them into the
19207          pattern before deduction.  */
19208       if (any_explicit)
19209         {
19210           /* Some arguments might still be unspecified or dependent.  */
19211           bool dependent;
19212           ++processing_template_decl;
19213           dependent = any_dependent_template_arguments_p (targs);
19214           if (!dependent)
19215             --processing_template_decl;
19216           parm = tsubst (pattern, targs,
19217                          explain_p ? tf_warning_or_error : tf_none,
19218                          NULL_TREE);
19219           if (dependent)
19220             --processing_template_decl;
19221           if (parm == error_mark_node)
19222             return 1;
19223         }
19224       else
19225         parm = pattern;
19226
19227       /* Unify the pattern with the current argument.  */
19228       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
19229                               explain_p))
19230         return 1;
19231
19232       /* For each parameter pack, collect the deduced value.  */
19233       for (pack = packs; pack; pack = TREE_CHAIN (pack))
19234         {
19235           int idx, level;
19236           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
19237
19238           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
19239             TMPL_ARG (targs, level, idx);
19240         }
19241     }
19242
19243   /* Verify that the results of unification with the parameter packs
19244      produce results consistent with what we've seen before, and make
19245      the deduced argument packs available.  */
19246   for (pack = packs; pack; pack = TREE_CHAIN (pack))
19247     {
19248       tree old_pack = TREE_VALUE (pack);
19249       tree new_args = TREE_TYPE (pack);
19250       int i, len = TREE_VEC_LENGTH (new_args);
19251       int idx, level;
19252       bool nondeduced_p = false;
19253
19254       /* By default keep the original deduced argument pack.
19255          If necessary, more specific code is going to update the
19256          resulting deduced argument later down in this function.  */
19257       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
19258       TMPL_ARG (targs, level, idx) = old_pack;
19259
19260       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
19261          actually deduce anything.  */
19262       for (i = 0; i < len && !nondeduced_p; ++i)
19263         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
19264           nondeduced_p = true;
19265       if (nondeduced_p)
19266         continue;
19267
19268       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
19269         {
19270           /* If we had fewer function args than explicit template args,
19271              just use the explicits.  */
19272           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
19273           int explicit_len = TREE_VEC_LENGTH (explicit_args);
19274           if (len < explicit_len)
19275             new_args = explicit_args;
19276         }
19277
19278       if (!old_pack)
19279         {
19280           tree result;
19281           /* Build the deduced *_ARGUMENT_PACK.  */
19282           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
19283             {
19284               result = make_node (NONTYPE_ARGUMENT_PACK);
19285               TREE_TYPE (result) = 
19286                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
19287               TREE_CONSTANT (result) = 1;
19288             }
19289           else
19290             result = cxx_make_type (TYPE_ARGUMENT_PACK);
19291
19292           SET_ARGUMENT_PACK_ARGS (result, new_args);
19293
19294           /* Note the deduced argument packs for this parameter
19295              pack.  */
19296           TMPL_ARG (targs, level, idx) = result;
19297         }
19298       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
19299                && (ARGUMENT_PACK_ARGS (old_pack) 
19300                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
19301         {
19302           /* We only had the explicitly-provided arguments before, but
19303              now we have a complete set of arguments.  */
19304           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
19305
19306           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
19307           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
19308           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
19309         }
19310       else
19311         {
19312           tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
19313           tree old_args = ARGUMENT_PACK_ARGS (old_pack);
19314
19315           if (!comp_template_args (old_args, new_args,
19316                                    &bad_old_arg, &bad_new_arg))
19317             /* Inconsistent unification of this parameter pack.  */
19318             return unify_parameter_pack_inconsistent (explain_p,
19319                                                       bad_old_arg,
19320                                                       bad_new_arg);
19321         }
19322     }
19323
19324   return unify_success (explain_p);
19325 }
19326
19327 /* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
19328    INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
19329    parameters and return value are as for unify.  */
19330
19331 static int
19332 unify_array_domain (tree tparms, tree targs,
19333                     tree parm_dom, tree arg_dom,
19334                     bool explain_p)
19335 {
19336   tree parm_max;
19337   tree arg_max;
19338   bool parm_cst;
19339   bool arg_cst;
19340
19341   /* Our representation of array types uses "N - 1" as the
19342      TYPE_MAX_VALUE for an array with "N" elements, if "N" is
19343      not an integer constant.  We cannot unify arbitrarily
19344      complex expressions, so we eliminate the MINUS_EXPRs
19345      here.  */
19346   parm_max = TYPE_MAX_VALUE (parm_dom);
19347   parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
19348   if (!parm_cst)
19349     {
19350       gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
19351       parm_max = TREE_OPERAND (parm_max, 0);
19352     }
19353   arg_max = TYPE_MAX_VALUE (arg_dom);
19354   arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
19355   if (!arg_cst)
19356     {
19357       /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
19358          trying to unify the type of a variable with the type
19359          of a template parameter.  For example:
19360
19361            template <unsigned int N>
19362            void f (char (&) [N]);
19363            int g();
19364            void h(int i) {
19365              char a[g(i)];
19366              f(a);
19367            }
19368
19369          Here, the type of the ARG will be "int [g(i)]", and
19370          may be a SAVE_EXPR, etc.  */
19371       if (TREE_CODE (arg_max) != MINUS_EXPR)
19372         return unify_vla_arg (explain_p, arg_dom);
19373       arg_max = TREE_OPERAND (arg_max, 0);
19374     }
19375
19376   /* If only one of the bounds used a MINUS_EXPR, compensate
19377      by adding one to the other bound.  */
19378   if (parm_cst && !arg_cst)
19379     parm_max = fold_build2_loc (input_location, PLUS_EXPR,
19380                                 integer_type_node,
19381                                 parm_max,
19382                                 integer_one_node);
19383   else if (arg_cst && !parm_cst)
19384     arg_max = fold_build2_loc (input_location, PLUS_EXPR,
19385                                integer_type_node,
19386                                arg_max,
19387                                integer_one_node);
19388
19389   return unify (tparms, targs, parm_max, arg_max,
19390                 UNIFY_ALLOW_INTEGER, explain_p);
19391 }
19392
19393 /* Deduce the value of template parameters.  TPARMS is the (innermost)
19394    set of template parameters to a template.  TARGS is the bindings
19395    for those template parameters, as determined thus far; TARGS may
19396    include template arguments for outer levels of template parameters
19397    as well.  PARM is a parameter to a template function, or a
19398    subcomponent of that parameter; ARG is the corresponding argument.
19399    This function attempts to match PARM with ARG in a manner
19400    consistent with the existing assignments in TARGS.  If more values
19401    are deduced, then TARGS is updated.
19402
19403    Returns 0 if the type deduction succeeds, 1 otherwise.  The
19404    parameter STRICT is a bitwise or of the following flags:
19405
19406      UNIFY_ALLOW_NONE:
19407        Require an exact match between PARM and ARG.
19408      UNIFY_ALLOW_MORE_CV_QUAL:
19409        Allow the deduced ARG to be more cv-qualified (by qualification
19410        conversion) than ARG.
19411      UNIFY_ALLOW_LESS_CV_QUAL:
19412        Allow the deduced ARG to be less cv-qualified than ARG.
19413      UNIFY_ALLOW_DERIVED:
19414        Allow the deduced ARG to be a template base class of ARG,
19415        or a pointer to a template base class of the type pointed to by
19416        ARG.
19417      UNIFY_ALLOW_INTEGER:
19418        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
19419        case for more information.
19420      UNIFY_ALLOW_OUTER_LEVEL:
19421        This is the outermost level of a deduction. Used to determine validity
19422        of qualification conversions. A valid qualification conversion must
19423        have const qualified pointers leading up to the inner type which
19424        requires additional CV quals, except at the outer level, where const
19425        is not required [conv.qual]. It would be normal to set this flag in
19426        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
19427      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
19428        This is the outermost level of a deduction, and PARM can be more CV
19429        qualified at this point.
19430      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
19431        This is the outermost level of a deduction, and PARM can be less CV
19432        qualified at this point.  */
19433
19434 static int
19435 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
19436        bool explain_p)
19437 {
19438   int idx;
19439   tree targ;
19440   tree tparm;
19441   int strict_in = strict;
19442
19443   /* I don't think this will do the right thing with respect to types.
19444      But the only case I've seen it in so far has been array bounds, where
19445      signedness is the only information lost, and I think that will be
19446      okay.  */
19447   while (TREE_CODE (parm) == NOP_EXPR)
19448     parm = TREE_OPERAND (parm, 0);
19449
19450   if (arg == error_mark_node)
19451     return unify_invalid (explain_p);
19452   if (arg == unknown_type_node
19453       || arg == init_list_type_node)
19454     /* We can't deduce anything from this, but we might get all the
19455        template args from other function args.  */
19456     return unify_success (explain_p);
19457
19458   /* If PARM uses template parameters, then we can't bail out here,
19459      even if ARG == PARM, since we won't record unifications for the
19460      template parameters.  We might need them if we're trying to
19461      figure out which of two things is more specialized.  */
19462   if (arg == parm && !uses_template_parms (parm))
19463     return unify_success (explain_p);
19464
19465   /* Handle init lists early, so the rest of the function can assume
19466      we're dealing with a type. */
19467   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
19468     {
19469       tree elt, elttype;
19470       unsigned i;
19471       tree orig_parm = parm;
19472
19473       /* Replace T with std::initializer_list<T> for deduction.  */
19474       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
19475           && flag_deduce_init_list)
19476         parm = listify (parm);
19477
19478       if (!is_std_init_list (parm)
19479           && TREE_CODE (parm) != ARRAY_TYPE)
19480         /* We can only deduce from an initializer list argument if the
19481            parameter is std::initializer_list or an array; otherwise this
19482            is a non-deduced context. */
19483         return unify_success (explain_p);
19484
19485       if (TREE_CODE (parm) == ARRAY_TYPE)
19486         elttype = TREE_TYPE (parm);
19487       else
19488         {
19489           elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
19490           /* Deduction is defined in terms of a single type, so just punt
19491              on the (bizarre) std::initializer_list<T...>.  */
19492           if (PACK_EXPANSION_P (elttype))
19493             return unify_success (explain_p);
19494         }
19495
19496       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
19497         {
19498           int elt_strict = strict;
19499
19500           if (elt == error_mark_node)
19501             return unify_invalid (explain_p);
19502
19503           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
19504             {
19505               tree type = TREE_TYPE (elt);
19506               if (type == error_mark_node)
19507                 return unify_invalid (explain_p);
19508               /* It should only be possible to get here for a call.  */
19509               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
19510               elt_strict |= maybe_adjust_types_for_deduction
19511                 (DEDUCE_CALL, &elttype, &type, elt);
19512               elt = type;
19513             }
19514
19515           RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
19516                                    explain_p);
19517         }
19518
19519       if (TREE_CODE (parm) == ARRAY_TYPE
19520           && deducible_array_bound (TYPE_DOMAIN (parm)))
19521         {
19522           /* Also deduce from the length of the initializer list.  */
19523           tree max = size_int (CONSTRUCTOR_NELTS (arg));
19524           tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
19525           if (idx == error_mark_node)
19526             return unify_invalid (explain_p);
19527           return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
19528                                      idx, explain_p);
19529         }
19530
19531       /* If the std::initializer_list<T> deduction worked, replace the
19532          deduced A with std::initializer_list<A>.  */
19533       if (orig_parm != parm)
19534         {
19535           idx = TEMPLATE_TYPE_IDX (orig_parm);
19536           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
19537           targ = listify (targ);
19538           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
19539         }
19540       return unify_success (explain_p);
19541     }
19542
19543   /* Immediately reject some pairs that won't unify because of
19544      cv-qualification mismatches.  */
19545   if (TREE_CODE (arg) == TREE_CODE (parm)
19546       && TYPE_P (arg)
19547       /* It is the elements of the array which hold the cv quals of an array
19548          type, and the elements might be template type parms. We'll check
19549          when we recurse.  */
19550       && TREE_CODE (arg) != ARRAY_TYPE
19551       /* We check the cv-qualifiers when unifying with template type
19552          parameters below.  We want to allow ARG `const T' to unify with
19553          PARM `T' for example, when computing which of two templates
19554          is more specialized, for example.  */
19555       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
19556       && !check_cv_quals_for_unify (strict_in, arg, parm))
19557     return unify_cv_qual_mismatch (explain_p, parm, arg);
19558
19559   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
19560       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
19561     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
19562   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
19563   strict &= ~UNIFY_ALLOW_DERIVED;
19564   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
19565   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
19566
19567   switch (TREE_CODE (parm))
19568     {
19569     case TYPENAME_TYPE:
19570     case SCOPE_REF:
19571     case UNBOUND_CLASS_TEMPLATE:
19572       /* In a type which contains a nested-name-specifier, template
19573          argument values cannot be deduced for template parameters used
19574          within the nested-name-specifier.  */
19575       return unify_success (explain_p);
19576
19577     case TEMPLATE_TYPE_PARM:
19578     case TEMPLATE_TEMPLATE_PARM:
19579     case BOUND_TEMPLATE_TEMPLATE_PARM:
19580       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
19581       if (error_operand_p (tparm))
19582         return unify_invalid (explain_p);
19583
19584       if (TEMPLATE_TYPE_LEVEL (parm)
19585           != template_decl_level (tparm))
19586         /* The PARM is not one we're trying to unify.  Just check
19587            to see if it matches ARG.  */
19588         {
19589           if (TREE_CODE (arg) == TREE_CODE (parm)
19590               && (is_auto (parm) ? is_auto (arg)
19591                   : same_type_p (parm, arg)))
19592             return unify_success (explain_p);
19593           else
19594             return unify_type_mismatch (explain_p, parm, arg);
19595         }
19596       idx = TEMPLATE_TYPE_IDX (parm);
19597       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
19598       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
19599       if (error_operand_p (tparm))
19600         return unify_invalid (explain_p);
19601
19602       /* Check for mixed types and values.  */
19603       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
19604            && TREE_CODE (tparm) != TYPE_DECL)
19605           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
19606               && TREE_CODE (tparm) != TEMPLATE_DECL))
19607         gcc_unreachable ();
19608
19609       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
19610         {
19611           /* ARG must be constructed from a template class or a template
19612              template parameter.  */
19613           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
19614               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
19615             return unify_template_deduction_failure (explain_p, parm, arg);
19616           {
19617             tree parmvec = TYPE_TI_ARGS (parm);
19618             /* An alias template name is never deduced.  */
19619             if (TYPE_ALIAS_P (arg))
19620               arg = strip_typedefs (arg);
19621             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
19622             tree full_argvec = add_to_template_args (targs, argvec);
19623             tree parm_parms 
19624               = DECL_INNERMOST_TEMPLATE_PARMS
19625                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
19626             int i, len;
19627             int parm_variadic_p = 0;
19628
19629             /* The resolution to DR150 makes clear that default
19630                arguments for an N-argument may not be used to bind T
19631                to a template template parameter with fewer than N
19632                parameters.  It is not safe to permit the binding of
19633                default arguments as an extension, as that may change
19634                the meaning of a conforming program.  Consider:
19635
19636                   struct Dense { static const unsigned int dim = 1; };
19637
19638                   template <template <typename> class View,
19639                             typename Block>
19640                   void operator+(float, View<Block> const&);
19641
19642                   template <typename Block,
19643                             unsigned int Dim = Block::dim>
19644                   struct Lvalue_proxy { operator float() const; };
19645
19646                   void
19647                   test_1d (void) {
19648                     Lvalue_proxy<Dense> p;
19649                     float b;
19650                     b + p;
19651                   }
19652
19653               Here, if Lvalue_proxy is permitted to bind to View, then
19654               the global operator+ will be used; if they are not, the
19655               Lvalue_proxy will be converted to float.  */
19656             if (coerce_template_parms (parm_parms,
19657                                        full_argvec,
19658                                        TYPE_TI_TEMPLATE (parm),
19659                                        (explain_p
19660                                         ? tf_warning_or_error
19661                                         : tf_none),
19662                                        /*require_all_args=*/true,
19663                                        /*use_default_args=*/false)
19664                 == error_mark_node)
19665               return 1;
19666
19667             /* Deduce arguments T, i from TT<T> or TT<i>.
19668                We check each element of PARMVEC and ARGVEC individually
19669                rather than the whole TREE_VEC since they can have
19670                different number of elements.  */
19671
19672             parmvec = expand_template_argument_pack (parmvec);
19673             argvec = expand_template_argument_pack (argvec);
19674
19675             len = TREE_VEC_LENGTH (parmvec);
19676
19677             /* Check if the parameters end in a pack, making them
19678                variadic.  */
19679             if (len > 0
19680                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
19681               parm_variadic_p = 1;
19682             
19683              for (i = 0; i < len - parm_variadic_p; ++i)
19684                /* If the template argument list of P contains a pack
19685                   expansion that is not the last template argument, the
19686                   entire template argument list is a non-deduced
19687                   context.  */
19688                if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
19689                  return unify_success (explain_p);
19690
19691             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
19692               return unify_too_few_arguments (explain_p,
19693                                               TREE_VEC_LENGTH (argvec), len);
19694
19695              for (i = 0; i < len - parm_variadic_p; ++i)
19696               {
19697                 RECUR_AND_CHECK_FAILURE (tparms, targs,
19698                                          TREE_VEC_ELT (parmvec, i),
19699                                          TREE_VEC_ELT (argvec, i),
19700                                          UNIFY_ALLOW_NONE, explain_p);
19701               }
19702
19703             if (parm_variadic_p
19704                 && unify_pack_expansion (tparms, targs,
19705                                          parmvec, argvec,
19706                                          DEDUCE_EXACT,
19707                                          /*subr=*/true, explain_p))
19708               return 1;
19709           }
19710           arg = TYPE_TI_TEMPLATE (arg);
19711
19712           /* Fall through to deduce template name.  */
19713         }
19714
19715       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
19716           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
19717         {
19718           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
19719
19720           /* Simple cases: Value already set, does match or doesn't.  */
19721           if (targ != NULL_TREE && template_args_equal (targ, arg))
19722             return unify_success (explain_p);
19723           else if (targ)
19724             return unify_inconsistency (explain_p, parm, targ, arg);
19725         }
19726       else
19727         {
19728           /* If PARM is `const T' and ARG is only `int', we don't have
19729              a match unless we are allowing additional qualification.
19730              If ARG is `const int' and PARM is just `T' that's OK;
19731              that binds `const int' to `T'.  */
19732           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
19733                                          arg, parm))
19734             return unify_cv_qual_mismatch (explain_p, parm, arg);
19735
19736           /* Consider the case where ARG is `const volatile int' and
19737              PARM is `const T'.  Then, T should be `volatile int'.  */
19738           arg = cp_build_qualified_type_real
19739             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
19740           if (arg == error_mark_node)
19741             return unify_invalid (explain_p);
19742
19743           /* Simple cases: Value already set, does match or doesn't.  */
19744           if (targ != NULL_TREE && same_type_p (targ, arg))
19745             return unify_success (explain_p);
19746           else if (targ)
19747             return unify_inconsistency (explain_p, parm, targ, arg);
19748
19749           /* Make sure that ARG is not a variable-sized array.  (Note
19750              that were talking about variable-sized arrays (like
19751              `int[n]'), rather than arrays of unknown size (like
19752              `int[]').)  We'll get very confused by such a type since
19753              the bound of the array is not constant, and therefore
19754              not mangleable.  Besides, such types are not allowed in
19755              ISO C++, so we can do as we please here.  We do allow
19756              them for 'auto' deduction, since that isn't ABI-exposed.  */
19757           if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
19758             return unify_vla_arg (explain_p, arg);
19759
19760           /* Strip typedefs as in convert_template_argument.  */
19761           arg = canonicalize_type_argument (arg, tf_none);
19762         }
19763
19764       /* If ARG is a parameter pack or an expansion, we cannot unify
19765          against it unless PARM is also a parameter pack.  */
19766       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
19767           && !template_parameter_pack_p (parm))
19768         return unify_parameter_pack_mismatch (explain_p, parm, arg);
19769
19770       /* If the argument deduction results is a METHOD_TYPE,
19771          then there is a problem.
19772          METHOD_TYPE doesn't map to any real C++ type the result of
19773          the deduction can not be of that type.  */
19774       if (TREE_CODE (arg) == METHOD_TYPE)
19775         return unify_method_type_error (explain_p, arg);
19776
19777       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
19778       return unify_success (explain_p);
19779
19780     case TEMPLATE_PARM_INDEX:
19781       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
19782       if (error_operand_p (tparm))
19783         return unify_invalid (explain_p);
19784
19785       if (TEMPLATE_PARM_LEVEL (parm)
19786           != template_decl_level (tparm))
19787         {
19788           /* The PARM is not one we're trying to unify.  Just check
19789              to see if it matches ARG.  */
19790           int result = !(TREE_CODE (arg) == TREE_CODE (parm)
19791                          && cp_tree_equal (parm, arg));
19792           if (result)
19793             unify_expression_unequal (explain_p, parm, arg);
19794           return result;
19795         }
19796
19797       idx = TEMPLATE_PARM_IDX (parm);
19798       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
19799
19800       if (targ)
19801         {
19802           int x = !cp_tree_equal (targ, arg);
19803           if (x)
19804             unify_inconsistency (explain_p, parm, targ, arg);
19805           return x;
19806         }
19807
19808       /* [temp.deduct.type] If, in the declaration of a function template
19809          with a non-type template-parameter, the non-type
19810          template-parameter is used in an expression in the function
19811          parameter-list and, if the corresponding template-argument is
19812          deduced, the template-argument type shall match the type of the
19813          template-parameter exactly, except that a template-argument
19814          deduced from an array bound may be of any integral type.
19815          The non-type parameter might use already deduced type parameters.  */
19816       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
19817       if (!TREE_TYPE (arg))
19818         /* Template-parameter dependent expression.  Just accept it for now.
19819            It will later be processed in convert_template_argument.  */
19820         ;
19821       else if (same_type_p (TREE_TYPE (arg), tparm))
19822         /* OK */;
19823       else if ((strict & UNIFY_ALLOW_INTEGER)
19824                && CP_INTEGRAL_TYPE_P (tparm))
19825         /* Convert the ARG to the type of PARM; the deduced non-type
19826            template argument must exactly match the types of the
19827            corresponding parameter.  */
19828         arg = fold (build_nop (tparm, arg));
19829       else if (uses_template_parms (tparm))
19830         /* We haven't deduced the type of this parameter yet.  Try again
19831            later.  */
19832         return unify_success (explain_p);
19833       else
19834         return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
19835
19836       /* If ARG is a parameter pack or an expansion, we cannot unify
19837          against it unless PARM is also a parameter pack.  */
19838       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
19839           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
19840         return unify_parameter_pack_mismatch (explain_p, parm, arg);
19841
19842       {
19843         bool removed_attr = false;
19844         arg = strip_typedefs_expr (arg, &removed_attr);
19845       }
19846       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
19847       return unify_success (explain_p);
19848
19849     case PTRMEM_CST:
19850      {
19851         /* A pointer-to-member constant can be unified only with
19852          another constant.  */
19853       if (TREE_CODE (arg) != PTRMEM_CST)
19854         return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
19855
19856       /* Just unify the class member. It would be useless (and possibly
19857          wrong, depending on the strict flags) to unify also
19858          PTRMEM_CST_CLASS, because we want to be sure that both parm and
19859          arg refer to the same variable, even if through different
19860          classes. For instance:
19861
19862          struct A { int x; };
19863          struct B : A { };
19864
19865          Unification of &A::x and &B::x must succeed.  */
19866       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
19867                     PTRMEM_CST_MEMBER (arg), strict, explain_p);
19868      }
19869
19870     case POINTER_TYPE:
19871       {
19872         if (!TYPE_PTR_P (arg))
19873           return unify_type_mismatch (explain_p, parm, arg);
19874
19875         /* [temp.deduct.call]
19876
19877            A can be another pointer or pointer to member type that can
19878            be converted to the deduced A via a qualification
19879            conversion (_conv.qual_).
19880
19881            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
19882            This will allow for additional cv-qualification of the
19883            pointed-to types if appropriate.  */
19884
19885         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
19886           /* The derived-to-base conversion only persists through one
19887              level of pointers.  */
19888           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
19889
19890         return unify (tparms, targs, TREE_TYPE (parm),
19891                       TREE_TYPE (arg), strict, explain_p);
19892       }
19893
19894     case REFERENCE_TYPE:
19895       if (TREE_CODE (arg) != REFERENCE_TYPE)
19896         return unify_type_mismatch (explain_p, parm, arg);
19897       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
19898                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
19899
19900     case ARRAY_TYPE:
19901       if (TREE_CODE (arg) != ARRAY_TYPE)
19902         return unify_type_mismatch (explain_p, parm, arg);
19903       if ((TYPE_DOMAIN (parm) == NULL_TREE)
19904           != (TYPE_DOMAIN (arg) == NULL_TREE))
19905         return unify_type_mismatch (explain_p, parm, arg);
19906       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
19907                                strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
19908       if (TYPE_DOMAIN (parm) != NULL_TREE)
19909         return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
19910                                    TYPE_DOMAIN (arg), explain_p);
19911       return unify_success (explain_p);
19912
19913     case REAL_TYPE:
19914     case COMPLEX_TYPE:
19915     case VECTOR_TYPE:
19916     case INTEGER_TYPE:
19917     case BOOLEAN_TYPE:
19918     case ENUMERAL_TYPE:
19919     case VOID_TYPE:
19920     case NULLPTR_TYPE:
19921       if (TREE_CODE (arg) != TREE_CODE (parm))
19922         return unify_type_mismatch (explain_p, parm, arg);
19923
19924       /* We have already checked cv-qualification at the top of the
19925          function.  */
19926       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
19927         return unify_type_mismatch (explain_p, parm, arg);
19928
19929       /* As far as unification is concerned, this wins.  Later checks
19930          will invalidate it if necessary.  */
19931       return unify_success (explain_p);
19932
19933       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
19934       /* Type INTEGER_CST can come from ordinary constant template args.  */
19935     case INTEGER_CST:
19936       while (TREE_CODE (arg) == NOP_EXPR)
19937         arg = TREE_OPERAND (arg, 0);
19938
19939       if (TREE_CODE (arg) != INTEGER_CST)
19940         return unify_template_argument_mismatch (explain_p, parm, arg);
19941       return (tree_int_cst_equal (parm, arg)
19942               ? unify_success (explain_p)
19943               : unify_template_argument_mismatch (explain_p, parm, arg));
19944
19945     case TREE_VEC:
19946       {
19947         int i, len, argslen;
19948         int parm_variadic_p = 0;
19949
19950         if (TREE_CODE (arg) != TREE_VEC)
19951           return unify_template_argument_mismatch (explain_p, parm, arg);
19952
19953         len = TREE_VEC_LENGTH (parm);
19954         argslen = TREE_VEC_LENGTH (arg);
19955
19956         /* Check for pack expansions in the parameters.  */
19957         for (i = 0; i < len; ++i)
19958           {
19959             if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
19960               {
19961                 if (i == len - 1)
19962                   /* We can unify against something with a trailing
19963                      parameter pack.  */
19964                   parm_variadic_p = 1;
19965                 else
19966                   /* [temp.deduct.type]/9: If the template argument list of
19967                      P contains a pack expansion that is not the last
19968                      template argument, the entire template argument list
19969                      is a non-deduced context.  */
19970                   return unify_success (explain_p);
19971               }
19972           }
19973
19974         /* If we don't have enough arguments to satisfy the parameters
19975            (not counting the pack expression at the end), or we have
19976            too many arguments for a parameter list that doesn't end in
19977            a pack expression, we can't unify.  */
19978         if (parm_variadic_p
19979             ? argslen < len - parm_variadic_p
19980             : argslen != len)
19981           return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
19982
19983         /* Unify all of the parameters that precede the (optional)
19984            pack expression.  */
19985         for (i = 0; i < len - parm_variadic_p; ++i)
19986           {
19987             RECUR_AND_CHECK_FAILURE (tparms, targs,
19988                                      TREE_VEC_ELT (parm, i),
19989                                      TREE_VEC_ELT (arg, i),
19990                                      UNIFY_ALLOW_NONE, explain_p);
19991           }
19992         if (parm_variadic_p)
19993           return unify_pack_expansion (tparms, targs, parm, arg,
19994                                        DEDUCE_EXACT,
19995                                        /*subr=*/true, explain_p);
19996         return unify_success (explain_p);
19997       }
19998
19999     case RECORD_TYPE:
20000     case UNION_TYPE:
20001       if (TREE_CODE (arg) != TREE_CODE (parm))
20002         return unify_type_mismatch (explain_p, parm, arg);
20003
20004       if (TYPE_PTRMEMFUNC_P (parm))
20005         {
20006           if (!TYPE_PTRMEMFUNC_P (arg))
20007             return unify_type_mismatch (explain_p, parm, arg);
20008
20009           return unify (tparms, targs,
20010                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
20011                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
20012                         strict, explain_p);
20013         }
20014       else if (TYPE_PTRMEMFUNC_P (arg))
20015         return unify_type_mismatch (explain_p, parm, arg);
20016
20017       if (CLASSTYPE_TEMPLATE_INFO (parm))
20018         {
20019           tree t = NULL_TREE;
20020
20021           if (strict_in & UNIFY_ALLOW_DERIVED)
20022             {
20023               /* First, we try to unify the PARM and ARG directly.  */
20024               t = try_class_unification (tparms, targs,
20025                                          parm, arg, explain_p);
20026
20027               if (!t)
20028                 {
20029                   /* Fallback to the special case allowed in
20030                      [temp.deduct.call]:
20031
20032                        If P is a class, and P has the form
20033                        template-id, then A can be a derived class of
20034                        the deduced A.  Likewise, if P is a pointer to
20035                        a class of the form template-id, A can be a
20036                        pointer to a derived class pointed to by the
20037                        deduced A.  */
20038                   enum template_base_result r;
20039                   r = get_template_base (tparms, targs, parm, arg,
20040                                          explain_p, &t);
20041
20042                   if (!t)
20043                     {
20044                       /* Don't give the derived diagnostic if we're
20045                          already dealing with the same template.  */
20046                       bool same_template
20047                         = (CLASSTYPE_TEMPLATE_INFO (arg)
20048                            && (CLASSTYPE_TI_TEMPLATE (parm)
20049                                == CLASSTYPE_TI_TEMPLATE (arg)));
20050                       return unify_no_common_base (explain_p && !same_template,
20051                                                    r, parm, arg);
20052                     }
20053                 }
20054             }
20055           else if (CLASSTYPE_TEMPLATE_INFO (arg)
20056                    && (CLASSTYPE_TI_TEMPLATE (parm)
20057                        == CLASSTYPE_TI_TEMPLATE (arg)))
20058             /* Perhaps PARM is something like S<U> and ARG is S<int>.
20059                Then, we should unify `int' and `U'.  */
20060             t = arg;
20061           else
20062             /* There's no chance of unification succeeding.  */
20063             return unify_type_mismatch (explain_p, parm, arg);
20064
20065           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
20066                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
20067         }
20068       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
20069         return unify_type_mismatch (explain_p, parm, arg);
20070       return unify_success (explain_p);
20071
20072     case METHOD_TYPE:
20073     case FUNCTION_TYPE:
20074       {
20075         unsigned int nargs;
20076         tree *args;
20077         tree a;
20078         unsigned int i;
20079
20080         if (TREE_CODE (arg) != TREE_CODE (parm))
20081           return unify_type_mismatch (explain_p, parm, arg);
20082
20083         /* CV qualifications for methods can never be deduced, they must
20084            match exactly.  We need to check them explicitly here,
20085            because type_unification_real treats them as any other
20086            cv-qualified parameter.  */
20087         if (TREE_CODE (parm) == METHOD_TYPE
20088             && (!check_cv_quals_for_unify
20089                 (UNIFY_ALLOW_NONE,
20090                  class_of_this_parm (arg),
20091                  class_of_this_parm (parm))))
20092           return unify_cv_qual_mismatch (explain_p, parm, arg);
20093
20094         RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
20095                                  TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
20096
20097         nargs = list_length (TYPE_ARG_TYPES (arg));
20098         args = XALLOCAVEC (tree, nargs);
20099         for (a = TYPE_ARG_TYPES (arg), i = 0;
20100              a != NULL_TREE && a != void_list_node;
20101              a = TREE_CHAIN (a), ++i)
20102           args[i] = TREE_VALUE (a);
20103         nargs = i;
20104
20105         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
20106                                       args, nargs, 1, DEDUCE_EXACT,
20107                                       LOOKUP_NORMAL, NULL, explain_p);
20108       }
20109
20110     case OFFSET_TYPE:
20111       /* Unify a pointer to member with a pointer to member function, which
20112          deduces the type of the member as a function type. */
20113       if (TYPE_PTRMEMFUNC_P (arg))
20114         {
20115           /* Check top-level cv qualifiers */
20116           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
20117             return unify_cv_qual_mismatch (explain_p, parm, arg);
20118
20119           RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
20120                                    TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
20121                                    UNIFY_ALLOW_NONE, explain_p);
20122
20123           /* Determine the type of the function we are unifying against. */
20124           tree fntype = static_fn_type (arg);
20125
20126           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
20127         }
20128
20129       if (TREE_CODE (arg) != OFFSET_TYPE)
20130         return unify_type_mismatch (explain_p, parm, arg);
20131       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
20132                                TYPE_OFFSET_BASETYPE (arg),
20133                                UNIFY_ALLOW_NONE, explain_p);
20134       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
20135                     strict, explain_p);
20136
20137     case CONST_DECL:
20138       if (DECL_TEMPLATE_PARM_P (parm))
20139         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
20140       if (arg != scalar_constant_value (parm))
20141         return unify_template_argument_mismatch (explain_p, parm, arg);
20142       return unify_success (explain_p);
20143
20144     case FIELD_DECL:
20145     case TEMPLATE_DECL:
20146       /* Matched cases are handled by the ARG == PARM test above.  */
20147       return unify_template_argument_mismatch (explain_p, parm, arg);
20148
20149     case VAR_DECL:
20150       /* We might get a variable as a non-type template argument in parm if the
20151          corresponding parameter is type-dependent.  Make any necessary
20152          adjustments based on whether arg is a reference.  */
20153       if (CONSTANT_CLASS_P (arg))
20154         parm = fold_non_dependent_expr (parm);
20155       else if (REFERENCE_REF_P (arg))
20156         {
20157           tree sub = TREE_OPERAND (arg, 0);
20158           STRIP_NOPS (sub);
20159           if (TREE_CODE (sub) == ADDR_EXPR)
20160             arg = TREE_OPERAND (sub, 0);
20161         }
20162       /* Now use the normal expression code to check whether they match.  */
20163       goto expr;
20164
20165     case TYPE_ARGUMENT_PACK:
20166     case NONTYPE_ARGUMENT_PACK:
20167       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
20168                     ARGUMENT_PACK_ARGS (arg), strict, explain_p);
20169
20170     case TYPEOF_TYPE:
20171     case DECLTYPE_TYPE:
20172     case UNDERLYING_TYPE:
20173       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
20174          or UNDERLYING_TYPE nodes.  */
20175       return unify_success (explain_p);
20176
20177     case ERROR_MARK:
20178       /* Unification fails if we hit an error node.  */
20179       return unify_invalid (explain_p);
20180
20181     case INDIRECT_REF:
20182       if (REFERENCE_REF_P (parm))
20183         {
20184           if (REFERENCE_REF_P (arg))
20185             arg = TREE_OPERAND (arg, 0);
20186           return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
20187                         strict, explain_p);
20188         }
20189       /* FALLTHRU */
20190
20191     default:
20192       /* An unresolved overload is a nondeduced context.  */
20193       if (is_overloaded_fn (parm) || type_unknown_p (parm))
20194         return unify_success (explain_p);
20195       gcc_assert (EXPR_P (parm) || TREE_CODE (parm) == TRAIT_EXPR);
20196     expr:
20197       /* We must be looking at an expression.  This can happen with
20198          something like:
20199
20200            template <int I>
20201            void foo(S<I>, S<I + 2>);
20202
20203          This is a "nondeduced context":
20204
20205            [deduct.type]
20206
20207            The nondeduced contexts are:
20208
20209            --A type that is a template-id in which one or more of
20210              the template-arguments is an expression that references
20211              a template-parameter.
20212
20213          In these cases, we assume deduction succeeded, but don't
20214          actually infer any unifications.  */
20215
20216       if (!uses_template_parms (parm)
20217           && !template_args_equal (parm, arg))
20218         return unify_expression_unequal (explain_p, parm, arg);
20219       else
20220         return unify_success (explain_p);
20221     }
20222 }
20223 #undef RECUR_AND_CHECK_FAILURE
20224 \f
20225 /* Note that DECL can be defined in this translation unit, if
20226    required.  */
20227
20228 static void
20229 mark_definable (tree decl)
20230 {
20231   tree clone;
20232   DECL_NOT_REALLY_EXTERN (decl) = 1;
20233   FOR_EACH_CLONE (clone, decl)
20234     DECL_NOT_REALLY_EXTERN (clone) = 1;
20235 }
20236
20237 /* Called if RESULT is explicitly instantiated, or is a member of an
20238    explicitly instantiated class.  */
20239
20240 void
20241 mark_decl_instantiated (tree result, int extern_p)
20242 {
20243   SET_DECL_EXPLICIT_INSTANTIATION (result);
20244
20245   /* If this entity has already been written out, it's too late to
20246      make any modifications.  */
20247   if (TREE_ASM_WRITTEN (result))
20248     return;
20249
20250   /* For anonymous namespace we don't need to do anything.  */
20251   if (decl_anon_ns_mem_p (result))
20252     {
20253       gcc_assert (!TREE_PUBLIC (result));
20254       return;
20255     }
20256
20257   if (TREE_CODE (result) != FUNCTION_DECL)
20258     /* The TREE_PUBLIC flag for function declarations will have been
20259        set correctly by tsubst.  */
20260     TREE_PUBLIC (result) = 1;
20261
20262   /* This might have been set by an earlier implicit instantiation.  */
20263   DECL_COMDAT (result) = 0;
20264
20265   if (extern_p)
20266     DECL_NOT_REALLY_EXTERN (result) = 0;
20267   else
20268     {
20269       mark_definable (result);
20270       mark_needed (result);
20271       /* Always make artificials weak.  */
20272       if (DECL_ARTIFICIAL (result) && flag_weak)
20273         comdat_linkage (result);
20274       /* For WIN32 we also want to put explicit instantiations in
20275          linkonce sections.  */
20276       else if (TREE_PUBLIC (result))
20277         maybe_make_one_only (result);
20278     }
20279
20280   /* If EXTERN_P, then this function will not be emitted -- unless
20281      followed by an explicit instantiation, at which point its linkage
20282      will be adjusted.  If !EXTERN_P, then this function will be
20283      emitted here.  In neither circumstance do we want
20284      import_export_decl to adjust the linkage.  */
20285   DECL_INTERFACE_KNOWN (result) = 1;
20286 }
20287
20288 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
20289    important template arguments.  If any are missing, we check whether
20290    they're important by using error_mark_node for substituting into any
20291    args that were used for partial ordering (the ones between ARGS and END)
20292    and seeing if it bubbles up.  */
20293
20294 static bool
20295 check_undeduced_parms (tree targs, tree args, tree end)
20296 {
20297   bool found = false;
20298   int i;
20299   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
20300     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
20301       {
20302         found = true;
20303         TREE_VEC_ELT (targs, i) = error_mark_node;
20304       }
20305   if (found)
20306     {
20307       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
20308       if (substed == error_mark_node)
20309         return true;
20310     }
20311   return false;
20312 }
20313
20314 /* Given two function templates PAT1 and PAT2, return:
20315
20316    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
20317    -1 if PAT2 is more specialized than PAT1.
20318    0 if neither is more specialized.
20319
20320    LEN indicates the number of parameters we should consider
20321    (defaulted parameters should not be considered).
20322
20323    The 1998 std underspecified function template partial ordering, and
20324    DR214 addresses the issue.  We take pairs of arguments, one from
20325    each of the templates, and deduce them against each other.  One of
20326    the templates will be more specialized if all the *other*
20327    template's arguments deduce against its arguments and at least one
20328    of its arguments *does* *not* deduce against the other template's
20329    corresponding argument.  Deduction is done as for class templates.
20330    The arguments used in deduction have reference and top level cv
20331    qualifiers removed.  Iff both arguments were originally reference
20332    types *and* deduction succeeds in both directions, an lvalue reference
20333    wins against an rvalue reference and otherwise the template
20334    with the more cv-qualified argument wins for that pairing (if
20335    neither is more cv-qualified, they both are equal).  Unlike regular
20336    deduction, after all the arguments have been deduced in this way,
20337    we do *not* verify the deduced template argument values can be
20338    substituted into non-deduced contexts.
20339
20340    The logic can be a bit confusing here, because we look at deduce1 and
20341    targs1 to see if pat2 is at least as specialized, and vice versa; if we
20342    can find template arguments for pat1 to make arg1 look like arg2, that
20343    means that arg2 is at least as specialized as arg1.  */
20344
20345 int
20346 more_specialized_fn (tree pat1, tree pat2, int len)
20347 {
20348   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
20349   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
20350   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
20351   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
20352   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
20353   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
20354   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
20355   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
20356   tree origs1, origs2;
20357   bool lose1 = false;
20358   bool lose2 = false;
20359
20360   /* Remove the this parameter from non-static member functions.  If
20361      one is a non-static member function and the other is not a static
20362      member function, remove the first parameter from that function
20363      also.  This situation occurs for operator functions where we
20364      locate both a member function (with this pointer) and non-member
20365      operator (with explicit first operand).  */
20366   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
20367     {
20368       len--; /* LEN is the number of significant arguments for DECL1 */
20369       args1 = TREE_CHAIN (args1);
20370       if (!DECL_STATIC_FUNCTION_P (decl2))
20371         args2 = TREE_CHAIN (args2);
20372     }
20373   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
20374     {
20375       args2 = TREE_CHAIN (args2);
20376       if (!DECL_STATIC_FUNCTION_P (decl1))
20377         {
20378           len--;
20379           args1 = TREE_CHAIN (args1);
20380         }
20381     }
20382
20383   /* If only one is a conversion operator, they are unordered.  */
20384   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
20385     return 0;
20386
20387   /* Consider the return type for a conversion function */
20388   if (DECL_CONV_FN_P (decl1))
20389     {
20390       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
20391       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
20392       len++;
20393     }
20394
20395   processing_template_decl++;
20396
20397   origs1 = args1;
20398   origs2 = args2;
20399
20400   while (len--
20401          /* Stop when an ellipsis is seen.  */
20402          && args1 != NULL_TREE && args2 != NULL_TREE)
20403     {
20404       tree arg1 = TREE_VALUE (args1);
20405       tree arg2 = TREE_VALUE (args2);
20406       int deduce1, deduce2;
20407       int quals1 = -1;
20408       int quals2 = -1;
20409       int ref1 = 0;
20410       int ref2 = 0;
20411
20412       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
20413           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
20414         {
20415           /* When both arguments are pack expansions, we need only
20416              unify the patterns themselves.  */
20417           arg1 = PACK_EXPANSION_PATTERN (arg1);
20418           arg2 = PACK_EXPANSION_PATTERN (arg2);
20419
20420           /* This is the last comparison we need to do.  */
20421           len = 0;
20422         }
20423
20424       if (TREE_CODE (arg1) == REFERENCE_TYPE)
20425         {
20426           ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
20427           arg1 = TREE_TYPE (arg1);
20428           quals1 = cp_type_quals (arg1);
20429         }
20430
20431       if (TREE_CODE (arg2) == REFERENCE_TYPE)
20432         {
20433           ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
20434           arg2 = TREE_TYPE (arg2);
20435           quals2 = cp_type_quals (arg2);
20436         }
20437
20438       arg1 = TYPE_MAIN_VARIANT (arg1);
20439       arg2 = TYPE_MAIN_VARIANT (arg2);
20440
20441       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
20442         {
20443           int i, len2 = remaining_arguments (args2);
20444           tree parmvec = make_tree_vec (1);
20445           tree argvec = make_tree_vec (len2);
20446           tree ta = args2;
20447
20448           /* Setup the parameter vector, which contains only ARG1.  */
20449           TREE_VEC_ELT (parmvec, 0) = arg1;
20450
20451           /* Setup the argument vector, which contains the remaining
20452              arguments.  */
20453           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
20454             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
20455
20456           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
20457                                            argvec, DEDUCE_EXACT,
20458                                            /*subr=*/true, /*explain_p=*/false)
20459                      == 0);
20460
20461           /* We cannot deduce in the other direction, because ARG1 is
20462              a pack expansion but ARG2 is not.  */
20463           deduce2 = 0;
20464         }
20465       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
20466         {
20467           int i, len1 = remaining_arguments (args1);
20468           tree parmvec = make_tree_vec (1);
20469           tree argvec = make_tree_vec (len1);
20470           tree ta = args1;
20471
20472           /* Setup the parameter vector, which contains only ARG1.  */
20473           TREE_VEC_ELT (parmvec, 0) = arg2;
20474
20475           /* Setup the argument vector, which contains the remaining
20476              arguments.  */
20477           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
20478             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
20479
20480           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
20481                                            argvec, DEDUCE_EXACT,
20482                                            /*subr=*/true, /*explain_p=*/false)
20483                      == 0);
20484
20485           /* We cannot deduce in the other direction, because ARG2 is
20486              a pack expansion but ARG1 is not.*/
20487           deduce1 = 0;
20488         }
20489
20490       else
20491         {
20492           /* The normal case, where neither argument is a pack
20493              expansion.  */
20494           deduce1 = (unify (tparms1, targs1, arg1, arg2,
20495                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
20496                      == 0);
20497           deduce2 = (unify (tparms2, targs2, arg2, arg1,
20498                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
20499                      == 0);
20500         }
20501
20502       /* If we couldn't deduce arguments for tparms1 to make arg1 match
20503          arg2, then arg2 is not as specialized as arg1.  */
20504       if (!deduce1)
20505         lose2 = true;
20506       if (!deduce2)
20507         lose1 = true;
20508
20509       /* "If, for a given type, deduction succeeds in both directions
20510          (i.e., the types are identical after the transformations above)
20511          and both P and A were reference types (before being replaced with
20512          the type referred to above):
20513          - if the type from the argument template was an lvalue reference and
20514          the type from the parameter template was not, the argument type is
20515          considered to be more specialized than the other; otherwise,
20516          - if the type from the argument template is more cv-qualified
20517          than the type from the parameter template (as described above),
20518          the argument type is considered to be more specialized than the other;
20519          otherwise,
20520          - neither type is more specialized than the other."  */
20521
20522       if (deduce1 && deduce2)
20523         {
20524           if (ref1 && ref2 && ref1 != ref2)
20525             {
20526               if (ref1 > ref2)
20527                 lose1 = true;
20528               else
20529                 lose2 = true;
20530             }
20531           else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
20532             {
20533               if ((quals1 & quals2) == quals2)
20534                 lose2 = true;
20535               if ((quals1 & quals2) == quals1)
20536                 lose1 = true;
20537             }
20538         }
20539
20540       if (lose1 && lose2)
20541         /* We've failed to deduce something in either direction.
20542            These must be unordered.  */
20543         break;
20544
20545       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
20546           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
20547         /* We have already processed all of the arguments in our
20548            handing of the pack expansion type.  */
20549         len = 0;
20550
20551       args1 = TREE_CHAIN (args1);
20552       args2 = TREE_CHAIN (args2);
20553     }
20554
20555   /* "In most cases, all template parameters must have values in order for
20556      deduction to succeed, but for partial ordering purposes a template
20557      parameter may remain without a value provided it is not used in the
20558      types being used for partial ordering."
20559
20560      Thus, if we are missing any of the targs1 we need to substitute into
20561      origs1, then pat2 is not as specialized as pat1.  This can happen when
20562      there is a nondeduced context.  */
20563   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
20564     lose2 = true;
20565   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
20566     lose1 = true;
20567
20568   processing_template_decl--;
20569
20570   /* If both deductions succeed, the partial ordering selects the more
20571      constrained template.  */
20572   if (!lose1 && !lose2)
20573     {
20574       tree c1 = get_constraints (DECL_TEMPLATE_RESULT (pat1));
20575       tree c2 = get_constraints (DECL_TEMPLATE_RESULT (pat2));
20576       lose1 = !subsumes_constraints (c1, c2);
20577       lose2 = !subsumes_constraints (c2, c1);
20578     }
20579
20580   /* All things being equal, if the next argument is a pack expansion
20581      for one function but not for the other, prefer the
20582      non-variadic function.  FIXME this is bogus; see c++/41958.  */
20583   if (lose1 == lose2
20584       && args1 && TREE_VALUE (args1)
20585       && args2 && TREE_VALUE (args2))
20586     {
20587       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
20588       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
20589     }
20590
20591   if (lose1 == lose2)
20592     return 0;
20593   else if (!lose1)
20594     return 1;
20595   else
20596     return -1;
20597 }
20598
20599 /* Determine which of two partial specializations of TMPL is more
20600    specialized.
20601
20602    PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
20603    to the first partial specialization.  The TREE_PURPOSE is the
20604    innermost set of template parameters for the partial
20605    specialization.  PAT2 is similar, but for the second template.
20606
20607    Return 1 if the first partial specialization is more specialized;
20608    -1 if the second is more specialized; 0 if neither is more
20609    specialized.
20610
20611    See [temp.class.order] for information about determining which of
20612    two templates is more specialized.  */
20613
20614 static int
20615 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
20616 {
20617   tree targs;
20618   int winner = 0;
20619   bool any_deductions = false;
20620
20621   tree tmpl1 = TREE_VALUE (pat1);
20622   tree tmpl2 = TREE_VALUE (pat2);
20623   tree parms1 = DECL_INNERMOST_TEMPLATE_PARMS (tmpl1);
20624   tree parms2 = DECL_INNERMOST_TEMPLATE_PARMS (tmpl2);
20625   tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
20626   tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
20627
20628   /* Just like what happens for functions, if we are ordering between
20629      different template specializations, we may encounter dependent
20630      types in the arguments, and we need our dependency check functions
20631      to behave correctly.  */
20632   ++processing_template_decl;
20633   targs = get_partial_spec_bindings (tmpl, parms1, specargs1, specargs2);
20634   if (targs)
20635     {
20636       --winner;
20637       any_deductions = true;
20638     }
20639
20640   targs = get_partial_spec_bindings (tmpl, parms2, specargs2, specargs1);
20641   if (targs)
20642     {
20643       ++winner;
20644       any_deductions = true;
20645     }
20646   --processing_template_decl;
20647
20648   /* If both deductions succeed, the partial ordering selects the more
20649      constrained template.  */
20650   if (!winner && any_deductions)
20651     return more_constrained (tmpl1, tmpl2);
20652
20653   /* In the case of a tie where at least one of the templates
20654      has a parameter pack at the end, the template with the most
20655      non-packed parameters wins.  */
20656   if (winner == 0
20657       && any_deductions
20658       && (template_args_variadic_p (TREE_PURPOSE (pat1))
20659           || template_args_variadic_p (TREE_PURPOSE (pat2))))
20660     {
20661       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
20662       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
20663       int len1 = TREE_VEC_LENGTH (args1);
20664       int len2 = TREE_VEC_LENGTH (args2);
20665
20666       /* We don't count the pack expansion at the end.  */
20667       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
20668         --len1;
20669       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
20670         --len2;
20671
20672       if (len1 > len2)
20673         return 1;
20674       else if (len1 < len2)
20675         return -1;
20676     }
20677
20678   return winner;
20679 }
20680
20681 /* Return the template arguments that will produce the function signature
20682    DECL from the function template FN, with the explicit template
20683    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
20684    also match.  Return NULL_TREE if no satisfactory arguments could be
20685    found.  */
20686
20687 static tree
20688 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
20689 {
20690   int ntparms = DECL_NTPARMS (fn);
20691   tree targs = make_tree_vec (ntparms);
20692   tree decl_type = TREE_TYPE (decl);
20693   tree decl_arg_types;
20694   tree *args;
20695   unsigned int nargs, ix;
20696   tree arg;
20697
20698   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
20699
20700   /* Never do unification on the 'this' parameter.  */
20701   decl_arg_types = skip_artificial_parms_for (decl, 
20702                                               TYPE_ARG_TYPES (decl_type));
20703
20704   nargs = list_length (decl_arg_types);
20705   args = XALLOCAVEC (tree, nargs);
20706   for (arg = decl_arg_types, ix = 0;
20707        arg != NULL_TREE && arg != void_list_node;
20708        arg = TREE_CHAIN (arg), ++ix)
20709     args[ix] = TREE_VALUE (arg);
20710
20711   if (fn_type_unification (fn, explicit_args, targs,
20712                            args, ix,
20713                            (check_rettype || DECL_CONV_FN_P (fn)
20714                             ? TREE_TYPE (decl_type) : NULL_TREE),
20715                            DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false,
20716                            /*decltype*/false)
20717       == error_mark_node)
20718     return NULL_TREE;
20719
20720   return targs;
20721 }
20722
20723 /* Return the innermost template arguments that, when applied to a partial
20724    specialization of TMPL whose innermost template parameters are
20725    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
20726    ARGS.
20727
20728    For example, suppose we have:
20729
20730      template <class T, class U> struct S {};
20731      template <class T> struct S<T*, int> {};
20732
20733    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
20734    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
20735    int}.  The resulting vector will be {double}, indicating that `T'
20736    is bound to `double'.  */
20737
20738 static tree
20739 get_partial_spec_bindings (tree tmpl, tree tparms, tree spec_args, tree args)
20740 {
20741   int i, ntparms = TREE_VEC_LENGTH (tparms);
20742   tree deduced_args;
20743   tree innermost_deduced_args;
20744
20745   innermost_deduced_args = make_tree_vec (ntparms);
20746   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
20747     {
20748       deduced_args = copy_node (args);
20749       SET_TMPL_ARGS_LEVEL (deduced_args,
20750                            TMPL_ARGS_DEPTH (deduced_args),
20751                            innermost_deduced_args);
20752     }
20753   else
20754     deduced_args = innermost_deduced_args;
20755
20756   if (unify (tparms, deduced_args,
20757              INNERMOST_TEMPLATE_ARGS (spec_args),
20758              INNERMOST_TEMPLATE_ARGS (args),
20759              UNIFY_ALLOW_NONE, /*explain_p=*/false))
20760     return NULL_TREE;
20761
20762   for (i =  0; i < ntparms; ++i)
20763     if (! TREE_VEC_ELT (innermost_deduced_args, i))
20764       return NULL_TREE;
20765
20766   /* Verify that nondeduced template arguments agree with the type
20767      obtained from argument deduction.
20768
20769      For example:
20770
20771        struct A { typedef int X; };
20772        template <class T, class U> struct C {};
20773        template <class T> struct C<T, typename T::X> {};
20774
20775      Then with the instantiation `C<A, int>', we can deduce that
20776      `T' is `A' but unify () does not check whether `typename T::X'
20777      is `int'.  */
20778   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
20779   spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
20780                                      spec_args, tmpl,
20781                                      tf_none, false, false);
20782   if (spec_args == error_mark_node
20783       /* We only need to check the innermost arguments; the other
20784          arguments will always agree.  */
20785       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
20786                               INNERMOST_TEMPLATE_ARGS (args)))
20787     return NULL_TREE;
20788
20789   /* Now that we have bindings for all of the template arguments,
20790      ensure that the arguments deduced for the template template
20791      parameters have compatible template parameter lists.  See the use
20792      of template_template_parm_bindings_ok_p in fn_type_unification
20793      for more information.  */
20794   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
20795     return NULL_TREE;
20796
20797   return deduced_args;
20798 }
20799
20800 // Compare two function templates T1 and T2 by deducing bindings
20801 // from one against the other. If both deductions succeed, compare
20802 // constraints to see which is more constrained.
20803 static int
20804 more_specialized_inst (tree t1, tree t2)
20805 {
20806   int fate = 0;
20807   int count = 0;
20808
20809   if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
20810     {
20811       --fate;
20812       ++count;
20813     }
20814
20815   if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
20816     {
20817       ++fate;
20818       ++count;
20819     }
20820
20821   // If both deductions succeed, then one may be more constrained.
20822   if (count == 2 && fate == 0)
20823     fate = more_constrained (t1, t2);
20824
20825   return fate;
20826 }
20827
20828 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
20829    Return the TREE_LIST node with the most specialized template, if
20830    any.  If there is no most specialized template, the error_mark_node
20831    is returned.
20832
20833    Note that this function does not look at, or modify, the
20834    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
20835    returned is one of the elements of INSTANTIATIONS, callers may
20836    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
20837    and retrieve it from the value returned.  */
20838
20839 tree
20840 most_specialized_instantiation (tree templates)
20841 {
20842   tree fn, champ;
20843
20844   ++processing_template_decl;
20845
20846   champ = templates;
20847   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
20848     {
20849       int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
20850       if (fate == -1)
20851         champ = fn;
20852       else if (!fate)
20853         {
20854           /* Equally specialized, move to next function.  If there
20855              is no next function, nothing's most specialized.  */
20856           fn = TREE_CHAIN (fn);
20857           champ = fn;
20858           if (!fn)
20859             break;
20860         }
20861     }
20862
20863   if (champ)
20864     /* Now verify that champ is better than everything earlier in the
20865        instantiation list.  */
20866     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
20867       if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
20868       {
20869         champ = NULL_TREE;
20870         break;
20871       }
20872     }
20873
20874   processing_template_decl--;
20875
20876   if (!champ)
20877     return error_mark_node;
20878
20879   return champ;
20880 }
20881
20882 /* If DECL is a specialization of some template, return the most
20883    general such template.  Otherwise, returns NULL_TREE.
20884
20885    For example, given:
20886
20887      template <class T> struct S { template <class U> void f(U); };
20888
20889    if TMPL is `template <class U> void S<int>::f(U)' this will return
20890    the full template.  This function will not trace past partial
20891    specializations, however.  For example, given in addition:
20892
20893      template <class T> struct S<T*> { template <class U> void f(U); };
20894
20895    if TMPL is `template <class U> void S<int*>::f(U)' this will return
20896    `template <class T> template <class U> S<T*>::f(U)'.  */
20897
20898 tree
20899 most_general_template (tree decl)
20900 {
20901   if (TREE_CODE (decl) != TEMPLATE_DECL)
20902     {
20903       if (tree tinfo = get_template_info (decl))
20904         decl = TI_TEMPLATE (tinfo);
20905       /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
20906          template friend, or a FIELD_DECL for a capture pack.  */
20907       if (TREE_CODE (decl) != TEMPLATE_DECL)
20908         return NULL_TREE;
20909     }
20910
20911   /* Look for more and more general templates.  */
20912   while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
20913     {
20914       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
20915          (See cp-tree.h for details.)  */
20916       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
20917         break;
20918
20919       if (CLASS_TYPE_P (TREE_TYPE (decl))
20920           && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
20921           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
20922         break;
20923
20924       /* Stop if we run into an explicitly specialized class template.  */
20925       if (!DECL_NAMESPACE_SCOPE_P (decl)
20926           && DECL_CONTEXT (decl)
20927           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
20928         break;
20929
20930       decl = DECL_TI_TEMPLATE (decl);
20931     }
20932
20933   return decl;
20934 }
20935
20936 /* Return the most specialized of the template partial specializations
20937    which can produce TARGET, a specialization of some class or variable
20938    template.  The value returned is actually a TREE_LIST; the TREE_VALUE is
20939    a TEMPLATE_DECL node corresponding to the partial specialization, while
20940    the TREE_PURPOSE is the set of template arguments that must be
20941    substituted into the template pattern in order to generate TARGET.
20942
20943    If the choice of partial specialization is ambiguous, a diagnostic
20944    is issued, and the error_mark_node is returned.  If there are no
20945    partial specializations matching TARGET, then NULL_TREE is
20946    returned, indicating that the primary template should be used.  */
20947
20948 static tree
20949 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
20950 {
20951   tree list = NULL_TREE;
20952   tree t;
20953   tree champ;
20954   int fate;
20955   bool ambiguous_p;
20956   tree outer_args = NULL_TREE;
20957   tree tmpl, args;
20958
20959   if (TYPE_P (target))
20960     {
20961       tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
20962       tmpl = TI_TEMPLATE (tinfo);
20963       args = TI_ARGS (tinfo);
20964     }
20965   else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
20966     {
20967       tmpl = TREE_OPERAND (target, 0);
20968       args = TREE_OPERAND (target, 1);
20969     }
20970   else if (VAR_P (target))
20971     {
20972       tree tinfo = DECL_TEMPLATE_INFO (target);
20973       tmpl = TI_TEMPLATE (tinfo);
20974       args = TI_ARGS (tinfo);
20975     }
20976   else
20977     gcc_unreachable ();
20978
20979   tree main_tmpl = most_general_template (tmpl);
20980
20981   /* For determining which partial specialization to use, only the
20982      innermost args are interesting.  */
20983   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
20984     {
20985       outer_args = strip_innermost_template_args (args, 1);
20986       args = INNERMOST_TEMPLATE_ARGS (args);
20987     }
20988
20989   for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
20990     {
20991       tree partial_spec_args;
20992       tree spec_args;
20993       tree spec_tmpl = TREE_VALUE (t);
20994
20995       partial_spec_args = TREE_PURPOSE (t);
20996
20997       ++processing_template_decl;
20998
20999       if (outer_args)
21000         {
21001           /* Discard the outer levels of args, and then substitute in the
21002              template args from the enclosing class.  */
21003           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
21004           partial_spec_args = tsubst_template_args
21005             (partial_spec_args, outer_args, tf_none, NULL_TREE);
21006
21007           /* And the same for the partial specialization TEMPLATE_DECL.  */
21008           spec_tmpl = tsubst (spec_tmpl, outer_args, tf_none, NULL_TREE);
21009         }
21010
21011       partial_spec_args =
21012           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
21013                                  partial_spec_args,
21014                                  tmpl, tf_none,
21015                                  /*require_all_args=*/true,
21016                                  /*use_default_args=*/true);
21017
21018       --processing_template_decl;
21019
21020       if (partial_spec_args == error_mark_node)
21021         return error_mark_node;
21022       if (spec_tmpl == error_mark_node)
21023         return error_mark_node;
21024
21025       tree parms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
21026       spec_args = get_partial_spec_bindings (tmpl, parms,
21027                                       partial_spec_args,
21028                                       args);
21029       if (spec_args)
21030         {
21031           if (outer_args)
21032             spec_args = add_to_template_args (outer_args, spec_args);
21033
21034           /* Keep the candidate only if the constraints are satisfied,
21035              or if we're not compiling with concepts.  */
21036           if (!flag_concepts
21037               || constraints_satisfied_p (spec_tmpl, spec_args))
21038             {
21039               list = tree_cons (spec_args, TREE_VALUE (t), list);
21040               TREE_TYPE (list) = TREE_TYPE (t);
21041             }
21042         }
21043     }
21044
21045   if (! list)
21046     return NULL_TREE;
21047
21048   ambiguous_p = false;
21049   t = list;
21050   champ = t;
21051   t = TREE_CHAIN (t);
21052   for (; t; t = TREE_CHAIN (t))
21053     {
21054       fate = more_specialized_partial_spec (tmpl, champ, t);
21055       if (fate == 1)
21056         ;
21057       else
21058         {
21059           if (fate == 0)
21060             {
21061               t = TREE_CHAIN (t);
21062               if (! t)
21063                 {
21064                   ambiguous_p = true;
21065                   break;
21066                 }
21067             }
21068           champ = t;
21069         }
21070     }
21071
21072   if (!ambiguous_p)
21073     for (t = list; t && t != champ; t = TREE_CHAIN (t))
21074       {
21075         fate = more_specialized_partial_spec (tmpl, champ, t);
21076         if (fate != 1)
21077           {
21078             ambiguous_p = true;
21079             break;
21080           }
21081       }
21082
21083   if (ambiguous_p)
21084     {
21085       const char *str;
21086       char *spaces = NULL;
21087       if (!(complain & tf_error))
21088         return error_mark_node;
21089       if (TYPE_P (target))
21090         error ("ambiguous template instantiation for %q#T", target);
21091       else
21092         error ("ambiguous template instantiation for %q#D", target);
21093       str = ngettext ("candidate is:", "candidates are:", list_length (list));
21094       for (t = list; t; t = TREE_CHAIN (t))
21095         {
21096           tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
21097           inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
21098                   "%s %#S", spaces ? spaces : str, subst);
21099           spaces = spaces ? spaces : get_spaces (str);
21100         }
21101       free (spaces);
21102       return error_mark_node;
21103     }
21104
21105   return champ;
21106 }
21107
21108 /* Explicitly instantiate DECL.  */
21109
21110 void
21111 do_decl_instantiation (tree decl, tree storage)
21112 {
21113   tree result = NULL_TREE;
21114   int extern_p = 0;
21115
21116   if (!decl || decl == error_mark_node)
21117     /* An error occurred, for which grokdeclarator has already issued
21118        an appropriate message.  */
21119     return;
21120   else if (! DECL_LANG_SPECIFIC (decl))
21121     {
21122       error ("explicit instantiation of non-template %q#D", decl);
21123       return;
21124     }
21125
21126   bool var_templ = (DECL_TEMPLATE_INFO (decl)
21127                     && variable_template_p (DECL_TI_TEMPLATE (decl)));
21128
21129   if (VAR_P (decl) && !var_templ)
21130     {
21131       /* There is an asymmetry here in the way VAR_DECLs and
21132          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
21133          the latter, the DECL we get back will be marked as a
21134          template instantiation, and the appropriate
21135          DECL_TEMPLATE_INFO will be set up.  This does not happen for
21136          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
21137          should handle VAR_DECLs as it currently handles
21138          FUNCTION_DECLs.  */
21139       if (!DECL_CLASS_SCOPE_P (decl))
21140         {
21141           error ("%qD is not a static data member of a class template", decl);
21142           return;
21143         }
21144       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
21145       if (!result || !VAR_P (result))
21146         {
21147           error ("no matching template for %qD found", decl);
21148           return;
21149         }
21150       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
21151         {
21152           error ("type %qT for explicit instantiation %qD does not match "
21153                  "declared type %qT", TREE_TYPE (result), decl,
21154                  TREE_TYPE (decl));
21155           return;
21156         }
21157     }
21158   else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
21159     {
21160       error ("explicit instantiation of %q#D", decl);
21161       return;
21162     }
21163   else
21164     result = decl;
21165
21166   /* Check for various error cases.  Note that if the explicit
21167      instantiation is valid the RESULT will currently be marked as an
21168      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
21169      until we get here.  */
21170
21171   if (DECL_TEMPLATE_SPECIALIZATION (result))
21172     {
21173       /* DR 259 [temp.spec].
21174
21175          Both an explicit instantiation and a declaration of an explicit
21176          specialization shall not appear in a program unless the explicit
21177          instantiation follows a declaration of the explicit specialization.
21178
21179          For a given set of template parameters, if an explicit
21180          instantiation of a template appears after a declaration of an
21181          explicit specialization for that template, the explicit
21182          instantiation has no effect.  */
21183       return;
21184     }
21185   else if (DECL_EXPLICIT_INSTANTIATION (result))
21186     {
21187       /* [temp.spec]
21188
21189          No program shall explicitly instantiate any template more
21190          than once.
21191
21192          We check DECL_NOT_REALLY_EXTERN so as not to complain when
21193          the first instantiation was `extern' and the second is not,
21194          and EXTERN_P for the opposite case.  */
21195       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
21196         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
21197       /* If an "extern" explicit instantiation follows an ordinary
21198          explicit instantiation, the template is instantiated.  */
21199       if (extern_p)
21200         return;
21201     }
21202   else if (!DECL_IMPLICIT_INSTANTIATION (result))
21203     {
21204       error ("no matching template for %qD found", result);
21205       return;
21206     }
21207   else if (!DECL_TEMPLATE_INFO (result))
21208     {
21209       permerror (input_location, "explicit instantiation of non-template %q#D", result);
21210       return;
21211     }
21212
21213   if (storage == NULL_TREE)
21214     ;
21215   else if (storage == ridpointers[(int) RID_EXTERN])
21216     {
21217       if (!in_system_header_at (input_location) && (cxx_dialect == cxx98))
21218         pedwarn (input_location, OPT_Wpedantic, 
21219                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
21220                  "instantiations");
21221       extern_p = 1;
21222     }
21223   else
21224     error ("storage class %qD applied to template instantiation", storage);
21225
21226   check_explicit_instantiation_namespace (result);
21227   mark_decl_instantiated (result, extern_p);
21228   if (! extern_p)
21229     instantiate_decl (result, /*defer_ok=*/1,
21230                       /*expl_inst_class_mem_p=*/false);
21231 }
21232
21233 static void
21234 mark_class_instantiated (tree t, int extern_p)
21235 {
21236   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
21237   SET_CLASSTYPE_INTERFACE_KNOWN (t);
21238   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
21239   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
21240   if (! extern_p)
21241     {
21242       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
21243       rest_of_type_compilation (t, 1);
21244     }
21245 }
21246
21247 /* Called from do_type_instantiation through binding_table_foreach to
21248    do recursive instantiation for the type bound in ENTRY.  */
21249 static void
21250 bt_instantiate_type_proc (binding_entry entry, void *data)
21251 {
21252   tree storage = *(tree *) data;
21253
21254   if (MAYBE_CLASS_TYPE_P (entry->type)
21255       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
21256     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
21257 }
21258
21259 /* Called from do_type_instantiation to instantiate a member
21260    (a member function or a static member variable) of an
21261    explicitly instantiated class template.  */
21262 static void
21263 instantiate_class_member (tree decl, int extern_p)
21264 {
21265   mark_decl_instantiated (decl, extern_p);
21266   if (! extern_p)
21267     instantiate_decl (decl, /*defer_ok=*/1,
21268                       /*expl_inst_class_mem_p=*/true);
21269 }
21270
21271 /* Perform an explicit instantiation of template class T.  STORAGE, if
21272    non-null, is the RID for extern, inline or static.  COMPLAIN is
21273    nonzero if this is called from the parser, zero if called recursively,
21274    since the standard is unclear (as detailed below).  */
21275
21276 void
21277 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
21278 {
21279   int extern_p = 0;
21280   int nomem_p = 0;
21281   int static_p = 0;
21282   int previous_instantiation_extern_p = 0;
21283
21284   if (TREE_CODE (t) == TYPE_DECL)
21285     t = TREE_TYPE (t);
21286
21287   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
21288     {
21289       tree tmpl =
21290         (TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
21291       if (tmpl)
21292         error ("explicit instantiation of non-class template %qD", tmpl);
21293       else
21294         error ("explicit instantiation of non-template type %qT", t);
21295       return;
21296     }
21297
21298   complete_type (t);
21299
21300   if (!COMPLETE_TYPE_P (t))
21301     {
21302       if (complain & tf_error)
21303         error ("explicit instantiation of %q#T before definition of template",
21304                t);
21305       return;
21306     }
21307
21308   if (storage != NULL_TREE)
21309     {
21310       if (!in_system_header_at (input_location))
21311         {
21312           if (storage == ridpointers[(int) RID_EXTERN])
21313             {
21314               if (cxx_dialect == cxx98)
21315                 pedwarn (input_location, OPT_Wpedantic, 
21316                          "ISO C++ 1998 forbids the use of %<extern%> on "
21317                          "explicit instantiations");
21318             }
21319           else
21320             pedwarn (input_location, OPT_Wpedantic, 
21321                      "ISO C++ forbids the use of %qE"
21322                      " on explicit instantiations", storage);
21323         }
21324
21325       if (storage == ridpointers[(int) RID_INLINE])
21326         nomem_p = 1;
21327       else if (storage == ridpointers[(int) RID_EXTERN])
21328         extern_p = 1;
21329       else if (storage == ridpointers[(int) RID_STATIC])
21330         static_p = 1;
21331       else
21332         {
21333           error ("storage class %qD applied to template instantiation",
21334                  storage);
21335           extern_p = 0;
21336         }
21337     }
21338
21339   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
21340     {
21341       /* DR 259 [temp.spec].
21342
21343          Both an explicit instantiation and a declaration of an explicit
21344          specialization shall not appear in a program unless the explicit
21345          instantiation follows a declaration of the explicit specialization.
21346
21347          For a given set of template parameters, if an explicit
21348          instantiation of a template appears after a declaration of an
21349          explicit specialization for that template, the explicit
21350          instantiation has no effect.  */
21351       return;
21352     }
21353   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
21354     {
21355       /* [temp.spec]
21356
21357          No program shall explicitly instantiate any template more
21358          than once.
21359
21360          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
21361          instantiation was `extern'.  If EXTERN_P then the second is.
21362          These cases are OK.  */
21363       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
21364
21365       if (!previous_instantiation_extern_p && !extern_p
21366           && (complain & tf_error))
21367         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
21368
21369       /* If we've already instantiated the template, just return now.  */
21370       if (!CLASSTYPE_INTERFACE_ONLY (t))
21371         return;
21372     }
21373
21374   check_explicit_instantiation_namespace (TYPE_NAME (t));
21375   mark_class_instantiated (t, extern_p);
21376
21377   if (nomem_p)
21378     return;
21379
21380   {
21381     tree tmp;
21382
21383     /* In contrast to implicit instantiation, where only the
21384        declarations, and not the definitions, of members are
21385        instantiated, we have here:
21386
21387          [temp.explicit]
21388
21389          The explicit instantiation of a class template specialization
21390          implies the instantiation of all of its members not
21391          previously explicitly specialized in the translation unit
21392          containing the explicit instantiation.
21393
21394        Of course, we can't instantiate member template classes, since
21395        we don't have any arguments for them.  Note that the standard
21396        is unclear on whether the instantiation of the members are
21397        *explicit* instantiations or not.  However, the most natural
21398        interpretation is that it should be an explicit instantiation.  */
21399
21400     if (! static_p)
21401       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
21402         if (TREE_CODE (tmp) == FUNCTION_DECL
21403             && DECL_TEMPLATE_INSTANTIATION (tmp)
21404             && (!extern_p || user_provided_p (tmp)))
21405           instantiate_class_member (tmp, extern_p);
21406
21407     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
21408       if (VAR_P (tmp) && DECL_TEMPLATE_INSTANTIATION (tmp))
21409         instantiate_class_member (tmp, extern_p);
21410
21411     if (CLASSTYPE_NESTED_UTDS (t))
21412       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
21413                              bt_instantiate_type_proc, &storage);
21414   }
21415 }
21416
21417 /* Given a function DECL, which is a specialization of TMPL, modify
21418    DECL to be a re-instantiation of TMPL with the same template
21419    arguments.  TMPL should be the template into which tsubst'ing
21420    should occur for DECL, not the most general template.
21421
21422    One reason for doing this is a scenario like this:
21423
21424      template <class T>
21425      void f(const T&, int i);
21426
21427      void g() { f(3, 7); }
21428
21429      template <class T>
21430      void f(const T& t, const int i) { }
21431
21432    Note that when the template is first instantiated, with
21433    instantiate_template, the resulting DECL will have no name for the
21434    first parameter, and the wrong type for the second.  So, when we go
21435    to instantiate the DECL, we regenerate it.  */
21436
21437 static void
21438 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
21439 {
21440   /* The arguments used to instantiate DECL, from the most general
21441      template.  */
21442   tree code_pattern;
21443
21444   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
21445
21446   /* Make sure that we can see identifiers, and compute access
21447      correctly.  */
21448   push_access_scope (decl);
21449
21450   if (TREE_CODE (decl) == FUNCTION_DECL)
21451     {
21452       tree decl_parm;
21453       tree pattern_parm;
21454       tree specs;
21455       int args_depth;
21456       int parms_depth;
21457
21458       args_depth = TMPL_ARGS_DEPTH (args);
21459       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
21460       if (args_depth > parms_depth)
21461         args = get_innermost_template_args (args, parms_depth);
21462
21463       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
21464                                               args, tf_error, NULL_TREE,
21465                                               /*defer_ok*/false);
21466       if (specs && specs != error_mark_node)
21467         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
21468                                                     specs);
21469
21470       /* Merge parameter declarations.  */
21471       decl_parm = skip_artificial_parms_for (decl,
21472                                              DECL_ARGUMENTS (decl));
21473       pattern_parm
21474         = skip_artificial_parms_for (code_pattern,
21475                                      DECL_ARGUMENTS (code_pattern));
21476       while (decl_parm && !DECL_PACK_P (pattern_parm))
21477         {
21478           tree parm_type;
21479           tree attributes;
21480           
21481           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
21482             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
21483           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
21484                               NULL_TREE);
21485           parm_type = type_decays_to (parm_type);
21486           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
21487             TREE_TYPE (decl_parm) = parm_type;
21488           attributes = DECL_ATTRIBUTES (pattern_parm);
21489           if (DECL_ATTRIBUTES (decl_parm) != attributes)
21490             {
21491               DECL_ATTRIBUTES (decl_parm) = attributes;
21492               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
21493             }
21494           decl_parm = DECL_CHAIN (decl_parm);
21495           pattern_parm = DECL_CHAIN (pattern_parm);
21496         }
21497       /* Merge any parameters that match with the function parameter
21498          pack.  */
21499       if (pattern_parm && DECL_PACK_P (pattern_parm))
21500         {
21501           int i, len;
21502           tree expanded_types;
21503           /* Expand the TYPE_PACK_EXPANSION that provides the types for
21504              the parameters in this function parameter pack.  */
21505           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
21506                                                  args, tf_error, NULL_TREE);
21507           len = TREE_VEC_LENGTH (expanded_types);
21508           for (i = 0; i < len; i++)
21509             {
21510               tree parm_type;
21511               tree attributes;
21512           
21513               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
21514                 /* Rename the parameter to include the index.  */
21515                 DECL_NAME (decl_parm) = 
21516                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
21517               parm_type = TREE_VEC_ELT (expanded_types, i);
21518               parm_type = type_decays_to (parm_type);
21519               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
21520                 TREE_TYPE (decl_parm) = parm_type;
21521               attributes = DECL_ATTRIBUTES (pattern_parm);
21522               if (DECL_ATTRIBUTES (decl_parm) != attributes)
21523                 {
21524                   DECL_ATTRIBUTES (decl_parm) = attributes;
21525                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
21526                 }
21527               decl_parm = DECL_CHAIN (decl_parm);
21528             }
21529         }
21530       /* Merge additional specifiers from the CODE_PATTERN.  */
21531       if (DECL_DECLARED_INLINE_P (code_pattern)
21532           && !DECL_DECLARED_INLINE_P (decl))
21533         DECL_DECLARED_INLINE_P (decl) = 1;
21534     }
21535   else if (VAR_P (decl))
21536     {
21537       DECL_INITIAL (decl) =
21538         tsubst_expr (DECL_INITIAL (code_pattern), args,
21539                      tf_error, DECL_TI_TEMPLATE (decl),
21540                      /*integral_constant_expression_p=*/false);
21541       if (VAR_HAD_UNKNOWN_BOUND (decl))
21542         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
21543                                    tf_error, DECL_TI_TEMPLATE (decl));
21544     }
21545   else
21546     gcc_unreachable ();
21547
21548   pop_access_scope (decl);
21549 }
21550
21551 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
21552    substituted to get DECL.  */
21553
21554 tree
21555 template_for_substitution (tree decl)
21556 {
21557   tree tmpl = DECL_TI_TEMPLATE (decl);
21558
21559   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
21560      for the instantiation.  This is not always the most general
21561      template.  Consider, for example:
21562
21563         template <class T>
21564         struct S { template <class U> void f();
21565                    template <> void f<int>(); };
21566
21567      and an instantiation of S<double>::f<int>.  We want TD to be the
21568      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
21569   while (/* An instantiation cannot have a definition, so we need a
21570             more general template.  */
21571          DECL_TEMPLATE_INSTANTIATION (tmpl)
21572            /* We must also deal with friend templates.  Given:
21573
21574                 template <class T> struct S {
21575                   template <class U> friend void f() {};
21576                 };
21577
21578               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
21579               so far as the language is concerned, but that's still
21580               where we get the pattern for the instantiation from.  On
21581               other hand, if the definition comes outside the class, say:
21582
21583                 template <class T> struct S {
21584                   template <class U> friend void f();
21585                 };
21586                 template <class U> friend void f() {}
21587
21588               we don't need to look any further.  That's what the check for
21589               DECL_INITIAL is for.  */
21590           || (TREE_CODE (decl) == FUNCTION_DECL
21591               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
21592               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
21593     {
21594       /* The present template, TD, should not be a definition.  If it
21595          were a definition, we should be using it!  Note that we
21596          cannot restructure the loop to just keep going until we find
21597          a template with a definition, since that might go too far if
21598          a specialization was declared, but not defined.  */
21599
21600       /* Fetch the more general template.  */
21601       tmpl = DECL_TI_TEMPLATE (tmpl);
21602     }
21603
21604   return tmpl;
21605 }
21606
21607 /* Returns true if we need to instantiate this template instance even if we
21608    know we aren't going to emit it.  */
21609
21610 bool
21611 always_instantiate_p (tree decl)
21612 {
21613   /* We always instantiate inline functions so that we can inline them.  An
21614      explicit instantiation declaration prohibits implicit instantiation of
21615      non-inline functions.  With high levels of optimization, we would
21616      normally inline non-inline functions -- but we're not allowed to do
21617      that for "extern template" functions.  Therefore, we check
21618      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
21619   return ((TREE_CODE (decl) == FUNCTION_DECL
21620            && (DECL_DECLARED_INLINE_P (decl)
21621                || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
21622           /* And we need to instantiate static data members so that
21623              their initializers are available in integral constant
21624              expressions.  */
21625           || (VAR_P (decl)
21626               && decl_maybe_constant_var_p (decl)));
21627 }
21628
21629 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
21630    instantiate it now, modifying TREE_TYPE (fn).  */
21631
21632 void
21633 maybe_instantiate_noexcept (tree fn)
21634 {
21635   tree fntype, spec, noex, clone;
21636
21637   /* Don't instantiate a noexcept-specification from template context.  */
21638   if (processing_template_decl)
21639     return;
21640
21641   if (DECL_CLONED_FUNCTION_P (fn))
21642     fn = DECL_CLONED_FUNCTION (fn);
21643   fntype = TREE_TYPE (fn);
21644   spec = TYPE_RAISES_EXCEPTIONS (fntype);
21645
21646   if (!spec || !TREE_PURPOSE (spec))
21647     return;
21648
21649   noex = TREE_PURPOSE (spec);
21650
21651   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
21652     {
21653       if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
21654         spec = get_defaulted_eh_spec (fn);
21655       else if (push_tinst_level (fn))
21656         {
21657           push_access_scope (fn);
21658           push_deferring_access_checks (dk_no_deferred);
21659           input_location = DECL_SOURCE_LOCATION (fn);
21660           noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
21661                                         DEFERRED_NOEXCEPT_ARGS (noex),
21662                                         tf_warning_or_error, fn,
21663                                         /*function_p=*/false,
21664                                         /*integral_constant_expression_p=*/true);
21665           pop_deferring_access_checks ();
21666           pop_access_scope (fn);
21667           pop_tinst_level ();
21668           spec = build_noexcept_spec (noex, tf_warning_or_error);
21669           if (spec == error_mark_node)
21670             spec = noexcept_false_spec;
21671         }
21672       else
21673         spec = noexcept_false_spec;
21674
21675       TREE_TYPE (fn) = build_exception_variant (fntype, spec);
21676     }
21677
21678   FOR_EACH_CLONE (clone, fn)
21679     {
21680       if (TREE_TYPE (clone) == fntype)
21681         TREE_TYPE (clone) = TREE_TYPE (fn);
21682       else
21683         TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
21684     }
21685 }
21686
21687 /* Produce the definition of D, a _DECL generated from a template.  If
21688    DEFER_OK is nonzero, then we don't have to actually do the
21689    instantiation now; we just have to do it sometime.  Normally it is
21690    an error if this is an explicit instantiation but D is undefined.
21691    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
21692    explicitly instantiated class template.  */
21693
21694 tree
21695 instantiate_decl (tree d, int defer_ok,
21696                   bool expl_inst_class_mem_p)
21697 {
21698   tree tmpl = DECL_TI_TEMPLATE (d);
21699   tree gen_args;
21700   tree args;
21701   tree td;
21702   tree code_pattern;
21703   tree spec;
21704   tree gen_tmpl;
21705   bool pattern_defined;
21706   location_t saved_loc = input_location;
21707   int saved_unevaluated_operand = cp_unevaluated_operand;
21708   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
21709   bool external_p;
21710   bool deleted_p;
21711   tree fn_context;
21712   bool nested = false;
21713
21714   /* This function should only be used to instantiate templates for
21715      functions and static member variables.  */
21716   gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
21717
21718   /* A concept is never instantiated. */
21719   gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
21720
21721   /* Variables are never deferred; if instantiation is required, they
21722      are instantiated right away.  That allows for better code in the
21723      case that an expression refers to the value of the variable --
21724      if the variable has a constant value the referring expression can
21725      take advantage of that fact.  */
21726   if (VAR_P (d)
21727       || DECL_DECLARED_CONSTEXPR_P (d))
21728     defer_ok = 0;
21729
21730   /* Don't instantiate cloned functions.  Instead, instantiate the
21731      functions they cloned.  */
21732   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
21733     d = DECL_CLONED_FUNCTION (d);
21734
21735   if (DECL_TEMPLATE_INSTANTIATED (d)
21736       || (TREE_CODE (d) == FUNCTION_DECL
21737           && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
21738       || DECL_TEMPLATE_SPECIALIZATION (d))
21739     /* D has already been instantiated or explicitly specialized, so
21740        there's nothing for us to do here.
21741
21742        It might seem reasonable to check whether or not D is an explicit
21743        instantiation, and, if so, stop here.  But when an explicit
21744        instantiation is deferred until the end of the compilation,
21745        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
21746        the instantiation.  */
21747     return d;
21748
21749   /* Check to see whether we know that this template will be
21750      instantiated in some other file, as with "extern template"
21751      extension.  */
21752   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
21753
21754   /* In general, we do not instantiate such templates.  */
21755   if (external_p && !always_instantiate_p (d))
21756     return d;
21757
21758   gen_tmpl = most_general_template (tmpl);
21759   gen_args = DECL_TI_ARGS (d);
21760
21761   if (tmpl != gen_tmpl)
21762     /* We should already have the extra args.  */
21763     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
21764                 == TMPL_ARGS_DEPTH (gen_args));
21765   /* And what's in the hash table should match D.  */
21766   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
21767               || spec == NULL_TREE);
21768
21769   /* This needs to happen before any tsubsting.  */
21770   if (! push_tinst_level (d))
21771     return d;
21772
21773   timevar_push (TV_TEMPLATE_INST);
21774
21775   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
21776      for the instantiation.  */
21777   td = template_for_substitution (d);
21778   args = gen_args;
21779
21780   if (VAR_P (d))
21781     {
21782       /* Look up an explicit specialization, if any.  */
21783       tree tid = lookup_template_variable (gen_tmpl, gen_args);
21784       tree elt = most_specialized_partial_spec (tid, tf_warning_or_error);
21785       if (elt && elt != error_mark_node)
21786         {
21787           td = TREE_VALUE (elt);
21788           args = TREE_PURPOSE (elt);
21789         }
21790     }
21791
21792   code_pattern = DECL_TEMPLATE_RESULT (td);
21793
21794   /* We should never be trying to instantiate a member of a class
21795      template or partial specialization.  */
21796   gcc_assert (d != code_pattern);
21797
21798   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
21799       || DECL_TEMPLATE_SPECIALIZATION (td))
21800     /* In the case of a friend template whose definition is provided
21801        outside the class, we may have too many arguments.  Drop the
21802        ones we don't need.  The same is true for specializations.  */
21803     args = get_innermost_template_args
21804       (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
21805
21806   if (TREE_CODE (d) == FUNCTION_DECL)
21807     {
21808       deleted_p = DECL_DELETED_FN (code_pattern);
21809       pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
21810                           && DECL_INITIAL (code_pattern) != error_mark_node)
21811                          || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern)
21812                          || deleted_p);
21813     }
21814   else
21815     {
21816       deleted_p = false;
21817       if (DECL_CLASS_SCOPE_P (code_pattern))
21818         pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
21819       else
21820         pattern_defined = ! DECL_EXTERNAL (code_pattern);
21821     }
21822
21823   /* We may be in the middle of deferred access check.  Disable it now.  */
21824   push_deferring_access_checks (dk_no_deferred);
21825
21826   /* Unless an explicit instantiation directive has already determined
21827      the linkage of D, remember that a definition is available for
21828      this entity.  */
21829   if (pattern_defined
21830       && !DECL_INTERFACE_KNOWN (d)
21831       && !DECL_NOT_REALLY_EXTERN (d))
21832     mark_definable (d);
21833
21834   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
21835   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
21836   input_location = DECL_SOURCE_LOCATION (d);
21837
21838   /* If D is a member of an explicitly instantiated class template,
21839      and no definition is available, treat it like an implicit
21840      instantiation.  */
21841   if (!pattern_defined && expl_inst_class_mem_p
21842       && DECL_EXPLICIT_INSTANTIATION (d))
21843     {
21844       /* Leave linkage flags alone on instantiations with anonymous
21845          visibility.  */
21846       if (TREE_PUBLIC (d))
21847         {
21848           DECL_NOT_REALLY_EXTERN (d) = 0;
21849           DECL_INTERFACE_KNOWN (d) = 0;
21850         }
21851       SET_DECL_IMPLICIT_INSTANTIATION (d);
21852     }
21853
21854   /* Defer all other templates, unless we have been explicitly
21855      forbidden from doing so.  */
21856   if (/* If there is no definition, we cannot instantiate the
21857          template.  */
21858       ! pattern_defined
21859       /* If it's OK to postpone instantiation, do so.  */
21860       || defer_ok
21861       /* If this is a static data member that will be defined
21862          elsewhere, we don't want to instantiate the entire data
21863          member, but we do want to instantiate the initializer so that
21864          we can substitute that elsewhere.  */
21865       || (external_p && VAR_P (d))
21866       /* Handle here a deleted function too, avoid generating
21867          its body (c++/61080).  */
21868       || deleted_p)
21869     {
21870       /* The definition of the static data member is now required so
21871          we must substitute the initializer.  */
21872       if (VAR_P (d)
21873           && !DECL_INITIAL (d)
21874           && DECL_INITIAL (code_pattern))
21875         {
21876           tree ns;
21877           tree init;
21878           bool const_init = false;
21879           bool enter_context = DECL_CLASS_SCOPE_P (d);
21880
21881           ns = decl_namespace_context (d);
21882           push_nested_namespace (ns);
21883           if (enter_context)
21884             push_nested_class (DECL_CONTEXT (d));
21885           init = tsubst_expr (DECL_INITIAL (code_pattern),
21886                               args,
21887                               tf_warning_or_error, NULL_TREE,
21888                               /*integral_constant_expression_p=*/false);
21889           /* If instantiating the initializer involved instantiating this
21890              again, don't call cp_finish_decl twice.  */
21891           if (!DECL_INITIAL (d))
21892             {
21893               /* Make sure the initializer is still constant, in case of
21894                  circular dependency (template/instantiate6.C). */
21895               const_init
21896                 = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
21897               cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
21898                               /*asmspec_tree=*/NULL_TREE,
21899                               LOOKUP_ONLYCONVERTING);
21900             }
21901           if (enter_context)
21902             pop_nested_class ();
21903           pop_nested_namespace (ns);
21904         }
21905
21906       /* We restore the source position here because it's used by
21907          add_pending_template.  */
21908       input_location = saved_loc;
21909
21910       if (at_eof && !pattern_defined
21911           && DECL_EXPLICIT_INSTANTIATION (d)
21912           && DECL_NOT_REALLY_EXTERN (d))
21913         /* [temp.explicit]
21914
21915            The definition of a non-exported function template, a
21916            non-exported member function template, or a non-exported
21917            member function or static data member of a class template
21918            shall be present in every translation unit in which it is
21919            explicitly instantiated.  */
21920         permerror (input_location,  "explicit instantiation of %qD "
21921                    "but no definition available", d);
21922
21923       /* If we're in unevaluated context, we just wanted to get the
21924          constant value; this isn't an odr use, so don't queue
21925          a full instantiation.  */
21926       if (cp_unevaluated_operand != 0)
21927         goto out;
21928       /* ??? Historically, we have instantiated inline functions, even
21929          when marked as "extern template".  */
21930       if (!(external_p && VAR_P (d)))
21931         add_pending_template (d);
21932       goto out;
21933     }
21934   /* Tell the repository that D is available in this translation unit
21935      -- and see if it is supposed to be instantiated here.  */
21936   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
21937     {
21938       /* In a PCH file, despite the fact that the repository hasn't
21939          requested instantiation in the PCH it is still possible that
21940          an instantiation will be required in a file that includes the
21941          PCH.  */
21942       if (pch_file)
21943         add_pending_template (d);
21944       /* Instantiate inline functions so that the inliner can do its
21945          job, even though we'll not be emitting a copy of this
21946          function.  */
21947       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
21948         goto out;
21949     }
21950
21951   fn_context = decl_function_context (d);
21952   nested = (current_function_decl != NULL_TREE);
21953   vec<tree> omp_privatization_save;
21954   if (nested)
21955     save_omp_privatization_clauses (omp_privatization_save);
21956
21957   if (!fn_context)
21958     push_to_top_level ();
21959   else
21960     {
21961       if (nested)
21962         push_function_context ();
21963       cp_unevaluated_operand = 0;
21964       c_inhibit_evaluation_warnings = 0;
21965     }
21966
21967   /* Mark D as instantiated so that recursive calls to
21968      instantiate_decl do not try to instantiate it again.  */
21969   DECL_TEMPLATE_INSTANTIATED (d) = 1;
21970
21971   /* Regenerate the declaration in case the template has been modified
21972      by a subsequent redeclaration.  */
21973   regenerate_decl_from_template (d, td, args);
21974
21975   /* We already set the file and line above.  Reset them now in case
21976      they changed as a result of calling regenerate_decl_from_template.  */
21977   input_location = DECL_SOURCE_LOCATION (d);
21978
21979   if (VAR_P (d))
21980     {
21981       tree init;
21982       bool const_init = false;
21983
21984       /* Clear out DECL_RTL; whatever was there before may not be right
21985          since we've reset the type of the declaration.  */
21986       SET_DECL_RTL (d, NULL);
21987       DECL_IN_AGGR_P (d) = 0;
21988
21989       /* The initializer is placed in DECL_INITIAL by
21990          regenerate_decl_from_template so we don't need to
21991          push/pop_access_scope again here.  Pull it out so that
21992          cp_finish_decl can process it.  */
21993       init = DECL_INITIAL (d);
21994       DECL_INITIAL (d) = NULL_TREE;
21995       DECL_INITIALIZED_P (d) = 0;
21996
21997       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
21998          initializer.  That function will defer actual emission until
21999          we have a chance to determine linkage.  */
22000       DECL_EXTERNAL (d) = 0;
22001
22002       /* Enter the scope of D so that access-checking works correctly.  */
22003       bool enter_context = DECL_CLASS_SCOPE_P (d);
22004       if (enter_context)
22005         push_nested_class (DECL_CONTEXT (d));
22006
22007       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
22008       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
22009
22010       if (enter_context)
22011         pop_nested_class ();
22012
22013       if (variable_template_p (gen_tmpl))
22014         note_variable_template_instantiation (d);
22015     }
22016   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
22017     synthesize_method (d);
22018   else if (TREE_CODE (d) == FUNCTION_DECL)
22019     {
22020       hash_map<tree, tree> *saved_local_specializations;
22021       tree subst_decl;
22022       tree tmpl_parm;
22023       tree spec_parm;
22024       tree block = NULL_TREE;
22025
22026       /* Save away the current list, in case we are instantiating one
22027          template from within the body of another.  */
22028       saved_local_specializations = local_specializations;
22029
22030       /* Set up the list of local specializations.  */
22031       local_specializations = new hash_map<tree, tree>;
22032
22033       /* Set up context.  */
22034       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
22035           && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
22036         block = push_stmt_list ();
22037       else
22038         start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
22039
22040       /* Some typedefs referenced from within the template code need to be
22041          access checked at template instantiation time, i.e now. These
22042          types were added to the template at parsing time. Let's get those
22043          and perform the access checks then.  */
22044       perform_typedefs_access_check (DECL_TEMPLATE_RESULT (gen_tmpl),
22045                                      gen_args);
22046
22047       /* Create substitution entries for the parameters.  */
22048       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
22049       tmpl_parm = DECL_ARGUMENTS (subst_decl);
22050       spec_parm = DECL_ARGUMENTS (d);
22051       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
22052         {
22053           register_local_specialization (spec_parm, tmpl_parm);
22054           spec_parm = skip_artificial_parms_for (d, spec_parm);
22055           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
22056         }
22057       for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
22058         {
22059           if (!DECL_PACK_P (tmpl_parm))
22060             {
22061               register_local_specialization (spec_parm, tmpl_parm);
22062               spec_parm = DECL_CHAIN (spec_parm);
22063             }
22064           else
22065             {
22066               /* Register the (value) argument pack as a specialization of
22067                  TMPL_PARM, then move on.  */
22068               tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
22069               register_local_specialization (argpack, tmpl_parm);
22070             }
22071         }
22072       gcc_assert (!spec_parm);
22073
22074       /* Substitute into the body of the function.  */
22075       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
22076         tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
22077                         tf_warning_or_error, tmpl);
22078       else
22079         {
22080           tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
22081                        tf_warning_or_error, tmpl,
22082                        /*integral_constant_expression_p=*/false);
22083
22084           /* Set the current input_location to the end of the function
22085              so that finish_function knows where we are.  */
22086           input_location
22087             = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
22088
22089           /* Remember if we saw an infinite loop in the template.  */
22090           current_function_infinite_loop
22091             = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
22092         }
22093
22094       /* We don't need the local specializations any more.  */
22095       delete local_specializations;
22096       local_specializations = saved_local_specializations;
22097
22098       /* Finish the function.  */
22099       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
22100           && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
22101         DECL_SAVED_TREE (d) = pop_stmt_list (block);
22102       else
22103         {
22104           d = finish_function (0);
22105           expand_or_defer_fn (d);
22106         }
22107
22108       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
22109         cp_check_omp_declare_reduction (d);
22110     }
22111
22112   /* We're not deferring instantiation any more.  */
22113   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
22114
22115   if (!fn_context)
22116     pop_from_top_level ();
22117   else if (nested)
22118     pop_function_context ();
22119
22120 out:
22121   input_location = saved_loc;
22122   cp_unevaluated_operand = saved_unevaluated_operand;
22123   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
22124   pop_deferring_access_checks ();
22125   pop_tinst_level ();
22126   if (nested)
22127     restore_omp_privatization_clauses (omp_privatization_save);
22128
22129   timevar_pop (TV_TEMPLATE_INST);
22130
22131   return d;
22132 }
22133
22134 /* Run through the list of templates that we wish we could
22135    instantiate, and instantiate any we can.  RETRIES is the
22136    number of times we retry pending template instantiation.  */
22137
22138 void
22139 instantiate_pending_templates (int retries)
22140 {
22141   int reconsider;
22142   location_t saved_loc = input_location;
22143
22144   /* Instantiating templates may trigger vtable generation.  This in turn
22145      may require further template instantiations.  We place a limit here
22146      to avoid infinite loop.  */
22147   if (pending_templates && retries >= max_tinst_depth)
22148     {
22149       tree decl = pending_templates->tinst->decl;
22150
22151       fatal_error (input_location,
22152                    "template instantiation depth exceeds maximum of %d"
22153                    " instantiating %q+D, possibly from virtual table generation"
22154                    " (use -ftemplate-depth= to increase the maximum)",
22155                    max_tinst_depth, decl);
22156       if (TREE_CODE (decl) == FUNCTION_DECL)
22157         /* Pretend that we defined it.  */
22158         DECL_INITIAL (decl) = error_mark_node;
22159       return;
22160     }
22161
22162   do
22163     {
22164       struct pending_template **t = &pending_templates;
22165       struct pending_template *last = NULL;
22166       reconsider = 0;
22167       while (*t)
22168         {
22169           tree instantiation = reopen_tinst_level ((*t)->tinst);
22170           bool complete = false;
22171
22172           if (TYPE_P (instantiation))
22173             {
22174               tree fn;
22175
22176               if (!COMPLETE_TYPE_P (instantiation))
22177                 {
22178                   instantiate_class_template (instantiation);
22179                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
22180                     for (fn = TYPE_METHODS (instantiation);
22181                          fn;
22182                          fn = TREE_CHAIN (fn))
22183                       if (! DECL_ARTIFICIAL (fn))
22184                         instantiate_decl (fn,
22185                                           /*defer_ok=*/0,
22186                                           /*expl_inst_class_mem_p=*/false);
22187                   if (COMPLETE_TYPE_P (instantiation))
22188                     reconsider = 1;
22189                 }
22190
22191               complete = COMPLETE_TYPE_P (instantiation);
22192             }
22193           else
22194             {
22195               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
22196                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
22197                 {
22198                   instantiation
22199                     = instantiate_decl (instantiation,
22200                                         /*defer_ok=*/0,
22201                                         /*expl_inst_class_mem_p=*/false);
22202                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
22203                     reconsider = 1;
22204                 }
22205
22206               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
22207                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
22208             }
22209
22210           if (complete)
22211             /* If INSTANTIATION has been instantiated, then we don't
22212                need to consider it again in the future.  */
22213             *t = (*t)->next;
22214           else
22215             {
22216               last = *t;
22217               t = &(*t)->next;
22218             }
22219           tinst_depth = 0;
22220           current_tinst_level = NULL;
22221         }
22222       last_pending_template = last;
22223     }
22224   while (reconsider);
22225
22226   input_location = saved_loc;
22227 }
22228
22229 /* Substitute ARGVEC into T, which is a list of initializers for
22230    either base class or a non-static data member.  The TREE_PURPOSEs
22231    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
22232    instantiate_decl.  */
22233
22234 static tree
22235 tsubst_initializer_list (tree t, tree argvec)
22236 {
22237   tree inits = NULL_TREE;
22238
22239   for (; t; t = TREE_CHAIN (t))
22240     {
22241       tree decl;
22242       tree init;
22243       tree expanded_bases = NULL_TREE;
22244       tree expanded_arguments = NULL_TREE;
22245       int i, len = 1;
22246
22247       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
22248         {
22249           tree expr;
22250           tree arg;
22251
22252           /* Expand the base class expansion type into separate base
22253              classes.  */
22254           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
22255                                                  tf_warning_or_error,
22256                                                  NULL_TREE);
22257           if (expanded_bases == error_mark_node)
22258             continue;
22259           
22260           /* We'll be building separate TREE_LISTs of arguments for
22261              each base.  */
22262           len = TREE_VEC_LENGTH (expanded_bases);
22263           expanded_arguments = make_tree_vec (len);
22264           for (i = 0; i < len; i++)
22265             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
22266
22267           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
22268              expand each argument in the TREE_VALUE of t.  */
22269           expr = make_node (EXPR_PACK_EXPANSION);
22270           PACK_EXPANSION_LOCAL_P (expr) = true;
22271           PACK_EXPANSION_PARAMETER_PACKS (expr) =
22272             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
22273
22274           if (TREE_VALUE (t) == void_type_node)
22275             /* VOID_TYPE_NODE is used to indicate
22276                value-initialization.  */
22277             {
22278               for (i = 0; i < len; i++)
22279                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
22280             }
22281           else
22282             {
22283               /* Substitute parameter packs into each argument in the
22284                  TREE_LIST.  */
22285               in_base_initializer = 1;
22286               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
22287                 {
22288                   tree expanded_exprs;
22289
22290                   /* Expand the argument.  */
22291                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
22292                   expanded_exprs 
22293                     = tsubst_pack_expansion (expr, argvec,
22294                                              tf_warning_or_error,
22295                                              NULL_TREE);
22296                   if (expanded_exprs == error_mark_node)
22297                     continue;
22298
22299                   /* Prepend each of the expanded expressions to the
22300                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
22301                   for (i = 0; i < len; i++)
22302                     {
22303                       TREE_VEC_ELT (expanded_arguments, i) = 
22304                         tree_cons (NULL_TREE, 
22305                                    TREE_VEC_ELT (expanded_exprs, i),
22306                                    TREE_VEC_ELT (expanded_arguments, i));
22307                     }
22308                 }
22309               in_base_initializer = 0;
22310
22311               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
22312                  since we built them backwards.  */
22313               for (i = 0; i < len; i++)
22314                 {
22315                   TREE_VEC_ELT (expanded_arguments, i) = 
22316                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
22317                 }
22318             }
22319         }
22320
22321       for (i = 0; i < len; ++i)
22322         {
22323           if (expanded_bases)
22324             {
22325               decl = TREE_VEC_ELT (expanded_bases, i);
22326               decl = expand_member_init (decl);
22327               init = TREE_VEC_ELT (expanded_arguments, i);
22328             }
22329           else
22330             {
22331               tree tmp;
22332               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
22333                                   tf_warning_or_error, NULL_TREE);
22334
22335               decl = expand_member_init (decl);
22336               if (decl && !DECL_P (decl))
22337                 in_base_initializer = 1;
22338
22339               init = TREE_VALUE (t);
22340               tmp = init;
22341               if (init != void_type_node)
22342                 init = tsubst_expr (init, argvec,
22343                                     tf_warning_or_error, NULL_TREE,
22344                                     /*integral_constant_expression_p=*/false);
22345               if (init == NULL_TREE && tmp != NULL_TREE)
22346                 /* If we had an initializer but it instantiated to nothing,
22347                    value-initialize the object.  This will only occur when
22348                    the initializer was a pack expansion where the parameter
22349                    packs used in that expansion were of length zero.  */
22350                 init = void_type_node;
22351               in_base_initializer = 0;
22352             }
22353
22354           if (decl)
22355             {
22356               init = build_tree_list (decl, init);
22357               TREE_CHAIN (init) = inits;
22358               inits = init;
22359             }
22360         }
22361     }
22362   return inits;
22363 }
22364
22365 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
22366
22367 static void
22368 set_current_access_from_decl (tree decl)
22369 {
22370   if (TREE_PRIVATE (decl))
22371     current_access_specifier = access_private_node;
22372   else if (TREE_PROTECTED (decl))
22373     current_access_specifier = access_protected_node;
22374   else
22375     current_access_specifier = access_public_node;
22376 }
22377
22378 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
22379    is the instantiation (which should have been created with
22380    start_enum) and ARGS are the template arguments to use.  */
22381
22382 static void
22383 tsubst_enum (tree tag, tree newtag, tree args)
22384 {
22385   tree e;
22386
22387   if (SCOPED_ENUM_P (newtag))
22388     begin_scope (sk_scoped_enum, newtag);
22389
22390   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
22391     {
22392       tree value;
22393       tree decl;
22394
22395       decl = TREE_VALUE (e);
22396       /* Note that in a template enum, the TREE_VALUE is the
22397          CONST_DECL, not the corresponding INTEGER_CST.  */
22398       value = tsubst_expr (DECL_INITIAL (decl),
22399                            args, tf_warning_or_error, NULL_TREE,
22400                            /*integral_constant_expression_p=*/true);
22401
22402       /* Give this enumeration constant the correct access.  */
22403       set_current_access_from_decl (decl);
22404
22405       /* Actually build the enumerator itself.  Here we're assuming that
22406          enumerators can't have dependent attributes.  */
22407       build_enumerator (DECL_NAME (decl), value, newtag,
22408                         DECL_ATTRIBUTES (decl), DECL_SOURCE_LOCATION (decl));
22409     }
22410
22411   if (SCOPED_ENUM_P (newtag))
22412     finish_scope ();
22413
22414   finish_enum_value_list (newtag);
22415   finish_enum (newtag);
22416
22417   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
22418     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
22419 }
22420
22421 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
22422    its type -- but without substituting the innermost set of template
22423    arguments.  So, innermost set of template parameters will appear in
22424    the type.  */
22425
22426 tree
22427 get_mostly_instantiated_function_type (tree decl)
22428 {
22429   /* For a function, DECL_TI_TEMPLATE is partially instantiated.  */
22430   return TREE_TYPE (DECL_TI_TEMPLATE (decl));
22431 }
22432
22433 /* Return truthvalue if we're processing a template different from
22434    the last one involved in diagnostics.  */
22435 bool
22436 problematic_instantiation_changed (void)
22437 {
22438   return current_tinst_level != last_error_tinst_level;
22439 }
22440
22441 /* Remember current template involved in diagnostics.  */
22442 void
22443 record_last_problematic_instantiation (void)
22444 {
22445   last_error_tinst_level = current_tinst_level;
22446 }
22447
22448 struct tinst_level *
22449 current_instantiation (void)
22450 {
22451   return current_tinst_level;
22452 }
22453
22454 /* Return TRUE if current_function_decl is being instantiated, false
22455    otherwise.  */
22456
22457 bool
22458 instantiating_current_function_p (void)
22459 {
22460   return (current_instantiation ()
22461           && current_instantiation ()->decl == current_function_decl);
22462 }
22463
22464 /* [temp.param] Check that template non-type parm TYPE is of an allowable
22465    type. Return zero for ok, nonzero for disallowed. Issue error and
22466    warning messages under control of COMPLAIN.  */
22467
22468 static int
22469 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
22470 {
22471   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
22472     return 0;
22473   else if (POINTER_TYPE_P (type))
22474     return 0;
22475   else if (TYPE_PTRMEM_P (type))
22476     return 0;
22477   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
22478     return 0;
22479   else if (TREE_CODE (type) == TYPENAME_TYPE)
22480     return 0;
22481   else if (TREE_CODE (type) == DECLTYPE_TYPE)
22482     return 0;
22483   else if (TREE_CODE (type) == NULLPTR_TYPE)
22484     return 0;
22485   /* A bound template template parm could later be instantiated to have a valid
22486      nontype parm type via an alias template.  */
22487   else if (cxx_dialect >= cxx11
22488            && TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
22489     return 0;
22490
22491   if (complain & tf_error)
22492     {
22493       if (type == error_mark_node)
22494         inform (input_location, "invalid template non-type parameter");
22495       else
22496         error ("%q#T is not a valid type for a template non-type parameter",
22497                type);
22498     }
22499   return 1;
22500 }
22501
22502 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
22503    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
22504
22505 static bool
22506 dependent_type_p_r (tree type)
22507 {
22508   tree scope;
22509
22510   /* [temp.dep.type]
22511
22512      A type is dependent if it is:
22513
22514      -- a template parameter. Template template parameters are types
22515         for us (since TYPE_P holds true for them) so we handle
22516         them here.  */
22517   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
22518       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
22519     return true;
22520   /* -- a qualified-id with a nested-name-specifier which contains a
22521         class-name that names a dependent type or whose unqualified-id
22522         names a dependent type.  */
22523   if (TREE_CODE (type) == TYPENAME_TYPE)
22524     return true;
22525
22526   /* An alias template specialization can be dependent even if the
22527      resulting type is not.  */
22528   if (dependent_alias_template_spec_p (type))
22529     return true;
22530
22531   /* -- a cv-qualified type where the cv-unqualified type is
22532         dependent.
22533      No code is necessary for this bullet; the code below handles
22534      cv-qualified types, and we don't want to strip aliases with
22535      TYPE_MAIN_VARIANT because of DR 1558.  */
22536   /* -- a compound type constructed from any dependent type.  */
22537   if (TYPE_PTRMEM_P (type))
22538     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
22539             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
22540                                            (type)));
22541   else if (TYPE_PTR_P (type)
22542            || TREE_CODE (type) == REFERENCE_TYPE)
22543     return dependent_type_p (TREE_TYPE (type));
22544   else if (TREE_CODE (type) == FUNCTION_TYPE
22545            || TREE_CODE (type) == METHOD_TYPE)
22546     {
22547       tree arg_type;
22548
22549       if (dependent_type_p (TREE_TYPE (type)))
22550         return true;
22551       for (arg_type = TYPE_ARG_TYPES (type);
22552            arg_type;
22553            arg_type = TREE_CHAIN (arg_type))
22554         if (dependent_type_p (TREE_VALUE (arg_type)))
22555           return true;
22556       return false;
22557     }
22558   /* -- an array type constructed from any dependent type or whose
22559         size is specified by a constant expression that is
22560         value-dependent.
22561
22562         We checked for type- and value-dependence of the bounds in
22563         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
22564   if (TREE_CODE (type) == ARRAY_TYPE)
22565     {
22566       if (TYPE_DOMAIN (type)
22567           && dependent_type_p (TYPE_DOMAIN (type)))
22568         return true;
22569       return dependent_type_p (TREE_TYPE (type));
22570     }
22571
22572   /* -- a template-id in which either the template name is a template
22573      parameter ...  */
22574   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
22575     return true;
22576   /* ... or any of the template arguments is a dependent type or
22577         an expression that is type-dependent or value-dependent.  */
22578   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
22579            && (any_dependent_template_arguments_p
22580                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
22581     return true;
22582
22583   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
22584      dependent; if the argument of the `typeof' expression is not
22585      type-dependent, then it should already been have resolved.  */
22586   if (TREE_CODE (type) == TYPEOF_TYPE
22587       || TREE_CODE (type) == DECLTYPE_TYPE
22588       || TREE_CODE (type) == UNDERLYING_TYPE)
22589     return true;
22590
22591   /* A template argument pack is dependent if any of its packed
22592      arguments are.  */
22593   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
22594     {
22595       tree args = ARGUMENT_PACK_ARGS (type);
22596       int i, len = TREE_VEC_LENGTH (args);
22597       for (i = 0; i < len; ++i)
22598         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
22599           return true;
22600     }
22601
22602   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
22603      be template parameters.  */
22604   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
22605     return true;
22606
22607   /* The standard does not specifically mention types that are local
22608      to template functions or local classes, but they should be
22609      considered dependent too.  For example:
22610
22611        template <int I> void f() {
22612          enum E { a = I };
22613          S<sizeof (E)> s;
22614        }
22615
22616      The size of `E' cannot be known until the value of `I' has been
22617      determined.  Therefore, `E' must be considered dependent.  */
22618   scope = TYPE_CONTEXT (type);
22619   if (scope && TYPE_P (scope))
22620     return dependent_type_p (scope);
22621   /* Don't use type_dependent_expression_p here, as it can lead
22622      to infinite recursion trying to determine whether a lambda
22623      nested in a lambda is dependent (c++/47687).  */
22624   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
22625            && DECL_LANG_SPECIFIC (scope)
22626            && DECL_TEMPLATE_INFO (scope)
22627            && (any_dependent_template_arguments_p
22628                (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
22629     return true;
22630
22631   /* Other types are non-dependent.  */
22632   return false;
22633 }
22634
22635 /* Returns TRUE if TYPE is dependent, in the sense of
22636    [temp.dep.type].  Note that a NULL type is considered dependent.  */
22637
22638 bool
22639 dependent_type_p (tree type)
22640 {
22641   /* If there are no template parameters in scope, then there can't be
22642      any dependent types.  */
22643   if (!processing_template_decl)
22644     {
22645       /* If we are not processing a template, then nobody should be
22646          providing us with a dependent type.  */
22647       gcc_assert (type);
22648       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
22649       return false;
22650     }
22651
22652   /* If the type is NULL, we have not computed a type for the entity
22653      in question; in that case, the type is dependent.  */
22654   if (!type)
22655     return true;
22656
22657   /* Erroneous types can be considered non-dependent.  */
22658   if (type == error_mark_node)
22659     return false;
22660
22661   /* If we have not already computed the appropriate value for TYPE,
22662      do so now.  */
22663   if (!TYPE_DEPENDENT_P_VALID (type))
22664     {
22665       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
22666       TYPE_DEPENDENT_P_VALID (type) = 1;
22667     }
22668
22669   return TYPE_DEPENDENT_P (type);
22670 }
22671
22672 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
22673    lookup.  In other words, a dependent type that is not the current
22674    instantiation.  */
22675
22676 bool
22677 dependent_scope_p (tree scope)
22678 {
22679   return (scope && TYPE_P (scope) && dependent_type_p (scope)
22680           && !currently_open_class (scope));
22681 }
22682
22683 /* T is a SCOPE_REF; return whether we need to consider it
22684     instantiation-dependent so that we can check access at instantiation
22685     time even though we know which member it resolves to.  */
22686
22687 static bool
22688 instantiation_dependent_scope_ref_p (tree t)
22689 {
22690   if (DECL_P (TREE_OPERAND (t, 1))
22691       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
22692       && accessible_in_template_p (TREE_OPERAND (t, 0),
22693                                    TREE_OPERAND (t, 1)))
22694     return false;
22695   else
22696     return true;
22697 }
22698
22699 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
22700    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
22701    expression.  */
22702
22703 /* Note that this predicate is not appropriate for general expressions;
22704    only constant expressions (that satisfy potential_constant_expression)
22705    can be tested for value dependence.  */
22706
22707 bool
22708 value_dependent_expression_p (tree expression)
22709 {
22710   if (!processing_template_decl)
22711     return false;
22712
22713   /* A name declared with a dependent type.  */
22714   if (DECL_P (expression) && type_dependent_expression_p (expression))
22715     return true;
22716
22717   switch (TREE_CODE (expression))
22718     {
22719     case IDENTIFIER_NODE:
22720       /* A name that has not been looked up -- must be dependent.  */
22721       return true;
22722
22723     case TEMPLATE_PARM_INDEX:
22724       /* A non-type template parm.  */
22725       return true;
22726
22727     case CONST_DECL:
22728       /* A non-type template parm.  */
22729       if (DECL_TEMPLATE_PARM_P (expression))
22730         return true;
22731       return value_dependent_expression_p (DECL_INITIAL (expression));
22732
22733     case VAR_DECL:
22734        /* A constant with literal type and is initialized
22735           with an expression that is value-dependent.
22736
22737           Note that a non-dependent parenthesized initializer will have
22738           already been replaced with its constant value, so if we see
22739           a TREE_LIST it must be dependent.  */
22740       if (DECL_INITIAL (expression)
22741           && decl_constant_var_p (expression)
22742           && (TREE_CODE (DECL_INITIAL (expression)) == TREE_LIST
22743               /* cp_finish_decl doesn't fold reference initializers.  */
22744               || TREE_CODE (TREE_TYPE (expression)) == REFERENCE_TYPE
22745               || type_dependent_expression_p (DECL_INITIAL (expression))
22746               || value_dependent_expression_p (DECL_INITIAL (expression))))
22747         return true;
22748       return false;
22749
22750     case DYNAMIC_CAST_EXPR:
22751     case STATIC_CAST_EXPR:
22752     case CONST_CAST_EXPR:
22753     case REINTERPRET_CAST_EXPR:
22754     case CAST_EXPR:
22755       /* These expressions are value-dependent if the type to which
22756          the cast occurs is dependent or the expression being casted
22757          is value-dependent.  */
22758       {
22759         tree type = TREE_TYPE (expression);
22760
22761         if (dependent_type_p (type))
22762           return true;
22763
22764         /* A functional cast has a list of operands.  */
22765         expression = TREE_OPERAND (expression, 0);
22766         if (!expression)
22767           {
22768             /* If there are no operands, it must be an expression such
22769                as "int()". This should not happen for aggregate types
22770                because it would form non-constant expressions.  */
22771             gcc_assert (cxx_dialect >= cxx11
22772                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
22773
22774             return false;
22775           }
22776
22777         if (TREE_CODE (expression) == TREE_LIST)
22778           return any_value_dependent_elements_p (expression);
22779
22780         return value_dependent_expression_p (expression);
22781       }
22782
22783     case SIZEOF_EXPR:
22784       if (SIZEOF_EXPR_TYPE_P (expression))
22785         return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
22786       /* FALLTHRU */
22787     case ALIGNOF_EXPR:
22788     case TYPEID_EXPR:
22789       /* A `sizeof' expression is value-dependent if the operand is
22790          type-dependent or is a pack expansion.  */
22791       expression = TREE_OPERAND (expression, 0);
22792       if (PACK_EXPANSION_P (expression))
22793         return true;
22794       else if (TYPE_P (expression))
22795         return dependent_type_p (expression);
22796       return instantiation_dependent_uneval_expression_p (expression);
22797
22798     case AT_ENCODE_EXPR:
22799       /* An 'encode' expression is value-dependent if the operand is
22800          type-dependent.  */
22801       expression = TREE_OPERAND (expression, 0);
22802       return dependent_type_p (expression);
22803
22804     case NOEXCEPT_EXPR:
22805       expression = TREE_OPERAND (expression, 0);
22806       return instantiation_dependent_uneval_expression_p (expression);
22807
22808     case SCOPE_REF:
22809       /* All instantiation-dependent expressions should also be considered
22810          value-dependent.  */
22811       return instantiation_dependent_scope_ref_p (expression);
22812
22813     case COMPONENT_REF:
22814       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
22815               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
22816
22817     case NONTYPE_ARGUMENT_PACK:
22818       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
22819          is value-dependent.  */
22820       {
22821         tree values = ARGUMENT_PACK_ARGS (expression);
22822         int i, len = TREE_VEC_LENGTH (values);
22823         
22824         for (i = 0; i < len; ++i)
22825           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
22826             return true;
22827         
22828         return false;
22829       }
22830
22831     case TRAIT_EXPR:
22832       {
22833         tree type2 = TRAIT_EXPR_TYPE2 (expression);
22834         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
22835                 || (type2 ? dependent_type_p (type2) : false));
22836       }
22837
22838     case MODOP_EXPR:
22839       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
22840               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
22841
22842     case ARRAY_REF:
22843       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
22844               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
22845
22846     case ADDR_EXPR:
22847       {
22848         tree op = TREE_OPERAND (expression, 0);
22849         return (value_dependent_expression_p (op)
22850                 || has_value_dependent_address (op));
22851       }
22852
22853     case REQUIRES_EXPR:
22854       /* Treat all requires-expressions as value-dependent so
22855          we don't try to fold them.  */
22856       return true;
22857
22858     case TYPE_REQ:
22859       return dependent_type_p (TREE_OPERAND (expression, 0));
22860
22861     case CALL_EXPR:
22862       {
22863         tree fn = get_callee_fndecl (expression);
22864         int i, nargs;
22865         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
22866           return true;
22867         nargs = call_expr_nargs (expression);
22868         for (i = 0; i < nargs; ++i)
22869           {
22870             tree op = CALL_EXPR_ARG (expression, i);
22871             /* In a call to a constexpr member function, look through the
22872                implicit ADDR_EXPR on the object argument so that it doesn't
22873                cause the call to be considered value-dependent.  We also
22874                look through it in potential_constant_expression.  */
22875             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
22876                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
22877                 && TREE_CODE (op) == ADDR_EXPR)
22878               op = TREE_OPERAND (op, 0);
22879             if (value_dependent_expression_p (op))
22880               return true;
22881           }
22882         return false;
22883       }
22884
22885     case TEMPLATE_ID_EXPR:
22886       /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
22887          type-dependent.  */
22888       return type_dependent_expression_p (expression)
22889         || variable_concept_p (TREE_OPERAND (expression, 0));
22890
22891     case CONSTRUCTOR:
22892       {
22893         unsigned ix;
22894         tree val;
22895         if (dependent_type_p (TREE_TYPE (expression)))
22896           return true;
22897         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
22898           if (value_dependent_expression_p (val))
22899             return true;
22900         return false;
22901       }
22902
22903     case STMT_EXPR:
22904       /* Treat a GNU statement expression as dependent to avoid crashing
22905          under instantiate_non_dependent_expr; it can't be constant.  */
22906       return true;
22907
22908     default:
22909       /* A constant expression is value-dependent if any subexpression is
22910          value-dependent.  */
22911       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
22912         {
22913         case tcc_reference:
22914         case tcc_unary:
22915         case tcc_comparison:
22916         case tcc_binary:
22917         case tcc_expression:
22918         case tcc_vl_exp:
22919           {
22920             int i, len = cp_tree_operand_length (expression);
22921
22922             for (i = 0; i < len; i++)
22923               {
22924                 tree t = TREE_OPERAND (expression, i);
22925
22926                 /* In some cases, some of the operands may be missing.l
22927                    (For example, in the case of PREDECREMENT_EXPR, the
22928                    amount to increment by may be missing.)  That doesn't
22929                    make the expression dependent.  */
22930                 if (t && value_dependent_expression_p (t))
22931                   return true;
22932               }
22933           }
22934           break;
22935         default:
22936           break;
22937         }
22938       break;
22939     }
22940
22941   /* The expression is not value-dependent.  */
22942   return false;
22943 }
22944
22945 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
22946    [temp.dep.expr].  Note that an expression with no type is
22947    considered dependent.  Other parts of the compiler arrange for an
22948    expression with type-dependent subexpressions to have no type, so
22949    this function doesn't have to be fully recursive.  */
22950
22951 bool
22952 type_dependent_expression_p (tree expression)
22953 {
22954   if (!processing_template_decl)
22955     return false;
22956
22957   if (expression == NULL_TREE || expression == error_mark_node)
22958     return false;
22959
22960   /* An unresolved name is always dependent.  */
22961   if (identifier_p (expression)
22962       || TREE_CODE (expression) == USING_DECL
22963       || TREE_CODE (expression) == WILDCARD_DECL)
22964     return true;
22965
22966   /* A fold expression is type-dependent. */
22967   if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
22968       || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
22969       || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
22970       || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
22971     return true;
22972
22973   /* Some expression forms are never type-dependent.  */
22974   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
22975       || TREE_CODE (expression) == SIZEOF_EXPR
22976       || TREE_CODE (expression) == ALIGNOF_EXPR
22977       || TREE_CODE (expression) == AT_ENCODE_EXPR
22978       || TREE_CODE (expression) == NOEXCEPT_EXPR
22979       || TREE_CODE (expression) == TRAIT_EXPR
22980       || TREE_CODE (expression) == TYPEID_EXPR
22981       || TREE_CODE (expression) == DELETE_EXPR
22982       || TREE_CODE (expression) == VEC_DELETE_EXPR
22983       || TREE_CODE (expression) == THROW_EXPR
22984       || TREE_CODE (expression) == REQUIRES_EXPR)
22985     return false;
22986
22987   /* The types of these expressions depends only on the type to which
22988      the cast occurs.  */
22989   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
22990       || TREE_CODE (expression) == STATIC_CAST_EXPR
22991       || TREE_CODE (expression) == CONST_CAST_EXPR
22992       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
22993       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
22994       || TREE_CODE (expression) == CAST_EXPR)
22995     return dependent_type_p (TREE_TYPE (expression));
22996
22997   /* The types of these expressions depends only on the type created
22998      by the expression.  */
22999   if (TREE_CODE (expression) == NEW_EXPR
23000       || TREE_CODE (expression) == VEC_NEW_EXPR)
23001     {
23002       /* For NEW_EXPR tree nodes created inside a template, either
23003          the object type itself or a TREE_LIST may appear as the
23004          operand 1.  */
23005       tree type = TREE_OPERAND (expression, 1);
23006       if (TREE_CODE (type) == TREE_LIST)
23007         /* This is an array type.  We need to check array dimensions
23008            as well.  */
23009         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
23010                || value_dependent_expression_p
23011                     (TREE_OPERAND (TREE_VALUE (type), 1));
23012       else
23013         return dependent_type_p (type);
23014     }
23015
23016   if (TREE_CODE (expression) == SCOPE_REF)
23017     {
23018       tree scope = TREE_OPERAND (expression, 0);
23019       tree name = TREE_OPERAND (expression, 1);
23020
23021       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
23022          contains an identifier associated by name lookup with one or more
23023          declarations declared with a dependent type, or...a
23024          nested-name-specifier or qualified-id that names a member of an
23025          unknown specialization.  */
23026       return (type_dependent_expression_p (name)
23027               || dependent_scope_p (scope));
23028     }
23029
23030   /* A function template specialization is type-dependent if it has any
23031      dependent template arguments.  */
23032   if (TREE_CODE (expression) == FUNCTION_DECL
23033       && DECL_LANG_SPECIFIC (expression)
23034       && DECL_TEMPLATE_INFO (expression))
23035     return any_dependent_template_arguments_p (DECL_TI_ARGS (expression));
23036
23037   if (TREE_CODE (expression) == TEMPLATE_DECL
23038       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
23039     return false;
23040
23041   if (TREE_CODE (expression) == STMT_EXPR)
23042     expression = stmt_expr_value_expr (expression);
23043
23044   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
23045     {
23046       tree elt;
23047       unsigned i;
23048
23049       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
23050         {
23051           if (type_dependent_expression_p (elt))
23052             return true;
23053         }
23054       return false;
23055     }
23056
23057   /* A static data member of the current instantiation with incomplete
23058      array type is type-dependent, as the definition and specializations
23059      can have different bounds.  */
23060   if (VAR_P (expression)
23061       && DECL_CLASS_SCOPE_P (expression)
23062       && dependent_type_p (DECL_CONTEXT (expression))
23063       && VAR_HAD_UNKNOWN_BOUND (expression))
23064     return true;
23065
23066   /* An array of unknown bound depending on a variadic parameter, eg:
23067
23068      template<typename... Args>
23069        void foo (Args... args)
23070        {
23071          int arr[] = { args... };
23072        }
23073
23074      template<int... vals>
23075        void bar ()
23076        {
23077          int arr[] = { vals... };
23078        }
23079
23080      If the array has no length and has an initializer, it must be that
23081      we couldn't determine its length in cp_complete_array_type because
23082      it is dependent.  */
23083   if (VAR_P (expression)
23084       && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
23085       && !TYPE_DOMAIN (TREE_TYPE (expression))
23086       && DECL_INITIAL (expression))
23087    return true;
23088
23089   /* A variable template specialization is type-dependent if it has any
23090      dependent template arguments.  */
23091   if (VAR_P (expression)
23092       && DECL_LANG_SPECIFIC (expression)
23093       && DECL_TEMPLATE_INFO (expression)
23094       && variable_template_p (DECL_TI_TEMPLATE (expression)))
23095     return any_dependent_template_arguments_p (DECL_TI_ARGS (expression));
23096
23097   /* Always dependent, on the number of arguments if nothing else.  */
23098   if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
23099     return true;
23100
23101   if (TREE_TYPE (expression) == unknown_type_node)
23102     {
23103       if (TREE_CODE (expression) == ADDR_EXPR)
23104         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
23105       if (TREE_CODE (expression) == COMPONENT_REF
23106           || TREE_CODE (expression) == OFFSET_REF)
23107         {
23108           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
23109             return true;
23110           expression = TREE_OPERAND (expression, 1);
23111           if (identifier_p (expression))
23112             return false;
23113         }
23114       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
23115       if (TREE_CODE (expression) == SCOPE_REF)
23116         return false;
23117
23118       if (BASELINK_P (expression))
23119         {
23120           if (BASELINK_OPTYPE (expression)
23121               && dependent_type_p (BASELINK_OPTYPE (expression)))
23122             return true;
23123           expression = BASELINK_FUNCTIONS (expression);
23124         }
23125
23126       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
23127         {
23128           if (any_dependent_template_arguments_p
23129               (TREE_OPERAND (expression, 1)))
23130             return true;
23131           expression = TREE_OPERAND (expression, 0);
23132           if (identifier_p (expression))
23133             return true;
23134         }
23135
23136       gcc_assert (TREE_CODE (expression) == OVERLOAD
23137                   || TREE_CODE (expression) == FUNCTION_DECL);
23138
23139       while (expression)
23140         {
23141           if (type_dependent_expression_p (OVL_CURRENT (expression)))
23142             return true;
23143           expression = OVL_NEXT (expression);
23144         }
23145       return false;
23146     }
23147
23148   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
23149
23150   return (dependent_type_p (TREE_TYPE (expression)));
23151 }
23152
23153 /* walk_tree callback function for instantiation_dependent_expression_p,
23154    below.  Returns non-zero if a dependent subexpression is found.  */
23155
23156 static tree
23157 instantiation_dependent_r (tree *tp, int *walk_subtrees,
23158                            void * /*data*/)
23159 {
23160   if (TYPE_P (*tp))
23161     {
23162       /* We don't have to worry about decltype currently because decltype
23163          of an instantiation-dependent expr is a dependent type.  This
23164          might change depending on the resolution of DR 1172.  */
23165       *walk_subtrees = false;
23166       return NULL_TREE;
23167     }
23168   enum tree_code code = TREE_CODE (*tp);
23169   switch (code)
23170     {
23171       /* Don't treat an argument list as dependent just because it has no
23172          TREE_TYPE.  */
23173     case TREE_LIST:
23174     case TREE_VEC:
23175       return NULL_TREE;
23176
23177     case TEMPLATE_PARM_INDEX:
23178       return *tp;
23179
23180       /* Handle expressions with type operands.  */
23181     case SIZEOF_EXPR:
23182     case ALIGNOF_EXPR:
23183     case TYPEID_EXPR:
23184     case AT_ENCODE_EXPR:
23185       {
23186         tree op = TREE_OPERAND (*tp, 0);
23187         if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
23188           op = TREE_TYPE (op);
23189         if (TYPE_P (op))
23190           {
23191             if (dependent_type_p (op))
23192               return *tp;
23193             else
23194               {
23195                 *walk_subtrees = false;
23196                 return NULL_TREE;
23197               }
23198           }
23199         break;
23200       }
23201
23202     case COMPONENT_REF:
23203       if (identifier_p (TREE_OPERAND (*tp, 1)))
23204         /* In a template, finish_class_member_access_expr creates a
23205            COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
23206            type-dependent, so that we can check access control at
23207            instantiation time (PR 42277).  See also Core issue 1273.  */
23208         return *tp;
23209       break;
23210
23211     case SCOPE_REF:
23212       if (instantiation_dependent_scope_ref_p (*tp))
23213         return *tp;
23214       else
23215         break;
23216
23217       /* Treat statement-expressions as dependent.  */
23218     case BIND_EXPR:
23219       return *tp;
23220
23221       /* Treat requires-expressions as dependent. */
23222     case REQUIRES_EXPR:
23223       return *tp;
23224
23225     case CALL_EXPR:
23226       /* Treat calls to function concepts as dependent. */
23227       if (function_concept_check_p (*tp))
23228         return *tp;
23229       break;
23230
23231     case TEMPLATE_ID_EXPR:
23232       /* And variable concepts.  */
23233       if (variable_concept_p (TREE_OPERAND (*tp, 0)))
23234         return *tp;
23235       break;
23236
23237     default:
23238       break;
23239     }
23240
23241   if (type_dependent_expression_p (*tp))
23242     return *tp;
23243   else
23244     return NULL_TREE;
23245 }
23246
23247 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
23248    sense defined by the ABI:
23249
23250    "An expression is instantiation-dependent if it is type-dependent
23251    or value-dependent, or it has a subexpression that is type-dependent
23252    or value-dependent."
23253
23254    Except don't actually check value-dependence for unevaluated expressions,
23255    because in sizeof(i) we don't care about the value of i.  Checking
23256    type-dependence will in turn check value-dependence of array bounds/template
23257    arguments as needed.  */
23258
23259 bool
23260 instantiation_dependent_uneval_expression_p (tree expression)
23261 {
23262   tree result;
23263
23264   if (!processing_template_decl)
23265     return false;
23266
23267   if (expression == error_mark_node)
23268     return false;
23269
23270   result = cp_walk_tree_without_duplicates (&expression,
23271                                             instantiation_dependent_r, NULL);
23272   return result != NULL_TREE;
23273 }
23274
23275 /* As above, but also check value-dependence of the expression as a whole.  */
23276
23277 bool
23278 instantiation_dependent_expression_p (tree expression)
23279 {
23280   return (instantiation_dependent_uneval_expression_p (expression)
23281           || value_dependent_expression_p (expression));
23282 }
23283
23284 /* Like type_dependent_expression_p, but it also works while not processing
23285    a template definition, i.e. during substitution or mangling.  */
23286
23287 bool
23288 type_dependent_expression_p_push (tree expr)
23289 {
23290   bool b;
23291   ++processing_template_decl;
23292   b = type_dependent_expression_p (expr);
23293   --processing_template_decl;
23294   return b;
23295 }
23296
23297 /* Returns TRUE if ARGS contains a type-dependent expression.  */
23298
23299 bool
23300 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
23301 {
23302   unsigned int i;
23303   tree arg;
23304
23305   FOR_EACH_VEC_SAFE_ELT (args, i, arg)
23306     {
23307       if (type_dependent_expression_p (arg))
23308         return true;
23309     }
23310   return false;
23311 }
23312
23313 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
23314    expressions) contains any type-dependent expressions.  */
23315
23316 bool
23317 any_type_dependent_elements_p (const_tree list)
23318 {
23319   for (; list; list = TREE_CHAIN (list))
23320     if (type_dependent_expression_p (TREE_VALUE (list)))
23321       return true;
23322
23323   return false;
23324 }
23325
23326 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
23327    expressions) contains any value-dependent expressions.  */
23328
23329 bool
23330 any_value_dependent_elements_p (const_tree list)
23331 {
23332   for (; list; list = TREE_CHAIN (list))
23333     if (value_dependent_expression_p (TREE_VALUE (list)))
23334       return true;
23335
23336   return false;
23337 }
23338
23339 /* Returns TRUE if the ARG (a template argument) is dependent.  */
23340
23341 bool
23342 dependent_template_arg_p (tree arg)
23343 {
23344   if (!processing_template_decl)
23345     return false;
23346
23347   /* Assume a template argument that was wrongly written by the user
23348      is dependent. This is consistent with what
23349      any_dependent_template_arguments_p [that calls this function]
23350      does.  */
23351   if (!arg || arg == error_mark_node)
23352     return true;
23353
23354   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
23355     arg = ARGUMENT_PACK_SELECT_ARG (arg);
23356
23357   if (TREE_CODE (arg) == TEMPLATE_DECL
23358       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
23359     return dependent_template_p (arg);
23360   else if (ARGUMENT_PACK_P (arg))
23361     {
23362       tree args = ARGUMENT_PACK_ARGS (arg);
23363       int i, len = TREE_VEC_LENGTH (args);
23364       for (i = 0; i < len; ++i)
23365         {
23366           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
23367             return true;
23368         }
23369
23370       return false;
23371     }
23372   else if (TYPE_P (arg))
23373     return dependent_type_p (arg);
23374   else
23375     return (type_dependent_expression_p (arg)
23376             || value_dependent_expression_p (arg));
23377 }
23378
23379 /* Returns true if ARGS (a collection of template arguments) contains
23380    any types that require structural equality testing.  */
23381
23382 bool
23383 any_template_arguments_need_structural_equality_p (tree args)
23384 {
23385   int i;
23386   int j;
23387
23388   if (!args)
23389     return false;
23390   if (args == error_mark_node)
23391     return true;
23392
23393   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
23394     {
23395       tree level = TMPL_ARGS_LEVEL (args, i + 1);
23396       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
23397         {
23398           tree arg = TREE_VEC_ELT (level, j);
23399           tree packed_args = NULL_TREE;
23400           int k, len = 1;
23401
23402           if (ARGUMENT_PACK_P (arg))
23403             {
23404               /* Look inside the argument pack.  */
23405               packed_args = ARGUMENT_PACK_ARGS (arg);
23406               len = TREE_VEC_LENGTH (packed_args);
23407             }
23408
23409           for (k = 0; k < len; ++k)
23410             {
23411               if (packed_args)
23412                 arg = TREE_VEC_ELT (packed_args, k);
23413
23414               if (error_operand_p (arg))
23415                 return true;
23416               else if (TREE_CODE (arg) == TEMPLATE_DECL)
23417                 continue;
23418               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
23419                 return true;
23420               else if (!TYPE_P (arg) && TREE_TYPE (arg)
23421                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
23422                 return true;
23423             }
23424         }
23425     }
23426
23427   return false;
23428 }
23429
23430 /* Returns true if ARGS (a collection of template arguments) contains
23431    any dependent arguments.  */
23432
23433 bool
23434 any_dependent_template_arguments_p (const_tree args)
23435 {
23436   int i;
23437   int j;
23438
23439   if (!args)
23440     return false;
23441   if (args == error_mark_node)
23442     return true;
23443
23444   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
23445     {
23446       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
23447       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
23448         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
23449           return true;
23450     }
23451
23452   return false;
23453 }
23454
23455 /* Returns TRUE if the template TMPL is dependent.  */
23456
23457 bool
23458 dependent_template_p (tree tmpl)
23459 {
23460   if (TREE_CODE (tmpl) == OVERLOAD)
23461     {
23462       while (tmpl)
23463         {
23464           if (dependent_template_p (OVL_CURRENT (tmpl)))
23465             return true;
23466           tmpl = OVL_NEXT (tmpl);
23467         }
23468       return false;
23469     }
23470
23471   /* Template template parameters are dependent.  */
23472   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
23473       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
23474     return true;
23475   /* So are names that have not been looked up.  */
23476   if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
23477     return true;
23478   /* So are member templates of dependent classes.  */
23479   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
23480     return dependent_type_p (DECL_CONTEXT (tmpl));
23481   return false;
23482 }
23483
23484 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
23485
23486 bool
23487 dependent_template_id_p (tree tmpl, tree args)
23488 {
23489   return (dependent_template_p (tmpl)
23490           || any_dependent_template_arguments_p (args));
23491 }
23492
23493 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
23494    are dependent.  */
23495
23496 bool
23497 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
23498 {
23499   int i;
23500
23501   if (!processing_template_decl)
23502     return false;
23503
23504   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
23505     {
23506       tree decl = TREE_VEC_ELT (declv, i);
23507       tree init = TREE_VEC_ELT (initv, i);
23508       tree cond = TREE_VEC_ELT (condv, i);
23509       tree incr = TREE_VEC_ELT (incrv, i);
23510
23511       if (type_dependent_expression_p (decl)
23512           || TREE_CODE (decl) == SCOPE_REF)
23513         return true;
23514
23515       if (init && type_dependent_expression_p (init))
23516         return true;
23517
23518       if (type_dependent_expression_p (cond))
23519         return true;
23520
23521       if (COMPARISON_CLASS_P (cond)
23522           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
23523               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
23524         return true;
23525
23526       if (TREE_CODE (incr) == MODOP_EXPR)
23527         {
23528           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
23529               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
23530             return true;
23531         }
23532       else if (type_dependent_expression_p (incr))
23533         return true;
23534       else if (TREE_CODE (incr) == MODIFY_EXPR)
23535         {
23536           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
23537             return true;
23538           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
23539             {
23540               tree t = TREE_OPERAND (incr, 1);
23541               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
23542                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
23543                 return true;
23544             }
23545         }
23546     }
23547
23548   return false;
23549 }
23550
23551 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
23552    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
23553    no such TYPE can be found.  Note that this function peers inside
23554    uninstantiated templates and therefore should be used only in
23555    extremely limited situations.  ONLY_CURRENT_P restricts this
23556    peering to the currently open classes hierarchy (which is required
23557    when comparing types).  */
23558
23559 tree
23560 resolve_typename_type (tree type, bool only_current_p)
23561 {
23562   tree scope;
23563   tree name;
23564   tree decl;
23565   int quals;
23566   tree pushed_scope;
23567   tree result;
23568
23569   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
23570
23571   scope = TYPE_CONTEXT (type);
23572   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
23573      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
23574      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
23575      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
23576      identifier  of the TYPENAME_TYPE anymore.
23577      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
23578      TYPENAME_TYPE instead, we avoid messing up with a possible
23579      typedef variant case.  */
23580   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
23581
23582   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
23583      it first before we can figure out what NAME refers to.  */
23584   if (TREE_CODE (scope) == TYPENAME_TYPE)
23585     {
23586       if (TYPENAME_IS_RESOLVING_P (scope))
23587         /* Given a class template A with a dependent base with nested type C,
23588            typedef typename A::C::C C will land us here, as trying to resolve
23589            the initial A::C leads to the local C typedef, which leads back to
23590            A::C::C.  So we break the recursion now.  */
23591         return type;
23592       else
23593         scope = resolve_typename_type (scope, only_current_p);
23594     }
23595   /* If we don't know what SCOPE refers to, then we cannot resolve the
23596      TYPENAME_TYPE.  */
23597   if (!CLASS_TYPE_P (scope))
23598     return type;
23599   /* If this is a typedef, we don't want to look inside (c++/11987).  */
23600   if (typedef_variant_p (type))
23601     return type;
23602   /* If SCOPE isn't the template itself, it will not have a valid
23603      TYPE_FIELDS list.  */
23604   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
23605     /* scope is either the template itself or a compatible instantiation
23606        like X<T>, so look up the name in the original template.  */
23607     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
23608   /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope.  */
23609   gcc_checking_assert (uses_template_parms (scope));
23610   /* If scope has no fields, it can't be a current instantiation.  Check this
23611      before currently_open_class to avoid infinite recursion (71515).  */
23612   if (!TYPE_FIELDS (scope))
23613     return type;
23614   /* If the SCOPE is not the current instantiation, there's no reason
23615      to look inside it.  */
23616   if (only_current_p && !currently_open_class (scope))
23617     return type;
23618   /* Enter the SCOPE so that name lookup will be resolved as if we
23619      were in the class definition.  In particular, SCOPE will no
23620      longer be considered a dependent type.  */
23621   pushed_scope = push_scope (scope);
23622   /* Look up the declaration.  */
23623   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
23624                         tf_warning_or_error);
23625
23626   result = NULL_TREE;
23627   
23628   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
23629      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
23630   if (!decl)
23631     /*nop*/;
23632   else if (identifier_p (TYPENAME_TYPE_FULLNAME (type))
23633            && TREE_CODE (decl) == TYPE_DECL)
23634     {
23635       result = TREE_TYPE (decl);
23636       if (result == error_mark_node)
23637         result = NULL_TREE;
23638     }
23639   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
23640            && DECL_CLASS_TEMPLATE_P (decl))
23641     {
23642       tree tmpl;
23643       tree args;
23644       /* Obtain the template and the arguments.  */
23645       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
23646       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
23647       /* Instantiate the template.  */
23648       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
23649                                       /*entering_scope=*/0,
23650                                       tf_error | tf_user);
23651       if (result == error_mark_node)
23652         result = NULL_TREE;
23653     }
23654   
23655   /* Leave the SCOPE.  */
23656   if (pushed_scope)
23657     pop_scope (pushed_scope);
23658
23659   /* If we failed to resolve it, return the original typename.  */
23660   if (!result)
23661     return type;
23662   
23663   /* If lookup found a typename type, resolve that too.  */
23664   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
23665     {
23666       /* Ill-formed programs can cause infinite recursion here, so we
23667          must catch that.  */
23668       TYPENAME_IS_RESOLVING_P (result) = 1;
23669       result = resolve_typename_type (result, only_current_p);
23670       TYPENAME_IS_RESOLVING_P (result) = 0;
23671     }
23672   
23673   /* Qualify the resulting type.  */
23674   quals = cp_type_quals (type);
23675   if (quals)
23676     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
23677
23678   return result;
23679 }
23680
23681 /* EXPR is an expression which is not type-dependent.  Return a proxy
23682    for EXPR that can be used to compute the types of larger
23683    expressions containing EXPR.  */
23684
23685 tree
23686 build_non_dependent_expr (tree expr)
23687 {
23688   tree inner_expr;
23689
23690   /* When checking, try to get a constant value for all non-dependent
23691      expressions in order to expose bugs in *_dependent_expression_p
23692      and constexpr.  This checking can change code generation, temporarily
23693      disabled.  See PR70704.  */
23694   if (0 && flag_checking && cxx_dialect >= cxx11
23695       /* Don't do this during nsdmi parsing as it can lead to
23696          unexpected recursive instantiations.  */
23697       && !parsing_nsdmi ()
23698       /* Don't do this during concept expansion either and for
23699          the same reason.  */
23700       && !expanding_concept ())
23701     fold_non_dependent_expr (expr);
23702
23703   /* Preserve OVERLOADs; the functions must be available to resolve
23704      types.  */
23705   inner_expr = expr;
23706   if (TREE_CODE (inner_expr) == STMT_EXPR)
23707     inner_expr = stmt_expr_value_expr (inner_expr);
23708   if (TREE_CODE (inner_expr) == ADDR_EXPR)
23709     inner_expr = TREE_OPERAND (inner_expr, 0);
23710   if (TREE_CODE (inner_expr) == COMPONENT_REF)
23711     inner_expr = TREE_OPERAND (inner_expr, 1);
23712   if (is_overloaded_fn (inner_expr)
23713       || TREE_CODE (inner_expr) == OFFSET_REF)
23714     return expr;
23715   /* There is no need to return a proxy for a variable.  */
23716   if (VAR_P (expr))
23717     return expr;
23718   /* Preserve string constants; conversions from string constants to
23719      "char *" are allowed, even though normally a "const char *"
23720      cannot be used to initialize a "char *".  */
23721   if (TREE_CODE (expr) == STRING_CST)
23722     return expr;
23723   /* Preserve void and arithmetic constants, as an optimization -- there is no
23724      reason to create a new node.  */
23725   if (TREE_CODE (expr) == VOID_CST
23726       || TREE_CODE (expr) == INTEGER_CST
23727       || TREE_CODE (expr) == REAL_CST)
23728     return expr;
23729   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
23730      There is at least one place where we want to know that a
23731      particular expression is a throw-expression: when checking a ?:
23732      expression, there are special rules if the second or third
23733      argument is a throw-expression.  */
23734   if (TREE_CODE (expr) == THROW_EXPR)
23735     return expr;
23736
23737   /* Don't wrap an initializer list, we need to be able to look inside.  */
23738   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
23739     return expr;
23740
23741   /* Don't wrap a dummy object, we need to be able to test for it.  */
23742   if (is_dummy_object (expr))
23743     return expr;
23744
23745   if (TREE_CODE (expr) == COND_EXPR)
23746     return build3 (COND_EXPR,
23747                    TREE_TYPE (expr),
23748                    TREE_OPERAND (expr, 0),
23749                    (TREE_OPERAND (expr, 1)
23750                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
23751                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
23752                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
23753   if (TREE_CODE (expr) == COMPOUND_EXPR
23754       && !COMPOUND_EXPR_OVERLOADED (expr))
23755     return build2 (COMPOUND_EXPR,
23756                    TREE_TYPE (expr),
23757                    TREE_OPERAND (expr, 0),
23758                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
23759
23760   /* If the type is unknown, it can't really be non-dependent */
23761   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
23762
23763   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
23764   return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
23765 }
23766
23767 /* ARGS is a vector of expressions as arguments to a function call.
23768    Replace the arguments with equivalent non-dependent expressions.
23769    This modifies ARGS in place.  */
23770
23771 void
23772 make_args_non_dependent (vec<tree, va_gc> *args)
23773 {
23774   unsigned int ix;
23775   tree arg;
23776
23777   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
23778     {
23779       tree newarg = build_non_dependent_expr (arg);
23780       if (newarg != arg)
23781         (*args)[ix] = newarg;
23782     }
23783 }
23784
23785 /* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
23786    TEMPLATE_TYPE_PARM with a level one deeper than the actual template
23787    parms.  If set_canonical is true, we set TYPE_CANONICAL on it.  */
23788
23789 static tree
23790 make_auto_1 (tree name, bool set_canonical)
23791 {
23792   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
23793   TYPE_NAME (au) = build_decl (input_location,
23794                                TYPE_DECL, name, au);
23795   TYPE_STUB_DECL (au) = TYPE_NAME (au);
23796   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
23797     (0, processing_template_decl + 1, processing_template_decl + 1,
23798      TYPE_NAME (au), NULL_TREE);
23799   if (set_canonical)
23800     TYPE_CANONICAL (au) = canonical_type_parameter (au);
23801   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
23802   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
23803
23804   return au;
23805 }
23806
23807 tree
23808 make_decltype_auto (void)
23809 {
23810   return make_auto_1 (get_identifier ("decltype(auto)"), true);
23811 }
23812
23813 tree
23814 make_auto (void)
23815 {
23816   return make_auto_1 (get_identifier ("auto"), true);
23817 }
23818
23819 /* Make a "constrained auto" type-specifier. This is an
23820    auto type with constraints that must be associated after
23821    deduction.  The constraint is formed from the given
23822    CONC and its optional sequence of arguments, which are
23823    non-null if written as partial-concept-id.  */
23824
23825 tree
23826 make_constrained_auto (tree con, tree args)
23827 {
23828   tree type = make_auto_1 (get_identifier ("auto"), false);
23829
23830   /* Build the constraint. */
23831   tree tmpl = DECL_TI_TEMPLATE (con);
23832   tree expr;
23833   if (VAR_P (con))
23834     expr = build_concept_check (tmpl, type, args);
23835   else
23836     expr = build_concept_check (build_overload (tmpl, NULL_TREE), type, args);
23837
23838   tree constr = normalize_expression (expr);
23839   PLACEHOLDER_TYPE_CONSTRAINTS (type) = constr;
23840
23841   /* Our canonical type depends on the constraint.  */
23842   TYPE_CANONICAL (type) = canonical_type_parameter (type);
23843
23844   /* Attach the constraint to the type declaration. */
23845   tree decl = TYPE_NAME (type);
23846   return decl;
23847 }
23848
23849 /* Given type ARG, return std::initializer_list<ARG>.  */
23850
23851 static tree
23852 listify (tree arg)
23853 {
23854   tree std_init_list = namespace_binding
23855     (get_identifier ("initializer_list"), std_node);
23856   tree argvec;
23857   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
23858     {    
23859       error ("deducing from brace-enclosed initializer list requires "
23860              "#include <initializer_list>");
23861       return error_mark_node;
23862     }
23863   argvec = make_tree_vec (1);
23864   TREE_VEC_ELT (argvec, 0) = arg;
23865   return lookup_template_class (std_init_list, argvec, NULL_TREE,
23866                                 NULL_TREE, 0, tf_warning_or_error);
23867 }
23868
23869 /* Replace auto in TYPE with std::initializer_list<auto>.  */
23870
23871 static tree
23872 listify_autos (tree type, tree auto_node)
23873 {
23874   tree init_auto = listify (auto_node);
23875   tree argvec = make_tree_vec (1);
23876   TREE_VEC_ELT (argvec, 0) = init_auto;
23877   if (processing_template_decl)
23878     argvec = add_to_template_args (current_template_args (), argvec);
23879   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
23880 }
23881
23882 /* Hash traits for hashing possibly constrained 'auto'
23883    TEMPLATE_TYPE_PARMs for use by do_auto_deduction.  */
23884
23885 struct auto_hash : default_hash_traits<tree>
23886 {
23887   static inline hashval_t hash (tree);
23888   static inline bool equal (tree, tree);
23889 };
23890
23891 /* Hash the 'auto' T.  */
23892
23893 inline hashval_t
23894 auto_hash::hash (tree t)
23895 {
23896   if (tree c = PLACEHOLDER_TYPE_CONSTRAINTS (t))
23897     /* Matching constrained-type-specifiers denote the same template
23898        parameter, so hash the constraint.  */
23899     return hash_placeholder_constraint (c);
23900   else
23901     /* But unconstrained autos are all separate, so just hash the pointer.  */
23902     return iterative_hash_object (t, 0);
23903 }
23904
23905 /* Compare two 'auto's.  */
23906
23907 inline bool
23908 auto_hash::equal (tree t1, tree t2)
23909 {
23910   if (t1 == t2)
23911     return true;
23912
23913   tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
23914   tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
23915
23916   /* Two unconstrained autos are distinct.  */
23917   if (!c1 || !c2)
23918     return false;
23919
23920   return equivalent_placeholder_constraints (c1, c2);
23921 }
23922
23923 /* for_each_template_parm callback for extract_autos: if t is a (possibly
23924    constrained) auto, add it to the vector.  */
23925
23926 static int
23927 extract_autos_r (tree t, void *data)
23928 {
23929   hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
23930   if (is_auto_or_concept (t))
23931     {
23932       /* All the autos were built with index 0; fix that up now.  */
23933       tree *p = hash.find_slot (t, INSERT);
23934       unsigned idx;
23935       if (*p)
23936         /* If this is a repeated constrained-type-specifier, use the index we
23937            chose before.  */
23938         idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
23939       else
23940         {
23941           /* Otherwise this is new, so use the current count.  */
23942           *p = t;
23943           idx = hash.elements () - 1;
23944         }
23945       TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
23946     }
23947
23948   /* Always keep walking.  */
23949   return 0;
23950 }
23951
23952 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
23953    says they can appear anywhere in the type.  */
23954
23955 static tree
23956 extract_autos (tree type)
23957 {
23958   hash_set<tree> visited;
23959   hash_table<auto_hash> hash (2);
23960
23961   for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
23962
23963   tree tree_vec = make_tree_vec (hash.elements());
23964   for (hash_table<auto_hash>::iterator iter = hash.begin();
23965        iter != hash.end(); ++iter)
23966     {
23967       tree elt = *iter;
23968       unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
23969       TREE_VEC_ELT (tree_vec, i)
23970         = build_tree_list (NULL_TREE, TYPE_NAME (elt));
23971     }
23972
23973   return tree_vec;
23974 }
23975
23976 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
23977    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
23978
23979 tree
23980 do_auto_deduction (tree type, tree init, tree auto_node)
23981 {
23982   return do_auto_deduction (type, init, auto_node,
23983                             tf_warning_or_error,
23984                             adc_unspecified);
23985 }
23986
23987 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
23988    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
23989    The CONTEXT determines the context in which auto deduction is performed
23990    and is used to control error diagnostics.
23991
23992    For partial-concept-ids, extra args may be appended to the list of deduced
23993    template arguments prior to determining constraint satisfaction.  */
23994
23995 tree
23996 do_auto_deduction (tree type, tree init, tree auto_node,
23997                    tsubst_flags_t complain, auto_deduction_context context)
23998 {
23999   tree targs;
24000
24001   if (init == error_mark_node)
24002     return error_mark_node;
24003
24004   if (type_dependent_expression_p (init))
24005     /* Defining a subset of type-dependent expressions that we can deduce
24006        from ahead of time isn't worth the trouble.  */
24007     return type;
24008
24009   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
24010      with either a new invented type template parameter U or, if the
24011      initializer is a braced-init-list (8.5.4), with
24012      std::initializer_list<U>.  */
24013   if (BRACE_ENCLOSED_INITIALIZER_P (init))
24014     {
24015       if (!DIRECT_LIST_INIT_P (init))
24016         type = listify_autos (type, auto_node);
24017       else if (CONSTRUCTOR_NELTS (init) == 1)
24018         init = CONSTRUCTOR_ELT (init, 0)->value;
24019       else
24020         {
24021           if (complain & tf_warning_or_error)
24022             {
24023               if (permerror (input_location, "direct-list-initialization of "
24024                              "%<auto%> requires exactly one element"))
24025                 inform (input_location,
24026                         "for deduction to %<std::initializer_list%>, use copy-"
24027                         "list-initialization (i.e. add %<=%> before the %<{%>)");
24028             }
24029           type = listify_autos (type, auto_node);
24030         }
24031     }
24032
24033   if (type == error_mark_node)
24034     return error_mark_node;
24035
24036   init = resolve_nondeduced_context (init, complain);
24037
24038   if (AUTO_IS_DECLTYPE (auto_node))
24039     {
24040       bool id = (DECL_P (init)
24041                  || ((TREE_CODE (init) == COMPONENT_REF
24042                       || TREE_CODE (init) == SCOPE_REF)
24043                      && !REF_PARENTHESIZED_P (init)));
24044       targs = make_tree_vec (1);
24045       TREE_VEC_ELT (targs, 0)
24046         = finish_decltype_type (init, id, tf_warning_or_error);
24047       if (type != auto_node)
24048         {
24049           if (complain & tf_error)
24050             error ("%qT as type rather than plain %<decltype(auto)%>", type);
24051           return error_mark_node;
24052         }
24053     }
24054   else
24055     {
24056       tree parms = build_tree_list (NULL_TREE, type);
24057       tree tparms;
24058
24059       if (flag_concepts)
24060         tparms = extract_autos (type);
24061       else
24062         {
24063           tparms = make_tree_vec (1);
24064           TREE_VEC_ELT (tparms, 0)
24065             = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
24066         }
24067
24068       targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
24069       int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
24070                                        DEDUCE_CALL, LOOKUP_NORMAL,
24071                                        NULL, /*explain_p=*/false);
24072       if (val > 0)
24073         {
24074           if (processing_template_decl)
24075             /* Try again at instantiation time.  */
24076             return type;
24077           if (type && type != error_mark_node
24078               && (complain & tf_error))
24079             /* If type is error_mark_node a diagnostic must have been
24080                emitted by now.  Also, having a mention to '<type error>'
24081                in the diagnostic is not really useful to the user.  */
24082             {
24083               if (cfun && auto_node == current_function_auto_return_pattern
24084                   && LAMBDA_FUNCTION_P (current_function_decl))
24085                 error ("unable to deduce lambda return type from %qE", init);
24086               else
24087                 error ("unable to deduce %qT from %qE", type, init);
24088               type_unification_real (tparms, targs, parms, &init, 1, 0,
24089                                      DEDUCE_CALL, LOOKUP_NORMAL,
24090                                      NULL, /*explain_p=*/true);
24091             }
24092           return error_mark_node;
24093         }
24094     }
24095
24096   /* Check any placeholder constraints against the deduced type. */
24097   if (flag_concepts && !processing_template_decl)
24098     if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (auto_node))
24099       {
24100         /* Use the deduced type to check the associated constraints. If we
24101            have a partial-concept-id, rebuild the argument list so that
24102            we check using the extra arguments. */
24103         gcc_assert (TREE_CODE (constr) == CHECK_CONSTR);
24104         tree cargs = CHECK_CONSTR_ARGS (constr);
24105         if (TREE_VEC_LENGTH (cargs) > 1)
24106           {
24107             cargs = copy_node (cargs);
24108             TREE_VEC_ELT (cargs, 0) = TREE_VEC_ELT (targs, 0);
24109           }
24110         else
24111           cargs = targs;
24112         if (!constraints_satisfied_p (constr, cargs))
24113           {
24114             if (complain & tf_warning_or_error)
24115               {
24116                 switch (context)
24117                   {
24118                   case adc_unspecified:
24119                     error("placeholder constraints not satisfied");
24120                     break;
24121                   case adc_variable_type:
24122                     error ("deduced initializer does not satisfy "
24123                            "placeholder constraints");
24124                     break;
24125                   case adc_return_type:
24126                     error ("deduced return type does not satisfy "
24127                            "placeholder constraints");
24128                     break;
24129                   case adc_requirement:
24130                     error ("deduced expression type does not saatisy "
24131                            "placeholder constraints");
24132                     break;
24133                   }
24134                 diagnose_constraints (input_location, constr, targs);
24135               }
24136             return error_mark_node;
24137           }
24138       }
24139
24140   if (processing_template_decl)
24141     targs = add_to_template_args (current_template_args (), targs);
24142   return tsubst (type, targs, complain, NULL_TREE);
24143 }
24144
24145 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
24146    result.  */
24147
24148 tree
24149 splice_late_return_type (tree type, tree late_return_type)
24150 {
24151   if (is_auto (type))
24152     {
24153       if (late_return_type)
24154         return late_return_type;
24155
24156       tree idx = get_template_parm_index (type);
24157       if (TEMPLATE_PARM_LEVEL (idx) <= processing_template_decl)
24158         /* In an abbreviated function template we didn't know we were dealing
24159            with a function template when we saw the auto return type, so update
24160            it to have the correct level.  */
24161         return make_auto_1 (TYPE_IDENTIFIER (type), true);
24162     }
24163   return type;
24164 }
24165
24166 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
24167    'decltype(auto)'.  */
24168
24169 bool
24170 is_auto (const_tree type)
24171 {
24172   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
24173       && (TYPE_IDENTIFIER (type) == get_identifier ("auto")
24174           || TYPE_IDENTIFIER (type) == get_identifier ("decltype(auto)")))
24175     return true;
24176   else
24177     return false;
24178 }
24179
24180 /* for_each_template_parm callback for type_uses_auto.  */
24181
24182 int
24183 is_auto_r (tree tp, void */*data*/)
24184 {
24185   return is_auto_or_concept (tp);
24186 }
24187
24188 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
24189    a use of `auto'.  Returns NULL_TREE otherwise.  */
24190
24191 tree
24192 type_uses_auto (tree type)
24193 {
24194   if (type == NULL_TREE)
24195     return NULL_TREE;
24196   else if (flag_concepts)
24197     {
24198       /* The Concepts TS allows multiple autos in one type-specifier; just
24199          return the first one we find, do_auto_deduction will collect all of
24200          them.  */
24201       if (uses_template_parms (type))
24202         return for_each_template_parm (type, is_auto_r, /*data*/NULL,
24203                                        /*visited*/NULL, /*nondeduced*/true);
24204       else
24205         return NULL_TREE;
24206     }
24207   else
24208     return find_type_usage (type, is_auto);
24209 }
24210
24211 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto',
24212    'decltype(auto)' or a concept.  */
24213
24214 bool
24215 is_auto_or_concept (const_tree type)
24216 {
24217   return is_auto (type); // or concept
24218 }
24219
24220 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing a generic type (`auto' or
24221    a concept identifier) iff TYPE contains a use of a generic type.  Returns
24222    NULL_TREE otherwise.  */
24223
24224 tree
24225 type_uses_auto_or_concept (tree type)
24226 {
24227   return find_type_usage (type, is_auto_or_concept);
24228 }
24229
24230
24231 /* For a given template T, return the vector of typedefs referenced
24232    in T for which access check is needed at T instantiation time.
24233    T is either  a FUNCTION_DECL or a RECORD_TYPE.
24234    Those typedefs were added to T by the function
24235    append_type_to_template_for_access_check.  */
24236
24237 vec<qualified_typedef_usage_t, va_gc> *
24238 get_types_needing_access_check (tree t)
24239 {
24240   tree ti;
24241   vec<qualified_typedef_usage_t, va_gc> *result = NULL;
24242
24243   if (!t || t == error_mark_node)
24244     return NULL;
24245
24246   if (!(ti = get_template_info (t)))
24247     return NULL;
24248
24249   if (CLASS_TYPE_P (t)
24250       || TREE_CODE (t) == FUNCTION_DECL)
24251     {
24252       if (!TI_TEMPLATE (ti))
24253         return NULL;
24254
24255       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
24256     }
24257
24258   return result;
24259 }
24260
24261 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
24262    tied to T. That list of typedefs will be access checked at
24263    T instantiation time.
24264    T is either a FUNCTION_DECL or a RECORD_TYPE.
24265    TYPE_DECL is a TYPE_DECL node representing a typedef.
24266    SCOPE is the scope through which TYPE_DECL is accessed.
24267    LOCATION is the location of the usage point of TYPE_DECL.
24268
24269    This function is a subroutine of
24270    append_type_to_template_for_access_check.  */
24271
24272 static void
24273 append_type_to_template_for_access_check_1 (tree t,
24274                                             tree type_decl,
24275                                             tree scope,
24276                                             location_t location)
24277 {
24278   qualified_typedef_usage_t typedef_usage;
24279   tree ti;
24280
24281   if (!t || t == error_mark_node)
24282     return;
24283
24284   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
24285                || CLASS_TYPE_P (t))
24286               && type_decl
24287               && TREE_CODE (type_decl) == TYPE_DECL
24288               && scope);
24289
24290   if (!(ti = get_template_info (t)))
24291     return;
24292
24293   gcc_assert (TI_TEMPLATE (ti));
24294
24295   typedef_usage.typedef_decl = type_decl;
24296   typedef_usage.context = scope;
24297   typedef_usage.locus = location;
24298
24299   vec_safe_push (TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti), typedef_usage);
24300 }
24301
24302 /* Append TYPE_DECL to the template TEMPL.
24303    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
24304    At TEMPL instanciation time, TYPE_DECL will be checked to see
24305    if it can be accessed through SCOPE.
24306    LOCATION is the location of the usage point of TYPE_DECL.
24307
24308    e.g. consider the following code snippet:
24309
24310      class C
24311      {
24312        typedef int myint;
24313      };
24314
24315      template<class U> struct S
24316      {
24317        C::myint mi; // <-- usage point of the typedef C::myint
24318      };
24319
24320      S<char> s;
24321
24322    At S<char> instantiation time, we need to check the access of C::myint
24323    In other words, we need to check the access of the myint typedef through
24324    the C scope. For that purpose, this function will add the myint typedef
24325    and the scope C through which its being accessed to a list of typedefs
24326    tied to the template S. That list will be walked at template instantiation
24327    time and access check performed on each typedefs it contains.
24328    Note that this particular code snippet should yield an error because
24329    myint is private to C.  */
24330
24331 void
24332 append_type_to_template_for_access_check (tree templ,
24333                                           tree type_decl,
24334                                           tree scope,
24335                                           location_t location)
24336 {
24337   qualified_typedef_usage_t *iter;
24338   unsigned i;
24339
24340   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
24341
24342   /* Make sure we don't append the type to the template twice.  */
24343   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (templ), i, iter)
24344     if (iter->typedef_decl == type_decl && scope == iter->context)
24345       return;
24346
24347   append_type_to_template_for_access_check_1 (templ, type_decl,
24348                                               scope, location);
24349 }
24350
24351 /* Convert the generic type parameters in PARM that match the types given in the
24352    range [START_IDX, END_IDX) from the current_template_parms into generic type
24353    packs.  */
24354
24355 tree
24356 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
24357 {
24358   tree current = current_template_parms;
24359   int depth = TMPL_PARMS_DEPTH (current);
24360   current = INNERMOST_TEMPLATE_PARMS (current);
24361   tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
24362
24363   for (int i = 0; i < start_idx; ++i)
24364     TREE_VEC_ELT (replacement, i)
24365       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
24366
24367   for (int i = start_idx; i < end_idx; ++i)
24368     {
24369       /* Create a distinct parameter pack type from the current parm and add it
24370          to the replacement args to tsubst below into the generic function
24371          parameter.  */
24372
24373       tree o = TREE_TYPE (TREE_VALUE
24374                           (TREE_VEC_ELT (current, i)));
24375       tree t = copy_type (o);
24376       TEMPLATE_TYPE_PARM_INDEX (t)
24377         = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
24378                                       o, 0, 0, tf_none);
24379       TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
24380       TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
24381       TYPE_MAIN_VARIANT (t) = t;
24382       TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
24383       TYPE_CANONICAL (t) = canonical_type_parameter (t);
24384       TREE_VEC_ELT (replacement, i) = t;
24385       TREE_VALUE (TREE_VEC_ELT (current, i)) = TREE_CHAIN (t);
24386     }
24387
24388   for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
24389     TREE_VEC_ELT (replacement, i)
24390       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
24391
24392   /* If there are more levels then build up the replacement with the outer
24393      template parms.  */
24394   if (depth > 1)
24395     replacement = add_to_template_args (template_parms_to_args
24396                                         (TREE_CHAIN (current_template_parms)),
24397                                         replacement);
24398
24399   return tsubst (parm, replacement, tf_none, NULL_TREE);
24400 }
24401
24402 /* Entries in the decl_constraint hash table. */
24403 struct GTY((for_user)) constr_entry
24404 {
24405   tree decl;
24406   tree ci;
24407 };
24408
24409 /* Hashing function and equality for constraint entries. */
24410 struct constr_hasher : ggc_ptr_hash<constr_entry>
24411 {
24412   static hashval_t hash (constr_entry *e)
24413   {
24414     return (hashval_t)DECL_UID (e->decl);
24415   }
24416
24417   static bool equal (constr_entry *e1, constr_entry *e2)
24418   {
24419     return e1->decl == e2->decl;
24420   }
24421 };
24422
24423 /* A mapping from declarations to constraint information. Note that
24424    both templates and their underlying declarations are mapped to the
24425    same constraint information.
24426
24427    FIXME: This is defined in pt.c because garbage collection
24428    code is not being generated for constraint.cc. */
24429
24430 static GTY (()) hash_table<constr_hasher> *decl_constraints;
24431
24432 /* Returns the template constraints of declaration T. If T is not
24433    constrained, return NULL_TREE. Note that T must be non-null. */
24434
24435 tree
24436 get_constraints (tree t)
24437 {
24438   if (!flag_concepts)
24439     return NULL_TREE;
24440
24441   gcc_assert (DECL_P (t));
24442   if (TREE_CODE (t) == TEMPLATE_DECL)
24443     t = DECL_TEMPLATE_RESULT (t);
24444   constr_entry elt = { t, NULL_TREE };
24445   constr_entry* found = decl_constraints->find (&elt);
24446   if (found)
24447     return found->ci;
24448   else
24449     return NULL_TREE;
24450 }
24451
24452 /* Associate the given constraint information CI with the declaration
24453    T. If T is a template, then the constraints are associated with
24454    its underlying declaration. Don't build associations if CI is
24455    NULL_TREE.  */
24456
24457 void
24458 set_constraints (tree t, tree ci)
24459 {
24460   if (!ci)
24461     return;
24462   gcc_assert (t && flag_concepts);
24463   if (TREE_CODE (t) == TEMPLATE_DECL)
24464     t = DECL_TEMPLATE_RESULT (t);
24465   gcc_assert (!get_constraints (t));
24466   constr_entry elt = {t, ci};
24467   constr_entry** slot = decl_constraints->find_slot (&elt, INSERT);
24468   constr_entry* entry = ggc_alloc<constr_entry> ();
24469   *entry = elt;
24470   *slot = entry;
24471 }
24472
24473 /* Remove the associated constraints of the declaration T.  */
24474
24475 void
24476 remove_constraints (tree t)
24477 {
24478   gcc_assert (DECL_P (t));
24479   if (TREE_CODE (t) == TEMPLATE_DECL)
24480     t = DECL_TEMPLATE_RESULT (t);
24481
24482   constr_entry elt = {t, NULL_TREE};
24483   constr_entry** slot = decl_constraints->find_slot (&elt, NO_INSERT);
24484   if (slot)
24485     decl_constraints->clear_slot (slot);
24486 }
24487
24488 /* Memoized satisfaction results for declarations. This
24489    maps the pair (constraint_info, arguments) to the result computed
24490    by constraints_satisfied_p.  */
24491
24492 struct GTY((for_user)) constraint_sat_entry
24493 {
24494   tree ci;
24495   tree args;
24496   tree result;
24497 };
24498
24499 /* Hashing function and equality for constraint entries. */
24500
24501 struct constraint_sat_hasher : ggc_ptr_hash<constraint_sat_entry>
24502 {
24503   static hashval_t hash (constraint_sat_entry *e)
24504   {
24505     hashval_t val = iterative_hash_object(e->ci, 0);
24506     return iterative_hash_template_arg (e->args, val);
24507   }
24508
24509   static bool equal (constraint_sat_entry *e1, constraint_sat_entry *e2)
24510   {
24511     return e1->ci == e2->ci && comp_template_args (e1->args, e2->args);
24512   }
24513 };
24514
24515 /* Memoized satisfaction results for concept checks. */
24516
24517 struct GTY((for_user)) concept_spec_entry
24518 {
24519   tree tmpl;
24520   tree args;
24521   tree result;
24522 };
24523
24524 /* Hashing function and equality for constraint entries.  */
24525
24526 struct concept_spec_hasher : ggc_ptr_hash<concept_spec_entry>
24527 {
24528   static hashval_t hash (concept_spec_entry *e)
24529   {
24530     return hash_tmpl_and_args (e->tmpl, e->args);
24531   }
24532
24533   static bool equal (concept_spec_entry *e1, concept_spec_entry *e2)
24534   {
24535     ++comparing_specializations;
24536     bool eq = e1->tmpl == e2->tmpl && comp_template_args (e1->args, e2->args);
24537     --comparing_specializations;
24538     return eq;
24539   }
24540 };
24541
24542 static GTY (()) hash_table<constraint_sat_hasher> *constraint_memos;
24543 static GTY (()) hash_table<concept_spec_hasher> *concept_memos;
24544
24545 /* Search for a memoized satisfaction result. Returns one of the
24546    truth value nodes if previously memoized, or NULL_TREE otherwise.   */
24547
24548 tree
24549 lookup_constraint_satisfaction (tree ci, tree args)
24550 {
24551   constraint_sat_entry elt = { ci, args, NULL_TREE };
24552   constraint_sat_entry* found = constraint_memos->find (&elt);
24553   if (found)
24554     return found->result;
24555   else
24556     return NULL_TREE;
24557 }
24558
24559 /* Memoize the result of a satisfication test. Returns the saved result.  */
24560
24561 tree
24562 memoize_constraint_satisfaction (tree ci, tree args, tree result)
24563 {
24564   constraint_sat_entry elt = {ci, args, result};
24565   constraint_sat_entry** slot = constraint_memos->find_slot (&elt, INSERT);
24566   constraint_sat_entry* entry = ggc_alloc<constraint_sat_entry> ();
24567   *entry = elt;
24568   *slot = entry;
24569   return result;
24570 }
24571
24572 /* Search for a memoized satisfaction result for a concept. */
24573
24574 tree
24575 lookup_concept_satisfaction (tree tmpl, tree args)
24576 {
24577   concept_spec_entry elt = { tmpl, args, NULL_TREE };
24578   concept_spec_entry* found = concept_memos->find (&elt);
24579   if (found)
24580     return found->result;
24581   else
24582     return NULL_TREE;
24583 }
24584
24585 /* Memoize the result of a concept check. Returns the saved result.  */
24586
24587 tree
24588 memoize_concept_satisfaction (tree tmpl, tree args, tree result)
24589 {
24590   concept_spec_entry elt = {tmpl, args, result};
24591   concept_spec_entry** slot = concept_memos->find_slot (&elt, INSERT);
24592   concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
24593   *entry = elt;
24594   *slot = entry;
24595   return result;
24596 }
24597
24598 static GTY (()) hash_table<concept_spec_hasher> *concept_expansions;
24599
24600 /* Returns a prior concept specialization. This returns the substituted
24601    and normalized constraints defined by the concept.  */
24602
24603 tree
24604 get_concept_expansion (tree tmpl, tree args)
24605 {
24606   concept_spec_entry elt = { tmpl, args, NULL_TREE };
24607   concept_spec_entry* found = concept_expansions->find (&elt);
24608   if (found)
24609     return found->result;
24610   else
24611     return NULL_TREE;
24612 }
24613
24614 /* Save a concept expansion for later.  */
24615
24616 tree
24617 save_concept_expansion (tree tmpl, tree args, tree def)
24618 {
24619   concept_spec_entry elt = {tmpl, args, def};
24620   concept_spec_entry** slot = concept_expansions->find_slot (&elt, INSERT);
24621   concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
24622   *entry = elt;
24623   *slot = entry;
24624   return def;
24625 }
24626
24627 static hashval_t
24628 hash_subsumption_args (tree t1, tree t2)
24629 {
24630   gcc_assert (TREE_CODE (t1) == CHECK_CONSTR);
24631   gcc_assert (TREE_CODE (t2) == CHECK_CONSTR);
24632   int val = 0;
24633   val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t1), val);
24634   val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t1), val);
24635   val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t2), val);
24636   val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t2), val);
24637   return val;
24638 }
24639
24640 /* Compare the constraints of two subsumption entries.  The LEFT1 and
24641    LEFT2 arguments comprise the first subsumption pair and the RIGHT1
24642    and RIGHT2 arguments comprise the second. These are all CHECK_CONSTRs. */
24643
24644 static bool
24645 comp_subsumption_args (tree left1, tree left2, tree right1, tree right2)
24646 {
24647   if (CHECK_CONSTR_CONCEPT (left1) == CHECK_CONSTR_CONCEPT (right1))
24648     if (CHECK_CONSTR_CONCEPT (left2) == CHECK_CONSTR_CONCEPT (right2))
24649       if (comp_template_args (CHECK_CONSTR_ARGS (left1),
24650                              CHECK_CONSTR_ARGS (right1)))
24651         return comp_template_args (CHECK_CONSTR_ARGS (left2),
24652                                   CHECK_CONSTR_ARGS (right2));
24653   return false;
24654 }
24655
24656 /* Key/value pair for learning and memoizing subsumption results. This
24657    associates a pair of check constraints (including arguments) with
24658    a boolean value indicating the result.  */
24659
24660 struct GTY((for_user)) subsumption_entry
24661 {
24662   tree t1;
24663   tree t2;
24664   bool result;
24665 };
24666
24667 /* Hashing function and equality for constraint entries.  */
24668
24669 struct subsumption_hasher : ggc_ptr_hash<subsumption_entry>
24670 {
24671   static hashval_t hash (subsumption_entry *e)
24672   {
24673     return hash_subsumption_args (e->t1, e->t2);
24674   }
24675
24676   static bool equal (subsumption_entry *e1, subsumption_entry *e2)
24677   {
24678     ++comparing_specializations;
24679     bool eq = comp_subsumption_args(e1->t1, e1->t2, e2->t1, e2->t2);
24680     --comparing_specializations;
24681     return eq;
24682   }
24683 };
24684
24685 static GTY (()) hash_table<subsumption_hasher> *subsumption_table;
24686
24687 /* Search for a previously cached subsumption result. */
24688
24689 bool*
24690 lookup_subsumption_result (tree t1, tree t2)
24691 {
24692   subsumption_entry elt = { t1, t2, false };
24693   subsumption_entry* found = subsumption_table->find (&elt);
24694   if (found)
24695     return &found->result;
24696   else
24697     return 0;
24698 }
24699
24700 /* Save a subsumption result. */
24701
24702 bool
24703 save_subsumption_result (tree t1, tree t2, bool result)
24704 {
24705   subsumption_entry elt = {t1, t2, result};
24706   subsumption_entry** slot = subsumption_table->find_slot (&elt, INSERT);
24707   subsumption_entry* entry = ggc_alloc<subsumption_entry> ();
24708   *entry = elt;
24709   *slot = entry;
24710   return result;
24711 }
24712
24713 /* Set up the hash table for constraint association. */
24714
24715 void
24716 init_constraint_processing (void)
24717 {
24718   if (!flag_concepts)
24719     return;
24720
24721   decl_constraints = hash_table<constr_hasher>::create_ggc(37);
24722   constraint_memos = hash_table<constraint_sat_hasher>::create_ggc(37);
24723   concept_memos = hash_table<concept_spec_hasher>::create_ggc(37);
24724   concept_expansions = hash_table<concept_spec_hasher>::create_ggc(37);
24725   subsumption_table = hash_table<subsumption_hasher>::create_ggc(37);
24726 }
24727
24728 /* Set up the hash tables for template instantiations.  */
24729
24730 void
24731 init_template_processing (void)
24732 {
24733   decl_specializations = hash_table<spec_hasher>::create_ggc (37);
24734   type_specializations = hash_table<spec_hasher>::create_ggc (37);
24735 }
24736
24737 /* Print stats about the template hash tables for -fstats.  */
24738
24739 void
24740 print_template_statistics (void)
24741 {
24742   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
24743            "%f collisions\n", (long) decl_specializations->size (),
24744            (long) decl_specializations->elements (),
24745            decl_specializations->collisions ());
24746   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
24747            "%f collisions\n", (long) type_specializations->size (),
24748            (long) type_specializations->elements (),
24749            type_specializations->collisions ());
24750 }
24751
24752 #include "gt-cp-pt.h"