array.c 57.8 KB
Newer Older
1
/* Array things
2
   Copyright (C) 2000-2017 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
#include "gfortran.h"
#include "match.h"
Jerry DeLisle committed
27
#include "constructor.h"
28 29 30 31 32 33

/**************** Array reference matching subroutines *****************/

/* Copy an array reference structure.  */

gfc_array_ref *
Steven G. Kargl committed
34
gfc_copy_array_ref (gfc_array_ref *src)
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
{
  gfc_array_ref *dest;
  int i;

  if (src == NULL)
    return NULL;

  dest = gfc_get_array_ref ();

  *dest = *src;

  for (i = 0; i < GFC_MAX_DIMENSIONS; i++)
    {
      dest->start[i] = gfc_copy_expr (src->start[i]);
      dest->end[i] = gfc_copy_expr (src->end[i]);
      dest->stride[i] = gfc_copy_expr (src->stride[i]);
    }

  return dest;
}


/* Match a single dimension of an array reference.  This can be a
   single element or an array section.  Any modifications we've made
   to the ar structure are cleaned up by the caller.  If the init
   is set, we require the subscript to be a valid initialization
   expression.  */

static match
64
match_subscript (gfc_array_ref *ar, int init, bool match_star)
65
{
66
  match m = MATCH_ERROR;
67
  bool star = false;
68 69
  int i;

70
  i = ar->dimen + ar->codimen;
71

72
  gfc_gobble_whitespace ();
73
  ar->c_where[i] = gfc_current_locus;
74 75 76 77 78 79 80 81 82 83 84 85
  ar->start[i] = ar->end[i] = ar->stride[i] = NULL;

  /* We can't be sure of the difference between DIMEN_ELEMENT and
     DIMEN_VECTOR until we know the type of the element itself at
     resolution time.  */

  ar->dimen_type[i] = DIMEN_UNKNOWN;

  if (gfc_match_char (':') == MATCH_YES)
    goto end_element;

  /* Get start element.  */
86 87 88 89
  if (match_star && (m = gfc_match_char ('*')) == MATCH_YES)
    star = true;

  if (!star && init)
90
    m = gfc_match_init_expr (&ar->start[i]);
91
  else if (!star)
92 93
    m = gfc_match_expr (&ar->start[i]);

94
  if (m == MATCH_NO)
95 96 97 98 99
    gfc_error ("Expected array subscript at %C");
  if (m != MATCH_YES)
    return MATCH_ERROR;

  if (gfc_match_char (':') == MATCH_NO)
100 101 102 103
    goto matched;

  if (star)
    {
104
      gfc_error ("Unexpected %<*%> in coarray subscript at %C");
105 106
      return MATCH_ERROR;
    }
107 108 109 110 111 112

  /* Get an optional end element.  Because we've seen the colon, we
     definitely have a range along this dimension.  */
end_element:
  ar->dimen_type[i] = DIMEN_RANGE;

113 114 115
  if (match_star && (m = gfc_match_char ('*')) == MATCH_YES)
    star = true;
  else if (init)
116 117 118 119 120 121 122 123 124 125
    m = gfc_match_init_expr (&ar->end[i]);
  else
    m = gfc_match_expr (&ar->end[i]);

  if (m == MATCH_ERROR)
    return MATCH_ERROR;

  /* See if we have an optional stride.  */
  if (gfc_match_char (':') == MATCH_YES)
    {
126 127 128 129 130 131
      if (star)
	{
	  gfc_error ("Strides not allowed in coarray subscript at %C");
	  return MATCH_ERROR;
	}

132
      m = init ? gfc_match_init_expr (&ar->stride[i])
Steven G. Kargl committed
133
	       : gfc_match_expr (&ar->stride[i]);
134 135 136 137 138 139 140

      if (m == MATCH_NO)
	gfc_error ("Expected array subscript stride at %C");
      if (m != MATCH_YES)
	return MATCH_ERROR;
    }

141 142 143 144
matched:
  if (star)
    ar->dimen_type[i] = DIMEN_STAR;

145 146 147 148
  return MATCH_YES;
}


149 150 151
/* Match an array reference, whether it is the whole array or particular
   elements or a section.  If init is set, the reference has to consist
   of init expressions.  */
152 153

match
154 155
gfc_match_array_ref (gfc_array_ref *ar, gfc_array_spec *as, int init,
		     int corank)
156 157
{
  match m;
158
  bool matched_bracket = false;
159 160
  gfc_expr *tmp;
  bool stat_just_seen = false;
161

162
  memset (ar, '\0', sizeof (*ar));
163

164
  ar->where = gfc_current_locus;
165
  ar->as = as;
166 167 168 169 170 171 172
  ar->type = AR_UNKNOWN;

  if (gfc_match_char ('[') == MATCH_YES)
    {
       matched_bracket = true;
       goto coarray;
    }
173 174 175 176 177 178 179 180 181 182

  if (gfc_match_char ('(') != MATCH_YES)
    {
      ar->type = AR_FULL;
      ar->dimen = 0;
      return MATCH_YES;
    }

  for (ar->dimen = 0; ar->dimen < GFC_MAX_DIMENSIONS; ar->dimen++)
    {
183
      m = match_subscript (ar, init, false);
184
      if (m == MATCH_ERROR)
185
	return MATCH_ERROR;
186 187

      if (gfc_match_char (')') == MATCH_YES)
188 189 190 191
	{
	  ar->dimen++;
	  goto coarray;
	}
192 193 194 195

      if (gfc_match_char (',') != MATCH_YES)
	{
	  gfc_error ("Invalid form of array reference at %C");
196
	  return MATCH_ERROR;
197 198 199
	}
    }

200 201
  gfc_error ("Array reference at %C cannot have more than %d dimensions",
	     GFC_MAX_DIMENSIONS);
202 203
  return MATCH_ERROR;

204 205 206 207 208 209 210 211 212
coarray:
  if (!matched_bracket && gfc_match_char ('[') != MATCH_YES)
    {
      if (ar->dimen > 0)
	return MATCH_YES;
      else
	return MATCH_ERROR;
    }

213
  if (flag_coarray == GFC_FCOARRAY_NONE)
214
    {
215
      gfc_fatal_error ("Coarrays disabled at %C, use %<-fcoarray=%> to enable");
216 217 218 219 220 221 222 223 224
      return MATCH_ERROR;
    }

  if (corank == 0)
    {
	gfc_error ("Unexpected coarray designator at %C");
	return MATCH_ERROR;
    }

225 226
  ar->stat = NULL;

227 228
  for (ar->codimen = 0; ar->codimen + ar->dimen < GFC_MAX_DIMENSIONS; ar->codimen++)
    {
229
      m = match_subscript (ar, init, true);
230 231 232
      if (m == MATCH_ERROR)
	return MATCH_ERROR;

233 234 235 236 237 238 239 240 241 242 243 244 245
      stat_just_seen = false;
      if (gfc_match(" , stat = %e",&tmp) == MATCH_YES && ar->stat == NULL)
	{
	  ar->stat = tmp;
	  stat_just_seen = true;
	}

      if (ar->stat && !stat_just_seen)
	{
	  gfc_error ("STAT= attribute in %C misplaced");
	  return MATCH_ERROR;
	}

246 247 248
      if (gfc_match_char (']') == MATCH_YES)
	{
	  ar->codimen++;
249 250 251 252 253 254
	  if (ar->codimen < corank)
	    {
	      gfc_error ("Too few codimensions at %C, expected %d not %d",
			 corank, ar->codimen);
	      return MATCH_ERROR;
	    }
255 256 257 258 259 260
	  if (ar->codimen > corank)
	    {
	      gfc_error ("Too many codimensions at %C, expected %d not %d",
			 corank, ar->codimen);
	      return MATCH_ERROR;
	    }
261 262 263 264 265
	  return MATCH_YES;
	}

      if (gfc_match_char (',') != MATCH_YES)
	{
266
	  if (gfc_match_char ('*') == MATCH_YES)
267
	    gfc_error ("Unexpected %<*%> for codimension %d of %d at %C",
268 269 270 271 272
		       ar->codimen + 1, corank);
	  else
	    gfc_error ("Invalid form of coarray reference at %C");
	  return MATCH_ERROR;
	}
273 274
      else if (ar->dimen_type[ar->codimen + ar->dimen] == DIMEN_STAR)
	{
275
	  gfc_error ("Unexpected %<*%> for codimension %d of %d at %C",
276 277 278 279
		     ar->codimen + 1, corank);
	  return MATCH_ERROR;
	}

280 281 282 283
      if (ar->codimen >= corank)
	{
	  gfc_error ("Invalid codimension %d at %C, only %d codimensions exist",
		     ar->codimen + 1, corank);
284 285 286 287 288 289 290
	  return MATCH_ERROR;
	}
    }

  gfc_error ("Array reference at %C cannot have more than %d dimensions",
	     GFC_MAX_DIMENSIONS);
  return MATCH_ERROR;
291 292 293 294 295 296 297 298 299 300

}


/************** Array specification matching subroutines ***************/

/* Free all of the expressions associated with array bounds
   specifications.  */

void
Steven G. Kargl committed
301
gfc_free_array_spec (gfc_array_spec *as)
302 303 304 305 306 307
{
  int i;

  if (as == NULL)
    return;

308
  for (i = 0; i < as->rank + as->corank; i++)
309 310 311 312 313
    {
      gfc_free_expr (as->lower[i]);
      gfc_free_expr (as->upper[i]);
    }

314
  free (as);
315 316 317 318 319 320
}


/* Take an array bound, resolves the expression, that make up the
   shape and check associated constraints.  */

321
static bool
Steven G. Kargl committed
322
resolve_array_bound (gfc_expr *e, int check_constant)
323 324
{
  if (e == NULL)
325
    return true;
326

327 328 329
  if (!gfc_resolve_expr (e)
      || !gfc_specification_expr (e))
    return false;
330

331
  if (check_constant && !gfc_is_constant_expr (e))
332
    {
333
      if (e->expr_type == EXPR_VARIABLE)
334
	gfc_error ("Variable %qs at %L in this context must be constant",
335 336 337 338
		   e->symtree->n.sym->name, &e->where);
      else
	gfc_error ("Expression at %L in this context must be constant",
		   &e->where);
339
      return false;
340 341
    }

342
  return true;
343 344 345 346 347 348
}


/* Takes an array specification, resolves the expressions that make up
   the shape and make sure everything is integral.  */

349
bool
Steven G. Kargl committed
350
gfc_resolve_array_spec (gfc_array_spec *as, int check_constant)
351 352 353 354 355
{
  gfc_expr *e;
  int i;

  if (as == NULL)
356
    return true;
357

358 359 360
  if (as->resolved)
    return true;

361
  for (i = 0; i < as->rank + as->corank; i++)
362 363
    {
      e = as->lower[i];
364 365
      if (!resolve_array_bound (e, check_constant))
	return false;
366 367

      e = as->upper[i];
368 369
      if (!resolve_array_bound (e, check_constant))
	return false;
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384

      if ((as->lower[i] == NULL) || (as->upper[i] == NULL))
	continue;

      /* If the size is negative in this dimension, set it to zero.  */
      if (as->lower[i]->expr_type == EXPR_CONSTANT
	    && as->upper[i]->expr_type == EXPR_CONSTANT
	    && mpz_cmp (as->upper[i]->value.integer,
			as->lower[i]->value.integer) < 0)
	{
	  gfc_free_expr (as->upper[i]);
	  as->upper[i] = gfc_copy_expr (as->lower[i]);
	  mpz_sub_ui (as->upper[i]->value.integer,
		      as->upper[i]->value.integer, 1);
	}
385 386
    }

387 388
  as->resolved = true;

389
  return true;
390 391 392 393 394 395 396 397 398
}


/* Match a single array element specification.  The return values as
   well as the upper and lower bounds of the array spec are filled
   in according to what we see on the input.  The caller makes sure
   individual specifications make sense as a whole.


Steven G. Kargl committed
399 400
	Parsed       Lower   Upper  Returned
	------------------------------------
401 402 403 404 405 406
	  :           NULL    NULL   AS_DEFERRED (*)
	  x            1       x     AS_EXPLICIT
	  x:           x      NULL   AS_ASSUMED_SHAPE
	  x:y          x       y     AS_EXPLICIT
	  x:*          x      NULL   AS_ASSUMED_SIZE
	  *            1      NULL   AS_ASSUMED_SIZE
407 408 409 410 411 412 413

  (*) For non-pointer dummy arrays this is AS_ASSUMED_SHAPE.  This
  is fixed during the resolution of formal interfaces.

   Anything else AS_UNKNOWN.  */

static array_type
Steven G. Kargl committed
414
match_array_element_spec (gfc_array_spec *as)
415 416 417
{
  gfc_expr **upper, **lower;
  match m;
418
  int rank;
419

420 421 422
  rank = as->rank == -1 ? 0 : as->rank;
  lower = &as->lower[rank + as->corank - 1];
  upper = &as->upper[rank + as->corank - 1];
423 424 425

  if (gfc_match_char ('*') == MATCH_YES)
    {
Jerry DeLisle committed
426
      *lower = gfc_get_int_expr (gfc_default_integer_kind, NULL, 1);
427 428 429 430 431 432 433 434 435 436 437
      return AS_ASSUMED_SIZE;
    }

  if (gfc_match_char (':') == MATCH_YES)
    return AS_DEFERRED;

  m = gfc_match_expr (upper);
  if (m == MATCH_NO)
    gfc_error ("Expected expression in array specification at %C");
  if (m != MATCH_YES)
    return AS_UNKNOWN;
438
  if (!gfc_expr_check_typed (*upper, gfc_current_ns, false))
439
    return AS_UNKNOWN;
440

441 442 443 444 445 446
  if (((*upper)->expr_type == EXPR_CONSTANT
	&& (*upper)->ts.type != BT_INTEGER) ||
      ((*upper)->expr_type == EXPR_FUNCTION
	&& (*upper)->ts.type == BT_UNKNOWN
	&& (*upper)->symtree
	&& strcmp ((*upper)->symtree->name, "null") == 0))
447
    {
448 449
      gfc_error ("Expecting a scalar INTEGER expression at %C, found %s",
		 gfc_basic_typename ((*upper)->ts.type));
450 451 452
      return AS_UNKNOWN;
    }

453 454
  if (gfc_match_char (':') == MATCH_NO)
    {
Jerry DeLisle committed
455
      *lower = gfc_get_int_expr (gfc_default_integer_kind, NULL, 1);
456 457 458 459 460 461 462 463 464 465 466 467 468 469
      return AS_EXPLICIT;
    }

  *lower = *upper;
  *upper = NULL;

  if (gfc_match_char ('*') == MATCH_YES)
    return AS_ASSUMED_SIZE;

  m = gfc_match_expr (upper);
  if (m == MATCH_ERROR)
    return AS_UNKNOWN;
  if (m == MATCH_NO)
    return AS_ASSUMED_SHAPE;
470
  if (!gfc_expr_check_typed (*upper, gfc_current_ns, false))
471
    return AS_UNKNOWN;
472

473 474 475 476 477 478
  if (((*upper)->expr_type == EXPR_CONSTANT
	&& (*upper)->ts.type != BT_INTEGER) ||
      ((*upper)->expr_type == EXPR_FUNCTION
	&& (*upper)->ts.type == BT_UNKNOWN
	&& (*upper)->symtree
	&& strcmp ((*upper)->symtree->name, "null") == 0))
479
    {
480 481
      gfc_error ("Expecting a scalar INTEGER expression at %C, found %s",
		 gfc_basic_typename ((*upper)->ts.type));
482 483 484
      return AS_UNKNOWN;
    }

485 486 487 488 489
  return AS_EXPLICIT;
}


/* Matches an array specification, incidentally figuring out what sort
490 491
   it is.  Match either a normal array specification, or a coarray spec
   or both.  Optionally allow [:] for coarrays.  */
492 493

match
494
gfc_match_array_spec (gfc_array_spec **asp, bool match_dim, bool match_codim)
495 496 497 498 499
{
  array_type current_type;
  gfc_array_spec *as;
  int i;

500
  as = gfc_get_array_spec ();
501

502 503 504 505 506 507 508 509 510
  if (!match_dim)
    goto coarray;

  if (gfc_match_char ('(') != MATCH_YES)
    {
      if (!match_codim)
	goto done;
      goto coarray;
    }
511

512 513 514 515 516
  if (gfc_match (" .. )") == MATCH_YES)
    {
      as->type = AS_ASSUMED_RANK;
      as->rank = -1;

517
      if (!gfc_notify_std (GFC_STD_F2008_TS, "Assumed-rank array at %C"))
518 519 520 521 522 523 524
	goto cleanup;

      if (!match_codim)
	goto done;
      goto coarray;
    }

525 526
  for (;;)
    {
527
      as->rank++;
528 529
      current_type = match_array_element_spec (as);

530 531 532 533 534 535
      /* Note that current_type == AS_ASSUMED_SIZE for both assumed-size
	 and implied-shape specifications.  If the rank is at least 2, we can
	 distinguish between them.  But for rank 1, we currently return
	 ASSUMED_SIZE; this gets adjusted later when we know for sure
	 whether the symbol parsed is a PARAMETER or not.  */

536 537 538 539 540 541 542 543
      if (as->rank == 1)
	{
	  if (current_type == AS_UNKNOWN)
	    goto cleanup;
	  as->type = current_type;
	}
      else
	switch (as->type)
Steven G. Kargl committed
544
	  {		/* See how current spec meshes with the existing.  */
545 546 547
	  case AS_UNKNOWN:
	    goto cleanup;

548 549 550 551 552 553 554 555 556
	  case AS_IMPLIED_SHAPE:
	    if (current_type != AS_ASSUMED_SHAPE)
	      {
		gfc_error ("Bad array specification for implied-shape"
			   " array at %C");
		goto cleanup;
	      }
	    break;

557 558 559 560 561 562 563 564 565 566
	  case AS_EXPLICIT:
	    if (current_type == AS_ASSUMED_SIZE)
	      {
		as->type = AS_ASSUMED_SIZE;
		break;
	      }

	    if (current_type == AS_EXPLICIT)
	      break;

Steven G. Kargl committed
567 568
	    gfc_error ("Bad array specification for an explicitly shaped "
		       "array at %C");
569 570 571 572 573 574 575 576

	    goto cleanup;

	  case AS_ASSUMED_SHAPE:
	    if ((current_type == AS_ASSUMED_SHAPE)
		|| (current_type == AS_DEFERRED))
	      break;

Steven G. Kargl committed
577 578
	    gfc_error ("Bad array specification for assumed shape "
		       "array at %C");
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
	    goto cleanup;

	  case AS_DEFERRED:
	    if (current_type == AS_DEFERRED)
	      break;

	    if (current_type == AS_ASSUMED_SHAPE)
	      {
		as->type = AS_ASSUMED_SHAPE;
		break;
	      }

	    gfc_error ("Bad specification for deferred shape array at %C");
	    goto cleanup;

	  case AS_ASSUMED_SIZE:
595 596 597 598 599 600
	    if (as->rank == 2 && current_type == AS_ASSUMED_SIZE)
	      {
		as->type = AS_IMPLIED_SHAPE;
		break;
	      }

601 602
	    gfc_error ("Bad specification for assumed size array at %C");
	    goto cleanup;
603 604

	  case AS_ASSUMED_RANK:
605
	    gcc_unreachable ();
606 607 608 609 610 611 612 613 614 615 616
	  }

      if (gfc_match_char (')') == MATCH_YES)
	break;

      if (gfc_match_char (',') != MATCH_YES)
	{
	  gfc_error ("Expected another dimension in array declaration at %C");
	  goto cleanup;
	}

617
      if (as->rank + as->corank >= GFC_MAX_DIMENSIONS)
618
	{
619 620
	  gfc_error ("Array specification at %C has more than %d dimensions",
		     GFC_MAX_DIMENSIONS);
621 622 623
	  goto cleanup;
	}

624
      if (as->corank + as->rank >= 7
625 626
	  && !gfc_notify_std (GFC_STD_F2008, "Array specification at %C "
			      "with more than 7 dimensions"))
627
	goto cleanup;
628
    }
629

630 631 632 633 634 635 636
  if (!match_codim)
    goto done;

coarray:
  if (gfc_match_char ('[')  != MATCH_YES)
    goto done;

637
  if (!gfc_notify_std (GFC_STD_F2008, "Coarray declaration at %C"))
638 639
    goto cleanup;

640
  if (flag_coarray == GFC_FCOARRAY_NONE)
641
    {
642
      gfc_fatal_error ("Coarrays disabled at %C, use %<-fcoarray=%> to enable");
643
      goto cleanup;
644 645
    }

646 647 648 649 650 651 652
  if (as->rank >= GFC_MAX_DIMENSIONS)
    {
      gfc_error ("Array specification at %C has more than %d "
		 "dimensions", GFC_MAX_DIMENSIONS);
      goto cleanup;
    }

653 654 655 656 657 658 659 660 661
  for (;;)
    {
      as->corank++;
      current_type = match_array_element_spec (as);

      if (current_type == AS_UNKNOWN)
	goto cleanup;

      if (as->corank == 1)
662
	as->cotype = current_type;
663
      else
664
	switch (as->cotype)
665
	  { /* See how current spec meshes with the existing.  */
666
	    case AS_IMPLIED_SHAPE:
667 668 669 670 671 672
	    case AS_UNKNOWN:
	      goto cleanup;

	    case AS_EXPLICIT:
	      if (current_type == AS_ASSUMED_SIZE)
		{
673
		  as->cotype = AS_ASSUMED_SIZE;
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
		  break;
		}

	      if (current_type == AS_EXPLICIT)
		break;

	      gfc_error ("Bad array specification for an explicitly "
			 "shaped array at %C");

	      goto cleanup;

	    case AS_ASSUMED_SHAPE:
	      if ((current_type == AS_ASSUMED_SHAPE)
		  || (current_type == AS_DEFERRED))
		break;

	      gfc_error ("Bad array specification for assumed shape "
			 "array at %C");
	      goto cleanup;

	    case AS_DEFERRED:
	      if (current_type == AS_DEFERRED)
		break;

	      if (current_type == AS_ASSUMED_SHAPE)
		{
700
		  as->cotype = AS_ASSUMED_SHAPE;
701 702 703 704 705 706 707 708 709
		  break;
		}

	      gfc_error ("Bad specification for deferred shape array at %C");
	      goto cleanup;

	    case AS_ASSUMED_SIZE:
	      gfc_error ("Bad specification for assumed size array at %C");
	      goto cleanup;
710 711

	    case AS_ASSUMED_RANK:
712
	      gcc_unreachable ();
713 714 715 716 717 718 719 720 721 722 723
	  }

      if (gfc_match_char (']') == MATCH_YES)
	break;

      if (gfc_match_char (',') != MATCH_YES)
	{
	  gfc_error ("Expected another dimension in array declaration at %C");
	  goto cleanup;
	}

724
      if (as->rank + as->corank >= GFC_MAX_DIMENSIONS)
725 726 727 728 729 730 731 732 733
	{
	  gfc_error ("Array specification at %C has more than %d "
		     "dimensions", GFC_MAX_DIMENSIONS);
	  goto cleanup;
	}
    }

  if (current_type == AS_EXPLICIT)
    {
734
      gfc_error ("Upper bound of last coarray dimension must be %<*%> at %C");
735 736 737
      goto cleanup;
    }

738 739 740 741 742
  if (as->cotype == AS_ASSUMED_SIZE)
    as->cotype = AS_EXPLICIT;

  if (as->rank == 0)
    as->type = as->cotype;
743 744 745 746 747 748 749

done:
  if (as->rank == 0 && as->corank == 0)
    {
      *asp = NULL;
      gfc_free_array_spec (as);
      return MATCH_NO;
750 751 752 753 754
    }

  /* If a lower bounds of an assumed shape array is blank, put in one.  */
  if (as->type == AS_ASSUMED_SHAPE)
    {
755
      for (i = 0; i < as->rank + as->corank; i++)
756 757
	{
	  if (as->lower[i] == NULL)
Jerry DeLisle committed
758
	    as->lower[i] = gfc_get_int_expr (gfc_default_integer_kind, NULL, 1);
759 760
	}
    }
761

762
  *asp = as;
763

764 765 766 767 768 769 770 771 772 773 774 775 776
  return MATCH_YES;

cleanup:
  /* Something went wrong.  */
  gfc_free_array_spec (as);
  return MATCH_ERROR;
}


/* Given a symbol and an array specification, modify the symbol to
   have that array specification.  The error locus is needed in case
   something goes wrong.  On failure, the caller must free the spec.  */

777
bool
Steven G. Kargl committed
778
gfc_set_array_spec (gfc_symbol *sym, gfc_array_spec *as, locus *error_loc)
779
{
780 781
  int i;

782
  if (as == NULL)
783
    return true;
784

785
  if (as->rank
786 787
      && !gfc_add_dimension (&sym->attr, sym->name, error_loc))
    return false;
788 789

  if (as->corank
790 791
      && !gfc_add_codimension (&sym->attr, sym->name, error_loc))
    return false;
792

793 794 795
  if (sym->as == NULL)
    {
      sym->as = as;
796
      return true;
797
    }
798

799 800 801
  if ((sym->as->type == AS_ASSUMED_RANK && as->corank)
      || (as->type == AS_ASSUMED_RANK && sym->as->corank))
    {
802
      gfc_error ("The assumed-rank array %qs at %L shall not have a "
803
		 "codimension", sym->name, error_loc);
804
      return false;
805 806
    }

807 808 809 810 811 812
  if (as->corank)
    {
      /* The "sym" has no corank (checked via gfc_add_codimension). Thus
	 the codimension is simply added.  */
      gcc_assert (as->rank == 0 && sym->as->corank == 0);

813
      sym->as->cotype = as->cotype;
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
      sym->as->corank = as->corank;
      for (i = 0; i < as->corank; i++)
	{
	  sym->as->lower[sym->as->rank + i] = as->lower[i];
	  sym->as->upper[sym->as->rank + i] = as->upper[i];
	}
    }
  else
    {
      /* The "sym" has no rank (checked via gfc_add_dimension). Thus
	 the dimension is added - but first the codimensions (if existing
	 need to be shifted to make space for the dimension.  */
      gcc_assert (as->corank == 0 && sym->as->rank == 0);

      sym->as->rank = as->rank;
      sym->as->type = as->type;
      sym->as->cray_pointee = as->cray_pointee;
      sym->as->cp_was_assumed = as->cp_was_assumed;

      for (i = 0; i < sym->as->corank; i++)
	{
	  sym->as->lower[as->rank + i] = sym->as->lower[i];
	  sym->as->upper[as->rank + i] = sym->as->upper[i];
	}
      for (i = 0; i < as->rank; i++)
	{
	  sym->as->lower[i] = as->lower[i];
	  sym->as->upper[i] = as->upper[i];
	}
    }

845
  free (as);
846
  return true;
847 848 849 850 851 852
}


/* Copy an array specification.  */

gfc_array_spec *
Steven G. Kargl committed
853
gfc_copy_array_spec (gfc_array_spec *src)
854 855 856 857 858 859 860 861 862 863 864
{
  gfc_array_spec *dest;
  int i;

  if (src == NULL)
    return NULL;

  dest = gfc_get_array_spec ();

  *dest = *src;

865
  for (i = 0; i < dest->rank + dest->corank; i++)
866 867 868 869 870 871 872 873
    {
      dest->lower[i] = gfc_copy_expr (dest->lower[i]);
      dest->upper[i] = gfc_copy_expr (dest->upper[i]);
    }

  return dest;
}

Steven G. Kargl committed
874

875 876 877 878
/* Returns nonzero if the two expressions are equal.  Only handles integer
   constants.  */

static int
Steven G. Kargl committed
879
compare_bounds (gfc_expr *bound1, gfc_expr *bound2)
880 881 882 883 884 885 886 887 888 889 890 891 892 893
{
  if (bound1 == NULL || bound2 == NULL
      || bound1->expr_type != EXPR_CONSTANT
      || bound2->expr_type != EXPR_CONSTANT
      || bound1->ts.type != BT_INTEGER
      || bound2->ts.type != BT_INTEGER)
    gfc_internal_error ("gfc_compare_array_spec(): Array spec clobbered");

  if (mpz_cmp (bound1->value.integer, bound2->value.integer) == 0)
    return 1;
  else
    return 0;
}

Steven G. Kargl committed
894

895 896 897 898
/* Compares two array specifications.  They must be constant or deferred
   shape.  */

int
Steven G. Kargl committed
899
gfc_compare_array_spec (gfc_array_spec *as1, gfc_array_spec *as2)
900 901 902 903 904 905 906 907 908 909 910 911
{
  int i;

  if (as1 == NULL && as2 == NULL)
    return 1;

  if (as1 == NULL || as2 == NULL)
    return 0;

  if (as1->rank != as2->rank)
    return 0;

912 913 914
  if (as1->corank != as2->corank)
    return 0;

915 916 917 918 919 920 921
  if (as1->rank == 0)
    return 1;

  if (as1->type != as2->type)
    return 0;

  if (as1->type == AS_EXPLICIT)
922
    for (i = 0; i < as1->rank + as1->corank; i++)
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
      {
	if (compare_bounds (as1->lower[i], as2->lower[i]) == 0)
	  return 0;

	if (compare_bounds (as1->upper[i], as2->upper[i]) == 0)
	  return 0;
      }

  return 1;
}


/****************** Array constructor functions ******************/


/* Given an expression node that might be an array constructor and a
   symbol, make sure that no iterators in this or child constructors
   use the symbol as an implied-DO iterator.  Returns nonzero if a
   duplicate was found.  */

static int
Jerry DeLisle committed
944
check_duplicate_iterator (gfc_constructor_base base, gfc_symbol *master)
945
{
Jerry DeLisle committed
946
  gfc_constructor *c;
947 948
  gfc_expr *e;

Jerry DeLisle committed
949
  for (c = gfc_constructor_first (base); c; c = gfc_constructor_next (c))
950 951 952 953 954 955 956 957 958 959 960 961
    {
      e = c->expr;

      if (e->expr_type == EXPR_ARRAY
	  && check_duplicate_iterator (e->value.constructor, master))
	return 1;

      if (c->iterator == NULL)
	continue;

      if (c->iterator->var->symtree->n.sym == master)
	{
962
	  gfc_error ("DO-iterator %qs at %L is inside iterator of the "
Steven G. Kargl committed
963
		     "same name", master->name, &c->where);
964 965 966 967 968 969 970 971 972 973

	  return 1;
	}
    }

  return 0;
}


/* Forward declaration because these functions are mutually recursive.  */
Jerry DeLisle committed
974
static match match_array_cons_element (gfc_constructor_base *);
975 976 977 978

/* Match a list of array elements.  */

static match
Jerry DeLisle committed
979
match_array_list (gfc_constructor_base *result)
980
{
Jerry DeLisle committed
981 982
  gfc_constructor_base head;
  gfc_constructor *p;
983 984 985 986 987 988
  gfc_iterator iter;
  locus old_loc;
  gfc_expr *e;
  match m;
  int n;

989
  old_loc = gfc_current_locus;
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008

  if (gfc_match_char ('(') == MATCH_NO)
    return MATCH_NO;

  memset (&iter, '\0', sizeof (gfc_iterator));
  head = NULL;

  m = match_array_cons_element (&head);
  if (m != MATCH_YES)
    goto cleanup;

  if (gfc_match_char (',') != MATCH_YES)
    {
      m = MATCH_NO;
      goto cleanup;
    }

  for (n = 1;; n++)
    {
1009
      m = gfc_match_iterator (&iter, 0);
1010 1011 1012 1013 1014
      if (m == MATCH_YES)
	break;
      if (m == MATCH_ERROR)
	goto cleanup;

Jerry DeLisle committed
1015
      m = match_array_cons_element (&head);
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
      if (m == MATCH_ERROR)
	goto cleanup;
      if (m == MATCH_NO)
	{
	  if (n > 2)
	    goto syntax;
	  m = MATCH_NO;
	  goto cleanup;		/* Could be a complex constant */
	}

      if (gfc_match_char (',') != MATCH_YES)
	{
	  if (n > 2)
	    goto syntax;
	  m = MATCH_NO;
	  goto cleanup;
	}
    }

  if (gfc_match_char (')') != MATCH_YES)
    goto syntax;

  if (check_duplicate_iterator (head, iter.var->symtree->n.sym))
    {
      m = MATCH_ERROR;
      goto cleanup;
    }

Jerry DeLisle committed
1044
  e = gfc_get_array_expr (BT_UNKNOWN, 0, &old_loc);
1045 1046
  e->value.constructor = head;

Jerry DeLisle committed
1047
  p = gfc_constructor_append_expr (result, e, &gfc_current_locus);
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
  p->iterator = gfc_get_iterator ();
  *p->iterator = iter;

  return MATCH_YES;

syntax:
  gfc_error ("Syntax error in array constructor at %C");
  m = MATCH_ERROR;

cleanup:
Jerry DeLisle committed
1058
  gfc_constructor_free (head);
1059
  gfc_free_iterator (&iter, 0);
1060
  gfc_current_locus = old_loc;
1061 1062 1063 1064 1065 1066 1067 1068
  return m;
}


/* Match a single element of an array constructor, which can be a
   single expression or a list of elements.  */

static match
Jerry DeLisle committed
1069
match_array_cons_element (gfc_constructor_base *result)
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
{
  gfc_expr *expr;
  match m;

  m = match_array_list (result);
  if (m != MATCH_NO)
    return m;

  m = gfc_match_expr (&expr);
  if (m != MATCH_YES)
    return m;

Jerry DeLisle committed
1082
  gfc_constructor_append_expr (result, expr, &gfc_current_locus);
1083 1084 1085 1086 1087 1088 1089
  return MATCH_YES;
}


/* Match an array constructor.  */

match
Steven G. Kargl committed
1090
gfc_match_array_constructor (gfc_expr **result)
1091
{
1092
  gfc_constructor *c;
1093
  gfc_constructor_base head;
1094
  gfc_expr *expr;
1095
  gfc_typespec ts;
1096 1097
  locus where;
  match m;
1098
  const char *end_delim;
1099
  bool seen_ts;
1100

1101 1102 1103
  head = NULL;
  seen_ts = false;

1104
  if (gfc_match (" (/") == MATCH_NO)
1105 1106
    {
      if (gfc_match (" [") == MATCH_NO)
Steven G. Kargl committed
1107
	return MATCH_NO;
1108
      else
Steven G. Kargl committed
1109
	{
1110 1111
	  if (!gfc_notify_std (GFC_STD_F2003, "[...] "
			       "style array constructors at %C"))
Steven G. Kargl committed
1112 1113 1114
	    return MATCH_ERROR;
	  end_delim = " ]";
	}
1115 1116 1117
    }
  else
    end_delim = " /)";
1118

1119
  where = gfc_current_locus;
1120 1121

  /* Try to match an optional "type-spec ::"  */
1122
  gfc_clear_ts (&ts);
1123 1124
  m = gfc_match_type_spec (&ts);
  if (m == MATCH_YES)
1125 1126 1127 1128 1129
    {
      seen_ts = (gfc_match (" ::") == MATCH_YES);

      if (seen_ts)
	{
1130 1131
	  if (!gfc_notify_std (GFC_STD_F2003, "Array constructor "
			       "including type specification at %C"))
1132
	    goto cleanup;
Steven G. Kargl committed
1133 1134 1135 1136 1137 1138 1139

	  if (ts.deferred)
	    {
	      gfc_error ("Type-spec at %L cannot contain a deferred "
			 "type parameter", &where);
	      goto cleanup;
	    }
1140 1141 1142 1143 1144 1145 1146 1147

	  if (ts.type == BT_CHARACTER
	      && ts.u.cl && !ts.u.cl->length && !ts.u.cl->length_from_typespec)
	    {
	      gfc_error ("Type-spec at %L cannot contain an asterisk for a "
			 "type parameter", &where);
	      goto cleanup;
	    }
1148 1149
	}
    }
1150
  else if (m == MATCH_ERROR)
1151
    goto cleanup;
1152

1153 1154
  if (!seen_ts)
    gfc_current_locus = where;
1155

1156
  if (gfc_match (end_delim) == MATCH_YES)
1157
    {
1158 1159 1160 1161 1162 1163 1164
      if (seen_ts)
	goto done;
      else
	{
	  gfc_error ("Empty array constructor at %C is not allowed");
	  goto cleanup;
	}
1165
    }
1166 1167 1168

  for (;;)
    {
Jerry DeLisle committed
1169
      m = match_array_cons_element (&head);
1170 1171 1172 1173 1174 1175 1176 1177 1178
      if (m == MATCH_ERROR)
	goto cleanup;
      if (m == MATCH_NO)
	goto syntax;

      if (gfc_match_char (',') == MATCH_NO)
	break;
    }

1179
  if (gfc_match (end_delim) == MATCH_NO)
1180 1181
    goto syntax;

1182
done:
1183
  /* Size must be calculated at resolution time.  */
1184
  if (seen_ts)
Jerry DeLisle committed
1185 1186 1187
    {
      expr = gfc_get_array_expr (ts.type, ts.kind, &where);
      expr->ts = ts;
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214

      /* If the typespec is CHARACTER, check that array elements can
	 be converted.  See PR fortran/67803.  */
      if (ts.type == BT_CHARACTER)
	{
	  c = gfc_constructor_first (head);
	  for (; c; c = gfc_constructor_next (c))
	    {
	      if (gfc_numeric_ts (&c->expr->ts)
		  || c->expr->ts.type == BT_LOGICAL)
		{
		  gfc_error ("Incompatible typespec for array element at %L",
			     &c->expr->where);
		  return MATCH_ERROR;
		}

	      /* Special case null().  */
	      if (c->expr->expr_type == EXPR_FUNCTION
		  && c->expr->ts.type == BT_UNKNOWN
		  && strcmp (c->expr->symtree->name, "null") == 0)
		{
		  gfc_error ("Incompatible typespec for array element at %L",
			     &c->expr->where);
		  return MATCH_ERROR;
		}
	    }
	}
1215 1216 1217 1218 1219 1220 1221 1222

      /* Walk the constructor and ensure type conversion for numeric types.  */
      if (gfc_numeric_ts (&ts))
	{
	  c = gfc_constructor_first (head);
	  for (; c; c = gfc_constructor_next (c))
	    gfc_convert_type (c->expr, &ts, 1);
	}
Jerry DeLisle committed
1223
    }
1224
  else
Jerry DeLisle committed
1225 1226 1227
    expr = gfc_get_array_expr (BT_UNKNOWN, 0, &where);

  expr->value.constructor = head;
1228 1229
  if (expr->ts.u.cl)
    expr->ts.u.cl->length_from_typespec = seen_ts;
1230

1231
  *result = expr;
1232

1233 1234 1235 1236 1237 1238
  return MATCH_YES;

syntax:
  gfc_error ("Syntax error in array constructor at %C");

cleanup:
Jerry DeLisle committed
1239
  gfc_constructor_free (head);
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
  return MATCH_ERROR;
}



/************** Check array constructors for correctness **************/

/* Given an expression, compare it's type with the type of the current
   constructor.  Returns nonzero if an error was issued.  The
   cons_state variable keeps track of whether the type of the
   constructor being read or resolved is known to be good, bad or just
   starting out.  */

static gfc_typespec constructor_ts;
static enum
{ CONS_START, CONS_GOOD, CONS_BAD }
cons_state;

static int
1259
check_element_type (gfc_expr *expr, bool convert)
1260 1261
{
  if (cons_state == CONS_BAD)
1262
    return 0;			/* Suppress further errors */
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279

  if (cons_state == CONS_START)
    {
      if (expr->ts.type == BT_UNKNOWN)
	cons_state = CONS_BAD;
      else
	{
	  cons_state = CONS_GOOD;
	  constructor_ts = expr->ts;
	}

      return 0;
    }

  if (gfc_compare_types (&constructor_ts, &expr->ts))
    return 0;

1280
  if (convert)
1281
    return gfc_convert_type(expr, &constructor_ts, 1) ? 0 : 1;
1282

1283 1284 1285 1286 1287 1288 1289 1290 1291
  gfc_error ("Element in %s array constructor at %L is %s",
	     gfc_typename (&constructor_ts), &expr->where,
	     gfc_typename (&expr->ts));

  cons_state = CONS_BAD;
  return 1;
}


1292
/* Recursive work function for gfc_check_constructor_type().  */
1293

1294
static bool
Jerry DeLisle committed
1295
check_constructor_type (gfc_constructor_base base, bool convert)
1296
{
Jerry DeLisle committed
1297
  gfc_constructor *c;
1298 1299
  gfc_expr *e;

Jerry DeLisle committed
1300
  for (c = gfc_constructor_first (base); c; c = gfc_constructor_next (c))
1301 1302 1303 1304 1305
    {
      e = c->expr;

      if (e->expr_type == EXPR_ARRAY)
	{
1306 1307
	  if (!check_constructor_type (e->value.constructor, convert))
	    return false;
1308 1309 1310 1311

	  continue;
	}

1312
      if (check_element_type (e, convert))
1313
	return false;
1314 1315
    }

1316
  return true;
1317 1318 1319 1320
}


/* Check that all elements of an array constructor are the same type.
1321
   On false, an error has been generated.  */
1322

1323
bool
Steven G. Kargl committed
1324
gfc_check_constructor_type (gfc_expr *e)
1325
{
1326
  bool t;
1327

1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
  if (e->ts.type != BT_UNKNOWN)
    {
      cons_state = CONS_GOOD;
      constructor_ts = e->ts;
    }
  else
    {
      cons_state = CONS_START;
      gfc_clear_ts (&constructor_ts);
    }
1338

1339 1340 1341
  /* If e->ts.type != BT_UNKNOWN, the array constructor included a
     typespec, and we will now convert the values on the fly.  */
  t = check_constructor_type (e->value.constructor, e->ts.type != BT_UNKNOWN);
1342
  if (t && e->ts.type == BT_UNKNOWN)
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
    e->ts = constructor_ts;

  return t;
}



typedef struct cons_stack
{
  gfc_iterator *iterator;
  struct cons_stack *previous;
}
cons_stack;

static cons_stack *base;

1359
static bool check_constructor (gfc_constructor_base, bool (*) (gfc_expr *));
1360 1361 1362 1363

/* Check an EXPR_VARIABLE expression in a constructor to make sure
   that that variable is an iteration variables.  */

1364
bool
Steven G. Kargl committed
1365
gfc_check_iter_variable (gfc_expr *expr)
1366 1367 1368 1369 1370 1371
{
  gfc_symbol *sym;
  cons_stack *c;

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

1372
  for (c = base; c && c->iterator; c = c->previous)
1373
    if (sym == c->iterator->var->symtree->n.sym)
1374
      return true;
1375

1376
  return false;
1377 1378 1379 1380 1381 1382 1383
}


/* Recursive work function for gfc_check_constructor().  This amounts
   to calling the check function for each expression in the
   constructor, giving variables with the names of iterators a pass.  */

1384 1385
static bool
check_constructor (gfc_constructor_base ctor, bool (*check_function) (gfc_expr *))
1386 1387 1388
{
  cons_stack element;
  gfc_expr *e;
1389
  bool t;
Jerry DeLisle committed
1390
  gfc_constructor *c;
1391

Jerry DeLisle committed
1392
  for (c = gfc_constructor_first (ctor); c; c = gfc_constructor_next (c))
1393 1394 1395
    {
      e = c->expr;

1396 1397 1398
      if (!e)
	continue;

1399 1400
      if (e->expr_type != EXPR_ARRAY)
	{
1401 1402
	  if (!(*check_function)(e))
	    return false;
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
	  continue;
	}

      element.previous = base;
      element.iterator = c->iterator;

      base = &element;
      t = check_constructor (e->value.constructor, check_function);
      base = element.previous;

1413 1414
      if (!t)
	return false;
1415 1416 1417
    }

  /* Nothing went wrong, so all OK.  */
1418
  return true;
1419 1420 1421 1422 1423 1424 1425
}


/* Checks a constructor to see if it is a particular kind of
   expression -- specification, restricted, or initialization as
   determined by the check_function.  */

1426 1427
bool
gfc_check_constructor (gfc_expr *expr, bool (*check_function) (gfc_expr *))
1428 1429
{
  cons_stack *base_save;
1430
  bool t;
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448

  base_save = base;
  base = NULL;

  t = check_constructor (expr->value.constructor, check_function);
  base = base_save;

  return t;
}



/**************** Simplification of array constructors ****************/

iterator_stack *iter_stack;

typedef struct
{
Jerry DeLisle committed
1449
  gfc_constructor_base base;
1450 1451 1452 1453 1454 1455
  int extract_count, extract_n;
  gfc_expr *extracted;
  mpz_t *count;

  mpz_t *offset;
  gfc_component *component;
1456
  mpz_t *repeat;
1457

1458
  bool (*expand_work_function) (gfc_expr *);
1459 1460 1461 1462 1463
}
expand_info;

static expand_info current_expand;

1464
static bool expand_constructor (gfc_constructor_base);
1465 1466 1467 1468 1469


/* Work function that counts the number of elements present in a
   constructor.  */

1470
static bool
Steven G. Kargl committed
1471
count_elements (gfc_expr *e)
1472 1473 1474 1475 1476 1477 1478
{
  mpz_t result;

  if (e->rank == 0)
    mpz_add_ui (*current_expand.count, *current_expand.count, 1);
  else
    {
1479
      if (!gfc_array_size (e, &result))
1480 1481
	{
	  gfc_free_expr (e);
1482
	  return false;
1483 1484 1485 1486 1487 1488 1489
	}

      mpz_add (*current_expand.count, *current_expand.count, result);
      mpz_clear (result);
    }

  gfc_free_expr (e);
1490
  return true;
1491 1492 1493 1494 1495 1496
}


/* Work function that extracts a particular element from an array
   constructor, freeing the rest.  */

1497
static bool
Steven G. Kargl committed
1498
extract_element (gfc_expr *e)
1499 1500 1501 1502
{
  if (e->rank != 0)
    {				/* Something unextractable */
      gfc_free_expr (e);
1503
      return false;
1504 1505 1506 1507 1508 1509 1510 1511
    }

  if (current_expand.extract_count == current_expand.extract_n)
    current_expand.extracted = e;
  else
    gfc_free_expr (e);

  current_expand.extract_count++;
1512

1513
  return true;
1514 1515 1516 1517 1518 1519
}


/* Work function that constructs a new constructor out of the old one,
   stringing new elements together.  */

1520
static bool
Steven G. Kargl committed
1521
expand (gfc_expr *e)
1522
{
Jerry DeLisle committed
1523 1524
  gfc_constructor *c = gfc_constructor_append_expr (&current_expand.base,
						    e, &e->where);
1525

Jerry DeLisle committed
1526
  c->n.component = current_expand.component;
1527
  return true;
1528 1529 1530 1531 1532 1533 1534
}


/* Given an initialization expression that is a variable reference,
   substitute the current value of the iteration variable.  */

void
Steven G. Kargl committed
1535
gfc_simplify_iterator_var (gfc_expr *e)
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
{
  iterator_stack *p;

  for (p = iter_stack; p; p = p->prev)
    if (e->symtree == p->variable)
      break;

  if (p == NULL)
    return;		/* Variable not found */

Jerry DeLisle committed
1546
  gfc_replace_expr (e, gfc_get_int_expr (gfc_default_integer_kind, NULL, 0));
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556

  mpz_set (e->value.integer, p->value);

  return;
}


/* Expand an expression with that is inside of a constructor,
   recursing into other constructors if present.  */

1557
static bool
Steven G. Kargl committed
1558
expand_expr (gfc_expr *e)
1559 1560 1561 1562 1563 1564
{
  if (e->expr_type == EXPR_ARRAY)
    return expand_constructor (e->value.constructor);

  e = gfc_copy_expr (e);

1565
  if (!gfc_simplify_expr (e, 1))
1566 1567
    {
      gfc_free_expr (e);
1568
      return false;
1569 1570 1571 1572 1573 1574
    }

  return current_expand.expand_work_function (e);
}


1575
static bool
Steven G. Kargl committed
1576
expand_iterator (gfc_constructor *c)
1577 1578 1579 1580
{
  gfc_expr *start, *end, *step;
  iterator_stack frame;
  mpz_t trip;
1581
  bool t;
1582 1583 1584

  end = step = NULL;

1585
  t = false;
1586 1587 1588

  mpz_init (trip);
  mpz_init (frame.value);
1589
  frame.prev = NULL;
1590 1591

  start = gfc_copy_expr (c->iterator->start);
1592
  if (!gfc_simplify_expr (start, 1))
1593 1594 1595 1596 1597 1598
    goto cleanup;

  if (start->expr_type != EXPR_CONSTANT || start->ts.type != BT_INTEGER)
    goto cleanup;

  end = gfc_copy_expr (c->iterator->end);
1599
  if (!gfc_simplify_expr (end, 1))
1600 1601 1602 1603 1604 1605
    goto cleanup;

  if (end->expr_type != EXPR_CONSTANT || end->ts.type != BT_INTEGER)
    goto cleanup;

  step = gfc_copy_expr (c->iterator->step);
1606
  if (!gfc_simplify_expr (step, 1))
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
    goto cleanup;

  if (step->expr_type != EXPR_CONSTANT || step->ts.type != BT_INTEGER)
    goto cleanup;

  if (mpz_sgn (step->value.integer) == 0)
    {
      gfc_error ("Iterator step at %L cannot be zero", &step->where);
      goto cleanup;
    }

  /* Calculate the trip count of the loop.  */
  mpz_sub (trip, end->value.integer, start->value.integer);
  mpz_add (trip, trip, step->value.integer);
  mpz_tdiv_q (trip, trip, step->value.integer);

  mpz_set (frame.value, start->value.integer);

  frame.prev = iter_stack;
  frame.variable = c->iterator->var->symtree;
  iter_stack = &frame;

  while (mpz_sgn (trip) > 0)
    {
1631
      if (!expand_expr (c->expr))
1632 1633 1634 1635 1636 1637
	goto cleanup;

      mpz_add (frame.value, frame.value, step->value.integer);
      mpz_sub_ui (trip, trip, 1);
    }

1638
  t = true;
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658

cleanup:
  gfc_free_expr (start);
  gfc_free_expr (end);
  gfc_free_expr (step);

  mpz_clear (trip);
  mpz_clear (frame.value);

  iter_stack = frame.prev;

  return t;
}


/* Expand a constructor into constant constructors without any
   iterators, calling the work function for each of the expanded
   expressions.  The work function needs to either save or free the
   passed expression.  */

1659
static bool
Jerry DeLisle committed
1660
expand_constructor (gfc_constructor_base base)
1661
{
Jerry DeLisle committed
1662
  gfc_constructor *c;
1663 1664
  gfc_expr *e;

Jerry DeLisle committed
1665
  for (c = gfc_constructor_first (base); c; c = gfc_constructor_next(c))
1666 1667 1668
    {
      if (c->iterator != NULL)
	{
1669 1670
	  if (!expand_iterator (c))
	    return false;
1671 1672 1673 1674 1675 1676 1677
	  continue;
	}

      e = c->expr;

      if (e->expr_type == EXPR_ARRAY)
	{
1678 1679
	  if (!expand_constructor (e->value.constructor))
	    return false;
1680 1681 1682 1683 1684

	  continue;
	}

      e = gfc_copy_expr (e);
1685
      if (!gfc_simplify_expr (e, 1))
1686 1687
	{
	  gfc_free_expr (e);
1688
	  return false;
1689
	}
Jerry DeLisle committed
1690
      current_expand.offset = &c->offset;
1691
      current_expand.repeat = &c->repeat;
Jerry DeLisle committed
1692
      current_expand.component = c->n.component;
1693 1694
      if (!current_expand.expand_work_function(e))
	return false;
1695
    }
1696
  return true;
1697 1698 1699
}


Jerry DeLisle committed
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
/* Given an array expression and an element number (starting at zero),
   return a pointer to the array element.  NULL is returned if the
   size of the array has been exceeded.  The expression node returned
   remains a part of the array and should not be freed.  Access is not
   efficient at all, but this is another place where things do not
   have to be particularly fast.  */

static gfc_expr *
gfc_get_array_element (gfc_expr *array, int element)
{
  expand_info expand_save;
  gfc_expr *e;
1712
  bool rc;
Jerry DeLisle committed
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725

  expand_save = current_expand;
  current_expand.extract_n = element;
  current_expand.expand_work_function = extract_element;
  current_expand.extracted = NULL;
  current_expand.extract_count = 0;

  iter_stack = NULL;

  rc = expand_constructor (array->value.constructor);
  e = current_expand.extracted;
  current_expand = expand_save;

1726
  if (!rc)
Jerry DeLisle committed
1727 1728 1729 1730 1731 1732
    return NULL;

  return e;
}


1733 1734 1735
/* Top level subroutine for expanding constructors.  We only expand
   constructor if they are small enough.  */

1736
bool
1737
gfc_expand_constructor (gfc_expr *e, bool fatal)
1738 1739 1740
{
  expand_info expand_save;
  gfc_expr *f;
1741
  bool rc;
1742

Jerry DeLisle committed
1743 1744
  /* If we can successfully get an array element at the max array size then
     the array is too big to expand, so we just return.  */
1745
  f = gfc_get_array_element (e, flag_max_array_constructor);
1746 1747 1748
  if (f != NULL)
    {
      gfc_free_expr (f);
1749 1750 1751 1752
      if (fatal)
	{
	  gfc_error ("The number of elements in the array constructor "
		     "at %L requires an increase of the allowed %d "
1753
		     "upper limit.   See %<-fmax-array-constructor%> "
1754
		     "option", &e->where, flag_max_array_constructor);
1755
	  return false;
1756
	}
1757
      return true;
1758 1759
    }

Jerry DeLisle committed
1760
  /* We now know the array is not too big so go ahead and try to expand it.  */
1761
  expand_save = current_expand;
Jerry DeLisle committed
1762
  current_expand.base = NULL;
1763 1764 1765 1766 1767

  iter_stack = NULL;

  current_expand.expand_work_function = expand;

1768
  if (!expand_constructor (e->value.constructor))
1769
    {
Jerry DeLisle committed
1770
      gfc_constructor_free (current_expand.base);
1771
      rc = false;
1772 1773 1774
      goto done;
    }

Jerry DeLisle committed
1775 1776
  gfc_constructor_free (e->value.constructor);
  e->value.constructor = current_expand.base;
1777

1778
  rc = true;
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788

done:
  current_expand = expand_save;

  return rc;
}


/* Work function for checking that an element of a constructor is a
   constant, after removal of any iteration variables.  We return
1789
   false if not so.  */
1790

1791
static bool
1792
is_constant_element (gfc_expr *e)
1793 1794 1795 1796 1797 1798
{
  int rv;

  rv = gfc_is_constant_expr (e);
  gfc_free_expr (e);

1799
  return rv ? true : false;
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
}


/* Given an array constructor, determine if the constructor is
   constant or not by expanding it and making sure that all elements
   are constants.  This is a bit of a hack since something like (/ (i,
   i=1,100000000) /) will take a while as* opposed to a more clever
   function that traverses the expression tree. FIXME.  */

int
Steven G. Kargl committed
1810
gfc_constant_ac (gfc_expr *e)
1811 1812
{
  expand_info expand_save;
1813
  bool rc;
1814

Jerry DeLisle committed
1815 1816 1817
  iter_stack = NULL;
  expand_save = current_expand;
  current_expand.expand_work_function = is_constant_element;
1818

Jerry DeLisle committed
1819
  rc = expand_constructor (e->value.constructor);
1820

Jerry DeLisle committed
1821
  current_expand = expand_save;
1822
  if (!rc)
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832
    return 0;

  return 1;
}


/* Returns nonzero if an array constructor has been completely
   expanded (no iterators) and zero if iterators are present.  */

int
Steven G. Kargl committed
1833
gfc_expanded_ac (gfc_expr *e)
1834
{
Jerry DeLisle committed
1835
  gfc_constructor *c;
1836 1837

  if (e->expr_type == EXPR_ARRAY)
Jerry DeLisle committed
1838 1839 1840
    for (c = gfc_constructor_first (e->value.constructor);
	 c; c = gfc_constructor_next (c))
      if (c->iterator != NULL || !gfc_expanded_ac (c->expr))
1841 1842 1843 1844 1845 1846 1847 1848
	return 0;

  return 1;
}


/*************** Type resolution of array constructors ***************/

1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892

/* The symbol expr_is_sought_symbol_ref will try to find.  */
static const gfc_symbol *sought_symbol = NULL;


/* Tells whether the expression E is a variable reference to the symbol
   in the static variable SOUGHT_SYMBOL, and sets the locus pointer WHERE
   accordingly.
   To be used with gfc_expr_walker: if a reference is found we don't need
   to look further so we return 1 to skip any further walk.  */

static int
expr_is_sought_symbol_ref (gfc_expr **e, int *walk_subtrees ATTRIBUTE_UNUSED,
			   void *where)
{
  gfc_expr *expr = *e;
  locus *sym_loc = (locus *)where;

  if (expr->expr_type == EXPR_VARIABLE
      && expr->symtree->n.sym == sought_symbol)
    {
      *sym_loc = expr->where;
      return 1;
    }

  return 0;
}


/* Tells whether the expression EXPR contains a reference to the symbol
   SYM and in that case sets the position SYM_LOC where the reference is.  */

static bool
find_symbol_in_expr (gfc_symbol *sym, gfc_expr *expr, locus *sym_loc)
{
  int ret;

  sought_symbol = sym;
  ret = gfc_expr_walker (&expr, &expr_is_sought_symbol_ref, sym_loc);
  sought_symbol = NULL;
  return ret;
}


1893 1894 1895
/* Recursive array list resolution function.  All of the elements must
   be of the same type.  */

1896
static bool
Jerry DeLisle committed
1897
resolve_array_list (gfc_constructor_base base)
1898
{
1899
  bool t;
Jerry DeLisle committed
1900
  gfc_constructor *c;
1901
  gfc_iterator *iter;
1902

1903
  t = true;
1904

Jerry DeLisle committed
1905
  for (c = gfc_constructor_first (base); c; c = gfc_constructor_next (c))
1906
    {
1907 1908 1909 1910 1911
      iter = c->iterator;
      if (iter != NULL)
        {
	  gfc_symbol *iter_var;
	  locus iter_var_loc;
1912

1913 1914
	  if (!gfc_resolve_iterator (iter, false, true))
	    t = false;
1915 1916 1917 1918 1919 1920

	  /* Check for bounds referencing the iterator variable.  */
	  gcc_assert (iter->var->expr_type == EXPR_VARIABLE);
	  iter_var = iter->var->symtree->n.sym;
	  if (find_symbol_in_expr (iter_var, iter->start, &iter_var_loc))
	    {
1921 1922 1923 1924
	      if (!gfc_notify_std (GFC_STD_LEGACY, "AC-IMPLIED-DO initial "
				   "expression references control variable "
				   "at %L", &iter_var_loc))
	       t = false;
1925 1926 1927
	    }
	  if (find_symbol_in_expr (iter_var, iter->end, &iter_var_loc))
	    {
1928 1929 1930 1931
	      if (!gfc_notify_std (GFC_STD_LEGACY, "AC-IMPLIED-DO final "
				   "expression references control variable "
				   "at %L", &iter_var_loc))
	       t = false;
1932 1933 1934
	    }
	  if (find_symbol_in_expr (iter_var, iter->step, &iter_var_loc))
	    {
1935 1936 1937 1938
	      if (!gfc_notify_std (GFC_STD_LEGACY, "AC-IMPLIED-DO step "
				   "expression references control variable "
				   "at %L", &iter_var_loc))
	       t = false;
1939 1940
	    }
	}
1941

1942 1943
      if (!gfc_resolve_expr (c->expr))
	t = false;
1944 1945 1946 1947 1948

      if (UNLIMITED_POLY (c->expr))
	{
	  gfc_error ("Array constructor value at %L shall not be unlimited "
		     "polymorphic [F2008: C4106]", &c->expr->where);
1949
	  t = false;
1950
	}
1951 1952 1953 1954 1955
    }

  return t;
}

1956
/* Resolve character array constructor. If it has a specified constant character
1957
   length, pad/truncate the elements here; if the length is not specified and
1958 1959
   all elements are of compile-time known length, emit an error as this is
   invalid.  */
1960

1961
bool
Steven G. Kargl committed
1962
gfc_resolve_character_array_constructor (gfc_expr *expr)
1963
{
Steven G. Kargl committed
1964
  gfc_constructor *p;
1965
  int found_length;
1966 1967 1968 1969

  gcc_assert (expr->expr_type == EXPR_ARRAY);
  gcc_assert (expr->ts.type == BT_CHARACTER);

1970
  if (expr->ts.u.cl == NULL)
Feng Wang committed
1971
    {
Jerry DeLisle committed
1972 1973
      for (p = gfc_constructor_first (expr->value.constructor);
	   p; p = gfc_constructor_next (p))
1974
	if (p->expr->ts.u.cl != NULL)
1975 1976 1977
	  {
	    /* Ensure that if there is a char_len around that it is
	       used; otherwise the middle-end confuses them!  */
1978
	    expr->ts.u.cl = p->expr->ts.u.cl;
1979 1980 1981
	    goto got_charlen;
	  }

1982
      expr->ts.u.cl = gfc_new_charlen (gfc_current_ns, NULL);
Feng Wang committed
1983 1984
    }

1985 1986
got_charlen:

1987 1988
  found_length = -1;

1989
  if (expr->ts.u.cl->length == NULL)
1990
    {
1991 1992
      /* Check that all constant string elements have the same length until
	 we reach the end or find a variable-length one.  */
1993

Jerry DeLisle committed
1994 1995
      for (p = gfc_constructor_first (expr->value.constructor);
	   p; p = gfc_constructor_next (p))
1996
	{
1997
	  int current_length = -1;
1998 1999 2000
	  gfc_ref *ref;
	  for (ref = p->expr->ref; ref; ref = ref->next)
	    if (ref->type == REF_SUBSTRING
Steven G. Kargl committed
2001 2002
		&& ref->u.ss.start->expr_type == EXPR_CONSTANT
		&& ref->u.ss.end->expr_type == EXPR_CONSTANT)
2003 2004 2005
	      break;

	  if (p->expr->expr_type == EXPR_CONSTANT)
2006
	    current_length = p->expr->value.character.length;
2007
	  else if (ref)
Steven G. Kargl committed
2008 2009 2010 2011
	    {
	      long j;
	      j = mpz_get_ui (ref->u.ss.end->value.integer)
		- mpz_get_ui (ref->u.ss.start->value.integer) + 1;
2012
	      current_length = (int) j;
Steven G. Kargl committed
2013
	    }
2014 2015
	  else if (p->expr->ts.u.cl && p->expr->ts.u.cl->length
		   && p->expr->ts.u.cl->length->expr_type == EXPR_CONSTANT)
Steven G. Kargl committed
2016 2017
	    {
	      long j;
2018
	      j = mpz_get_si (p->expr->ts.u.cl->length->value.integer);
2019
	      current_length = (int) j;
Steven G. Kargl committed
2020
	    }
2021
	  else
2022
	    return true;
2023

2024 2025 2026 2027 2028 2029 2030 2031 2032
	  gcc_assert (current_length != -1);

	  if (found_length == -1)
	    found_length = current_length;
	  else if (found_length != current_length)
	    {
	      gfc_error ("Different CHARACTER lengths (%d/%d) in array"
			 " constructor at %L", found_length, current_length,
			 &p->expr->where);
2033
	      return false;
2034 2035 2036
	    }

	  gcc_assert (found_length == current_length);
2037
	}
2038 2039 2040 2041

      gcc_assert (found_length != -1);

      /* Update the character length of the array constructor.  */
Jerry DeLisle committed
2042 2043
      expr->ts.u.cl->length = gfc_get_int_expr (gfc_default_integer_kind,
						NULL, found_length);
2044
    }
2045
  else
2046 2047 2048
    {
      /* We've got a character length specified.  It should be an integer,
	 otherwise an error is signalled elsewhere.  */
2049
      gcc_assert (expr->ts.u.cl->length);
2050 2051 2052 2053

      /* If we've got a constant character length, pad according to this.
	 gfc_extract_int does check for BT_INTEGER and EXPR_CONSTANT and sets
	 max_length only if they pass.  */
2054
      gfc_extract_int (expr->ts.u.cl->length, &found_length);
2055

2056
      /* Now pad/truncate the elements accordingly to the specified character
2057 2058 2059 2060
	 length.  This is ok inside this conditional, as in the case above
	 (without typespec) all elements are verified to have the same length
	 anyway.  */
      if (found_length != -1)
Jerry DeLisle committed
2061 2062
	for (p = gfc_constructor_first (expr->value.constructor);
	     p; p = gfc_constructor_next (p))
2063 2064 2065 2066 2067 2068
	  if (p->expr->expr_type == EXPR_CONSTANT)
	    {
	      gfc_expr *cl = NULL;
	      int current_length = -1;
	      bool has_ts;

2069
	      if (p->expr->ts.u.cl && p->expr->ts.u.cl->length)
2070
	      {
2071
		cl = p->expr->ts.u.cl->length;
2072 2073 2074 2075 2076 2077
		gfc_extract_int (cl, &current_length);
	      }

	      /* If gfc_extract_int above set current_length, we implicitly
		 know the type is BT_INTEGER and it's EXPR_CONSTANT.  */

2078
	      has_ts = expr->ts.u.cl->length_from_typespec;
2079 2080

	      if (! cl
2081
		  || (current_length != -1 && current_length != found_length))
2082 2083 2084
		gfc_set_constant_character_len (found_length, p->expr,
						has_ts ? -1 : found_length);
	    }
2085 2086
    }

2087
  return true;
2088 2089
}

Steven G. Kargl committed
2090

2091
/* Resolve all of the expressions in an array list.  */
2092

2093
bool
Steven G. Kargl committed
2094
gfc_resolve_array_constructor (gfc_expr *expr)
2095
{
2096
  bool t;
2097 2098

  t = resolve_array_list (expr->value.constructor);
2099
  if (t)
2100
    t = gfc_check_constructor_type (expr);
2101 2102 2103 2104

  /* gfc_resolve_character_array_constructor is called in gfc_resolve_expr after
     the call to this function, so we don't need to call it here; if it was
     called twice, an error message there would be duplicated.  */
2105 2106 2107 2108 2109 2110 2111

  return t;
}


/* Copy an iterator structure.  */

Jerry DeLisle committed
2112 2113
gfc_iterator *
gfc_copy_iterator (gfc_iterator *src)
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
{
  gfc_iterator *dest;

  if (src == NULL)
    return NULL;

  dest = gfc_get_iterator ();

  dest->var = gfc_copy_expr (src->var);
  dest->start = gfc_copy_expr (src->start);
  dest->end = gfc_copy_expr (src->end);
  dest->step = gfc_copy_expr (src->step);

  return dest;
}


/********* Subroutines for determining the size of an array *********/

2133
/* These are needed just to accommodate RESHAPE().  There are no
2134
   diagnostics here, we just return a negative number if something
2135
   goes wrong.  */
2136 2137 2138 2139 2140


/* Get the size of single dimension of an array specification.  The
   array is guaranteed to be one dimensional.  */

2141
bool
Steven G. Kargl committed
2142
spec_dimen_size (gfc_array_spec *as, int dimen, mpz_t *result)
2143 2144
{
  if (as == NULL)
2145
    return false;
2146 2147 2148 2149 2150 2151

  if (dimen < 0 || dimen > as->rank - 1)
    gfc_internal_error ("spec_dimen_size(): Bad dimension");

  if (as->type != AS_EXPLICIT
      || as->lower[dimen]->expr_type != EXPR_CONSTANT
2152 2153 2154
      || as->upper[dimen]->expr_type != EXPR_CONSTANT
      || as->lower[dimen]->ts.type != BT_INTEGER
      || as->upper[dimen]->ts.type != BT_INTEGER)
2155
    return false;
2156 2157 2158 2159 2160 2161 2162 2163

  mpz_init (*result);

  mpz_sub (*result, as->upper[dimen]->value.integer,
	   as->lower[dimen]->value.integer);

  mpz_add_ui (*result, *result, 1);

2164
  return true;
2165 2166 2167
}


2168
bool
Steven G. Kargl committed
2169
spec_size (gfc_array_spec *as, mpz_t *result)
2170 2171 2172 2173
{
  mpz_t size;
  int d;

2174
  if (!as || as->type == AS_ASSUMED_RANK)
2175
    return false;
2176

2177 2178 2179 2180
  mpz_init_set_ui (*result, 1);

  for (d = 0; d < as->rank; d++)
    {
2181
      if (!spec_dimen_size (as, d, &size))
2182 2183
	{
	  mpz_clear (*result);
2184
	  return false;
2185 2186 2187 2188 2189 2190
	}

      mpz_mul (*result, *result, size);
      mpz_clear (size);
    }

2191
  return true;
2192 2193 2194
}


2195 2196
/* Get the number of elements in an array section. Optionally, also supply
   the end value.  */
2197

2198
bool
2199
gfc_ref_dimen_size (gfc_array_ref *ar, int dimen, mpz_t *result, mpz_t *end)
2200 2201
{
  mpz_t upper, lower, stride;
2202
  mpz_t diff;
2203
  bool t;
2204 2205

  if (dimen < 0 || ar == NULL || dimen > ar->dimen - 1)
2206
    gfc_internal_error ("gfc_ref_dimen_size(): Bad dimension");
2207 2208 2209 2210 2211 2212

  switch (ar->dimen_type[dimen])
    {
    case DIMEN_ELEMENT:
      mpz_init (*result);
      mpz_set_ui (*result, 1);
2213
      t = true;
2214 2215 2216 2217 2218 2219 2220
      break;

    case DIMEN_VECTOR:
      t = gfc_array_size (ar->start[dimen], result);	/* Recurse! */
      break;

    case DIMEN_RANGE:
2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275

      mpz_init (stride);

      if (ar->stride[dimen] == NULL)
	mpz_set_ui (stride, 1);
      else
	{
	  if (ar->stride[dimen]->expr_type != EXPR_CONSTANT)
	    {
	      mpz_clear (stride);
	      return false;
	    }
	  mpz_set (stride, ar->stride[dimen]->value.integer);
	}

      /* Calculate the number of elements via gfc_dep_differce, but only if
	 start and end are both supplied in the reference or the array spec.
	 This is to guard against strange but valid code like

	 subroutine foo(a,n)
	 real a(1:n)
	 n = 3
	 print *,size(a(n-1:))

	 where the user changes the value of a variable.  If we have to
	 determine end as well, we cannot do this using gfc_dep_difference.
	 Fall back to the constants-only code then.  */

      if (end == NULL)
	{
	  bool use_dep;

	  use_dep = gfc_dep_difference (ar->end[dimen], ar->start[dimen],
					&diff);
	  if (!use_dep && ar->end[dimen] == NULL && ar->start[dimen] == NULL)
	    use_dep = gfc_dep_difference (ar->as->upper[dimen],
					    ar->as->lower[dimen], &diff);

	  if (use_dep)
	    {
	      mpz_init (*result);
	      mpz_add (*result, diff, stride);
	      mpz_div (*result, *result, stride);
	      if (mpz_cmp_ui (*result, 0) < 0)
		mpz_set_ui (*result, 0);

	      mpz_clear (stride);
	      mpz_clear (diff);
	      return true;
	    }

	}

      /*  Constant-only code here, which covers more cases
	  like a(:4) etc.  */
2276 2277
      mpz_init (upper);
      mpz_init (lower);
2278
      t = false;
2279 2280 2281 2282

      if (ar->start[dimen] == NULL)
	{
	  if (ar->as->lower[dimen] == NULL
2283 2284
	      || ar->as->lower[dimen]->expr_type != EXPR_CONSTANT
	      || ar->as->lower[dimen]->ts.type != BT_INTEGER)
2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297
	    goto cleanup;
	  mpz_set (lower, ar->as->lower[dimen]->value.integer);
	}
      else
	{
	  if (ar->start[dimen]->expr_type != EXPR_CONSTANT)
	    goto cleanup;
	  mpz_set (lower, ar->start[dimen]->value.integer);
	}

      if (ar->end[dimen] == NULL)
	{
	  if (ar->as->upper[dimen] == NULL
2298 2299
	      || ar->as->upper[dimen]->expr_type != EXPR_CONSTANT
	      || ar->as->upper[dimen]->ts.type != BT_INTEGER)
2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317
	    goto cleanup;
	  mpz_set (upper, ar->as->upper[dimen]->value.integer);
	}
      else
	{
	  if (ar->end[dimen]->expr_type != EXPR_CONSTANT)
	    goto cleanup;
	  mpz_set (upper, ar->end[dimen]->value.integer);
	}

      mpz_init (*result);
      mpz_sub (*result, upper, lower);
      mpz_add (*result, *result, stride);
      mpz_div (*result, *result, stride);

      /* Zero stride caught earlier.  */
      if (mpz_cmp_ui (*result, 0) < 0)
	mpz_set_ui (*result, 0);
2318
      t = true;
2319

2320 2321 2322 2323 2324 2325 2326 2327 2328
      if (end)
	{
	  mpz_init (*end);

	  mpz_sub_ui (*end, *result, 1UL);
	  mpz_mul (*end, *end, stride);
	  mpz_add (*end, *end, lower);
	}

2329 2330 2331 2332 2333 2334 2335
    cleanup:
      mpz_clear (upper);
      mpz_clear (lower);
      mpz_clear (stride);
      return t;

    default:
2336
      gfc_internal_error ("gfc_ref_dimen_size(): Bad dimen_type");
2337 2338 2339 2340 2341 2342
    }

  return t;
}


2343
static bool
Steven G. Kargl committed
2344
ref_size (gfc_array_ref *ar, mpz_t *result)
2345 2346 2347 2348 2349 2350 2351 2352
{
  mpz_t size;
  int d;

  mpz_init_set_ui (*result, 1);

  for (d = 0; d < ar->dimen; d++)
    {
2353
      if (!gfc_ref_dimen_size (ar, d, &size, NULL))
2354 2355
	{
	  mpz_clear (*result);
2356
	  return false;
2357 2358 2359 2360 2361 2362
	}

      mpz_mul (*result, *result, size);
      mpz_clear (size);
    }

2363
  return true;
2364 2365 2366 2367
}


/* Given an array expression and a dimension, figure out how many
2368 2369
   elements it has along that dimension.  Returns true if we were
   able to return a result in the 'result' variable, false
2370 2371
   otherwise.  */

2372
bool
Steven G. Kargl committed
2373
gfc_array_dimen_size (gfc_expr *array, int dimen, mpz_t *result)
2374 2375 2376 2377
{
  gfc_ref *ref;
  int i;

2378 2379
  gcc_assert (array != NULL);

2380
  if (array->ts.type == BT_CLASS)
2381
    return false;
2382

2383
  if (array->rank == -1)
2384
    return false;
2385

2386
  if (dimen < 0 || dimen > array->rank - 1)
2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406
    gfc_internal_error ("gfc_array_dimen_size(): Bad dimension");

  switch (array->expr_type)
    {
    case EXPR_VARIABLE:
    case EXPR_FUNCTION:
      for (ref = array->ref; ref; ref = ref->next)
	{
	  if (ref->type != REF_ARRAY)
	    continue;

	  if (ref->u.ar.type == AR_FULL)
	    return spec_dimen_size (ref->u.ar.as, dimen, result);

	  if (ref->u.ar.type == AR_SECTION)
	    {
	      for (i = 0; dimen >= 0; i++)
		if (ref->u.ar.dimen_type[i] != DIMEN_ELEMENT)
		  dimen--;

2407
	      return gfc_ref_dimen_size (&ref->u.ar, i - 1, result, NULL);
2408 2409 2410
	    }
	}

2411 2412 2413
      if (array->shape && array->shape[dimen])
	{
	  mpz_init_set (*result, array->shape[dimen]);
2414
	  return true;
2415 2416
	}

2417
      if (array->symtree->n.sym->attr.generic
2418
	  && array->value.function.esym != NULL)
2419
	{
2420 2421
	  if (!spec_dimen_size (array->value.function.esym->as, dimen, result))
	    return false;
2422
	}
2423 2424
      else if (!spec_dimen_size (array->symtree->n.sym->as, dimen, result))
	return false;
2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438

      break;

    case EXPR_ARRAY:
      if (array->shape == NULL) {
	/* Expressions with rank > 1 should have "shape" properly set */
	if ( array->rank != 1 )
	  gfc_internal_error ("gfc_array_dimen_size(): Bad EXPR_ARRAY expr");
	return gfc_array_size(array, result);
      }

      /* Fall through */
    default:
      if (array->shape == NULL)
2439
	return false;
2440 2441 2442 2443 2444 2445

      mpz_init_set (*result, array->shape[dimen]);

      break;
    }

2446
  return true;
2447 2448 2449 2450
}


/* Given an array expression, figure out how many elements are in the
2451 2452
   array.  Returns true if this is possible, and sets the 'result'
   variable.  Otherwise returns false.  */
2453

2454
bool
Steven G. Kargl committed
2455
gfc_array_size (gfc_expr *array, mpz_t *result)
2456 2457 2458
{
  expand_info expand_save;
  gfc_ref *ref;
2459
  int i;
2460
  bool t;
2461

2462
  if (array->ts.type == BT_CLASS)
2463
    return false;
2464

2465 2466 2467
  switch (array->expr_type)
    {
    case EXPR_ARRAY:
2468
      gfc_push_suppress_errors ();
2469 2470 2471 2472 2473 2474 2475 2476 2477 2478

      expand_save = current_expand;

      current_expand.count = result;
      mpz_init_set_ui (*result, 0);

      current_expand.expand_work_function = count_elements;
      iter_stack = NULL;

      t = expand_constructor (array->value.constructor);
2479 2480

      gfc_pop_suppress_errors ();
2481

2482
      if (!t)
2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504
	mpz_clear (*result);
      current_expand = expand_save;
      return t;

    case EXPR_VARIABLE:
      for (ref = array->ref; ref; ref = ref->next)
	{
	  if (ref->type != REF_ARRAY)
	    continue;

	  if (ref->u.ar.type == AR_FULL)
	    return spec_size (ref->u.ar.as, result);

	  if (ref->u.ar.type == AR_SECTION)
	    return ref_size (&ref->u.ar, result);
	}

      return spec_size (array->symtree->n.sym->as, result);


    default:
      if (array->rank == 0 || array->shape == NULL)
2505
	return false;
2506 2507 2508 2509 2510 2511 2512 2513 2514

      mpz_init_set_ui (*result, 1);

      for (i = 0; i < array->rank; i++)
	mpz_mul (*result, *result, array->shape[i]);

      break;
    }

2515
  return true;
2516 2517 2518 2519 2520 2521
}


/* Given an array reference, return the shape of the reference in an
   array of mpz_t integers.  */

2522
bool
Steven G. Kargl committed
2523
gfc_array_ref_shape (gfc_array_ref *ar, mpz_t *shape)
2524 2525 2526 2527 2528 2529 2530 2531 2532 2533
{
  int d;
  int i;

  d = 0;

  switch (ar->type)
    {
    case AR_FULL:
      for (; d < ar->as->rank; d++)
2534
	if (!spec_dimen_size (ar->as, d, &shape[d]))
2535 2536
	  goto cleanup;

2537
      return true;
2538 2539 2540 2541 2542 2543

    case AR_SECTION:
      for (i = 0; i < ar->dimen; i++)
	{
	  if (ar->dimen_type[i] != DIMEN_ELEMENT)
	    {
2544
	      if (!gfc_ref_dimen_size (ar, i, &shape[d], NULL))
2545 2546 2547 2548 2549
		goto cleanup;
	      d++;
	    }
	}

2550
      return true;
2551 2552 2553 2554 2555 2556

    default:
      break;
    }

cleanup:
2557
  gfc_clear_shape (shape, d);
2558
  return false;
2559 2560 2561 2562 2563 2564 2565
}


/* Given an array expression, find the array reference structure that
   characterizes the reference.  */

gfc_array_ref *
2566
gfc_find_array_ref (gfc_expr *e, bool allow_null)
2567 2568 2569 2570 2571
{
  gfc_ref *ref;

  for (ref = e->ref; ref; ref = ref->next)
    if (ref->type == REF_ARRAY
2572
	&& (ref->u.ar.type == AR_FULL || ref->u.ar.type == AR_SECTION))
2573 2574 2575
      break;

  if (ref == NULL)
2576 2577 2578 2579 2580 2581
    {
      if (allow_null)
	return NULL;
      else
	gfc_internal_error ("gfc_find_array_ref(): No ref found");
    }
2582 2583 2584

  return &ref->u.ar;
}
2585 2586 2587 2588


/* Find out if an array shape is known at compile time.  */

2589
bool
2590 2591 2592
gfc_is_compile_time_shape (gfc_array_spec *as)
{
  if (as->type != AS_EXPLICIT)
2593
    return false;
2594

2595
  for (int i = 0; i < as->rank; i++)
2596 2597
    if (!gfc_is_constant_expr (as->lower[i])
	|| !gfc_is_constant_expr (as->upper[i]))
2598
      return false;
2599

2600
  return true;
2601
}