expr.c 157 KB
Newer Older
1
/* Routines for manipulation of expression nodes.
2
   Copyright (C) 2000-2019 Free Software Foundation, Inc.
3 4
   Contributed by Andy Vaught

5
This file is part of GCC.
6

7 8
GCC 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
9
Software Foundation; either version 3, or (at your option) any later
10
version.
11

12 13 14 15
GCC 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.
16 17

You should have received a copy of the GNU General Public License
18 19
along with GCC; see the file COPYING3.  If not see
<http://www.gnu.org/licenses/>.  */
20 21

#include "config.h"
22
#include "system.h"
23
#include "coretypes.h"
24
#include "options.h"
25 26 27
#include "gfortran.h"
#include "arith.h"
#include "match.h"
28
#include "target-memory.h" /* for gfc_convert_boz */
Jerry DeLisle committed
29
#include "constructor.h"
30
#include "tree.h"
31

Jerry DeLisle committed
32 33 34 35 36 37 38 39 40 41 42

/* The following set of functions provide access to gfc_expr* of
   various types - actual all but EXPR_FUNCTION and EXPR_VARIABLE.

   There are two functions available elsewhere that provide
   slightly different flavours of variables.  Namely:
     expr.c (gfc_get_variable_expr)
     symbol.c (gfc_lval_expr_from_sym)
   TODO: Merge these functions, if possible.  */

/* Get a new expression node.  */
43 44 45 46 47 48

gfc_expr *
gfc_get_expr (void)
{
  gfc_expr *e;

49
  e = XCNEW (gfc_expr);
50 51 52 53 54 55 56 57
  gfc_clear_ts (&e->ts);
  e->shape = NULL;
  e->ref = NULL;
  e->symtree = NULL;
  return e;
}


Jerry DeLisle committed
58 59
/* Get a new expression node that is an array constructor
   of given type and kind.  */
60

Jerry DeLisle committed
61 62
gfc_expr *
gfc_get_array_expr (bt type, int kind, locus *where)
63
{
Jerry DeLisle committed
64
  gfc_expr *e;
65

Jerry DeLisle committed
66 67 68 69 70 71 72 73 74 75 76 77
  e = gfc_get_expr ();
  e->expr_type = EXPR_ARRAY;
  e->value.constructor = NULL;
  e->rank = 1;
  e->shape = NULL;

  e->ts.type = type;
  e->ts.kind = kind;
  if (where)
    e->where = *where;

  return e;
78 79 80
}


Jerry DeLisle committed
81
/* Get a new expression node that is the NULL expression.  */
82

Jerry DeLisle committed
83 84
gfc_expr *
gfc_get_null_expr (locus *where)
85
{
Jerry DeLisle committed
86
  gfc_expr *e;
87

Jerry DeLisle committed
88 89 90
  e = gfc_get_expr ();
  e->expr_type = EXPR_NULL;
  e->ts.type = BT_UNKNOWN;
91

Jerry DeLisle committed
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
  if (where)
    e->where = *where;

  return e;
}


/* Get a new expression node that is an operator expression node.  */

gfc_expr *
gfc_get_operator_expr (locus *where, gfc_intrinsic_op op,
                      gfc_expr *op1, gfc_expr *op2)
{
  gfc_expr *e;

  e = gfc_get_expr ();
  e->expr_type = EXPR_OP;
  e->value.op.op = op;
  e->value.op.op1 = op1;
  e->value.op.op2 = op2;

  if (where)
    e->where = *where;

  return e;
}


/* Get a new expression node that is an structure constructor
   of given type and kind.  */

gfc_expr *
gfc_get_structure_constructor_expr (bt type, int kind, locus *where)
{
  gfc_expr *e;

  e = gfc_get_expr ();
  e->expr_type = EXPR_STRUCTURE;
  e->value.constructor = NULL;

  e->ts.type = type;
  e->ts.kind = kind;
  if (where)
    e->where = *where;

  return e;
}


/* Get a new expression node that is an constant of given type and kind.  */

gfc_expr *
gfc_get_constant_expr (bt type, int kind, locus *where)
{
  gfc_expr *e;

  if (!where)
149 150
    gfc_internal_error ("gfc_get_constant_expr(): locus %<where%> cannot be "
			"NULL");
Jerry DeLisle committed
151 152 153 154 155 156 157 158 159

  e = gfc_get_expr ();

  e->expr_type = EXPR_CONSTANT;
  e->ts.type = type;
  e->ts.kind = kind;
  e->where = *where;

  switch (type)
160
    {
Jerry DeLisle committed
161 162 163
    case BT_INTEGER:
      mpz_init (e->value.integer);
      break;
164

Jerry DeLisle committed
165 166 167 168
    case BT_REAL:
      gfc_set_model_kind (kind);
      mpfr_init (e->value.real);
      break;
169

Jerry DeLisle committed
170 171 172 173
    case BT_COMPLEX:
      gfc_set_model_kind (kind);
      mpc_init2 (e->value.complex, mpfr_get_default_prec());
      break;
174

Jerry DeLisle committed
175 176
    default:
      break;
177 178
    }

Jerry DeLisle committed
179
  return e;
180 181 182
}


Jerry DeLisle committed
183 184 185
/* Get a new expression node that is an string constant.
   If no string is passed, a string of len is allocated,
   blanked and null-terminated.  */
186

Jerry DeLisle committed
187
gfc_expr *
188
gfc_get_character_expr (int kind, locus *where, const char *src, gfc_charlen_t len)
189
{
Jerry DeLisle committed
190 191
  gfc_expr *e;
  gfc_char_t *dest;
192

Jerry DeLisle committed
193
  if (!src)
194
    {
Jerry DeLisle committed
195 196 197 198 199 200
      dest = gfc_get_wide_string (len + 1);
      gfc_wide_memset (dest, ' ', len);
      dest[len] = '\0';
    }
  else
    dest = gfc_char_to_widechar (src);
201

Jerry DeLisle committed
202 203 204 205 206 207 208 209 210 211 212 213
  e = gfc_get_constant_expr (BT_CHARACTER, kind,
                            where ? where : &gfc_current_locus);
  e->value.character.string = dest;
  e->value.character.length = len;

  return e;
}


/* Get a new expression node that is an integer constant.  */

gfc_expr *
214
gfc_get_int_expr (int kind, locus *where, HOST_WIDE_INT value)
Jerry DeLisle committed
215 216 217 218 219
{
  gfc_expr *p;
  p = gfc_get_constant_expr (BT_INTEGER, kind,
			     where ? where : &gfc_current_locus);

220 221
  const wide_int w = wi::shwi (value, kind * BITS_PER_UNIT);
  wi::to_mpz (w, p->value.integer, SIGNED);
Jerry DeLisle committed
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288

  return p;
}


/* Get a new expression node that is a logical constant.  */

gfc_expr *
gfc_get_logical_expr (int kind, locus *where, bool value)
{
  gfc_expr *p;
  p = gfc_get_constant_expr (BT_LOGICAL, kind,
			     where ? where : &gfc_current_locus);

  p->value.logical = value;

  return p;
}


gfc_expr *
gfc_get_iokind_expr (locus *where, io_kind k)
{
  gfc_expr *e;

  /* Set the types to something compatible with iokind. This is needed to
     get through gfc_free_expr later since iokind really has no Basic Type,
     BT, of its own.  */

  e = gfc_get_expr ();
  e->expr_type = EXPR_CONSTANT;
  e->ts.type = BT_LOGICAL;
  e->value.iokind = k;
  e->where = *where;

  return e;
}


/* Given an expression pointer, return a copy of the expression.  This
   subroutine is recursive.  */

gfc_expr *
gfc_copy_expr (gfc_expr *p)
{
  gfc_expr *q;
  gfc_char_t *s;
  char *c;

  if (p == NULL)
    return NULL;

  q = gfc_get_expr ();
  *q = *p;

  switch (q->expr_type)
    {
    case EXPR_SUBSTRING:
      s = gfc_get_wide_string (p->value.character.length + 1);
      q->value.character.string = s;
      memcpy (s, p->value.character.string,
	      (p->value.character.length + 1) * sizeof (gfc_char_t));
      break;

    case EXPR_CONSTANT:
      /* Copy target representation, if it exists.  */
      if (p->representation.string)
289
	{
Jerry DeLisle committed
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
	  c = XCNEWVEC (char, p->representation.length + 1);
	  q->representation.string = c;
	  memcpy (c, p->representation.string, (p->representation.length + 1));
	}

      /* Copy the values of any pointer components of p->value.  */
      switch (q->ts.type)
	{
	case BT_INTEGER:
	  mpz_init_set (q->value.integer, p->value.integer);
	  break;

	case BT_REAL:
	  gfc_set_model_kind (q->ts.kind);
	  mpfr_init (q->value.real);
	  mpfr_set (q->value.real, p->value.real, GFC_RND_MODE);
	  break;

	case BT_COMPLEX:
	  gfc_set_model_kind (q->ts.kind);
	  mpc_init2 (q->value.complex, mpfr_get_default_prec());
	  mpc_set (q->value.complex, p->value.complex, GFC_MPC_RND_MODE);
	  break;

	case BT_CHARACTER:
	  if (p->representation.string)
	    q->value.character.string
	      = gfc_char_to_widechar (q->representation.string);
	  else
319
	    {
Jerry DeLisle committed
320 321
	      s = gfc_get_wide_string (p->value.character.length + 1);
	      q->value.character.string = s;
322

Jerry DeLisle committed
323 324 325 326 327 328 329 330 331 332 333 334 335
	      /* This is the case for the C_NULL_CHAR named constant.  */
	      if (p->value.character.length == 0
		  && (p->ts.is_c_interop || p->ts.is_iso_c))
		{
		  *s = '\0';
		  /* Need to set the length to 1 to make sure the NUL
		     terminator is copied.  */
		  q->value.character.length = 1;
		}
	      else
		memcpy (s, p->value.character.string,
			(p->value.character.length + 1) * sizeof (gfc_char_t));
	    }
336 337
	  break;

Jerry DeLisle committed
338 339
	case BT_HOLLERITH:
	case BT_LOGICAL:
340
	case_bt_struct:
Jerry DeLisle committed
341
	case BT_CLASS:
342
	case BT_ASSUMED:
Jerry DeLisle committed
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
	  break;		/* Already done.  */

	case BT_PROCEDURE:
        case BT_VOID:
           /* Should never be reached.  */
	case BT_UNKNOWN:
	  gfc_internal_error ("gfc_copy_expr(): Bad expr node");
	  /* Not reached.  */
	}

      break;

    case EXPR_OP:
      switch (q->value.op.op)
	{
	case INTRINSIC_NOT:
	case INTRINSIC_PARENTHESES:
	case INTRINSIC_UPLUS:
	case INTRINSIC_UMINUS:
	  q->value.op.op1 = gfc_copy_expr (p->value.op.op1);
363 364
	  break;

Jerry DeLisle committed
365 366 367
	default:		/* Binary operators.  */
	  q->value.op.op1 = gfc_copy_expr (p->value.op.op1);
	  q->value.op.op2 = gfc_copy_expr (p->value.op.op2);
368 369 370
	  break;
	}

Jerry DeLisle committed
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
      break;

    case EXPR_FUNCTION:
      q->value.function.actual =
	gfc_copy_actual_arglist (p->value.function.actual);
      break;

    case EXPR_COMPCALL:
    case EXPR_PPC:
      q->value.compcall.actual =
	gfc_copy_actual_arglist (p->value.compcall.actual);
      q->value.compcall.tbp = p->value.compcall.tbp;
      break;

    case EXPR_STRUCTURE:
    case EXPR_ARRAY:
      q->value.constructor = gfc_constructor_copy (p->value.constructor);
      break;

    case EXPR_VARIABLE:
    case EXPR_NULL:
      break;
393 394 395

    case EXPR_UNKNOWN:
      gcc_unreachable ();
396
    }
Jerry DeLisle committed
397 398 399 400 401

  q->shape = gfc_copy_shape (p->shape, p->rank);

  q->ref = gfc_copy_ref (p->ref);

402 403 404
  if (p->param_list)
    q->param_list = gfc_copy_actual_arglist (p->param_list);

Jerry DeLisle committed
405
  return q;
406 407 408
}


409 410 411 412 413 414 415 416 417 418 419 420 421
void
gfc_clear_shape (mpz_t *shape, int rank)
{
  int i;

  for (i = 0; i < rank; i++)
    mpz_clear (shape[i]);
}


void
gfc_free_shape (mpz_t **shape, int rank)
{
422 423 424
  if (*shape == NULL)
    return;

425 426 427 428 429 430
  gfc_clear_shape (*shape, rank);
  free (*shape);
  *shape = NULL;
}


431 432 433 434 435 436
/* Workhorse function for gfc_free_expr() that frees everything
   beneath an expression node, but not the node itself.  This is
   useful when we want to simplify a node and replace it with
   something else or the expression node belongs to another structure.  */

static void
437
free_expr0 (gfc_expr *e)
438 439 440 441
{
  switch (e->expr_type)
    {
    case EXPR_CONSTANT:
442
      /* Free any parts of the value that need freeing.  */
443 444 445 446 447 448 449
      switch (e->ts.type)
	{
	case BT_INTEGER:
	  mpz_clear (e->value.integer);
	  break;

	case BT_REAL:
450
	  mpfr_clear (e->value.real);
451 452 453
	  break;

	case BT_CHARACTER:
454
	  free (e->value.character.string);
455 456 457
	  break;

	case BT_COMPLEX:
458
	  mpc_clear (e->value.complex);
459 460 461 462 463 464
	  break;

	default:
	  break;
	}

465
      /* Free the representation.  */
466
      free (e->representation.string);
467

468 469 470
      break;

    case EXPR_OP:
471 472 473 474
      if (e->value.op.op1 != NULL)
	gfc_free_expr (e->value.op.op1);
      if (e->value.op.op2 != NULL)
	gfc_free_expr (e->value.op.op2);
475 476 477 478 479 480
      break;

    case EXPR_FUNCTION:
      gfc_free_actual_arglist (e->value.function.actual);
      break;

481
    case EXPR_COMPCALL:
482
    case EXPR_PPC:
483 484 485
      gfc_free_actual_arglist (e->value.compcall.actual);
      break;

486 487 488 489 490
    case EXPR_VARIABLE:
      break;

    case EXPR_ARRAY:
    case EXPR_STRUCTURE:
Jerry DeLisle committed
491
      gfc_constructor_free (e->value.constructor);
492 493 494
      break;

    case EXPR_SUBSTRING:
495
      free (e->value.character.string);
496 497 498 499 500 501 502 503 504 505
      break;

    case EXPR_NULL:
      break;

    default:
      gfc_internal_error ("free_expr0(): Bad expr type");
    }

  /* Free a shape array.  */
506
  gfc_free_shape (&e->shape, e->rank);
Jerry DeLisle committed
507 508 509

  gfc_free_ref_list (e->ref);

510 511
  gfc_free_actual_arglist (e->param_list);

Jerry DeLisle committed
512 513 514 515 516 517 518 519 520 521 522 523
  memset (e, '\0', sizeof (gfc_expr));
}


/* Free an expression node and everything beneath it.  */

void
gfc_free_expr (gfc_expr *e)
{
  if (e == NULL)
    return;
  free_expr0 (e);
524
  free (e);
Jerry DeLisle committed
525 526 527 528 529 530 531 532 533 534 535 536 537
}


/* Free an argument list and everything below it.  */

void
gfc_free_actual_arglist (gfc_actual_arglist *a1)
{
  gfc_actual_arglist *a2;

  while (a1)
    {
      a2 = a1->next;
538
      if (a1->expr)
Jerry DeLisle committed
539
      gfc_free_expr (a1->expr);
540
      free (a1);
Jerry DeLisle committed
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
      a1 = a2;
    }
}


/* Copy an arglist structure and all of the arguments.  */

gfc_actual_arglist *
gfc_copy_actual_arglist (gfc_actual_arglist *p)
{
  gfc_actual_arglist *head, *tail, *new_arg;

  head = tail = NULL;

  for (; p; p = p->next)
    {
      new_arg = gfc_get_actual_arglist ();
      *new_arg = *p;

      new_arg->expr = gfc_copy_expr (p->expr);
      new_arg->next = NULL;

      if (head == NULL)
	head = new_arg;
      else
	tail->next = new_arg;

      tail = new_arg;
    }

  return head;
}


/* Free a list of reference structures.  */

void
gfc_free_ref_list (gfc_ref *p)
{
  gfc_ref *q;
  int i;

  for (; p; p = q)
    {
      q = p->next;
586

Jerry DeLisle committed
587 588 589 590 591 592 593 594 595
      switch (p->type)
	{
	case REF_ARRAY:
	  for (i = 0; i < GFC_MAX_DIMENSIONS; i++)
	    {
	      gfc_free_expr (p->u.ar.start[i]);
	      gfc_free_expr (p->u.ar.end[i]);
	      gfc_free_expr (p->u.ar.stride[i]);
	    }
596

Jerry DeLisle committed
597
	  break;
598

Jerry DeLisle committed
599 600 601 602
	case REF_SUBSTRING:
	  gfc_free_expr (p->u.ss.start);
	  gfc_free_expr (p->u.ss.end);
	  break;
603

Jerry DeLisle committed
604
	case REF_COMPONENT:
605
	case REF_INQUIRY:
Jerry DeLisle committed
606 607
	  break;
	}
608

609
      free (p);
Jerry DeLisle committed
610
    }
611 612 613 614 615 616
}


/* Graft the *src expression onto the *dest subexpression.  */

void
617
gfc_replace_expr (gfc_expr *dest, gfc_expr *src)
618 619 620
{
  free_expr0 (dest);
  *dest = *src;
621
  free (src);
622 623 624 625
}


/* Try to extract an integer constant from the passed expression node.
626 627 628
   Return true if some error occurred, false on success.  If REPORT_ERROR
   is non-zero, emit error, for positive REPORT_ERROR using gfc_error,
   for negative using gfc_error_now.  */
629

630 631
bool
gfc_extract_int (gfc_expr *expr, int *result, int report_error)
632
{
633 634 635 636 637 638 639 640 641 642 643 644 645 646
  gfc_ref *ref;

  /* A KIND component is a parameter too. The expression for it
     is stored in the initializer and should be consistent with
     the tests below.  */
  if (gfc_expr_attr(expr).pdt_kind)
    {
      for (ref = expr->ref; ref; ref = ref->next)
	{
	   if (ref->u.c.component->attr.pdt_kind)
	     expr = ref->u.c.component->initializer;
	}
    }

647
  if (expr->expr_type != EXPR_CONSTANT)
648 649 650 651 652 653 654
    {
      if (report_error > 0)
	gfc_error ("Constant expression required at %C");
      else if (report_error < 0)
	gfc_error_now ("Constant expression required at %C");
      return true;
    }
655 656

  if (expr->ts.type != BT_INTEGER)
657 658 659 660 661 662 663
    {
      if (report_error > 0)
	gfc_error ("Integer expression required at %C");
      else if (report_error < 0)
	gfc_error_now ("Integer expression required at %C");
      return true;
    }
664 665 666 667

  if ((mpz_cmp_si (expr->value.integer, INT_MAX) > 0)
      || (mpz_cmp_si (expr->value.integer, INT_MIN) < 0))
    {
668 669 670 671 672
      if (report_error > 0)
	gfc_error ("Integer value too large in expression at %C");
      else if (report_error < 0)
	gfc_error_now ("Integer value too large in expression at %C");
      return true;
673 674 675 676
    }

  *result = (int) mpz_get_si (expr->value.integer);

677
  return false;
678 679 680
}


681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
/* Same as gfc_extract_int, but use a HWI.  */

bool
gfc_extract_hwi (gfc_expr *expr, HOST_WIDE_INT *result, int report_error)
{
  gfc_ref *ref;

  /* A KIND component is a parameter too. The expression for it is
     stored in the initializer and should be consistent with the tests
     below.  */
  if (gfc_expr_attr(expr).pdt_kind)
    {
      for (ref = expr->ref; ref; ref = ref->next)
	{
	  if (ref->u.c.component->attr.pdt_kind)
	    expr = ref->u.c.component->initializer;
	}
    }

  if (expr->expr_type != EXPR_CONSTANT)
    {
      if (report_error > 0)
	gfc_error ("Constant expression required at %C");
      else if (report_error < 0)
	gfc_error_now ("Constant expression required at %C");
      return true;
    }

  if (expr->ts.type != BT_INTEGER)
    {
      if (report_error > 0)
	gfc_error ("Integer expression required at %C");
      else if (report_error < 0)
	gfc_error_now ("Integer expression required at %C");
      return true;
    }

  /* Use long_long_integer_type_node to determine when to saturate.  */
  const wide_int val = wi::from_mpz (long_long_integer_type_node,
				     expr->value.integer, false);

  if (!wi::fits_shwi_p (val))
    {
      if (report_error > 0)
	gfc_error ("Integer value too large in expression at %C");
      else if (report_error < 0)
	gfc_error_now ("Integer value too large in expression at %C");
      return true;
    }

  *result = val.to_shwi ();

  return false;
}


737 738
/* Recursively copy a list of reference structures.  */

739 740
gfc_ref *
gfc_copy_ref (gfc_ref *src)
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
{
  gfc_array_ref *ar;
  gfc_ref *dest;

  if (src == NULL)
    return NULL;

  dest = gfc_get_ref ();
  dest->type = src->type;

  switch (src->type)
    {
    case REF_ARRAY:
      ar = gfc_copy_array_ref (&src->u.ar);
      dest->u.ar = *ar;
756
      free (ar);
757 758 759 760 761 762
      break;

    case REF_COMPONENT:
      dest->u.c = src->u.c;
      break;

763 764 765 766
    case REF_INQUIRY:
      dest->u.i = src->u.i;
      break;

767 768 769 770 771 772 773
    case REF_SUBSTRING:
      dest->u.ss = src->u.ss;
      dest->u.ss.start = gfc_copy_expr (src->u.ss.start);
      dest->u.ss.end = gfc_copy_expr (src->u.ss.end);
      break;
    }

774
  dest->next = gfc_copy_ref (src->next);
775 776 777 778 779

  return dest;
}


780
/* Detect whether an expression has any vector index array references.  */
781 782 783 784

int
gfc_has_vector_index (gfc_expr *e)
{
785
  gfc_ref *ref;
786 787 788 789 790 791 792 793 794 795
  int i;
  for (ref = e->ref; ref; ref = ref->next)
    if (ref->type == REF_ARRAY)
      for (i = 0; i < ref->u.ar.dimen; i++)
	if (ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
	  return 1;
  return 0;
}


796 797 798
/* Copy a shape array.  */

mpz_t *
799
gfc_copy_shape (mpz_t *shape, int rank)
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
{
  mpz_t *new_shape;
  int n;

  if (shape == NULL)
    return NULL;

  new_shape = gfc_get_shape (rank);

  for (n = 0; n < rank; n++)
    mpz_init_set (new_shape[n], shape[n]);

  return new_shape;
}


816
/* Copy a shape array excluding dimension N, where N is an integer
817
   constant expression.  Dimensions are numbered in Fortran style --
818 819 820 821 822 823 824 825
   starting with ONE.

   So, if the original shape array contains R elements
      { s1 ... sN-1  sN  sN+1 ... sR-1 sR}
   the result contains R-1 elements:
      { s1 ... sN-1  sN+1    ...  sR-1}

   If anything goes wrong -- N is not a constant, its value is out
826
   of range -- or anything else, just returns NULL.  */
827 828

mpz_t *
829
gfc_copy_shape_excluding (mpz_t *shape, int rank, gfc_expr *dim)
830 831 832 833
{
  mpz_t *new_shape, *s;
  int i, n;

834
  if (shape == NULL
835 836
      || rank <= 1
      || dim == NULL
837
      || dim->expr_type != EXPR_CONSTANT
838 839 840 841
      || dim->ts.type != BT_INTEGER)
    return NULL;

  n = mpz_get_si (dim->value.integer);
842
  n--; /* Convert to zero based index.  */
843
  if (n < 0 || n >= rank)
844 845
    return NULL;

846
  s = new_shape = gfc_get_shape (rank - 1);
847 848 849 850

  for (i = 0; i < rank; i++)
    {
      if (i == n)
851
	continue;
852 853 854 855 856 857 858
      mpz_init_set (*s, shape[i]);
      s++;
    }

  return new_shape;
}

859

860 861 862 863
/* Return the maximum kind of two expressions.  In general, higher
   kind numbers mean more precision for numeric types.  */

int
864
gfc_kind_max (gfc_expr *e1, gfc_expr *e2)
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
{
  return (e1->ts.kind > e2->ts.kind) ? e1->ts.kind : e2->ts.kind;
}


/* Returns nonzero if the type is numeric, zero otherwise.  */

static int
numeric_type (bt type)
{
  return type == BT_COMPLEX || type == BT_REAL || type == BT_INTEGER;
}


/* Returns nonzero if the typespec is a numeric type, zero otherwise.  */

int
882
gfc_numeric_ts (gfc_typespec *ts)
883 884 885 886 887 888 889 890 891 892
{
  return numeric_type (ts->type);
}


/* Return an expression node with an optional argument list attached.
   A variable number of gfc_expr pointers are strung together in an
   argument list with a NULL pointer terminating the list.  */

gfc_expr *
893
gfc_build_conversion (gfc_expr *e)
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
{
  gfc_expr *p;

  p = gfc_get_expr ();
  p->expr_type = EXPR_FUNCTION;
  p->symtree = NULL;
  p->value.function.actual = gfc_get_actual_arglist ();
  p->value.function.actual->expr = e;

  return p;
}


/* Given an expression node with some sort of numeric binary
   expression, insert type conversions required to make the operands
909 910
   have the same type. Conversion warnings are disabled if wconversion
   is set to 0.
911 912 913 914

   The exception is that the operands of an exponential don't have to
   have the same type.  If possible, the base is promoted to the type
   of the exponent.  For example, 1**2.3 becomes 1.0**2.3, but
915
   1.0**2 stays as it is.  */
916 917

void
918
gfc_type_convert_binary (gfc_expr *e, int wconversion)
919 920 921
{
  gfc_expr *op1, *op2;

922 923
  op1 = e->value.op.op1;
  op2 = e->value.op.op2;
924 925 926 927 928 929 930 931 932 933 934 935

  if (op1->ts.type == BT_UNKNOWN || op2->ts.type == BT_UNKNOWN)
    {
      gfc_clear_ts (&e->ts);
      return;
    }

  /* Kind conversions of same type.  */
  if (op1->ts.type == op2->ts.type)
    {
      if (op1->ts.kind == op2->ts.kind)
	{
936
	  /* No type conversions.  */
937 938 939 940 941
	  e->ts = op1->ts;
	  goto done;
	}

      if (op1->ts.kind > op2->ts.kind)
942
	gfc_convert_type_warn (op2, &op1->ts, 2, wconversion);
943
      else
944
	gfc_convert_type_warn (op1, &op2->ts, 2, wconversion);
945 946 947 948 949 950 951 952 953 954

      e->ts = op1->ts;
      goto done;
    }

  /* Integer combined with real or complex.  */
  if (op2->ts.type == BT_INTEGER)
    {
      e->ts = op1->ts;

955
      /* Special case for ** operator.  */
956
      if (e->value.op.op == INTRINSIC_POWER)
957 958
	goto done;

959
      gfc_convert_type_warn (e->value.op.op2, &e->ts, 2, wconversion);
960 961 962 963 964 965
      goto done;
    }

  if (op1->ts.type == BT_INTEGER)
    {
      e->ts = op2->ts;
966
      gfc_convert_type_warn (e->value.op.op1, &e->ts, 2, wconversion);
967 968 969 970 971 972 973 974 975 976
      goto done;
    }

  /* Real combined with complex.  */
  e->ts.type = BT_COMPLEX;
  if (op1->ts.kind > op2->ts.kind)
    e->ts.kind = op1->ts.kind;
  else
    e->ts.kind = op2->ts.kind;
  if (op1->ts.type != BT_COMPLEX || op1->ts.kind != e->ts.kind)
977
    gfc_convert_type_warn (e->value.op.op1, &e->ts, 2, wconversion);
978
  if (op2->ts.type != BT_COMPLEX || op2->ts.kind != e->ts.kind)
979
    gfc_convert_type_warn (e->value.op.op2, &e->ts, 2, wconversion);
980 981 982 983 984 985

done:
  return;
}


986
/* Determine if an expression is constant in the sense of F08:7.1.12.
987
 * This function expects that the expression has already been simplified.  */
988

989
bool
990
gfc_is_constant_expr (gfc_expr *e)
991 992 993 994 995
{
  gfc_constructor *c;
  gfc_actual_arglist *arg;

  if (e == NULL)
996
    return true;
997 998 999 1000

  switch (e->expr_type)
    {
    case EXPR_OP:
Jerry DeLisle committed
1001 1002 1003
      return (gfc_is_constant_expr (e->value.op.op1)
	      && (e->value.op.op2 == NULL
		  || gfc_is_constant_expr (e->value.op.op2)));
1004 1005

    case EXPR_VARIABLE:
1006 1007 1008 1009 1010
      /* The only context in which this can occur is in a parameterized
	 derived type declaration, so returning true is OK.  */
      if (e->symtree->n.sym->attr.pdt_len
	  || e->symtree->n.sym->attr.pdt_kind)
        return true;
1011
      return false;
1012 1013

    case EXPR_FUNCTION:
1014 1015
    case EXPR_PPC:
    case EXPR_COMPCALL:
1016 1017 1018
      gcc_assert (e->symtree || e->value.function.esym
		  || e->value.function.isym);

1019 1020 1021 1022
      /* Call to intrinsic with at least one argument.  */
      if (e->value.function.isym && e->value.function.actual)
	{
	  for (arg = e->value.function.actual; arg; arg = arg->next)
Jerry DeLisle committed
1023
	    if (!gfc_is_constant_expr (arg->expr))
1024
	      return false;
1025
	}
1026 1027 1028 1029 1030 1031

      if (e->value.function.isym
	  && (e->value.function.isym->elemental
	      || e->value.function.isym->pure
	      || e->value.function.isym->inquiry
	      || e->value.function.isym->transformational))
1032
	return true;
1033

1034
      return false;
1035 1036 1037

    case EXPR_CONSTANT:
    case EXPR_NULL:
1038
      return true;
1039 1040

    case EXPR_SUBSTRING:
Jerry DeLisle committed
1041 1042
      return e->ref == NULL || (gfc_is_constant_expr (e->ref->u.ss.start)
				&& gfc_is_constant_expr (e->ref->u.ss.end));
1043

1044
    case EXPR_ARRAY:
1045
    case EXPR_STRUCTURE:
1046 1047 1048 1049 1050
      c = gfc_constructor_first (e->value.constructor);
      if ((e->expr_type == EXPR_ARRAY) && c && c->iterator)
        return gfc_constant_ac (e);

      for (; c; c = gfc_constructor_next (c))
1051
	if (!gfc_is_constant_expr (c->expr))
1052
	  return false;
1053

1054
      return true;
1055 1056 1057 1058


    default:
      gfc_internal_error ("gfc_is_constant_expr(): Unknown expression type");
1059
      return false;
1060 1061 1062 1063
    }
}


1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
/* Is true if the expression or symbol is a passed CFI descriptor.  */
bool
is_CFI_desc (gfc_symbol *sym, gfc_expr *e)
{
  if (sym == NULL
      && e && e->expr_type == EXPR_VARIABLE)
    sym = e->symtree->n.sym;

  if (sym && sym->attr.dummy
      && sym->ns->proc_name->attr.is_bind_c
      && sym->attr.dimension
      && (sym->attr.pointer
	  || sym->attr.allocatable
	  || sym->as->type == AS_ASSUMED_SHAPE
	  || sym->as->type == AS_ASSUMED_RANK))
    return true;

return false;
}


1085 1086 1087 1088 1089 1090 1091
/* Is true if an array reference is followed by a component or substring
   reference.  */
bool
is_subref_array (gfc_expr * e)
{
  gfc_ref * ref;
  bool seen_array;
1092
  gfc_symbol *sym;
1093 1094 1095 1096

  if (e->expr_type != EXPR_VARIABLE)
    return false;

1097 1098 1099
  sym = e->symtree->n.sym;

  if (sym->attr.subref_array_pointer)
1100 1101 1102
    return true;

  seen_array = false;
1103

1104 1105
  for (ref = e->ref; ref; ref = ref->next)
    {
1106
      /* If we haven't seen the array reference and this is an intrinsic,
1107 1108
	 what follows cannot be a subreference array, unless there is a
	 substring reference.  */
1109
      if (!seen_array && ref->type == REF_COMPONENT
1110
	  && ref->u.c.component->ts.type != BT_CHARACTER
1111 1112 1113 1114
	  && ref->u.c.component->ts.type != BT_CLASS
	  && !gfc_bt_struct (ref->u.c.component->ts.type))
	return false;

1115 1116 1117 1118 1119 1120 1121 1122
      if (ref->type == REF_ARRAY
	    && ref->u.ar.type != AR_ELEMENT)
	seen_array = true;

      if (seen_array
	    && ref->type != REF_ARRAY)
	return seen_array;
    }
1123

1124 1125 1126 1127
  if (sym->ts.type == BT_CLASS
      && sym->attr.dummy
      && CLASS_DATA (sym)->attr.dimension
      && CLASS_DATA (sym)->attr.class_pointer)
1128 1129
    return true;

1130 1131 1132 1133
  return false;
}


1134 1135
/* Try to collapse intrinsic expressions.  */

1136
static bool
1137
simplify_intrinsic_op (gfc_expr *p, int type)
1138
{
1139
  gfc_intrinsic_op op;
1140 1141
  gfc_expr *op1, *op2, *result;

1142
  if (p->value.op.op == INTRINSIC_USER)
1143
    return true;
1144

1145 1146
  op1 = p->value.op.op1;
  op2 = p->value.op.op2;
1147
  op  = p->value.op.op;
1148

1149 1150 1151 1152
  if (!gfc_simplify_expr (op1, type))
    return false;
  if (!gfc_simplify_expr (op2, type))
    return false;
1153 1154 1155

  if (!gfc_is_constant_expr (op1)
      || (op2 != NULL && !gfc_is_constant_expr (op2)))
1156
    return true;
1157

1158
  /* Rip p apart.  */
1159 1160
  p->value.op.op1 = NULL;
  p->value.op.op2 = NULL;
1161

1162
  switch (op)
1163
    {
1164
    case INTRINSIC_PARENTHESES:
1165 1166 1167 1168
      result = gfc_parentheses (op1);
      break;

    case INTRINSIC_UPLUS:
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
      result = gfc_uplus (op1);
      break;

    case INTRINSIC_UMINUS:
      result = gfc_uminus (op1);
      break;

    case INTRINSIC_PLUS:
      result = gfc_add (op1, op2);
      break;

    case INTRINSIC_MINUS:
      result = gfc_subtract (op1, op2);
      break;

    case INTRINSIC_TIMES:
      result = gfc_multiply (op1, op2);
      break;

    case INTRINSIC_DIVIDE:
      result = gfc_divide (op1, op2);
      break;

    case INTRINSIC_POWER:
      result = gfc_power (op1, op2);
      break;

    case INTRINSIC_CONCAT:
      result = gfc_concat (op1, op2);
      break;

    case INTRINSIC_EQ:
1201 1202
    case INTRINSIC_EQ_OS:
      result = gfc_eq (op1, op2, op);
1203 1204 1205
      break;

    case INTRINSIC_NE:
1206 1207
    case INTRINSIC_NE_OS:
      result = gfc_ne (op1, op2, op);
1208 1209 1210
      break;

    case INTRINSIC_GT:
1211 1212
    case INTRINSIC_GT_OS:
      result = gfc_gt (op1, op2, op);
1213 1214 1215
      break;

    case INTRINSIC_GE:
1216 1217
    case INTRINSIC_GE_OS:
      result = gfc_ge (op1, op2, op);
1218 1219 1220
      break;

    case INTRINSIC_LT:
1221 1222
    case INTRINSIC_LT_OS:
      result = gfc_lt (op1, op2, op);
1223 1224 1225
      break;

    case INTRINSIC_LE:
1226 1227
    case INTRINSIC_LE_OS:
      result = gfc_le (op1, op2, op);
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
      break;

    case INTRINSIC_NOT:
      result = gfc_not (op1);
      break;

    case INTRINSIC_AND:
      result = gfc_and (op1, op2);
      break;

    case INTRINSIC_OR:
      result = gfc_or (op1, op2);
      break;

    case INTRINSIC_EQV:
      result = gfc_eqv (op1, op2);
      break;

    case INTRINSIC_NEQV:
      result = gfc_neqv (op1, op2);
      break;

    default:
      gfc_internal_error ("simplify_intrinsic_op(): Bad operator");
    }

  if (result == NULL)
    {
      gfc_free_expr (op1);
      gfc_free_expr (op2);
1258
      return false;
1259 1260
    }

1261 1262
  result->rank = p->rank;
  result->where = p->where;
1263 1264
  gfc_replace_expr (p, result);

1265
  return true;
1266 1267 1268 1269 1270 1271
}


/* Subroutine to simplify constructor expressions.  Mutually recursive
   with gfc_simplify_expr().  */

1272
static bool
Jerry DeLisle committed
1273
simplify_constructor (gfc_constructor_base base, int type)
1274
{
Jerry DeLisle committed
1275
  gfc_constructor *c;
1276 1277
  gfc_expr *p;

Jerry DeLisle committed
1278
  for (c = gfc_constructor_first (base); c; c = gfc_constructor_next (c))
1279 1280
    {
      if (c->iterator
1281 1282 1283 1284
	  && (!gfc_simplify_expr(c->iterator->start, type)
	      || !gfc_simplify_expr (c->iterator->end, type)
	      || !gfc_simplify_expr (c->iterator->step, type)))
	return false;
1285

1286 1287 1288 1289 1290 1291 1292
      if (c->expr)
	{
	  /* Try and simplify a copy.  Replace the original if successful
	     but keep going through the constructor at all costs.  Not
	     doing so can make a dog's dinner of complicated things.  */
	  p = gfc_copy_expr (c->expr);

1293
	  if (!gfc_simplify_expr (p, type))
1294 1295 1296 1297 1298 1299 1300
	    {
	      gfc_free_expr (p);
	      continue;
	    }

	  gfc_replace_expr (c->expr, p);
	}
1301 1302
    }

1303
  return true;
1304 1305 1306 1307 1308
}


/* Pull a single array element out of an array constructor.  */

1309
static bool
Jerry DeLisle committed
1310
find_array_element (gfc_constructor_base base, gfc_array_ref *ar,
1311
		    gfc_constructor **rval)
1312 1313 1314 1315 1316
{
  unsigned long nelemen;
  int i;
  mpz_t delta;
  mpz_t offset;
1317 1318
  mpz_t span;
  mpz_t tmp;
Jerry DeLisle committed
1319
  gfc_constructor *cons;
1320
  gfc_expr *e;
1321
  bool t;
1322

1323
  t = true;
1324
  e = NULL;
1325 1326 1327

  mpz_init_set_ui (offset, 0);
  mpz_init (delta);
1328 1329
  mpz_init (tmp);
  mpz_init_set_ui (span, 1);
1330 1331
  for (i = 0; i < ar->dimen; i++)
    {
1332 1333
      if (!gfc_reduce_init_expr (ar->as->lower[i])
	  || !gfc_reduce_init_expr (ar->as->upper[i]))
1334
	{
1335
	  t = false;
1336 1337 1338 1339
	  cons = NULL;
	  goto depart;
	}

1340
      e = ar->start[i];
1341
      if (e->expr_type != EXPR_CONSTANT)
1342 1343
	{
	  cons = NULL;
1344
	  goto depart;
1345
	}
1346

1347 1348 1349
      gcc_assert (ar->as->upper[i]->expr_type == EXPR_CONSTANT
		  && ar->as->lower[i]->expr_type == EXPR_CONSTANT);

1350
      /* Check the bounds.  */
1351
      if ((ar->as->upper[i]
1352 1353
	   && mpz_cmp (e->value.integer,
		       ar->as->upper[i]->value.integer) > 0)
1354 1355
	  || (mpz_cmp (e->value.integer,
		       ar->as->lower[i]->value.integer) < 0))
1356
	{
1357
	  gfc_error ("Index in dimension %d is out of bounds "
1358 1359
		     "at %L", i + 1, &ar->c_where[i]);
	  cons = NULL;
1360
	  t = false;
1361 1362 1363
	  goto depart;
	}

1364
      mpz_sub (delta, e->value.integer, ar->as->lower[i]->value.integer);
1365
      mpz_mul (delta, delta, span);
1366
      mpz_add (offset, offset, delta);
1367 1368 1369 1370 1371

      mpz_set_ui (tmp, 1);
      mpz_add (tmp, tmp, ar->as->upper[i]->value.integer);
      mpz_sub (tmp, tmp, ar->as->lower[i]->value.integer);
      mpz_mul (span, span, tmp);
1372 1373
    }

Jerry DeLisle committed
1374 1375
  for (cons = gfc_constructor_first (base), nelemen = mpz_get_ui (offset);
       cons && nelemen > 0; cons = gfc_constructor_next (cons), nelemen--)
1376
    {
Jerry DeLisle committed
1377
      if (cons->iterator)
1378
	{
Jerry DeLisle committed
1379 1380
	  cons = NULL;
	  goto depart;
1381 1382
	}
    }
1383

1384
depart:
1385 1386
  mpz_clear (delta);
  mpz_clear (offset);
1387 1388
  mpz_clear (span);
  mpz_clear (tmp);
1389 1390
  *rval = cons;
  return t;
1391 1392 1393 1394 1395 1396
}


/* Find a component of a structure constructor.  */

static gfc_constructor *
Jerry DeLisle committed
1397
find_component_ref (gfc_constructor_base base, gfc_ref *ref)
1398
{
1399
  gfc_component *pick = ref->u.c.component;
Jerry DeLisle committed
1400
  gfc_constructor *c = gfc_constructor_first (base);
1401

1402 1403 1404 1405 1406 1407
  gfc_symbol *dt = ref->u.c.sym;
  int ext = dt->attr.extension;

  /* For extended types, check if the desired component is in one of the
   * parent types.  */
  while (ext > 0 && gfc_find_component (dt->components->ts.u.derived,
1408
					pick->name, true, true, NULL))
1409 1410 1411 1412 1413 1414 1415
    {
      dt = dt->components->ts.u.derived;
      c = gfc_constructor_first (c->expr->value.constructor);
      ext--;
    }

  gfc_component *comp = dt->components;
1416 1417 1418
  while (comp != pick)
    {
      comp = comp->next;
Jerry DeLisle committed
1419
      c = gfc_constructor_next (c);
1420 1421
    }

Jerry DeLisle committed
1422
  return c;
1423 1424 1425 1426 1427 1428 1429
}


/* Replace an expression with the contents of a constructor, removing
   the subobject reference in the process.  */

static void
1430
remove_subobject_ref (gfc_expr *p, gfc_constructor *cons)
1431 1432 1433
{
  gfc_expr *e;

1434 1435 1436 1437 1438 1439 1440
  if (cons)
    {
      e = cons->expr;
      cons->expr = NULL;
    }
  else
    e = gfc_copy_expr (p);
1441 1442 1443 1444 1445 1446
  e->ref = p->ref->next;
  p->ref->next =  NULL;
  gfc_replace_expr (p, e);
}


1447 1448
/* Pull an array section out of an array constructor.  */

1449
static bool
1450 1451 1452 1453 1454
find_array_section (gfc_expr *expr, gfc_ref *ref)
{
  int idx;
  int rank;
  int d;
1455
  int shape_i;
1456
  int limit;
1457
  long unsigned one = 1;
1458
  bool incr_ctr;
1459
  mpz_t start[GFC_MAX_DIMENSIONS];
1460 1461 1462 1463 1464 1465 1466 1467
  mpz_t end[GFC_MAX_DIMENSIONS];
  mpz_t stride[GFC_MAX_DIMENSIONS];
  mpz_t delta[GFC_MAX_DIMENSIONS];
  mpz_t ctr[GFC_MAX_DIMENSIONS];
  mpz_t delta_mpz;
  mpz_t tmp_mpz;
  mpz_t nelts;
  mpz_t ptr;
Jerry DeLisle committed
1468 1469
  gfc_constructor_base base;
  gfc_constructor *cons, *vecsub[GFC_MAX_DIMENSIONS];
1470 1471 1472 1473 1474
  gfc_expr *begin;
  gfc_expr *finish;
  gfc_expr *step;
  gfc_expr *upper;
  gfc_expr *lower;
1475
  bool t;
1476

1477
  t = true;
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495

  base = expr->value.constructor;
  expr->value.constructor = NULL;

  rank = ref->u.ar.as->rank;

  if (expr->shape == NULL)
    expr->shape = gfc_get_shape (rank);

  mpz_init_set_ui (delta_mpz, one);
  mpz_init_set_ui (nelts, one);
  mpz_init (tmp_mpz);

  /* Do the initialization now, so that we can cleanup without
     keeping track of where we were.  */
  for (d = 0; d < rank; d++)
    {
      mpz_init (delta[d]);
1496
      mpz_init (start[d]);
1497 1498 1499
      mpz_init (end[d]);
      mpz_init (ctr[d]);
      mpz_init (stride[d]);
1500
      vecsub[d] = NULL;
1501 1502 1503
    }

  /* Build the counters to clock through the array reference.  */
1504
  shape_i = 0;
1505 1506 1507 1508 1509 1510 1511 1512 1513
  for (d = 0; d < rank; d++)
    {
      /* Make this stretch of code easier on the eye!  */
      begin = ref->u.ar.start[d];
      finish = ref->u.ar.end[d];
      step = ref->u.ar.stride[d];
      lower = ref->u.ar.as->lower[d];
      upper = ref->u.ar.as->upper[d];

1514
      if (ref->u.ar.dimen_type[d] == DIMEN_VECTOR)  /* Vector subscript.  */
1515
	{
Jerry DeLisle committed
1516
	  gfc_constructor *ci;
1517
	  gcc_assert (begin);
Tobias Burnus committed
1518

1519
	  if (begin->expr_type != EXPR_ARRAY || !gfc_is_constant_expr (begin))
Tobias Burnus committed
1520
	    {
1521
	      t = false;
Tobias Burnus committed
1522 1523 1524
	      goto cleanup;
	    }

1525
	  gcc_assert (begin->rank == 1);
1526
	  /* Zero-sized arrays have no shape and no elements, stop early.  */
1527
	  if (!begin->shape)
1528 1529 1530 1531
	    {
	      mpz_init_set_ui (nelts, 0);
	      break;
	    }
1532

Jerry DeLisle committed
1533
	  vecsub[d] = gfc_constructor_first (begin->value.constructor);
1534 1535 1536
	  mpz_set (ctr[d], vecsub[d]->expr->value.integer);
	  mpz_mul (nelts, nelts, begin->shape[0]);
	  mpz_set (expr->shape[shape_i++], begin->shape[0]);
1537

1538
	  /* Check bounds.  */
Jerry DeLisle committed
1539
	  for (ci = vecsub[d]; ci; ci = gfc_constructor_next (ci))
1540
	    {
Jerry DeLisle committed
1541 1542
	      if (mpz_cmp (ci->expr->value.integer, upper->value.integer) > 0
		  || mpz_cmp (ci->expr->value.integer,
1543
			      lower->value.integer) < 0)
1544 1545 1546
		{
		  gfc_error ("index in dimension %d is out of bounds "
			     "at %L", d + 1, &ref->u.ar.c_where[d]);
1547
		  t = false;
1548 1549 1550
		  goto cleanup;
		}
	    }
1551
	}
1552
      else
1553
	{
1554
	  if ((begin && begin->expr_type != EXPR_CONSTANT)
1555 1556
	      || (finish && finish->expr_type != EXPR_CONSTANT)
	      || (step && step->expr_type != EXPR_CONSTANT))
1557
	    {
1558
	      t = false;
1559 1560
	      goto cleanup;
	    }
1561

1562 1563 1564 1565 1566
	  /* Obtain the stride.  */
	  if (step)
	    mpz_set (stride[d], step->value.integer);
	  else
	    mpz_set_ui (stride[d], one);
1567

1568 1569
	  if (mpz_cmp_ui (stride[d], 0) == 0)
	    mpz_set_ui (stride[d], one);
1570

1571 1572 1573 1574 1575
	  /* Obtain the start value for the index.  */
	  if (begin)
	    mpz_set (start[d], begin->value.integer);
	  else
	    mpz_set (start[d], lower->value.integer);
1576

1577
	  mpz_set (ctr[d], start[d]);
1578

1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
	  /* Obtain the end value for the index.  */
	  if (finish)
	    mpz_set (end[d], finish->value.integer);
	  else
	    mpz_set (end[d], upper->value.integer);

	  /* Separate 'if' because elements sometimes arrive with
	     non-null end.  */
	  if (ref->u.ar.dimen_type[d] == DIMEN_ELEMENT)
	    mpz_set (end [d], begin->value.integer);

	  /* Check the bounds.  */
	  if (mpz_cmp (ctr[d], upper->value.integer) > 0
	      || mpz_cmp (end[d], upper->value.integer) > 0
	      || mpz_cmp (ctr[d], lower->value.integer) < 0
	      || mpz_cmp (end[d], lower->value.integer) < 0)
	    {
	      gfc_error ("index in dimension %d is out of bounds "
			 "at %L", d + 1, &ref->u.ar.c_where[d]);
1598
	      t = false;
1599 1600
	      goto cleanup;
	    }
1601

1602
	  /* Calculate the number of elements and the shape.  */
1603
	  mpz_set (tmp_mpz, stride[d]);
1604 1605 1606 1607 1608
	  mpz_add (tmp_mpz, end[d], tmp_mpz);
	  mpz_sub (tmp_mpz, tmp_mpz, ctr[d]);
	  mpz_div (tmp_mpz, tmp_mpz, stride[d]);
	  mpz_mul (nelts, nelts, tmp_mpz);

1609 1610
	  /* An element reference reduces the rank of the expression; don't
	     add anything to the shape array.  */
1611
	  if (ref->u.ar.dimen_type[d] != DIMEN_ELEMENT)
1612 1613
	    mpz_set (expr->shape[shape_i++], tmp_mpz);
	}
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623

      /* Calculate the 'stride' (=delta) for conversion of the
	 counter values into the index along the constructor.  */
      mpz_set (delta[d], delta_mpz);
      mpz_sub (tmp_mpz, upper->value.integer, lower->value.integer);
      mpz_add_ui (tmp_mpz, tmp_mpz, one);
      mpz_mul (delta_mpz, delta_mpz, tmp_mpz);
    }

  mpz_init (ptr);
Jerry DeLisle committed
1624
  cons = gfc_constructor_first (base);
1625 1626 1627

  /* Now clock through the array reference, calculating the index in
     the source constructor and transferring the elements to the new
1628
     constructor.  */
1629
  for (idx = 0; idx < (int) mpz_get_si (nelts); idx++)
1630
    {
1631
      mpz_init_set_ui (ptr, 0);
1632

1633
      incr_ctr = true;
1634 1635 1636
      for (d = 0; d < rank; d++)
	{
	  mpz_set (tmp_mpz, ctr[d]);
1637
	  mpz_sub (tmp_mpz, tmp_mpz, ref->u.ar.as->lower[d]->value.integer);
1638 1639 1640
	  mpz_mul (tmp_mpz, tmp_mpz, delta[d]);
	  mpz_add (ptr, ptr, tmp_mpz);

1641
	  if (!incr_ctr) continue;
1642

1643
	  if (ref->u.ar.dimen_type[d] == DIMEN_VECTOR) /* Vector subscript.  */
1644 1645 1646
	    {
	      gcc_assert(vecsub[d]);

Jerry DeLisle committed
1647 1648
	      if (!gfc_constructor_next (vecsub[d]))
		vecsub[d] = gfc_constructor_first (ref->u.ar.start[d]->value.constructor);
1649 1650
	      else
		{
Jerry DeLisle committed
1651
		  vecsub[d] = gfc_constructor_next (vecsub[d]);
1652 1653 1654 1655
		  incr_ctr = false;
		}
	      mpz_set (ctr[d], vecsub[d]->expr->value.integer);
	    }
1656
	  else
1657
	    {
1658
	      mpz_add (ctr[d], ctr[d], stride[d]);
1659

1660 1661 1662
	      if (mpz_cmp_ui (stride[d], 0) > 0
		  ? mpz_cmp (ctr[d], end[d]) > 0
		  : mpz_cmp (ctr[d], end[d]) < 0)
1663 1664 1665 1666
		mpz_set (ctr[d], start[d]);
	      else
		incr_ctr = false;
	    }
1667 1668
	}

1669
      limit = mpz_get_ui (ptr);
1670
      if (limit >= flag_max_array_constructor)
1671 1672 1673
        {
	  gfc_error ("The number of elements in the array constructor "
		     "at %L requires an increase of the allowed %d "
1674
		     "upper limit.  See %<-fmax-array-constructor%> "
1675
		     "option", &expr->where, flag_max_array_constructor);
1676
	  return false;
1677 1678 1679
	}

      cons = gfc_constructor_lookup (base, limit);
Jerry DeLisle committed
1680 1681 1682
      gcc_assert (cons);
      gfc_constructor_append_expr (&expr->value.constructor,
				   gfc_copy_expr (cons->expr), NULL);
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
    }

  mpz_clear (ptr);

cleanup:

  mpz_clear (delta_mpz);
  mpz_clear (tmp_mpz);
  mpz_clear (nelts);
  for (d = 0; d < rank; d++)
    {
      mpz_clear (delta[d]);
1695
      mpz_clear (start[d]);
1696 1697 1698 1699
      mpz_clear (end[d]);
      mpz_clear (ctr[d]);
      mpz_clear (stride[d]);
    }
Jerry DeLisle committed
1700
  gfc_constructor_free (base);
1701 1702 1703 1704 1705
  return t;
}

/* Pull a substring out of an expression.  */

1706
static bool
1707 1708
find_substring_ref (gfc_expr *p, gfc_expr **newp)
{
1709 1710 1711
  gfc_charlen_t end;
  gfc_charlen_t start;
  gfc_charlen_t length;
1712
  gfc_char_t *chr;
1713 1714

  if (p->ref->u.ss.start->expr_type != EXPR_CONSTANT
1715
      || p->ref->u.ss.end->expr_type != EXPR_CONSTANT)
1716
    return false;
1717 1718

  *newp = gfc_copy_expr (p);
1719
  free ((*newp)->value.character.string);
1720

1721 1722 1723 1724 1725 1726
  end = (gfc_charlen_t) mpz_get_ui (p->ref->u.ss.end->value.integer);
  start = (gfc_charlen_t) mpz_get_ui (p->ref->u.ss.start->value.integer);
  if (end >= start)
    length = end - start + 1;
  else
    length = 0;
1727

1728
  chr = (*newp)->value.character.string = gfc_get_wide_string (length + 1);
1729
  (*newp)->value.character.length = length;
1730 1731
  memcpy (chr, &p->value.character.string[start - 1],
	  length * sizeof (gfc_char_t));
1732
  chr[length] = '\0';
1733
  return true;
1734 1735 1736
}


1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
/* Pull an inquiry result out of an expression.  */

static bool
find_inquiry_ref (gfc_expr *p, gfc_expr **newp)
{
  gfc_ref *ref;
  gfc_ref *inquiry = NULL;
  gfc_expr *tmp;

  tmp = gfc_copy_expr (p);

  if (tmp->ref && tmp->ref->type == REF_INQUIRY)
    {
      inquiry = tmp->ref;
      tmp->ref = NULL;
    }
  else
    {
      for (ref = tmp->ref; ref; ref = ref->next)
	if (ref->next && ref->next->type == REF_INQUIRY)
	  {
	    inquiry = ref->next;
	    ref->next = NULL;
	  }
    }

  if (!inquiry)
    {
      gfc_free_expr (tmp);
      return false;
    }

  gfc_resolve_expr (tmp);

1771 1772
  /* In principle there can be more than one inquiry reference.  */
  for (; inquiry; inquiry = inquiry->next)
1773
    {
1774 1775 1776 1777 1778
      switch (inquiry->u.i)
	{
	case INQUIRY_LEN:
	  if (tmp->ts.type != BT_CHARACTER)
	    goto cleanup;
1779

1780 1781
	  if (!gfc_notify_std (GFC_STD_F2003, "LEN part_ref at %C"))
	    goto cleanup;
1782

1783 1784 1785
	  if (!tmp->ts.u.cl->length
	      || tmp->ts.u.cl->length->expr_type != EXPR_CONSTANT)
	    goto cleanup;
1786

1787 1788
	  *newp = gfc_copy_expr (tmp->ts.u.cl->length);
	  break;
1789

1790 1791 1792
	case INQUIRY_KIND:
	  if (tmp->ts.type == BT_DERIVED || tmp->ts.type == BT_CLASS)
	    goto cleanup;
1793

1794 1795
	  if (!gfc_notify_std (GFC_STD_F2003, "KIND part_ref at %C"))
	    goto cleanup;
1796

1797 1798 1799
	  *newp = gfc_get_int_expr (gfc_default_integer_kind,
				    NULL, tmp->ts.kind);
	  break;
1800

1801 1802 1803
	case INQUIRY_RE:
	  if (tmp->ts.type != BT_COMPLEX || tmp->expr_type != EXPR_CONSTANT)
	    goto cleanup;
1804

1805 1806
	  if (!gfc_notify_std (GFC_STD_F2008, "RE part_ref at %C"))
	    goto cleanup;
1807

1808 1809 1810 1811
	  *newp = gfc_get_constant_expr (BT_REAL, tmp->ts.kind, &tmp->where);
	  mpfr_set ((*newp)->value.real,
		    mpc_realref (p->value.complex), GFC_RND_MODE);
	  break;
1812

1813 1814 1815
	case INQUIRY_IM:
	  if (tmp->ts.type != BT_COMPLEX || tmp->expr_type != EXPR_CONSTANT)
	    goto cleanup;
1816

1817 1818
	  if (!gfc_notify_std (GFC_STD_F2008, "IM part_ref at %C"))
	    goto cleanup;
1819

1820 1821 1822 1823 1824 1825
	  *newp = gfc_get_constant_expr (BT_REAL, tmp->ts.kind, &tmp->where);
	  mpfr_set ((*newp)->value.real,
		    mpc_imagref (p->value.complex), GFC_RND_MODE);
	  break;
	}
      tmp = gfc_copy_expr (*newp);
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
    }

  if (!(*newp))
    goto cleanup;
  else if ((*newp)->expr_type != EXPR_CONSTANT)
    {
      gfc_free_expr (*newp);
      goto cleanup;
    }

  gfc_free_expr (tmp);
  return true;

cleanup:
  gfc_free_expr (tmp);
  return false;
}


1845

1846 1847 1848
/* Simplify a subobject reference of a constructor.  This occurs when
   parameter variable values are substituted.  */

1849
static bool
1850
simplify_const_ref (gfc_expr *p)
1851
{
Jerry DeLisle committed
1852
  gfc_constructor *cons, *c;
1853
  gfc_expr *newp = NULL;
1854
  gfc_ref *last_ref;
1855 1856 1857 1858 1859 1860 1861 1862 1863

  while (p->ref)
    {
      switch (p->ref->type)
	{
	case REF_ARRAY:
	  switch (p->ref->u.ar.type)
	    {
	    case AR_ELEMENT:
1864 1865 1866 1867 1868 1869 1870
	      /* <type/kind spec>, parameter :: x(<int>) = scalar_expr
		 will generate this.  */
	      if (p->expr_type != EXPR_ARRAY)
		{
		  remove_subobject_ref (p, NULL);
		  break;
		}
1871 1872
	      if (!find_array_element (p->value.constructor, &p->ref->u.ar, &cons))
		return false;
1873

1874
	      if (!cons)
1875
		return true;
1876

1877 1878 1879
	      remove_subobject_ref (p, cons);
	      break;

1880
	    case AR_SECTION:
1881 1882
	      if (!find_array_section (p, p->ref))
		return false;
1883 1884
	      p->ref->u.ar.type = AR_FULL;

1885
	    /* Fall through.  */
1886

1887
	    case AR_FULL:
1888
	      if (p->ref->next != NULL
1889
		  && (p->ts.type == BT_CHARACTER || gfc_bt_struct (p->ts.type)))
1890
		{
Jerry DeLisle committed
1891 1892
		  for (c = gfc_constructor_first (p->value.constructor);
		       c; c = gfc_constructor_next (c))
1893
		    {
Jerry DeLisle committed
1894
		      c->expr->ref = gfc_copy_ref (p->ref->next);
1895 1896
		      if (!simplify_const_ref (c->expr))
			return false;
1897 1898
		    }

1899
		  if (gfc_bt_struct (p->ts.type)
1900
			&& p->ref->next
Jerry DeLisle committed
1901
			&& (c = gfc_constructor_first (p->value.constructor)))
1902
		    {
1903
		      /* There may have been component references.  */
Jerry DeLisle committed
1904
		      p->ts = c->expr->ts;
1905
		    }
1906

1907 1908
		  last_ref = p->ref;
		  for (; last_ref->next; last_ref = last_ref->next) {};
1909

1910 1911 1912 1913 1914 1915 1916
		  if (p->ts.type == BT_CHARACTER
			&& last_ref->type == REF_SUBSTRING)
		    {
		      /* If this is a CHARACTER array and we possibly took
			 a substring out of it, update the type-spec's
			 character length according to the first element
			 (as all should have the same length).  */
1917
		      gfc_charlen_t string_len;
Jerry DeLisle committed
1918
		      if ((c = gfc_constructor_first (p->value.constructor)))
1919
			{
Jerry DeLisle committed
1920
			  const gfc_expr* first = c->expr;
1921 1922 1923 1924 1925 1926 1927
			  gcc_assert (first->expr_type == EXPR_CONSTANT);
			  gcc_assert (first->ts.type == BT_CHARACTER);
			  string_len = first->value.character.length;
			}
		      else
			string_len = 0;

1928
		      if (!p->ts.u.cl)
1929 1930 1931 1932 1933 1934 1935 1936
			{
			  if (p->symtree)
			    p->ts.u.cl = gfc_new_charlen (p->symtree->n.sym->ns,
							  NULL);
			  else
			    p->ts.u.cl = gfc_new_charlen (gfc_current_ns,
							  NULL);
			}
1937 1938 1939
		      else
			gfc_free_expr (p->ts.u.cl->length);

Jerry DeLisle committed
1940
		      p->ts.u.cl->length
1941
			= gfc_get_int_expr (gfc_charlen_int_kind,
Jerry DeLisle committed
1942
					    NULL, string_len);
1943
		    }
1944
		}
1945 1946
	      gfc_free_ref_list (p->ref);
	      p->ref = NULL;
1947 1948 1949
	      break;

	    default:
1950
	      return true;
1951 1952 1953 1954 1955 1956 1957 1958 1959
	    }

	  break;

	case REF_COMPONENT:
	  cons = find_component_ref (p->value.constructor, p->ref);
	  remove_subobject_ref (p, cons);
	  break;

1960 1961 1962 1963 1964 1965 1966 1967 1968
	case REF_INQUIRY:
	  if (!find_inquiry_ref (p, &newp))
	    return false;

	  gfc_replace_expr (p, newp);
	  gfc_free_ref_list (p->ref);
	  p->ref = NULL;
	  break;

1969
	case REF_SUBSTRING:
1970
	  if (!find_substring_ref (p, &newp))
1971
	    return false;
1972 1973 1974 1975 1976

	  gfc_replace_expr (p, newp);
	  gfc_free_ref_list (p->ref);
	  p->ref = NULL;
	  break;
1977 1978 1979
	}
    }

1980
  return true;
1981 1982 1983 1984 1985
}


/* Simplify a chain of references.  */

1986
static bool
1987
simplify_ref_chain (gfc_ref *ref, int type, gfc_expr **p)
1988 1989
{
  int n;
1990
  gfc_expr *newp;
1991 1992 1993 1994 1995 1996 1997 1998

  for (; ref; ref = ref->next)
    {
      switch (ref->type)
	{
	case REF_ARRAY:
	  for (n = 0; n < ref->u.ar.dimen; n++)
	    {
1999 2000 2001 2002 2003 2004
	      if (!gfc_simplify_expr (ref->u.ar.start[n], type))
		return false;
	      if (!gfc_simplify_expr (ref->u.ar.end[n], type))
		return false;
	      if (!gfc_simplify_expr (ref->u.ar.stride[n], type))
		return false;
2005 2006 2007 2008
	    }
	  break;

	case REF_SUBSTRING:
2009 2010 2011 2012
	  if (!gfc_simplify_expr (ref->u.ss.start, type))
	    return false;
	  if (!gfc_simplify_expr (ref->u.ss.end, type))
	    return false;
2013 2014
	  break;

2015 2016 2017 2018 2019 2020 2021
	case REF_INQUIRY:
	  if (!find_inquiry_ref (*p, &newp))
	    return false;

	  gfc_replace_expr (*p, newp);
	  gfc_free_ref_list ((*p)->ref);
	  (*p)->ref = NULL;
2022
	  return true;
2023

2024 2025 2026 2027
	default:
	  break;
	}
    }
2028
  return true;
2029 2030 2031 2032
}


/* Try to substitute the value of a parameter variable.  */
2033

2034
static bool
2035
simplify_parameter_variable (gfc_expr *p, int type)
2036 2037
{
  gfc_expr *e;
2038
  bool t;
2039

2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055
  if (gfc_is_size_zero_array (p))
    {
      if (p->expr_type == EXPR_ARRAY)
	return true;

      e = gfc_get_expr ();
      e->expr_type = EXPR_ARRAY;
      e->ts = p->ts;
      e->rank = p->rank;
      e->value.constructor = NULL;
      e->shape = gfc_copy_shape (p->shape, p->rank);
      e->where = p->where;
      gfc_replace_expr (p, e);
      return true;
    }

2056
  e = gfc_copy_expr (p->symtree->n.sym->value);
2057
  if (e == NULL)
2058
    return false;
2059

2060 2061
  e->rank = p->rank;

2062 2063
  /* Do not copy subobject refs for constant.  */
  if (e->expr_type != EXPR_CONSTANT && p->ref != NULL)
2064
    e->ref = gfc_copy_ref (p->ref);
2065 2066
  t = gfc_simplify_expr (e, type);

2067
  /* Only use the simplification if it eliminated all subobject references.  */
2068
  if (t && !e->ref)
2069 2070 2071 2072 2073 2074 2075
    gfc_replace_expr (p, e);
  else
    gfc_free_expr (e);

  return t;
}

2076 2077 2078 2079

static bool
scalarize_intrinsic_call (gfc_expr *, bool init_flag);

2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
/* Given an expression, simplify it by collapsing constant
   expressions.  Most simplification takes place when the expression
   tree is being constructed.  If an intrinsic function is simplified
   at some point, we get called again to collapse the result against
   other constants.

   We work by recursively simplifying expression nodes, simplifying
   intrinsic functions where possible, which can lead to further
   constant collapsing.  If an operator has constant operand(s), we
   rip the expression apart, and rebuild it, hoping that it becomes
   something simpler.

   The expression type is defined for:
     0   Basic expression parsing
     1   Simplifying array constructors -- will substitute
2095
	 iterator values.
2096
   Returns false on error, true otherwise.
2097
   NOTE: Will return true even if the expression cannot be simplified.  */
2098

2099
bool
2100
gfc_simplify_expr (gfc_expr *p, int type)
2101 2102
{
  gfc_actual_arglist *ap;
2103 2104
  gfc_intrinsic_sym* isym = NULL;

2105 2106

  if (p == NULL)
2107
    return true;
2108 2109 2110 2111

  switch (p->expr_type)
    {
    case EXPR_CONSTANT:
2112 2113 2114
      if (p->ref && p->ref->type == REF_INQUIRY)
	simplify_ref_chain (p->ref, type, &p);
      break;
2115 2116 2117 2118
    case EXPR_NULL:
      break;

    case EXPR_FUNCTION:
2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
      // For array-bound functions, we don't need to optimize
      // the 'array' argument. In particular, if the argument
      // is a PARAMETER, simplifying might convert an EXPR_VARIABLE
      // into an EXPR_ARRAY; the latter has lbound = 1, the former
      // can have any lbound.
      ap = p->value.function.actual;
      if (p->value.function.isym &&
	  (p->value.function.isym->id == GFC_ISYM_LBOUND
	   || p->value.function.isym->id == GFC_ISYM_UBOUND
	   || p->value.function.isym->id == GFC_ISYM_LCOBOUND
	   || p->value.function.isym->id == GFC_ISYM_UCOBOUND))
	ap = ap->next;

      for ( ; ap; ap = ap->next)
2133 2134
	if (!gfc_simplify_expr (ap->expr, type))
	  return false;
2135 2136 2137

      if (p->value.function.isym != NULL
	  && gfc_intrinsic_func_interface (p, 1) == MATCH_ERROR)
2138
	return false;
2139

2140 2141 2142 2143 2144 2145 2146 2147
      if (p->expr_type == EXPR_FUNCTION)
	{
	  if (p->symtree)
	    isym = gfc_find_function (p->symtree->n.sym->name);
	  if (isym && isym->elemental)
	    scalarize_intrinsic_call (p, false);
	}

2148 2149 2150
      break;

    case EXPR_SUBSTRING:
2151
      if (!simplify_ref_chain (p->ref, type, &p))
2152
	return false;
2153

2154 2155
      if (gfc_is_constant_expr (p))
	{
2156
	  gfc_char_t *s;
2157
	  HOST_WIDE_INT start, end;
2158

2159
	  start = 0;
2160 2161
	  if (p->ref && p->ref->u.ss.start)
	    {
2162
	      gfc_extract_hwi (p->ref->u.ss.start, &start);
2163 2164 2165
	      start--;  /* Convert from one-based to zero-based.  */
	    }

2166
	  end = p->value.character.length;
2167
	  if (p->ref && p->ref->u.ss.end)
2168
	    gfc_extract_hwi (p->ref->u.ss.end, &end);
2169

2170 2171
	  if (end < start)
	    end = start;
2172

2173 2174 2175
	  s = gfc_get_wide_string (end - start + 2);
	  memcpy (s, p->value.character.string + start,
		  (end - start) * sizeof (gfc_char_t));
2176
	  s[end - start + 1] = '\0';  /* TODO: C-style string.  */
2177
	  free (p->value.character.string);
2178 2179
	  p->value.character.string = s;
	  p->value.character.length = end - start;
2180
	  p->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
2181
	  p->ts.u.cl->length = gfc_get_int_expr (gfc_charlen_int_kind,
Jerry DeLisle committed
2182 2183
						 NULL,
						 p->value.character.length);
2184 2185 2186 2187
	  gfc_free_ref_list (p->ref);
	  p->ref = NULL;
	  p->expr_type = EXPR_CONSTANT;
	}
2188 2189 2190
      break;

    case EXPR_OP:
2191 2192
      if (!simplify_intrinsic_op (p, type))
	return false;
2193 2194 2195 2196
      break;

    case EXPR_VARIABLE:
      /* Only substitute array parameter variables if we are in an
2197
	 initialization expression, or we want a subsection.  */
2198
      if (p->symtree->n.sym->attr.flavor == FL_PARAMETER
2199
	  && (gfc_init_expr_flag || p->ref
2200
	      || p->symtree->n.sym->value->expr_type != EXPR_ARRAY))
2201
	{
2202 2203
	  if (!simplify_parameter_variable (p, type))
	    return false;
2204 2205 2206 2207 2208 2209 2210 2211 2212
	  break;
	}

      if (type == 1)
	{
	  gfc_simplify_iterator_var (p);
	}

      /* Simplify subcomponent references.  */
2213
      if (!simplify_ref_chain (p->ref, type, &p))
2214
	return false;
2215 2216 2217 2218 2219

      break;

    case EXPR_STRUCTURE:
    case EXPR_ARRAY:
2220
      if (!simplify_ref_chain (p->ref, type, &p))
2221
	return false;
2222

2223 2224
      if (!simplify_constructor (p->value.constructor, type))
	return false;
2225

2226 2227
      if (p->expr_type == EXPR_ARRAY && p->ref && p->ref->type == REF_ARRAY
	  && p->ref->u.ar.type == AR_FULL)
2228
	  gfc_expand_constructor (p, false);
2229

2230 2231
      if (!simplify_const_ref (p))
	return false;
2232 2233

      break;
2234 2235

    case EXPR_COMPCALL:
2236
    case EXPR_PPC:
2237
      break;
2238 2239 2240

    case EXPR_UNKNOWN:
      gcc_unreachable ();
2241 2242
    }

2243
  return true;
2244 2245 2246 2247 2248 2249 2250 2251
}


/* Returns the type of an expression with the exception that iterator
   variables are automatically integers no matter what else they may
   be declared as.  */

static bt
2252
et0 (gfc_expr *e)
2253
{
2254
  if (e->expr_type == EXPR_VARIABLE && gfc_check_iter_variable (e))
2255 2256 2257 2258 2259 2260
    return BT_INTEGER;

  return e->ts.type;
}


2261 2262
/* Scalarize an expression for an elemental intrinsic call.  */

2263
static bool
2264
scalarize_intrinsic_call (gfc_expr *e, bool init_flag)
2265 2266
{
  gfc_actual_arglist *a, *b;
Jerry DeLisle committed
2267
  gfc_constructor_base ctor;
2268
  gfc_constructor *args[5] = {};  /* Avoid uninitialized warnings.  */
Jerry DeLisle committed
2269
  gfc_constructor *ci, *new_ctor;
2270
  gfc_expr *expr, *old;
Paul Thomas committed
2271
  int n, i, rank[5], array_arg;
2272 2273 2274 2275 2276 2277 2278 2279 2280
  int errors = 0;

  if (e == NULL)
    return false;

  a = e->value.function.actual;
  for (; a; a = a->next)
    if (a->expr && !gfc_is_constant_expr (a->expr))
      return false;
2281

Paul Thomas committed
2282 2283 2284 2285
  /* Find which, if any, arguments are arrays.  Assume that the old
     expression carries the type information and that the first arg
     that is an array expression carries all the shape information.*/
  n = array_arg = 0;
2286
  a = e->value.function.actual;
Paul Thomas committed
2287 2288 2289
  for (; a; a = a->next)
    {
      n++;
2290
      if (!a->expr || a->expr->expr_type != EXPR_ARRAY)
Paul Thomas committed
2291 2292 2293 2294 2295 2296 2297
	continue;
      array_arg = n;
      expr = gfc_copy_expr (a->expr);
      break;
    }

  if (!array_arg)
2298
    return false;
2299 2300

  old = gfc_copy_expr (e);
Paul Thomas committed
2301

Jerry DeLisle committed
2302
  gfc_constructor_free (expr->value.constructor);
2303 2304
  expr->value.constructor = NULL;
  expr->ts = old->ts;
Paul Thomas committed
2305
  expr->where = old->where;
2306 2307 2308 2309 2310 2311 2312 2313 2314
  expr->expr_type = EXPR_ARRAY;

  /* Copy the array argument constructors into an array, with nulls
     for the scalars.  */
  n = 0;
  a = old->value.function.actual;
  for (; a; a = a->next)
    {
      /* Check that this is OK for an initialization expression.  */
2315
      if (a->expr && init_flag && !gfc_check_init_expr (a->expr))
2316 2317 2318 2319 2320 2321 2322
	goto cleanup;

      rank[n] = 0;
      if (a->expr && a->expr->rank && a->expr->expr_type == EXPR_VARIABLE)
	{
	  rank[n] = a->expr->rank;
	  ctor = a->expr->symtree->n.sym->value->value.constructor;
Jerry DeLisle committed
2323
	  args[n] = gfc_constructor_first (ctor);
2324 2325 2326 2327 2328 2329 2330
	}
      else if (a->expr && a->expr->expr_type == EXPR_ARRAY)
	{
	  if (a->expr->rank)
	    rank[n] = a->expr->rank;
	  else
	    rank[n] = 1;
Jerry DeLisle committed
2331 2332
	  ctor = gfc_constructor_copy (a->expr->value.constructor);
	  args[n] = gfc_constructor_first (ctor);
2333 2334 2335
	}
      else
	args[n] = NULL;
Jerry DeLisle committed
2336

2337 2338 2339
      n++;
    }

2340
  gfc_get_errors (NULL, &errors);
2341

2342
  /* Using the array argument as the master, step through the array
2343 2344
     calling the function for each element and advancing the array
     constructors together.  */
Jerry DeLisle committed
2345
  for (ci = args[array_arg - 1]; ci; ci = gfc_constructor_next (ci))
2346
    {
Jerry DeLisle committed
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357
      new_ctor = gfc_constructor_append_expr (&expr->value.constructor,
					      gfc_copy_expr (old), NULL);

      gfc_free_actual_arglist (new_ctor->expr->value.function.actual);
      a = NULL;
      b = old->value.function.actual;
      for (i = 0; i < n; i++)
	{
	  if (a == NULL)
	    new_ctor->expr->value.function.actual
			= a = gfc_get_actual_arglist ();
2358 2359
	  else
	    {
Jerry DeLisle committed
2360 2361
	      a->next = gfc_get_actual_arglist ();
	      a = a->next;
2362 2363
	    }

Jerry DeLisle committed
2364 2365 2366 2367 2368 2369 2370
	  if (args[i])
	    a->expr = gfc_copy_expr (args[i]->expr);
	  else
	    a->expr = gfc_copy_expr (b->expr);

	  b = b->next;
	}
2371

Jerry DeLisle committed
2372 2373 2374
      /* Simplify the function calls.  If the simplification fails, the
	 error will be flagged up down-stream or the library will deal
	 with it.  */
2375 2376
      if (errors == 0)
	gfc_simplify_expr (new_ctor->expr, 0);
2377

Jerry DeLisle committed
2378 2379 2380
      for (i = 0; i < n; i++)
	if (args[i])
	  args[i] = gfc_constructor_next (args[i]);
2381

Jerry DeLisle committed
2382 2383 2384 2385
      for (i = 1; i < n; i++)
	if (rank[i] && ((args[i] != NULL && args[array_arg - 1] == NULL)
			|| (args[i] == NULL && args[array_arg - 1] != NULL)))
	  goto compliance;
2386 2387 2388 2389
    }

  free_expr0 (e);
  *e = *expr;
2390 2391
  /* Free "expr" but not the pointers it contains.  */
  free (expr);
2392
  gfc_free_expr (old);
2393
  return true;
2394 2395 2396 2397 2398 2399 2400

compliance:
  gfc_error_now ("elemental function arguments at %C are not compliant");

cleanup:
  gfc_free_expr (expr);
  gfc_free_expr (old);
2401
  return false;
2402 2403 2404
}


2405 2406
static bool
check_intrinsic_op (gfc_expr *e, bool (*check_function) (gfc_expr *))
2407
{
2408 2409
  gfc_expr *op1 = e->value.op.op1;
  gfc_expr *op2 = e->value.op.op2;
2410

2411 2412
  if (!(*check_function)(op1))
    return false;
2413

2414
  switch (e->value.op.op)
2415 2416 2417
    {
    case INTRINSIC_UPLUS:
    case INTRINSIC_UMINUS:
2418
      if (!numeric_type (et0 (op1)))
2419 2420 2421 2422
	goto not_numeric;
      break;

    case INTRINSIC_EQ:
2423
    case INTRINSIC_EQ_OS:
2424
    case INTRINSIC_NE:
2425
    case INTRINSIC_NE_OS:
2426
    case INTRINSIC_GT:
2427
    case INTRINSIC_GT_OS:
2428
    case INTRINSIC_GE:
2429
    case INTRINSIC_GE_OS:
2430
    case INTRINSIC_LT:
2431
    case INTRINSIC_LT_OS:
2432
    case INTRINSIC_LE:
2433
    case INTRINSIC_LE_OS:
2434 2435
      if (!(*check_function)(op2))
	return false;
2436

2437 2438
      if (!(et0 (op1) == BT_CHARACTER && et0 (op2) == BT_CHARACTER)
	  && !(numeric_type (et0 (op1)) && numeric_type (et0 (op2))))
2439 2440 2441
	{
	  gfc_error ("Numeric or CHARACTER operands are required in "
		     "expression at %L", &e->where);
2442
	 return false;
2443 2444
	}
      break;
2445 2446 2447 2448 2449 2450

    case INTRINSIC_PLUS:
    case INTRINSIC_MINUS:
    case INTRINSIC_TIMES:
    case INTRINSIC_DIVIDE:
    case INTRINSIC_POWER:
2451 2452
      if (!(*check_function)(op2))
	return false;
2453

2454
      if (!numeric_type (et0 (op1)) || !numeric_type (et0 (op2)))
2455 2456 2457 2458 2459
	goto not_numeric;

      break;

    case INTRINSIC_CONCAT:
2460 2461
      if (!(*check_function)(op2))
	return false;
2462

2463
      if (et0 (op1) != BT_CHARACTER || et0 (op2) != BT_CHARACTER)
2464 2465
	{
	  gfc_error ("Concatenation operator in expression at %L "
2466
		     "must have two CHARACTER operands", &op1->where);
2467
	  return false;
2468 2469
	}

2470
      if (op1->ts.kind != op2->ts.kind)
2471 2472 2473
	{
	  gfc_error ("Concat operator at %L must concatenate strings of the "
		     "same kind", &e->where);
2474
	  return false;
2475 2476 2477 2478 2479
	}

      break;

    case INTRINSIC_NOT:
2480
      if (et0 (op1) != BT_LOGICAL)
2481 2482
	{
	  gfc_error (".NOT. operator in expression at %L must have a LOGICAL "
2483
		     "operand", &op1->where);
2484
	  return false;
2485 2486 2487 2488 2489 2490 2491 2492
	}

      break;

    case INTRINSIC_AND:
    case INTRINSIC_OR:
    case INTRINSIC_EQV:
    case INTRINSIC_NEQV:
2493 2494
      if (!(*check_function)(op2))
	return false;
2495

2496
      if (et0 (op1) != BT_LOGICAL || et0 (op2) != BT_LOGICAL)
2497 2498 2499
	{
	  gfc_error ("LOGICAL operands are required in expression at %L",
		     &e->where);
2500
	  return false;
2501 2502 2503 2504
	}

      break;

2505 2506 2507
    case INTRINSIC_PARENTHESES:
      break;

2508 2509 2510
    default:
      gfc_error ("Only intrinsic operators can be used in expression at %L",
		 &e->where);
2511
      return false;
2512 2513
    }

2514
  return true;
2515 2516 2517 2518

not_numeric:
  gfc_error ("Numeric operands are required in expression at %L", &e->where);

2519
  return false;
2520 2521
}

2522 2523
/* F2003, 7.1.7 (3): In init expression, allocatable components
   must not be data-initialized.  */
2524
static bool
2525 2526
check_alloc_comp_init (gfc_expr *e)
{
Jerry DeLisle committed
2527
  gfc_component *comp;
2528 2529 2530
  gfc_constructor *ctor;

  gcc_assert (e->expr_type == EXPR_STRUCTURE);
2531
  gcc_assert (e->ts.type == BT_DERIVED || e->ts.type == BT_CLASS);
2532

Jerry DeLisle committed
2533 2534 2535
  for (comp = e->ts.u.derived->components,
       ctor = gfc_constructor_first (e->value.constructor);
       comp; comp = comp->next, ctor = gfc_constructor_next (ctor))
2536
    {
2537
      if (comp->attr.allocatable && ctor->expr
2538 2539
          && ctor->expr->expr_type != EXPR_NULL)
        {
2540 2541 2542
	  gfc_error ("Invalid initialization expression for ALLOCATABLE "
		     "component %qs in structure constructor at %L",
		     comp->name, &ctor->expr->where);
2543
	  return false;
2544 2545 2546
	}
    }

2547
  return true;
2548
}
2549

2550 2551 2552 2553
static match
check_init_expr_arguments (gfc_expr *e)
{
  gfc_actual_arglist *ap;
2554

2555
  for (ap = e->value.function.actual; ap; ap = ap->next)
2556
    if (!gfc_check_init_expr (ap->expr))
2557
      return MATCH_ERROR;
2558

2559 2560 2561
  return MATCH_YES;
}

2562
static bool check_restricted (gfc_expr *);
2563

2564
/* F95, 7.1.6.1, Initialization expressions, (7)
2565 2566
   F2003, 7.1.7 Initialization expression, (8)
   F2008, 7.1.12 Constant expression, (4)  */
2567 2568

static match
2569
check_inquiry (gfc_expr *e, int not_restricted)
2570 2571
{
  const char *name;
2572 2573 2574 2575 2576 2577 2578 2579 2580
  const char *const *functions;

  static const char *const inquiry_func_f95[] = {
    "lbound", "shape", "size", "ubound",
    "bit_size", "len", "kind",
    "digits", "epsilon", "huge", "maxexponent", "minexponent",
    "precision", "radix", "range", "tiny",
    NULL
  };
2581

2582 2583 2584 2585 2586 2587
  static const char *const inquiry_func_f2003[] = {
    "lbound", "shape", "size", "ubound",
    "bit_size", "len", "kind",
    "digits", "epsilon", "huge", "maxexponent", "minexponent",
    "precision", "radix", "range", "tiny",
    "new_line", NULL
2588 2589
  };

2590 2591 2592 2593 2594 2595 2596 2597 2598
  /* std=f2008+ or -std=gnu */
  static const char *const inquiry_func_gnu[] = {
    "lbound", "shape", "size", "ubound",
    "bit_size", "len", "kind",
    "digits", "epsilon", "huge", "maxexponent", "minexponent",
    "precision", "radix", "range", "tiny",
    "new_line", "storage_size", NULL
  };

2599
  int i = 0;
2600 2601 2602 2603 2604
  gfc_actual_arglist *ap;

  if (!e->value.function.isym
      || !e->value.function.isym->inquiry)
    return MATCH_NO;
2605

2606 2607
  /* An undeclared parameter will get us here (PR25018).  */
  if (e->symtree == NULL)
2608
    return MATCH_NO;
2609

2610 2611 2612 2613 2614 2615
  if (e->symtree->n.sym->from_intmod)
    {
      if (e->symtree->n.sym->from_intmod == INTMOD_ISO_FORTRAN_ENV
	  && e->symtree->n.sym->intmod_sym_id != ISOFORTRAN_COMPILER_OPTIONS
	  && e->symtree->n.sym->intmod_sym_id != ISOFORTRAN_COMPILER_VERSION)
	return MATCH_NO;
2616

2617 2618 2619 2620 2621 2622 2623 2624
      if (e->symtree->n.sym->from_intmod == INTMOD_ISO_C_BINDING
	  && e->symtree->n.sym->intmod_sym_id != ISOCBINDING_C_SIZEOF)
	return MATCH_NO;
    }
  else
    {
      name = e->symtree->n.sym->name;

2625 2626 2627 2628 2629
      functions = inquiry_func_gnu;
      if (gfc_option.warn_std & GFC_STD_F2003)
	functions = inquiry_func_f2003;
      if (gfc_option.warn_std & GFC_STD_F95)
	functions = inquiry_func_f95;
2630

2631 2632 2633
      for (i = 0; functions[i]; i++)
	if (strcmp (functions[i], name) == 0)
	  break;
2634

2635 2636
      if (functions[i] == NULL)
	return MATCH_ERROR;
2637
    }
2638

2639 2640
  /* At this point we have an inquiry function with a variable argument.  The
     type of the variable might be undefined, but we need it now, because the
2641
     arguments of these functions are not allowed to be undefined.  */
2642

2643
  for (ap = e->value.function.actual; ap; ap = ap->next)
2644
    {
2645 2646 2647 2648 2649 2650
      if (!ap->expr)
	continue;

      if (ap->expr->ts.type == BT_UNKNOWN)
	{
	  if (ap->expr->symtree->n.sym->ts.type == BT_UNKNOWN
2651
	      && !gfc_set_default_type (ap->expr->symtree->n.sym, 0, gfc_current_ns))
2652
	    return MATCH_NO;
2653

2654 2655 2656 2657 2658
	  ap->expr->ts = ap->expr->symtree->n.sym->ts;
	}

	/* Assumed character length will not reduce to a constant expression
	   with LEN, as required by the standard.  */
2659
	if (i == 5 && not_restricted && ap->expr->symtree
2660
	    && ap->expr->symtree->n.sym->ts.type == BT_CHARACTER
Steven G. Kargl committed
2661 2662
	    && (ap->expr->symtree->n.sym->ts.u.cl->length == NULL
		|| ap->expr->symtree->n.sym->ts.deferred))
2663
	  {
2664
	    gfc_error ("Assumed or deferred character length variable %qs "
2665
			"in constant expression at %L",
Steven G. Kargl committed
2666 2667
			ap->expr->symtree->n.sym->name,
			&ap->expr->where);
2668 2669
	      return MATCH_ERROR;
	  }
2670
	else if (not_restricted && !gfc_check_init_expr (ap->expr))
2671
	  return MATCH_ERROR;
2672 2673 2674

	if (not_restricted == 0
	      && ap->expr->expr_type != EXPR_VARIABLE
2675
	      && !check_restricted (ap->expr))
2676
	  return MATCH_ERROR;
2677 2678 2679 2680 2681 2682

	if (not_restricted == 0
	    && ap->expr->expr_type == EXPR_VARIABLE
	    && ap->expr->symtree->n.sym->attr.dummy
	    && ap->expr->symtree->n.sym->attr.optional)
	  return MATCH_NO;
2683 2684
    }

2685 2686 2687
  return MATCH_YES;
}

2688

2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699
/* F95, 7.1.6.1, Initialization expressions, (5)
   F2003, 7.1.7 Initialization expression, (5)  */

static match
check_transformational (gfc_expr *e)
{
  static const char * const trans_func_f95[] = {
    "repeat", "reshape", "selected_int_kind",
    "selected_real_kind", "transfer", "trim", NULL
  };

2700
  static const char * const trans_func_f2003[] =  {
2701 2702
    "all", "any", "count", "dot_product", "matmul", "null", "pack",
    "product", "repeat", "reshape", "selected_char_kind", "selected_int_kind",
2703 2704
    "selected_real_kind", "spread", "sum", "transfer", "transpose",
    "trim", "unpack", NULL
2705 2706
  };

2707 2708 2709 2710 2711 2712 2713
  static const char * const trans_func_f2008[] =  {
    "all", "any", "count", "dot_product", "matmul", "null", "pack",
    "product", "repeat", "reshape", "selected_char_kind", "selected_int_kind",
    "selected_real_kind", "spread", "sum", "transfer", "transpose",
    "trim", "unpack", "findloc", NULL
  };

2714 2715
  int i;
  const char *name;
2716
  const char *const *functions;
2717 2718 2719 2720 2721 2722 2723

  if (!e->value.function.isym
      || !e->value.function.isym->transformational)
    return MATCH_NO;

  name = e->symtree->n.sym->name;

2724 2725 2726 2727 2728 2729
  if (gfc_option.allow_std & GFC_STD_F2008)
    functions = trans_func_f2008;
  else if (gfc_option.allow_std & GFC_STD_F2003)
    functions = trans_func_f2003;
  else
    functions = trans_func_f95;
2730

2731 2732 2733 2734
  /* NULL() is dealt with below.  */
  if (strcmp ("null", name) == 0)
    return MATCH_NO;

2735 2736 2737
  for (i = 0; functions[i]; i++)
    if (strcmp (functions[i], name) == 0)
       break;
2738

2739
  if (functions[i] == NULL)
2740
    {
2741 2742
      gfc_error ("transformational intrinsic %qs at %L is not permitted "
		 "in an initialization expression", name, &e->where);
2743 2744
      return MATCH_ERROR;
    }
2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769

  return check_init_expr_arguments (e);
}


/* F95, 7.1.6.1, Initialization expressions, (6)
   F2003, 7.1.7 Initialization expression, (6)  */

static match
check_null (gfc_expr *e)
{
  if (strcmp ("null", e->symtree->n.sym->name) != 0)
    return MATCH_NO;

  return check_init_expr_arguments (e);
}


static match
check_elemental (gfc_expr *e)
{
  if (!e->value.function.isym
      || !e->value.function.isym->elemental)
    return MATCH_NO;

2770 2771
  if (e->ts.type != BT_INTEGER
      && e->ts.type != BT_CHARACTER
2772 2773
      && !gfc_notify_std (GFC_STD_F2003, "Evaluation of nonstandard "
			  "initialization expression at %L", &e->where))
2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787
    return MATCH_ERROR;

  return check_init_expr_arguments (e);
}


static match
check_conversion (gfc_expr *e)
{
  if (!e->value.function.isym
      || !e->value.function.isym->conversion)
    return MATCH_NO;

  return check_init_expr_arguments (e);
2788 2789 2790 2791 2792 2793 2794 2795
}


/* Verify that an expression is an initialization expression.  A side
   effect is that the expression tree is reduced to a single constant
   node if all goes well.  This would normally happen when the
   expression is constructed but function references are assumed to be
   intrinsics in the context of initialization expressions.  If
2796
   false is returned an error message has been generated.  */
2797

2798
bool
2799
gfc_check_init_expr (gfc_expr *e)
2800 2801
{
  match m;
2802
  bool t;
2803 2804

  if (e == NULL)
2805
    return true;
2806 2807 2808 2809

  switch (e->expr_type)
    {
    case EXPR_OP:
2810
      t = check_intrinsic_op (e, gfc_check_init_expr);
2811
      if (t)
2812 2813 2814 2815 2816
	t = gfc_simplify_expr (e, 0);

      break;

    case EXPR_FUNCTION:
2817
      t = false;
2818

2819
      {
2820 2821
	bool conversion;
	gfc_intrinsic_sym* isym = NULL;
2822 2823
	gfc_symbol* sym = e->symtree->n.sym;

2824 2825 2826 2827 2828 2829
	/* Simplify here the intrinsics from the IEEE_ARITHMETIC and
	   IEEE_EXCEPTIONS modules.  */
	int mod = sym->from_intmod;
	if (mod == INTMOD_NONE && sym->generic)
	  mod = sym->generic->sym->from_intmod;
	if (mod == INTMOD_IEEE_ARITHMETIC || mod == INTMOD_IEEE_EXCEPTIONS)
2830
	  {
2831
	    gfc_expr *new_expr = gfc_simplify_ieee_functions (e);
2832 2833 2834 2835 2836 2837 2838
	    if (new_expr)
	      {
		gfc_replace_expr (e, new_expr);
		t = true;
		break;
	      }
	  }
2839

2840 2841 2842 2843 2844 2845 2846 2847
	/* If a conversion function, e.g., __convert_i8_i4, was inserted
	   into an array constructor, we need to skip the error check here.
           Conversion errors are  caught below in scalarize_intrinsic_call.  */
	conversion = e->value.function.isym
		   && (e->value.function.isym->conversion == 1);

	if (!conversion && (!gfc_is_intrinsic (sym, 0, e->where)
	    || (m = gfc_intrinsic_func_interface (e, 0)) != MATCH_YES))
2848
	  {
2849
	    gfc_error ("Function %qs in initialization expression at %L "
2850 2851 2852 2853
		       "must be an intrinsic function",
		       e->symtree->n.sym->name, &e->where);
	    break;
	  }
2854

2855 2856 2857 2858 2859 2860
	if ((m = check_conversion (e)) == MATCH_NO
	    && (m = check_inquiry (e, 1)) == MATCH_NO
	    && (m = check_null (e)) == MATCH_NO
	    && (m = check_transformational (e)) == MATCH_NO
	    && (m = check_elemental (e)) == MATCH_NO)
	  {
2861
	    gfc_error ("Intrinsic function %qs at %L is not permitted "
2862 2863 2864 2865
		       "in an initialization expression",
		       e->symtree->n.sym->name, &e->where);
	    m = MATCH_ERROR;
	  }
2866

2867
	if (m == MATCH_ERROR)
2868
	  return false;
2869

2870 2871 2872 2873
	/* Try to scalarize an elemental intrinsic function that has an
	   array argument.  */
	isym = gfc_find_function (e->symtree->n.sym->name);
	if (isym && isym->elemental
2874
	    && (t = scalarize_intrinsic_call (e, true)))
2875 2876
	  break;
      }
2877

2878
      if (m == MATCH_YES)
2879
	t = gfc_simplify_expr (e, 0);
2880

2881 2882 2883
      break;

    case EXPR_VARIABLE:
2884
      t = true;
2885

2886
      /* This occurs when parsing pdt templates.  */
2887
      if (gfc_expr_attr (e).pdt_kind)
2888 2889
	break;

2890
      if (gfc_check_iter_variable (e))
2891 2892 2893 2894
	break;

      if (e->symtree->n.sym->attr.flavor == FL_PARAMETER)
	{
2895 2896 2897 2898 2899
	  /* A PARAMETER shall not be used to define itself, i.e.
		REAL, PARAMETER :: x = transfer(0, x)
	     is invalid.  */
	  if (!e->symtree->n.sym->value)
	    {
2900 2901
	      gfc_error ("PARAMETER %qs is used at %L before its definition "
			 "is complete", e->symtree->n.sym->name, &e->where);
2902
	      t = false;
2903 2904 2905 2906
	    }
	  else
	    t = simplify_parameter_variable (e, 0);

2907 2908 2909
	  break;
	}

2910 2911 2912
      if (gfc_in_match_data ())
	break;

2913
      t = false;
2914 2915 2916 2917 2918 2919

      if (e->symtree->n.sym->as)
	{
	  switch (e->symtree->n.sym->as->type)
	    {
	      case AS_ASSUMED_SIZE:
2920
		gfc_error ("Assumed size array %qs at %L is not permitted "
2921 2922
			   "in an initialization expression",
			   e->symtree->n.sym->name, &e->where);
2923
		break;
2924 2925

	      case AS_ASSUMED_SHAPE:
2926
		gfc_error ("Assumed shape array %qs at %L is not permitted "
2927 2928
			   "in an initialization expression",
			   e->symtree->n.sym->name, &e->where);
2929
		break;
2930 2931

	      case AS_DEFERRED:
2932 2933 2934 2935 2936 2937 2938 2939 2940 2941
		if (!e->symtree->n.sym->attr.allocatable
		    && !e->symtree->n.sym->attr.pointer
		    && e->symtree->n.sym->attr.dummy)
		  gfc_error ("Assumed-shape array %qs at %L is not permitted "
			     "in an initialization expression",
			     e->symtree->n.sym->name, &e->where);
		else
		  gfc_error ("Deferred array %qs at %L is not permitted "
			     "in an initialization expression",
			     e->symtree->n.sym->name, &e->where);
2942
		break;
2943

2944
	      case AS_EXPLICIT:
2945
		gfc_error ("Array %qs at %L is a variable, which does "
2946 2947 2948 2949
			   "not reduce to a constant expression",
			   e->symtree->n.sym->name, &e->where);
		break;

2950 2951 2952 2953 2954
	      default:
		gcc_unreachable();
	  }
	}
      else
2955
	gfc_error ("Parameter %qs at %L has not been declared or is "
2956
		   "a variable, which does not reduce to a constant "
2957
		   "expression", e->symtree->name, &e->where);
2958

2959 2960 2961 2962
      break;

    case EXPR_CONSTANT:
    case EXPR_NULL:
2963
      t = true;
2964 2965 2966
      break;

    case EXPR_SUBSTRING:
2967 2968 2969 2970 2971
      if (e->ref)
	{
	  t = gfc_check_init_expr (e->ref->u.ss.start);
	  if (!t)
	    break;
2972

2973 2974 2975 2976 2977 2978
	  t = gfc_check_init_expr (e->ref->u.ss.end);
	  if (t)
	    t = gfc_simplify_expr (e, 0);
	}
      else
	t = false;
2979 2980 2981
      break;

    case EXPR_STRUCTURE:
2982 2983
      t = e->ts.is_iso_c ? true : false;
      if (t)
2984 2985 2986
	break;

      t = check_alloc_comp_init (e);
2987
      if (!t)
2988 2989
	break;

2990
      t = gfc_check_constructor (e, gfc_check_init_expr);
2991
      if (!t)
2992 2993
	break;

2994 2995 2996
      break;

    case EXPR_ARRAY:
2997
      t = gfc_check_constructor (e, gfc_check_init_expr);
2998
      if (!t)
2999 3000
	break;

3001
      t = gfc_expand_constructor (e, true);
3002
      if (!t)
3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014
	break;

      t = gfc_check_constructor_type (e);
      break;

    default:
      gfc_internal_error ("check_init_expr(): Unknown expression type");
    }

  return t;
}

3015 3016
/* Reduces a general expression to an initialization expression (a constant).
   This used to be part of gfc_match_init_expr.
3017
   Note that this function doesn't free the given expression on false.  */
3018

3019
bool
3020
gfc_reduce_init_expr (gfc_expr *expr)
3021
{
3022
  bool t;
3023

3024
  gfc_init_expr_flag = true;
3025
  t = gfc_resolve_expr (expr);
3026
  if (t)
3027
    t = gfc_check_init_expr (expr);
3028
  gfc_init_expr_flag = false;
3029

3030
  if (!t || !expr)
3031
    return false;
3032

3033
  if (expr->expr_type == EXPR_ARRAY)
3034
    {
3035 3036 3037 3038
      if (!gfc_check_constructor_type (expr))
	return false;
      if (!gfc_expand_constructor (expr, true))
	return false;
3039 3040
    }

3041
  return true;
3042 3043 3044 3045
}


/* Match an initialization expression.  We work by first matching an
3046
   expression, then reducing it to a constant.  */
3047 3048 3049 3050 3051 3052

match
gfc_match_init_expr (gfc_expr **result)
{
  gfc_expr *expr;
  match m;
3053
  bool t;
3054 3055 3056

  expr = NULL;

3057
  gfc_init_expr_flag = true;
3058

3059 3060
  m = gfc_match_expr (&expr);
  if (m != MATCH_YES)
3061
    {
3062
      gfc_init_expr_flag = false;
3063 3064
      return m;
    }
3065

3066 3067 3068 3069 3070 3071 3072
  if (gfc_derived_parameter_expr (expr))
    {
      *result = expr;
      gfc_init_expr_flag = false;
      return m;
    }

3073
  t = gfc_reduce_init_expr (expr);
3074
  if (!t)
3075 3076
    {
      gfc_free_expr (expr);
3077
      gfc_init_expr_flag = false;
3078 3079
      return MATCH_ERROR;
    }
3080 3081

  *result = expr;
3082
  gfc_init_expr_flag = false;
3083 3084 3085 3086 3087 3088 3089 3090 3091

  return MATCH_YES;
}


/* Given an actual argument list, test to see that each argument is a
   restricted expression and optionally if the expression type is
   integer or character.  */

3092
static bool
3093
restricted_args (gfc_actual_arglist *a)
3094 3095 3096
{
  for (; a; a = a->next)
    {
3097 3098
      if (!check_restricted (a->expr))
	return false;
3099 3100
    }

3101
  return true;
3102 3103 3104 3105 3106 3107
}


/************* Restricted/specification expressions *************/


3108 3109
/* Make sure a non-intrinsic function is a specification function,
 * see F08:7.1.11.5.  */
3110

3111
static bool
3112
external_spec_function (gfc_expr *e)
3113 3114 3115 3116 3117
{
  gfc_symbol *f;

  f = e->value.function.esym;

3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130
  /* IEEE functions allowed are "a reference to a transformational function
     from the intrinsic module IEEE_ARITHMETIC or IEEE_EXCEPTIONS", and
     "inquiry function from the intrinsic modules IEEE_ARITHMETIC and
     IEEE_EXCEPTIONS".  */
  if (f->from_intmod == INTMOD_IEEE_ARITHMETIC
      || f->from_intmod == INTMOD_IEEE_EXCEPTIONS)
    {
      if (!strcmp (f->name, "ieee_selected_real_kind")
	  || !strcmp (f->name, "ieee_support_rounding")
	  || !strcmp (f->name, "ieee_support_flag")
	  || !strcmp (f->name, "ieee_support_halting")
	  || !strcmp (f->name, "ieee_support_datatype")
	  || !strcmp (f->name, "ieee_support_denormal")
3131
	  || !strcmp (f->name, "ieee_support_subnormal")
3132 3133 3134 3135 3136 3137 3138 3139 3140 3141
	  || !strcmp (f->name, "ieee_support_divide")
	  || !strcmp (f->name, "ieee_support_inf")
	  || !strcmp (f->name, "ieee_support_io")
	  || !strcmp (f->name, "ieee_support_nan")
	  || !strcmp (f->name, "ieee_support_sqrt")
	  || !strcmp (f->name, "ieee_support_standard")
	  || !strcmp (f->name, "ieee_support_underflow_control"))
	goto function_allowed;
    }

3142 3143
  if (f->attr.proc == PROC_ST_FUNCTION)
    {
3144
      gfc_error ("Specification function %qs at %L cannot be a statement "
3145
		 "function", f->name, &e->where);
3146
      return false;
3147 3148 3149 3150
    }

  if (f->attr.proc == PROC_INTERNAL)
    {
3151
      gfc_error ("Specification function %qs at %L cannot be an internal "
3152
		 "function", f->name, &e->where);
3153
      return false;
3154 3155
    }

3156
  if (!f->attr.pure && !f->attr.elemental)
3157
    {
3158
      gfc_error ("Specification function %qs at %L must be PURE", f->name,
3159
		 &e->where);
3160
      return false;
3161 3162
    }

Janus Weil committed
3163 3164 3165
  /* F08:7.1.11.6. */
  if (f->attr.recursive
      && !gfc_notify_std (GFC_STD_F2003,
3166
			  "Specification function %qs "
Janus Weil committed
3167
			  "at %L cannot be RECURSIVE",  f->name, &e->where))
3168
      return false;
3169

3170
function_allowed:
3171
  return restricted_args (e->value.function.actual);
3172 3173 3174 3175
}


/* Check to see that a function reference to an intrinsic is a
3176
   restricted expression.  */
3177

3178
static bool
3179
restricted_intrinsic (gfc_expr *e)
3180
{
3181
  /* TODO: Check constraints on inquiry functions.  7.1.6.2 (7).  */
3182
  if (check_inquiry (e, 0) == MATCH_YES)
3183
    return true;
3184

3185
  return restricted_args (e->value.function.actual);
3186 3187 3188
}


3189 3190
/* Check the expressions of an actual arglist.  Used by check_restricted.  */

3191 3192
static bool
check_arglist (gfc_actual_arglist* arg, bool (*checker) (gfc_expr*))
3193 3194
{
  for (; arg; arg = arg->next)
3195 3196
    if (!checker (arg->expr))
      return false;
3197

3198
  return true;
3199 3200 3201 3202 3203 3204
}


/* Check the subscription expressions of a reference chain with a checking
   function; used by check_restricted.  */

3205 3206
static bool
check_references (gfc_ref* ref, bool (*checker) (gfc_expr*))
3207 3208 3209 3210
{
  int dim;

  if (!ref)
3211
    return true;
3212 3213 3214 3215 3216 3217

  switch (ref->type)
    {
    case REF_ARRAY:
      for (dim = 0; dim != ref->u.ar.dimen; ++dim)
	{
3218 3219 3220 3221 3222 3223
	  if (!checker (ref->u.ar.start[dim]))
	    return false;
	  if (!checker (ref->u.ar.end[dim]))
	    return false;
	  if (!checker (ref->u.ar.stride[dim]))
	    return false;
3224 3225 3226 3227 3228 3229 3230 3231
	}
      break;

    case REF_COMPONENT:
      /* Nothing needed, just proceed to next reference.  */
      break;

    case REF_SUBSTRING:
3232 3233 3234 3235
      if (!checker (ref->u.ss.start))
	return false;
      if (!checker (ref->u.ss.end))
	return false;
3236 3237 3238 3239 3240 3241 3242 3243 3244 3245
      break;

    default:
      gcc_unreachable ();
      break;
    }

  return check_references (ref->next, checker);
}

3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257
/*  Return true if ns is a parent of the current ns.  */

static bool
is_parent_of_current_ns (gfc_namespace *ns)
{
  gfc_namespace *p;
  for (p = gfc_current_ns->parent; p; p = p->parent)
    if (ns == p)
      return true;

  return false;
}
3258

3259 3260
/* Verify that an expression is a restricted expression.  Like its
   cousin check_init_expr(), an error message is generated if we
3261
   return false.  */
3262

3263
static bool
3264
check_restricted (gfc_expr *e)
3265
{
3266
  gfc_symbol* sym;
3267
  bool t;
3268 3269

  if (e == NULL)
3270
    return true;
3271 3272 3273 3274 3275

  switch (e->expr_type)
    {
    case EXPR_OP:
      t = check_intrinsic_op (e, check_restricted);
3276
      if (t)
3277 3278 3279 3280 3281
	t = gfc_simplify_expr (e, 0);

      break;

    case EXPR_FUNCTION:
3282 3283 3284
      if (e->value.function.esym)
	{
	  t = check_arglist (e->value.function.actual, &check_restricted);
3285
	  if (t)
3286 3287 3288 3289 3290
	    t = external_spec_function (e);
	}
      else
	{
	  if (e->value.function.isym && e->value.function.isym->inquiry)
3291
	    t = true;
3292 3293 3294
	  else
	    t = check_arglist (e->value.function.actual, &check_restricted);

3295
	  if (t)
3296 3297
	    t = restricted_intrinsic (e);
	}
3298 3299 3300 3301
      break;

    case EXPR_VARIABLE:
      sym = e->symtree->n.sym;
3302
      t = false;
3303

3304 3305 3306 3307 3308 3309 3310 3311
      /* If a dummy argument appears in a context that is valid for a
	 restricted expression in an elemental procedure, it will have
	 already been simplified away once we get here.  Therefore we
	 don't need to jump through hoops to distinguish valid from
	 invalid cases.  */
      if (sym->attr.dummy && sym->ns == gfc_current_ns
	  && sym->ns->proc_name && sym->ns->proc_name->attr.elemental)
	{
3312
	  gfc_error ("Dummy argument %qs not allowed in expression at %L",
3313 3314 3315 3316
		     sym->name, &e->where);
	  break;
	}

3317 3318
      if (sym->attr.optional)
	{
3319
	  gfc_error ("Dummy argument %qs at %L cannot be OPTIONAL",
3320 3321 3322 3323 3324 3325
		     sym->name, &e->where);
	  break;
	}

      if (sym->attr.intent == INTENT_OUT)
	{
3326
	  gfc_error ("Dummy argument %qs at %L cannot be INTENT(OUT)",
3327 3328 3329 3330
		     sym->name, &e->where);
	  break;
	}

3331
      /* Check reference chain if any.  */
3332
      if (!check_references (e->ref, &check_restricted))
3333 3334
	break;

3335 3336 3337 3338 3339
      /* gfc_is_formal_arg broadcasts that a formal argument list is being
	 processed in resolve.c(resolve_formal_arglist).  This is done so
	 that host associated dummy array indices are accepted (PR23446).
	 This mechanism also does the same for the specification expressions
	 of array-valued functions.  */
3340 3341 3342 3343 3344
      if (e->error
	    || sym->attr.in_common
	    || sym->attr.use_assoc
	    || sym->attr.dummy
	    || sym->attr.implied_index
3345
	    || sym->attr.flavor == FL_PARAMETER
3346
	    || is_parent_of_current_ns (sym->ns)
3347 3348 3349
	    || (sym->ns->proc_name != NULL
		  && sym->ns->proc_name->attr.flavor == FL_MODULE)
	    || (gfc_is_formal_arg () && (sym->ns == gfc_current_ns)))
3350
	{
3351
	  t = true;
3352 3353 3354
	  break;
	}

3355
      gfc_error ("Variable %qs cannot appear in the expression at %L",
3356
		 sym->name, &e->where);
3357 3358
      /* Prevent a repetition of the error.  */
      e->error = 1;
3359 3360 3361 3362
      break;

    case EXPR_NULL:
    case EXPR_CONSTANT:
3363
      t = true;
3364 3365 3366
      break;

    case EXPR_SUBSTRING:
3367
      t = gfc_specification_expr (e->ref->u.ss.start);
3368
      if (!t)
3369 3370
	break;

3371
      t = gfc_specification_expr (e->ref->u.ss.end);
3372
      if (t)
3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393
	t = gfc_simplify_expr (e, 0);

      break;

    case EXPR_STRUCTURE:
      t = gfc_check_constructor (e, check_restricted);
      break;

    case EXPR_ARRAY:
      t = gfc_check_constructor (e, check_restricted);
      break;

    default:
      gfc_internal_error ("check_restricted(): Unknown expression type");
    }

  return t;
}


/* Check to see that an expression is a specification expression.  If
3394
   we return false, an error has been generated.  */
3395

3396
bool
3397
gfc_specification_expr (gfc_expr *e)
3398
{
3399
  gfc_component *comp;
3400

3401
  if (e == NULL)
3402
    return true;
3403 3404 3405

  if (e->ts.type != BT_INTEGER)
    {
3406 3407
      gfc_error ("Expression at %L must be of INTEGER type, found %s",
		 &e->where, gfc_basic_typename (e->ts.type));
3408
      return false;
3409 3410
    }

3411
  comp = gfc_get_proc_ptr_comp (e);
3412
  if (e->expr_type == EXPR_FUNCTION
3413 3414 3415 3416
      && !e->value.function.isym
      && !e->value.function.esym
      && !gfc_pure (e->symtree->n.sym)
      && (!comp || !comp->attr.pure))
3417
    {
3418
      gfc_error ("Function %qs at %L must be PURE",
3419 3420 3421
		 e->symtree->n.sym->name, &e->where);
      /* Prevent repeat error messages.  */
      e->symtree->n.sym->attr.pure = 1;
3422
      return false;
3423 3424
    }

3425 3426 3427
  if (e->rank != 0)
    {
      gfc_error ("Expression at %L must be scalar", &e->where);
3428
      return false;
3429 3430
    }

3431 3432
  if (!gfc_simplify_expr (e, 0))
    return false;
3433 3434 3435 3436 3437 3438 3439 3440 3441

  return check_restricted (e);
}


/************** Expression conformance checks.  *************/

/* Given two expressions, make sure that the arrays are conformable.  */

3442
bool
3443
gfc_check_conformance (gfc_expr *op1, gfc_expr *op2, const char *optype_msgid, ...)
3444 3445 3446
{
  int op1_flag, op2_flag, d;
  mpz_t op1_size, op2_size;
3447
  bool t;
3448

3449 3450 3451
  va_list argp;
  char buffer[240];

3452
  if (op1->rank == 0 || op2->rank == 0)
3453
    return true;
3454

3455 3456 3457 3458
  va_start (argp, optype_msgid);
  vsnprintf (buffer, 240, optype_msgid, argp);
  va_end (argp);

3459 3460
  if (op1->rank != op2->rank)
    {
3461
      gfc_error ("Incompatible ranks in %s (%d and %d) at %L", _(buffer),
3462
		 op1->rank, op2->rank, &op1->where);
3463
      return false;
3464 3465
    }

3466
  t = true;
3467 3468 3469

  for (d = 0; d < op1->rank; d++)
    {
3470 3471
      op1_flag = gfc_array_dimen_size(op1, d, &op1_size);
      op2_flag = gfc_array_dimen_size(op2, d, &op2_size);
3472 3473 3474

      if (op1_flag && op2_flag && mpz_cmp (op1_size, op2_size) != 0)
	{
3475
	  gfc_error ("Different shape for %s at %L on dimension %d "
3476
		     "(%d and %d)", _(buffer), &op1->where, d + 1,
3477
		     (int) mpz_get_si (op1_size),
3478 3479
		     (int) mpz_get_si (op2_size));

3480
	  t = false;
3481 3482 3483 3484 3485 3486 3487
	}

      if (op1_flag)
	mpz_clear (op1_size);
      if (op2_flag)
	mpz_clear (op2_size);

3488 3489
      if (!t)
	return false;
3490 3491
    }

3492
  return true;
3493 3494 3495 3496
}


/* Given an assignable expression and an arbitrary expression, make
3497 3498 3499 3500
   sure that the assignment can take place.  Only add a call to the intrinsic
   conversion routines, when allow_convert is set.  When this assign is a
   coarray call, then the convert is done by the coarray routine implictly and
   adding the intrinsic conversion would do harm in most cases.  */
3501

3502
bool
3503 3504
gfc_check_assign (gfc_expr *lvalue, gfc_expr *rvalue, int conform,
		  bool allow_convert)
3505 3506
{
  gfc_symbol *sym;
3507 3508
  gfc_ref *ref;
  int has_pointer;
3509 3510 3511

  sym = lvalue->symtree->n.sym;

3512 3513
  /* See if this is the component or subcomponent of a pointer and guard
     against assignment to LEN or KIND part-refs.  */
3514 3515
  has_pointer = sym->attr.pointer;
  for (ref = lvalue->ref; ref; ref = ref->next)
3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527
    {
      if (!has_pointer && ref->type == REF_COMPONENT
	  && ref->u.c.component->attr.pointer)
        has_pointer = 1;
      else if (ref->type == REF_INQUIRY
	       && (ref->u.i == INQUIRY_LEN || ref->u.i == INQUIRY_KIND))
	{
	  gfc_error ("Assignment to a LEN or KIND part_ref at %L is not "
		     "allowed", &lvalue->where);
	  return false;
	}
    }
3528

3529 3530 3531 3532 3533
  /* 12.5.2.2, Note 12.26: The result variable is very similar to any other
     variable local to a function subprogram.  Its existence begins when
     execution of the function is initiated and ends when execution of the
     function is terminated...
     Therefore, the left hand side is no longer a variable, when it is:  */
3534 3535
  if (sym->attr.flavor == FL_PROCEDURE && sym->attr.proc != PROC_ST_FUNCTION
      && !sym->attr.external)
Paul Thomas committed
3536
    {
3537 3538 3539
      bool bad_proc;
      bad_proc = false;

3540
      /* (i) Use associated;  */
3541 3542 3543
      if (sym->attr.use_assoc)
	bad_proc = true;

3544
      /* (ii) The assignment is in the main program; or  */
3545 3546
      if (gfc_current_ns->proc_name
	  && gfc_current_ns->proc_name->attr.is_main_program)
3547 3548
	bad_proc = true;

3549
      /* (iii) A module or internal procedure...  */
3550 3551 3552
      if (gfc_current_ns->proc_name
	  && (gfc_current_ns->proc_name->attr.proc == PROC_INTERNAL
	      || gfc_current_ns->proc_name->attr.proc == PROC_MODULE)
3553 3554
	  && gfc_current_ns->parent
	  && (!(gfc_current_ns->parent->proc_name->attr.function
3555
		|| gfc_current_ns->parent->proc_name->attr.subroutine)
3556 3557
	      || gfc_current_ns->parent->proc_name->attr.is_main_program))
	{
3558
	  /* ... that is not a function...  */
3559 3560
	  if (gfc_current_ns->proc_name
	      && !gfc_current_ns->proc_name->attr.function)
3561 3562
	    bad_proc = true;

3563
	  /* ... or is not an entry and has a different name.  */
3564 3565 3566
	  if (!sym->attr.entry && sym->name != gfc_current_ns->proc_name->name)
	    bad_proc = true;
	}
Paul Thomas committed
3567

3568 3569 3570 3571 3572 3573 3574 3575 3576
      /* (iv) Host associated and not the function symbol or the
	      parent result.  This picks up sibling references, which
	      cannot be entries.  */
      if (!sym->attr.entry
	    && sym->ns == gfc_current_ns->parent
	    && sym != gfc_current_ns->proc_name
	    && sym != gfc_current_ns->parent->proc_name->result)
	bad_proc = true;

3577 3578
      if (bad_proc)
	{
3579
	  gfc_error ("%qs at %L is not a VALUE", sym->name, &lvalue->where);
3580
	  return false;
3581 3582
	}
    }
3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594
  else
    {
      /* Reject assigning to an external symbol.  For initializers, this
	 was already done before, in resolve_fl_procedure.  */
      if (sym->attr.flavor == FL_PROCEDURE && sym->attr.external
	  && sym->attr.proc != PROC_MODULE && !rvalue->error)
	{
	  gfc_error ("Illegal assignment to external procedure at %L",
		     &lvalue->where);
	  return false;
	}
    }
Paul Thomas committed
3595

3596 3597
  if (rvalue->rank != 0 && lvalue->rank != rvalue->rank)
    {
3598 3599
      gfc_error ("Incompatible ranks %d and %d in assignment at %L",
		 lvalue->rank, rvalue->rank, &lvalue->where);
3600
      return false;
3601 3602 3603 3604 3605 3606
    }

  if (lvalue->ts.type == BT_UNKNOWN)
    {
      gfc_error ("Variable type is UNKNOWN in assignment at %L",
		 &lvalue->where);
3607
      return false;
3608 3609
    }

3610
  if (rvalue->expr_type == EXPR_NULL)
3611
    {
3612
      if (has_pointer && (ref == NULL || ref->next == NULL)
3613
	  && lvalue->symtree->n.sym->attr.data)
3614
        return true;
3615 3616 3617 3618
      else
	{
	  gfc_error ("NULL appears on right-hand side in assignment at %L",
		     &rvalue->where);
3619
	  return false;
3620 3621
	}
    }
3622

3623
  /* This is possibly a typo: x = f() instead of x => f().  */
3624
  if (warn_surprising
3625
      && rvalue->expr_type == EXPR_FUNCTION && gfc_expr_attr (rvalue).pointer)
3626 3627
    gfc_warning (OPT_Wsurprising,
		 "POINTER-valued function appears on right-hand side of "
3628 3629
		 "assignment at %L", &rvalue->where);

3630 3631
  /* Check size of array assignments.  */
  if (lvalue->rank != 0 && rvalue->rank != 0
3632 3633
      && !gfc_check_conformance (lvalue, rvalue, "array assignment"))
    return false;
3634

3635 3636
  if (rvalue->is_boz && lvalue->ts.type != BT_INTEGER
      && lvalue->symtree->n.sym->attr.data
3637
      && !gfc_notify_std (GFC_STD_GNU, "BOZ literal at %L used to "
3638
			  "initialize non-integer variable %qs",
3639 3640
			  &rvalue->where, lvalue->symtree->n.sym->name))
    return false;
3641
  else if (rvalue->is_boz && !lvalue->symtree->n.sym->attr.data
3642 3643 3644 3645
      && !gfc_notify_std (GFC_STD_GNU, "BOZ literal at %L outside "
			  "a DATA statement and outside INT/REAL/DBLE/CMPLX",
			  &rvalue->where))
    return false;
3646 3647 3648 3649

  /* Handle the case of a BOZ literal on the RHS.  */
  if (rvalue->is_boz && lvalue->ts.type != BT_INTEGER)
    {
3650
      int rc;
3651
      if (warn_surprising)
3652 3653 3654 3655
	gfc_warning (OPT_Wsurprising,
		     "BOZ literal at %L is bitwise transferred "
		     "non-integer symbol %qs", &rvalue->where,
		     lvalue->symtree->n.sym->name);
3656
      if (!gfc_convert_boz (rvalue, &lvalue->ts))
3657
	return false;
3658 3659 3660 3661 3662
      if ((rc = gfc_range_check (rvalue)) != ARITH_OK)
	{
	  if (rc == ARITH_UNDERFLOW)
	    gfc_error ("Arithmetic underflow of bit-wise transferred BOZ at %L"
		       ". This check can be disabled with the option "
3663
		       "%<-fno-range-check%>", &rvalue->where);
3664 3665 3666
	  else if (rc == ARITH_OVERFLOW)
	    gfc_error ("Arithmetic overflow of bit-wise transferred BOZ at %L"
		       ". This check can be disabled with the option "
3667
		       "%<-fno-range-check%>", &rvalue->where);
3668 3669 3670
	  else if (rc == ARITH_NAN)
	    gfc_error ("Arithmetic NaN of bit-wise transferred BOZ at %L"
		       ". This check can be disabled with the option "
3671
		       "%<-fno-range-check%>", &rvalue->where);
3672
	  return false;
3673
	}
3674 3675
    }

3676 3677 3678 3679 3680 3681 3682 3683
  if (gfc_expr_attr (lvalue).pdt_kind || gfc_expr_attr (lvalue).pdt_len)
    {
      gfc_error ("The assignment to a KIND or LEN component of a "
		 "parameterized type at %L is not allowed",
		 &lvalue->where);
      return false;
    }

3684
  if (gfc_compare_types (&lvalue->ts, &rvalue->ts))
3685
    return true;
3686

3687
  /* Only DATA Statements come here.  */
3688 3689
  if (!conform)
    {
3690 3691
      locus *where;

3692 3693 3694 3695
      /* Numeric can be converted to any other numeric. And Hollerith can be
	 converted to any other type.  */
      if ((gfc_numeric_ts (&lvalue->ts) && gfc_numeric_ts (&rvalue->ts))
	  || rvalue->ts.type == BT_HOLLERITH)
3696
	return true;
3697

3698
      if (lvalue->ts.type == BT_LOGICAL && rvalue->ts.type == BT_LOGICAL)
3699
	return true;
3700

3701
      where = lvalue->where.lb ? &lvalue->where : &rvalue->where;
3702
      gfc_error ("Incompatible types in DATA statement at %L; attempted "
3703
		 "conversion of %s to %s", where,
3704
		 gfc_typename (&rvalue->ts), gfc_typename (&lvalue->ts));
3705

3706
      return false;
3707 3708
    }

3709 3710 3711 3712
  /* Assignment is the only case where character variables of different
     kind values can be converted into one another.  */
  if (lvalue->ts.type == BT_CHARACTER && rvalue->ts.type == BT_CHARACTER)
    {
3713
      if (lvalue->ts.kind != rvalue->ts.kind && allow_convert)
Janus Weil committed
3714 3715 3716
	return gfc_convert_chartype (rvalue, &lvalue->ts);
      else
	return true;
3717 3718
    }

3719 3720 3721
  if (!allow_convert)
    return true;

3722 3723 3724 3725 3726 3727 3728 3729
  return gfc_convert_type (rvalue, &lvalue->ts, 1);
}


/* Check that a pointer assignment is OK.  We first check lvalue, and
   we only check rvalue if it's not an assignment to NULL() or a
   NULLIFY statement.  */

3730
bool
3731
gfc_check_pointer_assign (gfc_expr *lvalue, gfc_expr *rvalue,
3732
			  bool suppress_type_test, bool is_init_expr)
3733
{
3734
  symbol_attribute attr, lhs_attr;
3735
  gfc_ref *ref;
3736
  bool is_pure, is_implicit_pure, rank_remap;
3737
  int proc_pointer;
3738
  bool same_rank;
3739

3740 3741
  lhs_attr = gfc_expr_attr (lvalue);
  if (lvalue->ts.type == BT_UNKNOWN && !lhs_attr.proc_pointer)
3742 3743 3744
    {
      gfc_error ("Pointer assignment target is not a POINTER at %L",
		 &lvalue->where);
3745
      return false;
3746 3747
    }

3748 3749
  if (lhs_attr.flavor == FL_PROCEDURE && lhs_attr.use_assoc
      && !lhs_attr.proc_pointer)
Paul Thomas committed
3750
    {
3751
      gfc_error ("%qs in the pointer assignment at %L cannot be an "
Paul Thomas committed
3752 3753
		 "l-value since it is a procedure",
		 lvalue->symtree->n.sym->name, &lvalue->where);
3754
      return false;
Paul Thomas committed
3755 3756
    }

3757
  proc_pointer = lvalue->symtree->n.sym->attr.proc_pointer;
3758

3759
  rank_remap = false;
3760
  same_rank = lvalue->rank == rvalue->rank;
3761 3762
  for (ref = lvalue->ref; ref; ref = ref->next)
    {
3763
      if (ref->type == REF_COMPONENT)
3764
	proc_pointer = ref->u.c.component->attr.proc_pointer;
3765 3766 3767

      if (ref->type == REF_ARRAY && ref->next == NULL)
	{
3768 3769
	  int dim;

3770 3771 3772 3773 3774
	  if (ref->u.ar.type == AR_FULL)
	    break;

	  if (ref->u.ar.type != AR_SECTION)
	    {
3775
	      gfc_error ("Expected bounds specification for %qs at %L",
3776
			 lvalue->symtree->n.sym->name, &lvalue->where);
3777
	      return false;
3778 3779
	    }

3780
	  if (!gfc_notify_std (GFC_STD_F2003, "Bounds specification "
3781
			       "for %qs in pointer assignment at %L",
3782 3783
			       lvalue->symtree->n.sym->name, &lvalue->where))
	    return false;
3784

3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804
	  /* Fortran standard (e.g. F2018, 10.2.2 Pointer assignment):
	   *
	   * (C1017) If bounds-spec-list is specified, the number of
	   * bounds-specs shall equal the rank of data-pointer-object.
	   *
	   * If bounds-spec-list appears, it specifies the lower bounds.
	   *
	   * (C1018) If bounds-remapping-list is specified, the number of
	   * bounds-remappings shall equal the rank of data-pointer-object.
	   *
	   * If bounds-remapping-list appears, it specifies the upper and
	   * lower bounds of each dimension of the pointer; the pointer target
	   * shall be simply contiguous or of rank one.
	   *
	   * (C1019) If bounds-remapping-list is not specified, the ranks of
	   * data-pointer-object and data-target shall be the same.
	   *
	   * Thus when bounds are given, all lbounds are necessary and either
	   * all or none of the upper bounds; no strides are allowed.  If the
	   * upper bounds are present, we may do rank remapping.  */
3805 3806
	  for (dim = 0; dim < ref->u.ar.dimen; ++dim)
	    {
3807
	      if (ref->u.ar.stride[dim])
3808
		{
3809
		  gfc_error ("Stride must not be present at %L",
3810
			     &lvalue->where);
3811
		  return false;
3812
		}
3813
	      if (!same_rank && (!ref->u.ar.start[dim] ||!ref->u.ar.end[dim]))
3814
		{
3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825
		  gfc_error ("Rank remapping requires a "
			     "list of %<lower-bound : upper-bound%> "
			     "specifications at %L", &lvalue->where);
		  return false;
		}
	      if (!ref->u.ar.start[dim]
		  || ref->u.ar.dimen_type[dim] != DIMEN_RANGE)
		{
		  gfc_error ("Expected list of %<lower-bound :%> or "
			     "list of %<lower-bound : upper-bound%> "
			     "specifications at %L", &lvalue->where);
3826
		  return false;
3827 3828 3829 3830 3831 3832
		}

	      if (dim == 0)
		rank_remap = (ref->u.ar.end[dim] != NULL);
	      else
		{
3833 3834 3835 3836 3837 3838 3839 3840
		  if ((rank_remap && !ref->u.ar.end[dim]))
		    {
		      gfc_error ("Rank remapping requires a "
				 "list of %<lower-bound : upper-bound%> "
				 "specifications at %L", &lvalue->where);
		      return false;
		    }
		  if (!rank_remap && ref->u.ar.end[dim])
3841
		    {
3842 3843 3844
		      gfc_error ("Expected list of %<lower-bound :%> or "
				 "list of %<lower-bound : upper-bound%> "
				 "specifications at %L", &lvalue->where);
3845
		      return false;
3846 3847 3848
		    }
		}
	    }
3849
	}
3850 3851
    }

3852
  is_pure = gfc_pure (NULL);
3853
  is_implicit_pure = gfc_implicit_pure (NULL);
3854 3855 3856 3857

  /* If rvalue is a NULL() or NULLIFY, we're done. Otherwise the type,
     kind, etc for lvalue and rvalue must match, and rvalue must be a
     pure variable if we're in a pure function.  */
3858
  if (rvalue->expr_type == EXPR_NULL && rvalue->ts.type == BT_UNKNOWN)
3859
    return true;
3860

3861 3862 3863 3864 3865 3866 3867 3868 3869 3870
  /* F2008, C723 (pointer) and C726 (proc-pointer); for PURE also C1283.  */
  if (lvalue->expr_type == EXPR_VARIABLE
      && gfc_is_coindexed (lvalue))
    {
      gfc_ref *ref;
      for (ref = lvalue->ref; ref; ref = ref->next)
	if (ref->type == REF_ARRAY && ref->u.ar.codimen)
	  {
	    gfc_error ("Pointer object at %L shall not have a coindex",
		       &lvalue->where);
3871
	    return false;
3872 3873 3874
	  }
    }

3875
  /* Checks on rvalue for procedure pointer assignments.  */
3876
  if (proc_pointer)
3877
    {
3878
      char err[200];
3879
      gfc_symbol *s1,*s2;
3880
      gfc_component *comp1, *comp2;
3881 3882
      const char *name;

3883 3884 3885
      attr = gfc_expr_attr (rvalue);
      if (!((rvalue->expr_type == EXPR_NULL)
	    || (rvalue->expr_type == EXPR_FUNCTION && attr.proc_pointer)
3886
	    || (rvalue->expr_type == EXPR_VARIABLE && attr.proc_pointer)
3887 3888 3889 3890 3891
	    || (rvalue->expr_type == EXPR_VARIABLE
		&& attr.flavor == FL_PROCEDURE)))
	{
	  gfc_error ("Invalid procedure pointer assignment at %L",
		     &rvalue->where);
3892
	  return false;
3893
	}
3894

3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906
      if (rvalue->expr_type == EXPR_VARIABLE && !attr.proc_pointer)
	{
      	  /* Check for intrinsics.  */
	  gfc_symbol *sym = rvalue->symtree->n.sym;
	  if (!sym->attr.intrinsic
	      && (gfc_is_intrinsic (sym, 0, sym->declared_at)
		  || gfc_is_intrinsic (sym, 1, sym->declared_at)))
	    {
	      sym->attr.intrinsic = 1;
	      gfc_resolve_intrinsic (sym, &rvalue->where);
	      attr = gfc_expr_attr (rvalue);
	    }
3907
	  /* Check for result of embracing function.  */
3908
	  if (sym->attr.function && sym->result == sym)
3909
	    {
3910 3911 3912 3913 3914
	      gfc_namespace *ns;

	      for (ns = gfc_current_ns; ns; ns = ns->parent)
		if (sym == ns->proc_name)
		  {
3915
		    gfc_error ("Function result %qs is invalid as proc-target "
3916 3917
			       "in procedure pointer assignment at %L",
			       sym->name, &rvalue->where);
3918
		    return false;
3919
		  }
3920
	    }
3921
	}
3922 3923
      if (attr.abstract)
	{
3924
	  gfc_error ("Abstract interface %qs is invalid "
3925 3926
		     "in procedure pointer assignment at %L",
		     rvalue->symtree->name, &rvalue->where);
3927
	  return false;
3928
	}
3929
      /* Check for F08:C729.  */
3930 3931 3932 3933
      if (attr.flavor == FL_PROCEDURE)
	{
	  if (attr.proc == PROC_ST_FUNCTION)
	    {
3934
	      gfc_error ("Statement function %qs is invalid "
3935 3936
			 "in procedure pointer assignment at %L",
			 rvalue->symtree->name, &rvalue->where);
3937
	      return false;
3938 3939
	    }
	  if (attr.proc == PROC_INTERNAL &&
3940
	      !gfc_notify_std(GFC_STD_F2008, "Internal procedure %qs "
3941 3942 3943
			      "is invalid in procedure pointer assignment "
			      "at %L", rvalue->symtree->name, &rvalue->where))
	    return false;
3944 3945 3946
	  if (attr.intrinsic && gfc_intrinsic_actual_ok (rvalue->symtree->name,
							 attr.subroutine) == 0)
	    {
3947
	      gfc_error ("Intrinsic %qs at %L is invalid in procedure pointer "
3948
			 "assignment", rvalue->symtree->name, &rvalue->where);
3949
	      return false;
3950
	    }
3951
	}
3952 3953 3954
      /* Check for F08:C730.  */
      if (attr.elemental && !attr.intrinsic)
	{
3955
	  gfc_error ("Nonintrinsic elemental procedure %qs is invalid "
3956
		     "in procedure pointer assignment at %L",
3957
		     rvalue->symtree->name, &rvalue->where);
3958
	  return false;
3959
	}
3960 3961 3962 3963 3964 3965 3966 3967

      /* Ensure that the calling convention is the same. As other attributes
	 such as DLLEXPORT may differ, one explicitly only tests for the
	 calling conventions.  */
      if (rvalue->expr_type == EXPR_VARIABLE
	  && lvalue->symtree->n.sym->attr.ext_attr
	       != rvalue->symtree->n.sym->attr.ext_attr)
	{
3968
	  symbol_attribute calls;
3969

3970 3971 3972 3973
	  calls.ext_attr = 0;
	  gfc_add_ext_attribute (&calls, EXT_ATTR_CDECL, NULL);
	  gfc_add_ext_attribute (&calls, EXT_ATTR_STDCALL, NULL);
	  gfc_add_ext_attribute (&calls, EXT_ATTR_FASTCALL, NULL);
3974

3975 3976
	  if ((calls.ext_attr & lvalue->symtree->n.sym->attr.ext_attr)
	      != (calls.ext_attr & rvalue->symtree->n.sym->attr.ext_attr))
3977 3978 3979 3980
	    {
	      gfc_error ("Mismatch in the procedure pointer assignment "
			 "at %L: mismatch in the calling convention",
			 &rvalue->where);
3981
	  return false;
3982 3983 3984
	    }
	}

3985 3986 3987
      comp1 = gfc_get_proc_ptr_comp (lvalue);
      if (comp1)
	s1 = comp1->ts.interface;
3988
      else
3989 3990 3991 3992 3993
	{
	  s1 = lvalue->symtree->n.sym;
	  if (s1->ts.interface)
	    s1 = s1->ts.interface;
	}
3994

3995 3996
      comp2 = gfc_get_proc_ptr_comp (rvalue);
      if (comp2)
3997
	{
3998 3999
	  if (rvalue->expr_type == EXPR_FUNCTION)
	    {
4000
	      s2 = comp2->ts.interface->result;
4001
	      name = s2->name;
4002 4003 4004
	    }
	  else
	    {
4005 4006
	      s2 = comp2->ts.interface;
	      name = comp2->name;
4007
	    }
4008 4009 4010
	}
      else if (rvalue->expr_type == EXPR_FUNCTION)
	{
4011 4012 4013 4014 4015
	  if (rvalue->value.function.esym)
	    s2 = rvalue->value.function.esym->result;
	  else
	    s2 = rvalue->symtree->n.sym->result;

4016
	  name = s2->name;
4017 4018 4019 4020
	}
      else
	{
	  s2 = rvalue->symtree->n.sym;
4021 4022 4023
	  name = s2->name;
	}

4024
      if (s2 && s2->attr.proc_pointer && s2->ts.interface)
4025 4026
	s2 = s2->ts.interface;

4027 4028 4029 4030 4031
      /* Special check for the case of absent interface on the lvalue.
       * All other interface checks are done below. */
      if (!s1 && comp1 && comp1->attr.subroutine && s2 && s2->attr.function)
	{
	  gfc_error ("Interface mismatch in procedure pointer assignment "
4032
		     "at %L: %qs is not a subroutine", &rvalue->where, name);
4033 4034 4035
	  return false;
	}

4036
      /* F08:7.2.2.4 (4)  */
4037
      if (s2 && gfc_explicit_interface_required (s2, err, sizeof(err)))
4038
	{
4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050
	  if (comp1 && !s1)
	    {
	      gfc_error ("Explicit interface required for component %qs at %L: %s",
			 comp1->name, &lvalue->where, err);
	      return false;
	    }
	  else if (s1->attr.if_source == IFSRC_UNKNOWN)
	    {
	      gfc_error ("Explicit interface required for %qs at %L: %s",
			 s1->name, &lvalue->where, err);
	      return false;
	    }
4051
	}
4052
      if (s1 && gfc_explicit_interface_required (s1, err, sizeof(err)))
4053
	{
4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065
	  if (comp2 && !s2)
	    {
	      gfc_error ("Explicit interface required for component %qs at %L: %s",
			 comp2->name, &rvalue->where, err);
	      return false;
	    }
	  else if (s2->attr.if_source == IFSRC_UNKNOWN)
	    {
	      gfc_error ("Explicit interface required for %qs at %L: %s",
			 s2->name, &rvalue->where, err);
	      return false;
	    }
4066 4067
	}

4068 4069 4070
      if (s1 == s2 || !s1 || !s2)
	return true;

4071 4072 4073 4074 4075
      if (!gfc_compare_interfaces (s1, s2, name, 0, 1,
				   err, sizeof(err), NULL, NULL))
	{
	  gfc_error ("Interface mismatch in procedure pointer assignment "
		     "at %L: %s", &rvalue->where, err);
4076
	  return false;
4077 4078
	}

4079 4080 4081 4082
      /* Check F2008Cor2, C729.  */
      if (!s2->attr.intrinsic && s2->attr.if_source == IFSRC_UNKNOWN
	  && !s2->attr.external && !s2->attr.subroutine && !s2->attr.function)
	{
4083
	  gfc_error ("Procedure pointer target %qs at %L must be either an "
4084 4085 4086 4087 4088
		     "intrinsic, host or use associated, referenced or have "
		     "the EXTERNAL attribute", s2->name, &rvalue->where);
	  return false;
	}

4089
      return true;
4090
    }
4091 4092 4093 4094 4095 4096 4097 4098 4099 4100
  else
    {
      /* A non-proc pointer cannot point to a constant.  */
      if (rvalue->expr_type == EXPR_CONSTANT)
	{
	  gfc_error_now ("Pointer assignment target cannot be a constant at %L",
			 &rvalue->where);
	  return false;
	}
    }
4101

4102
  if (!gfc_compare_types (&lvalue->ts, &rvalue->ts))
4103
    {
4104 4105 4106 4107 4108 4109
      /* Check for F03:C717.  */
      if (UNLIMITED_POLY (rvalue)
	  && !(UNLIMITED_POLY (lvalue)
	       || (lvalue->ts.type == BT_DERIVED
		   && (lvalue->ts.u.derived->attr.is_bind_c
		       || lvalue->ts.u.derived->attr.sequence))))
4110 4111 4112 4113
	gfc_error ("Data-pointer-object at %L must be unlimited "
		   "polymorphic, or of a type with the BIND or SEQUENCE "
		   "attribute, to be compatible with an unlimited "
		   "polymorphic target", &lvalue->where);
4114
      else if (!suppress_type_test)
4115 4116 4117 4118
	gfc_error ("Different types in pointer assignment at %L; "
		   "attempted assignment of %s to %s", &lvalue->where,
		   gfc_typename (&rvalue->ts),
		   gfc_typename (&lvalue->ts));
4119
      return false;
4120
    }
4121

4122
  if (lvalue->ts.type != BT_CLASS && lvalue->ts.kind != rvalue->ts.kind)
4123
    {
4124
      gfc_error ("Different kind type parameters in pointer "
4125
		 "assignment at %L", &lvalue->where);
4126
      return false;
4127
    }
4128

4129
  if (lvalue->rank != rvalue->rank && !rank_remap)
4130
    {
4131
      gfc_error ("Different ranks in pointer assignment at %L", &lvalue->where);
4132
      return false;
4133 4134
    }

4135 4136 4137
  /* Make sure the vtab is present.  */
  if (lvalue->ts.type == BT_CLASS && !UNLIMITED_POLY (rvalue))
    gfc_find_vtab (&rvalue->ts);
4138

4139 4140 4141 4142 4143 4144 4145
  /* Check rank remapping.  */
  if (rank_remap)
    {
      mpz_t lsize, rsize;

      /* If this can be determined, check that the target must be at least as
	 large as the pointer assigned to it is.  */
4146 4147
      if (gfc_array_size (lvalue, &lsize)
	  && gfc_array_size (rvalue, &rsize)
4148 4149 4150 4151 4152 4153
	  && mpz_cmp (rsize, lsize) < 0)
	{
	  gfc_error ("Rank remapping target is smaller than size of the"
		     " pointer (%ld < %ld) at %L",
		     mpz_get_si (rsize), mpz_get_si (lsize),
		     &lvalue->where);
4154
	  return false;
4155 4156 4157 4158 4159 4160
	}

      /* The target must be either rank one or it must be simply contiguous
	 and F2008 must be allowed.  */
      if (rvalue->rank != 1)
	{
4161
	  if (!gfc_is_simply_contiguous (rvalue, true, false))
4162 4163 4164
	    {
	      gfc_error ("Rank remapping target must be rank 1 or"
			 " simply contiguous at %L", &rvalue->where);
4165
	      return false;
4166
	    }
4167 4168 4169
	  if (!gfc_notify_std (GFC_STD_F2008, "Rank remapping target is not "
			       "rank 1 at %L", &rvalue->where))
	    return false;
4170 4171 4172
	}
    }

4173 4174
  /* Now punt if we are dealing with a NULLIFY(X) or X = NULL(X).  */
  if (rvalue->expr_type == EXPR_NULL)
4175
    return true;
4176

4177
  if (lvalue->ts.type == BT_CHARACTER)
Paul Thomas committed
4178
    {
4179 4180 4181
      bool t = gfc_check_same_strlen (lvalue, rvalue, "pointer assignment");
      if (!t)
	return false;
Paul Thomas committed
4182 4183
    }

4184 4185 4186
  if (rvalue->expr_type == EXPR_VARIABLE && is_subref_array (rvalue))
    lvalue->symtree->n.sym->attr.subref_array_pointer = 1;

4187
  attr = gfc_expr_attr (rvalue);
4188 4189 4190

  if (rvalue->expr_type == EXPR_FUNCTION && !attr.pointer)
    {
4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204
      /* F2008, C725.  For PURE also C1283.  Sometimes rvalue is a function call
	 to caf_get.  Map this to the same error message as below when it is
	 still a variable expression.  */
      if (rvalue->value.function.isym
	  && rvalue->value.function.isym->id == GFC_ISYM_CAF_GET)
	/* The test above might need to be extend when F08, Note 5.4 has to be
	   interpreted in the way that target and pointer with the same coindex
	   are allowed.  */
	gfc_error ("Data target at %L shall not have a coindex",
		   &rvalue->where);
      else
	gfc_error ("Target expression in pointer assignment "
		   "at %L must deliver a pointer result",
		   &rvalue->where);
4205
      return false;
4206 4207
    }

4208
  if (is_init_expr)
4209
    {
4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236
      gfc_symbol *sym;
      bool target;

      gcc_assert (rvalue->symtree);
      sym = rvalue->symtree->n.sym;

      if (sym->ts.type == BT_CLASS && sym->attr.class_ok)
	target = CLASS_DATA (sym)->attr.target;
      else
	target = sym->attr.target;

      if (!target && !proc_pointer)
	{
	  gfc_error ("Pointer assignment target in initialization expression "
		     "does not have the TARGET attribute at %L",
		     &rvalue->where);
	  return false;
	}
    }
  else
    {
      if (!attr.target && !attr.pointer)
	{
	  gfc_error ("Pointer assignment target is neither TARGET "
		     "nor POINTER at %L", &rvalue->where);
	  return false;
	}
4237
    }
4238

4239 4240
  if (is_pure && gfc_impure_variable (rvalue->symtree->n.sym))
    {
4241
      gfc_error ("Bad target in pointer assignment in PURE "
4242 4243
		 "procedure at %L", &rvalue->where);
    }
4244

4245
  if (is_implicit_pure && gfc_impure_variable (rvalue->symtree->n.sym))
4246
    gfc_unset_implicit_pure (gfc_current_ns->proc_name);
4247

4248 4249 4250 4251
  if (gfc_has_vector_index (rvalue))
    {
      gfc_error ("Pointer assignment with vector subscript "
		 "on rhs at %L", &rvalue->where);
4252
      return false;
4253 4254
    }

4255 4256
  if (attr.is_protected && attr.use_assoc
      && !(attr.pointer || attr.proc_pointer))
4257
    {
4258
      gfc_error ("Pointer assignment target has PROTECTED "
4259
		 "attribute at %L", &rvalue->where);
4260
      return false;
4261 4262
    }

4263 4264 4265 4266 4267 4268 4269 4270 4271 4272
  /* F2008, C725. For PURE also C1283.  */
  if (rvalue->expr_type == EXPR_VARIABLE
      && gfc_is_coindexed (rvalue))
    {
      gfc_ref *ref;
      for (ref = rvalue->ref; ref; ref = ref->next)
	if (ref->type == REF_ARRAY && ref->u.ar.codimen)
	  {
	    gfc_error ("Data target at %L shall not have a coindex",
		       &rvalue->where);
4273
	    return false;
4274 4275 4276
	  }
    }

4277
  /* Warn for assignments of contiguous pointers to targets which is not
4278
     contiguous.  Be lenient in the definition of what counts as
4279
     contiguous.  */
4280 4281

  if (lhs_attr.contiguous && !gfc_is_simply_contiguous (rvalue, false, true))
4282 4283
    gfc_warning (OPT_Wextra, "Assignment to contiguous pointer from "
		 "non-contiguous target at %L", &rvalue->where);
4284

4285
  /* Warn if it is the LHS pointer may lives longer than the RHS target.  */
4286
  if (warn_target_lifetime
4287 4288
      && rvalue->expr_type == EXPR_VARIABLE
      && !rvalue->symtree->n.sym->attr.save
4289 4290
      && !rvalue->symtree->n.sym->attr.pointer && !attr.pointer
      && !rvalue->symtree->n.sym->attr.host_assoc
4291 4292 4293 4294 4295 4296 4297 4298 4299
      && !rvalue->symtree->n.sym->attr.in_common
      && !rvalue->symtree->n.sym->attr.use_assoc
      && !rvalue->symtree->n.sym->attr.dummy)
    {
      bool warn;
      gfc_namespace *ns;

      warn = lvalue->symtree->n.sym->attr.dummy
	     || lvalue->symtree->n.sym->attr.result
4300
	     || lvalue->symtree->n.sym->attr.function
4301 4302 4303
	     || (lvalue->symtree->n.sym->attr.host_assoc
		 && lvalue->symtree->n.sym->ns
		    != rvalue->symtree->n.sym->ns)
4304 4305 4306 4307 4308 4309 4310
	     || lvalue->symtree->n.sym->attr.use_assoc
	     || lvalue->symtree->n.sym->attr.in_common;

      if (rvalue->symtree->n.sym->ns->proc_name
	  && rvalue->symtree->n.sym->ns->proc_name->attr.flavor != FL_PROCEDURE
	  && rvalue->symtree->n.sym->ns->proc_name->attr.flavor != FL_PROGRAM)
       for (ns = rvalue->symtree->n.sym->ns;
4311
	    ns && ns->proc_name && ns->proc_name->attr.flavor != FL_PROCEDURE;
4312 4313
	    ns = ns->parent)
	if (ns->parent == lvalue->symtree->n.sym->ns)
4314 4315 4316 4317
	  {
	    warn = true;
	    break;
	  }
4318 4319

      if (warn)
4320 4321
	gfc_warning (OPT_Wtarget_lifetime,
		     "Pointer at %L in pointer assignment might outlive the "
4322 4323 4324
		     "pointer target", &lvalue->where);
    }

4325
  return true;
4326 4327 4328 4329
}


/* Relative of gfc_check_assign() except that the lvalue is a single
4330
   symbol.  Used for initialization assignments.  */
4331

4332
bool
4333
gfc_check_assign_symbol (gfc_symbol *sym, gfc_component *comp, gfc_expr *rvalue)
4334 4335
{
  gfc_expr lvalue;
4336
  bool r;
4337
  bool pointer, proc_pointer;
4338 4339 4340 4341 4342 4343 4344

  memset (&lvalue, '\0', sizeof (gfc_expr));

  lvalue.expr_type = EXPR_VARIABLE;
  lvalue.ts = sym->ts;
  if (sym->as)
    lvalue.rank = sym->as->rank;
4345
  lvalue.symtree = XCNEW (gfc_symtree);
4346 4347 4348
  lvalue.symtree->n.sym = sym;
  lvalue.where = sym->declared_at;

4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369
  if (comp)
    {
      lvalue.ref = gfc_get_ref ();
      lvalue.ref->type = REF_COMPONENT;
      lvalue.ref->u.c.component = comp;
      lvalue.ref->u.c.sym = sym;
      lvalue.ts = comp->ts;
      lvalue.rank = comp->as ? comp->as->rank : 0;
      lvalue.where = comp->loc;
      pointer = comp->ts.type == BT_CLASS &&  CLASS_DATA (comp)
		? CLASS_DATA (comp)->attr.class_pointer : comp->attr.pointer;
      proc_pointer = comp->attr.proc_pointer;
    }
  else
    {
      pointer = sym->ts.type == BT_CLASS &&  CLASS_DATA (sym)
		? CLASS_DATA (sym)->attr.class_pointer : sym->attr.pointer;
      proc_pointer = sym->attr.proc_pointer;
    }

  if (pointer || proc_pointer)
4370
    r = gfc_check_pointer_assign (&lvalue, rvalue, false, true);
4371
  else
4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382
    {
      /* If a conversion function, e.g., __convert_i8_i4, was inserted
	 into an array constructor, we should check if it can be reduced
	 as an initialization expression.  */
      if (rvalue->expr_type == EXPR_FUNCTION
	  && rvalue->value.function.isym
	  && (rvalue->value.function.isym->conversion == 1))
	gfc_check_init_expr (rvalue);

      r = gfc_check_assign (&lvalue, rvalue, 1);
    }
4383

4384
  free (lvalue.symtree);
4385
  free (lvalue.ref);
4386

4387
  if (!r)
4388
    return r;
4389

4390
  if (pointer && rvalue->expr_type != EXPR_NULL && !proc_pointer)
4391 4392 4393 4394 4395 4396
    {
      /* F08:C461. Additional checks for pointer initialization.  */
      symbol_attribute attr;
      attr = gfc_expr_attr (rvalue);
      if (attr.allocatable)
	{
4397 4398
	  gfc_error ("Pointer initialization target at %L "
	             "must not be ALLOCATABLE", &rvalue->where);
4399
	  return false;
4400
	}
4401
      if (!attr.target || attr.pointer)
4402
	{
4403 4404
	  gfc_error ("Pointer initialization target at %L "
		     "must have the TARGET attribute", &rvalue->where);
4405
	  return false;
4406
	}
4407 4408 4409 4410 4411 4412 4413 4414 4415

      if (!attr.save && rvalue->expr_type == EXPR_VARIABLE
	  && rvalue->symtree->n.sym->ns->proc_name
	  && rvalue->symtree->n.sym->ns->proc_name->attr.is_main_program)
	{
	  rvalue->symtree->n.sym->ns->proc_name->attr.save = SAVE_IMPLICIT;
	  attr.save = SAVE_IMPLICIT;
	}

4416 4417
      if (!attr.save)
	{
4418 4419
	  gfc_error ("Pointer initialization target at %L "
		     "must have the SAVE attribute", &rvalue->where);
4420
	  return false;
4421 4422
	}
    }
4423

4424
  if (proc_pointer && rvalue->expr_type != EXPR_NULL)
4425 4426 4427 4428 4429 4430 4431
    {
      /* F08:C1220. Additional checks for procedure pointer initialization.  */
      symbol_attribute attr = gfc_expr_attr (rvalue);
      if (attr.proc_pointer)
	{
	  gfc_error ("Procedure pointer initialization target at %L "
		     "may not be a procedure pointer", &rvalue->where);
4432
	  return false;
4433
	}
4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447
      if (attr.proc == PROC_INTERNAL)
	{
	  gfc_error ("Internal procedure %qs is invalid in "
		     "procedure pointer initialization at %L",
		     rvalue->symtree->name, &rvalue->where);
	  return false;
	}
      if (attr.dummy)
	{
	  gfc_error ("Dummy procedure %qs is invalid in "
		     "procedure pointer initialization at %L",
		     rvalue->symtree->name, &rvalue->where);
	  return false;
	}
4448
    }
4449

4450
  return true;
4451
}
4452

4453 4454 4455 4456 4457 4458 4459 4460
/* Invoke gfc_build_init_expr to create an initializer expression, but do not
 * require that an expression be built.  */

gfc_expr *
gfc_build_default_init_expr (gfc_typespec *ts, locus *where)
{
  return gfc_build_init_expr (ts, where, false);
}
4461

4462 4463
/* Build an initializer for a local integer, real, complex, logical, or
   character variable, based on the command line flags finit-local-zero,
4464 4465
   finit-integer=, finit-real=, finit-logical=, and finit-character=.
   With force, an initializer is ALWAYS generated.  */
4466 4467

gfc_expr *
4468
gfc_build_init_expr (gfc_typespec *ts, locus *where, bool force)
4469 4470 4471 4472 4473 4474
{
  gfc_expr *init_expr;

  /* Try to build an initializer expression.  */
  init_expr = gfc_get_constant_expr (ts->type, ts->kind, where);

4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485
  /* If we want to force generation, make sure we default to zero.  */
  gfc_init_local_real init_real = flag_init_real;
  int init_logical = gfc_option.flag_init_logical;
  if (force)
    {
      if (init_real == GFC_INIT_REAL_OFF)
	init_real = GFC_INIT_REAL_ZERO;
      if (init_logical == GFC_INIT_LOGICAL_OFF)
	init_logical = GFC_INIT_LOGICAL_FALSE;
    }

4486 4487 4488 4489 4490 4491
  /* We will only initialize integers, reals, complex, logicals, and
     characters, and only if the corresponding command-line flags
     were set.  Otherwise, we free init_expr and return null.  */
  switch (ts->type)
    {
    case BT_INTEGER:
4492
      if (force || gfc_option.flag_init_integer != GFC_INIT_INTEGER_OFF)
4493 4494 4495 4496 4497 4498 4499 4500 4501 4502
        mpz_set_si (init_expr->value.integer,
                         gfc_option.flag_init_integer_value);
      else
        {
          gfc_free_expr (init_expr);
          init_expr = NULL;
        }
      break;

    case BT_REAL:
4503
      switch (init_real)
4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531
        {
        case GFC_INIT_REAL_SNAN:
          init_expr->is_snan = 1;
          /* Fall through.  */
        case GFC_INIT_REAL_NAN:
          mpfr_set_nan (init_expr->value.real);
          break;

        case GFC_INIT_REAL_INF:
          mpfr_set_inf (init_expr->value.real, 1);
          break;

        case GFC_INIT_REAL_NEG_INF:
          mpfr_set_inf (init_expr->value.real, -1);
          break;

        case GFC_INIT_REAL_ZERO:
          mpfr_set_ui (init_expr->value.real, 0.0, GFC_RND_MODE);
          break;

        default:
          gfc_free_expr (init_expr);
          init_expr = NULL;
          break;
        }
      break;

    case BT_COMPLEX:
4532
      switch (init_real)
4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563
        {
        case GFC_INIT_REAL_SNAN:
          init_expr->is_snan = 1;
          /* Fall through.  */
        case GFC_INIT_REAL_NAN:
          mpfr_set_nan (mpc_realref (init_expr->value.complex));
          mpfr_set_nan (mpc_imagref (init_expr->value.complex));
          break;

        case GFC_INIT_REAL_INF:
          mpfr_set_inf (mpc_realref (init_expr->value.complex), 1);
          mpfr_set_inf (mpc_imagref (init_expr->value.complex), 1);
          break;

        case GFC_INIT_REAL_NEG_INF:
          mpfr_set_inf (mpc_realref (init_expr->value.complex), -1);
          mpfr_set_inf (mpc_imagref (init_expr->value.complex), -1);
          break;

        case GFC_INIT_REAL_ZERO:
          mpc_set_ui (init_expr->value.complex, 0, GFC_MPC_RND_MODE);
          break;

        default:
          gfc_free_expr (init_expr);
          init_expr = NULL;
          break;
        }
      break;

    case BT_LOGICAL:
4564
      if (init_logical == GFC_INIT_LOGICAL_FALSE)
4565
        init_expr->value.logical = 0;
4566
      else if (init_logical == GFC_INIT_LOGICAL_TRUE)
4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577
        init_expr->value.logical = 1;
      else
        {
          gfc_free_expr (init_expr);
          init_expr = NULL;
        }
      break;

    case BT_CHARACTER:
      /* For characters, the length must be constant in order to
         create a default initializer.  */
4578
      if ((force || gfc_option.flag_init_character == GFC_INIT_CHARACTER_ON)
4579 4580 4581
          && ts->u.cl->length
          && ts->u.cl->length->expr_type == EXPR_CONSTANT)
        {
4582
          HOST_WIDE_INT char_len = gfc_mpz_get_hwi (ts->u.cl->length->value.integer);
4583 4584
          init_expr->value.character.length = char_len;
          init_expr->value.character.string = gfc_get_wide_string (char_len+1);
4585
          for (size_t i = 0; i < (size_t) char_len; i++)
4586 4587 4588 4589 4590 4591 4592 4593
            init_expr->value.character.string[i]
              = (unsigned char) gfc_option.flag_init_character_value;
        }
      else
        {
          gfc_free_expr (init_expr);
          init_expr = NULL;
        }
4594 4595
      if (!init_expr
	  && (force || gfc_option.flag_init_character == GFC_INIT_CHARACTER_ON)
4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632
          && ts->u.cl->length && flag_max_stack_var_size != 0)
        {
          gfc_actual_arglist *arg;
          init_expr = gfc_get_expr ();
          init_expr->where = *where;
          init_expr->ts = *ts;
          init_expr->expr_type = EXPR_FUNCTION;
          init_expr->value.function.isym =
                gfc_intrinsic_function_by_id (GFC_ISYM_REPEAT);
          init_expr->value.function.name = "repeat";
          arg = gfc_get_actual_arglist ();
          arg->expr = gfc_get_character_expr (ts->kind, where, NULL, 1);
          arg->expr->value.character.string[0] =
            gfc_option.flag_init_character_value;
          arg->next = gfc_get_actual_arglist ();
          arg->next->expr = gfc_copy_expr (ts->u.cl->length);
          init_expr->value.function.actual = arg;
        }
      break;

    default:
     gfc_free_expr (init_expr);
     init_expr = NULL;
    }

  return init_expr;
}

/* Apply an initialization expression to a typespec. Can be used for symbols or
   components. Similar to add_init_expr_to_sym in decl.c; could probably be
   combined with some effort.  */

void
gfc_apply_init (gfc_typespec *ts, symbol_attribute *attr, gfc_expr *init)
{
  if (ts->type == BT_CHARACTER && !attr->pointer && init
      && ts->u.cl
4633 4634 4635
      && ts->u.cl->length
      && ts->u.cl->length->expr_type == EXPR_CONSTANT
      && ts->u.cl->length->ts.type == BT_INTEGER)
4636
    {
4637
      HOST_WIDE_INT len = gfc_mpz_get_hwi (ts->u.cl->length->value.integer);
4638 4639 4640 4641

      if (init->expr_type == EXPR_CONSTANT)
        gfc_set_constant_character_len (len, init, -1);
      else if (init
4642
	       && init->ts.type == BT_CHARACTER
4643
               && init->ts.u.cl && init->ts.u.cl->length
4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659
               && mpz_cmp (ts->u.cl->length->value.integer,
                           init->ts.u.cl->length->value.integer))
        {
          gfc_constructor *ctor;
          ctor = gfc_constructor_first (init->value.constructor);

          if (ctor)
            {
              bool has_ts = (init->ts.u.cl
                             && init->ts.u.cl->length_from_typespec);

              /* Remember the length of the first element for checking
                 that all elements *in the constructor* have the same
                 length.  This need not be the length of the LHS!  */
              gcc_assert (ctor->expr->expr_type == EXPR_CONSTANT);
              gcc_assert (ctor->expr->ts.type == BT_CHARACTER);
4660
              gfc_charlen_t first_len = ctor->expr->value.character.length;
4661 4662 4663 4664 4665 4666

              for ( ; ctor; ctor = gfc_constructor_next (ctor))
                if (ctor->expr->expr_type == EXPR_CONSTANT)
                {
                  gfc_set_constant_character_len (len, ctor->expr,
                                                  has_ts ? -1 : first_len);
4667 4668 4669 4670 4671 4672
		  if (!ctor->expr->ts.u.cl)
		    ctor->expr->ts.u.cl
		      = gfc_new_charlen (gfc_current_ns, ts->u.cl);
		  else
                    ctor->expr->ts.u.cl->length
		      = gfc_copy_expr (ts->u.cl->length);
4673 4674 4675 4676 4677 4678 4679
                }
            }
        }
    }
}


4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699
/* Check whether an expression is a structure constructor and whether it has
   other values than NULL.  */

bool
is_non_empty_structure_constructor (gfc_expr * e)
{
  if (e->expr_type != EXPR_STRUCTURE)
    return false;

  gfc_constructor *cons = gfc_constructor_first (e->value.constructor);
  while (cons)
    {
      if (!cons->expr || cons->expr->expr_type != EXPR_NULL)
	return true;
      cons = gfc_constructor_next (cons);
    }
  return false;
}


4700 4701 4702 4703 4704 4705 4706 4707
/* Check for default initializer; sym->value is not enough
   as it is also set for EXPR_NULL of allocatables.  */

bool
gfc_has_default_initializer (gfc_symbol *der)
{
  gfc_component *c;

4708
  gcc_assert (gfc_fl_struct (der->attr.flavor));
4709
  for (c = der->components; c; c = c->next)
4710
    if (gfc_bt_struct (c->ts.type))
4711
      {
4712
        if (!c->attr.pointer && !c->attr.proc_pointer
4713
	     && !(c->attr.allocatable && der == c->ts.u.derived)
4714 4715 4716
	     && ((c->initializer
		  && is_non_empty_structure_constructor (c->initializer))
		 || gfc_has_default_initializer (c->ts.u.derived)))
4717
	  return true;
4718 4719
	if (c->attr.pointer && c->initializer)
	  return true;
4720 4721 4722 4723 4724 4725 4726 4727 4728 4729
      }
    else
      {
        if (c->initializer)
	  return true;
      }

  return false;
}

4730

4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784
/*
   Generate an initializer expression which initializes the entirety of a union.
   A normal structure constructor is insufficient without undue effort, because
   components of maps may be oddly aligned/overlapped. (For example if a
   character is initialized from one map overtop a real from the other, only one
   byte of the real is actually initialized.)  Unfortunately we don't know the
   size of the union right now, so we can't generate a proper initializer, but
   we use a NULL expr as a placeholder and do the right thing later in
   gfc_trans_subcomponent_assign.
 */
static gfc_expr *
generate_union_initializer (gfc_component *un)
{
  if (un == NULL || un->ts.type != BT_UNION)
    return NULL;

  gfc_expr *placeholder = gfc_get_null_expr (&un->loc);
  placeholder->ts = un->ts;
  return placeholder;
}


/* Get the user-specified initializer for a union, if any. This means the user
   has said to initialize component(s) of a map.  For simplicity's sake we
   only allow the user to initialize the first map.  We don't have to worry
   about overlapping initializers as they are released early in resolution (see
   resolve_fl_struct).   */

static gfc_expr *
get_union_initializer (gfc_symbol *union_type, gfc_component **map_p)
{
  gfc_component *map;
  gfc_expr *init=NULL;

  if (!union_type || union_type->attr.flavor != FL_UNION)
    return NULL;

  for (map = union_type->components; map; map = map->next)
    {
      if (gfc_has_default_initializer (map->ts.u.derived))
        {
          init = gfc_default_initializer (&map->ts);
          if (map_p)
            *map_p = map;
          break;
        }
    }

  if (map_p && !init)
    *map_p = NULL;

  return init;
}

4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813
static bool
class_allocatable (gfc_component *comp)
{
  return comp->ts.type == BT_CLASS && CLASS_DATA (comp)
    && CLASS_DATA (comp)->attr.allocatable;
}

static bool
class_pointer (gfc_component *comp)
{
  return comp->ts.type == BT_CLASS && CLASS_DATA (comp)
    && CLASS_DATA (comp)->attr.pointer;
}

static bool
comp_allocatable (gfc_component *comp)
{
  return comp->attr.allocatable || class_allocatable (comp);
}

static bool
comp_pointer (gfc_component *comp)
{
  return comp->attr.pointer
    || comp->attr.proc_pointer
    || comp->attr.class_pointer
    || class_pointer (comp);
}

4814 4815 4816 4817
/* Fetch or generate an initializer for the given component.
   Only generate an initializer if generate is true.  */

static gfc_expr *
4818
component_initializer (gfc_component *c, bool generate)
4819 4820 4821
{
  gfc_expr *init = NULL;

4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833
  /* Allocatable components always get EXPR_NULL.
     Pointer components are only initialized when generating, and only if they
     do not already have an initializer.  */
  if (comp_allocatable (c) || (generate && comp_pointer (c) && !c->initializer))
    {
      init = gfc_get_null_expr (&c->loc);
      init->ts = c->ts;
      return init;
    }

  /* See if we can find the initializer immediately.  */
  if (c->initializer || !generate)
4834 4835 4836
    return c->initializer;

  /* Recursively handle derived type components.  */
4837
  else if (c->ts.type == BT_DERIVED || c->ts.type == BT_CLASS)
4838 4839
    init = gfc_generate_initializer (&c->ts, true);

4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876
  else if (c->ts.type == BT_UNION && c->ts.u.derived->components)
    {
      gfc_component *map = NULL;
      gfc_constructor *ctor;
      gfc_expr *user_init;

      /* If we don't have a user initializer and we aren't generating one, this
         union has no initializer.  */
      user_init = get_union_initializer (c->ts.u.derived, &map);
      if (!user_init && !generate)
        return NULL;

      /* Otherwise use a structure constructor.  */
      init = gfc_get_structure_constructor_expr (c->ts.type, c->ts.kind,
                                                 &c->loc);
      init->ts = c->ts;

      /* If we are to generate an initializer for the union, add a constructor
         which initializes the whole union first.  */
      if (generate)
        {
          ctor = gfc_constructor_get ();
          ctor->expr = generate_union_initializer (c);
          gfc_constructor_append (&init->value.constructor, ctor);
        }

      /* If we found an initializer in one of our maps, apply it.  Note this
         is applied _after_ the entire-union initializer above if any.  */
      if (user_init)
        {
          ctor = gfc_constructor_get ();
          ctor->expr = user_init;
          ctor->n.component = map;
          gfc_constructor_append (&init->value.constructor, ctor);
        }
    }

4877 4878 4879
  /* Treat simple components like locals.  */
  else
    {
4880 4881
      /* We MUST give an initializer, so force generation.  */
      init = gfc_build_init_expr (&c->ts, &c->loc, true);
4882 4883 4884
      gfc_apply_init (&c->ts, &c->attr, init);
    }

4885
  return init;
4886 4887 4888 4889
}


/* Get an expression for a default initializer of a derived type.  */
4890 4891 4892 4893

gfc_expr *
gfc_default_initializer (gfc_typespec *ts)
{
4894 4895 4896
  return gfc_generate_initializer (ts, false);
}

4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922
/* Generate an initializer expression for an iso_c_binding type
   such as c_[fun]ptr. The appropriate initializer is c_null_[fun]ptr.  */

static gfc_expr *
generate_isocbinding_initializer (gfc_symbol *derived)
{
  /* The initializers have already been built into the c_null_[fun]ptr symbols
     from gen_special_c_interop_ptr.  */
  gfc_symtree *npsym = NULL;
  if (0 == strcmp (derived->name, "c_ptr"))
    gfc_find_sym_tree ("c_null_ptr", gfc_current_ns, true, &npsym);
  else if (0 == strcmp (derived->name, "c_funptr"))
    gfc_find_sym_tree ("c_null_funptr", gfc_current_ns, true, &npsym);
  else
    gfc_internal_error ("generate_isocbinding_initializer(): bad iso_c_binding"
			" type, expected %<c_ptr%> or %<c_funptr%>");
  if (npsym)
    {
      gfc_expr *init = gfc_copy_expr (npsym->n.sym->value);
      init->symtree = npsym;
      init->ts.is_iso_c = true;
      return init;
    }

  return NULL;
}
4923

4924
/* Get or generate an expression for a default initializer of a derived type.
4925 4926 4927 4928 4929 4930 4931
   If -finit-derived is specified, generate default initialization expressions
   for components that lack them when generate is set.  */

gfc_expr *
gfc_generate_initializer (gfc_typespec *ts, bool generate)
{
  gfc_expr *init, *tmp;
Jerry DeLisle committed
4932
  gfc_component *comp;
4933

4934
  generate = flag_init_derived && generate;
4935

4936 4937 4938
  if (ts->u.derived->ts.is_iso_c && generate)
    return generate_isocbinding_initializer (ts->u.derived);

4939
  /* See if we have a default initializer in this, but not in nested
4940 4941 4942 4943 4944 4945
     types (otherwise we could use gfc_has_default_initializer()).
     We don't need to check if we are going to generate them.  */
  comp = ts->u.derived->components;
  if (!generate)
    {
      for (; comp; comp = comp->next)
4946
	if (comp->initializer || comp_allocatable (comp))
4947 4948
          break;
    }
4949

Jerry DeLisle committed
4950
  if (!comp)
4951 4952
    return NULL;

Jerry DeLisle committed
4953 4954
  init = gfc_get_structure_constructor_expr (ts->type, ts->kind,
					     &ts->u.derived->declared_at);
4955
  init->ts = *ts;
4956

Jerry DeLisle committed
4957
  for (comp = ts->u.derived->components; comp; comp = comp->next)
4958
    {
Jerry DeLisle committed
4959
      gfc_constructor *ctor = gfc_constructor_get();
4960

4961
      /* Fetch or generate an initializer for the component.  */
4962
      tmp = component_initializer (comp, generate);
4963
      if (tmp)
4964
	{
4965 4966 4967 4968
	  /* Save the component ref for STRUCTUREs and UNIONs.  */
	  if (ts->u.derived->attr.flavor == FL_STRUCT
	      || ts->u.derived->attr.flavor == FL_UNION)
	    ctor->n.component = comp;
4969 4970 4971

          /* If the initializer was not generated, we need a copy.  */
          ctor->expr = comp->initializer ? gfc_copy_expr (tmp) : tmp;
4972
	  if ((comp->ts.type != tmp->ts.type || comp->ts.kind != tmp->ts.kind)
4973
	      && !comp->attr.pointer && !comp->attr.proc_pointer)
4974 4975 4976 4977 4978 4979
	    {
	      bool val;
	      val = gfc_convert_type_warn (ctor->expr, &comp->ts, 1, false);
	      if (val == false)
		return NULL;
	    }
4980
	}
Paul Thomas committed
4981

Jerry DeLisle committed
4982
      gfc_constructor_append (&init->value.constructor, ctor);
4983
    }
Jerry DeLisle committed
4984

4985 4986
  return init;
}
4987 4988 4989 4990 4991 4992 4993


/* Given a symbol, create an expression node with that symbol as a
   variable. If the symbol is array valued, setup a reference of the
   whole array.  */

gfc_expr *
4994
gfc_get_variable_expr (gfc_symtree *var)
4995 4996 4997 4998 4999 5000 5001 5002
{
  gfc_expr *e;

  e = gfc_get_expr ();
  e->expr_type = EXPR_VARIABLE;
  e->symtree = var;
  e->ts = var->n.sym->ts;

5003 5004 5005 5006
  if (var->n.sym->attr.flavor != FL_PROCEDURE
      && ((var->n.sym->as != NULL && var->n.sym->ts.type != BT_CLASS)
	   || (var->n.sym->ts.type == BT_CLASS && CLASS_DATA (var->n.sym)
	       && CLASS_DATA (var->n.sym)->as)))
5007
    {
5008 5009
      e->rank = var->n.sym->ts.type == BT_CLASS
		? CLASS_DATA (var->n.sym)->as->rank : var->n.sym->as->rank;
5010 5011 5012
      e->ref = gfc_get_ref ();
      e->ref->type = REF_ARRAY;
      e->ref->u.ar.type = AR_FULL;
5013 5014 5015
      e->ref->u.ar.as = gfc_copy_array_spec (var->n.sym->ts.type == BT_CLASS
					     ? CLASS_DATA (var->n.sym)->as
					     : var->n.sym->as);
5016 5017 5018 5019 5020
    }

  return e;
}

5021

5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048
/* Adds a full array reference to an expression, as needed.  */

void
gfc_add_full_array_ref (gfc_expr *e, gfc_array_spec *as)
{
  gfc_ref *ref;
  for (ref = e->ref; ref; ref = ref->next)
    if (!ref->next)
      break;
  if (ref)
    {
      ref->next = gfc_get_ref ();
      ref = ref->next;
    }
  else
    {
      e->ref = gfc_get_ref ();
      ref = e->ref;
    }
  ref->type = REF_ARRAY;
  ref->u.ar.type = AR_FULL;
  ref->u.ar.dimen = e->rank;
  ref->u.ar.where = e->where;
  ref->u.ar.as = as;
}


5049 5050 5051 5052
gfc_expr *
gfc_lval_expr_from_sym (gfc_symbol *sym)
{
  gfc_expr *lval;
Andre Vehreschild committed
5053
  gfc_array_spec *as;
5054 5055 5056 5057 5058 5059 5060
  lval = gfc_get_expr ();
  lval->expr_type = EXPR_VARIABLE;
  lval->where = sym->declared_at;
  lval->ts = sym->ts;
  lval->symtree = gfc_find_symtree (sym->ns->sym_root, sym->name);

  /* It will always be a full array.  */
Andre Vehreschild committed
5061 5062
  as = IS_CLASS_ARRAY (sym) ? CLASS_DATA (sym)->as : sym->as;
  lval->rank = as ? as->rank : 0;
5063
  if (lval->rank)
Andre Vehreschild committed
5064
    gfc_add_full_array_ref (lval, as);
5065 5066 5067 5068
  return lval;
}


5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083
/* Returns the array_spec of a full array expression.  A NULL is
   returned otherwise.  */
gfc_array_spec *
gfc_get_full_arrayspec_from_expr (gfc_expr *expr)
{
  gfc_array_spec *as;
  gfc_ref *ref;

  if (expr->rank == 0)
    return NULL;

  /* Follow any component references.  */
  if (expr->expr_type == EXPR_VARIABLE
      || expr->expr_type == EXPR_CONSTANT)
    {
5084 5085 5086 5087 5088
      if (expr->symtree)
	as = expr->symtree->n.sym->as;
      else
	as = NULL;

5089 5090 5091 5092 5093 5094 5095 5096 5097
      for (ref = expr->ref; ref; ref = ref->next)
	{
	  switch (ref->type)
	    {
	    case REF_COMPONENT:
	      as = ref->u.c.component->as;
	      continue;

	    case REF_SUBSTRING:
5098
	    case REF_INQUIRY:
5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125
	      continue;

	    case REF_ARRAY:
	      {
		switch (ref->u.ar.type)
		  {
		  case AR_ELEMENT:
		  case AR_SECTION:
		  case AR_UNKNOWN:
		    as = NULL;
		    continue;

		  case AR_FULL:
		    break;
		  }
		break;
	      }
	    }
	}
    }
  else
    as = NULL;

  return as;
}


Paul Thomas committed
5126
/* General expression traversal function.  */
5127

Paul Thomas committed
5128 5129 5130 5131
bool
gfc_traverse_expr (gfc_expr *expr, gfc_symbol *sym,
		   bool (*func)(gfc_expr *, gfc_symbol *, int*),
		   int f)
5132
{
Paul Thomas committed
5133
  gfc_array_ref ar;
5134
  gfc_ref *ref;
Paul Thomas committed
5135 5136
  gfc_actual_arglist *args;
  gfc_constructor *c;
5137 5138
  int i;

Paul Thomas committed
5139 5140
  if (!expr)
    return false;
5141

5142 5143
  if ((*func) (expr, sym, &f))
    return true;
5144

5145
  if (expr->ts.type == BT_CHARACTER
5146 5147 5148 5149
	&& expr->ts.u.cl
	&& expr->ts.u.cl->length
	&& expr->ts.u.cl->length->expr_type != EXPR_CONSTANT
	&& gfc_traverse_expr (expr->ts.u.cl->length, sym, func, f))
5150
    return true;
5151

5152 5153
  switch (expr->expr_type)
    {
5154 5155
    case EXPR_PPC:
    case EXPR_COMPCALL:
Paul Thomas committed
5156 5157 5158 5159 5160 5161
    case EXPR_FUNCTION:
      for (args = expr->value.function.actual; args; args = args->next)
	{
	  if (gfc_traverse_expr (args->expr, sym, func, f))
	    return true;
	}
5162 5163
      break;

5164
    case EXPR_VARIABLE:
5165 5166 5167 5168 5169 5170 5171
    case EXPR_CONSTANT:
    case EXPR_NULL:
    case EXPR_SUBSTRING:
      break;

    case EXPR_STRUCTURE:
    case EXPR_ARRAY:
Jerry DeLisle committed
5172 5173
      for (c = gfc_constructor_first (expr->value.constructor);
	   c; c = gfc_constructor_next (c))
5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188
	{
	  if (gfc_traverse_expr (c->expr, sym, func, f))
	    return true;
	  if (c->iterator)
	    {
	      if (gfc_traverse_expr (c->iterator->var, sym, func, f))
		return true;
	      if (gfc_traverse_expr (c->iterator->start, sym, func, f))
		return true;
	      if (gfc_traverse_expr (c->iterator->end, sym, func, f))
		return true;
	      if (gfc_traverse_expr (c->iterator->step, sym, func, f))
		return true;
	    }
	}
5189 5190
      break;

Paul Thomas committed
5191 5192 5193 5194 5195 5196 5197
    case EXPR_OP:
      if (gfc_traverse_expr (expr->value.op.op1, sym, func, f))
	return true;
      if (gfc_traverse_expr (expr->value.op.op2, sym, func, f))
	return true;
      break;

5198 5199 5200 5201 5202
    default:
      gcc_unreachable ();
      break;
    }

Paul Thomas committed
5203 5204 5205
  ref = expr->ref;
  while (ref != NULL)
    {
5206
      switch (ref->type)
5207
	{
Paul Thomas committed
5208 5209 5210
	case  REF_ARRAY:
	  ar = ref->u.ar;
	  for (i = 0; i < GFC_MAX_DIMENSIONS; i++)
5211
	    {
Paul Thomas committed
5212 5213 5214 5215 5216 5217
	      if (gfc_traverse_expr (ar.start[i], sym, func, f))
		return true;
	      if (gfc_traverse_expr (ar.end[i], sym, func, f))
		return true;
	      if (gfc_traverse_expr (ar.stride[i], sym, func, f))
		return true;
5218 5219
	    }
	  break;
Paul Thomas committed
5220

5221
	case REF_SUBSTRING:
Paul Thomas committed
5222 5223 5224 5225
	  if (gfc_traverse_expr (ref->u.ss.start, sym, func, f))
	    return true;
	  if (gfc_traverse_expr (ref->u.ss.end, sym, func, f))
	    return true;
5226
	  break;
Paul Thomas committed
5227

5228 5229
	case REF_COMPONENT:
	  if (ref->u.c.component->ts.type == BT_CHARACTER
5230 5231 5232
		&& ref->u.c.component->ts.u.cl
		&& ref->u.c.component->ts.u.cl->length
		&& ref->u.c.component->ts.u.cl->length->expr_type
5233
		     != EXPR_CONSTANT
5234
		&& gfc_traverse_expr (ref->u.c.component->ts.u.cl->length,
5235 5236 5237 5238
				      sym, func, f))
	    return true;

	  if (ref->u.c.component->as)
5239 5240
	    for (i = 0; i < ref->u.c.component->as->rank
			    + ref->u.c.component->as->corank; i++)
5241 5242 5243 5244 5245 5246 5247 5248 5249
	      {
		if (gfc_traverse_expr (ref->u.c.component->as->lower[i],
				       sym, func, f))
		  return true;
		if (gfc_traverse_expr (ref->u.c.component->as->upper[i],
				       sym, func, f))
		  return true;
	      }
	  break;
Paul Thomas committed
5250

5251 5252 5253
	case REF_INQUIRY:
	  return true;

5254 5255 5256
	default:
	  gcc_unreachable ();
	}
Paul Thomas committed
5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268
      ref = ref->next;
    }
  return false;
}

/* Traverse expr, marking all EXPR_VARIABLE symbols referenced.  */

static bool
expr_set_symbols_referenced (gfc_expr *expr,
			     gfc_symbol *sym ATTRIBUTE_UNUSED,
			     int *f ATTRIBUTE_UNUSED)
{
5269 5270
  if (expr->expr_type != EXPR_VARIABLE)
    return false;
Paul Thomas committed
5271 5272 5273 5274 5275 5276 5277 5278
  gfc_set_sym_referenced (expr->symtree->n.sym);
  return false;
}

void
gfc_expr_set_symbols_referenced (gfc_expr *expr)
{
  gfc_traverse_expr (expr, NULL, expr_set_symbols_referenced, 0);
5279
}
5280 5281


5282 5283
/* Determine if an expression is a procedure pointer component and return
   the component in that case.  Otherwise return NULL.  */
5284

5285 5286
gfc_component *
gfc_get_proc_ptr_comp (gfc_expr *expr)
5287 5288 5289 5290
{
  gfc_ref *ref;

  if (!expr || !expr->ref)
5291
    return NULL;
5292 5293 5294 5295 5296

  ref = expr->ref;
  while (ref->next)
    ref = ref->next;

5297 5298 5299 5300 5301 5302 5303
  if (ref->type == REF_COMPONENT
      && ref->u.c.component->attr.proc_pointer)
    return ref->u.c.component;

  return NULL;
}

5304

5305 5306 5307 5308 5309 5310
/* Determine if an expression is a procedure pointer component.  */

bool
gfc_is_proc_ptr_comp (gfc_expr *expr)
{
  return (gfc_get_proc_ptr_comp (expr) != NULL);
5311 5312 5313
}


5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333
/* Determine if an expression is a function with an allocatable class scalar
   result.  */
bool
gfc_is_alloc_class_scalar_function (gfc_expr *expr)
{
  if (expr->expr_type == EXPR_FUNCTION
      && expr->value.function.esym
      && expr->value.function.esym->result
      && expr->value.function.esym->result->ts.type == BT_CLASS
      && !CLASS_DATA (expr->value.function.esym->result)->attr.dimension
      && CLASS_DATA (expr->value.function.esym->result)->attr.allocatable)
    return true;

  return false;
}


/* Determine if an expression is a function with an allocatable class array
   result.  */
bool
5334
gfc_is_class_array_function (gfc_expr *expr)
5335 5336 5337 5338 5339 5340
{
  if (expr->expr_type == EXPR_FUNCTION
      && expr->value.function.esym
      && expr->value.function.esym->result
      && expr->value.function.esym->result->ts.type == BT_CLASS
      && CLASS_DATA (expr->value.function.esym->result)->attr.dimension
5341 5342
      && (CLASS_DATA (expr->value.function.esym->result)->attr.allocatable
	  || CLASS_DATA (expr->value.function.esym->result)->attr.pointer))
5343 5344 5345 5346 5347 5348
    return true;

  return false;
}


5349 5350
/* Walk an expression tree and check each variable encountered for being typed.
   If strict is not set, a top-level variable is tolerated untyped in -std=gnu
5351 5352
   mode as is a basic arithmetic expression using those; this is for things in
   legacy-code like:
5353 5354

     INTEGER :: arr(n), n
5355
     INTEGER :: arr(n + 1), n
5356 5357 5358

   The namespace is needed for IMPLICIT typing.  */

5359 5360 5361 5362 5363
static gfc_namespace* check_typed_ns;

static bool
expr_check_typed_help (gfc_expr* e, gfc_symbol* sym ATTRIBUTE_UNUSED,
                       int* f ATTRIBUTE_UNUSED)
5364
{
5365
  bool t;
5366

5367 5368
  if (e->expr_type != EXPR_VARIABLE)
    return false;
5369

5370 5371 5372
  gcc_assert (e->symtree);
  t = gfc_check_symbol_typed (e->symtree->n.sym, check_typed_ns,
                              true, e->where);
5373

5374
  return (!t);
5375
}
5376

5377
bool
5378 5379 5380
gfc_expr_check_typed (gfc_expr* e, gfc_namespace* ns, bool strict)
{
  bool error_found;
5381

5382 5383 5384 5385 5386 5387 5388 5389 5390
  /* If this is a top-level variable or EXPR_OP, do the check with strict given
     to us.  */
  if (!strict)
    {
      if (e->expr_type == EXPR_VARIABLE && !e->ref)
	return gfc_check_symbol_typed (e->symtree->n.sym, ns, strict, e->where);

      if (e->expr_type == EXPR_OP)
	{
5391
	  bool t = true;
5392 5393 5394 5395

	  gcc_assert (e->value.op.op1);
	  t = gfc_expr_check_typed (e->value.op.op1, ns, strict);

5396
	  if (t && e->value.op.op2)
5397 5398 5399 5400 5401
	    t = gfc_expr_check_typed (e->value.op.op2, ns, strict);

	  return t;
	}
    }
5402

5403 5404 5405
  /* Otherwise, walk the expression and do it strictly.  */
  check_typed_ns = ns;
  error_found = gfc_traverse_expr (e, NULL, &expr_check_typed_help, 0);
5406

5407
  return error_found ? false : true;
5408
}
5409

5410

5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480
/* This function returns true if it contains any references to PDT KIND
   or LEN parameters.  */

static bool
derived_parameter_expr (gfc_expr* e, gfc_symbol* sym ATTRIBUTE_UNUSED,
			int* f ATTRIBUTE_UNUSED)
{
  if (e->expr_type != EXPR_VARIABLE)
    return false;

  gcc_assert (e->symtree);
  if (e->symtree->n.sym->attr.pdt_kind
      || e->symtree->n.sym->attr.pdt_len)
    return true;

  return false;
}


bool
gfc_derived_parameter_expr (gfc_expr *e)
{
  return gfc_traverse_expr (e, NULL, &derived_parameter_expr, 0);
}


/* This function returns the overall type of a type parameter spec list.
   If all the specs are explicit, SPEC_EXPLICIT is returned. If any of the
   parameters are assumed/deferred then SPEC_ASSUMED/DEFERRED is returned
   unless derived is not NULL.  In this latter case, all the LEN parameters
   must be either assumed or deferred for the return argument to be set to
   anything other than SPEC_EXPLICIT.  */

gfc_param_spec_type
gfc_spec_list_type (gfc_actual_arglist *param_list, gfc_symbol *derived)
{
  gfc_param_spec_type res = SPEC_EXPLICIT;
  gfc_component *c;
  bool seen_assumed = false;
  bool seen_deferred = false;

  if (derived == NULL)
    {
      for (; param_list; param_list = param_list->next)
	if (param_list->spec_type == SPEC_ASSUMED
	    || param_list->spec_type == SPEC_DEFERRED)
	  return param_list->spec_type;
    }
  else
    {
      for (; param_list; param_list = param_list->next)
	{
	  c = gfc_find_component (derived, param_list->name,
				  true, true, NULL);
	  gcc_assert (c != NULL);
	  if (c->attr.pdt_kind)
	    continue;
	  else if (param_list->spec_type == SPEC_EXPLICIT)
	    return SPEC_EXPLICIT;
	  seen_assumed = param_list->spec_type == SPEC_ASSUMED;
	  seen_deferred = param_list->spec_type == SPEC_DEFERRED;
	  if (seen_assumed && seen_deferred)
	    return SPEC_EXPLICIT;
	}
      res = seen_assumed ? SPEC_ASSUMED : SPEC_DEFERRED;
    }
  return res;
}


5481
bool
5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494
gfc_ref_this_image (gfc_ref *ref)
{
  int n;

  gcc_assert (ref->type == REF_ARRAY && ref->u.ar.codimen > 0);

  for (n = ref->u.ar.dimen; n < ref->u.ar.dimen + ref->u.ar.codimen; n++)
    if (ref->u.ar.dimen_type[n] != DIMEN_THIS_IMAGE)
      return false;

  return true;
}

5495
gfc_expr *
5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514
gfc_find_team_co (gfc_expr *e)
{
  gfc_ref *ref;

  for (ref = e->ref; ref; ref = ref->next)
    if (ref->type == REF_ARRAY && ref->u.ar.codimen > 0)
      return ref->u.ar.team;

  if (e->value.function.actual->expr)
    for (ref = e->value.function.actual->expr->ref; ref;
	 ref = ref->next)
      if (ref->type == REF_ARRAY && ref->u.ar.codimen > 0)
	return ref->u.ar.team;

  return NULL;
}

gfc_expr *
gfc_find_stat_co (gfc_expr *e)
5515 5516 5517 5518 5519 5520 5521
{
  gfc_ref *ref;

  for (ref = e->ref; ref; ref = ref->next)
    if (ref->type == REF_ARRAY && ref->u.ar.codimen > 0)
      return ref->u.ar.stat;

5522 5523 5524
  if (e->value.function.actual->expr)
    for (ref = e->value.function.actual->expr->ref; ref;
	 ref = ref->next)
5525 5526 5527 5528 5529
      if (ref->type == REF_ARRAY && ref->u.ar.codimen > 0)
	return ref->u.ar.stat;

  return NULL;
}
5530 5531

bool
5532 5533 5534 5535 5536 5537
gfc_is_coindexed (gfc_expr *e)
{
  gfc_ref *ref;

  for (ref = e->ref; ref; ref = ref->next)
    if (ref->type == REF_ARRAY && ref->u.ar.codimen > 0)
5538
      return !gfc_ref_this_image (ref);
5539 5540 5541 5542 5543

  return false;
}


5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574
/* Coarrays are variables with a corank but not being coindexed. However, also
   the following is a coarray: A subobject of a coarray is a coarray if it does
   not have any cosubscripts, vector subscripts, allocatable component
   selection, or pointer component selection. (F2008, 2.4.7)  */

bool
gfc_is_coarray (gfc_expr *e)
{
  gfc_ref *ref;
  gfc_symbol *sym;
  gfc_component *comp;
  bool coindexed;
  bool coarray;
  int i;

  if (e->expr_type != EXPR_VARIABLE)
    return false;

  coindexed = false;
  sym = e->symtree->n.sym;

  if (sym->ts.type == BT_CLASS && sym->attr.class_ok)
    coarray = CLASS_DATA (sym)->attr.codimension;
  else
    coarray = sym->attr.codimension;

  for (ref = e->ref; ref; ref = ref->next)
    switch (ref->type)
    {
      case REF_COMPONENT:
	comp = ref->u.c.component;
5575 5576 5577
	if (comp->ts.type == BT_CLASS && comp->attr.class_ok
	    && (CLASS_DATA (comp)->attr.class_pointer
		|| CLASS_DATA (comp)->attr.allocatable))
5578 5579
	  {
	    coindexed = false;
5580 5581 5582 5583 5584 5585
	    coarray = CLASS_DATA (comp)->attr.codimension;
	  }
        else if (comp->attr.pointer || comp->attr.allocatable)
	  {
	    coindexed = false;
	    coarray = comp->attr.codimension;
5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607
	  }
        break;

     case REF_ARRAY:
	if (!coarray)
	  break;

	if (ref->u.ar.codimen > 0 && !gfc_ref_this_image (ref))
	  {
	    coindexed = true;
	    break;
	  }

	for (i = 0; i < ref->u.ar.dimen; i++)
	  if (ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
	    {
	      coarray = false;
	      break;
	    }
	break;

     case REF_SUBSTRING:
5608
     case REF_INQUIRY:
5609 5610 5611 5612 5613 5614 5615
	break;
    }

  return coarray && !coindexed;
}


5616
int
5617 5618 5619 5620
gfc_get_corank (gfc_expr *e)
{
  int corank;
  gfc_ref *ref;
5621 5622 5623 5624

  if (!gfc_is_coarray (e))
    return 0;

5625 5626 5627
  if (e->ts.type == BT_CLASS && e->ts.u.derived->components)
    corank = e->ts.u.derived->components->as
	     ? e->ts.u.derived->components->as->corank : 0;
5628
  else
5629
    corank = e->symtree->n.sym->as ? e->symtree->n.sym->as->corank : 0;
5630

5631 5632 5633 5634 5635 5636
  for (ref = e->ref; ref; ref = ref->next)
    {
      if (ref->type == REF_ARRAY)
	corank = ref->u.ar.as->corank;
      gcc_assert (ref->type != REF_SUBSTRING);
    }
5637

5638 5639 5640 5641
  return corank;
}


5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656
/* Check whether the expression has an ultimate allocatable component.
   Being itself allocatable does not count.  */
bool
gfc_has_ultimate_allocatable (gfc_expr *e)
{
  gfc_ref *ref, *last = NULL;

  if (e->expr_type != EXPR_VARIABLE)
    return false;

  for (ref = e->ref; ref; ref = ref->next)
    if (ref->type == REF_COMPONENT)
      last = ref;

  if (last && last->u.c.component->ts.type == BT_CLASS)
5657
    return CLASS_DATA (last->u.c.component)->attr.alloc_comp;
5658 5659 5660 5661 5662 5663
  else if (last && last->u.c.component->ts.type == BT_DERIVED)
    return last->u.c.component->ts.u.derived->attr.alloc_comp;
  else if (last)
    return false;

  if (e->ts.type == BT_CLASS)
5664
    return CLASS_DATA (e)->attr.alloc_comp;
5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684
  else if (e->ts.type == BT_DERIVED)
    return e->ts.u.derived->attr.alloc_comp;
  else
    return false;
}


/* Check whether the expression has an pointer component.
   Being itself a pointer does not count.  */
bool
gfc_has_ultimate_pointer (gfc_expr *e)
{
  gfc_ref *ref, *last = NULL;

  if (e->expr_type != EXPR_VARIABLE)
    return false;

  for (ref = e->ref; ref; ref = ref->next)
    if (ref->type == REF_COMPONENT)
      last = ref;
5685

5686
  if (last && last->u.c.component->ts.type == BT_CLASS)
5687
    return CLASS_DATA (last->u.c.component)->attr.pointer_comp;
5688 5689 5690 5691 5692 5693
  else if (last && last->u.c.component->ts.type == BT_DERIVED)
    return last->u.c.component->ts.u.derived->attr.pointer_comp;
  else if (last)
    return false;

  if (e->ts.type == BT_CLASS)
5694
    return CLASS_DATA (e)->attr.pointer_comp;
5695 5696 5697 5698 5699
  else if (e->ts.type == BT_DERIVED)
    return e->ts.u.derived->attr.pointer_comp;
  else
    return false;
}
5700 5701 5702 5703


/* Check whether an expression is "simply contiguous", cf. F2008, 6.5.4.
   Note: A scalar is not regarded as "simply contiguous" by the standard.
5704
   if bool is not strict, some further checks are done - for instance,
5705 5706 5707
   a "(::1)" is accepted.  */

bool
5708
gfc_is_simply_contiguous (gfc_expr *expr, bool strict, bool permit_element)
5709 5710 5711 5712 5713
{
  bool colon;
  int i;
  gfc_array_ref *ar = NULL;
  gfc_ref *ref, *part_ref = NULL;
5714
  gfc_symbol *sym;
5715

5716 5717 5718
  if (expr->expr_type == EXPR_ARRAY)
    return true;

5719
  if (expr->expr_type == EXPR_FUNCTION)
5720 5721 5722 5723 5724
    {
      if (expr->value.function.esym)
	return expr->value.function.esym->result->attr.contiguous;
      else
	{
5725 5726 5727
	  /* Type-bound procedures.  */
	  gfc_symbol *s = expr->symtree->n.sym;
	  if (s->ts.type != BT_CLASS && s->ts.type != BT_DERIVED)
5728
	    return false;
5729

5730 5731
	  gfc_ref *rc = NULL;
	  for (gfc_ref *r = expr->ref; r; r = r->next)
5732 5733 5734 5735 5736 5737 5738 5739 5740 5741
	    if (r->type == REF_COMPONENT)
	      rc = r;

	  if (rc == NULL || rc->u.c.component == NULL
	      || rc->u.c.component->ts.interface == NULL)
	    return false;

	  return rc->u.c.component->ts.interface->attr.contiguous;
	}
    }
5742 5743 5744
  else if (expr->expr_type != EXPR_VARIABLE)
    return false;

5745
  if (!permit_element && expr->rank == 0)
5746 5747 5748 5749 5750
    return false;

  for (ref = expr->ref; ref; ref = ref->next)
    {
      if (ar)
5751
	return false; /* Array shall be last part-ref.  */
5752 5753 5754 5755 5756 5757 5758 5759 5760

      if (ref->type == REF_COMPONENT)
	part_ref  = ref;
      else if (ref->type == REF_SUBSTRING)
	return false;
      else if (ref->u.ar.type != AR_ELEMENT)
	ar = &ref->u.ar;
    }

5761 5762
  sym = expr->symtree->n.sym;
  if (expr->ts.type != BT_CLASS
5763 5764 5765 5766 5767 5768 5769 5770
      && ((part_ref
	   && !part_ref->u.c.component->attr.contiguous
	   && part_ref->u.c.component->attr.pointer)
	  || (!part_ref
	      && !sym->attr.contiguous
	      && (sym->attr.pointer
		  || (sym->as && sym->as->type == AS_ASSUMED_RANK)
		  || (sym->as && sym->as->type == AS_ASSUMED_SHAPE)))))
5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804
    return false;

  if (!ar || ar->type == AR_FULL)
    return true;

  gcc_assert (ar->type == AR_SECTION);

  /* Check for simply contiguous array */
  colon = true;
  for (i = 0; i < ar->dimen; i++)
    {
      if (ar->dimen_type[i] == DIMEN_VECTOR)
	return false;

      if (ar->dimen_type[i] == DIMEN_ELEMENT)
	{
	  colon = false;
	  continue;
	}

      gcc_assert (ar->dimen_type[i] == DIMEN_RANGE);


      /* If the previous section was not contiguous, that's an error,
	 unless we have effective only one element and checking is not
	 strict.  */
      if (!colon && (strict || !ar->start[i] || !ar->end[i]
		     || ar->start[i]->expr_type != EXPR_CONSTANT
		     || ar->end[i]->expr_type != EXPR_CONSTANT
		     || mpz_cmp (ar->start[i]->value.integer,
				 ar->end[i]->value.integer) != 0))
	return false;

      /* Following the standard, "(::1)" or - if known at compile time -
5805
	 "(lbound:ubound)" are not simply contiguous; if strict
5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827
	 is false, they are regarded as simply contiguous.  */
      if (ar->stride[i] && (strict || ar->stride[i]->expr_type != EXPR_CONSTANT
			    || ar->stride[i]->ts.type != BT_INTEGER
			    || mpz_cmp_si (ar->stride[i]->value.integer, 1) != 0))
	return false;

      if (ar->start[i]
	  && (strict || ar->start[i]->expr_type != EXPR_CONSTANT
	      || !ar->as->lower[i]
	      || ar->as->lower[i]->expr_type != EXPR_CONSTANT
	      || mpz_cmp (ar->start[i]->value.integer,
			  ar->as->lower[i]->value.integer) != 0))
	colon = false;

      if (ar->end[i]
	  && (strict || ar->end[i]->expr_type != EXPR_CONSTANT
	      || !ar->as->upper[i]
	      || ar->as->upper[i]->expr_type != EXPR_CONSTANT
	      || mpz_cmp (ar->end[i]->value.integer,
			  ar->as->upper[i]->value.integer) != 0))
	colon = false;
    }
5828

5829 5830
  return true;
}
5831

5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900
/* Return true if the expression is guaranteed to be non-contiguous,
   false if we cannot prove anything.  It is probably best to call
   this after gfc_is_simply_contiguous.  If neither of them returns
   true, we cannot say (at compile-time).  */

bool
gfc_is_not_contiguous (gfc_expr *array)
{
  int i;
  gfc_array_ref *ar = NULL;
  gfc_ref *ref;
  bool previous_incomplete;

  for (ref = array->ref; ref; ref = ref->next)
    {
      /* Array-ref shall be last ref.  */

      if (ar)
	return true;

      if (ref->type == REF_ARRAY)
	ar = &ref->u.ar;
    }

  if (ar == NULL || ar->type != AR_SECTION)
    return false;

  previous_incomplete = false;

  /* Check if we can prove that the array is not contiguous.  */

  for (i = 0; i < ar->dimen; i++)
    {
      mpz_t arr_size, ref_size;

      if (gfc_ref_dimen_size (ar, i, &ref_size, NULL))
	{
	  if (gfc_dep_difference (ar->as->lower[i], ar->as->upper[i], &arr_size))
	    {
	      /* a(2:4,2:) is known to be non-contiguous, but
		 a(2:4,i:i) can be contiguous.  */
	      if (previous_incomplete && mpz_cmp_si (ref_size, 1) != 0)
		{
		  mpz_clear (arr_size);
		  mpz_clear (ref_size);
		  return true;
		}
	      else if (mpz_cmp (arr_size, ref_size) != 0)
		previous_incomplete = true;

	      mpz_clear (arr_size);
	    }

	  /* Check for a(::2), i.e. where the stride is not unity.
	     This is only done if there is more than one element in
	     the reference along this dimension.  */

	  if (mpz_cmp_ui (ref_size, 1) > 0 && ar->type == AR_SECTION
	      && ar->dimen_type[i] == DIMEN_RANGE
	      && ar->stride[i] && ar->stride[i]->expr_type == EXPR_CONSTANT
	      && mpz_cmp_si (ar->stride[i]->value.integer, 1) != 0)
	    return true;

	  mpz_clear (ref_size);
	}
    }
  /* We didn't find anything definitive.  */
  return false;
}
5901 5902 5903 5904 5905 5906

/* Build call to an intrinsic procedure.  The number of arguments has to be
   passed (rather than ending the list with a NULL value) because we may
   want to add arguments but with a NULL-expression.  */

gfc_expr*
5907 5908
gfc_build_intrinsic_call (gfc_namespace *ns, gfc_isym_id id, const char* name,
			  locus where, unsigned numarg, ...)
5909 5910 5911 5912 5913 5914
{
  gfc_expr* result;
  gfc_actual_arglist* atail;
  gfc_intrinsic_sym* isym;
  va_list ap;
  unsigned i;
5915
  const char *mangled_name = gfc_get_string (GFC_PREFIX ("%s"), name);
5916

5917
  isym = gfc_intrinsic_function_by_id (id);
5918
  gcc_assert (isym);
5919

5920 5921 5922 5923
  result = gfc_get_expr ();
  result->expr_type = EXPR_FUNCTION;
  result->ts = isym->ts;
  result->where = where;
5924
  result->value.function.name = mangled_name;
5925 5926
  result->value.function.isym = isym;

5927 5928
  gfc_get_sym_tree (mangled_name, ns, &result->symtree, false);
  gfc_commit_symbol (result->symtree->n.sym);
5929 5930 5931
  gcc_assert (result->symtree
	      && (result->symtree->n.sym->attr.flavor == FL_PROCEDURE
		  || result->symtree->n.sym->attr.flavor == FL_UNKNOWN));
5932 5933 5934
  result->symtree->n.sym->intmod_sym_id = id;
  result->symtree->n.sym->attr.flavor = FL_PROCEDURE;
  result->symtree->n.sym->attr.intrinsic = 1;
5935
  result->symtree->n.sym->attr.artificial = 1;
5936

5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954
  va_start (ap, numarg);
  atail = NULL;
  for (i = 0; i < numarg; ++i)
    {
      if (atail)
	{
	  atail->next = gfc_get_actual_arglist ();
	  atail = atail->next;
	}
      else
	atail = result->value.function.actual = gfc_get_actual_arglist ();

      atail->expr = va_arg (ap, gfc_expr*);
    }
  va_end (ap);

  return result;
}
5955 5956 5957 5958 5959 5960


/* Check if an expression may appear in a variable definition context
   (F2008, 16.6.7) or pointer association context (F2008, 16.6.8).
   This is called from the various places when resolving
   the pieces that make up such a context.
5961 5962
   If own_scope is true (applies to, e.g., ac-implied-do/data-implied-do
   variables), some checks are not performed.
5963 5964

   Optionally, a possible error message can be suppressed if context is NULL
5965
   and just the return status (true / false) be requested.  */
5966

5967
bool
5968
gfc_check_vardef_context (gfc_expr* e, bool pointer, bool alloc_obj,
5969
			  bool own_scope, const char* context)
5970
{
5971
  gfc_symbol* sym = NULL;
5972 5973 5974 5975 5976
  bool is_pointer;
  bool check_intentin;
  bool ptr_component;
  symbol_attribute attr;
  gfc_ref* ref;
5977
  int i;
5978

5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989
  if (e->expr_type == EXPR_VARIABLE)
    {
      gcc_assert (e->symtree);
      sym = e->symtree->n.sym;
    }
  else if (e->expr_type == EXPR_FUNCTION)
    {
      gcc_assert (e->symtree);
      sym = e->value.function.esym ? e->value.function.esym : e->symtree->n.sym;
    }

5990 5991
  attr = gfc_expr_attr (e);
  if (!pointer && e->expr_type == EXPR_FUNCTION && attr.pointer)
5992 5993 5994 5995 5996 5997
    {
      if (!(gfc_option.allow_std & GFC_STD_F2008))
	{
	  if (context)
	    gfc_error ("Fortran 2008: Pointer functions in variable definition"
		       " context (%s) at %L", context, &e->where);
5998
	  return false;
5999 6000 6001
	}
    }
  else if (e->expr_type != EXPR_VARIABLE)
6002 6003 6004 6005
    {
      if (context)
	gfc_error ("Non-variable expression in variable definition context (%s)"
		   " at %L", context, &e->where);
6006
      return false;
6007 6008 6009 6010 6011
    }

  if (!pointer && sym->attr.flavor == FL_PARAMETER)
    {
      if (context)
6012
	gfc_error ("Named constant %qs in variable definition context (%s)"
6013
		   " at %L", sym->name, context, &e->where);
6014
      return false;
6015 6016 6017 6018 6019 6020
    }
  if (!pointer && sym->attr.flavor != FL_VARIABLE
      && !(sym->attr.flavor == FL_PROCEDURE && sym == sym->result)
      && !(sym->attr.flavor == FL_PROCEDURE && sym->attr.proc_pointer))
    {
      if (context)
6021
	gfc_error ("%qs in variable definition context (%s) at %L is not"
6022
		   " a variable", sym->name, context, &e->where);
6023
      return false;
6024 6025 6026 6027 6028
    }

  /* Find out whether the expr is a pointer; this also means following
     component references to the last one.  */
  is_pointer = (attr.pointer || attr.proc_pointer);
6029
  if (pointer && !is_pointer)
6030 6031 6032 6033
    {
      if (context)
	gfc_error ("Non-POINTER in pointer association context (%s)"
		   " at %L", context, &e->where);
6034
      return false;
6035 6036
    }

Paul Thomas committed
6037 6038 6039 6040 6041 6042 6043 6044 6045
  if (e->ts.type == BT_DERIVED
      && e->ts.u.derived == NULL)
    {
      if (context)
	gfc_error ("Type inaccessible in variable definition context (%s) "
		   "at %L", context, &e->where);
      return false;
    }

6046 6047 6048 6049 6050 6051 6052 6053 6054 6055
  /* F2008, C1303.  */
  if (!alloc_obj
      && (attr.lock_comp
	  || (e->ts.type == BT_DERIVED
	      && e->ts.u.derived->from_intmod == INTMOD_ISO_FORTRAN_ENV
	      && e->ts.u.derived->intmod_sym_id == ISOFORTRAN_LOCK_TYPE)))
    {
      if (context)
	gfc_error ("LOCK_TYPE in variable definition context (%s) at %L",
		   context, &e->where);
6056
      return false;
6057 6058
    }

6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071
  /* TS18508, C702/C203.  */
  if (!alloc_obj
      && (attr.lock_comp
	  || (e->ts.type == BT_DERIVED
	      && e->ts.u.derived->from_intmod == INTMOD_ISO_FORTRAN_ENV
	      && e->ts.u.derived->intmod_sym_id == ISOFORTRAN_EVENT_TYPE)))
    {
      if (context)
	gfc_error ("LOCK_EVENT in variable definition context (%s) at %L",
		   context, &e->where);
      return false;
    }

Tobias Burnus committed
6072 6073 6074 6075 6076
  /* INTENT(IN) dummy argument.  Check this, unless the object itself is the
     component of sub-component of a pointer; we need to distinguish
     assignment to a pointer component from pointer-assignment to a pointer
     component.  Note that (normal) assignment to procedure pointers is not
     possible.  */
6077
  check_intentin = !own_scope;
6078 6079
  ptr_component = (sym->ts.type == BT_CLASS && sym->ts.u.derived
		   && CLASS_DATA (sym))
6080
		  ? CLASS_DATA (sym)->attr.class_pointer : sym->attr.pointer;
6081 6082 6083 6084 6085
  for (ref = e->ref; ref && check_intentin; ref = ref->next)
    {
      if (ptr_component && ref->type == REF_COMPONENT)
	check_intentin = false;
      if (ref->type == REF_COMPONENT && ref->u.c.component->attr.pointer)
Tobias Burnus committed
6086 6087 6088 6089 6090
	{
	  ptr_component = true;
	  if (!pointer)
	    check_intentin = false;
	}
6091
    }
6092 6093 6094 6095 6096 6097

  if (check_intentin
      && (sym->attr.intent == INTENT_IN
	  || (sym->attr.select_type_temporary && sym->assoc
	      && sym->assoc->target && sym->assoc->target->symtree
	      && sym->assoc->target->symtree->n.sym->attr.intent == INTENT_IN)))
6098 6099 6100 6101
    {
      if (pointer && is_pointer)
	{
	  if (context)
6102
	    gfc_error ("Dummy argument %qs with INTENT(IN) in pointer"
6103 6104
		       " association context (%s) at %L",
		       sym->name, context, &e->where);
6105
	  return false;
6106
	}
6107
      if (!pointer && !is_pointer && !sym->attr.pointer)
6108
	{
6109 6110
	  const char *name = sym->attr.select_type_temporary
			   ? sym->assoc->target->symtree->name : sym->name;
6111
	  if (context)
6112
	    gfc_error ("Dummy argument %qs with INTENT(IN) in variable"
6113
		       " definition context (%s) at %L",
6114
		       name, context, &e->where);
6115
	  return false;
6116 6117 6118 6119
	}
    }

  /* PROTECTED and use-associated.  */
6120
  if (sym->attr.is_protected && sym->attr.use_assoc && check_intentin)
6121 6122 6123 6124
    {
      if (pointer && is_pointer)
	{
	  if (context)
6125
	    gfc_error ("Variable %qs is PROTECTED and cannot appear in a"
6126 6127
		       " pointer association context (%s) at %L",
		       sym->name, context, &e->where);
6128
	  return false;
6129 6130 6131 6132
	}
      if (!pointer && !is_pointer)
	{
	  if (context)
6133
	    gfc_error ("Variable %qs is PROTECTED and cannot appear in a"
6134 6135
		       " variable definition context (%s) at %L",
		       sym->name, context, &e->where);
6136
	  return false;
6137 6138 6139 6140 6141
	}
    }

  /* Variable not assignable from a PURE procedure but appears in
     variable definition context.  */
6142
  if (!pointer && !own_scope && gfc_pure (NULL) && gfc_impure_variable (sym))
6143 6144
    {
      if (context)
6145
	gfc_error ("Variable %qs cannot appear in a variable definition"
6146 6147
		   " context (%s) at %L in PURE procedure",
		   sym->name, context, &e->where);
6148
      return false;
6149 6150
    }

6151 6152 6153 6154 6155
  if (!pointer && context && gfc_implicit_pure (NULL)
      && gfc_impure_variable (sym))
    {
      gfc_namespace *ns;
      gfc_symbol *sym;
6156

6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168
      for (ns = gfc_current_ns; ns; ns = ns->parent)
	{
	  sym = ns->proc_name;
	  if (sym == NULL)
	    break;
	  if (sym->attr.flavor == FL_PROCEDURE)
	    {
	      sym->attr.implicit_pure = 0;
	      break;
	    }
	}
    }
6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203
  /* Check variable definition context for associate-names.  */
  if (!pointer && sym->assoc)
    {
      const char* name;
      gfc_association_list* assoc;

      gcc_assert (sym->assoc->target);

      /* If this is a SELECT TYPE temporary (the association is used internally
	 for SELECT TYPE), silently go over to the target.  */
      if (sym->attr.select_type_temporary)
	{
	  gfc_expr* t = sym->assoc->target;

	  gcc_assert (t->expr_type == EXPR_VARIABLE);
	  name = t->symtree->name;

	  if (t->symtree->n.sym->assoc)
	    assoc = t->symtree->n.sym->assoc;
	  else
	    assoc = sym->assoc;
	}
      else
	{
	  name = sym->name;
	  assoc = sym->assoc;
	}
      gcc_assert (name && assoc);

      /* Is association to a valid variable?  */
      if (!assoc->variable)
	{
	  if (context)
	    {
	      if (assoc->target->expr_type == EXPR_VARIABLE)
6204 6205 6206
		gfc_error ("%qs at %L associated to vector-indexed target"
			   " cannot be used in a variable definition"
			   " context (%s)",
6207 6208
			   name, &e->where, context);
	      else
6209 6210 6211
		gfc_error ("%qs at %L associated to expression"
			   " cannot be used in a variable definition"
			   " context (%s)",
6212 6213
			   name, &e->where, context);
	    }
6214
	  return false;
6215 6216 6217
	}

      /* Target must be allowed to appear in a variable definition context.  */
6218
      if (!gfc_check_vardef_context (assoc->target, pointer, false, false, NULL))
6219 6220
	{
	  if (context)
6221
	    gfc_error ("Associate-name %qs cannot appear in a variable"
6222
		       " definition context (%s) at %L because its target"
6223
		       " at %L cannot, either",
6224 6225
		       name, context, &e->where,
		       &assoc->target->where);
6226
	  return false;
6227 6228 6229
	}
    }

6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243
  /* Check for same value in vector expression subscript.  */

  if (e->rank > 0)
    for (ref = e->ref; ref != NULL; ref = ref->next)
      if (ref->type == REF_ARRAY && ref->u.ar.type == AR_SECTION)
	for (i = 0; i < GFC_MAX_DIMENSIONS
	       && ref->u.ar.dimen_type[i] != 0; i++)
	  if (ref->u.ar.dimen_type[i] == DIMEN_VECTOR)
	    {
	      gfc_expr *arr = ref->u.ar.start[i];
	      if (arr->expr_type == EXPR_ARRAY)
		{
		  gfc_constructor *c, *n;
		  gfc_expr *ec, *en;
6244

6245 6246 6247 6248 6249
		  for (c = gfc_constructor_first (arr->value.constructor);
		       c != NULL; c = gfc_constructor_next (c))
		    {
		      if (c == NULL || c->iterator != NULL)
			continue;
6250

6251 6252 6253 6254 6255 6256 6257
		      ec = c->expr;

		      for (n = gfc_constructor_next (c); n != NULL;
			   n = gfc_constructor_next (n))
			{
			  if (n->iterator != NULL)
			    continue;
6258

6259 6260 6261
			  en = n->expr;
			  if (gfc_dep_compare_expr (ec, en) == 0)
			    {
6262
			      if (context)
6263 6264 6265 6266 6267 6268
				gfc_error_now ("Elements with the same value "
					       "at %L and %L in vector "
					       "subscript in a variable "
					       "definition context (%s)",
					       &(ec->where), &(en->where),
					       context);
6269 6270 6271 6272 6273 6274
			      return false;
			    }
			}
		    }
		}
	    }
6275

6276
  return true;
6277
}