pt.c 257 KB
Newer Older
mrs's avatar
mrs committed
1
/* Handle parameterized types (templates) for GNU C++.
jason's avatar
jason committed
2
   Copyright (C) 1992, 93-97, 1998 Free Software Foundation, Inc.
mrs's avatar
mrs committed
3
   Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
mrs's avatar
mrs committed
4
   Rewritten by Jason Merrill (jason@cygnus.com).
mrs's avatar
mrs committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

This file is part of GNU CC.

GNU CC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU CC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU CC; see the file COPYING.  If not, write to
kenner's avatar
kenner committed
20 21
the Free Software Foundation, 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.  */
mrs's avatar
mrs committed
22 23

/* Known bugs or deficiencies include:
mrs's avatar
mrs committed
24 25 26

     all methods must be provided in header files; can't use a source
     file that contains only the method templates and "just win".  */
mrs's avatar
mrs committed
27 28

#include "config.h"
29
#include "system.h"
mrs's avatar
mrs committed
30 31 32 33 34 35 36
#include "obstack.h"

#include "tree.h"
#include "flags.h"
#include "cp-tree.h"
#include "decl.h"
#include "parse.h"
mrs's avatar
mrs committed
37
#include "lex.h"
mrs's avatar
mrs committed
38
#include "output.h"
mrs's avatar
mrs committed
39
#include "defaults.h"
40
#include "except.h"
41
#include "toplev.h"
42

43 44 45 46
/* The type of functions taking a tree, and some additional data, and
   returning an int.  */
typedef int (*tree_fn_t) PROTO((tree, void*));

mrs's avatar
mrs committed
47 48 49 50 51 52
extern struct obstack permanent_obstack;

extern int lineno;
extern char *input_filename;
struct pending_inline *pending_template_expansions;

mrs's avatar
mrs committed
53 54
tree current_template_parms;
HOST_WIDE_INT processing_template_decl;
mrs's avatar
mrs committed
55

mrs's avatar
mrs committed
56 57 58
tree pending_templates;
static tree *template_tail = &pending_templates;

mrs's avatar
mrs committed
59 60 61
tree maybe_templates;
static tree *maybe_template_tail = &maybe_templates;

mrs's avatar
mrs committed
62
int minimal_parse_mode;
63

64
int processing_specialization;
65
int processing_explicit_instantiation;
66
int processing_template_parmlist;
67 68
static int template_header_count;

69 70
static tree saved_trees;

mrs's avatar
mrs committed
71 72 73
#define obstack_chunk_alloc xmalloc
#define obstack_chunk_free free

74 75 76 77
#define UNIFY_ALLOW_NONE 0
#define UNIFY_ALLOW_MORE_CV_QUAL 1
#define UNIFY_ALLOW_LESS_CV_QUAL 2
#define UNIFY_ALLOW_DERIVED 4
78
#define UNIFY_ALLOW_INTEGER 8
79

80 81 82 83
static int unify PROTO((tree, tree, tree, tree, int, int*));
static int resolve_overloaded_unification PROTO((tree, tree, tree, tree,
						 unification_kind_t, int,
						 int*));
84
static int try_one_overload PROTO((tree, tree, tree, tree, tree,
85
				   unification_kind_t, int, int*));
86
static int unify PROTO((tree, tree, tree, tree, int, int*));
87 88 89
static void add_pending_template PROTO((tree));
static int push_tinst_level PROTO((tree));
static tree classtype_mangled_name PROTO((tree));
90
static char *mangle_class_name_for_template PROTO((char *, tree, tree));
91 92
static tree tsubst_expr_values PROTO((tree, tree));
static int list_eq PROTO((tree, tree));
93
static tree get_class_bindings PROTO((tree, tree, tree));
94
static tree coerce_template_parms PROTO((tree, tree, tree, int, int));
95
static void tsubst_enum	PROTO((tree, tree, tree));
96
static tree add_to_template_args PROTO((tree, tree));
97
static tree add_outermost_template_args PROTO((tree, tree));
98 99
static void maybe_adjust_types_for_deduction PROTO((unification_kind_t, tree*,
						    tree*)); 
100
static int  type_unification_real PROTO((tree, tree, tree, tree,
101
					 int, unification_kind_t, int, int*));
102
static void note_template_header PROTO((int));
103
static tree maybe_fold_nontype_arg PROTO((tree));
104
static tree convert_nontype_argument PROTO((tree, tree));
105 106
static tree convert_template_argument PROTO ((tree, tree, tree, int,
					      int , tree));
107
static tree get_bindings_overload PROTO((tree, tree, tree));
108
static int for_each_template_parm PROTO((tree, tree_fn_t, void*));
law's avatar
8  
law committed
109
static tree build_template_parm_index PROTO((int, int, int, tree, tree));
110 111 112
static int inline_needs_template_parms PROTO((tree));
static void push_inline_template_parms_recursive PROTO((tree, int));
static tree retrieve_specialization PROTO((tree, tree));
113 114
static tree register_specialization PROTO((tree, tree, tree));
static int unregister_specialization PROTO((tree, tree));
115 116 117 118 119
static void print_candidates PROTO((tree));
static tree reduce_template_parm_level PROTO((tree, tree, int));
static tree build_template_decl PROTO((tree, tree));
static int mark_template_parm PROTO((tree, void *));
static tree tsubst_friend_function PROTO((tree, tree));
120
static tree tsubst_friend_class PROTO((tree, tree));
121
static tree get_bindings_real PROTO((tree, tree, tree, int));
mmitchel's avatar
mmitchel committed
122
static int template_decl_level PROTO((tree));
123
static tree maybe_get_template_decl_from_type_decl PROTO((tree));
124 125
static int check_cv_quals_for_unify PROTO((int, tree, tree));
static tree tsubst_template_arg_vector PROTO((tree, tree));
126
static tree tsubst_template_parms PROTO((tree, tree));
127
static void regenerate_decl_from_template PROTO((tree, tree));
128 129 130 131
static tree most_specialized PROTO((tree, tree, tree));
static tree most_specialized_class PROTO((tree, tree));
static tree most_general_template PROTO((tree));
static void set_mangled_name_for_template_decl PROTO((tree));
132
static int template_class_depth_real PROTO((tree, int));
133 134
static tree tsubst_aggr_type PROTO((tree, tree, tree, int));
static tree tsubst_decl PROTO((tree, tree, tree, tree));
135
static tree tsubst_arg_types PROTO((tree, tree, tree));
136 137
static void check_specialization_scope PROTO((void));
static tree process_partial_specialization PROTO((tree));
138
static void set_current_access_from_decl PROTO((tree));
139
static void check_default_tmpl_args PROTO((tree, tree, int, int));
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159

/* We use TREE_VECs to hold template arguments.  If there is only one
   level of template arguments, then the TREE_VEC contains the
   arguments directly.  If there is more than one level of template
   arguments, then each entry in the TREE_VEC is itself a TREE_VEC,
   containing the template arguments for a single level.  The first
   entry in the outer TREE_VEC is the outermost level of template
   parameters; the last is the innermost.  

   It is incorrect to ever form a template argument vector containing
   only one level of arguments, but which is a TREE_VEC containing as
   its only entry the TREE_VEC for that level.  */

/* Non-zero if the template arguments is actually a vector of vectors,
   rather than just a vector.  */
#define TMPL_ARGS_HAVE_MULTIPLE_LEVELS(NODE) \
  (NODE != NULL_TREE						\
   && TREE_CODE (NODE) == TREE_VEC				\
   && TREE_VEC_LENGTH (NODE) > 0				\
   && TREE_VEC_ELT (NODE, 0) != NULL_TREE			\
160 161
   && TREE_CODE (TREE_VEC_ELT (NODE, 0)) == TREE_VEC)

162 163 164 165 166 167 168 169
/* The depth of a template argument vector.  When called directly by
   the parser, we use a TREE_LIST rather than a TREE_VEC to represent
   template arguments.  In fact, we may even see NULL_TREE if there
   are no template arguments.  In both of those cases, there is only
   one level of template arguments.  */
#define TMPL_ARGS_DEPTH(NODE)					\
  (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (NODE) ? TREE_VEC_LENGTH (NODE) : 1)

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
/* The LEVELth level of the template ARGS.  Note that template
   parameter levels are indexed from 1, not from 0.  */
#define TMPL_ARGS_LEVEL(ARGS, LEVEL)		\
  (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (ARGS) 	\
   ? TREE_VEC_ELT ((ARGS), (LEVEL) - 1) : ARGS)

/* Set the LEVELth level of the template ARGS to VAL.  This macro does
   not work with single-level argument vectors.  */
#define SET_TMPL_ARGS_LEVEL(ARGS, LEVEL, VAL)	\
  (TREE_VEC_ELT ((ARGS), (LEVEL) - 1) = (VAL))

/* Accesses the IDXth parameter in the LEVELth level of the ARGS.  */
#define TMPL_ARG(ARGS, LEVEL, IDX)				\
  (TREE_VEC_ELT (TMPL_ARGS_LEVEL (ARGS, LEVEL), IDX))

/* Set the IDXth element in the LEVELth level of ARGS to VAL.  This
   macro does not work with single-level argument vectors.  */
#define SET_TMPL_ARG(ARGS, LEVEL, IDX, VAL)			\
  (TREE_VEC_ELT (TREE_VEC_ELT ((ARGS), (LEVEL) - 1), (IDX)) = (VAL))

190 191 192 193 194 195 196
/* Given a single level of template arguments in NODE, return the
   number of arguments.  */
#define NUM_TMPL_ARGS(NODE) 				\
  ((NODE) == NULL_TREE ? 0 				\
   : (TREE_CODE (NODE) == TREE_VEC 			\
      ? TREE_VEC_LENGTH (NODE) : list_length (NODE)))

197 198 199 200
/* The number of levels of template parameters given by NODE.  */
#define TMPL_PARMS_DEPTH(NODE) \
  (TREE_INT_CST_HIGH (TREE_PURPOSE (NODE)))

201 202 203 204 205 206
/* Do any processing required when DECL (a member template declaration
   using TEMPLATE_PARAMETERS as its innermost parameter list) is
   finished.  Returns the TEMPLATE_DECL corresponding to DECL, unless
   it is a specialization, in which case the DECL itself is returned.  */

tree
207
finish_member_template_decl (decl)
208 209
  tree decl;
{
210 211
  if (decl == NULL_TREE || decl == void_type_node)
    return NULL_TREE;
212 213 214 215
  else if (decl == error_mark_node)
    /* By returning NULL_TREE, the parser will just ignore this
       declaration.  We have already issued the error.  */
    return NULL_TREE;
216 217
  else if (TREE_CODE (decl) == TREE_LIST)
    {
jason's avatar
comment  
jason committed
218
      /* Assume that the class is the only declspec.  */
219
      decl = TREE_VALUE (decl);
220 221
      if (IS_AGGR_TYPE (decl) && CLASSTYPE_TEMPLATE_INFO (decl)
	  && ! CLASSTYPE_TEMPLATE_SPECIALIZATION (decl))
222 223 224 225 226
	{
	  tree tmpl = CLASSTYPE_TI_TEMPLATE (decl);
	  check_member_template (tmpl);
	  return tmpl;
	}
227
      return NULL_TREE;
228
    }
229
  else if (DECL_TEMPLATE_INFO (decl))
230
    {
231 232 233 234 235 236 237 238 239
      if (!DECL_TEMPLATE_SPECIALIZATION (decl))
	{
	  check_member_template (DECL_TI_TEMPLATE (decl));
	  return DECL_TI_TEMPLATE (decl);
	}
      else
	return decl;
    } 
  else
jason's avatar
jason committed
240
    cp_error ("invalid member template declaration `%D'", decl);
241

242
  return error_mark_node;
jason's avatar
jason committed
243
}
244

jason's avatar
jason committed
245 246 247 248 249 250 251 252 253 254
/* Returns the template nesting level of the indicated class TYPE.
   
   For example, in:
     template <class T>
     struct A
     {
       template <class U>
       struct B {};
     };

255 256 257 258 259 260 261 262
   A<T>::B<U> has depth two, while A<T> has depth one.  
   Both A<T>::B<int> and A<int>::B<U> have depth one, if
   COUNT_SPECIALIZATIONS is 0 or if they are instantiations, not
   specializations.  

   This function is guaranteed to return 0 if passed NULL_TREE so
   that, for example, `template_class_depth (current_class_type)' is
   always safe.  */
jason's avatar
jason committed
263 264

int 
265
template_class_depth_real (type, count_specializations)
jason's avatar
jason committed
266
     tree type;
267
     int count_specializations;
jason's avatar
jason committed
268
{
269
  int depth;
jason's avatar
jason committed
270

jason's avatar
jason committed
271
  for (depth = 0; 
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
       type && TREE_CODE (type) != NAMESPACE_DECL;
       type = (TREE_CODE (type) == FUNCTION_DECL) 
	 ? DECL_REAL_CONTEXT (type) : TYPE_CONTEXT (type))
    {
      if (TREE_CODE (type) != FUNCTION_DECL)
	{
	  if (CLASSTYPE_TEMPLATE_INFO (type)
	      && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type))
	      && ((count_specializations
		   && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
		  || uses_template_parms (CLASSTYPE_TI_ARGS (type))))
	    ++depth;
	}
      else 
	{
	  if (DECL_TEMPLATE_INFO (type)
	      && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (type))
	      && ((count_specializations
		   && DECL_TEMPLATE_SPECIALIZATION (type))
		  || uses_template_parms (DECL_TI_ARGS (type))))
	    ++depth;
	}
    }
jason's avatar
jason committed
295 296

  return depth;
297
}
298

299 300 301 302 303 304 305 306 307 308 309
/* Returns the template nesting level of the indicated class TYPE.
   Like template_class_depth_real, but instantiations do not count in
   the depth.  */

int 
template_class_depth (type)
     tree type;
{
  return template_class_depth_real (type, /*count_specializations=*/0);
}

310 311 312 313 314 315 316 317 318
/* Returns 1 if processing DECL as part of do_pending_inlines
   needs us to push template parms.  */

static int
inline_needs_template_parms (decl)
     tree decl;
{
  if (! DECL_TEMPLATE_INFO (decl))
    return 0;
jason's avatar
jason committed
319

320
  return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
	  > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
}

/* Subroutine of maybe_begin_member_template_processing.
   Push the template parms in PARMS, starting from LEVELS steps into the
   chain, and ending at the beginning, since template parms are listed
   innermost first.  */

static void
push_inline_template_parms_recursive (parmlist, levels)
     tree parmlist;
     int levels;
{
  tree parms = TREE_VALUE (parmlist);
  int i;

  if (levels > 1)
    push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
339

340
  ++processing_template_decl;
341
  current_template_parms
342 343
    = tree_cons (build_int_2 (0, processing_template_decl),
		 parms, current_template_parms);
344 345
  TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;

346
  pushlevel (0);
347 348
  for (i = 0; i < TREE_VEC_LENGTH (parms); ++i) 
    {
349 350
      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
      my_friendly_assert (TREE_CODE_CLASS (TREE_CODE (parm)) == 'd', 0);
351

352 353
      switch (TREE_CODE (parm))
	{
354
	case TYPE_DECL:
355
	case TEMPLATE_DECL:
356 357
	  pushdecl (parm);
	  break;
358 359 360 361 362 363 364 365 366

	case PARM_DECL:
	  {
	    /* Make a CONST_DECL as is done in process_template_parm. */
	    tree decl = build_decl (CONST_DECL, DECL_NAME (parm),
				    TREE_TYPE (parm));
	    DECL_INITIAL (decl) = DECL_INITIAL (parm);
	    pushdecl (decl);
	  }
367
	  break;
368

369 370 371 372 373 374
	default:
	  my_friendly_abort (0);
	}
    }
}

375 376 377 378 379 380 381 382 383 384 385 386 387
/* Restore the template parameter context for a member template or
   a friend template defined in a class definition.  */

void
maybe_begin_member_template_processing (decl)
     tree decl;
{
  tree parms;
  int levels;

  if (! inline_needs_template_parms (decl))
    return;

388
  parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
389

390
  levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
391 392 393 394 395 396 397 398 399 400

  if (DECL_TEMPLATE_SPECIALIZATION (decl))
    {
      --levels;
      parms = TREE_CHAIN (parms);
    }

  push_inline_template_parms_recursive (parms, levels);
}

401 402 403
/* Undo the effects of begin_member_template_processing. */

void 
ghazi's avatar
ghazi committed
404
maybe_end_member_template_processing ()
405 406 407 408
{
  if (! processing_template_decl)
    return;

409 410 411 412 413 414 415
  while (current_template_parms
	 && TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
    {
      --processing_template_decl;
      current_template_parms = TREE_CHAIN (current_template_parms);
      poplevel (0, 0, 0);
    }
416 417
}

418
/* Returns non-zero iff T is a member template function.  We must be
jason's avatar
jason committed
419
   careful as in
420 421 422 423 424 425 426 427 428 429 430

     template <class T> class C { void f(); }

   Here, f is a template function, and a member, but not a member
   template.  This function does not concern itself with the origin of
   T, only its present state.  So if we have 

     template <class T> class C { template <class U> void f(U); }

   then neither C<int>::f<char> nor C<T>::f<double> is considered
   to be a member template.  */
431

432 433
int
is_member_template (t)
434 435
     tree t;
{
436 437
  if (TREE_CODE (t) != FUNCTION_DECL
      && !DECL_FUNCTION_TEMPLATE_P (t))
438
    /* Anything that isn't a function or a template function is
439 440 441
       certainly not a member template.  */
    return 0;

442 443 444 445 446
  /* A local class can't have member templates.  */
  if (hack_decl_function_context (t))
    return 0;

  if ((DECL_FUNCTION_MEMBER_P (t) 
447
       && !DECL_TEMPLATE_SPECIALIZATION (t))
jason's avatar
jason committed
448
      || (TREE_CODE (t) == TEMPLATE_DECL 
449
	  && DECL_FUNCTION_MEMBER_P (DECL_TEMPLATE_RESULT (t))))
450
    {
jason's avatar
jason committed
451
      tree tmpl;
452 453 454 455 456 457

      if (DECL_FUNCTION_TEMPLATE_P (t))
	tmpl = t;
      else if (DECL_TEMPLATE_INFO (t) 
	       && DECL_FUNCTION_TEMPLATE_P (DECL_TI_TEMPLATE (t)))
	tmpl = DECL_TI_TEMPLATE (t);
jason's avatar
jason committed
458 459 460
      else
	tmpl = NULL_TREE;

461
      if (tmpl
jason's avatar
jason committed
462 463 464
	  /* If there are more levels of template parameters than
	     there are template classes surrounding the declaration,
	     then we have a member template.  */
465
	  && (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)) > 
466
	      template_class_depth (DECL_CLASS_CONTEXT (t))))
jason's avatar
jason committed
467 468
	return 1;
    }
469

jason's avatar
jason committed
470 471
  return 0;
}
472

473
#if 0 /* UNUSED */
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
/* Returns non-zero iff T is a member template class.  See
   is_member_template for a description of what precisely constitutes
   a member template.  */

int
is_member_template_class (t)
     tree t;
{
  if (!DECL_CLASS_TEMPLATE_P (t))
    /* Anything that isn't a class template, is certainly not a member
       template.  */
    return 0;

  if (!DECL_CLASS_SCOPE_P (t))
    /* Anything whose context isn't a class type is surely not a
       member template.  */
    return 0;

  /* If there are more levels of template parameters than there are
     template classes surrounding the declaration, then we have a
     member template.  */
495
  return  (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (t)) > 
496 497
	   template_class_depth (DECL_CONTEXT (t)));
}
498
#endif
499

500 501 502 503
/* Return a new template argument vector which contains all of ARGS,
   but has as its innermost set of arguments the EXTRA_ARGS.  The
   resulting vector will be built on a temporary obstack, and so must
   be explicitly copied to the permanent obstack, if required.  */
504 505

static tree
506 507 508
add_to_template_args (args, extra_args)
     tree args;
     tree extra_args;
509
{
510 511 512 513
  tree new_args;
  int extra_depth;
  int i;
  int j;
514

515 516
  extra_depth = TMPL_ARGS_DEPTH (extra_args);
  new_args = make_temp_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
517

518 519
  for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
    SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
520

521 522 523
  for (j = 1; j <= extra_depth; ++j, ++i)
    SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
    
524 525 526
  return new_args;
}

527 528 529 530 531 532
/* Like add_to_template_args, but only the outermost ARGS are added to
   the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
   (EXTRA_ARGS) levels are added.  This function is used to combine
   the template arguments from a partial instantiation with the
   template arguments used to attain the full instantiation from the
   partial instantiation.  */
533

534
static tree
535
add_outermost_template_args (args, extra_args)
536 537 538 539 540
     tree args;
     tree extra_args;
{
  tree new_args;

541 542 543 544 545 546 547 548 549 550
  /* If there are more levels of EXTRA_ARGS than there are ARGS,
     something very fishy is going on.  */
  my_friendly_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args),
		      0);

  /* If *all* the new arguments will be the EXTRA_ARGS, just return
     them.  */
  if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
    return extra_args;

551 552 553 554
  /* For the moment, we make ARGS look like it contains fewer levels.  */
  TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
  
  new_args = add_to_template_args (args, extra_args);
555

556 557
  /* Now, we restore ARGS to its full dimensions.  */
  TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
558 559 560

  return new_args;
}
mrs's avatar
mrs committed
561 562 563

/* We've got a template header coming up; push to a new level for storing
   the parms.  */
mrs's avatar
mrs committed
564 565 566 567

void
begin_template_parm_list ()
{
568 569 570 571 572 573 574 575 576 577 578 579 580 581
  /* We use a non-tag-transparent scope here, which causes pushtag to
     put tags in this scope, rather than in the enclosing class or
     namespace scope.  This is the right thing, since we want
     TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
     global template class, push_template_decl handles putting the
     TEMPLATE_DECL into top-level scope.  For a nested template class,
     e.g.:

       template <class T> struct S1 {
         template <class T> struct S2 {}; 
       };

     pushtag contains special code to call pushdecl_with_scope on the
     TEMPLATE_DECL for S2.  */
mrs's avatar
mrs committed
582
  pushlevel (0);
mrs's avatar
mrs committed
583
  declare_pseudo_global_level ();
mrs's avatar
mrs committed
584
  ++processing_template_decl;
585
  ++processing_template_parmlist;
586 587 588
  note_template_header (0);
}

589 590 591 592 593 594 595
/* This routine is called when a specialization is declared.  If it is
   illegal to declare a specialization here, an error is reported.  */

void
check_specialization_scope ()
{
  tree scope = current_scope ();
596

597 598 599 600 601 602 603 604 605 606
  /* [temp.expl.spec] 
     
     An explicit specialization shall be declared in the namespace of
     which the template is a member, or, for member templates, in the
     namespace of which the enclosing class or enclosing class
     template is a member.  An explicit specialization of a member
     function, member class or static data member of a class template
     shall be declared in the namespace of which the class template
     is a member.  */
  if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
jason's avatar
jason committed
607
    cp_error ("explicit specialization in non-namespace scope `%D'",
608
	      scope);
609

610 611 612 613 614 615 616 617 618
  /* [temp.expl.spec] 

     In an explicit specialization declaration for a member of a class
     template or a member template that appears in namespace scope,
     the member template and some of its enclosing class templates may
     remain unspecialized, except that the declaration shall not
     explicitly specialize a class member template if its enclosing
     class templates are not explicitly specialized as well.  */
  if (current_template_parms) 
619
    cp_error ("enclosing class templates are not explicitly specialized");
620 621
}

622 623 624 625 626 627
/* We've just seen template <>. */

void
begin_specialization ()
{
  note_template_header (1);
628
  check_specialization_scope ();
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
}

/* Called at then end of processing a declaration preceeded by
   template<>.  */

void 
end_specialization ()
{
  reset_specialization ();
}

/* Any template <>'s that we have seen thus far are not referring to a
   function specialization. */

void
reset_specialization ()
{
  processing_specialization = 0;
  template_header_count = 0;
}

/* We've just seen a template header.  If SPECIALIZATION is non-zero,
   it was of the form template <>.  */

653
static void 
654 655 656 657 658 659 660
note_template_header (specialization)
     int specialization;
{
  processing_specialization = specialization;
  template_header_count++;
}

661
/* We're beginning an explicit instantiation.  */
662

663 664
void
begin_explicit_instantiation ()
665
{
666 667
  ++processing_explicit_instantiation;
}
668 669


670 671 672 673 674 675
void
end_explicit_instantiation ()
{
  my_friendly_assert(processing_explicit_instantiation > 0, 0);
  --processing_explicit_instantiation;
}
676

677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
/* The TYPE is being declared.  If it is a template type, that means it
   is a partial specialization.  Do appropriate error-checking.  */

void 
maybe_process_partial_specialization (type)
     tree type;
{
  if (IS_AGGR_TYPE (type) && CLASSTYPE_USE_TEMPLATE (type))
    {
      if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
	  && TYPE_SIZE (type) == NULL_TREE)
	{
	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
	  if (processing_template_decl)
	    push_template_decl (TYPE_MAIN_DECL (type));
	}
      else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
jason's avatar
jason committed
694
	cp_error ("specialization of `%T' after instantiation", type);
695 696 697
    }
}

698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
/* Retrieve the specialization (in the sense of [temp.spec] - a
   specialization is either an instantiation or an explicit
   specialization) of TMPL for the given template ARGS.  If there is
   no such specialization, return NULL_TREE.  The ARGS are a vector of
   arguments, or a vector of vectors of arguments, in the case of
   templates with more than one level of parameters.  */
   
static tree
retrieve_specialization (tmpl, args)
     tree tmpl;
     tree args;
{
  tree s;

  my_friendly_assert (TREE_CODE (tmpl) == TEMPLATE_DECL, 0);

714 715 716 717 718 719
  /* There should be as many levels of arguments as there are
     levels of parameters.  */
  my_friendly_assert (TMPL_ARGS_DEPTH (args) 
		      == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)),
		      0);
		      
720 721 722 723 724 725 726
  for (s = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
       s != NULL_TREE;
       s = TREE_CHAIN (s))
    if (comp_template_args (TREE_PURPOSE (s), args))
      return TREE_VALUE (s);

  return NULL_TREE;
727 728
}

729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
/* Returns non-zero iff DECL is a specialization of TMPL.  */

int
is_specialization_of (decl, tmpl)
     tree decl;
     tree tmpl;
{
  tree t;

  if (TREE_CODE (decl) == FUNCTION_DECL)
    {
      for (t = decl; 
	   t != NULL_TREE;
	   t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
	if (t == tmpl)
	  return 1;
    }
  else 
    {
      my_friendly_assert (TREE_CODE (decl) == TYPE_DECL, 0);

      for (t = TREE_TYPE (decl);
	   t != NULL_TREE;
	   t = CLASSTYPE_USE_TEMPLATE (t)
	     ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
754 755
	if (same_type_p (TYPE_MAIN_VARIANT (t), 
			 TYPE_MAIN_VARIANT (TREE_TYPE (tmpl))))
756 757
	  return 1;
    }  
758

759 760
  return 0;
}
761 762

/* Register the specialization SPEC as a specialization of TMPL with
763 764
   the indicated ARGS.  Returns SPEC, or an equivalent prior
   declaration, if available.  */
765

766
static tree
767 768 769 770 771 772 773 774 775
register_specialization (spec, tmpl, args)
     tree spec;
     tree tmpl;
     tree args;
{
  tree s;

  my_friendly_assert (TREE_CODE (tmpl) == TEMPLATE_DECL, 0);

776 777 778 779 780 781 782 783 784 785 786 787 788 789
  if (TREE_CODE (spec) == FUNCTION_DECL 
      && uses_template_parms (DECL_TI_ARGS (spec)))
    /* This is the FUNCTION_DECL for a partial instantiation.  Don't
       register it; we want the corresponding TEMPLATE_DECL instead.
       We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
       the more obvious `uses_template_parms (spec)' to avoid problems
       with default function arguments.  In particular, given
       something like this:

          template <class T> void f(T t1, T t = T())

       the default argument expression is not substituted for in an
       instantiation unless and until it is actually needed.  */
    return spec;
790
    
791 792 793 794 795 796
  /* There should be as many levels of arguments as there are
     levels of parameters.  */
  my_friendly_assert (TMPL_ARGS_DEPTH (args) 
		      == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)),
		      0);

797 798 799 800 801 802 803 804 805 806 807 808 809 810
  for (s = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
       s != NULL_TREE;
       s = TREE_CHAIN (s))
    if (comp_template_args (TREE_PURPOSE (s), args))
      {
	tree fn = TREE_VALUE (s);

	if (DECL_TEMPLATE_SPECIALIZATION (spec))
	  {
	    if (DECL_TEMPLATE_INSTANTIATION (fn))
	      {
		if (TREE_USED (fn) 
		    || DECL_EXPLICIT_INSTANTIATION (fn))
		  {
jason's avatar
jason committed
811
		    cp_error ("specialization of %D after instantiation",
812
			      fn);
813
		    return spec;
814 815 816 817 818 819 820 821
		  }
		else
		  {
		    /* This situation should occur only if the first
		       specialization is an implicit instantiation,
		       the second is an explicit specialization, and
		       the implicit instantiation has not yet been
		       used.  That situation can occur if we have
822 823 824 825 826 827 828 829 830 831 832 833 834
		       implicitly instantiated a member function and
		       then specialized it later.

		       We can also wind up here if a friend
		       declaration that looked like an instantiation
		       turns out to be a specialization:

		         template <class T> void foo(T);
			 class S { friend void foo<>(int) };
			 template <> void foo(int);  

		       We transform the existing DECL in place so that
		       any pointers to it become pointers to the
835 836 837 838 839 840 841 842 843 844
		       updated declaration.  

		       If there was a definition for the template, but
		       not for the specialization, we want this to
		       look as if there is no definition, and vice
		       versa.  */
		    DECL_INITIAL (fn) = NULL_TREE;
		    duplicate_decls (spec, fn);

		    return fn;
845 846 847 848
		  }
	      }
	    else if (DECL_TEMPLATE_SPECIALIZATION (fn))
	      {
849 850
		duplicate_decls (spec, fn);
		return fn;
851 852 853 854 855 856
	      }
	  }
      }

  DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
     = perm_tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881

  return spec;
}

/* Unregister the specialization SPEC as a specialization of TMPL.
   Returns nonzero if the SPEC was listed as a specialization of
   TMPL.  */

static int
unregister_specialization (spec, tmpl)
     tree spec;
     tree tmpl;
{
  tree* s;

  for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
       *s != NULL_TREE;
       s = &TREE_CHAIN (*s))
    if (TREE_VALUE (*s) == spec)
      {
	*s = TREE_CHAIN (*s);
	return 1;
      }

  return 0;
882 883
}

884 885 886 887 888 889 890 891 892 893 894 895
/* Print the list of candidate FNS in an error message.  */

static void
print_candidates (fns)
     tree fns;
{
  tree fn;

  char* str = "candidates are:";

  for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
    {
jason's avatar
jason committed
896
      cp_error_at ("%s %+#D", str, TREE_VALUE (fn));
897 898 899 900
      str = "               ";
    }
}

901
/* Returns the template (one of the functions given by TEMPLATE_ID)
902 903 904 905 906 907 908 909
   which can be specialized to match the indicated DECL with the
   explicit template args given in TEMPLATE_ID.  If
   NEED_MEMBER_TEMPLATE is true the function is a specialization of a
   member template.  The template args (those explicitly specified and
   those deduced) are output in a newly created vector *TARGS_OUT.  If
   it is impossible to determine the result, an error message is
   issued, unless COMPLAIN is 0.  The DECL may be NULL_TREE if none is
   available.  */
910

911
tree
912
determine_specialization (template_id, decl, targs_out, 
913 914
			  need_member_template,
			  complain)
915
     tree template_id;
916
     tree decl;
917 918 919 920
     tree* targs_out;
     int need_member_template;
     int complain;
{
921
  tree fns, targs_in;
922
  tree templates = NULL_TREE;
923 924
  tree fn;

925 926
  *targs_out = NULL_TREE;

927 928 929 930 931 932
  if (template_id == error_mark_node)
    return error_mark_node;

  fns = TREE_OPERAND (template_id, 0);
  targs_in = TREE_OPERAND (template_id, 1);

933 934 935
  if (fns == error_mark_node)
    return error_mark_node;

jason's avatar
jason committed
936 937 938
  /* Check for baselinks. */
  if (TREE_CODE (fns) == TREE_LIST)
    fns = TREE_VALUE (fns);
939

jason's avatar
jason committed
940
  for (; fns; fns = OVL_NEXT (fns))
941
    {
942 943
      tree tmpl;

jason's avatar
jason committed
944
      fn = OVL_CURRENT (fns);
945 946
      if (!need_member_template 
	  && TREE_CODE (fn) == FUNCTION_DECL 
947
	  && DECL_FUNCTION_MEMBER_P (fn)
948 949
	  && DECL_USE_TEMPLATE (fn)
	  && DECL_TI_TEMPLATE (fn))
950 951 952 953 954
	/* We can get here when processing something like:
	     template <class T> class X { void f(); }
	     template <> void X<int>::f() {}
	   We're specializing a member function, but not a member
	   template.  */
955 956
	tmpl = DECL_TI_TEMPLATE (fn);
      else if (TREE_CODE (fn) != TEMPLATE_DECL
957
	       || (need_member_template && !is_member_template (fn)))
958
	continue;
959 960
      else
	tmpl = fn;
961

962
      if (list_length (targs_in) > DECL_NTPARMS (tmpl))
963 964
	continue;

965
      if (decl == NULL_TREE)
966
	{
967 968 969 970 971 972 973 974
	  /* Unify against ourselves to make sure that the args we have
	     make sense and there aren't any undeducible parms.  It's OK if
	     not all the parms are specified; they might be deduced
	     later. */
	  tree targs = get_bindings_overload (tmpl, DECL_RESULT (tmpl),
					      targs_in);

	  if (targs) 
975 976
	    /* Unification was successful.  */
	    templates = scratch_tree_cons (targs, tmpl, templates);
977
	}
978 979
      else
	templates = scratch_tree_cons (NULL_TREE, tmpl, templates);
980
    }
981
  
982
  if (decl != NULL_TREE)
983
    {
984
      tree tmpl = most_specialized (templates, decl, targs_in);
985 986
      tree inner_args;
      tree tmpl_args;
987 988 989 990 991 992

      if (tmpl == error_mark_node) 
	goto ambiguous;
      else if (tmpl == NULL_TREE)
	goto no_match;

993 994 995 996 997 998 999 1000 1001 1002 1003 1004
      inner_args = get_bindings (tmpl, decl, targs_in);
      tmpl_args = DECL_TI_ARGS (DECL_RESULT (tmpl));
      if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (tmpl_args))
	{
	  *targs_out = copy_node (tmpl_args);
	  SET_TMPL_ARGS_LEVEL (*targs_out, 
			       TMPL_ARGS_DEPTH (*targs_out),
			       inner_args);
	}
      else
	*targs_out = inner_args;
      
1005 1006 1007 1008 1009 1010
      return tmpl;
    }

  if (templates == NULL_TREE)
    {
    no_match:
1011
      if (complain)
1012
	{
jason's avatar
jason committed
1013
	  cp_error_at ("template-id `%D' for `%+D' does not match any template declaration",
1014 1015 1016
		       template_id, decl);
	  return error_mark_node;
	}
1017 1018
      return NULL_TREE;
    }
1019 1020
  else if (TREE_CHAIN (templates) != NULL_TREE
	   || uses_template_parms (TREE_PURPOSE (templates)))
1021
    {
1022
    ambiguous:
1023 1024
      if (complain)
	{
jason's avatar
jason committed
1025
	  cp_error_at ("ambiguous template specialization `%D' for `%+D'",
1026
		       template_id, decl);
1027
	  print_candidates (templates);
1028
	  return error_mark_node;
1029 1030 1031 1032 1033
	}
      return NULL_TREE;
    }

  /* We have one, and exactly one, match. */
1034 1035
  *targs_out = TREE_PURPOSE (templates);
  return TREE_VALUE (templates);
mrs's avatar
mrs committed
1036
}
1037
      
1038
/* Check to see if the function just declared, as indicated in
1039 1040 1041 1042
   DECLARATOR, and in DECL, is a specialization of a function
   template.  We may also discover that the declaration is an explicit
   instantiation at this point.

1043 1044
   Returns DECL, or an equivalent declaration that should be used
   instead. 
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
   
   FLAGS is a bitmask consisting of the following flags: 

   2: The function has a definition.
   4: The function is a friend.

   The TEMPLATE_COUNT is the number of references to qualifying
   template classes that appeared in the name of the function.  For
   example, in

     template <class T> struct S { void f(); };
     void S<int>::f();
     
   the TEMPLATE_COUNT would be 1.  However, explicitly specialized
   classes are not counted in the TEMPLATE_COUNT, so that in

     template <class T> struct S {};
     template <> struct S<int> { void f(); }
1063
     template <> void S<int>::f();
1064 1065 1066 1067 1068 1069 1070 1071

   the TEMPLATE_COUNT would be 0.  (Note that this declaration is
   illegal; there should be no template <>.)

   If the function is a specialization, it is marked as such via
   DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
   is set up correctly, and it is added to the list of specializations 
   for that template.  */
1072

1073
tree
1074
check_explicit_specialization (declarator, decl, template_count, flags)
1075 1076 1077 1078 1079
     tree declarator;
     tree decl;
     int template_count;
     int flags;
{
1080 1081 1082
  int have_def = flags & 2;
  int is_friend = flags & 4;
  int specialization = 0;
1083
  int explicit_instantiation = 0;
1084
  int member_specialization = 0;
1085 1086 1087

  tree ctype = DECL_CLASS_CONTEXT (decl);
  tree dname = DECL_NAME (decl);
1088

1089
  if (processing_specialization) 
1090
    {
1091
      /* The last template header was of the form template <>.  */
1092
	  
1093 1094 1095 1096 1097 1098
      if (template_header_count > template_count) 
	{
	  /* There were more template headers than qualifying template
	     classes.  */
	  if (template_header_count - template_count > 1)
	    /* There shouldn't be that many template parameter
1099 1100 1101
		   lists.  There can be at most one parameter list for
		   every qualifying class, plus one for the function
		   itself.  */
1102
	    cp_error ("too many template parameter lists in declaration of `%D'", decl);
1103

1104 1105 1106 1107 1108
	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
	  if (ctype)
	    member_specialization = 1;
	  else
	    specialization = 1;
1109
	}
1110
      else if (template_header_count == template_count)
1111
	{
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
	  /* The counts are equal.  So, this might be a
	     specialization, but it is not a specialization of a
	     member template.  It might be something like
		 
	     template <class T> struct S { 
	     void f(int i); 
	     };
	     template <>
	     void S<int>::f(int i) {}  */
	  specialization = 1;
	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1123
	}
1124
      else 
1125
	{
1126 1127 1128 1129 1130 1131
	  /* This cannot be an explicit specialization.  There are not
	     enough headers for all of the qualifying classes.  For
	     example, we might have:
	     
	     template <>
	     void S<int>::T<char>::f();
1132

1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
	     But, we're missing another template <>.  */
	  cp_error("too few template parameter lists in declaration of `%D'", decl);
	  return decl;
	} 
    }
  else if (processing_explicit_instantiation)
    {
      if (template_header_count)
	cp_error ("template parameter list used in explicit instantiation");
	  
      if (have_def)
	cp_error ("definition provided for explicit instantiation");
1145

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
      explicit_instantiation = 1;
    }
  else if (ctype != NULL_TREE
	   && !TYPE_BEING_DEFINED (ctype)
	   && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype)
	   && !is_friend)
    {
      /* This case catches outdated code that looks like this:

	 template <class T> struct S { void f(); };
	 void S<int>::f() {} // Missing template <>

	 We disable this check when the type is being defined to
	 avoid complaining about default compiler-generated
	 constructors, destructors, and assignment operators.
	 Since the type is an instantiation, not a specialization,
	 these are the only functions that can be defined before
	 the class is complete.  */
1164

1165 1166 1167
	  /* If they said
	       template <class T> void S<int>::f() {}
	     that's bogus.  */
1168 1169 1170 1171
      if (template_header_count)
	{
	  cp_error ("template parameters specified in specialization");
	  return decl;
1172
	}
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188

      if (pedantic)
	cp_pedwarn
	  ("explicit specialization not preceded by `template <>'");
      specialization = 1;
      SET_DECL_TEMPLATE_SPECIALIZATION (decl);
    }
  else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
    {
      if (is_friend)
	/* This could be something like:

	   template <class T> void f(T);
	   class S { friend void f<>(int); }  */
	specialization = 1;
      else
1189
	{
1190 1191
	  /* This case handles bogus declarations like template <>
	     template <class T> void f<int>(); */
1192

1193 1194 1195
	  cp_error ("template-id `%D' in declaration of primary template",
		    declarator);
	  return decl;
1196
	}
1197
    }
1198

1199 1200 1201 1202 1203 1204
  if (specialization || member_specialization)
    {
      tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
      for (; t; t = TREE_CHAIN (t))
	if (TREE_PURPOSE (t))
	  {
jason's avatar
jason committed
1205 1206
	    cp_pedwarn
	      ("default argument specified in explicit specialization");
1207 1208 1209 1210
	    break;
	  }
    }

1211
  if (specialization || member_specialization || explicit_instantiation)
1212
    {
1213
      tree gen_tmpl;
1214 1215 1216 1217
      tree tmpl = NULL_TREE;
      tree targs = NULL_TREE;

      /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
1218 1219 1220 1221 1222 1223 1224
      if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
	{
	  tree fns;

	  my_friendly_assert (TREE_CODE (declarator) == IDENTIFIER_NODE, 
			      0);
	  if (!ctype)
jason's avatar
jason committed
1225
	    fns = IDENTIFIER_NAMESPACE_VALUE (dname);
1226 1227 1228
	  else
	    fns = dname;

1229 1230
	  declarator = 
	    lookup_template_function (fns, NULL_TREE);
1231 1232
	}

1233 1234 1235 1236
      if (declarator == error_mark_node)
	return error_mark_node;

      if (TREE_CODE (TREE_OPERAND (declarator, 0)) == LOOKUP_EXPR)
1237 1238 1239 1240
	{
	  /* A friend declaration.  We can't do much, because we don't
	   know what this resolves to, yet.  */
	  my_friendly_assert (is_friend != 0, 0);
1241
	  my_friendly_assert (!explicit_instantiation, 0);
1242
	  SET_DECL_IMPLICIT_INSTANTIATION (decl);
1243
	  return decl;
1244 1245
	} 

1246 1247
      if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
	{
1248
	  if (!explicit_instantiation)
1249 1250 1251 1252
	    /* A specialization in class scope.  This is illegal,
	       but the error will already have been flagged by
	       check_specialization_scope.  */
	    return error_mark_node;
1253
	  else
ghazi's avatar
ghazi committed
1254 1255 1256
	    {
	      /* It's not legal to write an explicit instantiation in
		 class scope, e.g.:
1257

ghazi's avatar
ghazi committed
1258
	           class C { template void f(); }
1259

ghazi's avatar
ghazi committed
1260 1261
		   This case is caught by the parser.  However, on
		   something like:
1262
	       
ghazi's avatar
ghazi committed
1263
		   template class C { void f(); };
1264

ghazi's avatar
ghazi committed
1265 1266 1267 1268
		   (which is illegal) we can get here.  The error will be
		   issued later.  */
	      ;
	    }
1269

1270
	  return decl;
1271 1272 1273 1274
	}
      else if (ctype != NULL_TREE 
	       && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
		   IDENTIFIER_NODE))
1275
	{
1276 1277 1278
	  /* Find the list of functions in ctype that have the same
	     name as the declared function.  */
	  tree name = TREE_OPERAND (declarator, 0);
1279
	  tree fns;
1280 1281 1282
	  
	  if (name == constructor_name (ctype) 
	      || name == constructor_name_full (ctype))
1283
	    {
1284 1285 1286 1287 1288 1289
	      int is_constructor = DECL_CONSTRUCTOR_P (decl);
	      
	      if (is_constructor ? !TYPE_HAS_CONSTRUCTOR (ctype)
		  : !TYPE_HAS_DESTRUCTOR (ctype))
		{
		  /* From [temp.expl.spec]:
1290
		       
1291 1292 1293
		     If such an explicit specialization for the member
		     of a class template names an implicitly-declared
		     special member function (clause _special_), the
1294 1295 1296
		     program is ill-formed.  

		     Similar language is found in [temp.explicit].  */
jason's avatar
jason committed
1297
		  cp_error ("specialization of implicitly-declared special member function");
1298

1299
		  return decl;
1300
		}
1301

1302
	      name = is_constructor ? ctor_identifier : dtor_identifier;
1303
	    }
1304 1305

	  fns = lookup_fnfields (TYPE_BINFO (ctype), name, 1);
1306 1307 1308
	  
	  if (fns == NULL_TREE) 
	    {
jason's avatar
jason committed
1309
	      cp_error ("no member function `%s' declared in `%T'",
1310
			IDENTIFIER_POINTER (name),
1311
			ctype);
1312
	      return decl;
1313 1314 1315 1316
	    }
	  else
	    TREE_OPERAND (declarator, 0) = fns;
	}
1317
      
1318 1319
      /* Figure out what exactly is being specialized at this point.
	 Note that for an explicit instantiation, even one for a
law's avatar
law committed
1320
	 member function, we cannot tell apriori whether the
1321
	 instantiation is for a member template, or just a member
1322 1323 1324 1325
	 function of a template class.  Even if a member template is
	 being instantiated, the member template arguments may be
	 elided if they can be deduced from the rest of the
	 declaration.  */
1326 1327
      tmpl = determine_specialization (declarator, decl,
				       &targs, 
1328 1329
				       member_specialization,
				       1);
1330
	    
1331
      if (tmpl && tmpl != error_mark_node)
1332
	{
1333 1334
	  gen_tmpl = most_general_template (tmpl);

1335 1336
	  if (explicit_instantiation)
	    {
1337 1338
	      /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
		 is done by do_decl_instantiation later.  */
1339
	      decl = instantiate_template (tmpl, innermost_args (targs));
1340 1341
	      return decl;
	    }
1342 1343 1344 1345 1346 1347
	  
	  /* If we though that the DECL was a member function, but it
	     turns out to be specializing a static member function,
	     make DECL a static member function as well.  */
	  if (DECL_STATIC_FUNCTION_P (tmpl)
	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1348 1349 1350 1351
	    {
	      revert_static_member_fn (&decl, 0, 0);
	      last_function_parms = TREE_CHAIN (last_function_parms);
	    }
1352

1353 1354 1355 1356
	  /* Set up the DECL_TEMPLATE_INFO for DECL.  */
	  DECL_TEMPLATE_INFO (decl) 
	    = perm_tree_cons (tmpl, targs, NULL_TREE);

1357 1358 1359
	  /* Mangle the function name appropriately.  Note that we do
	     not mangle specializations of non-template member
	     functions of template classes, e.g. with
1360

1361
	       template <class T> struct S { void f(); }
1362

1363
	     and given the specialization 
1364

1365
	       template <> void S<int>::f() {}
1366

1367 1368
	     we do not mangle S<int>::f() here.  That's because it's
	     just an ordinary member function and doesn't need special
1369 1370 1371
	     treatment.  We do this here so that the ordinary,
	     non-template, name-mangling algorith will not be used
	     later.  */
1372
	  if ((is_member_template (tmpl) || ctype == NULL_TREE)
1373
	      && name_mangling_version >= 1)
1374
	    set_mangled_name_for_template_decl (decl);
1375 1376

	  if (is_friend && !have_def)
1377 1378 1379
	    /* This is not really a declaration of a specialization.
	       It's just the name of an instantiation.  But, it's not
	       a request for an instantiation, either.  */
1380
	    SET_DECL_IMPLICIT_INSTANTIATION (decl);
1381

1382 1383 1384
	  /* Register this specialization so that we can find it
	     again.  */
	  decl = register_specialization (decl, gen_tmpl, targs);
1385

1386
	  return decl;
1387 1388
	}
    }
1389
  
1390
  return decl;
1391
}
1392

1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
/* TYPE is being declared.  Verify that the use of template headers
   and such is reasonable.  Issue error messages if not.  */

void
maybe_check_template_type (type)
     tree type;
{
  if (template_header_count)
    {
      /* We are in the scope of some `template <...>' header.  */

      int context_depth 
	= template_class_depth_real (TYPE_CONTEXT (type),
				     /*count_specializations=*/1);

      if (template_header_count <= context_depth)
	/* This is OK; the template headers are for the context.  We
	   are actually too lenient here; like
	   check_explicit_specialization we should consider the number
	   of template types included in the actual declaration.  For
	   example, 

	     template <class T> struct S {
	       template <class U> template <class V>
	       struct I {};
	     }; 

	   is illegal, but:

	     template <class T> struct S {
	       template <class U> struct I;
	     }; 

	     template <class T> template <class U.
	     struct S<T>::I {};

	   is not.  */
	; 
      else if (template_header_count > context_depth + 1)
	/* There are two many template parameter lists.  */
jason's avatar
jason committed
1433
	cp_error ("too many template parameter lists in declaration of `%T'", type); 
1434 1435 1436
    }
}

1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
/* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
   parameters.  These are represented in the same format used for
   DECL_TEMPLATE_PARMS.  */

int comp_template_parms (parms1, parms2)
     tree parms1;
     tree parms2;
{
  tree p1;
  tree p2;

  if (parms1 == parms2)
    return 1;

  for (p1 = parms1, p2 = parms2; 
       p1 != NULL_TREE && p2 != NULL_TREE;
       p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
    {
      tree t1 = TREE_VALUE (p1);
      tree t2 = TREE_VALUE (p2);
      int i;

      my_friendly_assert (TREE_CODE (t1) == TREE_VEC, 0);
      my_friendly_assert (TREE_CODE (t2) == TREE_VEC, 0);

      if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
	return 0;

      for (i = 0; i < TREE_VEC_LENGTH (t2); ++i) 
	{
	  tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
	  tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));

	  if (TREE_CODE (parm1) != TREE_CODE (parm2))
	    return 0;

	  if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM)
	    continue;
1475
	  else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
	    return 0;
	}
    }

  if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
    /* One set of parameters has more parameters lists than the
       other.  */
    return 0;

  return 1;
}

bkoz's avatar
h  
bkoz committed
1488 1489 1490 1491 1492 1493 1494

/* Returns 1 iff old_id is a template parameter. OLD_DECL is the decl
   from IDENTIFIER_LOCAL_VALUE (new identifier). */

int decl_template_parm_p (old_decl)
     tree old_decl;
{
bkoz's avatar
 
bkoz committed
1495 1496 1497 1498
  /* For template template parms. */
  if (TREE_CODE (old_decl) == TEMPLATE_DECL
      && TREE_TYPE (old_decl)
      && TREE_CODE (TREE_TYPE (old_decl)) == TEMPLATE_TEMPLATE_PARM)
bkoz's avatar
h  
bkoz committed
1499
    return 1;
bkoz's avatar
 
bkoz committed
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513

  /* For template type parms. */
  if (TREE_CODE (old_decl) == TYPE_DECL
      && TREE_TYPE (old_decl)
      && TREE_CODE (TREE_TYPE (old_decl)) == TEMPLATE_TYPE_PARM)
    return 1;

  /* For template non-type parms. */
  if (TREE_CODE (old_decl) == CONST_DECL
      && DECL_INITIAL (old_decl) 
      && TREE_CODE (DECL_INITIAL (old_decl)) == TEMPLATE_PARM_INDEX)
    return 1;

  return 0;
bkoz's avatar
h  
bkoz committed
1514 1515 1516 1517
}


 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
jason's avatar
jason committed
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
   ORIG_LEVEL, DECL, and TYPE.  */

static tree
build_template_parm_index (index, level, orig_level, decl, type)
     int index;
     int level;
     int orig_level;
     tree decl;
     tree type;
{
  tree t = make_node (TEMPLATE_PARM_INDEX);
  TEMPLATE_PARM_IDX (t) = index;
  TEMPLATE_PARM_LEVEL (t) = level;
  TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
  TEMPLATE_PARM_DECL (t) = decl;
  TREE_TYPE (t) = type;

  return t;
}

/* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
1539
   TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
jason's avatar
jason committed
1540 1541 1542 1543
   TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
   new one is created.  */

static tree 
1544
reduce_template_parm_level (index, type, levels)
jason's avatar
jason committed
1545 1546
     tree index;
     tree type;
1547
     int levels;
jason's avatar
jason committed
1548 1549 1550
{
  if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
      || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
1551
	  != TEMPLATE_PARM_LEVEL (index) - levels))
jason's avatar
jason committed
1552 1553 1554 1555 1556 1557 1558
    {
      tree decl 
	= build_decl (TREE_CODE (TEMPLATE_PARM_DECL (index)),
		      DECL_NAME (TEMPLATE_PARM_DECL (index)),
		      type);
      tree t
	= build_template_parm_index (TEMPLATE_PARM_IDX (index),
1559
				     TEMPLATE_PARM_LEVEL (index) - levels,
jason's avatar
jason committed
1560 1561 1562
				     TEMPLATE_PARM_ORIG_LEVEL (index),
				     decl, type);
      TEMPLATE_PARM_DESCENDANTS (index) = t;
1563 1564 1565 1566

      /* Template template parameters need this.  */
      DECL_TEMPLATE_PARMS (decl)
	= DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index));
jason's avatar
jason committed
1567 1568 1569 1570 1571
    }

  return TEMPLATE_PARM_DESCENDANTS (index);
}

mrs's avatar
mrs committed
1572
/* Process information from new template parameter NEXT and append it to the
mrs's avatar
mrs committed
1573
   LIST being built.  */
mrs's avatar
mrs committed
1574

mrs's avatar
mrs committed
1575 1576 1577 1578 1579 1580
tree
process_template_parm (list, next)
     tree list, next;
{
  tree parm;
  tree decl = 0;
mrs's avatar
mrs committed
1581
  tree defval;
mrs's avatar
mrs committed
1582
  int is_type, idx;
jason's avatar
jason committed
1583

mrs's avatar
mrs committed
1584 1585
  parm = next;
  my_friendly_assert (TREE_CODE (parm) == TREE_LIST, 259);
mrs's avatar
mrs committed
1586 1587 1588
  defval = TREE_PURPOSE (parm);
  parm = TREE_VALUE (parm);
  is_type = TREE_PURPOSE (parm) == class_type_node;
mrs's avatar
mrs committed
1589 1590 1591 1592 1593 1594 1595

  if (list)
    {
      tree p = TREE_VALUE (tree_last (list));

      if (TREE_CODE (p) == TYPE_DECL)
	idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
1596 1597
      else if (TREE_CODE (p) == TEMPLATE_DECL)
	idx = TEMPLATE_TYPE_IDX (TREE_TYPE (DECL_TEMPLATE_RESULT (p)));
mrs's avatar
mrs committed
1598
      else
jason's avatar
jason committed
1599
	idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
mrs's avatar
mrs committed
1600 1601 1602 1603 1604
      ++idx;
    }
  else
    idx = 0;

mrs's avatar
mrs committed
1605 1606
  if (!is_type)
    {
mrs's avatar
mrs committed
1607
      my_friendly_assert (TREE_CODE (TREE_PURPOSE (parm)) == TREE_LIST, 260);
mrs's avatar
mrs committed
1608
      /* is a const-param */
mrs's avatar
mrs committed
1609
      parm = grokdeclarator (TREE_VALUE (parm), TREE_PURPOSE (parm),
mrs's avatar
merging  
mrs committed
1610
			     PARM, 0, NULL_TREE);
mrs's avatar
mrs committed
1611 1612
      /* A template parameter is not modifiable.  */
      TREE_READONLY (parm) = 1;
mrs's avatar
mrs committed
1613
      if (IS_AGGR_TYPE (TREE_TYPE (parm))
1614 1615
	  && TREE_CODE (TREE_TYPE (parm)) != TEMPLATE_TYPE_PARM
	  && TREE_CODE (TREE_TYPE (parm)) != TYPENAME_TYPE)
mrs's avatar
mrs committed
1616
	{
jason's avatar
jason committed
1617
	  cp_error ("`%#T' is not a valid type for a template constant parameter",
mrs's avatar
mrs committed
1618 1619
		    TREE_TYPE (parm));
	  if (DECL_NAME (parm) == NULL_TREE)
jason's avatar
jason committed
1620
	    error ("  a template type parameter must begin with `class' or `typename'");
mrs's avatar
mrs committed
1621 1622
	  TREE_TYPE (parm) = void_type_node;
	}
mrs's avatar
mrs committed
1623 1624 1625
      else if (pedantic
	       && (TREE_CODE (TREE_TYPE (parm)) == REAL_TYPE
		   || TREE_CODE (TREE_TYPE (parm)) == COMPLEX_TYPE))
jason's avatar
jason committed
1626
	cp_pedwarn ("`%T' is not a valid type for a template constant parameter",
mrs's avatar
mrs committed
1627
		    TREE_TYPE (parm));
mrs's avatar
mrs committed
1628 1629 1630 1631 1632 1633
      if (TREE_PERMANENT (parm) == 0)
        {
	  parm = copy_node (parm);
	  TREE_PERMANENT (parm) = 1;
        }
      decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
jason's avatar
jason committed
1634 1635 1636 1637
      DECL_INITIAL (parm) = DECL_INITIAL (decl) 
	= build_template_parm_index (idx, processing_template_decl,
				     processing_template_decl,
				     decl, TREE_TYPE (parm));
mrs's avatar
mrs committed
1638 1639 1640
    }
  else
    {
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
      tree t;
      parm = TREE_VALUE (parm);
      
      if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
	{
	  t = make_lang_type (TEMPLATE_TEMPLATE_PARM);
	  /* This is for distinguishing between real templates and template 
	     template parameters */
	  TREE_TYPE (parm) = t;
	  TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
	  decl = parm;
	}
      else
	{
	  t = make_lang_type (TEMPLATE_TYPE_PARM);
	  /* parm is either IDENTIFIER_NODE or NULL_TREE */
	  decl = build_decl (TYPE_DECL, parm, t);
	}
        
mrs's avatar
mrs committed
1660 1661
      TYPE_NAME (t) = decl;
      TYPE_STUB_DECL (t) = decl;
mrs's avatar
mrs committed
1662
      parm = decl;
jason's avatar
jason committed
1663 1664 1665 1666
      TEMPLATE_TYPE_PARM_INDEX (t)
	= build_template_parm_index (idx, processing_template_decl, 
				     processing_template_decl,
				     decl, TREE_TYPE (parm));
mrs's avatar
mrs committed
1667
    }
mrs's avatar
mrs committed
1668
  SET_DECL_ARTIFICIAL (decl);
mrs's avatar
mrs committed
1669
  pushdecl (decl);
mrs's avatar
mrs committed
1670
  parm = build_tree_list (defval, parm);
mrs's avatar
mrs committed
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
  return chainon (list, parm);
}

/* The end of a template parameter list has been reached.  Process the
   tree list into a parameter vector, converting each parameter into a more
   useful form.	 Type parameters are saved as IDENTIFIER_NODEs, and others
   as PARM_DECLs.  */

tree
end_template_parm_list (parms)
     tree parms;
{
mrs's avatar
mrs committed
1683
  int nparms;
mrs's avatar
mrs committed
1684
  tree parm;
mrs's avatar
mrs committed
1685 1686 1687 1688 1689
  tree saved_parmlist = make_tree_vec (list_length (parms));

  current_template_parms
    = tree_cons (build_int_2 (0, processing_template_decl),
		 saved_parmlist, current_template_parms);
mrs's avatar
mrs committed
1690 1691

  for (parm = parms, nparms = 0; parm; parm = TREE_CHAIN (parm), nparms++)
mrs's avatar
mrs committed
1692
    TREE_VEC_ELT (saved_parmlist, nparms) = parm;
mrs's avatar
mrs committed
1693

1694 1695
  --processing_template_parmlist;

mrs's avatar
mrs committed
1696 1697 1698
  return saved_parmlist;
}

mrs's avatar
mrs committed
1699 1700
/* end_template_decl is called after a template declaration is seen.  */

mrs's avatar
mrs committed
1701
void
mrs's avatar
mrs committed
1702
end_template_decl ()
mrs's avatar
mrs committed
1703
{
1704 1705
  reset_specialization ();

mrs's avatar
mrs committed
1706
  if (! processing_template_decl)
mrs's avatar
mrs committed
1707 1708
    return;

mrs's avatar
mrs committed
1709 1710
  /* This matches the pushlevel in begin_template_parm_list.  */
  poplevel (0, 0, 0);
mrs's avatar
mrs committed
1711

mrs's avatar
mrs committed
1712 1713 1714 1715
  --processing_template_decl;
  current_template_parms = TREE_CHAIN (current_template_parms);
  (void) get_pending_sizes ();	/* Why? */
}
mrs's avatar
mrs committed
1716

1717 1718
/* Given a template argument vector containing the template PARMS.
   The innermost PARMS are given first.  */
mrs's avatar
mrs committed
1719 1720 1721

tree
current_template_args ()
mrs's avatar
mrs committed
1722
{
1723
  tree header;
ghazi's avatar
ghazi committed
1724
  tree args = NULL_TREE;
1725
  int length = TMPL_PARMS_DEPTH (current_template_parms);
1726 1727
  int l = length;

1728 1729 1730 1731 1732 1733 1734
  /* If there is only one level of template parameters, we do not
     create a TREE_VEC of TREE_VECs.  Instead, we return a single
     TREE_VEC containing the arguments.  */
  if (length > 1)
    args = make_tree_vec (length);

  for (header = current_template_parms; header; header = TREE_CHAIN (header))
mrs's avatar
mrs committed
1735
    {
mrs's avatar
mrs committed
1736
      tree a = copy_node (TREE_VALUE (header));
1737 1738
      int i;

mrs's avatar
mrs committed
1739
      TREE_TYPE (a) = NULL_TREE;
1740
      for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
mrs's avatar
mrs committed
1741
	{
1742 1743
	  tree t = TREE_VEC_ELT (a, i);

1744
	  /* T will be a list if we are called from within a
1745 1746 1747 1748 1749 1750
	     begin/end_template_parm_list pair, but a vector directly
	     if within a begin/end_member_template_processing pair.  */
	  if (TREE_CODE (t) == TREE_LIST) 
	    {
	      t = TREE_VALUE (t);
	      
1751 1752
	      if (TREE_CODE (t) == TYPE_DECL 
		  || TREE_CODE (t) == TEMPLATE_DECL)
1753 1754 1755
		t = TREE_TYPE (t);
	      else
		t = DECL_INITIAL (t);
1756
	      TREE_VEC_ELT (a, i) = t;
1757
	    }
mrs's avatar
mrs committed
1758
	}
1759 1760 1761 1762 1763

      if (length > 1)
	TREE_VEC_ELT (args, --l) = a;
      else
	args = a;
mrs's avatar
mrs committed
1764 1765
    }

mrs's avatar
mrs committed
1766 1767
  return args;
}
1768

1769 1770 1771
/* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
   template PARMS.  Used by push_template_decl below.  */

1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
static tree
build_template_decl (decl, parms)
     tree decl;
     tree parms;
{
  tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
  DECL_TEMPLATE_PARMS (tmpl) = parms;
  DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
  if (DECL_LANG_SPECIFIC (decl))
    {
      DECL_CLASS_CONTEXT (tmpl) = DECL_CLASS_CONTEXT (decl);
      DECL_STATIC_FUNCTION_P (tmpl) = 
	DECL_STATIC_FUNCTION_P (decl);
    }

  return tmpl;
}

1790 1791
struct template_parm_data
{
1792 1793
  /* The level of the template parameters we are currently
     processing.  */
1794
  int level;
1795 1796 1797 1798 1799 1800 1801 1802

  /* The index of the specialization argument we are currently
     processing.  */
  int current_arg;

  /* An array whose size is the number of template parameters.  The
     elements are non-zero if the parameter has been used in any one
     of the arguments processed so far.  */
1803
  int* parms;
1804 1805 1806 1807 1808

  /* An array whose size is the number of template arguments.  The
     elements are non-zero if the argument makes use of template
     parameters of this level.  */
  int* arg_uses_template_parms;
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
};

/* Subroutine of push_template_decl used to see if each template
   parameter in a partial specialization is used in the explicit
   argument list.  If T is of the LEVEL given in DATA (which is
   treated as a template_parm_data*), then DATA->PARMS is marked
   appropriately.  */

static int
mark_template_parm (t, data)
     tree t;
     void* data;
{
  int level;
  int idx;
  struct template_parm_data* tpd = (struct template_parm_data*) data;

  if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
    {
      level = TEMPLATE_PARM_LEVEL (t);
      idx = TEMPLATE_PARM_IDX (t);
    }
  else
    {
      level = TEMPLATE_TYPE_LEVEL (t);
      idx = TEMPLATE_TYPE_IDX (t);
    }

  if (level == tpd->level)
1838 1839 1840 1841
    {
      tpd->parms[idx] = 1;
      tpd->arg_uses_template_parms[tpd->current_arg] = 1;
    }
1842 1843 1844 1845 1846 1847

  /* Return zero so that for_each_template_parm will continue the
     traversal of the tree; we want to mark *every* template parm.  */
  return 0;
}

1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
/* Process the partial specialization DECL.  */

tree
process_partial_specialization (decl)
     tree decl;
{
  tree type = TREE_TYPE (decl);
  tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
  tree specargs = CLASSTYPE_TI_ARGS (type);
  tree inner_args = innermost_args (specargs);
  tree inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
  tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
  int nargs = TREE_VEC_LENGTH (inner_args);
  int ntparms = TREE_VEC_LENGTH (inner_parms);
  int  i;
  int did_error_intro = 0;
  struct template_parm_data tpd;
  struct template_parm_data tpd2;

  /* We check that each of the template parameters given in the
     partial specialization is used in the argument list to the
     specialization.  For example:

       template <class T> struct S;
       template <class T> struct S<T*>;

     The second declaration is OK because `T*' uses the template
     parameter T, whereas

       template <class T> struct S<int>;

     is no good.  Even trickier is:

       template <class T>
       struct S1
       {
	  template <class U>
	  struct S2;
	  template <class U>
	  struct S2<T>;
       };

     The S2<T> declaration is actually illegal; it is a
     full-specialization.  Of course, 

	  template <class U>
	  struct S2<T (*)(U)>;

     or some such would have been OK.  */
  tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
  tpd.parms = alloca (sizeof (int) * ntparms);
ghazi's avatar
ghazi committed
1899
  bzero ((PTR) tpd.parms, sizeof (int) * ntparms);
1900 1901

  tpd.arg_uses_template_parms = alloca (sizeof (int) * nargs);
ghazi's avatar
ghazi committed
1902
  bzero ((PTR) tpd.arg_uses_template_parms, sizeof (int) * nargs);
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916
  for (i = 0; i < nargs; ++i)
    {
      tpd.current_arg = i;
      for_each_template_parm (TREE_VEC_ELT (inner_args, i),
			      &mark_template_parm,
			      &tpd);
    }
  for (i = 0; i < ntparms; ++i)
    if (tpd.parms[i] == 0)
      {
	/* One of the template parms was not used in the
           specialization.  */
	if (!did_error_intro)
	  {
jason's avatar
jason committed
1917
	    cp_error ("template parameters not used in partial specialization:");
1918 1919 1920
	    did_error_intro = 1;
	  }

jason's avatar
jason committed
1921
	cp_error ("        `%D'", 
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
		  TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
      }

  /* [temp.class.spec]

     The argument list of the specialization shall not be identical to
     the implicit argument list of the primary template.  */
  if (comp_template_args (inner_args, 
			  innermost_args (CLASSTYPE_TI_ARGS (TREE_TYPE
							     (maintmpl)))))
jason's avatar
jason committed
1932
    cp_error ("partial specialization `%T' does not specialize any template arguments", type);
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956

  /* [temp.class.spec]

     A partially specialized non-type argument expression shall not
     involve template parameters of the partial specialization except
     when the argument expression is a simple identifier.

     The type of a template parameter corresponding to a specialized
     non-type argument shall not be dependent on a parameter of the
     specialization.  */
  my_friendly_assert (nargs == DECL_NTPARMS (maintmpl), 0);
  tpd2.parms = 0;
  for (i = 0; i < nargs; ++i)
    {
      tree arg = TREE_VEC_ELT (inner_args, i);
      if (/* These first two lines are the `non-type' bit.  */
	  TREE_CODE_CLASS (TREE_CODE (arg)) != 't'
	  && TREE_CODE (arg) != TEMPLATE_DECL
	  /* This next line is the `argument expression is not just a
	     simple identifier' condition and also the `specialized
	     non-type argument' bit.  */
	  && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
	{
	  if (tpd.arg_uses_template_parms[i])
jason's avatar
jason committed
1957
	    cp_error ("template argument `%E' involves template parameter(s)", arg);
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971
	  else 
	    {
	      /* Look at the corresponding template parameter,
		 marking which template parameters its type depends
		 upon.  */
	      tree type = 
		TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (main_inner_parms, 
						     i)));

	      if (!tpd2.parms)
		{
		  /* We haven't yet initialized TPD2.  Do so now.  */
		  tpd2.arg_uses_template_parms 
		    =  (int*) alloca (sizeof (int) * nargs);
1972 1973 1974
		  /* The number of paramters here is the number in the
		     main template, which, as checked in the assertion
		     above, is NARGS.  */
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
		  tpd2.parms = (int*) alloca (sizeof (int) * nargs);
		  tpd2.level = 
		    TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
		}

	      /* Mark the template paramters.  But this time, we're
		 looking for the template parameters of the main
		 template, not in the specialization.  */
	      tpd2.current_arg = i;
	      tpd2.arg_uses_template_parms[i] = 0;
ghazi's avatar
ghazi committed
1985
	      bzero ((PTR) tpd2.parms, sizeof (int) * nargs);
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
	      for_each_template_parm (type,
				      &mark_template_parm,
				      &tpd2);
		  
	      if (tpd2.arg_uses_template_parms [i])
		{
		  /* The type depended on some template parameters.
		     If they are fully specialized in the
		     specialization, that's OK.  */
		  int j;
		  for (j = 0; j < nargs; ++j)
		    if (tpd2.parms[j] != 0
			&& tpd.arg_uses_template_parms [j])
		      {
jason's avatar
jason committed
2000
			cp_error ("type `%T' of template argument `%E' depends on template paramter(s)", 
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
				  type,
				  arg);
			break;
		      }
		}
	    }
	}
    }

  if (retrieve_specialization (maintmpl, specargs))
    /* We've already got this specialization.  */
    return decl;

  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl) = CLASSTYPE_TI_SPEC_INFO (type)
    = perm_tree_cons (inner_args, inner_parms,
		      DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
  TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
  return decl;
}

2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121
/* Check that a template declaration's use of default arguments is not
   invalid.  Here, PARMS are the template parameters.  IS_PRIMARY is
   non-zero if DECL is the thing declared by a primary template.
   IS_PARTIAL is non-zero if DECL is a partial specialization.  */

static void
check_default_tmpl_args (decl, parms, is_primary, is_partial)
     tree decl;
     tree parms;
     int is_primary;
     int is_partial;
{
  char* msg;
  int   last_level_to_check;

  /* [temp.param] 

     A default template-argument shall not be specified in a
     function template declaration or a function template definition, nor
     in the template-parameter-list of the definition of a member of a
     class template.  */

  if (current_class_type
      && !TYPE_BEING_DEFINED (current_class_type)
      && DECL_REAL_CONTEXT (decl) == current_class_type
      && DECL_DEFINED_IN_CLASS_P (decl)) 
    /* We already checked these parameters when the template was
       declared, so there's no need to do it again now.  This is an
       inline member function definition.  */
    return;

  if (TREE_CODE (decl) != TYPE_DECL || is_partial || !is_primary)
    /* For an ordinary class template, default template arguments are
       allowed at the innermost level, e.g.:
         template <class T = int>
	 struct S {};
       but, in a partial specialization, they're not allowed even
       there, as we have in [temp.class.spec]:
     
	 The template parameter list of a specialization shall not
	 contain default template argument values.  

       So, for a partial specialization, or for a function template,
       we look at all of them.  */
    ;
  else
    /* But, for a primary class template that is not a partial
       specialization we look at all template parameters except the
       innermost ones.  */
    parms = TREE_CHAIN (parms);

  /* Figure out what error message to issue.  */
  if (TREE_CODE (decl) == FUNCTION_DECL)
    msg = "default argument for template parameter in function template `%D'";
  else if (is_partial)
    msg = "default argument in partial specialization `%D'";
  else
    msg = "default argument for template parameter for class enclosing `%D'";

  if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
    /* If we're inside a class definition, there's no need to
       examine the paramters to the class itself.  On the one
       hand, they will be checked when the class is defined, and,
       on the other, default arguments are legal in things like:
         template <class T = double>
         struct S { template <class U> void f(U); };
       Here the default argument for `S' has no bearing on the
       declaration of `f'.  */
    last_level_to_check = template_class_depth (current_class_type) + 1;
  else
    /* Check everything.  */
    last_level_to_check = 0;

  for (; parms && TMPL_PARMS_DEPTH (parms) >= last_level_to_check; 
       parms = TREE_CHAIN (parms))
    {
      tree inner_parms = TREE_VALUE (parms);
      int i, ntparms;

      ntparms = TREE_VEC_LENGTH (inner_parms);
      for (i = 0; i < ntparms; ++i) 
	if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
	  {
	    if (msg)
	      {
		cp_error (msg, decl);
		msg = 0;
	      }

	    /* Clear out the default argument so that we are not
	       confused later.  */
	    TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
	  }

      /* At this point, if we're still interested in issuing messages,
	 they must apply to classes surrounding the object declared.  */
      if (msg)
	msg = "default argument for template parameter for class enclosing `%D'"; 
    }
}

2122
/* Creates a TEMPLATE_DECL for the indicated DECL using the template
jason's avatar
jason committed
2123 2124
   parameters given by current_template_args, or reuses a
   previously existing one, if appropriate.  Returns the DECL, or an
2125 2126 2127
   equivalent one, if it is replaced via a call to duplicate_decls.  

   If IS_FRIEND is non-zero, DECL is a friend declaration.  */
2128 2129

tree
2130
push_template_decl_real (decl, is_friend)
mrs's avatar
mrs committed
2131
     tree decl;
2132
     int is_friend;
mrs's avatar
mrs committed
2133 2134
{
  tree tmpl;
jason's avatar
jason committed
2135
  tree args;
mrs's avatar
mrs committed
2136
  tree info;
jason's avatar
jason committed
2137 2138
  tree ctx;
  int primary;
2139 2140 2141 2142 2143 2144
  int is_partial;

  /* See if this is a partial specialization.  */
  is_partial = (TREE_CODE (decl) == TYPE_DECL && DECL_ARTIFICIAL (decl)
		&& TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
		&& CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
2145 2146

  is_friend |= (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl));
jason's avatar
jason committed
2147 2148 2149 2150 2151

  if (is_friend)
    /* For a friend, we want the context of the friend function, not
       the type of which it is a friend.  */
    ctx = DECL_CONTEXT (decl);
jason's avatar
jason committed
2152 2153
  else if (DECL_REAL_CONTEXT (decl)
	   && TREE_CODE (DECL_REAL_CONTEXT (decl)) != NAMESPACE_DECL)
jason's avatar
jason committed
2154 2155 2156 2157 2158 2159 2160 2161
    /* In the case of a virtual function, we want the class in which
       it is defined.  */
    ctx = DECL_REAL_CONTEXT (decl);
  else
    /* Otherwise, if we're currently definining some class, the DECL
       is assumed to be a member of the class.  */
    ctx = current_class_type;

jason's avatar
jason committed
2162 2163 2164 2165
  if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
    ctx = NULL_TREE;

  if (!DECL_CONTEXT (decl))
2166
    DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
jason's avatar
jason committed
2167

2168 2169 2170
  /* For determining whether this is a primary template or not, we're really
     interested in the lexical context, not the true context.  */
  if (is_friend)
2171
    info = current_class_type;
2172 2173 2174
  else
    info = ctx;

2175
  /* See if this is a primary template.  */
2176 2177
  if (info && TREE_CODE (info) == FUNCTION_DECL)
    primary = 0;
2178 2179 2180
  /* Note that template_class_depth returns 0 if given NULL_TREE, so
     this next line works even when we are at global scope.  */
  else if (processing_template_decl > template_class_depth (info))
mrs's avatar
mrs committed
2181
    primary = 1;
jason's avatar
jason committed
2182 2183
  else
    primary = 0;
mrs's avatar
mrs committed
2184

2185 2186 2187
  if (primary)
    {
      if (current_lang_name == lang_name_c)
jason's avatar
jason committed
2188
	cp_error ("template with C linkage");
2189
      if (TREE_CODE (decl) == TYPE_DECL && ANON_AGGRNAME_P (DECL_NAME (decl)))
jason's avatar
jason committed
2190
	cp_error ("template class without a name");
2191 2192
      if (TREE_CODE (decl) == TYPE_DECL 
	  && TREE_CODE (TREE_TYPE (decl)) == ENUMERAL_TYPE)
jason's avatar
jason committed
2193
	cp_error ("template declaration of `%#T'", TREE_TYPE (decl));
2194 2195
    }

2196 2197 2198 2199
  /* Check to see that the rules regarding the use of default
     arguments are not being violated.  */
  check_default_tmpl_args (decl, current_template_parms, 
			   primary, is_partial);
mrs's avatar
mrs committed
2200

2201 2202
  if (is_partial)
    return process_partial_specialization (decl);
2203

mrs's avatar
mrs committed
2204 2205
  args = current_template_args ();

jason's avatar
jason committed
2206 2207 2208 2209
  if (!ctx 
      || TREE_CODE (ctx) == FUNCTION_DECL
      || TYPE_BEING_DEFINED (ctx)
      || (is_friend && !DECL_TEMPLATE_INFO (decl)))
mrs's avatar
mrs committed
2210
    {
2211
      if (DECL_LANG_SPECIFIC (decl)
jason's avatar
jason committed
2212 2213 2214 2215
	  && DECL_TEMPLATE_INFO (decl)
	  && DECL_TI_TEMPLATE (decl))
	tmpl = DECL_TI_TEMPLATE (decl);
      else
2216
	{
jason's avatar
jason committed
2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227
	  tmpl = build_template_decl (decl, current_template_parms);
	  
	  if (DECL_LANG_SPECIFIC (decl)
	      && DECL_TEMPLATE_SPECIALIZATION (decl))
	    {
	      /* A specialization of a member template of a template
		 class. */
	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
	      DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
	      DECL_TEMPLATE_INFO (decl) = NULL_TREE;
	    }
2228
	}
mrs's avatar
mrs committed
2229 2230 2231
    }
  else
    {
2232
      tree a, t, current, parms;
2233
      int i;
mrs's avatar
mrs committed
2234

mrs's avatar
mrs committed
2235
      if (CLASSTYPE_TEMPLATE_INSTANTIATION (ctx))
jason's avatar
jason committed
2236
	cp_error ("must specialize `%#T' before defining member `%#D'",
mrs's avatar
mrs committed
2237
		  ctx, decl);
2238 2239
      if (TREE_CODE (decl) == TYPE_DECL)
	{
2240 2241 2242 2243 2244
	  if ((IS_AGGR_TYPE_CODE (TREE_CODE (TREE_TYPE (decl)))
	       || TREE_CODE (TREE_TYPE (decl)) == ENUMERAL_TYPE)
	      && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
	      && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
	    tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
2245 2246
	  else
	    {
jason's avatar
jason committed
2247
	      cp_error ("`%D' does not declare a template type", decl);
2248 2249 2250
	      return decl;
	    }
	}
mrs's avatar
mrs committed
2251
      else if (! DECL_TEMPLATE_INFO (decl))
mrs's avatar
mrs committed
2252
	{
jason's avatar
jason committed
2253
	  cp_error ("template definition of non-template `%#D'", decl);
2254
	  return decl;
mrs's avatar
mrs committed
2255
	}
mrs's avatar
mrs committed
2256
      else
mrs's avatar
mrs committed
2257
	tmpl = DECL_TI_TEMPLATE (decl);
2258
      
2259 2260 2261 2262
      if (is_member_template (tmpl)
	  && DECL_FUNCTION_TEMPLATE_P (tmpl)
	  && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl) 
	  && DECL_TEMPLATE_SPECIALIZATION (decl))
2263
	{
2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283
	  tree new_tmpl;

	  /* The declaration is a specialization of a member
	     template, declared outside the class.  Therefore, the
	     innermost template arguments will be NULL, so we
	     replace them with the arguments determined by the
	     earlier call to check_explicit_specialization.  */
	  args = DECL_TI_ARGS (decl);

	  new_tmpl 
	    = build_template_decl (decl, current_template_parms);
	  DECL_TEMPLATE_RESULT (new_tmpl) = decl;
	  TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
	  DECL_TI_TEMPLATE (decl) = new_tmpl;
	  SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
	  DECL_TEMPLATE_INFO (new_tmpl) = 
	    perm_tree_cons (tmpl, args, NULL_TREE);

	  register_specialization (new_tmpl, tmpl, args);
	  return decl;
2284 2285
	}

2286
      /* Make sure the template headers we got make sense.  */
mrs's avatar
mrs committed
2287

2288 2289 2290
      parms = DECL_TEMPLATE_PARMS (tmpl);
      i = TMPL_PARMS_DEPTH (parms);
      if (TMPL_ARGS_DEPTH (args) != i)
2291
	{
2292 2293
	  cp_error ("expected %d levels of template parms for `%#D', got %d",
		    i, decl, TMPL_ARGS_DEPTH (args));
2294
	}
2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310
      else
	for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
	  {
	    a = TMPL_ARGS_LEVEL (args, i);
	    t = INNERMOST_TEMPLATE_PARMS (parms);

	    if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
	      {
		if (current == decl)
		  cp_error ("got %d template parameters for `%#D'",
			    TREE_VEC_LENGTH (a), decl);
		else
		  cp_error ("got %d template parameters for `%#T'",
			    TREE_VEC_LENGTH (a), current);
		cp_error ("  but %d required", TREE_VEC_LENGTH (t));
	      }
2311

2312 2313
	    /* Perhaps we should also check that the parms are used in the
               appropriate qualifying scopes in the declarator?  */
mrs's avatar
mrs committed
2314

2315 2316 2317 2318 2319
	    if (current == decl)
	      current = ctx;
	    else
	      current = TYPE_CONTEXT (current);
	  }
mrs's avatar
mrs committed
2320
    }
mrs's avatar
mrs committed
2321

mrs's avatar
mrs committed
2322 2323
  DECL_TEMPLATE_RESULT (tmpl) = decl;
  TREE_TYPE (tmpl) = TREE_TYPE (decl);
mrs's avatar
mrs committed
2324

2325 2326 2327
  /* Push template declarations for global functions and types.  Note
     that we do not try to push a global template friend declared in a
     template class; such a thing may well depend on the template
2328
     parameters of the class.  */
2329 2330
  if (! ctx 
      && !(is_friend && template_class_depth (current_class_type) > 0))
jason's avatar
jason committed
2331
    tmpl = pushdecl_namespace_level (tmpl);
mrs's avatar
mrs committed
2332

mrs's avatar
mrs committed
2333
  if (primary)
2334
    DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
mrs's avatar
mrs committed
2335 2336 2337

  info = perm_tree_cons (tmpl, args, NULL_TREE);

mrs's avatar
mrs committed
2338
  if (TREE_CODE (decl) == TYPE_DECL && DECL_ARTIFICIAL (decl))
mrs's avatar
mrs committed
2339
    {
2340 2341 2342
      SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
      if ((!ctx || TREE_CODE (ctx) != FUNCTION_DECL)
	  && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE)
2343
	DECL_NAME (decl) = classtype_mangled_name (TREE_TYPE (decl));
mrs's avatar
mrs committed
2344
    }
mrs's avatar
mrs committed
2345
  else if (! DECL_LANG_SPECIFIC (decl))
jason's avatar
jason committed
2346
    cp_error ("template declaration of `%#D'", decl);
mrs's avatar
mrs committed
2347
  else
mrs's avatar
mrs committed
2348
    DECL_TEMPLATE_INFO (decl) = info;
2349 2350

  return DECL_TEMPLATE_RESULT (tmpl);
mrs's avatar
mrs committed
2351 2352
}

2353 2354 2355 2356 2357 2358 2359 2360 2361
tree
push_template_decl (decl)
     tree decl;
{
  return push_template_decl_real (decl, 0);
}

/* Called when a class template TYPE is redeclared with the indicated
   template PARMS, e.g.:
2362 2363 2364 2365 2366

     template <class T> struct S;
     template <class T> struct S {};  */

void 
2367
redeclare_class_template (type, parms)
2368
     tree type;
2369
     tree parms;
2370 2371
{
  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
2372
  tree tmpl_parms;
2373 2374 2375 2376 2377 2378 2379 2380
  int i;

  if (!PRIMARY_TEMPLATE_P (tmpl))
    /* The type is nested in some template class.  Nothing to worry
       about here; there are no new template parameters for the nested
       type.  */
    return;

2381 2382 2383
  parms = INNERMOST_TEMPLATE_PARMS (parms);
  tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);

2384 2385
  if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
    {
jason's avatar
jason committed
2386 2387
      cp_error_at ("previous declaration `%D'", tmpl);
      cp_error ("used %d template parameter%s instead of %d",
2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402
		TREE_VEC_LENGTH (tmpl_parms), 
		TREE_VEC_LENGTH (tmpl_parms) == 1 ? "" : "s",
		TREE_VEC_LENGTH (parms));
      return;
    }

  for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
    {
      tree tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
      tree tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
      tree parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));

      if (TREE_CODE (tmpl_parm) != TREE_CODE (parm))
	{
jason's avatar
jason committed
2403 2404
	  cp_error_at ("template parameter `%#D'", tmpl_parm);
	  cp_error ("redeclared here as `%#D'", parm);
2405 2406 2407 2408 2409 2410 2411 2412 2413
	  return;
	}

      if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
	{
	  /* We have in [temp.param]:

	     A template-parameter may not be given default arguments
	     by two different declarations in the same scope.  */
jason's avatar
jason committed
2414 2415
	  cp_error ("redefinition of default argument for `%#D'", parm);
	  cp_error_at ("  original definition appeared here", tmpl_parm);
2416 2417 2418 2419 2420 2421 2422 2423 2424
	  return;
	}

      if (parm_default != NULL_TREE)
	/* Update the previous template parameters (which are the ones
	   that will really count) with the new default value.  */
	TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
    }
}
2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436

/* Attempt to convert the non-type template parameter EXPR to the
   indicated TYPE.  If the conversion is successful, return the
   converted value.  If the conversion is unsuccesful, return
   NULL_TREE if we issued an error message, or error_mark_node if we
   did not.  We issue error messages for out-and-out bad template
   parameters, but not simply because the conversion failed, since we
   might be just trying to do argument deduction.  By the time this
   function is called, neither TYPE nor EXPR may make use of template
   parameters.  */

static tree
2437
convert_nontype_argument (type, expr)
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452
     tree type;
     tree expr;
{
  tree expr_type = TREE_TYPE (expr);

  /* A template-argument for a non-type, non-template
     template-parameter shall be one of:

     --an integral constant-expression of integral or enumeration
     type; or
     
     --the name of a non-type template-parameter; or
     
     --the name of an object or function with external linkage,
     including function templates and function template-ids but
2453
     excluding non-static class members, expressed as id-expression;
2454 2455 2456 2457 2458 2459 2460 2461 2462 2463
     or
     
     --the address of an object or function with external linkage,
     including function templates and function template-ids but
     excluding non-static class members, expressed as & id-expression
     where the & is optional if the name refers to a function or
     array; or
     
     --a pointer to member expressed as described in _expr.unary.op_.  */

2464 2465 2466 2467 2468
  /* An integral constant-expression can include const variables
     or enumerators.  */
  if (INTEGRAL_TYPE_P (expr_type) && TREE_READONLY_DECL_P (expr))
    expr = decl_constant_value (expr);

2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479
  if (is_overloaded_fn (expr))
    /* OK for now.  We'll check that it has external linkage later.
       Check this first since if expr_type is the unknown_type_node
       we would otherwise complain below.  */
    ;
  else if (INTEGRAL_TYPE_P (expr_type) 
	   || TYPE_PTRMEM_P (expr_type) 
	   || TYPE_PTRMEMFUNC_P (expr_type)
	   /* The next two are g++ extensions.  */
	   || TREE_CODE (expr_type) == REAL_TYPE
	   || TREE_CODE (expr_type) == COMPLEX_TYPE)
2480
    {
2481
      if (! TREE_CONSTANT (expr))
2482
	{
2483
	non_constant:
jason's avatar
jason committed
2484
	  cp_error ("non-constant `%E' cannot be used as template argument",
2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
		    expr);
	  return NULL_TREE;
	}
    }
  else if (TYPE_PTR_P (expr_type) 
	   /* If expr is the address of an overloaded function, we
	      will get the unknown_type_node at this point.  */
	   || expr_type == unknown_type_node)
    {
      tree referent;
2495 2496
      tree e = expr;
      STRIP_NOPS (e);
2497

2498
      if (TREE_CODE (e) != ADDR_EXPR)
2499 2500
	{
	bad_argument:
jason's avatar
jason committed
2501 2502
	  cp_error ("`%E' is not a valid template argument", expr);
	  error ("it must be %s%s with external linkage",
2503 2504 2505 2506 2507 2508 2509
		 TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE
		 ? "a pointer to " : "",
		 TREE_CODE (TREE_TYPE (TREE_TYPE (expr))) == FUNCTION_TYPE
		 ? "a function" : "an object");
	  return NULL_TREE;
	}

2510
      referent = TREE_OPERAND (e, 0);
2511 2512 2513 2514
      STRIP_NOPS (referent);
      
      if (TREE_CODE (referent) == STRING_CST)
	{
jason's avatar
jason committed
2515
	  cp_error ("string literal %E is not a valid template argument", 
2516
		    referent);
jason's avatar
jason committed
2517
	  error ("because it is the address of an object with static linkage");
2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
	  return NULL_TREE;
	}

      if (is_overloaded_fn (referent))
	/* We'll check that it has external linkage later.  */
	;
      else if (TREE_CODE (referent) != VAR_DECL)
	goto bad_argument;
      else if (!TREE_PUBLIC (referent))
	{
jason's avatar
jason committed
2528
	  cp_error ("address of non-extern `%E' cannot be used as template argument", referent); 
2529 2530 2531
	  return error_mark_node;
	}
    }
2532
  else if (TREE_CODE (expr) == VAR_DECL)
2533 2534 2535 2536 2537 2538
    {
      if (!TREE_PUBLIC (expr))
	goto bad_argument;
    }
  else 
    {
jason's avatar
jason committed
2539
      cp_error ("object `%E' cannot be used as template argument", expr);
2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555
      return NULL_TREE;
    }

  switch (TREE_CODE (type))
    {
    case INTEGER_TYPE:
    case BOOLEAN_TYPE:
    case ENUMERAL_TYPE:
      /* For a non-type template-parameter of integral or enumeration
         type, integral promotions (_conv.prom_) and integral
         conversions (_conv.integral_) are applied. */
      if (!INTEGRAL_TYPE_P (expr_type))
	return error_mark_node;
      
      /* It's safe to call digest_init in this case; we know we're
	 just converting one integral constant expression to another.  */
2556
      expr = digest_init (type, expr, (tree*) 0);
2557

2558 2559 2560 2561 2562 2563 2564 2565
      if (TREE_CODE (expr) != INTEGER_CST)
	/* Curiously, some TREE_CONSTNAT integral expressions do not
	   simplify to integer constants.  For example, `3 % 0',
	   remains a TRUNC_MOD_EXPR.  */
	goto non_constant;
      
      return expr;
	
2566 2567 2568 2569 2570 2571
    case REAL_TYPE:
    case COMPLEX_TYPE:
      /* These are g++ extensions.  */
      if (TREE_CODE (expr_type) != TREE_CODE (type))
	return error_mark_node;

2572 2573 2574 2575 2576 2577
      expr = digest_init (type, expr, (tree*) 0);
      
      if (TREE_CODE (expr) != REAL_CST)
	goto non_constant;

      return expr;
2578

2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598
    case POINTER_TYPE:
      {
	tree type_pointed_to = TREE_TYPE (type);
 
	if (TYPE_PTRMEM_P (type))
	  /* For a non-type template-parameter of type pointer to data
	     member, qualification conversions (_conv.qual_) are
	     applied.  */
	  return perform_qualification_conversions (type, expr);
	else if (TREE_CODE (type_pointed_to) == FUNCTION_TYPE)
	  { 
	    /* For a non-type template-parameter of type pointer to
	       function, only the function-to-pointer conversion
	       (_conv.func_) is applied.  If the template-argument
	       represents a set of overloaded functions (or a pointer to
	       such), the matching function is selected from the set
	       (_over.over_).  */
	    tree fns;
	    tree fn;

2599
	    if (TREE_CODE (expr) == ADDR_EXPR)
2600 2601 2602 2603
	      fns = TREE_OPERAND (expr, 0);
	    else
	      fns = expr;

jason's avatar
Revert  
jason committed
2604
	    fn = instantiate_type (type_pointed_to, fns, 0);
2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618

	    if (fn == error_mark_node)
	      return error_mark_node;

	    if (!TREE_PUBLIC (fn))
	      {
		if (really_overloaded_fn (fns))
		  return error_mark_node;
		else
		  goto bad_argument;
	      }

	    expr = build_unary_op (ADDR_EXPR, fn, 0);

2619
	    my_friendly_assert (same_type_p (type, TREE_TYPE (expr)), 
2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632
				0);
	    return expr;
	  }
	else 
	  {
	    /* For a non-type template-parameter of type pointer to
	       object, qualification conversions (_conv.qual_) and the
	       array-to-pointer conversion (_conv.array_) are applied.
	       [Note: In particular, neither the null pointer conversion
	       (_conv.ptr_) nor the derived-to-base conversion
	       (_conv.ptr_) are applied.  Although 0 is a valid
	       template-argument for a non-type template-parameter of
	       integral type, it is not a valid template-argument for a
2633 2634 2635 2636 2637
	       non-type template-parameter of pointer type.]  
	    
	       The call to decay_conversion performs the
	       array-to-pointer conversion, if appropriate.  */
	    expr = decay_conversion (expr);
2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653

	    if (expr == error_mark_node)
	      return error_mark_node;
	    else
	      return perform_qualification_conversions (type, expr);
	  }
      }
      break;

    case REFERENCE_TYPE:
      {
	tree type_referred_to = TREE_TYPE (type);

	if (TREE_CODE (type_referred_to) == FUNCTION_TYPE)
	  {
	    /* For a non-type template-parameter of type reference to
2654 2655 2656 2657
	       function, no conversions apply.  If the
	       template-argument represents a set of overloaded
	       functions, the matching function is selected from the
	       set (_over.over_).  */
2658 2659 2660
	    tree fns = expr;
	    tree fn;

jason's avatar
Revert  
jason committed
2661
	    fn = instantiate_type (type_referred_to, fns, 0);
2662 2663 2664

	    if (fn == error_mark_node)
	      return error_mark_node;
2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676

	    if (!TREE_PUBLIC (fn))
	      {
		if (really_overloaded_fn (fns))
		  /* Don't issue an error here; we might get a different
		     function if the overloading had worked out
		     differently.  */
		  return error_mark_node;
		else
		  goto bad_argument;
	      }

2677 2678
	    my_friendly_assert (same_type_p (type_referred_to, 
					     TREE_TYPE (fn)),
2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690
				0);

	    return fn;
	  }
	else
	  {
	    /* For a non-type template-parameter of type reference to
	       object, no conversions apply.  The type referred to by the
	       reference may be more cv-qualified than the (otherwise
	       identical) type of the template-argument.  The
	       template-parameter is bound directly to the
	       template-argument, which must be an lvalue.  */
2691 2692
	    if ((TYPE_MAIN_VARIANT (expr_type)
		 != TYPE_MAIN_VARIANT (type_referred_to))
2693 2694
		|| !at_least_as_qualified_p (type_referred_to,
					     expr_type)
2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707
		|| !real_lvalue_p (expr))
	      return error_mark_node;
	    else
	      return expr;
	  }
      }
      break;

    case RECORD_TYPE:
      {
	tree fns;
	tree fn;

2708 2709 2710 2711 2712 2713 2714
	if (!TYPE_PTRMEMFUNC_P (type))
	  /* This handles templates like
	       template<class T, T t> void f();
	     when T is substituted with any class.  The second template
	     parameter becomes invalid and the template candidate is
	     rejected.  */
	  return error_mark_node;
2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728

	/* For a non-type template-parameter of type pointer to member
	   function, no conversions apply.  If the template-argument
	   represents a set of overloaded member functions, the
	   matching member function is selected from the set
	   (_over.over_).  */

	if (!TYPE_PTRMEMFUNC_P (expr_type) && 
	    expr_type != unknown_type_node)
	  return error_mark_node;

	if (TREE_CODE (expr) == CONSTRUCTOR)
	  {
	    /* A ptr-to-member constant.  */
2729
	    if (!same_type_p (type, expr_type))
2730 2731 2732 2733 2734 2735 2736 2737 2738 2739
	      return error_mark_node;
	    else 
	      return expr;
	  }

	if (TREE_CODE (expr) != ADDR_EXPR)
	  return error_mark_node;

	fns = TREE_OPERAND (expr, 0);
	
2740
	fn = instantiate_type (TREE_TYPE (TREE_TYPE (type)), 
jason's avatar
Revert  
jason committed
2741
			       fns, 0);
2742 2743 2744 2745 2746 2747
	
	if (fn == error_mark_node)
	  return error_mark_node;

	expr = build_unary_op (ADDR_EXPR, fn, 0);
	
2748
	my_friendly_assert (same_type_p (type, TREE_TYPE (expr)),
2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
			    0);
	return expr;
      }
      break;

    default:
      /* All non-type parameters must have one of these types.  */
      my_friendly_abort (0);
      break;
    }

  return error_mark_node;
}

2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826
/* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for 
   template template parameters.  Both PARM_PARMS and ARG_PARMS are 
   vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL 
   or PARM_DECL.
   
   ARG_PARMS may contain more parameters than PARM_PARMS.  If this is 
   the case, then extra parameters must have default arguments.

   Consider the example:
     template <class T, class Allocator = allocator> class vector;
     template<template <class U> class TT> class C;

   C<vector> is a valid instantiation.  PARM_PARMS for the above code 
   contains a TYPE_DECL (for U),  ARG_PARMS contains two TYPE_DECLs (for 
   T and Allocator) and OUTER_ARGS contains the argument that is used to 
   substitute the TT parameter.  */

static int
coerce_template_template_parms (parm_parms, arg_parms, in_decl, outer_args)
     tree parm_parms, arg_parms, in_decl, outer_args;
{
  int nparms, nargs, i;
  tree parm, arg;

  my_friendly_assert (TREE_CODE (parm_parms) == TREE_VEC, 0);
  my_friendly_assert (TREE_CODE (arg_parms) == TREE_VEC, 0);

  nparms = TREE_VEC_LENGTH (parm_parms);
  nargs = TREE_VEC_LENGTH (arg_parms);

  /* The rule here is opposite of coerce_template_parms.  */
  if (nargs < nparms
      || (nargs > nparms
	  && TREE_PURPOSE (TREE_VEC_ELT (arg_parms, nparms)) == NULL_TREE))
    return 0;

  for (i = 0; i < nparms; ++i)
    {
      parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
      arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));

      if (arg == NULL_TREE || arg == error_mark_node
          || parm == NULL_TREE || parm == error_mark_node)
	return 0;

      if (TREE_CODE (arg) != TREE_CODE (parm))
        return 0;

      switch (TREE_CODE (parm))
	{
	case TYPE_DECL:
	  break;

	case TEMPLATE_DECL:
	  /* We encounter instantiations of templates like
	       template <template <template <class> class> class TT>
	       class C;  */
	  sorry ("nested template template parameter");
	  return 0;

	case PARM_DECL:
	  /* The tsubst call is used to handle cases such as
	       template <class T, template <T> class TT> class D;  
	     i.e. the parameter list of TT depends on earlier parameters.  */
2827 2828
	  if (!same_type_p (tsubst (TREE_TYPE (parm), outer_args, in_decl), 
			    TREE_TYPE (arg)))
2829 2830 2831 2832 2833 2834 2835 2836 2837 2838
	    return 0;
	  break;
	  
	default:
	  my_friendly_abort (0);
	}
    }
  return 1;
}

2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887
/* Convert the indicated template ARG as necessary to match the
   indicated template PARM.  Returns the converted ARG, or
   error_mark_node if the conversion was unsuccessful.  Error messages
   are issued if COMPLAIN is non-zero.  This conversion is for the Ith
   parameter in the parameter list.  ARGS is the full set of template
   arguments deduced so far.  */

static tree
convert_template_argument (parm, arg, args, complain, i, in_decl)
     tree parm;
     tree arg;
     tree args;
     int complain;
     int i;
     tree in_decl;
{
  tree val;
  tree inner_args;
  int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
  
  inner_args = innermost_args (args);

  if (TREE_CODE (arg) == TREE_LIST 
      && TREE_TYPE (arg) != NULL_TREE
      && TREE_CODE (TREE_TYPE (arg)) == OFFSET_TYPE)
    {  
      /* The template argument was the name of some
	 member function.  That's usually
	 illegal, but static members are OK.  In any
	 case, grab the underlying fields/functions
	 and issue an error later if required.  */
      arg = TREE_VALUE (arg);
      TREE_TYPE (arg) = unknown_type_node;
    }

  requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
  requires_type = (TREE_CODE (parm) == TYPE_DECL
		   || requires_tmpl_type);

  /* Check if it is a class template.  If REQUIRES_TMPL_TYPE is true,
     we also accept implicitly created TYPE_DECL as a valid argument.
     This is necessary to handle the case where we pass a template name
     to a template template parameter in a scope where we've derived from
     in instantiation of that template, so the template name refers to that
     instantiation.  We really ought to handle this better.  */
  is_tmpl_type 
    = ((TREE_CODE (arg) == TEMPLATE_DECL
	&& TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
       || (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
2888
	   && !TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (arg))
2889 2890 2891 2892 2893
       || (TREE_CODE (arg) == RECORD_TYPE
	   && CLASSTYPE_TEMPLATE_INFO (arg)
	   && TREE_CODE (TYPE_NAME (arg)) == TYPE_DECL
	   && DECL_ARTIFICIAL (TYPE_NAME (arg))
	   && requires_tmpl_type
2894
	   && is_base_of_enclosing_class (arg, current_class_type)));
2895 2896 2897 2898 2899 2900 2901 2902 2903 2904
  if (is_tmpl_type && TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
    arg = TYPE_STUB_DECL (arg);
  else if (is_tmpl_type && TREE_CODE (arg) == RECORD_TYPE)
    arg = CLASSTYPE_TI_TEMPLATE (arg);

  is_type = TREE_CODE_CLASS (TREE_CODE (arg)) == 't' || is_tmpl_type;

  if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
      && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
    {
jason's avatar
jason committed
2905 2906
      cp_pedwarn ("to refer to a type member of a template parameter,");
      cp_pedwarn ("  use `typename %E'", arg);
2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917
      
      arg = make_typename_type (TREE_OPERAND (arg, 0),
				TREE_OPERAND (arg, 1));
      is_type = 1;
    }
  if (is_type != requires_type)
    {
      if (in_decl)
	{
	  if (complain)
	    {
jason's avatar
jason committed
2918
	      cp_error ("type/value mismatch at argument %d in template parameter list for `%D'",
2919 2920
			i + 1, in_decl);
	      if (is_type)
jason's avatar
jason committed
2921
		cp_error ("  expected a constant of type `%T', got `%T'",
2922 2923 2924
			  TREE_TYPE (parm),
			  (is_tmpl_type ? DECL_NAME (arg) : arg));
	      else
jason's avatar
jason committed
2925
		cp_error ("  expected a type, got `%E'", arg);
2926 2927 2928 2929 2930 2931 2932 2933
	    }
	}
      return error_mark_node;
    }
  if (is_tmpl_type ^ requires_tmpl_type)
    {
      if (in_decl && complain)
	{
jason's avatar
jason committed
2934
	  cp_error ("type/value mismatch at argument %d in template parameter list for `%D'",
2935 2936
		    i + 1, in_decl);
	  if (is_tmpl_type)
jason's avatar
jason committed
2937
	    cp_error ("  expected a type, got `%T'", DECL_NAME (arg));
2938
	  else
jason's avatar
jason committed
2939
	    cp_error ("  expected a class template, got `%T'", arg);
2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965
	}
      return error_mark_node;
    }
      
  if (is_type)
    {
      if (requires_tmpl_type)
	{
	  tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
	  tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);

	  if (coerce_template_template_parms (parmparm, argparm, 
					      in_decl, inner_args))
	    {
	      val = arg;
		  
	      /* TEMPLATE_TEMPLATE_PARM node is preferred over 
		 TEMPLATE_DECL.  */
	      if (val != error_mark_node 
		  && DECL_TEMPLATE_TEMPLATE_PARM_P (val))
		val = TREE_TYPE (val);
	    }
	  else
	    {
	      if (in_decl && complain)
		{
jason's avatar
jason committed
2966
		  cp_error ("type/value mismatch at argument %d in template parameter list for `%D'",
2967
			    i + 1, in_decl);
jason's avatar
jason committed
2968
		  cp_error ("  expected a template of type `%D', got `%D'", parm, arg);
2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987
		}
		  
	      val = error_mark_node;
	    }
	}
      else
	{
	  val = groktypename (arg);
	  if (! processing_template_decl)
	    {
	      /* [basic.link]: A name with no linkage (notably, the
		 name of a class or enumeration declared in a local
		 scope) shall not be used to declare an entity with
		 linkage.  This implies that names with no linkage
		 cannot be used as template arguments.  */
	      tree t = no_linkage_check (val);
	      if (t)
		{
		  if (ANON_AGGRNAME_P (TYPE_IDENTIFIER (t)))
jason's avatar
jason committed
2988 2989
		    cp_pedwarn
		      ("template-argument `%T' uses anonymous type", val);
2990
		  else
jason's avatar
jason committed
2991 2992
		    cp_error
		      ("template-argument `%T' uses local type `%T'",
2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023
		       val, t);
		  return error_mark_node;
		}
	    }
	}
    }
  else
    {
      tree t = tsubst (TREE_TYPE (parm), args, in_decl);

      if (processing_template_decl)
	arg = maybe_fold_nontype_arg (arg);

      if (!uses_template_parms (arg) && !uses_template_parms (t))
	/* We used to call digest_init here.  However, digest_init
	   will report errors, which we don't want when complain
	   is zero.  More importantly, digest_init will try too
	   hard to convert things: for example, `0' should not be
	   converted to pointer type at this point according to
	   the standard.  Accepting this is not merely an
	   extension, since deciding whether or not these
	   conversions can occur is part of determining which
	   function template to call, or whether a given epxlicit
	   argument specification is legal.  */
	val = convert_nontype_argument (t, arg);
      else
	val = arg;

      if (val == NULL_TREE)
	val = error_mark_node;
      else if (val == error_mark_node && complain)
jason's avatar
jason committed
3024
	cp_error ("could not convert template argument `%E' to `%T'", 
3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036
		  arg, t);
    }

  return val;
}

/* Convert all template arguments to their appropriate types, and
   return a vector containing the innermost resulting template
   arguments.  If any error occurs, return error_mark_node, and, if
   COMPLAIN is non-zero, issue an error message.  Some error messages
   are issued even if COMPLAIN is zero; for instance, if a template
   argument is composed from a local class.
3037 3038 3039 3040

   If REQUIRE_ALL_ARGUMENTS is non-zero, all arguments must be
   provided in ARGLIST, or else trailing parameters must have default
   values.  If REQUIRE_ALL_ARGUMENTS is zero, we will attempt argument
3041 3042 3043 3044
   deduction for any unspecified trailing arguments.  

   The resulting TREE_VEC is allocated on a temporary obstack, and
   must be explicitly copied if it will be permanent.  */
3045
   
mrs's avatar
mrs committed
3046
static tree
3047
coerce_template_parms (parms, args, in_decl,
3048
		       complain,
3049
		       require_all_arguments)
3050
     tree parms, args;
mrs's avatar
mrs committed
3051
     tree in_decl;
3052 3053
     int complain;
     int require_all_arguments;
mrs's avatar
mrs committed
3054
{
mrs's avatar
mrs committed
3055
  int nparms, nargs, i, lost = 0;
3056
  tree inner_args;
3057 3058
  tree new_args;
  tree new_inner_args;
mrs's avatar
mrs committed
3059

3060
  inner_args = innermost_args (args);
3061
  nargs = NUM_TMPL_ARGS (inner_args);
mrs's avatar
mrs committed
3062 3063 3064 3065
  nparms = TREE_VEC_LENGTH (parms);

  if (nargs > nparms
      || (nargs < nparms
3066
	  && require_all_arguments
mrs's avatar
mrs committed
3067
	  && TREE_PURPOSE (TREE_VEC_ELT (parms, nargs)) == NULL_TREE))
mrs's avatar
mrs committed
3068
    {
3069 3070
      if (complain) 
	{
jason's avatar
jason committed
3071
	  cp_error ("wrong number of template arguments (%d, should be %d)",
3072
		    nargs, nparms);
3073 3074
	  
	  if (in_decl)
jason's avatar
jason committed
3075
	    cp_error_at ("provided for `%D'", in_decl);
3076 3077
	}

mrs's avatar
mrs committed
3078 3079 3080
      return error_mark_node;
    }

3081
  new_inner_args = make_temp_vec (nparms);
3082 3083
  new_args = add_outermost_template_args (args, new_inner_args);
  for (i = 0; i < nparms; i++)
mrs's avatar
mrs committed
3084
    {
3085 3086
      tree arg;
      tree parm;
3087

3088 3089
      /* Get the Ith template parameter.  */
      parm = TREE_VEC_ELT (parms, i);
3090

3091 3092
      /* Calculate the Ith argument.  */
      if (inner_args && TREE_CODE (inner_args) == TREE_LIST)
mrs's avatar
mrs committed
3093
	{
3094 3095
	  arg = TREE_VALUE (inner_args);
	  inner_args = TREE_CHAIN (inner_args);
mrs's avatar
mrs committed
3096
	}
3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110
      else if (i < nargs)
	arg = TREE_VEC_ELT (inner_args, i);
      /* If no template argument was supplied, look for a default
	 value.  */
      else if (TREE_PURPOSE (parm) == NULL_TREE)
	{
	  /* There was no default value.  */
	  my_friendly_assert (!require_all_arguments, 0);
	  break;
	}
      else if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL)
	arg = tsubst (TREE_PURPOSE (parm), new_args, in_decl);
      else
	arg = tsubst_expr (TREE_PURPOSE (parm), new_args, in_decl);
3111

3112
      /* Now, convert the Ith argument, as necessary.  */
3113 3114 3115 3116 3117 3118
      if (arg == NULL_TREE)
	/* We're out of arguments.  */
	{
	  my_friendly_assert (!require_all_arguments, 0);
	  break;
	}
3119
      else if (arg == error_mark_node)
3120
	{
jason's avatar
jason committed
3121
	  cp_error ("template argument %d is invalid", i + 1);
3122
	  arg = error_mark_node;
mrs's avatar
mrs committed
3123
	}
3124 3125 3126 3127 3128 3129
      else 
	arg = convert_template_argument (TREE_VALUE (parm), 
					 arg, new_args, complain, i,
					 in_decl); 
      
      if (arg == error_mark_node)
mrs's avatar
mrs committed
3130
	lost++;
3131
      TREE_VEC_ELT (new_inner_args, i) = arg;
mrs's avatar
mrs committed
3132
    }
3133

mrs's avatar
mrs committed
3134 3135
  if (lost)
    return error_mark_node;
3136 3137

  return new_inner_args;
mrs's avatar
mrs committed
3138 3139
}

3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153
/* Returns 1 if template args OT and NT are equivalent.  */

int
template_args_equal (ot, nt)
     tree ot, nt;
{
  if (nt == ot)
    return 1;
  if (TREE_CODE (nt) != TREE_CODE (ot))
    return 0;
  if (TREE_CODE (nt) == TREE_VEC)
    /* For member templates */
    return comp_template_args (ot, nt);
  else if (TREE_CODE_CLASS (TREE_CODE (ot)) == 't')
3154
    return same_type_p (ot, nt);
3155 3156 3157 3158 3159
  else
    return (cp_tree_equal (ot, nt) > 0);
}

/* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
jason's avatar
jason committed
3160 3161
   of template arguments.  Returns 0 otherwise.  */

3162
int
mrs's avatar
mrs committed
3163 3164 3165 3166 3167
comp_template_args (oldargs, newargs)
     tree oldargs, newargs;
{
  int i;

3168 3169 3170
  if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
    return 0;

mrs's avatar
mrs committed
3171 3172 3173 3174 3175
  for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
    {
      tree nt = TREE_VEC_ELT (newargs, i);
      tree ot = TREE_VEC_ELT (oldargs, i);

3176
      if (! template_args_equal (ot, nt))
3177
	return 0;
mrs's avatar
mrs committed
3178 3179 3180 3181
    }
  return 1;
}

mrs's avatar
mrs committed
3182 3183
/* Given class template name and parameter list, produce a user-friendly name
   for the instantiation.  */
mrs's avatar
mrs committed
3184

mrs's avatar
mrs committed
3185
static char *
3186
mangle_class_name_for_template (name, parms, arglist)
mrs's avatar
mrs committed
3187 3188 3189 3190 3191 3192 3193 3194
     char *name;
     tree parms, arglist;
{
  static struct obstack scratch_obstack;
  static char *scratch_firstobj;
  int i, nparms;

  if (!scratch_firstobj)
mrs's avatar
mrs committed
3195
    gcc_obstack_init (&scratch_obstack);
mrs's avatar
mrs committed
3196 3197
  else
    obstack_free (&scratch_obstack, scratch_firstobj);
mrs's avatar
mrs committed
3198
  scratch_firstobj = obstack_alloc (&scratch_obstack, 1);
mrs's avatar
mrs committed
3199 3200 3201 3202 3203 3204 3205

#define ccat(c)	obstack_1grow (&scratch_obstack, (c));
#define cat(s)	obstack_grow (&scratch_obstack, (s), strlen (s))

  cat (name);
  ccat ('<');
  nparms = TREE_VEC_LENGTH (parms);
3206
  arglist = innermost_args (arglist);
mrs's avatar
mrs committed
3207 3208 3209
  my_friendly_assert (nparms == TREE_VEC_LENGTH (arglist), 268);
  for (i = 0; i < nparms; i++)
    {
mrs's avatar
mrs committed
3210 3211
      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
      tree arg = TREE_VEC_ELT (arglist, i);
mrs's avatar
mrs committed
3212 3213 3214 3215

      if (i)
	ccat (',');

mrs's avatar
mrs committed
3216
      if (TREE_CODE (parm) == TYPE_DECL)
mrs's avatar
mrs committed
3217
	{
3218
	  cat (type_as_string_real (arg, 0, 1));
mrs's avatar
mrs committed
3219 3220
	  continue;
	}
3221 3222 3223
      else if (TREE_CODE (parm) == TEMPLATE_DECL)
	{
	  if (TREE_CODE (arg) == TEMPLATE_DECL)
jason's avatar
jason committed
3224 3225 3226
	    {
	      /* Already substituted with real template.  Just output 
		 the template name here */
3227 3228
              tree context = DECL_CONTEXT (arg);
	      if (context)
jason's avatar
jason committed
3229
		{
3230
                  my_friendly_assert (TREE_CODE (context) == NAMESPACE_DECL, 980422);
jason's avatar
jason committed
3231 3232 3233 3234 3235
		  cat(decl_as_string (DECL_CONTEXT (arg), 0));
		  cat("::");
		}
	      cat (IDENTIFIER_POINTER (DECL_NAME (arg)));
	    }
3236 3237
	  else
	    /* Output the parameter declaration */
3238
	    cat (type_as_string_real (arg, 0, 1));
3239 3240
	  continue;
	}
mrs's avatar
mrs committed
3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270
      else
	my_friendly_assert (TREE_CODE (parm) == PARM_DECL, 269);

      if (TREE_CODE (arg) == TREE_LIST)
	{
	  /* New list cell was built because old chain link was in
	     use.  */
	  my_friendly_assert (TREE_PURPOSE (arg) == NULL_TREE, 270);
	  arg = TREE_VALUE (arg);
	}
      /* No need to check arglist against parmlist here; we did that
	 in coerce_template_parms, called from lookup_template_class.  */
      cat (expr_as_string (arg, 0));
    }
  {
    char *bufp = obstack_next_free (&scratch_obstack);
    int offset = 0;
    while (bufp[offset - 1] == ' ')
      offset--;
    obstack_blank_fast (&scratch_obstack, offset);

    /* B<C<char> >, not B<C<char>> */
    if (bufp[offset - 1] == '>')
      ccat (' ');
  }
  ccat ('>');
  ccat ('\0');
  return (char *) obstack_base (&scratch_obstack);
}

mrs's avatar
mrs committed
3271
static tree
mrs's avatar
mrs committed
3272 3273 3274 3275
classtype_mangled_name (t)
     tree t;
{
  if (CLASSTYPE_TEMPLATE_INFO (t)
3276 3277
      /* Specializations have already had their names set up in
	 lookup_template_class.  */
3278 3279 3280 3281
      && !CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
    {
      tree tmpl = most_general_template (CLASSTYPE_TI_TEMPLATE (t));

3282 3283
      /* For non-primary templates, the template parameters are
	 implicit from their surrounding context.  */
3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294
      if (PRIMARY_TEMPLATE_P (tmpl))
	{
	  tree name = DECL_NAME (tmpl);
	  char *mangled_name = mangle_class_name_for_template
	    (IDENTIFIER_POINTER (name), 
	     DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
	     CLASSTYPE_TI_ARGS (t));
	  tree id = get_identifier (mangled_name);
	  IDENTIFIER_TEMPLATE (id) = name;
	  return id;
	}
mrs's avatar
mrs committed
3295
    }
3296 3297

  return TYPE_IDENTIFIER (t);
mrs's avatar
mrs committed
3298 3299 3300 3301 3302 3303
}

static void
add_pending_template (d)
     tree d;
{
mrs's avatar
mrs committed
3304 3305 3306 3307 3308 3309 3310
  tree ti;

  if (TREE_CODE_CLASS (TREE_CODE (d)) == 't')
    ti = CLASSTYPE_TEMPLATE_INFO (d);
  else
    ti = DECL_TEMPLATE_INFO (d);

mrs's avatar
mrs committed
3311
  if (TI_PENDING_TEMPLATE_FLAG (ti))
mrs's avatar
mrs committed
3312 3313 3314
    return;

  *template_tail = perm_tree_cons
jason's avatar
jason committed
3315
    (build_srcloc_here (), d, NULL_TREE);
mrs's avatar
mrs committed
3316
  template_tail = &TREE_CHAIN (*template_tail);
mrs's avatar
mrs committed
3317
  TI_PENDING_TEMPLATE_FLAG (ti) = 1;
mrs's avatar
mrs committed
3318 3319
}

3320 3321 3322 3323 3324 3325 3326 3327 3328

/* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS (which
   may be either a _DECL or an overloaded function or an
   IDENTIFIER_NODE), and ARGLIST.  */

tree
lookup_template_function (fns, arglist)
     tree fns, arglist;
{
jason's avatar
jason committed
3329
  tree type;
3330

3331 3332
  if (fns == NULL_TREE)
    {
jason's avatar
jason committed
3333
      cp_error ("non-template used as template");
3334 3335 3336
      return error_mark_node;
    }

jason's avatar
jason committed
3337 3338 3339 3340
  type = TREE_TYPE (fns);
  if (TREE_CODE (fns) == OVERLOAD || !type)
    type = unknown_type_node;

3341 3342 3343 3344
  if (processing_template_decl)
    return build_min (TEMPLATE_ID_EXPR, type, fns, arglist);  
  else
    return build (TEMPLATE_ID_EXPR, type, fns, arglist);
3345 3346
}

3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363
/* Within the scope of a template class S<T>, the name S gets bound
   (in build_self_reference) to a TYPE_DECL for the class, not a
   TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
   or one of its enclosing classes, and that type is a template,
   return the associated TEMPLATE_DECL.  Otherwise, the original
   DECL is returned.  */

tree
maybe_get_template_decl_from_type_decl (decl)
     tree decl;
{
  return (decl != NULL_TREE
	  && TREE_CODE (decl) == TYPE_DECL 
	  && DECL_ARTIFICIAL (decl)
	  && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))) 
    ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
}
3364

mrs's avatar
mrs committed
3365 3366 3367 3368
/* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
   parameters, find the desired type.

   D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
3369 3370 3371 3372 3373
   (Actually ARGLIST may be either a TREE_LIST or a TREE_VEC.  It will
   be a TREE_LIST if called directly from the parser, and a TREE_VEC
   otherwise.)  Since ARGLIST is build on the decl_obstack, we must
   copy it here to keep it from being reclaimed when the decl storage
   is reclaimed.
mrs's avatar
mrs committed
3374 3375

   IN_DECL, if non-NULL, is the template declaration we are trying to
3376 3377
   instantiate.  

3378 3379 3380
   If ENTERING_SCOPE is non-zero, we are about to enter the scope of
   the class we are looking up.

3381 3382 3383
   If the template class is really a local class in a template
   function, then the FUNCTION_CONTEXT is the function in which it is
   being instantiated.  */
mrs's avatar
mrs committed
3384

mrs's avatar
mrs committed
3385
tree
3386
lookup_template_class (d1, arglist, in_decl, context, entering_scope)
mrs's avatar
mrs committed
3387 3388
     tree d1, arglist;
     tree in_decl;
3389
     tree context;
3390
     int entering_scope;
mrs's avatar
mrs committed
3391
{
3392
  tree template = NULL_TREE, parmlist;
3393
  tree t;
mrs's avatar
mrs committed
3394 3395 3396

  if (TREE_CODE (d1) == IDENTIFIER_NODE)
    {
3397 3398 3399 3400 3401
      if (IDENTIFIER_LOCAL_VALUE (d1) 
	  && DECL_TEMPLATE_TEMPLATE_PARM_P (IDENTIFIER_LOCAL_VALUE (d1)))
	template = IDENTIFIER_LOCAL_VALUE (d1);
      else
	{
jason's avatar
jason committed
3402 3403
	  if (context)
	    push_decl_namespace (context);
3404 3405 3406 3407
	  if (current_class_type != NULL_TREE)
	    template = 
	      maybe_get_template_decl_from_type_decl
	      (IDENTIFIER_CLASS_VALUE (d1));
3408
	  if (template == NULL_TREE)
jason's avatar
jason committed
3409 3410 3411
	    template = lookup_name_nonclass (d1);
	  if (context)
	    pop_decl_namespace ();
3412
	}
3413 3414
      if (template)
	context = DECL_CONTEXT (template);
mrs's avatar
mrs committed
3415
    }
mrs's avatar
mrs committed
3416 3417
  else if (TREE_CODE (d1) == TYPE_DECL && IS_AGGR_TYPE (TREE_TYPE (d1)))
    {
3418 3419
      if (CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (d1)) == NULL_TREE)
	return error_mark_node;
mrs's avatar
mrs committed
3420 3421 3422
      template = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (d1));
      d1 = DECL_NAME (template);
    }
3423 3424 3425
  else if (TREE_CODE (d1) == ENUMERAL_TYPE 
	   || (TREE_CODE_CLASS (TREE_CODE (d1)) == 't' 
	       && IS_AGGR_TYPE (d1)))
mrs's avatar
mrs committed
3426
    {
3427
      template = TYPE_TI_TEMPLATE (d1);
mrs's avatar
mrs committed
3428 3429
      d1 = DECL_NAME (template);
    }
3430 3431 3432 3433 3434 3435 3436
  else if (TREE_CODE (d1) == TEMPLATE_DECL
	   && TREE_CODE (DECL_RESULT (d1)) == TYPE_DECL)
    {
      template = d1;
      d1 = DECL_NAME (template);
      context = DECL_CONTEXT (template);
    }
mrs's avatar
mrs committed
3437 3438
  else
    my_friendly_abort (272);
mrs's avatar
mrs committed
3439 3440 3441 3442 3443 3444 3445

  /* With something like `template <class T> class X class X { ... };'
     we could end up with D1 having nothing but an IDENTIFIER_LOCAL_VALUE.
     We don't want to do that, but we have to deal with the situation, so
     let's give them some syntax errors to chew on instead of a crash.  */
  if (! template)
    return error_mark_node;
jason's avatar
jason committed
3446

3447 3448
  if (context == NULL_TREE)
    context = global_namespace;
jason's avatar
jason committed
3449

mrs's avatar
mrs committed
3450 3451
  if (TREE_CODE (template) != TEMPLATE_DECL)
    {
jason's avatar
jason committed
3452
      cp_error ("non-template type `%T' used as a template", d1);
mrs's avatar
mrs committed
3453
      if (in_decl)
jason's avatar
jason committed
3454
	cp_error_at ("for template declaration `%D'", in_decl);
mrs's avatar
mrs committed
3455 3456 3457
      return error_mark_node;
    }

3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468
  if (DECL_TEMPLATE_TEMPLATE_PARM_P (template))
    {
      /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
         template arguments */

      tree parm = copy_template_template_parm (TREE_TYPE (template));
      tree template2 = TYPE_STUB_DECL (parm);
      tree arglist2;

      parmlist = DECL_INNERMOST_TEMPLATE_PARMS (template);

3469
      arglist2 = coerce_template_parms (parmlist, arglist, template, 1, 1);
3470 3471 3472 3473
      if (arglist2 == error_mark_node)
	return error_mark_node;

      arglist2 = copy_to_permanent (arglist2);
3474
      TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (parm)
3475 3476 3477 3478
	= perm_tree_cons (template2, arglist2, NULL_TREE);
      TYPE_SIZE (parm) = 0;
      return parm;
    }
3479
  else 
mrs's avatar
mrs committed
3480
    {
3481 3482 3483 3484 3485
      tree template_type = TREE_TYPE (template);
      tree type_decl;
      tree found = NULL_TREE;
      int arg_depth;
      int parm_depth;
3486
      int is_partial_instantiation;
3487

3488 3489 3490 3491 3492
      template = most_general_template (template);
      parmlist = DECL_TEMPLATE_PARMS (template);
      parm_depth = TMPL_PARMS_DEPTH (parmlist);
      arg_depth = TMPL_ARGS_DEPTH (arglist);

3493 3494 3495 3496
      /* We build up the coerced arguments and such on the
	 momentary_obstack.  */
      push_momentary ();

3497 3498
      if (arg_depth == 1 && parm_depth > 1)
	{
3499
	  /* We've been given an incomplete set of template arguments.
3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511
	     For example, given:

	       template <class T> struct S1 {
	         template <class U> struct S2 {};
		 template <class U> struct S2<U*> {};
	        };
	     
	     we will be called with an ARGLIST of `U*', but the
	     TEMPLATE will be `template <class T> template
	     <class U> struct S1<T>::S2'.  We must fill in the missing
	     arguments.  */
	  my_friendly_assert (context != NULL_TREE, 0);
3512 3513
	  while (!IS_AGGR_TYPE_CODE (TREE_CODE (context))
		 && context != global_namespace)
3514
	    context = DECL_REAL_CONTEXT (context);
3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529

	  if (context == global_namespace)
	    /* This is bad.  We cannot get enough arguments, even from
	       the surrounding context, to resolve this class.  One
	       case where this might happen is (illegal) code like:

	           template <class U> 
		   template <class T>
		   struct S { 
		     A(const A<T>& a) {}
		   };  
	    
	       We should catch this error sooner (at the opening curly
	       for `S', but it is better to be safe than sorry here.  */
	    {
jason's avatar
jason committed
3530
	      cp_error ("invalid use of `%D'", template);
3531 3532 3533
	      return error_mark_node;
	    }

3534
	  arglist = add_to_template_args (TYPE_TI_ARGS (context),
3535 3536 3537
					  arglist);
	  arg_depth = TMPL_ARGS_DEPTH (arglist);
	}
mrs's avatar
mrs committed
3538

3539 3540 3541 3542 3543 3544
      my_friendly_assert (parm_depth == arg_depth, 0);
      
      /* Calculate the BOUND_ARGS.  These will be the args that are
	 actually tsubst'd into the definition to create the
	 instantiation.  */
      if (parm_depth > 1)
3545 3546 3547
	{
	  /* We have multiple levels of arguments to coerce, at once.  */
	  int i;
3548
	  int saved_depth = TMPL_ARGS_DEPTH (arglist);
3549

3550
	  tree bound_args = make_temp_vec (parm_depth);
3551
	  
3552
	  for (i = saved_depth,
3553
		 t = DECL_TEMPLATE_PARMS (template); 
3554
	       i > 0 && t != NULL_TREE;
3555
	       --i, t = TREE_CHAIN (t))
3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570
	    {
	      tree a = coerce_template_parms (TREE_VALUE (t),
					      arglist, template, 1, 1);
	      SET_TMPL_ARGS_LEVEL (bound_args, i, a);

	      /* We temporarily reduce the length of the ARGLIST so
		 that coerce_template_parms will see only the arguments
		 corresponding to the template parameters it is
		 examining.  */
	      TREE_VEC_LENGTH (arglist)--;
	    }

	  /* Restore the ARGLIST to its full size.  */
	  TREE_VEC_LENGTH (arglist) = saved_depth;

3571
	  arglist = bound_args;
3572 3573
	}
      else
3574 3575 3576 3577 3578 3579 3580
	arglist
	  = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
				   innermost_args (arglist),
				   template, 1, 1);

      if (arglist == error_mark_node)
	/* We were unable to bind the arguments.  */
mrs's avatar
mrs committed
3581 3582
	return error_mark_node;

3583 3584 3585 3586 3587 3588 3589 3590
      /* In the scope of a template class, explicit references to the
	 template class refer to the type of the template, not any
	 instantiation of it.  For example, in:
	 
	   template <class T> class C { void f(C<T>); }

	 the `C<T>' is just the same as `C'.  Outside of the
	 class, however, such a reference is an instantiation.  */
3591
      if (comp_template_args (TYPE_TI_ARGS (template_type),
3592 3593 3594 3595 3596
			      arglist))
	{
	  found = template_type;
	  
	  if (!entering_scope && PRIMARY_TEMPLATE_P (template))
mrs's avatar
mrs committed
3597
	    {
3598 3599 3600 3601 3602 3603 3604 3605 3606 3607
	      tree ctx;
	      
	      /* Note that we use DECL_CONTEXT, rather than
		 CP_DECL_CONTEXT, so that the termination test is
		 always just `ctx'.  We're not interested in namepace
		 scopes.  */
	      for (ctx = current_class_type; 
		   ctx; 
		   ctx = (TREE_CODE_CLASS (TREE_CODE (ctx)) == 't') 
		     ? TYPE_CONTEXT (ctx) : DECL_CONTEXT (ctx))
3608
		if (same_type_p (ctx, template_type))
3609 3610 3611 3612 3613 3614 3615
		  break;
	      
	      if (!ctx)
		/* We're not in the scope of the class, so the
		   TEMPLATE_TYPE is not the type we want after
		   all.  */
		found = NULL_TREE;
mrs's avatar
mrs committed
3616 3617
	    }
	}
3618 3619
      
      if (!found)
3620
	{
3621 3622 3623 3624
	  for (found = DECL_TEMPLATE_INSTANTIATIONS (template);
	       found; found = TREE_CHAIN (found))
	    if (comp_template_args (TREE_PURPOSE (found), arglist))
	      break;
3625

3626 3627
	  if (found)
	    found = TREE_VALUE (found);
mrs's avatar
mrs committed
3628
	}
3629 3630
      
      if (found)
mrs's avatar
mrs committed
3631
	{
3632
	  pop_momentary ();
3633
	  return found;
mrs's avatar
mrs committed
3634
	}
mrs's avatar
mrs committed
3635

3636 3637 3638 3639 3640
      /* Since we didn't find the type, we'll have to create it.
	 Since we'll be saving this type on the
	 DECL_TEMPLATE_INSTANTIATIONS list, it must be permanent.  */
      push_obstacks (&permanent_obstack, &permanent_obstack);
      
3641
      /* This type is a "partial instantiation" if any of the template
3642 3643 3644
	 arguments still inolve template parameters.  Note that we set
	 IS_PARTIAL_INSTANTIATION for partial specializations as
	 well.  */
3645 3646
      is_partial_instantiation = uses_template_parms (arglist);

3647
      /* Create the type.  */
3648 3649
      if (TREE_CODE (template_type) == ENUMERAL_TYPE)
	{
3650
	  if (!is_partial_instantiation)
3651
	    t = start_enum (TYPE_IDENTIFIER (template_type));
3652
	  else
3653
	    /* We don't want to call start_enum for this type, since
3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665
	       the values for the enumeration constants may involve
	       template parameters.  And, no one should be interested
	       in the enumeration constants for such a type.  */
	    t = make_node (ENUMERAL_TYPE);
	}
      else
	{
	  t = make_lang_type (TREE_CODE (template_type));
	  CLASSTYPE_DECLARED_CLASS (t) 
	    = CLASSTYPE_DECLARED_CLASS (template_type);
	  CLASSTYPE_GOT_SEMICOLON (t) = 1;
	  SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
bothner's avatar
(  
bothner committed
3666
	  TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
3667 3668
	}

3669
      /* If we called start_enum above, this information will already
3670 3671 3672 3673
	 be set up.  */
      if (!TYPE_NAME (t))
	{
	  TYPE_CONTEXT (t) = FROB_CONTEXT (context);
3674
	  
3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686
	  /* Create a stub TYPE_DECL for it.  */
	  type_decl = build_decl (TYPE_DECL, DECL_NAME (template), t);
	  SET_DECL_ARTIFICIAL (type_decl);
	  DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
	  DECL_SOURCE_FILE (type_decl) 
	    = DECL_SOURCE_FILE (TYPE_STUB_DECL (template_type));
	  DECL_SOURCE_LINE (type_decl) 
	    = DECL_SOURCE_LINE (TYPE_STUB_DECL (template_type));
	  TYPE_STUB_DECL (t) = TYPE_NAME (t) = type_decl;
	}
      else
	type_decl = TYPE_NAME (t);
3687

3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737
      /* Set up the template information.  We have to figure out which
	 template is the immediate parent if this is a full
	 instantiation.  */
      if (parm_depth == 1 || is_partial_instantiation
	  || !PRIMARY_TEMPLATE_P (template))
	/* This case is easy; there are no member templates involved.  */
	found = template;
      else
	{
	  /* This is a full instantiation of a member template.  There
	     should be some partial instantiation of which this is an
	     instance.  */

	  for (found = DECL_TEMPLATE_INSTANTIATIONS (template);
	       found; found = TREE_CHAIN (found))
	    {
	      int success;
	      tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));

	      /* We only want partial instantiations, here, not
		 specializations or full instantiations.  */
	      if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
		  || !uses_template_parms (TREE_VALUE (found)))
		continue;

	      /* Temporarily reduce by one the number of levels in the
		 ARGLIST and in FOUND so as to avoid comparing the
		 last set of arguments.  */
	      TREE_VEC_LENGTH (arglist)--;
	      TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;

	      /* See if the arguments match.  If they do, then TMPL is
		 the partial instantiation we want.  */
	      success = comp_template_args (TREE_PURPOSE (found), arglist);

	      /* Restore the argument vectors to their full size.  */
	      TREE_VEC_LENGTH (arglist)++;
	      TREE_VEC_LENGTH (TREE_PURPOSE (found))++;

	      if (success)
		{
		  found = tmpl;
		  break;
		}
	    }

	  if (!found)
	    my_friendly_abort (0);
	}

mrs's avatar
mrs committed
3738
      arglist = copy_to_permanent (arglist);
3739
      SET_TYPE_TEMPLATE_INFO (t,
3740
			      tree_cons (found, arglist, NULL_TREE));  
3741 3742 3743 3744 3745 3746
      DECL_TEMPLATE_INSTANTIATIONS (template) 
	= tree_cons (arglist, t, 
		     DECL_TEMPLATE_INSTANTIATIONS (template));

      if (TREE_CODE (t) == ENUMERAL_TYPE 
	  && !is_partial_instantiation)
3747 3748 3749 3750 3751 3752 3753 3754
	/* Now that the type has been registered on the instantiations
	   list, we set up the enumerators.  Because the enumeration
	   constants may involve the enumeration type itself, we make
	   sure to register the type first, and then create the
	   constants.  That way, doing tsubst_expr for the enumeration
	   constants won't result in recursive calls here; we'll find
	   the instantiation and exit above.  */
	tsubst_enum (template_type, t, arglist);
3755 3756 3757

      /* We're done with the permanent obstack, now.  */
      pop_obstacks ();
3758 3759 3760
      /* We're also done with the momentary allocation we started
	 above.  */
      pop_momentary ();
mrs's avatar
mrs committed
3761

3762 3763
      /* Reset the name of the type, now that CLASSTYPE_TEMPLATE_INFO
	 is set up.  */
3764 3765
      if (TREE_CODE (t) != ENUMERAL_TYPE)
	DECL_NAME (type_decl) = classtype_mangled_name (t);
3766
      DECL_ASSEMBLER_NAME (type_decl) = DECL_NAME (type_decl);
3767
      if (!is_partial_instantiation)
3768 3769 3770
	{
	  DECL_ASSEMBLER_NAME (type_decl)
	    = get_identifier (build_overload_name (t, 1, 1));
3771 3772 3773 3774 3775

	  /* For backwards compatibility; code that uses
	     -fexternal-templates expects looking up a template to
	     instantiate it.  I think DDD still relies on this.
	     (jason 8/20/1998) */
3776 3777
	  if (TREE_CODE (t) != ENUMERAL_TYPE
	      && flag_external_templates
3778 3779 3780 3781 3782
	      && CLASSTYPE_INTERFACE_KNOWN (TREE_TYPE (template))
	      && ! CLASSTYPE_INTERFACE_ONLY (TREE_TYPE (template)))
	    add_pending_template (t);
	}
      else
3783 3784 3785
	/* If the type makes use of template parameters, the
	   code that generates debugging information will crash.  */
	DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
mrs's avatar
mrs committed
3786

3787 3788
      return t;
    }
mrs's avatar
mrs committed
3789 3790
}

3791 3792 3793 3794 3795 3796 3797 3798
/* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM, or
   TEMPLATE_PARM_INDEX in T, call FN with the parameter and the DATA.
   If FN returns non-zero, the iteration is terminated, and
   for_each_template_parm returns 1.  Otherwise, the iteration
   continues.  If FN never returns a non-zero value, the value
   returned by for_each_template_parm is 0.  If FN is NULL, it is
   considered to be the function which always returns 1.  */

mrs's avatar
mrs committed
3799
int
3800
for_each_template_parm (t, fn, data)
mrs's avatar
mrs committed
3801
     tree t;
3802 3803
     tree_fn_t fn;
     void* data;
mrs's avatar
mrs committed
3804 3805 3806
{
  if (!t)
    return 0;
3807 3808 3809 3810 3811

  if (TREE_CODE_CLASS (TREE_CODE (t)) == 't'
      && for_each_template_parm (TYPE_CONTEXT (t), fn, data))
    return 1;

mrs's avatar
mrs committed
3812 3813 3814 3815 3816 3817 3818
  switch (TREE_CODE (t))
    {
    case INDIRECT_REF:
    case COMPONENT_REF:
      /* We assume that the object must be instantiated in order to build
	 the COMPONENT_REF, so we test only whether the type of the
	 COMPONENT_REF uses template parms.  */
3819
      return for_each_template_parm (TREE_TYPE (t), fn, data);
mrs's avatar
mrs committed
3820 3821 3822 3823

    case IDENTIFIER_NODE:
      if (!IDENTIFIER_TEMPLATE (t))
	return 0;
mrs's avatar
mrs committed
3824
      my_friendly_abort (42);
mrs's avatar
mrs committed
3825 3826 3827 3828 3829 3830

      /* aggregates of tree nodes */
    case TREE_VEC:
      {
	int i = TREE_VEC_LENGTH (t);
	while (i--)
3831
	  if (for_each_template_parm (TREE_VEC_ELT (t, i), fn, data))
mrs's avatar
mrs committed
3832 3833 3834 3835
	    return 1;
	return 0;
      }
    case TREE_LIST:
3836 3837
      if (for_each_template_parm (TREE_PURPOSE (t), fn, data)
	  || for_each_template_parm (TREE_VALUE (t), fn, data))
mrs's avatar
mrs committed
3838
	return 1;
3839
      return for_each_template_parm (TREE_CHAIN (t), fn, data);
mrs's avatar
mrs committed
3840

jason's avatar
jason committed
3841 3842 3843 3844 3845
    case OVERLOAD:
      if (for_each_template_parm (OVL_FUNCTION (t), fn, data))
	return 1;
      return for_each_template_parm (OVL_CHAIN (t), fn, data);

mrs's avatar
mrs committed
3846 3847 3848
      /* constructed type nodes */
    case POINTER_TYPE:
    case REFERENCE_TYPE:
3849
      return for_each_template_parm (TREE_TYPE (t), fn, data);
3850

mrs's avatar
mrs committed
3851
    case RECORD_TYPE:
mrs's avatar
mrs committed
3852
      if (TYPE_PTRMEMFUNC_FLAG (t))
3853 3854
	return for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE (t),
				       fn, data);
3855 3856
      /* Fall through.  */

mrs's avatar
mrs committed
3857
    case UNION_TYPE:
3858 3859
    case ENUMERAL_TYPE:
      if (! TYPE_TEMPLATE_INFO (t))
mrs's avatar
mrs committed
3860
	return 0;
3861
      return for_each_template_parm (TREE_VALUE
3862
				     (TYPE_TEMPLATE_INFO (t)),
3863
				     fn, data);
3864 3865
    case METHOD_TYPE:
      if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data))
mrs's avatar
mrs committed
3866
	return 1;
3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884
      /* Fall through.  */

    case FUNCTION_TYPE:
      /* Check the parameter types.  Since default arguments are not
	 instantiated until they are needed, the TYPE_ARG_TYPES may
	 contain expressions that involve template parameters.  But,
	 no-one should be looking at them yet.  And, once they're
	 instantiated, they don't contain template parameters, so
	 there's no point in looking at them then, either.  */
      {
	tree parm;

	for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
	  if (for_each_template_parm (TREE_VALUE (parm), fn, data))
	    return 1;
      }

      /* Check the return type, too.  */
3885
      return for_each_template_parm (TREE_TYPE (t), fn, data);
3886

mrs's avatar
mrs committed
3887
    case ARRAY_TYPE:
3888
      if (for_each_template_parm (TYPE_DOMAIN (t), fn, data))
mrs's avatar
mrs committed
3889
	return 1;
3890
      return for_each_template_parm (TREE_TYPE (t), fn, data);
mrs's avatar
mrs committed
3891
    case OFFSET_TYPE:
3892
      if (for_each_template_parm (TYPE_OFFSET_BASETYPE (t), fn, data))
mrs's avatar
mrs committed
3893
	return 1;
3894
      return for_each_template_parm (TREE_TYPE (t), fn, data);
mrs's avatar
mrs committed
3895 3896 3897

      /* decl nodes */
    case TYPE_DECL:
3898
      return for_each_template_parm (TREE_TYPE (t), fn, data);
mrs's avatar
mrs committed
3899

3900 3901 3902
    case TEMPLATE_DECL:
      /* A template template parameter is encountered */
      if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
3903 3904
	return for_each_template_parm (TREE_TYPE (t), fn, data);
      /* Already substituted template template parameter */
3905 3906
      return 0;
      
3907
    case CONST_DECL:
3908
      if (for_each_template_parm (DECL_INITIAL (t), fn, data))
3909 3910 3911
	return 1;
      goto check_type_and_context;

mrs's avatar
mrs committed
3912
    case FUNCTION_DECL:
mrs's avatar
mrs committed
3913 3914 3915
    case VAR_DECL:
      /* ??? What about FIELD_DECLs?  */
      if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
3916
	  && for_each_template_parm (DECL_TI_ARGS (t), fn, data))
mrs's avatar
mrs committed
3917 3918 3919
	return 1;
      /* fall through */
    case PARM_DECL:
3920
    check_type_and_context:
3921
      if (for_each_template_parm (TREE_TYPE (t), fn, data))
mrs's avatar
mrs committed
3922
	return 1;
3923 3924
      if (DECL_CONTEXT (t) 
	  && for_each_template_parm (DECL_CONTEXT (t), fn, data))
mrs's avatar
mrs committed
3925 3926 3927 3928
	return 1;
      return 0;

    case CALL_EXPR:
3929
      return for_each_template_parm (TREE_TYPE (t), fn, data);
mrs's avatar
mrs committed
3930
    case ADDR_EXPR:
3931
      return for_each_template_parm (TREE_OPERAND (t, 0), fn, data);
mrs's avatar
mrs committed
3932 3933

      /* template parm nodes */
3934
    case TEMPLATE_TEMPLATE_PARM:
3935
      /* Record template parameters such as `T' inside `TT<T>'.  */
3936 3937
      if (TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t)
	  && for_each_template_parm (TYPE_TI_ARGS (t), fn, data))
3938 3939
	return 1;
    case TEMPLATE_TYPE_PARM:
jason's avatar
jason committed
3940
    case TEMPLATE_PARM_INDEX:
3941 3942 3943 3944
      if (fn)
	return (*fn)(t, data);
      else
	return 1;
mrs's avatar
mrs committed
3945 3946 3947

      /* simple type nodes */
    case INTEGER_TYPE:
3948
      if (for_each_template_parm (TYPE_MIN_VALUE (t), fn, data))
mrs's avatar
mrs committed
3949
	return 1;
3950
      return for_each_template_parm (TYPE_MAX_VALUE (t), fn, data);
mrs's avatar
mrs committed
3951 3952

    case REAL_TYPE:
mrs's avatar
mrs committed
3953
    case COMPLEX_TYPE:
mrs's avatar
mrs committed
3954
    case VOID_TYPE:
mrs's avatar
mrs committed
3955
    case BOOLEAN_TYPE:
jason's avatar
jason committed
3956
    case NAMESPACE_DECL:
mrs's avatar
mrs committed
3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970
      return 0;

      /* constants */
    case INTEGER_CST:
    case REAL_CST:
    case STRING_CST:
      return 0;

    case ERROR_MARK:
      /* Non-error_mark_node ERROR_MARKs are bad things.  */
      my_friendly_assert (t == error_mark_node, 274);
      /* NOTREACHED */
      return 0;

mrs's avatar
mrs committed
3971
    case LOOKUP_EXPR:
mrs's avatar
mrs committed
3972
    case TYPENAME_TYPE:
mrs's avatar
mrs committed
3973 3974
      return 1;

3975 3976 3977
    case PTRMEM_CST:
      return for_each_template_parm (TREE_TYPE (t), fn, data);

mrs's avatar
mrs committed
3978
    case SCOPE_REF:
3979
      return for_each_template_parm (TREE_OPERAND (t, 0), fn, data);
mrs's avatar
mrs committed
3980

mrs's avatar
mrs committed
3981 3982
    case CONSTRUCTOR:
      if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t)))
3983 3984 3985
	return for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
				       (TREE_TYPE (t)), fn, data);
      return for_each_template_parm (TREE_OPERAND (t, 1), fn, data);
mrs's avatar
mrs committed
3986

brendan's avatar
brendan committed
3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997
    case MODOP_EXPR:
    case CAST_EXPR:
    case REINTERPRET_CAST_EXPR:
    case CONST_CAST_EXPR:
    case STATIC_CAST_EXPR:
    case DYNAMIC_CAST_EXPR:
    case ARROW_EXPR:
    case DOTSTAR_EXPR:
    case TYPEID_EXPR:
      return 1;

3998 3999
    case SIZEOF_EXPR:
    case ALIGNOF_EXPR:
4000
      return for_each_template_parm (TREE_OPERAND (t, 0), fn, data);
4001

mrs's avatar
mrs committed
4002 4003 4004 4005 4006
    default:
      switch (TREE_CODE_CLASS (TREE_CODE (t)))
	{
	case '1':
	case '2':
mrs's avatar
mrs committed
4007
	case 'e':
mrs's avatar
mrs committed
4008 4009 4010
	case '<':
	  {
	    int i;
4011
	    for (i = first_rtl_op (TREE_CODE (t)); --i >= 0;)
4012
	      if (for_each_template_parm (TREE_OPERAND (t, i), fn, data))
mrs's avatar
mrs committed
4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026
		return 1;
	    return 0;
	  }
	default:
	  break;
	}
      sorry ("testing %s for template parms",
	     tree_code_name [(int) TREE_CODE (t)]);
      my_friendly_abort (82);
      /* NOTREACHED */
      return 0;
    }
}

4027 4028 4029 4030 4031 4032 4033
int
uses_template_parms (t)
     tree t;
{
  return for_each_template_parm (t, 0, 0);
}

4034 4035 4036
static struct tinst_level *current_tinst_level;
static struct tinst_level *free_tinst_level;
static int tinst_depth;
mrs's avatar
mrs committed
4037
extern int max_tinst_depth;
mrs's avatar
mrs committed
4038
#ifdef GATHER_STATISTICS
4039
int depth_reached;
mrs's avatar
mrs committed
4040
#endif
4041 4042
int tinst_level_tick;
int last_template_error_tick;
mrs's avatar
mrs committed
4043

4044
/* Print out all the template instantiations that we are currently
4045 4046
   working on.  If ERR, we are being called from cp_thing, so do
   the right thing for an error message.  */
4047

4048 4049 4050
static void
print_template_context (err)
     int err;
4051 4052 4053 4054 4055
{
  struct tinst_level *p = current_tinst_level;
  int line = lineno;
  char *file = input_filename;

4056
  if (err && p)
4057
    {
4058 4059 4060 4061 4062 4063
      if (current_function_decl != p->decl
	  && current_function_decl != NULL_TREE)
	/* We can get here during the processing of some synthesized
	   method.  Then, p->decl will be the function that's causing
	   the synthesis.  */
	;
4064 4065
      else
	{
4066 4067 4068 4069 4070 4071
	  if (current_function_decl == p->decl)
	    /* Avoid redundancy with the the "In function" line.  */;
	  else 
	    fprintf (stderr, "%s: In instantiation of `%s':\n",
		     file, decl_as_string (p->decl, 0));
	  
4072 4073
	  line = p->line;
	  file = p->file;
4074 4075 4076 4077
	  p = p->next;
	}
    }

4078 4079
  for (; p; p = p->next)
    {
4080 4081 4082 4083
      fprintf (stderr, "%s:%d:   instantiated from `%s'\n", file, line,
	       decl_as_string (p->decl, 0));
      line = p->line;
      file = p->file;
4084
    }
4085
  fprintf (stderr, "%s:%d:   instantiated from here\n", file, line);
4086 4087
}

4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100
/* Called from cp_thing to print the template context for an error.  */

void
maybe_print_template_context ()
{
  if (last_template_error_tick == tinst_level_tick
      || current_tinst_level == 0)
    return;

  last_template_error_tick = tinst_level_tick;
  print_template_context (1);
}

mrs's avatar
mrs committed
4101
static int
mrs's avatar
mrs committed
4102 4103
push_tinst_level (d)
     tree d;
mrs's avatar
mrs committed
4104 4105 4106
{
  struct tinst_level *new;

mrs's avatar
mrs committed
4107 4108
  if (tinst_depth >= max_tinst_depth)
    {
4109 4110 4111 4112 4113 4114
      /* If the instantiation in question still has unbound template parms,
	 we don't really care if we can't instantiate it, so just return.
         This happens with base instantiation for implicit `typename'.  */
      if (uses_template_parms (d))
	return 0;

jason's avatar
jason committed
4115
      last_template_error_tick = tinst_level_tick;
jason's avatar
jason committed
4116
      error ("template instantiation depth exceeds maximum of %d",
mrs's avatar
mrs committed
4117
	     max_tinst_depth);
jason's avatar
jason committed
4118 4119
      error (" (use -ftemplate-depth-NN to increase the maximum)");
      cp_error ("  instantiating `%D'", d);
mrs's avatar
mrs committed
4120

4121
      print_template_context (0);
mrs's avatar
mrs committed
4122

mrs's avatar
mrs committed
4123 4124 4125
      return 0;
    }

mrs's avatar
mrs committed
4126 4127 4128 4129 4130 4131 4132 4133
  if (free_tinst_level)
    {
      new = free_tinst_level;
      free_tinst_level = new->next;
    }
  else
    new = (struct tinst_level *) xmalloc (sizeof (struct tinst_level));

mrs's avatar
mrs committed
4134 4135 4136
  new->decl = d;
  new->line = lineno;
  new->file = input_filename;
mrs's avatar
mrs committed
4137 4138
  new->next = current_tinst_level;
  current_tinst_level = new;
mrs's avatar
mrs committed
4139

mrs's avatar
mrs committed
4140
  ++tinst_depth;
mrs's avatar
mrs committed
4141 4142 4143 4144 4145
#ifdef GATHER_STATISTICS
  if (tinst_depth > depth_reached)
    depth_reached = tinst_depth;
#endif

4146
  ++tinst_level_tick;
mrs's avatar
mrs committed
4147
  return 1;
mrs's avatar
mrs committed
4148 4149 4150 4151 4152 4153 4154
}

void
pop_tinst_level ()
{
  struct tinst_level *old = current_tinst_level;

4155 4156 4157 4158
  /* Restore the filename and line number stashed away when we started
     this instantiation.  */
  lineno = old->line;
  input_filename = old->file;
4159
  extract_interface_info ();
4160
  
mrs's avatar
mrs committed
4161 4162 4163
  current_tinst_level = old->next;
  old->next = free_tinst_level;
  free_tinst_level = old;
mrs's avatar
mrs committed
4164
  --tinst_depth;
4165
  ++tinst_level_tick;
mrs's avatar
mrs committed
4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178
}

struct tinst_level *
tinst_for_decl ()
{
  struct tinst_level *p = current_tinst_level;

  if (p)
    for (; p->next ; p = p->next )
      ;
  return p;
}

jason's avatar
jason committed
4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189
/* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
   vector of template arguments, as for tsubst.

   Returns an appropriate tsbust'd friend declaration.  */

static tree
tsubst_friend_function (decl, args)
     tree decl;
     tree args;
{
  tree new_friend;
4190 4191 4192 4193 4194 4195
  int line = lineno;
  char *file = input_filename;

  lineno = DECL_SOURCE_LINE (decl);
  input_filename = DECL_SOURCE_FILE (decl);

jason's avatar
jason committed
4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213
  if (TREE_CODE (decl) == FUNCTION_DECL 
      && DECL_TEMPLATE_INSTANTIATION (decl)
      && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
    /* This was a friend declared with an explicit template
       argument list, e.g.:
       
       friend void f<>(T);
       
       to indicate that f was a template instantiation, not a new
       function declaration.  Now, we have to figure out what
       instantiation of what template.  */
    {
      tree template_id;
      tree new_args;
      tree tmpl;

      template_id
	= lookup_template_function (tsubst_expr (DECL_TI_TEMPLATE (decl),
4214
						 args, NULL_TREE),
jason's avatar
jason committed
4215
				    tsubst (DECL_TI_ARGS (decl),
4216
					    args, NULL_TREE));
4217 4218
      /* FIXME: The decl we create via the next tsubst could be
	 created on a temporary obstack.  */
4219
      new_friend = tsubst (decl, args, NULL_TREE);
4220 4221 4222 4223
      tmpl = determine_specialization (template_id, new_friend,
				       &new_args, 
				       /*need_member_template=*/0, 
				       /*complain=*/1);
4224 4225
      new_friend = instantiate_template (tmpl, new_args);
      goto done;
jason's avatar
jason committed
4226
    }
4227 4228

  new_friend = tsubst (decl, args, NULL_TREE);
jason's avatar
jason committed
4229
	
4230
  /* The NEW_FRIEND will look like an instantiation, to the
jason's avatar
jason committed
4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242
     compiler, but is not an instantiation from the point of view of
     the language.  For example, we might have had:
     
     template <class T> struct S {
       template <class U> friend void f(T, U);
     };
     
     Then, in S<int>, template <class U> void f(int, U) is not an
     instantiation of anything.  */
  DECL_USE_TEMPLATE (new_friend) = 0;
  if (TREE_CODE (decl) == TEMPLATE_DECL)
    DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258

  /* The mangled name for the NEW_FRIEND is incorrect.  The call to
     tsubst will have resulted in a call to
     set_mangled_name_for_template_decl.  But, the function is not a
     template instantiation and should not be mangled like one.
     Therefore, we remangle the function name.  We don't have to do
     this if the NEW_FRIEND is a template since
     set_mangled_name_for_template_decl doesn't do anything if the
     function declaration still uses template arguments.  */
  if (TREE_CODE (new_friend) != TEMPLATE_DECL)
    {
      set_mangled_name_for_decl (new_friend);
      DECL_RTL (new_friend) = 0;
      make_decl_rtl (new_friend, NULL_PTR, 1);
    }
      
4259
  if (DECL_NAMESPACE_SCOPE_P (new_friend))
jason's avatar
jason committed
4260
    {
4261
      tree old_decl;
4262 4263 4264 4265 4266 4267 4268 4269
      tree new_friend_template_info;
      tree new_friend_result_template_info;
      int  new_friend_is_defn;

      /* We must save some information from NEW_FRIEND before calling
	 duplicate decls since that function will free NEW_FRIEND if
	 possible.  */
      new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
jason's avatar
jason committed
4270
      if (TREE_CODE (new_friend) == TEMPLATE_DECL)
4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284
	{
	  /* This declaration is a `primary' template.  */
	  DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
	  
	  new_friend_is_defn 
	    = DECL_INITIAL (DECL_RESULT (new_friend)) != NULL_TREE;
	  new_friend_result_template_info
	    = DECL_TEMPLATE_INFO (DECL_RESULT (new_friend));
	}
      else
	{
	  new_friend_is_defn = DECL_INITIAL (new_friend) != NULL_TREE;
	  new_friend_result_template_info = NULL_TREE;
	}
4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323

      old_decl = pushdecl_namespace_level (new_friend);

      if (old_decl != new_friend)
	{
	  /* This new friend declaration matched an existing
	     declaration.  For example, given:

	       template <class T> void f(T);
	       template <class U> class C { 
		 template <class T> friend void f(T) {} 
	       };

	     the friend declaration actually provides the definition
	     of `f', once C has been instantiated for some type.  So,
	     old_decl will be the out-of-class template declaration,
	     while new_friend is the in-class definition.

	     But, if `f' was called before this point, the
	     instantiation of `f' will have DECL_TI_ARGS corresponding
	     to `T' but not to `U', references to which might appear
	     in the definition of `f'.  Previously, the most general
	     template for an instantiation of `f' was the out-of-class
	     version; now it is the in-class version.  Therefore, we
	     run through all specialization of `f', adding to their
	     DECL_TI_ARGS appropriately.  In particular, they need a
	     new set of outer arguments, corresponding to the
	     arguments for this class instantiation.  

	     The same situation can arise with something like this:

	       friend void f(int);
	       template <class T> class C { 
	         friend void f(T) {}
               };

	     when `C<int>' is instantiated.  Now, `f(int)' is defined
	     in the class.  */

4324 4325 4326 4327 4328
	  if (!new_friend_is_defn)
	    /* On the other hand, if the in-class declaration does
	       *not* provide a definition, then we don't want to alter
	       existing definitions.  We can just leave everything
	       alone.  */
4329
	    ;
4330
	  else
4331
	    {
4332 4333 4334 4335 4336 4337 4338 4339 4340
	      /* Overwrite whatever template info was there before, if
		 any, with the new template information pertaining to
		 the declaration.  */
	      DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;

	      if (TREE_CODE (old_decl) != TEMPLATE_DECL)
		/* duplicate_decls will take care of this case.  */
		;
	      else 
4341
		{
4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353
		  tree t;
		  tree new_friend_args;

		  DECL_TEMPLATE_INFO (DECL_RESULT (old_decl)) 
		    = new_friend_result_template_info;
		    
		  new_friend_args = TI_ARGS (new_friend_template_info);
		  for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl); 
		       t != NULL_TREE;
		       t = TREE_CHAIN (t))
		    {
		      tree spec = TREE_VALUE (t);
4354
		  
4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372
		      DECL_TI_ARGS (spec) 
			= add_outermost_template_args (new_friend_args,
						       DECL_TI_ARGS (spec));
		      DECL_TI_ARGS (spec)
			= copy_to_permanent (DECL_TI_ARGS (spec));
		    }

		  /* Now, since specializations are always supposed to
		     hang off of the most general template, we must move
		     them.  */
		  t = most_general_template (old_decl);
		  if (t != old_decl)
		    {
		      DECL_TEMPLATE_SPECIALIZATIONS (t)
			= chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
				   DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
		      DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
		    }
4373 4374 4375 4376 4377 4378 4379
		}
	    }

	  /* The information from NEW_FRIEND has been merged into OLD_DECL
	     by duplicate_decls.  */
	  new_friend = old_decl;
	}
jason's avatar
jason committed
4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391
    }
  else if (TYPE_SIZE (DECL_CONTEXT (new_friend)))
    {
      /* Check to see that the declaration is really present, and,
	 possibly obtain an improved declaration.  */
      tree fn = check_classfn (DECL_CONTEXT (new_friend),
			       new_friend);
      
      if (fn)
	new_friend = fn;
    }

4392 4393 4394
 done:
  lineno = line;
  input_filename = file;
jason's avatar
jason committed
4395 4396 4397
  return new_friend;
}

4398 4399
/* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
   template arguments, as for tsubst.
4400 4401 4402 4403

   Returns an appropriate tsbust'd friend type.  */

static tree
4404 4405
tsubst_friend_class (friend_tmpl, args)
     tree friend_tmpl;
4406 4407
     tree args;
{
4408
  tree friend_type;
4409
  tree tmpl = lookup_name (DECL_NAME (friend_tmpl), 1); 
4410 4411 4412 4413 4414 4415

  tmpl = maybe_get_template_decl_from_type_decl (tmpl);

  if (tmpl != NULL_TREE && DECL_CLASS_TEMPLATE_P (tmpl))
    {
      /* The friend template has already been declared.  Just
4416 4417 4418 4419 4420 4421 4422 4423 4424
	 check to see that the declarations match, and install any new
	 default parameters.  We must tsubst the default parameters,
	 of course.  We only need the innermost template parameters
	 because that is all that redeclare_class_template will look
	 at.  */
      tree parms 
	= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
				 args);
      redeclare_class_template (TREE_TYPE (tmpl), parms);
4425 4426 4427 4428 4429 4430 4431
      friend_type = TREE_TYPE (tmpl);
    }
  else
    {
      /* The friend template has not already been declared.  In this
	 case, the instantiation of the template class will cause the
	 injection of this template into the global scope.  */
4432
      tmpl = tsubst (friend_tmpl, args, NULL_TREE);
4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447

      /* The new TMPL is not an instantiation of anything, so we
 	 forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
	 the new type because that is supposed to be the corresponding
	 template decl, i.e., TMPL.  */
      DECL_USE_TEMPLATE (tmpl) = 0;
      DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
      CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;

      /* Inject this template into the global scope.  */
      friend_type = TREE_TYPE (pushdecl_top_level (tmpl));
    }

  return friend_type;
}
jason's avatar
jason committed
4448

mrs's avatar
mrs committed
4449
tree
mrs's avatar
mrs committed
4450 4451
instantiate_class_template (type)
     tree type;
mrs's avatar
mrs committed
4452
{
4453
  tree template, args, pattern, t;
4454
  tree typedecl;
mrs's avatar
mrs committed
4455

mrs's avatar
mrs committed
4456
  if (type == error_mark_node)
mrs's avatar
mrs committed
4457 4458
    return error_mark_node;

mrs's avatar
mrs committed
4459 4460 4461
  if (TYPE_BEING_DEFINED (type) || TYPE_SIZE (type))
    return type;

4462 4463 4464 4465 4466 4467
  /* We want to allocate temporary vectors of template arguments and
     template argument expressions on the momentary obstack, not on
     the expression obstack.  Otherwise, all the space allocated in
     argument coercion and such is simply lost.  */
  push_momentary ();

4468 4469
  template = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
  args = CLASSTYPE_TI_ARGS (type);
mrs's avatar
mrs committed
4470
  my_friendly_assert (TREE_CODE (template) == TEMPLATE_DECL, 279);
4471
  t = most_specialized_class (template, args);
mrs's avatar
mrs committed
4472 4473 4474 4475

  if (t == error_mark_node)
    {
      char *str = "candidates are:";
jason's avatar
jason committed
4476
      cp_error ("ambiguous class template instantiation for `%#T'", type);
mrs's avatar
mrs committed
4477 4478
      for (t = DECL_TEMPLATE_SPECIALIZATIONS (template); t; t = TREE_CHAIN (t))
	{
4479
	  if (get_class_bindings (TREE_VALUE (t), TREE_PURPOSE (t),
4480
				  args))
mrs's avatar
mrs committed
4481
	    {
jason's avatar
jason committed
4482
	      cp_error_at ("%s %+#T", str, TREE_TYPE (t));
mrs's avatar
mrs committed
4483 4484 4485 4486
	      str = "               ";
	    }
	}
      TYPE_BEING_DEFINED (type) = 1;
4487 4488
      type = error_mark_node;
      goto end;
mrs's avatar
mrs committed
4489 4490 4491 4492 4493
    }
  else if (t)
    pattern = TREE_TYPE (t);
  else
    pattern = TREE_TYPE (template);
mrs's avatar
mrs committed
4494 4495

  if (TYPE_SIZE (pattern) == NULL_TREE)
4496
    goto end;
mrs's avatar
mrs committed
4497

mrs's avatar
mrs committed
4498
  if (t)
4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524
    {
      /* This TYPE is actually a instantiation of of a partial
	 specialization.  We replace the innermost set of ARGS with
	 the arguments appropriate for substitution.  For example,
	 given:

	   template <class T> struct S {};
	   template <class T> struct S<T*> {};
	 
	 and supposing that we are instantiating S<int*>, ARGS will
	 present be {int*} but we need {int}.  */
      tree inner_args 
	= get_class_bindings (TREE_VALUE (t), TREE_PURPOSE (t),
			      args);

      /* If there were multiple levels in ARGS, replacing the
	 innermost level would alter CLASSTYPE_TI_ARGS, which we don't
	 want, so we make a copy first.  */
      if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
	{
	  args = copy_node (args);
	  SET_TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args), inner_args);
	}
      else
	args = inner_args;
    }
4525

4526
  if (pedantic && uses_template_parms (args))
4527 4528 4529 4530 4531 4532 4533 4534
    {
      /* If there are still template parameters amongst the args, then
	 we can't instantiate the type; there's no telling whether or not one
	 of the template parameters might eventually be instantiated to some
	 value that results in a specialization being used.  We do the
	 type as complete so that, for example, declaring one of its
	 members to be a friend will not be rejected.  */
      TYPE_SIZE (type) = integer_zero_node;
4535
      goto end;
4536
    }
4537

mrs's avatar
mrs committed
4538 4539 4540
  TYPE_BEING_DEFINED (type) = 1;

  if (! push_tinst_level (type))
4541
    goto end;
mrs's avatar
mrs committed
4542

mrs's avatar
mrs committed
4543 4544 4545
  maybe_push_to_top_level (uses_template_parms (type));
  pushclass (type, 0);

4546 4547 4548 4549
  /* We must copy the arguments to the permanent obstack since
     during the tsubst'ing below they may wind up in the
     DECL_TI_ARGS of some instantiated member template.  */
  args = copy_to_permanent (args);
4550

mrs's avatar
mrs committed
4551 4552 4553 4554 4555 4556 4557
  if (flag_external_templates)
    {
      if (flag_alt_external_templates)
	{
	  CLASSTYPE_INTERFACE_ONLY (type) = interface_only;
	  SET_CLASSTYPE_INTERFACE_UNKNOWN_X (type, interface_unknown);
	  CLASSTYPE_VTABLE_NEEDS_WRITING (type)
4558 4559
	    = (! CLASSTYPE_INTERFACE_ONLY (type)
	       && CLASSTYPE_INTERFACE_KNOWN (type));
mrs's avatar
mrs committed
4560 4561 4562 4563 4564 4565 4566
	}
      else
	{
	  CLASSTYPE_INTERFACE_ONLY (type) = CLASSTYPE_INTERFACE_ONLY (pattern);
	  SET_CLASSTYPE_INTERFACE_UNKNOWN_X
	    (type, CLASSTYPE_INTERFACE_UNKNOWN (pattern));
	  CLASSTYPE_VTABLE_NEEDS_WRITING (type)
4567 4568
	    = (! CLASSTYPE_INTERFACE_ONLY (type)
	       && CLASSTYPE_INTERFACE_KNOWN (type));
mrs's avatar
mrs committed
4569 4570 4571
	}
    }
  else
mrs's avatar
mrs committed
4572
    {
mrs's avatar
mrs committed
4573 4574
      SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
      CLASSTYPE_VTABLE_NEEDS_WRITING (type) = 1;
mrs's avatar
mrs committed
4575 4576
    }

mrs's avatar
mrs committed
4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600
  TYPE_HAS_CONSTRUCTOR (type) = TYPE_HAS_CONSTRUCTOR (pattern);
  TYPE_HAS_DESTRUCTOR (type) = TYPE_HAS_DESTRUCTOR (pattern);
  TYPE_HAS_ASSIGNMENT (type) = TYPE_HAS_ASSIGNMENT (pattern);
  TYPE_OVERLOADS_CALL_EXPR (type) = TYPE_OVERLOADS_CALL_EXPR (pattern);
  TYPE_OVERLOADS_ARRAY_REF (type) = TYPE_OVERLOADS_ARRAY_REF (pattern);
  TYPE_OVERLOADS_ARROW (type) = TYPE_OVERLOADS_ARROW (pattern);
  TYPE_GETS_NEW (type) = TYPE_GETS_NEW (pattern);
  TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
  TYPE_VEC_DELETE_TAKES_SIZE (type) = TYPE_VEC_DELETE_TAKES_SIZE (pattern);
  TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
  TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
  TYPE_HAS_ABSTRACT_ASSIGN_REF (type) = TYPE_HAS_ABSTRACT_ASSIGN_REF (pattern);
  TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
  TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
  TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
  TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
  TYPE_USES_COMPLEX_INHERITANCE (type)
    = TYPE_USES_COMPLEX_INHERITANCE (pattern);
  TYPE_USES_MULTIPLE_INHERITANCE (type)
    = TYPE_USES_MULTIPLE_INHERITANCE (pattern);
  TYPE_USES_VIRTUAL_BASECLASSES (type)
    = TYPE_USES_VIRTUAL_BASECLASSES (pattern);
  TYPE_PACKED (type) = TYPE_PACKED (pattern);
  TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
bothner's avatar
d  
bothner committed
4601
  TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
mrs's avatar
mrs committed
4602

4603 4604 4605 4606 4607 4608 4609 4610 4611 4612
  /* If this is a partial instantiation, don't tsubst anything.  We will
     only use this type for implicit typename, so the actual contents don't
     matter.  All that matters is whether a particular name is a type.  */
  if (uses_template_parms (type))
    {
      TYPE_BINFO_BASETYPES (type) = TYPE_BINFO_BASETYPES (pattern);
      TYPE_FIELDS (type) = TYPE_FIELDS (pattern);
      TYPE_METHODS (type) = TYPE_METHODS (pattern);
      CLASSTYPE_TAGS (type) = CLASSTYPE_TAGS (pattern);
      TYPE_SIZE (type) = integer_zero_node;
4613
      goto done_with_instantiation;
4614 4615
    }

mrs's avatar
mrs committed
4616 4617 4618 4619 4620 4621 4622 4623 4624
  {
    tree binfo = TYPE_BINFO (type);
    tree pbases = TYPE_BINFO_BASETYPES (pattern);

    if (pbases)
      {
	tree bases;
	int i;
	int len = TREE_VEC_LENGTH (pbases);
mrs's avatar
mrs committed
4625
	bases = make_tree_vec (len);
mrs's avatar
mrs committed
4626 4627
	for (i = 0; i < len; ++i)
	  {
4628
	    tree elt, basetype;
mrs's avatar
mrs committed
4629 4630

	    TREE_VEC_ELT (bases, i) = elt
4631
	      = tsubst (TREE_VEC_ELT (pbases, i), args, NULL_TREE);
mrs's avatar
mrs committed
4632 4633
	    BINFO_INHERITANCE_CHAIN (elt) = binfo;

4634 4635 4636
	    basetype = TREE_TYPE (elt);

	    if (! IS_AGGR_TYPE (basetype))
jason's avatar
jason committed
4637 4638
	      cp_error
		("base type `%T' of `%T' fails to be a struct or class type",
4639 4640
		 basetype, type);
	    else if (TYPE_SIZE (complete_type (basetype)) == NULL_TREE)
jason's avatar
jason committed
4641
	      cp_error ("base class `%T' of `%T' has incomplete type",
4642 4643 4644 4645
			basetype, type);

	    /* These are set up in xref_basetypes for normal classes, so
	       we have to handle them here for template bases.  */
4646 4647 4648

	    unshare_base_binfos (elt);

4649 4650 4651 4652 4653 4654 4655
	    if (TYPE_USES_VIRTUAL_BASECLASSES (basetype))
	      {
		TYPE_USES_VIRTUAL_BASECLASSES (type) = 1;
		TYPE_USES_COMPLEX_INHERITANCE (type) = 1;
	      }
	    TYPE_GETS_NEW (type) |= TYPE_GETS_NEW (basetype);
	    TYPE_GETS_DELETE (type) |= TYPE_GETS_DELETE (basetype);
mrs's avatar
mrs committed
4656
	  }
mrs's avatar
mrs committed
4657 4658 4659
	/* Don't initialize this until the vector is filled out, or
	   lookups will crash.  */
	BINFO_BASETYPES (binfo) = bases;
mrs's avatar
mrs committed
4660 4661 4662 4663
      }
  }

  for (t = CLASSTYPE_TAGS (pattern); t; t = TREE_CHAIN (t))
mrs's avatar
mrs committed
4664
    {
mrs's avatar
mrs committed
4665
      tree tag = TREE_VALUE (t);
4666 4667
      tree name = TYPE_IDENTIFIER (tag);
      tree newtag;
mrs's avatar
mrs committed
4668

4669
      newtag = tsubst (tag, args, NULL_TREE);
4670
      if (TREE_CODE (newtag) != ENUMERAL_TYPE)
4671
	{
4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682
	  if (TYPE_LANG_SPECIFIC (tag) && CLASSTYPE_IS_TEMPLATE (tag))
	    /* Unfortunately, lookup_template_class sets
	       CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
	       instantiation (i.e., for the type of a member template
	       class nested within a template class.)  This behavior is
	       required for maybe_process_partial_specialization to work
	       correctly, but is not accurate in this case; the TAG is not
	       an instantiation of anything.  (The corresponding
	       TEMPLATE_DECL is an instantiation, but the TYPE is not.) */
	    CLASSTYPE_USE_TEMPLATE (newtag) = 0;

4683 4684 4685 4686 4687 4688 4689 4690 4691
	  /* Now, we call pushtag to put this NEWTAG into the scope of
	     TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
	     pushtag calling push_template_decl.  We don't have to do
	     this for enums because it will already have been done in
	     tsubst_enum.  */
	  if (name)
	    SET_IDENTIFIER_TYPE_VALUE (name, newtag);
	  pushtag (name, newtag, /*globalize=*/0);
	}
mrs's avatar
mrs committed
4692 4693
    }

mrs's avatar
mrs committed
4694 4695 4696 4697
  /* Don't replace enum constants here.  */
  for (t = TYPE_FIELDS (pattern); t; t = TREE_CHAIN (t))
    if (TREE_CODE (t) != CONST_DECL)
      {
4698 4699 4700 4701 4702 4703 4704 4705 4706
	tree r;

	/* The the file and line for this declaration, to assist in
	   error message reporting.  Since we called push_tinst_level
	   above, we don't need to restore these.  */
	lineno = DECL_SOURCE_LINE (t);
	input_filename = DECL_SOURCE_FILE (t);

	r = tsubst (t, args, NULL_TREE);
mrs's avatar
mrs committed
4707 4708
	if (TREE_CODE (r) == VAR_DECL)
	  {
4709 4710
	    pending_statics = perm_tree_cons (NULL_TREE, r, pending_statics);
	    /* Perhaps we should do more of grokfield here.  */
mrs's avatar
mrs committed
4711 4712 4713 4714
	    start_decl_1 (r);
	    DECL_IN_AGGR_P (r) = 1;
	    DECL_EXTERNAL (r) = 1;
	    cp_finish_decl (r, DECL_INITIAL (r), NULL_TREE, 0, 0);
4715 4716
	    if (DECL_DEFINED_IN_CLASS_P (r))
	      check_static_variable_definition (r, TREE_TYPE (r));
mrs's avatar
mrs committed
4717
	  }
4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728
	
	/* R will have a TREE_CHAIN if and only if it has already been
	   processed by finish_member_declaration.  This can happen
	   if, for example, it is a TYPE_DECL for a class-scoped
	   ENUMERAL_TYPE; such a thing will already have been added to
	   the field list by tsubst_enum above.  */
	if (!TREE_CHAIN (r))
	  {
	    set_current_access_from_decl (r);
	    finish_member_declaration (r);
	  }
mrs's avatar
mrs committed
4729
      }
mrs's avatar
mrs committed
4730

4731 4732 4733 4734 4735 4736 4737 4738
  /* Set up the list (TYPE_METHODS) and vector (CLASSTYPE_METHOD_VEC)
     for this instantiation.  */
  for (t = TYPE_METHODS (pattern); t; t = TREE_CHAIN (t))
    {
      tree r = tsubst (t, args, NULL_TREE);
      set_current_access_from_decl (r);
      finish_member_declaration (r);
    }
mrs's avatar
mrs committed
4739

4740 4741 4742 4743 4744
  /* Construct the DECL_FRIENDLIST for the new class type.  */
  typedecl = TYPE_MAIN_DECL (type);
  for (t = DECL_FRIENDLIST (TYPE_MAIN_DECL (pattern));
       t != NULL_TREE;
       t = TREE_CHAIN (t))
jason's avatar
jason committed
4745
    {
4746
      tree friends;
jason's avatar
jason committed
4747

4748 4749 4750
      DECL_FRIENDLIST (typedecl)
	= tree_cons (TREE_PURPOSE (t), NULL_TREE, 
		     DECL_FRIENDLIST (typedecl));
jason's avatar
jason committed
4751

4752 4753 4754 4755 4756
      for (friends = TREE_VALUE (t);
	   friends != NULL_TREE;
	   friends = TREE_CHAIN (friends))
	{
	  if (TREE_PURPOSE (friends) == error_mark_node)
jason's avatar
jason committed
4757
	    {
4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769
	      TREE_VALUE (DECL_FRIENDLIST (typedecl))
		= tree_cons (error_mark_node, 
			     tsubst_friend_function (TREE_VALUE (friends),
						     args),
			     TREE_VALUE (DECL_FRIENDLIST (typedecl)));
	    }
	  else
	    {
	      TREE_VALUE (DECL_FRIENDLIST (typedecl))
		= tree_cons (tsubst (TREE_PURPOSE (friends), args, NULL_TREE),
			     NULL_TREE,
			     TREE_VALUE (DECL_FRIENDLIST (typedecl)));
jason's avatar
jason committed
4770 4771 4772

	    }
	}
4773
    }
mrs's avatar
mrs committed
4774

4775 4776 4777 4778 4779
  for (t = CLASSTYPE_FRIEND_CLASSES (pattern);
       t != NULL_TREE;
       t = TREE_CHAIN (t))
    {
      tree friend_type = TREE_VALUE (t);
4780
      tree new_friend_type;
4781

4782 4783 4784 4785 4786
      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
	new_friend_type = tsubst_friend_class (friend_type, args);
      else if (uses_template_parms (friend_type))
	new_friend_type = tsubst (friend_type, args, NULL_TREE);
      else 
4787 4788
	/* The call to xref_tag_from_type does injection for friend
	   classes.  */
4789
	new_friend_type = 
4790 4791
	  xref_tag_from_type (friend_type, NULL_TREE, 1);

4792 4793 4794 4795 4796 4797 4798 4799 4800 4801

      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
	/* Trick make_friend_class into realizing that the friend
	   we're adding is a template, not an ordinary class.  It's
	   important that we use make_friend_class since it will
	   perform some error-checking and output cross-reference
	   information.  */
	++processing_template_decl;

      make_friend_class (type, new_friend_type);
mrs's avatar
mrs committed
4802

4803 4804
      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
	--processing_template_decl;
4805
    }
mrs's avatar
mrs committed
4806

4807 4808 4809 4810
  /* This does injection for friend functions. */
  if (!processing_template_decl)
    {
      t = tsubst (DECL_TEMPLATE_INJECT (template), args, NULL_TREE);
mrs's avatar
mrs committed
4811

4812 4813 4814
      for (; t; t = TREE_CHAIN (t))
	{
	  tree d = TREE_VALUE (t);
mrs's avatar
mrs committed
4815

4816 4817 4818 4819 4820 4821
	  if (TREE_CODE (d) == TYPE_DECL)
	    /* Already injected.  */;
	  else
	    pushdecl (d);
	}
    } 
mrs's avatar
mrs committed
4822

4823 4824 4825 4826 4827 4828
  for (t = TYPE_FIELDS (type); t; t = TREE_CHAIN (t))
    if (TREE_CODE (t) == FIELD_DECL)
      {
	TREE_TYPE (t) = complete_type (TREE_TYPE (t));
	require_complete_type (t);
      }
mrs's avatar
mrs committed
4829

4830 4831 4832 4833 4834 4835 4836 4837
  /* Set the file and line number information to whatever is given for
     the class itself.  This puts error messages involving generated
     implicit functions at a predictable point, and the same point
     that would be used for non-template classes.  */
  lineno = DECL_SOURCE_LINE (typedecl);
  input_filename = DECL_SOURCE_FILE (typedecl);

  unreverse_member_declarations (type);
4838 4839
  type = finish_struct_1 (type, 0);
  CLASSTYPE_GOT_SEMICOLON (type) = 1;
mrs's avatar
mrs committed
4840

4841 4842
  /* Clear this now so repo_template_used is happy.  */
  TYPE_BEING_DEFINED (type) = 0;
4843
  repo_template_used (type);
mrs's avatar
mrs committed
4844

4845
 done_with_instantiation:
mrs's avatar
mrs committed
4846 4847 4848 4849 4850 4851
  TYPE_BEING_DEFINED (type) = 0;
  popclass (0);

  pop_from_top_level ();
  pop_tinst_level ();

4852 4853 4854
 end:
  pop_momentary ();

mrs's avatar
mrs committed
4855
  return type;
mrs's avatar
mrs committed
4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873
}

static int
list_eq (t1, t2)
     tree t1, t2;
{
  if (t1 == NULL_TREE)
    return t2 == NULL_TREE;
  if (t2 == NULL_TREE)
    return 0;
  /* Don't care if one declares its arg const and the other doesn't -- the
     main variant of the arg type is all that matters.  */
  if (TYPE_MAIN_VARIANT (TREE_VALUE (t1))
      != TYPE_MAIN_VARIANT (TREE_VALUE (t2)))
    return 0;
  return list_eq (TREE_CHAIN (t1), TREE_CHAIN (t2));
}

4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899
/* If arg is a non-type template parameter that does not depend on template
   arguments, fold it like we weren't in the body of a template.  */

static tree
maybe_fold_nontype_arg (arg)
     tree arg;
{
  if (TREE_CODE_CLASS (TREE_CODE (arg)) != 't'
      && !uses_template_parms (arg))
    {
      /* Sometimes, one of the args was an expression involving a
	 template constant parameter, like N - 1.  Now that we've
	 tsubst'd, we might have something like 2 - 1.  This will
	 confuse lookup_template_class, so we do constant folding
	 here.  We have to unset processing_template_decl, to
	 fool build_expr_from_tree() into building an actual
	 tree.  */

      int saved_processing_template_decl = processing_template_decl; 
      processing_template_decl = 0;
      arg = fold (build_expr_from_tree (arg));
      processing_template_decl = saved_processing_template_decl; 
    }
  return arg;
}

4900
/* Return the TREE_VEC with the arguments for the innermost template header,
4901 4902
   where ARGS is either that or the VEC of VECs for all the
   arguments.  */
4903 4904

tree
4905
innermost_args (args)
4906 4907
     tree args;
{
4908
  return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
4909
}
jason's avatar
jason committed
4910

4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938
/* Substitute ARGS into the vector of template arguments T.  */

tree
tsubst_template_arg_vector (t, args)
     tree t;
     tree args;
{
  int len = TREE_VEC_LENGTH (t), need_new = 0, i;
  tree *elts = (tree *) alloca (len * sizeof (tree));
  
  bzero ((char *) elts, len * sizeof (tree));
  
  for (i = 0; i < len; i++)
    {
      if (TREE_VEC_ELT (t, i) != NULL_TREE
	  && TREE_CODE (TREE_VEC_ELT (t, i)) == TREE_VEC)
	elts[i] = tsubst_template_arg_vector (TREE_VEC_ELT (t, i), args);
      else
	elts[i] = maybe_fold_nontype_arg
	  (tsubst_expr (TREE_VEC_ELT (t, i), args, NULL_TREE));
      
      if (elts[i] != TREE_VEC_ELT (t, i))
	need_new = 1;
    }
  
  if (!need_new)
    return t;
  
4939
  t = make_temp_vec (len);
4940 4941 4942 4943 4944 4945
  for (i = 0; i < len; i++)
    TREE_VEC_ELT (t, i) = elts[i];
  
  return t;
}

4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991
/* Return the result of substituting ARGS into the template parameters
   given by PARMS.  If there are m levels of ARGS and m + n levels of
   PARMS, then the result will contain n levels of PARMS.  For
   example, if PARMS is `template <class T> template <class U>
   template <T*, U, class V>' and ARGS is {{int}, {double}} then the
   result will be `template <int*, double, class V>'.  */

tree
tsubst_template_parms (parms, args)
     tree parms;
     tree args;
{
  tree r;
  tree* new_parms = &r;

  for (new_parms = &r;
       TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
       new_parms = &(TREE_CHAIN (*new_parms)),
	 parms = TREE_CHAIN (parms))
    {
      tree new_vec = 
	make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
      int i;
      
      for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
	{
	  tree default_value =
	    TREE_PURPOSE (TREE_VEC_ELT (TREE_VALUE (parms), i));
	  tree parm_decl = 
	    TREE_VALUE (TREE_VEC_ELT (TREE_VALUE (parms), i));
	  
	  TREE_VEC_ELT (new_vec, i)
	    = build_tree_list (tsubst (default_value, args, NULL_TREE),
			       tsubst (parm_decl, args, NULL_TREE));
	  
	}
      
      *new_parms = 
	tree_cons (build_int_2 (0, (TMPL_PARMS_DEPTH (parms) 
				    - TMPL_ARGS_DEPTH (args))),
		   new_vec, NULL_TREE);
    }

  return r;
}

4992 4993 4994 4995 4996
/* Substitute the ARGS into the indicated aggregate (or enumeration)
   type T.  If T is not an aggregate or enumeration type, it is
   handled as if by tsubst.  IN_DECL is as for tsubst.  If
   ENTERING_SCOPE is non-zero, T is the context for a template which
   we are presently tsubst'ing.  Return the subsituted value.  */
4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014

tree
tsubst_aggr_type (t, args, in_decl, entering_scope)
     tree t;
     tree args;
     tree in_decl;
     int entering_scope;
{
  if (t == NULL_TREE)
    return NULL_TREE;

  switch (TREE_CODE (t))
    {
    case RECORD_TYPE:
      if (TYPE_PTRMEMFUNC_P (t))
	{
	  tree r = build_ptrmemfunc_type
	    (tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, in_decl));
5015
	  return cp_build_qualified_type (r, TYPE_QUALS (t));
5016 5017 5018
	}

      /* else fall through */
5019
    case ENUMERAL_TYPE:
5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043
    case UNION_TYPE:
      if (uses_template_parms (t))
	{
	  tree argvec;
	  tree context;
	  tree r;

	  /* First, determine the context for the type we are looking
	     up.  */
	  if (TYPE_CONTEXT (t) != NULL_TREE)
	    context = tsubst_aggr_type (TYPE_CONTEXT (t), args,
					in_decl, /*entering_scope=*/1);
	  else
	    context = NULL_TREE;

	  /* Then, figure out what arguments are appropriate for the
	     type we are trying to find.  For example, given:

	       template <class T> struct S;
	       template <class T, class U> void f(T, U) { S<U> su; }

	     and supposing that we are instantiating f<int, double>,
	     then our ARGS will be {int, double}, but, when looking up
	     S we only want {double}.  */
5044 5045
	  push_momentary ();
	  argvec = tsubst_template_arg_vector (TYPE_TI_ARGS (t), args);
5046 5047 5048

  	  r = lookup_template_class (t, argvec, in_decl, context,
				     entering_scope);
5049
	  pop_momentary ();
5050

5051
	  return cp_build_qualified_type (r, TYPE_QUALS (t));
5052 5053 5054 5055 5056 5057 5058 5059 5060 5061
	}
      else 
	/* This is not a template type, so there's nothing to do.  */
	return t;

    default:
      return tsubst (t, args, in_decl);
    }
}

5062 5063 5064 5065
/* Substitute the ARGS into the T, which is a _DECL.  TYPE is the
   (already computed) substitution of ARGS into TREE_TYPE (T), if
   appropriate.  Return the result of the substitution.  IN_DECL is as
   for tsubst.  */
5066

5067
tree
5068 5069 5070 5071
tsubst_decl (t, args, type, in_decl)
     tree t;
     tree args;
     tree type;
mrs's avatar
mrs committed
5072 5073
     tree in_decl;
{
5074 5075
  int saved_lineno;
  char* saved_filename;
ghazi's avatar
ghazi committed
5076
  tree r = NULL_TREE;
5077

5078 5079 5080 5081 5082
  /* Set the filename and linenumber to improve error-reporting.  */
  saved_lineno = lineno;
  saved_filename = input_filename;
  lineno = DECL_SOURCE_LINE (t);
  input_filename = DECL_SOURCE_FILE (t);
mrs's avatar
mrs committed
5083

mrs's avatar
mrs committed
5084 5085
  switch (TREE_CODE (t))
    {
5086 5087 5088 5089 5090
    case TEMPLATE_DECL:
      {
	/* We can get here when processing a member template function
	   of a template class.  */
	tree decl = DECL_TEMPLATE_RESULT (t);
5091
	tree spec;
5092
	int is_template_template_parm = DECL_TEMPLATE_TEMPLATE_PARM_P (t);
5093

5094 5095
	if (!is_template_template_parm)
	  {
5096 5097 5098 5099 5100 5101 5102
	    /* We might already have an instance of this template.
	       The ARGS are for the surrounding class type, so the
	       full args contain the tsubst'd args for the context,
	       plus the innermost args from the template decl.  */
	    tree tmpl_args = DECL_CLASS_TEMPLATE_P (t) 
	      ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
	      : DECL_TI_ARGS (DECL_RESULT (t));
5103 5104 5105 5106
	    tree full_args;
	    
	    push_momentary ();
	    full_args = tsubst_template_arg_vector (tmpl_args, args);
5107 5108 5109 5110 5111 5112 5113

	    /* tsubst_template_arg_vector doesn't copy the vector if
	       nothing changed.  But, *something* should have
	       changed.  */
	    my_friendly_assert (full_args != tmpl_args, 0);

	    spec = retrieve_specialization (t, full_args);
5114
	    pop_momentary ();
5115
	    if (spec != NULL_TREE)
5116 5117 5118 5119
	      {
		r = spec;
		break;
	      }
5120
	  }
5121 5122 5123 5124 5125 5126

	/* Make a new template decl.  It will be similar to the
	   original, but will record the current template arguments. 
	   We also create a new function declaration, which is just
	   like the old one, but points to this new template, rather
	   than the old one.  */
5127 5128 5129 5130
	r = copy_node (t);
	copy_lang_decl (r);
	my_friendly_assert (DECL_LANG_SPECIFIC (r) != 0, 0);
	TREE_CHAIN (r) = NULL_TREE;
5131 5132 5133 5134

	if (is_template_template_parm)
	  {
	    tree new_decl = tsubst (decl, args, in_decl);
5135 5136 5137
	    DECL_RESULT (r) = new_decl;
	    TREE_TYPE (r) = TREE_TYPE (new_decl);
	    break;
5138 5139
	  }

5140
	DECL_CONTEXT (r) 
5141 5142
	  = tsubst_aggr_type (DECL_CONTEXT (t), args, in_decl,
			      /*entering_scope=*/1);
5143
	DECL_CLASS_CONTEXT (r) 
5144 5145
	  = tsubst_aggr_type (DECL_CLASS_CONTEXT (t), args, in_decl,
			      /*entering_scope=*/1);
5146
	DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
5147 5148 5149 5150

	if (TREE_CODE (decl) == TYPE_DECL)
	  {
	    tree new_type = tsubst (TREE_TYPE (t), args, in_decl);
5151 5152 5153 5154
	    TREE_TYPE (r) = new_type;
	    CLASSTYPE_TI_TEMPLATE (new_type) = r;
	    DECL_RESULT (r) = TYPE_MAIN_DECL (new_type);
	    DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
5155 5156 5157 5158
	  }
	else
	  {
	    tree new_decl = tsubst (decl, args, in_decl);
5159 5160 5161 5162
	    DECL_RESULT (r) = new_decl;
	    DECL_TI_TEMPLATE (new_decl) = r;
	    TREE_TYPE (r) = TREE_TYPE (new_decl);
	    DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
5163 5164
	  }

5165 5166 5167
	SET_DECL_IMPLICIT_INSTANTIATION (r);
	DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
	DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
5168 5169 5170 5171

	/* The template parameters for this new template are all the
	   template parameters for the old template, except the
	   outermost level of parameters. */
5172
	DECL_TEMPLATE_PARMS (r) 
5173
	  = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args);
5174

5175
	if (PRIMARY_TEMPLATE_P (t))
5176
	  DECL_PRIMARY_TEMPLATE (r) = r;
5177

5178
	/* We don't partially instantiate partial specializations.  */
5179
	if (TREE_CODE (decl) == TYPE_DECL)
5180
	  break;
5181

5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221
	for (spec = DECL_TEMPLATE_SPECIALIZATIONS (t);
	     spec != NULL_TREE;
	     spec = TREE_CHAIN (spec))
	  {
	    /* It helps to consider example here.  Consider:

	       template <class T>
	       struct S {
	         template <class U>
		 void f(U u);

		 template <>
		 void f(T* t) {}
	       };
	       
	       Now, for example, we are instantiating S<int>::f(U u).  
	       We want to make a template:

	       template <class U>
	       void S<int>::f(U);

	       It will have a specialization, for the case U = int*, of
	       the form:

	       template <>
	       void S<int>::f<int*>(int*);

	       This specialization will be an instantiation of
	       the specialization given in the declaration of S, with
	       argument list int*.  */

	    tree fn = TREE_VALUE (spec);
	    tree spec_args;
	    tree new_fn;

	    if (!DECL_TEMPLATE_SPECIALIZATION (fn))
	      /* Instantiations are on the same list, but they're of
		 no concern to us.  */
	      continue;

5222 5223 5224 5225 5226 5227 5228 5229 5230
	    if (TREE_CODE (fn) != TEMPLATE_DECL)
	      /* A full specialization.  There's no need to record
		 that here.  */
	      continue;

	    spec_args = tsubst (DECL_TI_ARGS (fn), args, in_decl); 
	    new_fn = tsubst (DECL_RESULT (most_general_template (fn)), 
			     spec_args, in_decl); 
	    DECL_TI_TEMPLATE (new_fn) = fn;
5231
	    register_specialization (new_fn, r, 
5232
				     innermost_args (spec_args));
5233 5234 5235
	  }

	/* Record this partial instantiation.  */
5236 5237
	register_specialization (r, t, 
				 DECL_TI_ARGS (DECL_RESULT (r)));
5238

5239
      }
5240
      break;
mrs's avatar
mrs committed
5241 5242 5243

    case FUNCTION_DECL:
      {
5244
	tree ctx;
ghazi's avatar
ghazi committed
5245
	tree argvec = NULL_TREE;
5246
	tree gen_tmpl;
mrs's avatar
mrs committed
5247
	int member;
5248 5249
	int args_depth;
	int parms_depth;
mrs's avatar
mrs committed
5250

5251 5252 5253 5254 5255 5256 5257
	/* Nobody should be tsubst'ing into non-template functions.  */
	my_friendly_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE, 0);

	if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
	  {
	    tree spec;

5258 5259 5260 5261
	    /* Allocate template arguments on the momentary obstack,
	       in case we don't need to keep them.  */
	    push_momentary ();

5262 5263 5264 5265
	    /* Calculate the most general template of which R is a
	       specialization, and the complete set of arguments used to
	       specialize R.  */
	    gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
5266 5267 5268 5269
	    argvec 
	      = tsubst_template_arg_vector (DECL_TI_ARGS 
					    (DECL_TEMPLATE_RESULT (gen_tmpl)),
					    args); 
5270 5271 5272

	    /* Check to see if we already have this specialization.  */
	    spec = retrieve_specialization (gen_tmpl, argvec);
5273

5274
	    if (spec)
5275 5276
	      {
		r = spec;
5277
		pop_momentary ();
5278 5279
		break;
	      }
5280

5281 5282 5283 5284 5285
	    /* We're going to need to keep the ARGVEC, so we copy it
	       here.  */
	    argvec = copy_to_permanent (argvec);
	    pop_momentary ();

5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325
	    /* Here, we deal with the peculiar case:

		 template <class T> struct S { 
		   template <class U> friend void f();
		 };
		 template <class U> friend void f() {}
		 template S<int>;
		 template void f<double>();

	       Here, the ARGS for the instantiation of will be {int,
	       double}.  But, we only need as many ARGS as there are
	       levels of template parameters in CODE_PATTERN.  We are
	       careful not to get fooled into reducing the ARGS in
	       situations like:

		 template <class T> struct S { template <class U> void f(U); }
		 template <class T> template <> void S<T>::f(int) {}

	       which we can spot because the pattern will be a
	       specialization in this case.  */
	    args_depth = TMPL_ARGS_DEPTH (args);
	    parms_depth = 
	      TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t))); 
	    if (args_depth > parms_depth
		&& !DECL_TEMPLATE_SPECIALIZATION (t))
	      {
		my_friendly_assert (DECL_FRIEND_P (t), 0);

		if (parms_depth > 1)
		  {
		    int i;

		    args = make_temp_vec (parms_depth);
		    for (i = 0; i < parms_depth; ++i)
		      TREE_VEC_ELT (args, i) = 
			TREE_VEC_ELT (args, i + (args_depth - parms_depth));
		  }
		else
		  args = TREE_VEC_ELT (args, args_depth - parms_depth);
	      }
5326 5327 5328 5329 5330 5331 5332 5333 5334 5335
	  }
	else
	  {
	    /* This special case arises when we have something like this:

	         template <class T> struct S { 
		   friend void f<int>(int, double); 
		 };

	       Here, the DECL_TI_TEMPLATE for the friend declaration
5336 5337 5338 5339 5340 5341 5342 5343
	       will be a LOOKUP_EXPR or an IDENTIFIER_NODE.  We are
	       being called from tsubst_friend_function, and we want
	       only to create a new decl (R) with appropriate types so
	       that we can call determine_specialization.  */
	    my_friendly_assert ((TREE_CODE (DECL_TI_TEMPLATE (t)) 
				 == LOOKUP_EXPR)
				|| (TREE_CODE (DECL_TI_TEMPLATE (t))
				    == IDENTIFIER_NODE), 0);
5344 5345 5346
	    gen_tmpl = NULL_TREE;
	  }

5347
	if (DECL_CLASS_SCOPE_P (t))
mrs's avatar
mrs committed
5348
	  {
mrs's avatar
mrs committed
5349 5350 5351 5352
	    if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
	      member = 2;
	    else
	      member = 1;
5353 5354
	    ctx = tsubst_aggr_type (DECL_CLASS_CONTEXT (t), args, t,
				    /*entering_scope=*/1);
mrs's avatar
mrs committed
5355 5356 5357 5358 5359 5360
	  }
	else
	  {
	    member = 0;
	    ctx = NULL_TREE;
	  }
bothner's avatar
d  
bothner committed
5361
	type = tsubst (type, args, in_decl);
mrs's avatar
mrs committed
5362

mrs's avatar
mrs committed
5363 5364 5365
	/* We do NOT check for matching decls pushed separately at this
           point, as they may not represent instantiations of this
           template, and in any case are considered separate under the
mrs's avatar
mrs committed
5366
           discrete model.  Instead, see add_maybe_template.  */
mrs's avatar
mrs committed
5367 5368 5369

	r = copy_node (t);
	copy_lang_decl (r);
5370
	DECL_USE_TEMPLATE (r) = 0;
mrs's avatar
mrs committed
5371 5372 5373
	TREE_TYPE (r) = type;

	DECL_CONTEXT (r)
5374
	  = tsubst_aggr_type (DECL_CONTEXT (t), args, t, /*entering_scope=*/1);
mrs's avatar
mrs committed
5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385
	DECL_CLASS_CONTEXT (r) = ctx;

	if (member && !strncmp (OPERATOR_TYPENAME_FORMAT,
				IDENTIFIER_POINTER (DECL_NAME (r)),
				sizeof (OPERATOR_TYPENAME_FORMAT) - 1))
	  {
	    /* Type-conversion operator.  Reconstruct the name, in
	       case it's the name of one of the template's parameters.  */
	    DECL_NAME (r) = build_typename_overload (TREE_TYPE (type));
	  }

5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399
	DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args, t);
	DECL_MAIN_VARIANT (r) = r;
	DECL_RESULT (r) = NULL_TREE;

	TREE_STATIC (r) = 0;
	TREE_PUBLIC (r) = TREE_PUBLIC (t);
	DECL_EXTERNAL (r) = 1;
	DECL_INTERFACE_KNOWN (r) = 0;
	DECL_DEFER_OUTPUT (r) = 0;
	TREE_CHAIN (r) = NULL_TREE;
	DECL_PENDING_INLINE_INFO (r) = 0;
	TREE_USED (r) = 0;

	if (DECL_CONSTRUCTOR_P (r))
mrs's avatar
mrs committed
5400
	  {
5401 5402
	    maybe_retrofit_in_chrg (r);
	    grok_ctor_properties (ctx, r);
mrs's avatar
mrs committed
5403
	  }
5404 5405 5406
	if (IDENTIFIER_OPNAME_P (DECL_NAME (r)))
	  grok_op_properties (r, DECL_VIRTUAL_P (r), DECL_FRIEND_P (r));

5407 5408 5409 5410
	/* Set up the DECL_TEMPLATE_INFO for R and compute its mangled
	   name.  There's no need to do this in the special friend
	   case mentioned above where GEN_TMPL is NULL.  */
	if (gen_tmpl)
5411
	  {
5412 5413 5414
	    /* The ARGVEC was built on the momentary obstack.  Make it
	       permanent now.  */
	    argvec = copy_to_permanent (argvec);
5415 5416 5417 5418 5419 5420 5421 5422 5423
	    DECL_TEMPLATE_INFO (r) 
	      = perm_tree_cons (gen_tmpl, argvec, NULL_TREE);
	    SET_DECL_IMPLICIT_INSTANTIATION (r);
	    register_specialization (r, gen_tmpl, argvec);

	    /* Set the mangled name for R.  */
	    if (DECL_DESTRUCTOR_P (t))
	      DECL_ASSEMBLER_NAME (r) = build_destructor_name (ctx);
	    else 
5424
	      {
5425 5426 5427 5428
		/* Instantiations of template functions must be mangled
		   specially, in order to conform to 14.5.5.1
		   [temp.over.link].  */
		tree tmpl = DECL_TI_TEMPLATE (t);
5429
		
5430 5431 5432 5433 5434 5435 5436
		/* TMPL will be NULL if this is a specialization of a
		   member function of a template class.  */
		if (name_mangling_version < 1
		    || tmpl == NULL_TREE
		    || (member && !is_member_template (tmpl)
			&& !DECL_TEMPLATE_INFO (tmpl)))
		  set_mangled_name_for_decl (r);
5437
		else
5438
		  set_mangled_name_for_template_decl (r);
5439
	      }
5440 5441 5442 5443 5444 5445 5446 5447
	    
	    DECL_RTL (r) = 0;
	    make_decl_rtl (r, NULL_PTR, 1);
	    
	    /* Like grokfndecl.  If we don't do this, pushdecl will
	       mess up our TREE_CHAIN because it doesn't find a
	       previous decl.  Sigh.  */
	    if (member
5448
		&& ! uses_template_parms (r)
5449 5450 5451
		&& (IDENTIFIER_GLOBAL_VALUE (DECL_ASSEMBLER_NAME (r)) 
		    == NULL_TREE))
	      SET_IDENTIFIER_GLOBAL_VALUE (DECL_ASSEMBLER_NAME (r), r);
5452
	  }
mrs's avatar
mrs committed
5453
      }
5454
      break;
mrs's avatar
mrs committed
5455 5456 5457

    case PARM_DECL:
      {
5458
	r = copy_node (t);
mrs's avatar
mrs committed
5459
	TREE_TYPE (r) = type;
5460 5461 5462 5463 5464
	if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
	  DECL_INITIAL (r) = TREE_TYPE (r);
	else
	  DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args, in_decl);

mrs's avatar
mrs committed
5465
	DECL_CONTEXT (r) = NULL_TREE;
kenner's avatar
kenner committed
5466 5467 5468 5469 5470 5471
#ifdef PROMOTE_PROTOTYPES
	if ((TREE_CODE (type) == INTEGER_TYPE
	     || TREE_CODE (type) == ENUMERAL_TYPE)
	    && TYPE_PRECISION (type) < TYPE_PRECISION (integer_type_node))
	  DECL_ARG_TYPE (r) = integer_type_node;
#endif
mrs's avatar
mrs committed
5472
	if (TREE_CHAIN (t))
5473
	  TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args, TREE_CHAIN (t));
mrs's avatar
mrs committed
5474
      }
5475
      break;
mrs's avatar
mrs committed
5476

mrs's avatar
mrs committed
5477 5478
    case FIELD_DECL:
      {
5479
	r = copy_node (t);
mrs's avatar
mrs committed
5480 5481 5482
	TREE_TYPE (r) = type;
	copy_lang_decl (r);
#if 0
5483
	DECL_FIELD_CONTEXT (r) = tsubst (DECL_FIELD_CONTEXT (t), args, in_decl);
mrs's avatar
mrs committed
5484
#endif
5485
	DECL_INITIAL (r) = tsubst_expr (DECL_INITIAL (t), args, in_decl);
mrs's avatar
mrs committed
5486
	TREE_CHAIN (r) = NULL_TREE;
5487
	if (TREE_CODE (type) == VOID_TYPE)
jason's avatar
jason committed
5488
	  cp_error_at ("instantiation of `%D' as type void", r);
mrs's avatar
mrs committed
5489
      }
5490
      break;
mrs's avatar
mrs committed
5491 5492 5493

    case USING_DECL:
      {
5494
	r = copy_node (t);
mrs's avatar
mrs committed
5495
	DECL_INITIAL (r)
5496
	  = tsubst_copy (DECL_INITIAL (t), args, in_decl);
mrs's avatar
mrs committed
5497 5498
	TREE_CHAIN (r) = NULL_TREE;
      }
5499
      break;
mrs's avatar
mrs committed
5500 5501 5502

    case VAR_DECL:
      {
5503 5504 5505 5506 5507 5508 5509 5510 5511 5512
	tree argvec;
	tree gen_tmpl;
	tree spec;
	tree tmpl;
	tree ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, in_decl,
				     /*entering_scope=*/1);
	
	/* Nobody should be tsubst'ing into non-template variables.  */
	my_friendly_assert (DECL_LANG_SPECIFIC (t) 
			    && DECL_TEMPLATE_INFO (t) != NULL_TREE, 0);
mrs's avatar
mrs committed
5513

5514 5515 5516 5517 5518 5519 5520
	/* Check to see if we already have this specialization.  */
	tmpl = DECL_TI_TEMPLATE (t);
	gen_tmpl = most_general_template (tmpl);
	argvec = tsubst (DECL_TI_ARGS (t), args, in_decl);
	spec = retrieve_specialization (gen_tmpl, argvec);
	
	if (spec)
5521 5522 5523 5524
	  {
	    r = spec;
	    break;
	  }
mrs's avatar
mrs committed
5525 5526 5527 5528 5529 5530 5531

	r = copy_node (t);
	TREE_TYPE (r) = type;
	DECL_CONTEXT (r) = ctx;
	if (TREE_STATIC (r))
	  DECL_ASSEMBLER_NAME (r)
	    = build_static_name (DECL_CONTEXT (r), DECL_NAME (r));
mrs's avatar
mrs committed
5532 5533 5534 5535

	/* Don't try to expand the initializer until someone tries to use
	   this variable; otherwise we run into circular dependencies.  */
	DECL_INITIAL (r) = NULL_TREE;
mrs's avatar
mrs committed
5536 5537
	DECL_RTL (r) = 0;
	DECL_SIZE (r) = 0;
5538 5539
	copy_lang_decl (r);
	DECL_CLASS_CONTEXT (r) = DECL_CONTEXT (r);
mrs's avatar
mrs committed
5540

5541 5542 5543
	DECL_TEMPLATE_INFO (r) = perm_tree_cons (tmpl, argvec, NULL_TREE);
	SET_DECL_IMPLICIT_INSTANTIATION (r);
	register_specialization (r, gen_tmpl, argvec);
mrs's avatar
mrs committed
5544 5545

	TREE_CHAIN (r) = NULL_TREE;
5546
	if (TREE_CODE (type) == VOID_TYPE)
jason's avatar
jason committed
5547
	  cp_error_at ("instantiation of `%D' as type void", r);
mrs's avatar
mrs committed
5548
      }
5549
      break;
mrs's avatar
mrs committed
5550 5551

    case TYPE_DECL:
mrs's avatar
mrs committed
5552
      if (t == TYPE_NAME (TREE_TYPE (t)))
5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573
	r = TYPE_NAME (type);
      else
	{
	  r = copy_node (t);
	  TREE_TYPE (r) = type;
	  DECL_CONTEXT (r) = current_class_type;
	  TREE_CHAIN (r) = NULL_TREE;
	}
      break;

    default:
      my_friendly_abort (0);
    } 

  /* Restore the file and line information.  */
  lineno = saved_lineno;
  input_filename = saved_filename;

  return r;
}

5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604
/* Substitue into the ARG_TYPES of a function type.  */

tree
tsubst_arg_types (arg_types, args, in_decl)
     tree arg_types;
     tree args;
     tree in_decl;
{
  tree remaining_arg_types;
  tree type;

  if (!arg_types || arg_types == void_list_node)
    return arg_types;
  
  remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
					  args, in_decl);

  /* We use TYPE_MAIN_VARIANT is because top-level qualifiers don't
     matter on function types.  */
  type = TYPE_MAIN_VARIANT (type_decays_to 
			    (tsubst (TREE_VALUE (arg_types),
				     args, in_decl)));

  /* Note that we do not substitute into default arguments here.  The
     standard mandates that they be instantiated only when needed,
     which is done in build_over_call.  */
  return hash_tree_cons_simple (TREE_PURPOSE (arg_types), type,
				remaining_arg_types);
			 
}

5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616
/* Take the tree structure T and replace template parameters used therein
   with the argument vector ARGS.  IN_DECL is an associated decl for
   diagnostics.

   tsubst is used for dealing with types, decls and the like; for
   expressions, use tsubst_expr or tsubst_copy.  */

tree
tsubst (t, args, in_decl)
     tree t, args;
     tree in_decl;
{
5617
  tree type, r;
5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667

  if (t == NULL_TREE || t == error_mark_node
      || t == integer_type_node
      || t == void_type_node
      || t == char_type_node
      || TREE_CODE (t) == NAMESPACE_DECL)
    return t;

  if (TREE_CODE (t) == IDENTIFIER_NODE)
    type = IDENTIFIER_TYPE_VALUE (t);
  else
    type = TREE_TYPE (t);
  if (type == unknown_type_node)
    my_friendly_abort (42);

  if (type && TREE_CODE (t) != FUNCTION_DECL
      && TREE_CODE (t) != TYPENAME_TYPE
      && TREE_CODE (t) != TEMPLATE_DECL
      && TREE_CODE (t) != IDENTIFIER_NODE)
    type = tsubst (type, args, in_decl);

  if (TREE_CODE_CLASS (TREE_CODE (t)) == 'd')
    return tsubst_decl (t, args, type, in_decl);

  switch (TREE_CODE (t))
    {
    case RECORD_TYPE:
    case UNION_TYPE:
    case ENUMERAL_TYPE:
      return tsubst_aggr_type (t, args, in_decl, /*entering_scope=*/0);

    case ERROR_MARK:
    case IDENTIFIER_NODE:
    case OP_IDENTIFIER:
    case VOID_TYPE:
    case REAL_TYPE:
    case COMPLEX_TYPE:
    case BOOLEAN_TYPE:
    case INTEGER_CST:
    case REAL_CST:
    case STRING_CST:
      return t;

    case INTEGER_TYPE:
      if (t == integer_type_node)
	return t;

      if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
	  && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
	return t;
mrs's avatar
mrs committed
5668

mrs's avatar
mrs committed
5669
      {
5670
	tree max = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
5671

5672 5673 5674 5675 5676 5677 5678 5679 5680 5681
	max = tsubst_expr (max, args, in_decl);
	if (processing_template_decl)
	  {
	    tree itype = make_node (INTEGER_TYPE);
	    TYPE_MIN_VALUE (itype) = size_zero_node;
	    TYPE_MAX_VALUE (itype) = build_min (MINUS_EXPR, sizetype, max,
						integer_one_node);
	    return itype;
	  }

5682 5683 5684 5685 5686 5687 5688 5689
	if (pedantic && integer_zerop (max))
	  pedwarn ("creating array with size zero");
	else if (INT_CST_LT (max, integer_zero_node))
	  {
	    cp_error ("creating array with size `%E'", max);
	    max = integer_one_node;
	  }

5690
	max = fold (build_binary_op (MINUS_EXPR, max, integer_one_node, 1));
5691 5692
	if (!TREE_PERMANENT (max) && !allocation_temporary_p ())
	  max = copy_to_permanent (max);
5693
	return build_index_type (max);
5694 5695 5696 5697 5698 5699 5700 5701 5702
      }

    case TEMPLATE_TYPE_PARM:
    case TEMPLATE_TEMPLATE_PARM:
    case TEMPLATE_PARM_INDEX:
      {
	int idx;
	int level;
	int levels;
5703 5704

	r = NULL_TREE;
5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725

	if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
	    || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
	  {
	    idx = TEMPLATE_TYPE_IDX (t);
	    level = TEMPLATE_TYPE_LEVEL (t);
	  }
	else
	  {
	    idx = TEMPLATE_PARM_IDX (t);
	    level = TEMPLATE_PARM_LEVEL (t);
	  }

	if (TREE_VEC_LENGTH (args) > 0)
	  {
	    tree arg = NULL_TREE;

	    levels = TMPL_ARGS_DEPTH (args);
	    if (level <= levels)
	      arg = TMPL_ARG (args, level, idx);

5726 5727 5728
	    if (arg == error_mark_node)
	      return error_mark_node;
	    else if (arg != NULL_TREE)
5729 5730 5731 5732 5733
	      {
		if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
		  {
		    my_friendly_assert (TREE_CODE_CLASS (TREE_CODE (arg))
					== 't', 0);
5734 5735
		    return cp_build_qualified_type
		      (arg, CP_TYPE_QUALS (arg) | CP_TYPE_QUALS (t));
5736 5737 5738
		  }
		else if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
		  {
5739
		    if (TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t))
5740 5741 5742
		      {
			/* We are processing a type constructed from
			   a template template parameter */
5743
			tree argvec = tsubst (TYPE_TI_ARGS (t),
5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757
					      args, in_decl);

			/* We can get a TEMPLATE_TEMPLATE_PARM here when 
			   we are resolving nested-types in the signature of 
			   a member function templates.
			   Otherwise ARG is a TEMPLATE_DECL and is the real 
			   template to be instantiated.  */
			if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
			  arg = TYPE_NAME (arg);

			r = lookup_template_class (DECL_NAME (arg), 
						   argvec, in_decl, 
						   DECL_CONTEXT (arg),
						   /*entering_scope=*/0);
5758
			return cp_build_qualified_type (r, TYPE_QUALS (t));
5759 5760 5761 5762 5763 5764 5765 5766 5767
		      }
		    else
		      /* We are processing a template argument list.  */ 
		      return arg;
		  }
		else
		  return arg;
	      }
	  }
5768 5769
	else
	  my_friendly_abort (981018);
5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793

	if (level == 1)
	  /* This can happen during the attempted tsubst'ing in
	     unify.  This means that we don't yet have any information
	     about the template parameter in question.  */
	  return t;

	/* If we get here, we must have been looking at a parm for a
	   more deeply nested template.  Make a new version of this
	   template parameter, but with a lower level.  */
	switch (TREE_CODE (t))
	  {
	  case TEMPLATE_TYPE_PARM:
	  case TEMPLATE_TEMPLATE_PARM:
	    r = copy_node (t);
	    TEMPLATE_TYPE_PARM_INDEX (r)
	      = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
					    r, levels);
	    TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
	    TYPE_MAIN_VARIANT (r) = r;
	    TYPE_POINTER_TO (r) = NULL_TREE;
	    TYPE_REFERENCE_TO (r) = NULL_TREE;

	    if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
5794
		&& TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t))
5795
	      {
5796 5797
		tree argvec = tsubst (TYPE_TI_ARGS (t), args, in_decl);
		TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809
		  = perm_tree_cons (TYPE_NAME (t), argvec, NULL_TREE);
	      }
	    break;

	  case TEMPLATE_PARM_INDEX:
	    r = reduce_template_parm_level (t, type, levels);
	    break;
	   
	  default:
	    my_friendly_abort (0);
	  }

mrs's avatar
mrs committed
5810
	return r;
5811
      }
mrs's avatar
mrs committed
5812

mrs's avatar
mrs committed
5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826
    case TREE_LIST:
      {
	tree purpose, value, chain, result;
	int via_public, via_virtual, via_protected;

	if (t == void_list_node)
	  return t;

	via_public = TREE_VIA_PUBLIC (t);
	via_protected = TREE_VIA_PROTECTED (t);
	via_virtual = TREE_VIA_VIRTUAL (t);

	purpose = TREE_PURPOSE (t);
	if (purpose)
5827
	  purpose = tsubst (purpose, args, in_decl);
mrs's avatar
mrs committed
5828 5829
	value = TREE_VALUE (t);
	if (value)
5830
	  value = tsubst (value, args, in_decl);
mrs's avatar
mrs committed
5831 5832
	chain = TREE_CHAIN (t);
	if (chain && chain != void_type_node)
5833
	  chain = tsubst (chain, args, in_decl);
mrs's avatar
mrs committed
5834 5835 5836 5837 5838 5839 5840 5841 5842 5843
	if (purpose == TREE_PURPOSE (t)
	    && value == TREE_VALUE (t)
	    && chain == TREE_CHAIN (t))
	  return t;
	result = hash_tree_cons (via_public, via_virtual, via_protected,
				 purpose, value, chain);
	TREE_PARMLIST (result) = TREE_PARMLIST (t);
	return result;
      }
    case TREE_VEC:
mrs's avatar
mrs committed
5844 5845
      if (type != NULL_TREE)
	{
5846 5847
	  /* A binfo node.  We always need to make a copy, of the node
	     itself and of its BINFO_BASETYPES.  */
5848

mrs's avatar
mrs committed
5849 5850
	  t = copy_node (t);

5851 5852 5853
	  /* Make sure type isn't a typedef copy.  */
	  type = BINFO_TYPE (TYPE_BINFO (type));

mrs's avatar
mrs committed
5854
	  TREE_TYPE (t) = complete_type (type);
mrs's avatar
mrs committed
5855 5856 5857 5858 5859 5860 5861
	  if (IS_AGGR_TYPE (type))
	    {
	      BINFO_VTABLE (t) = TYPE_BINFO_VTABLE (type);
	      BINFO_VIRTUALS (t) = TYPE_BINFO_VIRTUALS (type);
	      if (TYPE_BINFO_BASETYPES (type) != NULL_TREE)
		BINFO_BASETYPES (t) = copy_node (TYPE_BINFO_BASETYPES (type));
	    }
mrs's avatar
mrs committed
5862 5863
	  return t;
	}
5864 5865

      /* Otherwise, a vector of template arguments.  */
5866
      return tsubst_template_arg_vector (t, args);
mrs's avatar
mrs committed
5867 5868 5869 5870 5871

    case POINTER_TYPE:
    case REFERENCE_TYPE:
      {
	enum tree_code code;
5872

mrs's avatar
mrs committed
5873 5874 5875 5876
	if (type == TREE_TYPE (t))
	  return t;

	code = TREE_CODE (t);
5877 5878
	if (TREE_CODE (type) == REFERENCE_TYPE
	    || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
5879 5880 5881 5882 5883 5884 5885 5886 5887 5888
	  {
	    static int   last_line = 0;
	    static char* last_file = 0;

	    /* We keep track of the last time we issued this error
	       message to avoid spewing a ton of messages during a
	       single bad template instantiation.  */
	    if (last_line != lineno ||
		last_file != input_filename)
	      {
5889 5890 5891 5892 5893 5894
		if (TREE_CODE (type) == VOID_TYPE)
		  cp_error ("forming reference to void");
		else
		  cp_error ("forming %s to reference type `%T'",
			    (code == POINTER_TYPE) ? "pointer" : "reference",
			    type);
5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907
		last_line = lineno;
		last_file = input_filename;
	      }

	    /* Use the underlying type in an attempt at error
	       recovery; maybe the user meant vector<int> and wrote
	       vector<int&>, or some such.  */
	    if (code == REFERENCE_TYPE)
	      r = type;
	    else
	      r = build_pointer_type (TREE_TYPE (type));
	  }
	else if (code == POINTER_TYPE)
mrs's avatar
mrs committed
5908 5909 5910
	  r = build_pointer_type (type);
	else
	  r = build_reference_type (type);
5911
	r = cp_build_qualified_type (r, TYPE_QUALS (t));
5912

mrs's avatar
mrs committed
5913 5914 5915 5916
	/* Will this ever be needed for TYPE_..._TO values?  */
	layout_type (r);
	return r;
      }
mrs's avatar
mrs committed
5917
    case OFFSET_TYPE:
5918 5919 5920 5921 5922 5923
      {
	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, in_decl);
	if (! IS_AGGR_TYPE (r))
	  cp_error ("creating pointer to member of non-class type `%T'", r);
	return build_offset_type (r, type);
      }
mrs's avatar
mrs committed
5924 5925 5926
    case FUNCTION_TYPE:
    case METHOD_TYPE:
      {
5927 5928
	tree arg_types;
	tree raises;
mrs's avatar
merging  
mrs committed
5929
	tree fntype;
mrs's avatar
mrs committed
5930

5931 5932 5933 5934 5935
	/* The TYPE_CONTEXT is not used for function/method types.  */
	my_friendly_assert (TYPE_CONTEXT (t) == NULL_TREE, 0);
	
	/* Substitue the argument types.  */
	arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, in_decl);
mrs's avatar
mrs committed
5936 5937

	/* Construct a new type node and return it.  */
5938 5939
	if (TREE_CODE (t) == FUNCTION_TYPE)
	  fntype = build_function_type (type, arg_types);
5940 5941 5942 5943 5944 5945 5946 5947 5948
	else
	  {
	    r = TREE_TYPE (TREE_VALUE (arg_types));
	    if (! IS_AGGR_TYPE (r))
	      cp_error ("creating pointer to member function of non-class type `%T'",
			r);
	      
	    fntype = build_cplus_method_type (r, type, TREE_CHAIN (arg_types));
	  }
5949
	fntype = build_qualified_type (fntype, TYPE_QUALS (t));
5950 5951 5952

	/* Substitue the exception specification. */
	raises = TYPE_RAISES_EXCEPTIONS (t);
mrs's avatar
merging  
mrs committed
5953 5954
	if (raises)
	  {
5955
	    raises = tsubst (raises, args, in_decl);
mrs's avatar
merging  
mrs committed
5956 5957 5958
	    fntype = build_exception_variant (fntype, raises);
	  }
	return fntype;
mrs's avatar
mrs committed
5959 5960 5961
      }
    case ARRAY_TYPE:
      {
5962
	tree domain = tsubst (TYPE_DOMAIN (t), args, in_decl);
mrs's avatar
mrs committed
5963 5964
	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
	  return t;
5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982

	/* These checks should match the ones in grokdeclarator.  */
	if (TREE_CODE (type) == VOID_TYPE)
	  {
	    cp_error ("creating array of void");
	    type = build_pointer_type (type);
	  }
	else if (TREE_CODE (type) == FUNCTION_TYPE)
	  {
	    cp_error ("creating array of functions `%T'", type);
	    type = build_pointer_type (type);
	  }
	else if (TREE_CODE (type) == REFERENCE_TYPE)
	  {
	    cp_error ("creating array of references `%T'", type);
	    type = TREE_TYPE (type);
	  }

mrs's avatar
mrs committed
5983 5984 5985 5986 5987
	r = build_cplus_array_type (type, domain);
	return r;
      }

    case PLUS_EXPR:
mrs's avatar
mrs committed
5988
    case MINUS_EXPR:
mrs's avatar
mrs committed
5989
      return fold (build (TREE_CODE (t), TREE_TYPE (t),
5990 5991
			  tsubst (TREE_OPERAND (t, 0), args, in_decl),
			  tsubst (TREE_OPERAND (t, 1), args, in_decl)));
mrs's avatar
mrs committed
5992 5993 5994 5995

    case NEGATE_EXPR:
    case NOP_EXPR:
      return fold (build1 (TREE_CODE (t), TREE_TYPE (t),
5996
			   tsubst (TREE_OPERAND (t, 0), args, in_decl)));
mrs's avatar
mrs committed
5997

mrs's avatar
mrs committed
5998 5999
    case TYPENAME_TYPE:
      {
6000 6001
	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, in_decl,
				     /*entering_scope=*/1);
6002
	tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args, in_decl);
6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015

	/* Normally, make_typename_type does not require that the CTX
	   have complete type in order to allow things like:
	     
             template <class T> struct S { typename S<T>::X Y; };

	   But, such constructs have already been resolved by this
	   point, so here CTX really should have complete type, unless
	   it's a partial instantiation.  */
	if (!uses_template_parms (ctx) 
	    && !complete_type_or_else (ctx))
	  return error_mark_node;

6016
	f = make_typename_type (ctx, f);
6017 6018 6019
	return cp_build_qualified_type (f, 
					CP_TYPE_QUALS (f) 
					| CP_TYPE_QUALS (t));
mrs's avatar
mrs committed
6020 6021 6022 6023
      }

    case INDIRECT_REF:
      return make_pointer_declarator
6024
	(type, tsubst (TREE_OPERAND (t, 0), args, in_decl));
mrs's avatar
mrs committed
6025 6026 6027
      
    case ADDR_EXPR:
      return make_reference_declarator
6028
	(type, tsubst (TREE_OPERAND (t, 0), args, in_decl));
mrs's avatar
mrs committed
6029 6030 6031

    case ARRAY_REF:
      return build_parse_node
6032 6033
	(ARRAY_REF, tsubst (TREE_OPERAND (t, 0), args, in_decl),
	 tsubst_expr (TREE_OPERAND (t, 1), args, in_decl));
mrs's avatar
mrs committed
6034 6035

    case CALL_EXPR:
mrs's avatar
merging  
mrs committed
6036
      return make_call_declarator
6037 6038
	(tsubst (TREE_OPERAND (t, 0), args, in_decl),
	 tsubst (TREE_OPERAND (t, 1), args, in_decl),
mrs's avatar
merging  
mrs committed
6039
	 TREE_OPERAND (t, 2),
6040
	 tsubst (TREE_TYPE (t), args, in_decl));
mrs's avatar
mrs committed
6041

mrs's avatar
mrs committed
6042 6043
    case SCOPE_REF:
      return build_parse_node
6044 6045
	(TREE_CODE (t), tsubst (TREE_OPERAND (t, 0), args, in_decl),
	 tsubst (TREE_OPERAND (t, 1), args, in_decl));
mrs's avatar
mrs committed
6046

6047 6048 6049
    case TYPEOF_TYPE:
      return TREE_TYPE (tsubst_expr (TYPE_FIELDS (t), args, in_decl));

mrs's avatar
mrs committed
6050
    default:
mrs's avatar
mrs committed
6051
      sorry ("use of `%s' in template",
mrs's avatar
mrs committed
6052 6053 6054 6055 6056
	     tree_code_name [(int) TREE_CODE (t)]);
      return error_mark_node;
    }
}

mrs's avatar
mrs committed
6057 6058 6059 6060 6061 6062 6063 6064 6065 6066
void
do_pushlevel ()
{
  emit_line_note (input_filename, lineno);
  pushlevel (0);
  clear_last_expr ();
  push_momentary ();
  expand_start_bindings (0);
}  

mrs's avatar
mrs committed
6067
tree
mrs's avatar
mrs committed
6068
do_poplevel ()
mrs's avatar
mrs committed
6069
{
mrs's avatar
mrs committed
6070
  tree t;
6071
  int saved_warn_unused = 0;
mrs's avatar
mrs committed
6072

6073 6074 6075 6076 6077
  if (processing_template_decl)
    {
      saved_warn_unused = warn_unused;
      warn_unused = 0;
    }
6078
  expand_end_bindings (getdecls (), kept_level_p (), 0);
6079 6080
  if (processing_template_decl)
    warn_unused = saved_warn_unused;
mrs's avatar
mrs committed
6081 6082 6083 6084
  t = poplevel (kept_level_p (), 1, 0);
  pop_momentary ();
  return t;
}
mrs's avatar
mrs committed
6085

6086 6087 6088 6089
/* Like tsubst, but deals with expressions.  This function just replaces
   template parms; to finish processing the resultant expression, use
   tsubst_expr.  */

mrs's avatar
mrs committed
6090
tree
6091
tsubst_copy (t, args, in_decl)
6092
     tree t, args;
mrs's avatar
mrs committed
6093 6094 6095
     tree in_decl;
{
  enum tree_code code;
6096
  tree r;
mrs's avatar
mrs committed
6097

mrs's avatar
mrs committed
6098 6099 6100 6101
  if (t == NULL_TREE || t == error_mark_node)
    return t;

  code = TREE_CODE (t);
mrs's avatar
mrs committed
6102

mrs's avatar
mrs committed
6103 6104 6105
  switch (code)
    {
    case PARM_DECL:
6106
      return do_identifier (DECL_NAME (t), 0, NULL_TREE);
mrs's avatar
mrs committed
6107 6108

    case CONST_DECL:
6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141
      {
	tree enum_type;
	tree v;

	if (!DECL_CONTEXT (t))
	  /* This is a global enumeration constant.  */
	  return t;

	/* Unfortunately, we cannot just call lookup_name here.
	 Consider:

	 template <int I> int f() {
	   enum E { a = I };
	   struct S { void g() { E e = a; } };
	 };

	 When we instantiate f<7>::S::g(), say, lookup_name is not
	 clever enough to find f<7>::a.  */
	enum_type 
	  = tsubst_aggr_type (TREE_TYPE (t), args, in_decl, 
			      /*entering_scope=*/0);

	for (v = TYPE_VALUES (enum_type); 
	     v != NULL_TREE; 
	     v = TREE_CHAIN (v))
	  if (TREE_PURPOSE (v) == DECL_NAME (t))
	    return TREE_VALUE (v);

	  /* We didn't find the name.  That should never happen; if
	     name-lookup found it during preliminary parsing, we
	     should find it again here during instantiation.  */
	my_friendly_abort (0);
      }
jason's avatar
jason committed
6142
      return t;
6143

mrs's avatar
mrs committed
6144 6145 6146
    case FIELD_DECL:
      if (DECL_CONTEXT (t))
	{
6147 6148
	  tree ctx;

6149 6150
	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, in_decl,
				  /*entering_scope=*/1);
6151
	  if (ctx != DECL_CONTEXT (t))
mrs's avatar
mrs committed
6152 6153 6154 6155 6156 6157 6158
	    return lookup_field (ctx, DECL_NAME (t), 0, 0);
	}
      return t;

    case VAR_DECL:
    case FUNCTION_DECL:
      if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
6159
	t = tsubst (t, args, in_decl);
mrs's avatar
mrs committed
6160 6161 6162
      mark_used (t);
      return t;

6163 6164
    case TEMPLATE_DECL:
      if (is_member_template (t))
6165
	return tsubst (t, args, in_decl);
6166 6167 6168
      else
	return t;

6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179
    case LOOKUP_EXPR:
      {
	/* We must tsbust into a LOOKUP_EXPR in case the names to
	   which it refers is a conversion operator; in that case the
	   name will change.  We avoid making unnecessary copies,
	   however.  */
	
	tree id = tsubst_copy (TREE_OPERAND (t, 0), args, in_decl);

	if (id != TREE_OPERAND (t, 0))
	  {
6180
	    r = build_nt (LOOKUP_EXPR, id);
6181 6182 6183 6184 6185 6186 6187
	    LOOKUP_EXPR_GLOBAL (r) = LOOKUP_EXPR_GLOBAL (t);
	    t = r;
	  }

	return t;
      }

mrs's avatar
mrs committed
6188 6189
    case CAST_EXPR:
    case REINTERPRET_CAST_EXPR:
mrs's avatar
mrs committed
6190 6191 6192
    case CONST_CAST_EXPR:
    case STATIC_CAST_EXPR:
    case DYNAMIC_CAST_EXPR:
6193
    case NOP_EXPR:
mrs's avatar
mrs committed
6194
      return build1
6195 6196
	(code, tsubst (TREE_TYPE (t), args, in_decl),
	 tsubst_copy (TREE_OPERAND (t, 0), args, in_decl));
mrs's avatar
mrs committed
6197 6198 6199 6200 6201 6202 6203 6204

    case INDIRECT_REF:
    case PREDECREMENT_EXPR:
    case PREINCREMENT_EXPR:
    case POSTDECREMENT_EXPR:
    case POSTINCREMENT_EXPR:
    case NEGATE_EXPR:
    case TRUTH_NOT_EXPR:
mrs's avatar
mrs committed
6205
    case BIT_NOT_EXPR:
mrs's avatar
mrs committed
6206 6207 6208
    case ADDR_EXPR:
    case CONVERT_EXPR:      /* Unary + */
    case SIZEOF_EXPR:
6209
    case ALIGNOF_EXPR:
mrs's avatar
mrs committed
6210
    case ARROW_EXPR:
mrs's avatar
mrs committed
6211
    case THROW_EXPR:
mrs's avatar
mrs committed
6212
    case TYPEID_EXPR:
mrs's avatar
mrs committed
6213 6214
      return build1
	(code, NULL_TREE,
6215
	 tsubst_copy (TREE_OPERAND (t, 0), args, in_decl));
mrs's avatar
mrs committed
6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253

    case PLUS_EXPR:
    case MINUS_EXPR:
    case MULT_EXPR:
    case TRUNC_DIV_EXPR:
    case CEIL_DIV_EXPR:
    case FLOOR_DIV_EXPR:
    case ROUND_DIV_EXPR:
    case EXACT_DIV_EXPR:
    case BIT_AND_EXPR:
    case BIT_ANDTC_EXPR:
    case BIT_IOR_EXPR:
    case BIT_XOR_EXPR:
    case TRUNC_MOD_EXPR:
    case FLOOR_MOD_EXPR:
    case TRUTH_ANDIF_EXPR:
    case TRUTH_ORIF_EXPR:
    case TRUTH_AND_EXPR:
    case TRUTH_OR_EXPR:
    case RSHIFT_EXPR:
    case LSHIFT_EXPR:
    case RROTATE_EXPR:
    case LROTATE_EXPR:
    case EQ_EXPR:
    case NE_EXPR:
    case MAX_EXPR:
    case MIN_EXPR:
    case LE_EXPR:
    case GE_EXPR:
    case LT_EXPR:
    case GT_EXPR:
    case COMPONENT_REF:
    case ARRAY_REF:
    case COMPOUND_EXPR:
    case SCOPE_REF:
    case DOTSTAR_EXPR:
    case MEMBER_REF:
      return build_nt
6254 6255
	(code, tsubst_copy (TREE_OPERAND (t, 0), args, in_decl),
	 tsubst_copy (TREE_OPERAND (t, 1), args, in_decl));
mrs's avatar
mrs committed
6256 6257 6258 6259

    case CALL_EXPR:
      {
	tree fn = TREE_OPERAND (t, 0);
jason's avatar
jason committed
6260
	if (is_overloaded_fn (fn))
6261
	  fn = tsubst_copy (get_first_fn (fn), args, in_decl);
mrs's avatar
mrs committed
6262
	else
jason's avatar
jason committed
6263
	  /* Sometimes FN is a LOOKUP_EXPR.  */
6264
	  fn = tsubst_copy (fn, args, in_decl);
mrs's avatar
mrs committed
6265
	return build_nt
6266
	  (code, fn, tsubst_copy (TREE_OPERAND (t, 1), args, in_decl),
mrs's avatar
mrs committed
6267 6268 6269 6270 6271 6272 6273 6274
	   NULL_TREE);
      }

    case METHOD_CALL_EXPR:
      {
	tree name = TREE_OPERAND (t, 0);
	if (TREE_CODE (name) == BIT_NOT_EXPR)
	  {
6275
	    name = tsubst_copy (TREE_OPERAND (name, 0), args, in_decl);
6276
	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
mrs's avatar
mrs committed
6277 6278 6279 6280
	  }
	else if (TREE_CODE (name) == SCOPE_REF
		 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
	  {
6281
	    tree base = tsubst_copy (TREE_OPERAND (name, 0), args, in_decl);
mrs's avatar
mrs committed
6282
	    name = TREE_OPERAND (name, 1);
6283
	    name = tsubst_copy (TREE_OPERAND (name, 0), args, in_decl);
6284
	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
mrs's avatar
mrs committed
6285 6286 6287
	    name = build_nt (SCOPE_REF, base, name);
	  }
	else
6288
	  name = tsubst_copy (TREE_OPERAND (t, 0), args, in_decl);
mrs's avatar
mrs committed
6289
	return build_nt
6290 6291
	  (code, name, tsubst_copy (TREE_OPERAND (t, 1), args, in_decl),
	   tsubst_copy (TREE_OPERAND (t, 2), args, in_decl),
mrs's avatar
mrs committed
6292 6293 6294
	   NULL_TREE);
      }

6295
    case BIND_EXPR:
mrs's avatar
mrs committed
6296 6297
    case COND_EXPR:
    case MODOP_EXPR:
6298
      {
6299
	r = build_nt
6300 6301 6302
	  (code, tsubst_copy (TREE_OPERAND (t, 0), args, in_decl),
	   tsubst_copy (TREE_OPERAND (t, 1), args, in_decl),
	   tsubst_copy (TREE_OPERAND (t, 2), args, in_decl));
6303 6304 6305 6306 6307 6308 6309 6310 6311

	if (code == BIND_EXPR && !processing_template_decl)
	  {
	    /* This processing  should really occur in tsubst_expr,
	       However, tsubst_expr does not recurse into expressions,
	       since it assumes that there aren't any statements
	       inside them.  Instead, it simply calls
	       build_expr_from_tree.  So, we need to expand the
	       BIND_EXPR here.  */ 
6312
	    tree rtl_expr = begin_stmt_expr ();
6313
	    tree block = tsubst_expr (TREE_OPERAND (r, 1), args, in_decl);
6314
	    r = finish_stmt_expr (rtl_expr, block);
6315 6316 6317 6318
	  }

	return r;
      }
mrs's avatar
mrs committed
6319 6320 6321

    case NEW_EXPR:
      {
6322
	r = build_nt
6323 6324 6325
	(code, tsubst_copy (TREE_OPERAND (t, 0), args, in_decl),
	 tsubst_copy (TREE_OPERAND (t, 1), args, in_decl),
	 tsubst_copy (TREE_OPERAND (t, 2), args, in_decl));
mrs's avatar
mrs committed
6326 6327 6328 6329 6330 6331
	NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
	return r;
      }

    case DELETE_EXPR:
      {
6332
	r = build_nt
6333 6334
	(code, tsubst_copy (TREE_OPERAND (t, 0), args, in_decl),
	 tsubst_copy (TREE_OPERAND (t, 1), args, in_decl));
mrs's avatar
mrs committed
6335 6336 6337 6338 6339
	DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
	DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
	return r;
      }

6340 6341
    case TEMPLATE_ID_EXPR:
      {
6342
        /* Substituted template arguments */
6343
	tree targs = tsubst_copy (TREE_OPERAND (t, 1), args, in_decl);
6344 6345 6346 6347 6348
	tree chain;
	for (chain = targs; chain; chain = TREE_CHAIN (chain))
	  TREE_VALUE (chain) = maybe_fold_nontype_arg (TREE_VALUE (chain));

	return lookup_template_function
6349
	  (tsubst_copy (TREE_OPERAND (t, 0), args, in_decl), targs);
6350 6351
      }

mrs's avatar
mrs committed
6352 6353 6354 6355 6356 6357 6358 6359 6360
    case TREE_LIST:
      {
	tree purpose, value, chain;

	if (t == void_list_node)
	  return t;

	purpose = TREE_PURPOSE (t);
	if (purpose)
6361
	  purpose = tsubst_copy (purpose, args, in_decl);
mrs's avatar
mrs committed
6362 6363
	value = TREE_VALUE (t);
	if (value)
6364
	  value = tsubst_copy (value, args, in_decl);
mrs's avatar
mrs committed
6365 6366
	chain = TREE_CHAIN (t);
	if (chain && chain != void_type_node)
6367
	  chain = tsubst_copy (chain, args, in_decl);
mrs's avatar
mrs committed
6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379
	if (purpose == TREE_PURPOSE (t)
	    && value == TREE_VALUE (t)
	    && chain == TREE_CHAIN (t))
	  return t;
	return tree_cons (purpose, value, chain);
      }

    case RECORD_TYPE:
    case UNION_TYPE:
    case ENUMERAL_TYPE:
    case INTEGER_TYPE:
    case TEMPLATE_TYPE_PARM:
6380
    case TEMPLATE_TEMPLATE_PARM:
jason's avatar
jason committed
6381
    case TEMPLATE_PARM_INDEX:
mrs's avatar
mrs committed
6382 6383 6384 6385 6386 6387 6388
    case POINTER_TYPE:
    case REFERENCE_TYPE:
    case OFFSET_TYPE:
    case FUNCTION_TYPE:
    case METHOD_TYPE:
    case ARRAY_TYPE:
    case TYPENAME_TYPE:
jason's avatar
jason committed
6389
    case TYPE_DECL:
6390
      return tsubst (t, args, in_decl);
mrs's avatar
mrs committed
6391

mrs's avatar
mrs committed
6392
    case IDENTIFIER_NODE:
6393 6394 6395 6396
      if (IDENTIFIER_TYPENAME_P (t)
	  /* Make sure it's not just a variable named `__opr', for instance,
	     which can occur in some existing code.  */
	  && TREE_TYPE (t))
mrs's avatar
mrs committed
6397
	return build_typename_overload
6398
	  (tsubst (TREE_TYPE (t), args, in_decl));
mrs's avatar
mrs committed
6399 6400 6401
      else
	return t;

mrs's avatar
mrs committed
6402
    case CONSTRUCTOR:
6403 6404 6405 6406 6407 6408 6409
      {
	r = build
	  (CONSTRUCTOR, tsubst (TREE_TYPE (t), args, in_decl), NULL_TREE,
	   tsubst_copy (CONSTRUCTOR_ELTS (t), args, in_decl));
	TREE_HAS_CONSTRUCTOR (r) = TREE_HAS_CONSTRUCTOR (t);
	return r;
      }
mrs's avatar
mrs committed
6410

mrs's avatar
mrs committed
6411 6412 6413 6414 6415
    default:
      return t;
    }
}

6416 6417
/* Like tsubst_copy, but also does semantic processing and RTL expansion.  */

mrs's avatar
mrs committed
6418
tree
6419
tsubst_expr (t, args, in_decl)
6420
     tree t, args;
mrs's avatar
mrs committed
6421 6422 6423 6424 6425
     tree in_decl;
{
  if (t == NULL_TREE || t == error_mark_node)
    return t;

mrs's avatar
mrs committed
6426
  if (processing_template_decl)
6427
    return tsubst_copy (t, args, in_decl);
mrs's avatar
mrs committed
6428 6429

  switch (TREE_CODE (t))
mrs's avatar
mrs committed
6430
    {
mrs's avatar
mrs committed
6431 6432
    case RETURN_STMT:
      lineno = TREE_COMPLEXITY (t);
6433 6434
      finish_return_stmt (tsubst_expr (RETURN_EXPR (t),
				       args, in_decl));
mrs's avatar
mrs committed
6435 6436 6437 6438
      break;

    case EXPR_STMT:
      lineno = TREE_COMPLEXITY (t);
6439 6440
      finish_expr_stmt (tsubst_expr (EXPR_STMT_EXPR (t),
				     args, in_decl));
mrs's avatar
mrs committed
6441 6442 6443 6444 6445
      break;

    case DECL_STMT:
      {
	int i = suspend_momentary ();
mrs's avatar
mrs committed
6446
	tree dcl, init;
mrs's avatar
mrs committed
6447 6448 6449 6450

	lineno = TREE_COMPLEXITY (t);
	emit_line_note (input_filename, lineno);
	dcl = start_decl
6451 6452
	  (tsubst (TREE_OPERAND (t, 0), args, in_decl),
	   tsubst (TREE_OPERAND (t, 1), args, in_decl),
bkoz's avatar
d  
bkoz committed
6453
	   TREE_OPERAND (t, 2) != 0, NULL_TREE, NULL_TREE);
6454
	init = tsubst_expr (TREE_OPERAND (t, 2), args, in_decl);
mrs's avatar
mrs committed
6455
	cp_finish_decl
mrs's avatar
mrs committed
6456
	  (dcl, init, NULL_TREE, 1, /*init ? LOOKUP_ONLYCONVERTING :*/ 0);
mrs's avatar
mrs committed
6457 6458 6459
	resume_momentary (i);
	return dcl;
      }
mrs's avatar
mrs committed
6460

mrs's avatar
mrs committed
6461 6462 6463 6464 6465
    case FOR_STMT:
      {
	tree tmp;
	lineno = TREE_COMPLEXITY (t);

6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476
	begin_for_stmt ();
	for (tmp = FOR_INIT_STMT (t); tmp; tmp = TREE_CHAIN (tmp))
	  tsubst_expr (tmp, args, in_decl);
	finish_for_init_stmt (NULL_TREE);
	finish_for_cond (tsubst_expr (FOR_COND (t), args,
				      in_decl),
			 NULL_TREE);
	tmp = tsubst_expr (FOR_EXPR (t), args, in_decl);
	finish_for_expr (tmp, NULL_TREE);
	tsubst_expr (FOR_BODY (t), args, in_decl);
	finish_for_stmt (tmp, NULL_TREE);
mrs's avatar
mrs committed
6477 6478
      }
      break;
mrs's avatar
mrs committed
6479

mrs's avatar
mrs committed
6480 6481 6482
    case WHILE_STMT:
      {
	lineno = TREE_COMPLEXITY (t);
6483 6484 6485 6486 6487 6488
	begin_while_stmt ();
	finish_while_stmt_cond (tsubst_expr (WHILE_COND (t),
					     args, in_decl),
				NULL_TREE);
	tsubst_expr (WHILE_BODY (t), args, in_decl);
	finish_while_stmt (NULL_TREE);
mrs's avatar
mrs committed
6489 6490
      }
      break;
mrs's avatar
mrs committed
6491

mrs's avatar
mrs committed
6492 6493 6494
    case DO_STMT:
      {
	lineno = TREE_COMPLEXITY (t);
6495 6496 6497 6498 6499 6500
	begin_do_stmt ();
	tsubst_expr (DO_BODY (t), args, in_decl);
	finish_do_body (NULL_TREE);
	finish_do_stmt (tsubst_expr (DO_COND (t), args,
				     in_decl),
			NULL_TREE);
mrs's avatar
mrs committed
6501 6502
      }
      break;
mrs's avatar
mrs committed
6503

mrs's avatar
mrs committed
6504
    case IF_STMT:
mrs's avatar
mrs committed
6505
      {
mrs's avatar
mrs committed
6506 6507 6508
	tree tmp;

	lineno = TREE_COMPLEXITY (t);
6509 6510 6511 6512
	begin_if_stmt ();
	finish_if_stmt_cond (tsubst_expr (IF_COND (t),
					  args, in_decl),
			     NULL_TREE);
mrs's avatar
mrs committed
6513

6514
	if (tmp = THEN_CLAUSE (t), tmp)
mrs's avatar
mrs committed
6515
	  {
6516
	    tsubst_expr (tmp, args, in_decl);
6517
	    finish_then_clause (NULL_TREE);
mrs's avatar
mrs committed
6518 6519
	  }

6520 6521 6522 6523 6524 6525
	if (tmp = ELSE_CLAUSE (t), tmp)
	  {
	    begin_else_clause ();
	    tsubst_expr (tmp, args, in_decl);
	    finish_else_clause (NULL_TREE);
	  }
mrs's avatar
mrs committed
6526

6527
	finish_if_stmt ();
mrs's avatar
mrs committed
6528
      }
mrs's avatar
mrs committed
6529
      break;
mrs's avatar
mrs committed
6530

mrs's avatar
mrs committed
6531 6532
    case COMPOUND_STMT:
      {
6533
	tree substmt;
mrs's avatar
mrs committed
6534

mrs's avatar
mrs committed
6535
	lineno = TREE_COMPLEXITY (t);
6536 6537 6538 6539
	begin_compound_stmt (COMPOUND_STMT_NO_SCOPE (t));
	for (substmt = COMPOUND_BODY (t); 
	     substmt != NULL_TREE;
	     substmt = TREE_CHAIN (substmt))
6540
	  tsubst_expr (substmt, args, in_decl);
6541 6542
	return finish_compound_stmt (COMPOUND_STMT_NO_SCOPE (t), 
				     NULL_TREE);
mrs's avatar
mrs committed
6543 6544
      }
      break;
mrs's avatar
mrs committed
6545

mrs's avatar
mrs committed
6546 6547
    case BREAK_STMT:
      lineno = TREE_COMPLEXITY (t);
6548
      finish_break_stmt ();
mrs's avatar
mrs committed
6549
      break;
mrs's avatar
mrs committed
6550

mrs's avatar
mrs committed
6551 6552
    case CONTINUE_STMT:
      lineno = TREE_COMPLEXITY (t);
6553
      finish_continue_stmt ();
mrs's avatar
mrs committed
6554 6555
      break;

mrs's avatar
mrs committed
6556 6557 6558 6559 6560
    case SWITCH_STMT:
      {
	tree val, tmp;

	lineno = TREE_COMPLEXITY (t);
6561 6562 6563
	begin_switch_stmt ();
	val = tsubst_expr (SWITCH_COND (t), args, in_decl);
	finish_switch_cond (val);
mrs's avatar
mrs committed
6564 6565
	
	if (tmp = TREE_OPERAND (t, 1), tmp)
6566
	  tsubst_expr (tmp, args, in_decl);
mrs's avatar
mrs committed
6567

6568
	finish_switch_stmt (val, NULL_TREE);
mrs's avatar
mrs committed
6569 6570 6571 6572
      }
      break;

    case CASE_LABEL:
6573 6574
      finish_case_label (tsubst_expr (CASE_LOW (t), args, in_decl),
			 tsubst_expr (CASE_HIGH (t), args, in_decl));
mrs's avatar
mrs committed
6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585
      break;

    case LABEL_DECL:
      t = define_label (DECL_SOURCE_FILE (t), DECL_SOURCE_LINE (t),
			DECL_NAME (t));
      if (t)
	expand_label (t);
      break;

    case GOTO_STMT:
      lineno = TREE_COMPLEXITY (t);
mmitchel's avatar
 
mmitchel committed
6586 6587 6588 6589 6590 6591 6592
      t = GOTO_DESTINATION (t);
      if (TREE_CODE (t) != IDENTIFIER_NODE)
	/* Computed goto's must be tsubst'd into.  On the other hand,
	   non-computed gotos must not be; the identifier in question
	   will have no binding.  */
	t = tsubst_expr (t, args, in_decl);
      finish_goto_stmt (t);
6593 6594 6595 6596 6597 6598 6599 6600 6601
      break;

    case ASM_STMT:
      lineno = TREE_COMPLEXITY (t);
      finish_asm_stmt (tsubst_expr (ASM_CV_QUAL (t), args, in_decl),
		       tsubst_expr (ASM_STRING (t), args, in_decl),
		       tsubst_expr (ASM_OUTPUTS (t), args, in_decl),
		       tsubst_expr (ASM_INPUTS (t), args, in_decl), 
		       tsubst_expr (ASM_CLOBBERS (t), args, in_decl));
mrs's avatar
mrs committed
6602
      break;
mrs's avatar
mrs committed
6603 6604 6605

    case TRY_BLOCK:
      lineno = TREE_COMPLEXITY (t);
6606 6607 6608
      begin_try_block ();
      tsubst_expr (TRY_STMTS (t), args, in_decl);
      finish_try_block (NULL_TREE);
mrs's avatar
mrs committed
6609
      {
6610
	tree handler = TRY_HANDLERS (t);
mrs's avatar
mrs committed
6611
	for (; handler; handler = TREE_CHAIN (handler))
6612
	  tsubst_expr (handler, args, in_decl);
mrs's avatar
mrs committed
6613
      }
6614
      finish_handler_sequence (NULL_TREE);
mrs's avatar
mrs committed
6615 6616 6617 6618
      break;

    case HANDLER:
      lineno = TREE_COMPLEXITY (t);
6619 6620
      begin_handler ();
      if (HANDLER_PARMS (t))
mrs's avatar
mrs committed
6621
	{
6622
	  tree d = HANDLER_PARMS (t);
mrs's avatar
mrs committed
6623
	  expand_start_catch_block
6624 6625
	    (tsubst (TREE_OPERAND (d, 1), args, in_decl),
	     tsubst (TREE_OPERAND (d, 0), args, in_decl));
mrs's avatar
mrs committed
6626 6627 6628
	}
      else
	expand_start_catch_block (NULL_TREE, NULL_TREE);
6629 6630 6631
      finish_handler_parms (NULL_TREE);
      tsubst_expr (HANDLER_BODY (t), args, in_decl);
      finish_handler (NULL_TREE);
mrs's avatar
mrs committed
6632 6633
      break;

mrs's avatar
mrs committed
6634 6635 6636 6637
    case TAG_DEFN:
      lineno = TREE_COMPLEXITY (t);
      t = TREE_TYPE (t);
      if (TREE_CODE (t) == ENUMERAL_TYPE)
6638
	tsubst (t, args, NULL_TREE);
mrs's avatar
mrs committed
6639 6640
      break;

mrs's avatar
mrs committed
6641
    default:
6642
      return build_expr_from_tree (tsubst_copy (t, args, in_decl));
mrs's avatar
mrs committed
6643 6644
    }
  return NULL_TREE;
mrs's avatar
mrs committed
6645 6646
}

6647
/* Instantiate the indicated variable or function template TMPL with
6648 6649
   the template arguments in TARG_PTR.  */

mrs's avatar
mrs committed
6650 6651
tree
instantiate_template (tmpl, targ_ptr)
6652
     tree tmpl, targ_ptr;
mrs's avatar
mrs committed
6653
{
mrs's avatar
mrs committed
6654
  tree fndecl;
6655 6656
  tree gen_tmpl;
  tree spec;
mrs's avatar
mrs committed
6657 6658 6659
  int i, len;
  struct obstack *old_fmp_obstack;
  extern struct obstack *function_maybepermanent_obstack;
6660
  tree inner_args;
mrs's avatar
mrs committed
6661

6662 6663 6664
  if (tmpl == error_mark_node)
    return error_mark_node;

6665 6666
  my_friendly_assert (TREE_CODE (tmpl) == TEMPLATE_DECL, 283);

6667 6668 6669 6670 6671 6672
  /* Check to see if we already have this specialization.  */
  spec = retrieve_specialization (tmpl, targ_ptr);
  if (spec != NULL_TREE)
    return spec;

  if (DECL_TEMPLATE_INFO (tmpl))
6673
    {
6674 6675 6676 6677 6678 6679 6680 6681 6682
      /* The TMPL is a partial instantiation.  To get a full set of
	 arguments we must add the arguments used to perform the
	 partial instantiation.  */
      targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
					      targ_ptr);
      gen_tmpl = most_general_template (tmpl);

      /* Check to see if we already have this specialization.  */
      spec = retrieve_specialization (gen_tmpl, targ_ptr);
6683 6684
      if (spec != NULL_TREE)
	return spec;
6685
    }
6686 6687
  else
    gen_tmpl = tmpl;
6688

mrs's avatar
mrs committed
6689 6690 6691
  push_obstacks (&permanent_obstack, &permanent_obstack);
  old_fmp_obstack = function_maybepermanent_obstack;
  function_maybepermanent_obstack = &permanent_obstack;
mrs's avatar
mrs committed
6692

6693 6694
  len = DECL_NTPARMS (gen_tmpl);
  inner_args = innermost_args (targ_ptr);
mrs's avatar
mrs committed
6695 6696
  i = len;
  while (i--)
mrs's avatar
mrs committed
6697
    {
6698
      tree t = TREE_VEC_ELT (inner_args, i);
mrs's avatar
mrs committed
6699 6700 6701
      if (TREE_CODE_CLASS (TREE_CODE (t)) == 't')
	{
	  tree nt = target_type (t);
mrs's avatar
mrs committed
6702
	  if (IS_AGGR_TYPE (nt) && decl_function_context (TYPE_MAIN_DECL (nt)))
mrs's avatar
mrs committed
6703
	    {
jason's avatar
jason committed
6704 6705
	      cp_error ("type `%T' composed from a local class is not a valid template-argument", t);
	      cp_error ("  trying to instantiate `%D'", gen_tmpl);
mrs's avatar
mrs committed
6706 6707 6708 6709
	      fndecl = error_mark_node;
	      goto out;
	    }
	}
mrs's avatar
mrs committed
6710
    }
6711
  targ_ptr = copy_to_permanent (targ_ptr);
mrs's avatar
mrs committed
6712

mrs's avatar
mrs committed
6713
  /* substitute template parameters */
6714 6715 6716 6717
  fndecl = tsubst (DECL_RESULT (gen_tmpl), targ_ptr, gen_tmpl);
  /* The DECL_TI_TEMPLATE should always be the immediate parent
     template, not the most general template.  */
  DECL_TI_TEMPLATE (fndecl) = tmpl;
mrs's avatar
mrs committed
6718

mrs's avatar
mrs committed
6719 6720 6721
  if (flag_external_templates)
    add_pending_template (fndecl);

mrs's avatar
mrs committed
6722 6723 6724
 out:
  function_maybepermanent_obstack = old_fmp_obstack;
  pop_obstacks ();
mrs's avatar
mrs committed
6725

mrs's avatar
mrs committed
6726
  return fndecl;
mrs's avatar
mrs committed
6727
}
mrs's avatar
mrs committed
6728 6729

/* Push the name of the class template into the scope of the instantiation.  */
mrs's avatar
mrs committed
6730 6731

void
mrs's avatar
mrs committed
6732 6733
overload_template_name (type)
     tree type;
mrs's avatar
mrs committed
6734
{
mrs's avatar
mrs committed
6735 6736
  tree id = DECL_NAME (CLASSTYPE_TI_TEMPLATE (type));
  tree decl;
mrs's avatar
mrs committed
6737

mrs's avatar
mrs committed
6738 6739 6740
  if (IDENTIFIER_CLASS_VALUE (id)
      && TREE_TYPE (IDENTIFIER_CLASS_VALUE (id)) == type)
    return;
mrs's avatar
mrs committed
6741

mrs's avatar
mrs committed
6742 6743 6744
  decl = build_decl (TYPE_DECL, id, type);
  SET_DECL_ARTIFICIAL (decl);
  pushdecl_class_level (decl);
mrs's avatar
mrs committed
6745 6746
}

law's avatar
law committed
6747
/* Like type_unification but designed specially to handle conversion
6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759
   operators.  

   The FN is a TEMPLATE_DECL for a function.  The ARGS are the
   arguments that are being used when calling it.  

   If FN is a conversion operator, RETURN_TYPE is the type desired as
   the result of the conversion operator.

   The EXTRA_FN_ARG, if any, is the type of an additional
   parameter to be added to the beginning of FN's parameter list.  

   The other arguments are as for type_unification.  */
6760 6761

int
6762 6763
fn_type_unification (fn, explicit_targs, targs, args, return_type,
		     strict, extra_fn_arg)
6764
     tree fn, explicit_targs, targs, args, return_type;
6765
     unification_kind_t strict;
6766
     tree extra_fn_arg;
6767
{
6768
  tree parms;
6769 6770 6771

  my_friendly_assert (TREE_CODE (fn) == TEMPLATE_DECL, 0);

6772 6773
  parms = TYPE_ARG_TYPES (TREE_TYPE (fn));

6774
  if (DECL_CONV_FN_P (fn))
6775 6776 6777
    {
      /* This is a template conversion operator.  Use the return types
         as well as the argument types.  */
6778 6779 6780 6781
      parms = scratch_tree_cons (NULL_TREE, 
				 TREE_TYPE (TREE_TYPE (fn)),
				 parms);
      args = scratch_tree_cons (NULL_TREE, return_type, args);
6782 6783
    }

6784
  if (extra_fn_arg != NULL_TREE)
6785
    parms = scratch_tree_cons (NULL_TREE, extra_fn_arg, parms);
6786

6787 6788 6789 6790
  /* We allow incomplete unification without an error message here
     because the standard doesn't seem to explicitly prohibit it.  Our
     callers must be ready to deal with unification failures in any
     event.  */
6791 6792 6793 6794 6795 6796
  return type_unification (DECL_INNERMOST_TEMPLATE_PARMS (fn), 
			   targs,
			   parms,
			   args,
			   explicit_targs,
			   strict, 1);
6797 6798 6799
}


mrs's avatar
mrs committed
6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810
/* Type unification.

   We have a function template signature with one or more references to
   template parameters, and a parameter list we wish to fit to this
   template.  If possible, produce a list of parameters for the template
   which will cause it to fit the supplied parameter list.

   Return zero for success, 2 for an incomplete match that doesn't resolve
   all the types, and 1 for complete failure.  An error message will be
   printed only for an incomplete match.

6811
   TPARMS[NTPARMS] is an array of template parameter types.
mrs's avatar
mrs committed
6812

6813 6814 6815 6816 6817 6818 6819
   TARGS[NTPARMS] is the array into which the deduced template
   parameter values are placed.  PARMS is the function template's
   signature (using TEMPLATE_PARM_IDX nodes), and ARGS is the argument
   list we're trying to match against it.

   The EXPLICIT_TARGS are explicit template arguments provided via a
   template-id.
mrs's avatar
mrs committed
6820

6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835
   The parameter STRICT is one of:

   DEDUCE_CALL: 
     We are deducing arguments for a function call, as in
     [temp.deduct.call].

   DEDUCE_CONV:
     We are deducing arguments for a conversion function, as in 
     [temp.deduct.conv].

   DEDUCE_EXACT:
     We are deducing arguments when calculating the partial
     ordering between specializations of function or class
     templates, as in [temp.func.order] and [temp.class.order],
     when doing an explicit instantiation as in [temp.explicit],
6836
     when determining an explicit specialization as in
6837 6838
     [temp.expl.spec], or when taking the address of a function
     template, as in [temp.deduct.funcaddr].  */
mrs's avatar
mrs committed
6839 6840

int
6841
type_unification (tparms, targs, parms, args, explicit_targs,
6842
		  strict, allow_incomplete)
6843
     tree tparms, targs, parms, args, explicit_targs;
6844 6845
     unification_kind_t strict;
     int allow_incomplete;
6846
{
6847
  int* explicit_mask;
6848 6849
  int i;

6850
  for (i = 0; i < TREE_VEC_LENGTH (tparms); i++)
6851
    TREE_VEC_ELT (targs, i) = NULL_TREE;
6852

6853
  if (explicit_targs != NULL_TREE)
6854 6855
    {
      tree arg_vec;
6856
      arg_vec = coerce_template_parms (tparms, explicit_targs, NULL_TREE, 0,
6857
				       0);
6858 6859 6860

      if (arg_vec == error_mark_node)
	return 1;
6861

6862
      explicit_mask = alloca (sizeof (int) * TREE_VEC_LENGTH (targs));
ghazi's avatar
ghazi committed
6863
      bzero ((char *) explicit_mask, sizeof(int) * TREE_VEC_LENGTH (targs));
6864

6865 6866
      for (i = 0; 
	   i < TREE_VEC_LENGTH (arg_vec) 
6867
	     && TREE_VEC_ELT (arg_vec, i) != NULL_TREE;  
6868
	   ++i)
6869 6870 6871 6872 6873
	{
	  TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (arg_vec, i);
	  /* Let unify know that this argument was explicit.  */
	  explicit_mask [i] = 1;
	}
6874
    }
6875 6876
  else
    explicit_mask = 0;
6877

6878 6879 6880 6881 6882 6883 6884
  return 
    type_unification_real (tparms, targs, parms, args, 0,
			   strict, allow_incomplete, explicit_mask); 
}

/* Adjust types before performing type deduction, as described in
   [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
mmitchel's avatar
mmitchel committed
6885 6886 6887 6888
   sections are symmetric.  PARM is the type of a function parameter
   or the return type of the conversion function.  ARG is the type of
   the argument passed to the call, or the type of the value
   intialized with the result of the conversion function.  */
6889

6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902
void
maybe_adjust_types_for_deduction (strict, parm, arg)
     unification_kind_t strict;
     tree* parm;
     tree* arg;
{
  switch (strict)
    {
    case DEDUCE_CALL:
      break;

    case DEDUCE_CONV:
      {
mmitchel's avatar
mmitchel committed
6903 6904 6905
	/* Swap PARM and ARG throughout the remainder of this
	   function; the handling is precisely symmetric since PARM
	   will initialize ARG rather than vice versa.  */
6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955
	tree* temp = parm;
	parm = arg;
	arg = temp;
	break;
      }

    case DEDUCE_EXACT:
      /* There is nothing to do in this case.  */
      return;

    default:
      my_friendly_abort (0);
    }

  if (TREE_CODE (*parm) != REFERENCE_TYPE)
    {
      /* [temp.deduct.call]
	 
	 If P is not a reference type:
	 
	 --If A is an array type, the pointer type produced by the
	 array-to-pointer standard conversion (_conv.array_) is
	 used in place of A for type deduction; otherwise,
	 
	 --If A is a function type, the pointer type produced by
	 the function-to-pointer standard conversion
	 (_conv.func_) is used in place of A for type deduction;
	 otherwise,
	 
	 --If A is a cv-qualified type, the top level
	 cv-qualifiers of A's type are ignored for type
	 deduction.  */
      if (TREE_CODE (*arg) == ARRAY_TYPE)
	*arg = build_pointer_type (TREE_TYPE (*arg));
      else if (TREE_CODE (*arg) == FUNCTION_TYPE
	  || TREE_CODE (*arg) == METHOD_TYPE)
	*arg = build_pointer_type (*arg);
      else
	*arg = TYPE_MAIN_VARIANT (*arg);
    }
  
  /* [temp.deduct.call]
     
     If P is a cv-qualified type, the top level cv-qualifiers
     of P's type are ignored for type deduction.  If P is a
     reference type, the type referred to by P is used for
     type deduction.  */
  *parm = TYPE_MAIN_VARIANT (*parm);
  if (TREE_CODE (*parm) == REFERENCE_TYPE)
    *parm = TREE_TYPE (*parm);
6956 6957
}

6958 6959
/* Like type_unfication.  EXPLICIT_MASK, if non-NULL, is an array of
   integers, with ones in positions corresponding to arguments in
6960 6961 6962 6963 6964
   targs that were provided explicitly, and zeros elsewhere.  

   If SUBR is 1, we're being called recursively (to unify the
   arguments of a function or method parameter of a function
   template).  */
6965

6966
static int
6967
type_unification_real (tparms, targs, parms, args, subr,
6968 6969
		       strict, allow_incomplete, explicit_mask)
     tree tparms, targs, parms, args;
6970 6971 6972
     int subr;
     unification_kind_t strict;
     int allow_incomplete;
6973
     int* explicit_mask;
mrs's avatar
mrs committed
6974 6975 6976 6977
{
  tree parm, arg;
  int i;
  int ntparms = TREE_VEC_LENGTH (tparms);
6978
  int sub_strict;
mrs's avatar
mrs committed
6979 6980

  my_friendly_assert (TREE_CODE (tparms) == TREE_VEC, 289);
6981 6982
  my_friendly_assert (parms == NULL_TREE 
		      || TREE_CODE (parms) == TREE_LIST, 290);
mrs's avatar
mrs committed
6983
  /* ARGS could be NULL (via a call from parse.y to
mrs's avatar
mrs committed
6984 6985 6986 6987 6988
     build_x_function_call).  */
  if (args)
    my_friendly_assert (TREE_CODE (args) == TREE_LIST, 291);
  my_friendly_assert (ntparms > 0, 292);

6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006
  switch (strict)
    {
    case DEDUCE_CALL:
      sub_strict = UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_DERIVED;
      break;
      
    case DEDUCE_CONV:
      sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
      break;

    case DEDUCE_EXACT:
      sub_strict = UNIFY_ALLOW_NONE;
      break;
      
    default:
      my_friendly_abort (0);
    }

mrs's avatar
mrs committed
7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019
  while (parms
	 && parms != void_list_node
	 && args
	 && args != void_list_node)
    {
      parm = TREE_VALUE (parms);
      parms = TREE_CHAIN (parms);
      arg = TREE_VALUE (args);
      args = TREE_CHAIN (args);

      if (arg == error_mark_node)
	return 1;
      if (arg == unknown_type_node)
7020 7021 7022
	/* We can't deduce anything from this, but we might get all the
	   template args from other function args.  */
	continue;
mrs's avatar
mrs committed
7023

7024 7025 7026 7027 7028
      /* Conversions will be performed on a function argument that
	 corresponds with a function parameter that contains only
	 non-deducible template parameters and explicitly specified
	 template parameters.  */
      if (! uses_template_parms (parm))
mrs's avatar
mrs committed
7029
	{
7030 7031 7032 7033 7034 7035 7036 7037 7038 7039
	  tree type;

	  if (TREE_CODE_CLASS (TREE_CODE (arg)) != 't')
	    type = TREE_TYPE (arg);
	  else
	    {
	      type = arg;
	      arg = NULL_TREE;
	    }

7040
	  if (strict == DEDUCE_EXACT)
7041
	    {
7042
	      if (same_type_p (parm, type))
7043 7044 7045
		continue;
	    }
	  else
7046 7047 7048 7049
	    /* It might work; we shouldn't check now, because we might
	       get into infinite recursion.  Overload resolution will
	       handle it.  */
	    continue;
7050

mrs's avatar
mrs committed
7051 7052 7053
	  return 1;
	}
	
mrs's avatar
mrs committed
7054 7055 7056 7057 7058 7059 7060 7061 7062
#if 0
      if (TREE_CODE (arg) == VAR_DECL)
	arg = TREE_TYPE (arg);
      else if (TREE_CODE_CLASS (TREE_CODE (arg)) == 'e')
	arg = TREE_TYPE (arg);
#else
      if (TREE_CODE_CLASS (TREE_CODE (arg)) != 't')
	{
	  my_friendly_assert (TREE_TYPE (arg) != NULL_TREE, 293);
7063
	  if (type_unknown_p (arg))
mrs's avatar
mrs committed
7064
	    {
7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075
	      /* [temp.deduct.type] A template-argument can be deduced from
		 a pointer to function or pointer to member function
		 argument if the set of overloaded functions does not
		 contain function templates and at most one of a set of
		 overloaded functions provides a unique match.  */

	      if (resolve_overloaded_unification
		  (tparms, targs, parm, arg, strict, sub_strict, explicit_mask)
		  != 0)
		return 1;
	      continue;
mrs's avatar
mrs committed
7076
	    }
mrs's avatar
mrs committed
7077 7078 7079
	  arg = TREE_TYPE (arg);
	}
#endif
7080 7081
      if (!subr)
	maybe_adjust_types_for_deduction (strict, &parm, &arg);
mrs's avatar
mrs committed
7082

7083
      switch (unify (tparms, targs, parm, arg, sub_strict,
7084
		     explicit_mask)) 
mrs's avatar
mrs committed
7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102
	{
	case 0:
	  break;
	case 1:
	  return 1;
	}
    }
  /* Fail if we've reached the end of the parm list, and more args
     are present, and the parm list isn't variadic.  */
  if (args && args != void_list_node && parms == void_list_node)
    return 1;
  /* Fail if parms are left and they don't have default values.	 */
  if (parms
      && parms != void_list_node
      && TREE_PURPOSE (parms) == NULL_TREE)
    return 1;
  if (!subr)
    for (i = 0; i < ntparms; i++)
7103
      if (TREE_VEC_ELT (targs, i) == NULL_TREE)
mrs's avatar
mrs committed
7104
	{
7105
	  if (!allow_incomplete)
jason's avatar
jason committed
7106
	    error ("incomplete type unification");
mrs's avatar
mrs committed
7107 7108 7109 7110 7111
	  return 2;
	}
  return 0;
}

7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150
/* Subroutine of type_unification_real.  Args are like the variables at the
   call site.  ARG is an overloaded function (or template-id); we try
   deducing template args from each of the overloads, and if only one
   succeeds, we go with that.  Modifies TARGS and returns 0 on success.  */

static int
resolve_overloaded_unification (tparms, targs, parm, arg, strict,
				sub_strict, explicit_mask)
     tree tparms, targs, parm, arg;
     unification_kind_t strict;
     int sub_strict;
     int* explicit_mask;
{
  tree tempargs = copy_node (targs);
  int good = 0;

  if (TREE_CODE (arg) == ADDR_EXPR)
    arg = TREE_OPERAND (arg, 0);
  if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
    {
      /* If we got some explicit template args, we need to plug them into
	 the affected templates before we try to unify, in case the
	 explicit args will completely resolve the templates in question.  */

      tree expl_subargs = TREE_OPERAND (arg, 1);
      arg = TREE_OPERAND (arg, 0);

      for (; arg; arg = OVL_NEXT (arg))
	{
	  tree fn = OVL_CURRENT (arg);
	  tree subargs, elem;

	  if (TREE_CODE (fn) != TEMPLATE_DECL)
	    continue;

	  subargs = get_bindings_overload (fn, DECL_RESULT (fn), expl_subargs);
	  if (subargs)
	    {
	      elem = tsubst (TREE_TYPE (fn), subargs, NULL_TREE);
7151
	      good += try_one_overload (tparms, targs, tempargs, parm, elem,
7152 7153 7154 7155 7156 7157 7158
					strict, sub_strict, explicit_mask);
	    }
	}
    }
  else if (TREE_CODE (arg) == OVERLOAD)
    {
      for (; arg; arg = OVL_NEXT (arg))
7159
	good += try_one_overload (tparms, targs, tempargs, parm,
7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192
				  TREE_TYPE (OVL_CURRENT (arg)),
				  strict, sub_strict, explicit_mask);
    }
  else
    my_friendly_abort (981006);

  /* [temp.deduct.type] A template-argument can be deduced from a pointer
     to function or pointer to member function argument if the set of
     overloaded functions does not contain function templates and at most
     one of a set of overloaded functions provides a unique match.

     So if we found multiple possibilities, we return success but don't
     deduce anything.  */

  if (good == 1)
    {
      int i = TREE_VEC_LENGTH (targs);
      for (; i--; )
	if (TREE_VEC_ELT (tempargs, i))
	  TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
    }
  if (good)
    return 0;

  return 1;
}

/* Subroutine of resolve_overloaded_unification; does deduction for a single
   overload.  Fills TARGS with any deduced arguments, or error_mark_node if
   different overloads deduce different arguments for a given parm.
   Returns 1 on success.  */

static int
7193
try_one_overload (tparms, orig_targs, targs, parm, arg, strict,
7194
		  sub_strict, explicit_mask)
7195
     tree tparms, orig_targs, targs, parm, arg;
7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226
     unification_kind_t strict;
     int sub_strict;
     int* explicit_mask;
{
  int nargs;
  tree tempargs;
  int i;

  /* [temp.deduct.type] A template-argument can be deduced from a pointer
     to function or pointer to member function argument if the set of
     overloaded functions does not contain function templates and at most
     one of a set of overloaded functions provides a unique match.

     So if this is a template, just return success.  */

  if (uses_template_parms (arg))
    return 1;

  maybe_adjust_types_for_deduction (strict, &parm, &arg);

  /* We don't copy orig_targs for this because if we have already deduced
     some template args from previous args, unify would complain when we
     try to deduce a template parameter for the same argument, even though
     there isn't really a conflict.  */
  nargs = TREE_VEC_LENGTH (targs);
  tempargs = make_scratch_vec (nargs);

  if (unify (tparms, tempargs, parm, arg, sub_strict, explicit_mask) != 0)
    return 0;

  /* First make sure we didn't deduce anything that conflicts with
7227
     explicitly specified args.  */
7228 7229 7230
  for (i = nargs; i--; )
    {
      tree elt = TREE_VEC_ELT (tempargs, i);
7231
      tree oldelt = TREE_VEC_ELT (orig_targs, i);
7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257

      if (elt == NULL_TREE)
	continue;
      else if (uses_template_parms (elt))
	{
	  /* Since we're unifying against ourselves, we will fill in template
	     args used in the function parm list with our own template parms.
	     Discard them.  */
	  TREE_VEC_ELT (tempargs, i) = NULL_TREE;
	  continue;
	}
      else if (oldelt && ! template_args_equal (oldelt, elt))
	return 0;
    }

  for (i = nargs; i--; )
    {
      tree elt = TREE_VEC_ELT (tempargs, i);

      if (elt)
	TREE_VEC_ELT (targs, i) = elt;
    }

  return 1;
}

7258 7259
/* Returns the level of DECL, which declares a template parameter.  */

mmitchel's avatar
mmitchel committed
7260
int
7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274
template_decl_level (decl)
     tree decl;
{
  switch (TREE_CODE (decl))
    {
    case TYPE_DECL:
    case TEMPLATE_DECL:
      return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));

    case PARM_DECL:
      return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));

    default:
      my_friendly_abort (0);
7275
      return 0;
7276 7277 7278
    }
}

7279 7280 7281
/* Decide whether ARG can be unified with PARM, considering only the
   cv-qualifiers of each type, given STRICT as documented for unify.
   Returns non-zero iff the unification is OK on that basis.*/
mrs's avatar
mrs committed
7282

7283 7284 7285 7286 7287 7288 7289
int
check_cv_quals_for_unify (strict, arg, parm)
     int strict;
     tree arg;
     tree parm;
{
  return !((!(strict & UNIFY_ALLOW_MORE_CV_QUAL)
7290
	    && !at_least_as_qualified_p (arg, parm))
7291
	   || (!(strict & UNIFY_ALLOW_LESS_CV_QUAL)
7292
	       && (!at_least_as_qualified_p (parm, arg))));
7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307
}

/* Takes parameters as for type_unification.  Returns 0 if the
   type deduction suceeds, 1 otherwise.  The parameter STRICT is a
   bitwise or of the following flags:

     UNIFY_ALLOW_NONE:
       Require an exact match between PARM and ARG.
     UNIFY_ALLOW_MORE_CV_QUAL:
       Allow the deduced ARG to be more cv-qualified than ARG.
     UNIFY_ALLOW_LESS_CV_QUAL:
       Allow the deduced ARG to be less cv-qualified than ARG.
     UNIFY_ALLOW_DERIVED:
       Allow the deduced ARG to be a template base class of ARG,
       or a pointer to a template base class of the type pointed to by
7308 7309 7310 7311
       ARG.
     UNIFY_ALLOW_INTEGER:
       Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
       case for more information.  */
7312 7313 7314

int
unify (tparms, targs, parm, arg, strict, explicit_mask)
7315
     tree tparms, targs, parm, arg;
7316
     int strict;
7317
     int* explicit_mask;
mrs's avatar
mrs committed
7318 7319
{
  int idx;
7320
  tree targ;
7321
  tree tparm;
mrs's avatar
mrs committed
7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332

  /* I don't think this will do the right thing with respect to types.
     But the only case I've seen it in so far has been array bounds, where
     signedness is the only information lost, and I think that will be
     okay.  */
  while (TREE_CODE (parm) == NOP_EXPR)
    parm = TREE_OPERAND (parm, 0);

  if (arg == error_mark_node)
    return 1;
  if (arg == unknown_type_node)
7333 7334 7335 7336
    /* We can't deduce anything from this, but we might get all the
       template args from other function args.  */
    return 0;

7337 7338 7339 7340 7341
  /* If PARM uses template parameters, then we can't bail out here,
     even in ARG == PARM, since we won't record unifications for the
     template parameters.  We might need them if we're trying to
     figure out which of two things is more specialized.  */
  if (arg == parm && !uses_template_parms (parm))
mrs's avatar
mrs committed
7342 7343
    return 0;

7344 7345 7346
  /* Immediately reject some pairs that won't unify because of
     cv-qualification mismatches.  */
  if (TREE_CODE (arg) == TREE_CODE (parm)
7347
      && TREE_CODE_CLASS (TREE_CODE (arg)) == 't'
7348 7349 7350 7351 7352 7353
      /* We check the cv-qualifiers when unifying with template type
	 parameters below.  We want to allow ARG `const T' to unify with
	 PARM `T' for example, when computing which of two templates
	 is more specialized, for example.  */
      && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
      && !check_cv_quals_for_unify (strict, arg, parm))
7354 7355
    return 1;

mrs's avatar
mrs committed
7356 7357
  switch (TREE_CODE (parm))
    {
7358 7359 7360 7361 7362 7363
    case TYPENAME_TYPE:
      /* In a type which contains a nested-name-specifier, template
	 argument values cannot be deduced for template parameters used
	 within the nested-name-specifier.  */
      return 0;

mrs's avatar
mrs committed
7364
    case TEMPLATE_TYPE_PARM:
7365
    case TEMPLATE_TEMPLATE_PARM:
7366 7367 7368 7369 7370 7371 7372
      tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));

      if (TEMPLATE_TYPE_LEVEL (parm)
	  != template_decl_level (tparm))
	/* The PARM is not one we're trying to unify.  Just check
	   to see if it matches ARG.  */
	return (TREE_CODE (arg) == TREE_CODE (parm)
7373
		&& same_type_p (parm, arg)) ? 0 : 1;
7374
      idx = TEMPLATE_TYPE_IDX (parm);
7375
      targ = TREE_VEC_ELT (targs, idx);
7376
      tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
7377

7378
      /* Check for mixed types and values.  */
7379 7380 7381 7382
      if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
	   && TREE_CODE (tparm) != TYPE_DECL)
	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM 
	      && TREE_CODE (tparm) != TEMPLATE_DECL))
7383 7384
	return 1;

7385 7386
      if (!strict && targ != NULL_TREE 
	  && explicit_mask && explicit_mask[idx])
7387 7388 7389 7390 7391
	/* An explicit template argument.  Don't even try to match
	   here; the overload resolution code will manage check to
	   see whether the call is legal.  */ 
	return 0;

7392
      if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
7393
	{
7394
	  if (TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (parm))
7395 7396 7397
	    {
	      /* We arrive here when PARM does not involve template 
		 specialization.  */
7398

7399 7400 7401
	      /* ARG must be constructed from a template class.  */
	      if (TREE_CODE (arg) != RECORD_TYPE || !CLASSTYPE_TEMPLATE_INFO (arg))
		return 1;
7402

7403
	      {
7404 7405
		tree parmtmpl = TYPE_TI_TEMPLATE (parm);
		tree parmvec = TYPE_TI_ARGS (parm);
7406 7407 7408 7409 7410 7411 7412 7413 7414
		tree argvec = CLASSTYPE_TI_ARGS (arg);
		tree argtmplvec
		  = DECL_INNERMOST_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (arg));
		int i;

		/* The parameter and argument roles have to be switched here 
		   in order to handle default arguments properly.  For example, 
		   template<template <class> class TT> void f(TT<int>) 
		   should be able to accept vector<int> which comes from 
7415
		   template <class T, class Allocator = allocator> 
7416 7417
		   class vector.  */

7418
		if (coerce_template_parms (argtmplvec, parmvec, parmtmpl, 1, 1)
7419 7420
		    == error_mark_node)
		  return 1;
7421
	  
7422 7423 7424 7425 7426 7427 7428 7429
		/* Deduce arguments T, i from TT<T> or TT<i>.  */
		for (i = 0; i < TREE_VEC_LENGTH (parmvec); ++i)
		  {
		    tree t = TREE_VEC_ELT (parmvec, i);
		    if (TREE_CODE (t) != TEMPLATE_TYPE_PARM
			&& TREE_CODE (t) != TEMPLATE_TEMPLATE_PARM
			&& TREE_CODE (t) != TEMPLATE_PARM_INDEX)
		      continue;
7430

7431
		    /* This argument can be deduced.  */
7432

7433 7434 7435
		    if (unify (tparms, targs, t, 
			       TREE_VEC_ELT (argvec, i), 
			       UNIFY_ALLOW_NONE, explicit_mask))
7436 7437
		      return 1;
		  }
7438
	      }
7439 7440 7441 7442 7443
	      arg = CLASSTYPE_TI_TEMPLATE (arg);
	    }
	}
      else
	{
7444 7445 7446 7447 7448 7449
	  /* If PARM is `const T' and ARG is only `int', we don't have
	     a match unless we are allowing additional qualification.
	     If ARG is `const int' and PARM is just `T' that's OK;
	     that binds `const int' to `T'.  */
	  if (!check_cv_quals_for_unify (strict | UNIFY_ALLOW_LESS_CV_QUAL, 
					 arg, parm))
7450 7451
	    return 1;

7452 7453 7454
	  /* Consider the case where ARG is `const volatile int' and
	     PARM is `const T'.  Then, T should be `volatile int'.  */
	  arg = 
7455 7456 7457
	    cp_build_qualified_type (arg,
				     CP_TYPE_QUALS (arg) 
				     & ~CP_TYPE_QUALS (parm));
7458 7459 7460
	}

      /* Simple cases: Value already set, does match or doesn't.  */
7461
      if (targ != NULL_TREE 
7462
	  && (same_type_p (targ, arg)
7463
	      || (explicit_mask && explicit_mask[idx])))
7464
	return 0;
7465
      else if (targ)
7466
	return 1;
7467
      TREE_VEC_ELT (targs, idx) = arg;
7468 7469
      return 0;

jason's avatar
jason committed
7470
    case TEMPLATE_PARM_INDEX:
7471 7472 7473 7474 7475 7476 7477
      tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));

      if (TEMPLATE_PARM_LEVEL (parm) 
	  != template_decl_level (tparm))
	/* The PARM is not one we're trying to unify.  Just check
	   to see if it matches ARG.  */
	return (TREE_CODE (arg) == TREE_CODE (parm)
7478
		&& cp_tree_equal (parm, arg) > 0) ? 0 : 1;
7479

jason's avatar
jason committed
7480
      idx = TEMPLATE_PARM_IDX (parm);
7481
      targ = TREE_VEC_ELT (targs, idx);
7482

7483
      if (targ)
mrs's avatar
mrs committed
7484
	{
7485
	  int i = (cp_tree_equal (targ, arg) > 0);
mrs's avatar
mrs committed
7486 7487 7488 7489 7490 7491
	  if (i == 1)
	    return 0;
	  else if (i == 0)
	    return 1;
	  else
	    my_friendly_abort (42);
mrs's avatar
mrs committed
7492 7493
	}

7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509
      /* [temp.deduct.type] If, in the declaration of a function template
	 with a non-type template-parameter, the non-type
	 template-parameter is used in an expression in the function
	 parameter-list and, if the corresponding template-argument is
	 deduced, the template-argument type shall match the type of the
	 template-parameter exactly, except that a template-argument
	 deduced from an array bound may be of any integral type.  */
      if (same_type_p (TREE_TYPE (arg), TREE_TYPE (parm)))
	/* OK */;
      else if ((strict & UNIFY_ALLOW_INTEGER)
	       && (TREE_CODE (TREE_TYPE (parm)) == INTEGER_TYPE
		   || TREE_CODE (TREE_TYPE (parm)) == BOOLEAN_TYPE))
	/* OK */;
      else
	return 1;

7510
      TREE_VEC_ELT (targs, idx) = copy_to_permanent (arg);
mrs's avatar
mrs committed
7511 7512 7513
      return 0;

    case POINTER_TYPE:
7514 7515
      {
	int sub_strict;
mrs's avatar
mrs committed
7516

7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549
	if (TREE_CODE (arg) == RECORD_TYPE && TYPE_PTRMEMFUNC_FLAG (arg))
	  return (unify (tparms, targs, parm, 
			 TYPE_PTRMEMFUNC_FN_TYPE (arg), strict,
			 explicit_mask)); 
	
	if (TREE_CODE (arg) != POINTER_TYPE)
	  return 1;
	
	/* [temp.deduct.call]

	   A can be another pointer or pointer to member type that can
	   be converted to the deduced A via a qualification
	   conversion (_conv.qual_).

	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
	   This will allow for additional cv-qualification of the
	   pointed-to types if appropriate.  In general, this is a bit
	   too generous; we are only supposed to allow qualification
	   conversions and this method will allow an ARG of char** and
	   a deduced ARG of const char**.  However, overload
	   resolution will subsequently invalidate the candidate, so
	   this is probably OK.  */
	sub_strict = strict;
	
	if (TREE_CODE (TREE_TYPE (arg)) != RECORD_TYPE
	    || TYPE_PTRMEMFUNC_FLAG (TREE_TYPE (arg)))
	  /* The derived-to-base conversion only persists through one
	     level of pointers.  */
	  sub_strict &= ~UNIFY_ALLOW_DERIVED;

	return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE
		      (arg), sub_strict,  explicit_mask);
      }
mrs's avatar
mrs committed
7550 7551

    case REFERENCE_TYPE:
7552 7553 7554 7555
      if (TREE_CODE (arg) != REFERENCE_TYPE)
	return 1;
      return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
		    UNIFY_ALLOW_NONE, explicit_mask);
mrs's avatar
mrs committed
7556 7557 7558 7559

    case ARRAY_TYPE:
      if (TREE_CODE (arg) != ARRAY_TYPE)
	return 1;
7560 7561 7562 7563
      if ((TYPE_DOMAIN (parm) == NULL_TREE)
	  != (TYPE_DOMAIN (arg) == NULL_TREE))
	return 1;
      if (TYPE_DOMAIN (parm) != NULL_TREE
7564 7565
	  && unify (tparms, targs, TYPE_DOMAIN (parm),
		    TYPE_DOMAIN (arg), UNIFY_ALLOW_NONE, explicit_mask) != 0)
mrs's avatar
mrs committed
7566
	return 1;
7567 7568
      return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
		    UNIFY_ALLOW_NONE, explicit_mask);
mrs's avatar
mrs committed
7569 7570

    case REAL_TYPE:
mrs's avatar
mrs committed
7571
    case COMPLEX_TYPE:
mrs's avatar
mrs committed
7572
    case INTEGER_TYPE:
brendan's avatar
brendan committed
7573
    case BOOLEAN_TYPE:
7574
    case VOID_TYPE:
mrs's avatar
mrs committed
7575 7576 7577
      if (TREE_CODE (arg) != TREE_CODE (parm))
	return 1;

7578 7579
      if (TREE_CODE (parm) == INTEGER_TYPE
	  && TREE_CODE (TYPE_MAX_VALUE (parm)) != INTEGER_CST)
mrs's avatar
mrs committed
7580 7581
	{
	  if (TYPE_MIN_VALUE (parm) && TYPE_MIN_VALUE (arg)
7582
	      && unify (tparms, targs, TYPE_MIN_VALUE (parm),
7583 7584
			TYPE_MIN_VALUE (arg), UNIFY_ALLOW_INTEGER,
			explicit_mask))
mrs's avatar
mrs committed
7585 7586
	    return 1;
	  if (TYPE_MAX_VALUE (parm) && TYPE_MAX_VALUE (arg)
7587
	      && unify (tparms, targs, TYPE_MAX_VALUE (parm),
7588 7589
			TYPE_MAX_VALUE (arg), UNIFY_ALLOW_INTEGER,
			explicit_mask))
mrs's avatar
mrs committed
7590 7591
	    return 1;
	}
7592 7593 7594
      /* We use the TYPE_MAIN_VARIANT since we have already
	 checked cv-qualification at the top of the
	 function.  */
7595 7596
      else if (!same_type_p (TYPE_MAIN_VARIANT (arg),
			     TYPE_MAIN_VARIANT (parm)))
7597 7598
	return 1;

mrs's avatar
mrs committed
7599 7600 7601 7602 7603
      /* As far as unification is concerned, this wins.	 Later checks
	 will invalidate it if necessary.  */
      return 0;

      /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
mrs's avatar
mrs committed
7604
      /* Type INTEGER_CST can come from ordinary constant template args.  */
mrs's avatar
mrs committed
7605
    case INTEGER_CST:
mrs's avatar
mrs committed
7606 7607 7608
      while (TREE_CODE (arg) == NOP_EXPR)
	arg = TREE_OPERAND (arg, 0);

mrs's avatar
mrs committed
7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620
      if (TREE_CODE (arg) != INTEGER_CST)
	return 1;
      return !tree_int_cst_equal (parm, arg);

    case TREE_VEC:
      {
	int i;
	if (TREE_CODE (arg) != TREE_VEC)
	  return 1;
	if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
	  return 1;
	for (i = TREE_VEC_LENGTH (parm) - 1; i >= 0; i--)
7621
	  if (unify (tparms, targs,
mrs's avatar
mrs committed
7622
		     TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
7623
		     UNIFY_ALLOW_NONE, explicit_mask))
mrs's avatar
mrs committed
7624 7625 7626 7627 7628
	    return 1;
	return 0;
      }

    case RECORD_TYPE:
mrs's avatar
mrs committed
7629
      if (TYPE_PTRMEMFUNC_FLAG (parm))
7630
	return unify (tparms, targs, TYPE_PTRMEMFUNC_FN_TYPE (parm),
7631
		      arg, strict, explicit_mask);
mrs's avatar
mrs committed
7632

7633
      if (TREE_CODE (arg) != RECORD_TYPE)
mrs's avatar
mrs committed
7634
	return 1;
7635
  
mrs's avatar
mrs committed
7636
      if (CLASSTYPE_TEMPLATE_INFO (parm) && uses_template_parms (parm))
mrs's avatar
mrs committed
7637
	{
mrs's avatar
mrs committed
7638
	  tree t = NULL_TREE;
7639 7640 7641 7642 7643 7644 7645
	  if (strict & UNIFY_ALLOW_DERIVED)
	    /* [temp.deduct.call]

	       If P is a class, and P has the form template-id, then A
	       can be a derived class of the deduced A.  Likewise, if
	       P is a pointer to a class of the form template-id, A
	       can be a pointer to a derived class pointed to by the
7646 7647 7648 7649 7650
	       deduced A. 

	       The call to get_template_base also handles the case
	       where PARM and ARG are the same type, i.e., where no
	       derivation is involved.  */
mrs's avatar
mrs committed
7651
	    t = get_template_base (CLASSTYPE_TI_TEMPLATE (parm), arg);
7652
	  else if (CLASSTYPE_TEMPLATE_INFO (arg) 
7653 7654
		   && (CLASSTYPE_TI_TEMPLATE (parm) 
		       == CLASSTYPE_TI_TEMPLATE (arg)))
7655 7656
	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
	       Then, we should unify `int' and `U'.  */
mrs's avatar
mrs committed
7657
	    t = arg;
7658

mrs's avatar
mrs committed
7659
	  if (! t || t == error_mark_node)
mrs's avatar
mrs committed
7660
	    return 1;
mrs's avatar
mrs committed
7661

7662 7663 7664
	  return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
			CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE,
			explicit_mask);
mrs's avatar
mrs committed
7665
	}
7666 7667
      else if (!same_type_p (TYPE_MAIN_VARIANT (parm),
			     TYPE_MAIN_VARIANT (arg)))
mrs's avatar
mrs committed
7668
	return 1;
mrs's avatar
mrs committed
7669
      return 0;
mrs's avatar
mrs committed
7670 7671 7672

    case METHOD_TYPE:
    case FUNCTION_TYPE:
7673
      if (TREE_CODE (arg) != TREE_CODE (parm))
mrs's avatar
mrs committed
7674
	return 1;
7675 7676 7677

      if (unify (tparms, targs, TREE_TYPE (parm),
		 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explicit_mask))
mrs's avatar
mrs committed
7678
	return 1;
7679
      return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
7680
				    TYPE_ARG_TYPES (arg), 1, 
7681
				    DEDUCE_EXACT, 0, explicit_mask);
mrs's avatar
mrs committed
7682 7683 7684 7685

    case OFFSET_TYPE:
      if (TREE_CODE (arg) != OFFSET_TYPE)
	return 1;
7686 7687
      if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
		 TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE, explicit_mask))
mrs's avatar
mrs committed
7688
	return 1;
7689 7690
      return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
		    UNIFY_ALLOW_NONE, explicit_mask);
mrs's avatar
mrs committed
7691

jason's avatar
merge  
jason committed
7692
    case CONST_DECL:
7693
      if (arg != decl_constant_value (parm)) 
jason's avatar
merge  
jason committed
7694 7695 7696
	return 1;
      return 0;

7697 7698 7699 7700
    case TEMPLATE_DECL:
      /* Matched cases are handled by the ARG == PARM test above.  */
      return 1;

7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719
    case MINUS_EXPR:
      if (TREE_CODE (TREE_OPERAND (parm, 1)) == INTEGER_CST)
	{
	  /* We handle this case specially, since it comes up with
	     arrays.  In particular, something like:

	     template <int N> void f(int (&x)[N]);

	     Here, we are trying to unify the range type, which
	     looks like [0 ... (N - 1)].  */
	  tree t, t1, t2;
	  t1 = TREE_OPERAND (parm, 0);
	  t2 = TREE_OPERAND (parm, 1);

	  /* Should this be a regular fold?  */
	  t = maybe_fold_nontype_arg (build (PLUS_EXPR,
					     integer_type_node,
					     arg, t2));

7720
	  return unify (tparms, targs, t1, t, strict, explicit_mask);
7721 7722 7723
	}
      /* else fall through */

mrs's avatar
mrs committed
7724
    default:
7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742
      if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (TREE_CODE (parm))))
	{
	  /* We're looking at an expression.  This can happen with
	     something like:

	       template <int I>
	       void foo(S<I>, S<I + 2>);

             If the call looked like:

               foo(S<2>(), S<4>());

	     we would have already matched `I' with `2'.  Now, we'd
	     like to know if `4' matches `I + 2'.  So, we substitute
	     into that expression, and fold constants, in the hope of
	     figuring it out.  */
	  tree t = 
	    maybe_fold_nontype_arg (tsubst_expr (parm, targs, NULL_TREE)); 
7743
	  tree a = maybe_fold_nontype_arg (arg);
7744

7745
	  if (!IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (TREE_CODE (t))))
7746
	    /* Good, we mangaged to simplify the exression.  */
7747
	    return unify (tparms, targs, t, a, UNIFY_ALLOW_NONE,
7748 7749 7750 7751 7752 7753 7754
			  explicit_mask);
	  else
	    /* Bad, we couldn't simplify this.  Assume it doesn't
	       unify.  */
	    return 1;
	}
      else
7755 7756
	sorry ("use of `%s' in template type unification",
	       tree_code_name [(int) TREE_CODE (parm)]);
7757

mrs's avatar
mrs committed
7758 7759 7760 7761
      return 1;
    }
}

7762 7763 7764 7765
/* Called if RESULT is explicitly instantiated, or is a member of an
   explicitly instantiated class, or if using -frepo and the
   instantiation of RESULT has been assigned to this file.  */

mrs's avatar
mrs committed
7766
void
mrs's avatar
mrs committed
7767
mark_decl_instantiated (result, extern_p)
mrs's avatar
mrs committed
7768 7769 7770
     tree result;
     int extern_p;
{
7771 7772 7773 7774
  if (TREE_CODE (result) != FUNCTION_DECL)
    /* The TREE_PUBLIC flag for function declarations will have been
       set correctly by tsubst.  */
    TREE_PUBLIC (result) = 1;
mrs's avatar
mrs committed
7775 7776 7777 7778 7779

  if (! extern_p)
    {
      DECL_INTERFACE_KNOWN (result) = 1;
      DECL_NOT_REALLY_EXTERN (result) = 1;
7780

7781 7782 7783
      /* Always make artificials weak.  */
      if (DECL_ARTIFICIAL (result) && flag_weak)
	comdat_linkage (result);
7784 7785
      /* For WIN32 we also want to put explicit instantiations in
	 linkonce sections.  */
7786
      else if (TREE_PUBLIC (result))
7787
	maybe_make_one_only (result);
mrs's avatar
mrs committed
7788
    }
mrs's avatar
mrs committed
7789 7790
  else if (TREE_CODE (result) == FUNCTION_DECL)
    mark_inline_for_output (result);
mrs's avatar
mrs committed
7791 7792
}

7793 7794
/* Given two function templates PAT1 and PAT2, and explicit template
   arguments EXPLICIT_ARGS return:
mrs's avatar
mrs committed
7795 7796 7797 7798 7799 7800

   1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
   -1 if PAT2 is more specialized than PAT1.
   0 if neither is more specialized.  */
   
int
7801 7802
more_specialized (pat1, pat2, explicit_args)
     tree pat1, pat2, explicit_args;
mrs's avatar
mrs committed
7803
{
7804
  tree targs;
mrs's avatar
mrs committed
7805
  int winner = 0;
mrs's avatar
mrs committed
7806

7807
  targs = get_bindings_overload (pat1, pat2, explicit_args);
mrs's avatar
mrs committed
7808
  if (targs)
7809
    --winner;
mrs's avatar
mrs committed
7810

7811
  targs = get_bindings_overload (pat2, pat1, explicit_args);
mrs's avatar
mrs committed
7812
  if (targs)
7813
    ++winner;
mrs's avatar
mrs committed
7814

mrs's avatar
mrs committed
7815 7816
  return winner;
}
mrs's avatar
mrs committed
7817

mrs's avatar
mrs committed
7818
/* Given two class template specialization list nodes PAT1 and PAT2, return:
mrs's avatar
mrs committed
7819

mrs's avatar
mrs committed
7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830
   1 if PAT1 is more specialized than PAT2 as described in [temp.class.order].
   -1 if PAT2 is more specialized than PAT1.
   0 if neither is more specialized.  */
   
int
more_specialized_class (pat1, pat2)
     tree pat1, pat2;
{
  tree targs;
  int winner = 0;

7831 7832
  targs = get_class_bindings (TREE_VALUE (pat1), TREE_PURPOSE (pat1),
			      TREE_PURPOSE (pat2));
mrs's avatar
mrs committed
7833 7834 7835
  if (targs)
    --winner;

7836 7837
  targs = get_class_bindings (TREE_VALUE (pat2), TREE_PURPOSE (pat2),
			      TREE_PURPOSE (pat1));
mrs's avatar
mrs committed
7838
  if (targs)
mrs's avatar
mrs committed
7839 7840 7841 7842
    ++winner;

  return winner;
}
mrs's avatar
mrs committed
7843 7844

/* Return the template arguments that will produce the function signature
7845
   DECL from the function template FN, with the explicit template
7846 7847
   arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is 1, the return type must
   also match.  */
mrs's avatar
mrs committed
7848

7849 7850
static tree
get_bindings_real (fn, decl, explicit_args, check_rettype)
7851
     tree fn, decl, explicit_args;
7852
     int check_rettype;
mrs's avatar
mrs committed
7853
{
7854
  int ntparms = DECL_NTPARMS (fn);
7855
  tree targs = make_scratch_vec (ntparms);
7856 7857
  tree decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
  tree extra_fn_arg = NULL_TREE;
7858 7859
  int i;

7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879
  if (DECL_STATIC_FUNCTION_P (fn) 
      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
    {
      /* Sometimes we are trying to figure out what's being
	 specialized by a declaration that looks like a method, and it
	 turns out to be a static member function.  */
      if (CLASSTYPE_TEMPLATE_INFO (DECL_REAL_CONTEXT (fn))
	  && !is_member_template (fn))
	/* The natural thing to do here seems to be to remove the
	   spurious `this' parameter from the DECL, but that prevents
	   unification from making use of the class type.  So,
	   instead, we have fn_type_unification add to the parameters
	   for FN.  */
	extra_fn_arg = build_pointer_type (DECL_REAL_CONTEXT (fn));
      else
	/* In this case, though, adding the extra_fn_arg can confuse
	   things, so we remove from decl_arg_types instead.  */
	decl_arg_types = TREE_CHAIN (decl_arg_types);
    }

7880
  i = fn_type_unification (fn, explicit_args, targs, 
7881
			   decl_arg_types,
7882
			   TREE_TYPE (TREE_TYPE (decl)),
7883
			   DEDUCE_EXACT,
7884
			   extra_fn_arg);
7885

7886 7887 7888 7889
  if (i != 0)
    return NULL_TREE;

  if (check_rettype)
7890 7891
    {
      /* Check to see that the resulting return type is also OK.  */
7892
      tree t = tsubst (TREE_TYPE (TREE_TYPE (fn)), targs,
7893
		       NULL_TREE);
7894

7895
      if (!same_type_p (t, TREE_TYPE (TREE_TYPE (decl))))
7896 7897 7898
	return NULL_TREE;
    }

7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917
  return targs;
}

/* For most uses, we want to check the return type.  */

tree 
get_bindings (fn, decl, explicit_args)
     tree fn, decl, explicit_args;
{
  return get_bindings_real (fn, decl, explicit_args, 1);
}

/* But for more_specialized, we only care about the parameter types.  */

static tree
get_bindings_overload (fn, decl, explicit_args)
     tree fn, decl, explicit_args;
{
  return get_bindings_real (fn, decl, explicit_args, 0);
mrs's avatar
mrs committed
7918 7919
}

7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934
/* Return the innermost template arguments that, when applied to a
   template specialization whose innermost template parameters are
   TPARMS, and whose specialization arguments are ARGS, yield the
   ARGS.  

   For example, suppose we have:

     template <class T, class U> struct S {};
     template <class T> struct S<T*, int> {};

   Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
   {T}, the PARMS will be {T*, int} and the ARGS will be {double*,
   int}.  The resulting vector will be {double}, indicating that `T'
   is bound to `double'.  */

mrs's avatar
mrs committed
7935
static tree
7936 7937
get_class_bindings (tparms, parms, args)
     tree tparms, parms, args;
mrs's avatar
mrs committed
7938
{
7939
  int i, ntparms = TREE_VEC_LENGTH (tparms);
mrs's avatar
mrs committed
7940 7941
  tree vec = make_temp_vec (ntparms);

7942
  args = innermost_args (args);
7943

mrs's avatar
mrs committed
7944 7945
  for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
    {
7946
      switch (unify (tparms, vec, 
7947
		     TREE_VEC_ELT (parms, i), TREE_VEC_ELT (args, i),
7948
		     UNIFY_ALLOW_NONE, 0))
mrs's avatar
mrs committed
7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964
	{
	case 0:
	  break;
	case 1:
	  return NULL_TREE;
	}
    }

  for (i =  0; i < ntparms; ++i)
    if (! TREE_VEC_ELT (vec, i))
      return NULL_TREE;

  return vec;
}

/* Return the most specialized of the list of templates in FNS that can
7965 7966
   produce an instantiation matching DECL, given the explicit template
   arguments EXPLICIT_ARGS.  */
mrs's avatar
mrs committed
7967 7968

tree
7969 7970
most_specialized (fns, decl, explicit_args)
     tree fns, decl, explicit_args;
mrs's avatar
mrs committed
7971
{
7972 7973
  tree candidates = NULL_TREE;
  tree fn, champ, args;
mrs's avatar
mrs committed
7974 7975
  int fate;

7976
  for (fn = fns; fn; fn = TREE_CHAIN (fn))
mrs's avatar
mrs committed
7977
    {
7978 7979 7980
      tree candidate = TREE_VALUE (fn);

      args = get_bindings (candidate, decl, explicit_args);
mrs's avatar
mrs committed
7981
      if (args)
7982 7983
	candidates = scratch_tree_cons (NULL_TREE, candidate, 
					candidates);
mrs's avatar
mrs committed
7984 7985
    }

7986
  if (!candidates)
mrs's avatar
mrs committed
7987 7988
    return NULL_TREE;

7989 7990
  champ = TREE_VALUE (candidates);
  for (fn = TREE_CHAIN (candidates); fn; fn = TREE_CHAIN (fn))
mrs's avatar
mrs committed
7991
    {
7992
      fate = more_specialized (champ, TREE_VALUE (fn), explicit_args);
mrs's avatar
mrs committed
7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006
      if (fate == 1)
	;
      else
	{
	  if (fate == 0)
	    {
	      fn = TREE_CHAIN (fn);
	      if (! fn)
		return error_mark_node;
	    }
	  champ = TREE_VALUE (fn);
	}
    }

8007
  for (fn = candidates; fn && TREE_VALUE (fn) != champ; fn = TREE_CHAIN (fn))
mrs's avatar
mrs committed
8008
    {
8009
      fate = more_specialized (champ, TREE_VALUE (fn), explicit_args);
mrs's avatar
mrs committed
8010 8011 8012 8013 8014 8015 8016
      if (fate != 1)
	return error_mark_node;
    }

  return champ;
}

8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029
/* If DECL is a specialization of some template, return the most
   general such template.  For example, given:

     template <class T> struct S { template <class U> void f(U); };

   if TMPL is `template <class U> void S<int>::f(U)' this will return
   the full template.  This function will not trace past partial
   specializations, however.  For example, given in addition:

     template <class T> struct S<T*> { template <class U> void f(U); };

   if TMPL is `template <class U> void S<int*>::f(U)' this will return
   `template <class T> template <class U> S<T*>::f(U)'.  */
mrs's avatar
mrs committed
8030 8031

tree
8032 8033
most_general_template (decl)
     tree decl;
mrs's avatar
mrs committed
8034
{
8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052
  while (DECL_TEMPLATE_INFO (decl))
    decl = DECL_TI_TEMPLATE (decl);

  return decl;
}

/* Return the most specialized of the class template specializations
   of TMPL which can produce an instantiation matching ARGS, or
   error_mark_node if the choice is ambiguous.  */

tree
most_specialized_class (tmpl, args)
     tree tmpl;
     tree args;
{
  tree list = NULL_TREE;
  tree t;
  tree champ;
mrs's avatar
mrs committed
8053 8054
  int fate;

8055 8056
  tmpl = most_general_template (tmpl);
  for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
mrs's avatar
mrs committed
8057
    {
8058 8059 8060
      tree spec_args 
	= get_class_bindings (TREE_VALUE (t), TREE_PURPOSE (t), args);
      if (spec_args)
mrs's avatar
mrs committed
8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091
	{
	  list = decl_tree_cons (TREE_PURPOSE (t), TREE_VALUE (t), list);
	  TREE_TYPE (list) = TREE_TYPE (t);
	}
    }

  if (! list)
    return NULL_TREE;

  t = list;
  champ = t;
  t = TREE_CHAIN (t);
  for (; t; t = TREE_CHAIN (t))
    {
      fate = more_specialized_class (champ, t);
      if (fate == 1)
	;
      else
	{
	  if (fate == 0)
	    {
	      t = TREE_CHAIN (t);
	      if (! t)
		return error_mark_node;
	    }
	  champ = t;
	}
    }

  for (t = list; t && t != champ; t = TREE_CHAIN (t))
    {
8092
      fate = more_specialized_class (champ, t);
mrs's avatar
mrs committed
8093 8094 8095 8096 8097 8098 8099
      if (fate != 1)
	return error_mark_node;
    }

  return champ;
}

mrs's avatar
mrs committed
8100
/* called from the parser.  */
mrs's avatar
mrs committed
8101

mrs's avatar
mrs committed
8102
void
mrs's avatar
mrs committed
8103
do_decl_instantiation (declspecs, declarator, storage)
mrs's avatar
mrs committed
8104
     tree declspecs, declarator, storage;
mrs's avatar
mrs committed
8105
{
mrs's avatar
merging  
mrs committed
8106
  tree decl = grokdeclarator (declarator, declspecs, NORMAL, 0, NULL_TREE);
mrs's avatar
mrs committed
8107
  tree result = NULL_TREE;
mrs's avatar
mrs committed
8108
  int extern_p = 0;
mrs's avatar
mrs committed
8109

mrs's avatar
mrs committed
8110 8111
  if (! DECL_LANG_SPECIFIC (decl))
    {
jason's avatar
jason committed
8112
      cp_error ("explicit instantiation of non-template `%#D'", decl);
mrs's avatar
mrs committed
8113 8114
      return;
    }
8115
  else if (TREE_CODE (decl) == VAR_DECL)
mrs's avatar
mrs committed
8116
    {
8117 8118 8119 8120 8121 8122 8123 8124
      /* There is an asymmetry here in the way VAR_DECLs and
	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
	 the latter, the DECL we get back will be marked as a
	 template instantiation, and the appropriate
	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
	 should handle VAR_DECLs as it currently handles
	 FUNCTION_DECLs.  */
mrs's avatar
mrs committed
8125 8126
      result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, 0);
      if (result && TREE_CODE (result) != VAR_DECL)
8127
	{
jason's avatar
jason committed
8128
	  cp_error ("no matching template for `%D' found", result);
8129 8130
	  return;
	}
mrs's avatar
mrs committed
8131 8132 8133
    }
  else if (TREE_CODE (decl) != FUNCTION_DECL)
    {
jason's avatar
jason committed
8134
      cp_error ("explicit instantiation of `%#D'", decl);
mrs's avatar
mrs committed
8135 8136
      return;
    }
8137 8138
  else
    result = decl;
8139

8140 8141 8142 8143 8144 8145
  /* Check for various error cases.  Note that if the explicit
     instantiation is legal the RESULT will currently be marked as an
     *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
     until we get here.  */

  if (DECL_TEMPLATE_SPECIALIZATION (result))
8146
    {
8147 8148 8149 8150
      /* [temp.spec]

	 No program shall both explicitly instantiate and explicitly
	 specialize a template.  */
jason's avatar
jason committed
8151 8152
      cp_error ("explicit instantiation of `%#D' after", result);
      cp_error_at ("explicit specialization here", result);
8153 8154
      return;
    }
8155 8156 8157
  else if (DECL_EXPLICIT_INSTANTIATION (result))
    {
      /* [temp.spec]
8158

8159 8160 8161 8162 8163 8164 8165
	 No program shall explicitly instantiate any template more
	 than once.  

	 We check DECL_INTERFACE_KNOWN so as not to complain when the
	 first instantiation was `extern' and the second is not, and
	 EXTERN_P for the opposite case.  */
      if (DECL_INTERFACE_KNOWN (result) && !extern_p)
jason's avatar
jason committed
8166
	cp_error ("duplicate explicit instantiation of `%#D'", result);
8167 8168 8169 8170 8171 8172

      /* If we've already instantiated the template, just return now.  */
      if (DECL_INTERFACE_KNOWN (result))
	return;
    }
  else if (!DECL_IMPLICIT_INSTANTIATION (result))
mrs's avatar
mrs committed
8173
    {
jason's avatar
jason committed
8174
      cp_error ("no matching template for `%D' found", result);
mrs's avatar
mrs committed
8175 8176
      return;
    }
8177
  else if (!DECL_TEMPLATE_INFO (result))
mrs's avatar
mrs committed
8178
    {
jason's avatar
jason committed
8179
      cp_pedwarn ("explicit instantiation of non-template `%#D'", result);
mrs's avatar
mrs committed
8180 8181 8182
      return;
    }

mrs's avatar
mrs committed
8183 8184 8185
  if (flag_external_templates)
    return;

mrs's avatar
mrs committed
8186
  if (storage == NULL_TREE)
mrs's avatar
mrs committed
8187
    ;
mrs's avatar
mrs committed
8188
  else if (storage == ridpointers[(int) RID_EXTERN])
8189 8190
    {
      if (pedantic)
jason's avatar
jason committed
8191
	cp_pedwarn ("ANSI C++ forbids the use of `extern' on explicit instantiations");
8192 8193
      extern_p = 1;
    }
mrs's avatar
mrs committed
8194
  else
jason's avatar
jason committed
8195
    cp_error ("storage class `%D' applied to template instantiation",
mrs's avatar
mrs committed
8196
	      storage);
mrs's avatar
mrs committed
8197

8198
  SET_DECL_EXPLICIT_INSTANTIATION (result);
mrs's avatar
mrs committed
8199
  mark_decl_instantiated (result, extern_p);
mrs's avatar
mrs committed
8200
  repo_template_instantiated (result, extern_p);
mrs's avatar
mrs committed
8201 8202
  if (! extern_p)
    instantiate_decl (result);
mrs's avatar
mrs committed
8203 8204
}

mrs's avatar
mrs committed
8205 8206 8207 8208 8209 8210
void
mark_class_instantiated (t, extern_p)
     tree t;
     int extern_p;
{
  SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
8211 8212
  SET_CLASSTYPE_INTERFACE_KNOWN (t);
  CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
mrs's avatar
mrs committed
8213 8214 8215 8216 8217 8218 8219 8220
  CLASSTYPE_VTABLE_NEEDS_WRITING (t) = ! extern_p;
  TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
  if (! extern_p)
    {
      CLASSTYPE_DEBUG_REQUESTED (t) = 1;
      rest_of_type_compilation (t, 1);
    }
}     
mrs's avatar
mrs committed
8221

mrs's avatar
mrs committed
8222
void
8223 8224
do_type_instantiation (t, storage)
     tree t, storage;
mrs's avatar
mrs committed
8225
{
mrs's avatar
mrs committed
8226 8227
  int extern_p = 0;
  int nomem_p = 0;
mrs's avatar
mrs committed
8228 8229
  int static_p = 0;

8230 8231 8232
  if (TREE_CODE (t) == TYPE_DECL)
    t = TREE_TYPE (t);

8233
  if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
8234
    {
jason's avatar
jason committed
8235
      cp_error ("explicit instantiation of non-template type `%T'", t);
8236 8237 8238
      return;
    }

mrs's avatar
mrs committed
8239
  complete_type (t);
mrs's avatar
mrs committed
8240

mrs's avatar
mrs committed
8241 8242
  /* With -fexternal-templates, explicit instantiations are treated the same
     as implicit ones.  */
mrs's avatar
mrs committed
8243 8244 8245
  if (flag_external_templates)
    return;

mrs's avatar
mrs committed
8246 8247
  if (TYPE_SIZE (t) == NULL_TREE)
    {
jason's avatar
jason committed
8248
      cp_error ("explicit instantiation of `%#T' before definition of template",
mrs's avatar
mrs committed
8249 8250 8251 8252
		t);
      return;
    }

8253
  if (storage != NULL_TREE)
mrs's avatar
mrs committed
8254
    {
8255
      if (pedantic)
jason's avatar
jason committed
8256 8257
	cp_pedwarn("ANSI C++ forbids the use of `%s' on explicit instantiations", 
		   IDENTIFIER_POINTER (storage));
8258 8259 8260 8261 8262 8263 8264 8265 8266

      if (storage == ridpointers[(int) RID_INLINE])
	nomem_p = 1;
      else if (storage == ridpointers[(int) RID_EXTERN])
	extern_p = 1;
      else if (storage == ridpointers[(int) RID_STATIC])
	static_p = 1;
      else
	{
jason's avatar
jason committed
8267
	  cp_error ("storage class `%D' applied to template instantiation",
8268 8269 8270
		    storage);
	  extern_p = 0;
	}
mrs's avatar
mrs committed
8271 8272
    }

8273 8274 8275
  if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
    {
      /* [temp.spec]
mrs's avatar
mrs committed
8276

8277 8278
	 No program shall both explicitly instantiate and explicitly
	 specialize a template.  */
jason's avatar
jason committed
8279 8280
      cp_error ("explicit instantiation of `%#T' after", t);
      cp_error_at ("explicit specialization here", t);
8281 8282 8283
      return;
    }
  else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
mrs's avatar
mrs committed
8284
    {
8285 8286 8287 8288 8289 8290 8291 8292 8293
      /* [temp.spec]

	 No program shall explicitly instantiate any template more
	 than once.  

         If CLASSTYPE_INTERFACE_ONLY, then the first explicit
	 instantiation was `extern', and if EXTERN_P then the second
	 is.  Both cases are OK.  */
      if (!CLASSTYPE_INTERFACE_ONLY (t) && !extern_p)
jason's avatar
jason committed
8294
	cp_error ("duplicate explicit instantiation of `%#T'", t);
8295 8296 8297 8298
      
      /* If we've already instantiated the template, just return now.  */
      if (!CLASSTYPE_INTERFACE_ONLY (t))
	return;
mrs's avatar
mrs committed
8299
    }
mrs's avatar
mrs committed
8300

8301 8302 8303
  mark_class_instantiated (t, extern_p);
  repo_template_instantiated (t, extern_p);

mrs's avatar
mrs committed
8304 8305 8306
  if (nomem_p)
    return;

mrs's avatar
mrs committed
8307
  {
mrs's avatar
mrs committed
8308
    tree tmp;
mrs's avatar
mrs committed
8309

8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328
    /* In contrast to implicit instantiation, where only the
       declarations, and not the definitions, of members are
       instantiated, we have here:

         [temp.explicit]

	 The explicit instantiation of a class template specialization
	 implies the instantiation of all of its members not
	 previously explicitly specialized in the translation unit
	 containing the explicit instantiation.  

       Of course, we can't instantiate member template classes, since
       we don't have any arguments for them.  Note that the standard
       is unclear on whether the instatiation of the members are
       *explicit* instantiations or not.  We choose to be generous,
       and not set DECL_EXPLICIT_INSTANTIATION.  Therefore, we allow
       the explicit instantiation of a class where some of the members
       have no definition in the current translation unit.  */

mrs's avatar
mrs committed
8329 8330
    if (! static_p)
      for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
8331
	if (TREE_CODE (tmp) == FUNCTION_DECL
8332
	    && DECL_TEMPLATE_INSTANTIATION (tmp))
mrs's avatar
mrs committed
8333 8334 8335 8336 8337 8338 8339 8340 8341
	  {
	    mark_decl_instantiated (tmp, extern_p);
	    repo_template_instantiated (tmp, extern_p);
	    if (! extern_p)
	      instantiate_decl (tmp);
	  }

    for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
      if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
mrs's avatar
mrs committed
8342
	{
mrs's avatar
mrs committed
8343
	  mark_decl_instantiated (tmp, extern_p);
mrs's avatar
mrs committed
8344
	  repo_template_instantiated (tmp, extern_p);
mrs's avatar
mrs committed
8345 8346
	  if (! extern_p)
	    instantiate_decl (tmp);
mrs's avatar
mrs committed
8347
	}
mrs's avatar
mrs committed
8348

mrs's avatar
mrs committed
8349
    for (tmp = CLASSTYPE_TAGS (t); tmp; tmp = TREE_CHAIN (tmp))
8350 8351
      if (IS_AGGR_TYPE (TREE_VALUE (tmp))
	  && !uses_template_parms (CLASSTYPE_TI_ARGS (TREE_VALUE (tmp))))
mrs's avatar
mrs committed
8352
	do_type_instantiation (TYPE_MAIN_DECL (TREE_VALUE (tmp)), storage);
mrs's avatar
mrs committed
8353
  }
mrs's avatar
mrs committed
8354
}
mrs's avatar
mrs committed
8355

8356 8357 8358 8359
/* Given a function DECL, which is a specialization of TMPL, modify
   DECL to be a re-instantiation of TMPL with the same template
   arguments.  TMPL should be the template into which tsubst'ing
   should occur for DECL, not the most general template.
8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383

   One reason for doing this is a scenario like this:

     template <class T>
     void f(const T&, int i);

     void g() { f(3, 7); }

     template <class T>
     void f(const T& t, const int i) { }

   Note that when the template is first instantiated, with
   instantiate_template, the resulting DECL will have no name for the
   first parameter, and the wrong type for the second.  So, when we go
   to instantiate the DECL, we regenerate it.  */

void
regenerate_decl_from_template (decl, tmpl)
     tree decl;
     tree tmpl;
{
  tree args;
  tree code_pattern;
  tree new_decl;
8384 8385
  tree gen_tmpl;
  int unregistered;
8386 8387 8388 8389

  args = DECL_TI_ARGS (decl);
  code_pattern = DECL_TEMPLATE_RESULT (tmpl);

jason's avatar
jason committed
8390 8391 8392 8393 8394
  /* Unregister the specialization so that when we tsubst we will not
     just return DECL.  We don't have to unregister DECL from TMPL
     because if would only be registered there if it were a partial
     instantiation of a specialization, which it isn't: it's a full
     instantiation.  */
8395 8396 8397 8398 8399 8400 8401 8402
  gen_tmpl = most_general_template (tmpl);
  unregistered = unregister_specialization (decl, gen_tmpl);

  /* If the DECL was not unregistered then something peculiar is
     happening: we created a specialization but did not call
     register_specialization for it.  */
  my_friendly_assert (unregistered, 0);

8403 8404 8405 8406 8407 8408
  if (TREE_CODE (decl) == VAR_DECL)
    /* Make sure that we can see identifiers, and compute access
       correctly, for the class members used in the declaration of
       this static variable.  */
    pushclass (DECL_CONTEXT (decl), 2);

8409 8410
  /* Do the substitution to get the new declaration.  */
  new_decl = tsubst (code_pattern, args, NULL_TREE);
8411 8412 8413 8414 8415

  if (TREE_CODE (decl) == VAR_DECL)
    {
      /* Set up DECL_INITIAL, since tsubst doesn't.  */
      DECL_INITIAL (new_decl) = 
8416
	tsubst_expr (DECL_INITIAL (code_pattern), args, 
8417
		     DECL_TI_TEMPLATE (decl));
8418
      /* Pop the class context we pushed above.  */
8419 8420 8421 8422
      popclass (1);
    }

  if (TREE_CODE (decl) == FUNCTION_DECL)
8423 8424 8425 8426 8427 8428 8429
    {
      /* Convince duplicate_decls to use the DECL_ARGUMENTS from the
	 new decl.  */ 
      DECL_INITIAL (new_decl) = error_mark_node;
      /* And don't complain about a duplicate definition.  */
      DECL_INITIAL (decl) = NULL_TREE;
    }
8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442

  /* The immediate parent of the new template is still whatever it was
     before, even though tsubst sets DECL_TI_TEMPLATE up as the most
     general template.  We also reset the DECL_ASSEMBLER_NAME since
     tsubst always calculates the name as if the function in question
     were really a template instance, and sometimes, with friend
     functions, this is not so.  See tsubst_friend_function for
     details.  */
  DECL_TI_TEMPLATE (new_decl) = DECL_TI_TEMPLATE (decl);
  DECL_ASSEMBLER_NAME (new_decl) = DECL_ASSEMBLER_NAME (decl);
  DECL_RTL (new_decl) = DECL_RTL (decl);

  /* Call duplicate decls to merge the old and new declarations.  */
8443 8444
  duplicate_decls (new_decl, decl);

8445 8446
  /* Now, re-register the specialization.  */
  register_specialization (decl, gen_tmpl, args);
8447 8448
}

jason's avatar
jason committed
8449 8450
/* Produce the definition of D, a _DECL generated from a template.  */

mrs's avatar
mrs committed
8451
tree
mrs's avatar
mrs committed
8452 8453
instantiate_decl (d)
     tree d;
mrs's avatar
mrs committed
8454
{
8455 8456
  tree tmpl = DECL_TI_TEMPLATE (d);
  tree args = DECL_TI_ARGS (d);
8457
  tree td;
8458 8459 8460
  tree code_pattern;
  tree spec;
  tree gen_tmpl;
mrs's avatar
mrs committed
8461 8462
  int nested = in_function_p ();
  int pattern_defined;
8463 8464
  int line = lineno;
  char *file = input_filename;
mrs's avatar
mrs committed
8465

8466 8467 8468 8469 8470
  /* This function should only be used to instantiate templates for
     functions and static member variables.  */
  my_friendly_assert (TREE_CODE (d) == FUNCTION_DECL
		      || TREE_CODE (d) == VAR_DECL, 0);

8471
  if (DECL_TEMPLATE_INSTANTIATED (d))
8472 8473 8474 8475 8476
    /* D has already been instantiated.  It might seem reasonable to
       check whether or not D is an explict instantiation, and, if so,
       stop here.  But when an explicit instantiation is deferred
       until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
       is set, even though we still need to do the instantiation.  */
8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492
    return d;

  /* If we already have a specialization of this declaration, then
     there's no reason to instantiate it.  Note that
     retrieve_specialization gives us both instantiations and
     specializations, so we must explicitly check
     DECL_TEMPLATE_SPECIALIZATION.  */
  gen_tmpl = most_general_template (tmpl);
  spec = retrieve_specialization (gen_tmpl, args);
  if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
    return spec;

  /* This needs to happen before any tsubsting.  */
  if (! push_tinst_level (d))
    return d;

8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526
  /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
     for the instantiation.  This is not always the most general
     template.  Consider, for example:

        template <class T>
	struct S { template <class U> void f();
	           template <> void f<int>(); };

     and an instantiation of S<double>::f<int>.  We want TD to be the
     specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
  td = tmpl;
  for (td = tmpl;
       /* An instantiation cannot have a definition, so we need a
	  more general template.  */
       DECL_TEMPLATE_INSTANTIATION (td)
	 /* We must also deal with friend templates.  Given:

	      template <class T> struct S { 
		template <class U> friend void f() {};
	      };
	 
	    S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
	    so far as the language is concerned, but that's still
	    where we get the pattern for the instantiation from.  On
	    ther hand, if the definition comes outside the class, say:

 	      template <class T> struct S { 
	        template <class U> friend void f();
              };
	      template <class U> friend void f() {}

	    we don't need to look any further.  That's what the check for
	    DECL_INITIAL is for.  */
	|| (TREE_CODE (d) == FUNCTION_DECL
8527
	    && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (td)
8528
	    && !DECL_INITIAL (DECL_TEMPLATE_RESULT (td)));
jason's avatar
jason committed
8529
       )
8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542
    {
      /* The present template, TD, should not be a definition.  If it
	 were a definition, we should be using it!  Note that we
	 cannot restructure the loop to just keep going until we find
	 a template with a definition, since that might go too far if
	 a specialization was declared, but not defined.  */
      my_friendly_assert (!(TREE_CODE (d) == VAR_DECL
			    && !DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (td))), 
			  0); 
      
      /* Fetch the more general template.  */
      td = DECL_TI_TEMPLATE (td);
    }
8543

jason's avatar
jason committed
8544
  code_pattern = DECL_TEMPLATE_RESULT (td);
8545

mrs's avatar
mrs committed
8546
  if (TREE_CODE (d) == FUNCTION_DECL)
8547
    pattern_defined = (DECL_INITIAL (code_pattern) != NULL_TREE);
mrs's avatar
mrs committed
8548
  else
8549
    pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
mrs's avatar
mrs committed
8550 8551 8552 8553 8554 8555

  push_to_top_level ();
  lineno = DECL_SOURCE_LINE (d);
  input_filename = DECL_SOURCE_FILE (d);

  if (pattern_defined)
mrs's avatar
mrs committed
8556 8557 8558 8559 8560 8561 8562 8563 8564 8565
    {
      repo_template_used (d);

      if (flag_external_templates && ! DECL_INTERFACE_KNOWN (d))
	{
	  if (flag_alt_external_templates)
	    {
	      if (interface_unknown)
		warn_if_unknown_interface (d);
	    }
jason's avatar
jason committed
8566
	  else if (DECL_INTERFACE_KNOWN (code_pattern))
mrs's avatar
mrs committed
8567 8568
	    {
	      DECL_INTERFACE_KNOWN (d) = 1;
jason's avatar
jason committed
8569
	      DECL_NOT_REALLY_EXTERN (d) = ! DECL_EXTERNAL (code_pattern);
mrs's avatar
mrs committed
8570 8571
	    }
	  else
jason's avatar
jason committed
8572
	    warn_if_unknown_interface (code_pattern);
mrs's avatar
mrs committed
8573 8574
	}

mrs's avatar
mrs committed
8575
      if (at_eof)
mrs's avatar
mrs committed
8576 8577 8578
	import_export_decl (d);
    }

8579 8580 8581 8582 8583 8584
  /* Reject all external templates except inline functions.  */
  if (DECL_INTERFACE_KNOWN (d)
      && ! DECL_NOT_REALLY_EXTERN (d)
      && ! (TREE_CODE (d) == FUNCTION_DECL && DECL_INLINE (d)))
    goto out;

8585
  if (TREE_CODE (d) == VAR_DECL 
8586
      && TREE_READONLY (d)
8587 8588 8589 8590 8591 8592 8593
      && DECL_INITIAL (d) == NULL_TREE
      && DECL_INITIAL (code_pattern) != NULL_TREE)
    /* We need to set up DECL_INITIAL regardless of pattern_defined if
	 the variable is a static const initialized in the class body.  */;
  else if (! pattern_defined
	   || (! (TREE_CODE (d) == FUNCTION_DECL && DECL_INLINE (d) && nested)
	       && ! at_eof))
mrs's avatar
mrs committed
8594
    {
8595
      /* Defer all templates except inline functions used in another
8596 8597 8598 8599 8600
         function.  We restore the source position here because it's used
         by add_pending_template.  */
      lineno = line;
      input_filename = file;

8601 8602 8603 8604 8605 8606 8607 8608 8609
      if (at_eof && !pattern_defined 
	  && DECL_EXPLICIT_INSTANTIATION (d))
	/* [temp.explicit]

	   The definition of a non-exported function template, a
	   non-exported member function template, or a non-exported
	   member function or static data member of a class template
	   shall be present in every translation unit in which it is
	   explicitly instantiated.  */
jason's avatar
jason committed
8610
	cp_error ("explicit instantiation of `%D' but no definition available",
8611 8612
		  d);

mrs's avatar
mrs committed
8613
      add_pending_template (d);
mrs's avatar
mrs committed
8614
      goto out;
mrs's avatar
mrs committed
8615 8616
    }

8617
  regenerate_decl_from_template (d, td);
8618
  DECL_TEMPLATE_INSTANTIATED (d) = 1;
8619 8620 8621

  /* We already set the file and line above.  Reset them now in case
     they changed as a result of calling regenerate_decl_from_template.  */
mrs's avatar
mrs committed
8622 8623 8624
  lineno = DECL_SOURCE_LINE (d);
  input_filename = DECL_SOURCE_FILE (d);

mrs's avatar
mrs committed
8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638
  if (TREE_CODE (d) == VAR_DECL)
    {
      DECL_IN_AGGR_P (d) = 0;
      if (DECL_INTERFACE_KNOWN (d))
	DECL_EXTERNAL (d) = ! DECL_NOT_REALLY_EXTERN (d);
      else
	{
	  DECL_EXTERNAL (d) = 1;
	  DECL_NOT_REALLY_EXTERN (d) = 1;
	}
      cp_finish_decl (d, DECL_INITIAL (d), NULL_TREE, 0, 0);
    }
  else if (TREE_CODE (d) == FUNCTION_DECL)
    {
jason's avatar
jason committed
8639
      tree t = DECL_SAVED_TREE (code_pattern);
mrs's avatar
mrs committed
8640

mrs's avatar
merging  
mrs committed
8641
      start_function (NULL_TREE, d, NULL_TREE, 1);
mrs's avatar
mrs committed
8642 8643
      store_parm_decls ();

mrs's avatar
mrs committed
8644 8645 8646 8647
      if (t && TREE_CODE (t) == RETURN_INIT)
	{
	  store_return_init
	    (TREE_OPERAND (t, 0),
8648
	     tsubst_expr (TREE_OPERAND (t, 1), args, tmpl));
mrs's avatar
mrs committed
8649 8650 8651
	  t = TREE_CHAIN (t);
	}

mrs's avatar
mrs committed
8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662
      if (t && TREE_CODE (t) == CTOR_INITIALIZER)
	{
	  current_member_init_list
	    = tsubst_expr_values (TREE_OPERAND (t, 0), args);
	  current_base_init_list
	    = tsubst_expr_values (TREE_OPERAND (t, 1), args);
	  t = TREE_CHAIN (t);
	}

      setup_vtbl_ptr ();
      /* Always keep the BLOCK node associated with the outermost
law's avatar
law committed
8663
	 pair of curly braces of a function.  These are needed
mrs's avatar
mrs committed
8664 8665 8666 8667
	 for correct operation of dwarfout.c.  */
      keep_next_level ();

      my_friendly_assert (TREE_CODE (t) == COMPOUND_STMT, 42);
8668
      tsubst_expr (t, args, tmpl);
mrs's avatar
mrs committed
8669

mrs's avatar
mrs committed
8670 8671 8672
      finish_function (lineno, 0, nested);
    }

mrs's avatar
mrs committed
8673
out:
8674 8675 8676
  lineno = line;
  input_filename = file;

mrs's avatar
mrs committed
8677 8678
  pop_from_top_level ();
  pop_tinst_level ();
mrs's avatar
mrs committed
8679 8680 8681

  return d;
}
mrs's avatar
mrs committed
8682

mrs's avatar
mrs committed
8683
static tree
mrs's avatar
mrs committed
8684 8685 8686 8687 8688 8689 8690 8691
tsubst_expr_values (t, argvec)
     tree t, argvec;
{
  tree first = NULL_TREE;
  tree *p = &first;

  for (; t; t = TREE_CHAIN (t))
    {
8692 8693
      tree pur = tsubst_copy (TREE_PURPOSE (t), argvec, NULL_TREE);
      tree val = tsubst_expr (TREE_VALUE (t), argvec, NULL_TREE);
mrs's avatar
mrs committed
8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707
      *p = build_tree_list (pur, val);
      p = &TREE_CHAIN (*p);
    }
  return first;
}

tree last_tree;

void
add_tree (t)
     tree t;
{
  last_tree = TREE_CHAIN (last_tree) = t;
}
mrs's avatar
mrs committed
8708

8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726

void
begin_tree ()
{
  saved_trees = tree_cons (NULL_TREE, last_tree, saved_trees);
  last_tree = NULL_TREE;
}


void 
end_tree ()
{
  my_friendly_assert (saved_trees != NULL_TREE, 0);

  last_tree = TREE_VALUE (saved_trees);
  saved_trees = TREE_CHAIN (saved_trees);
}

mrs's avatar
mrs committed
8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740
/* D is an undefined function declaration in the presence of templates with
   the same name, listed in FNS.  If one of them can produce D as an
   instantiation, remember this so we can instantiate it at EOF if D has
   not been defined by that time.  */

void
add_maybe_template (d, fns)
     tree d, fns;
{
  tree t;

  if (DECL_MAYBE_TEMPLATE (d))
    return;

8741
  t = most_specialized (fns, d, NULL_TREE);
mrs's avatar
mrs committed
8742 8743 8744 8745
  if (! t)
    return;
  if (t == error_mark_node)
    {
jason's avatar
jason committed
8746
      cp_error ("ambiguous template instantiation for `%D'", d);
mrs's avatar
mrs committed
8747 8748 8749 8750 8751 8752 8753
      return;
    }

  *maybe_template_tail = perm_tree_cons (t, d, NULL_TREE);
  maybe_template_tail = &TREE_CHAIN (*maybe_template_tail);
  DECL_MAYBE_TEMPLATE (d) = 1;
}
mrs's avatar
mrs committed
8754

8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768
/* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */

static void
set_current_access_from_decl (decl)
     tree decl;
{
  if (TREE_PRIVATE (decl))
    current_access_specifier = access_private_node;
  else if (TREE_PROTECTED (decl))
    current_access_specifier = access_protected_node;
  else
    current_access_specifier = access_public_node;
}

8769 8770 8771
/* Instantiate an enumerated type.  TAG is the template type, NEWTAG
   is the instantiation (which should have been created with
   start_enum) and ARGS are the template arguments to use.  */
mrs's avatar
mrs committed
8772

8773 8774 8775 8776 8777
static void
tsubst_enum (tag, newtag, args)
     tree tag;
     tree newtag;
     tree args;
mrs's avatar
mrs committed
8778
{
8779
  tree e;
mrs's avatar
mrs committed
8780 8781 8782

  for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
    {
8783 8784 8785 8786 8787 8788
      tree value;
      tree elt;

      /* Note that in a template enum, the TREE_VALUE is the
	 CONST_DECL, not the corresponding INTEGER_CST.  */
      value = tsubst_expr (DECL_INITIAL (TREE_VALUE (e)), 
8789
					 args,
8790 8791 8792 8793 8794 8795 8796
					 NULL_TREE);

      /* Give this enumeration constant the correct access.  */
      set_current_access_from_decl (TREE_VALUE (e));

      /* Actually build the enumerator itself.  */
      elt = build_enumerator (TREE_PURPOSE (e), value, newtag); 
mrs's avatar
mrs committed
8797

8798 8799 8800 8801 8802 8803 8804
      /* We save the enumerators we have built so far in the
	 TYPE_VALUES so that if the enumeration constants for
	 subsequent enumerators involve those for previous ones,
	 tsubst_copy will be able to find them.  */
      TREE_CHAIN (elt) = TYPE_VALUES (newtag);
      TYPE_VALUES (newtag) = elt;
    }
8805

8806
  finish_enum (newtag);
mrs's avatar
mrs committed
8807
}
8808 8809 8810 8811 8812 8813 8814 8815 8816 8817

/* Set the DECL_ASSEMBLER_NAME for DECL, which is a FUNCTION_DECL that
   is either an instantiation or specialization of a template
   function.  */

static void
set_mangled_name_for_template_decl (decl)
     tree decl;
{
  tree saved_namespace;
ghazi's avatar
ghazi committed
8818
  tree context = NULL_TREE;
8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872
  tree fn_type;
  tree ret_type;
  tree parm_types;
  tree tparms;
  tree targs;
  tree tmpl;
  int parm_depth;

  my_friendly_assert (TREE_CODE (decl) == FUNCTION_DECL, 0);
  my_friendly_assert (DECL_TEMPLATE_INFO (decl) != NULL_TREE, 0);

  /* The names of template functions must be mangled so as to indicate
     what template is being specialized with what template arguments.
     For example, each of the following three functions must get
     different mangled names:

       void f(int);                  
       template <> void f<7>(int);
       template <> void f<8>(int);  */

  targs = DECL_TI_ARGS (decl);
  if (uses_template_parms (targs))
    /* This DECL is for a partial instantiation.  There's no need to
       mangle the name of such an entity.  */
    return;

  tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
  tparms = DECL_TEMPLATE_PARMS (tmpl);
  parm_depth = TMPL_PARMS_DEPTH (tparms);

  /* There should be as many levels of arguments as there are levels
     of parameters.  */
  my_friendly_assert (parm_depth == TMPL_ARGS_DEPTH (targs), 0);

  /* We now compute the PARMS and RET_TYPE to give to
     build_decl_overload_real.  The PARMS and RET_TYPE are the
     parameter and return types of the template, after all but the
     innermost template arguments have been substituted, not the
     parameter and return types of the function DECL.  For example,
     given:

       template <class T> T f(T);

     both PARMS and RET_TYPE should be `T' even if DECL is `int f(int)'.  
     A more subtle example is:

       template <class T> struct S { template <class U> void f(T, U); }

     Here, if DECL is `void S<int>::f(int, double)', PARMS should be
     {int, U}.  Thus, the args that we want to subsitute into the
     return and parameter type for the function are those in TARGS,
     with the innermost level omitted.  */
  fn_type = TREE_TYPE (tmpl);
  if (DECL_STATIC_FUNCTION_P (decl))
8873
    context = DECL_CLASS_CONTEXT (decl);
8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950

  if (parm_depth == 1)
    /* No substitution is necessary.  */
    ;
  else
    {
      int i;
      tree partial_args;

      /* Replace the innermost level of the TARGS with NULL_TREEs to
	 let tsubst know not to subsitute for those parameters.  */
      partial_args = make_temp_vec (TREE_VEC_LENGTH (targs));
      for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
	SET_TMPL_ARGS_LEVEL (partial_args, i,
			     TMPL_ARGS_LEVEL (targs, i));
      SET_TMPL_ARGS_LEVEL (partial_args,
			   TMPL_ARGS_DEPTH (targs),
			   make_temp_vec (DECL_NTPARMS (tmpl)));

      /* Now, do the (partial) substitution to figure out the
	 appropriate function type.  */
      fn_type = tsubst (fn_type, partial_args, NULL_TREE);
      if (DECL_STATIC_FUNCTION_P (decl))
	context = tsubst (context, partial_args, NULL_TREE);

      /* Substitute into the template parameters to obtain the real
	 innermost set of parameters.  This step is important if the
	 innermost set of template parameters contains value
	 parameters whose types depend on outer template parameters.  */
      TREE_VEC_LENGTH (partial_args)--;
      tparms = tsubst_template_parms (tparms, partial_args);
    }

  /* Now, get the innermost parameters and arguments, and figure out
     the parameter and return types.  */
  tparms = INNERMOST_TEMPLATE_PARMS (tparms);
  targs = innermost_args (targs);
  ret_type = TREE_TYPE (fn_type);
  parm_types = TYPE_ARG_TYPES (fn_type);

  /* For a static member function, we generate a fake `this' pointer,
     for the purposes of mangling.  This indicates of which class the
     function is a member.  Because of:

       [class.static] 

       There shall not be a static and a nonstatic member function
       with the same name and the same parameter types

     we don't have to worry that this will result in a clash with a
     non-static member function.  */
  if (DECL_STATIC_FUNCTION_P (decl))
    parm_types = hash_tree_chain (build_pointer_type (context), parm_types);

  /* There should be the same number of template parameters as
     template arguments.  */
  my_friendly_assert (TREE_VEC_LENGTH (tparms) == TREE_VEC_LENGTH (targs),
		      0);

  /* If the template is in a namespace, we need to put that into the
     mangled name. Unfortunately, build_decl_overload_real does not
     get the decl to mangle, so it relies on the current
     namespace. Therefore, we set that here temporarily. */
  my_friendly_assert (TREE_CODE_CLASS (TREE_CODE (decl)) == 'd', 980702);
  saved_namespace = current_namespace;
  current_namespace = CP_DECL_CONTEXT (decl);  

  /* Actually set the DCL_ASSEMBLER_NAME.  */
  DECL_ASSEMBLER_NAME (decl)
    = build_decl_overload_real (DECL_NAME (decl), parm_types, ret_type,
				tparms, targs, 
				DECL_FUNCTION_MEMBER_P (decl) 
				+ DECL_CONSTRUCTOR_P (decl));

  /* Restore the previously active namespace.  */
  current_namespace = saved_namespace;
}